using System; using System.Collections.Specialized; using System.Globalization; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Timers; using System.Web; using System.Windows.Forms; using System.Threading; using System.IO; namespace Plugin { public delegate void SongChangedEventHandler(Object source, SongChangedEventArgs e); public delegate void PlayerStoppedEventHandler(Object source, EventArgs e); public delegate void ConfigChangedEventHandler(Object source, EventArgs e); /// /// Description résumée de mainApp. /// public class MainApp : IDisposable { PluginPrefs Prefs; WebClient ClientWeb; WebProxy Proxy; NetworkCredential Credentials; IPlayerWatcher watcher; HFRCookie IdCookie; Uri UriForum; NameValueCollection CurrentID3Atts; const string HfrUri = @"http://forum.hardware.fr/user/editprofil_validation.php?config=hardwarefr.inc"; //string NowPlaying; bool PluginStarted; bool UseProxyAuthentication; bool disposed; public IPlayerWatcher Watcher { get { return watcher; } } public bool Started { get { return PluginStarted; } set { PluginStarted = value; } } public MainApp(IntPtr pluginHwnd) { // initialisations diverses UriForum = new Uri(HfrUri); Prefs = PluginPrefs.GetInstance(); Proxy = null; Credentials = null; // initialisation de la requete HTTP IdCookie = new HFRCookie(Prefs.GenPassword, Prefs.GenPseudo); ClientWeb = new WebClient(); // souscription aux évenements déclenchés par le watcher watcher = new WinampWatcher(pluginHwnd); watcher.SongChanged += new SongChangedEventHandler(watcher_SongChanged); watcher.PlayerStopped += new PlayerStoppedEventHandler(watcher_PlayerStopped); // souscription à l'évenement déclenché par les prefs Prefs.ConfigChanged += new ConfigChangedEventHandler(prefs_ConfigChanged); // initialisation du proxy InitProxy(); // démarrage du timer si config OK if (Prefs.PluginActif == true) StartPlugin(); } public void StartPlugin() { PluginStarted = true; watcher.Start(); } public void StopPlugin() { watcher.Stop(); PluginStarted = false; } private void PostToForum(string signature) { try { #if DEBUG Utils.Log("Post en cours"); #endif ClientWeb.UploadData(UriForum, "POST", InitRequestHeaders(signature)); } catch (WebException e) { #if DEBUG Utils.Log("Erreur pendant le Post"); #endif MessageBox.Show(e.Message, "Forum Signature Update Plugin", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } private byte[] InitRequestHeaders(string signature) { byte[] data = Encoding.GetEncoding("iso-8859-1").GetBytes(GetParams(signature)); ClientWeb.Headers.Clear(); ClientWeb.Headers.Add("Cookie", IdCookie.Cookie); ClientWeb.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); return data; } private void InitProxy() { if (CheckForProxy() == true) { // informations d'authentification de l'utilisateur if (UseProxyAuthentication && (Proxy != null)) { Credentials = new NetworkCredential(Prefs.ProxyLogin, Prefs.ProxyPassword); Proxy.Credentials = Credentials; } if (Proxy != null) WebRequest.DefaultWebProxy = Proxy; } } private bool CheckForProxy() { if (Prefs.UseProxy == true) { if (ProxyUrlNotEmpty() || ProxyPortNotEmpty()) { Proxy = new WebProxy(Prefs.ProxyUrl, Convert.ToInt32(Prefs.ProxyPort, CultureInfo.InvariantCulture)); if (ProxyLoginNotEmpty() || ProxyPassNotEmpty()) UseProxyAuthentication = true; return true; } } return false; } private string GetParams(string signature) { return String.Format( "citation={0}&signature={1}&configuration={2}&page=2&submit=Valider+les+modifications", Prefs.GenCitation, signature, Prefs.ConfigMat ); } private string GetNowPlaying(string pattern, NameValueCollection atts, string[] infos) { string NP = String.Empty; // variables standard NP = pattern.Replace("{TITLE}", atts["TITLE"]); NP = NP.Replace("{ARTIST}", atts["ARTIST"]); NP = NP.Replace("{YEAR}", atts["YEAR"]); NP = NP.Replace("{TRACK}", atts["TRACK"]); NP = NP.Replace("{ALBUM}", atts["ALBUM"]); // variables spécifiques si Discofeel activé if (infos != null) { NP = NP.Replace("{IDALBUM}", infos[1]); NP = NP.Replace("{PRIX}", infos[2]); } else { NP = NP.Replace("{IDALBUM}", string.Empty); NP = NP.Replace("{PRIX}", string.Empty); } return NP; } private string CreateSignature(string pattern, NameValueCollection ID3) { string signature; string NowPlaying = null; string[] infos = null; // on récupère d'abord le NP formatté if (ID3 != null) { if (Prefs.UseDiscofeel) { DiscofeelPage df = new DiscofeelPage(ID3); infos = df.DiscofeelInfos; if (InfosDiscofeelAreHere(infos)) NowPlaying = GetNowPlaying(Prefs.SigPattern, ID3, infos); else NowPlaying = GetNowPlaying(Prefs.SigPattern, ID3, null); } else NowPlaying = GetNowPlaying(Prefs.SigPattern, ID3, null); } // puis on l'inclut dans la signature si la variable {NP} y est présente, sinon on renvoie le // pattern par défaut if (NPIsInSignature()) signature = pattern.Replace(@"{NP}", NowPlaying); else signature = pattern; #if DEBUG Utils.Log("Signature : " + signature); #endif // si on utilise Discofeel, alors on décore la signature avec l'URL du site if (Prefs.UseDiscofeel) { if (InfosDiscofeelAreHere(infos)) { string urldiscofeel = string.Format(@"http://www.discofeel.com/album-{0}.html", infos[1]); signature = string.Format(@"[url={0}]{1}[/url]", urldiscofeel, signature); } } // pour finir, on l'encode au format Web signature = HttpUtility.UrlEncode(signature, Encoding.GetEncoding("iso-8859-1")); return signature; } private string CreateSignature(string pattern, string Song) { // dans le cas ou le morceau ne comporte pas d'ID3, on se contente de remplacer le NP par le nom du fichier if (NPIsInSignature()) return pattern.Replace(@"{NP}", Song); return pattern; } private void watcher_SongChanged(Object sender, SongChangedEventArgs e) { CurrentID3Atts = e.ID3Attributes; if (Prefs.PluginActif) { if (AttributesAreHere(CurrentID3Atts)) PostToForum(CreateSignature(Prefs.PatternLecture, CurrentID3Atts)); else PostToForum(CreateSignature(Prefs.PatternLecture, e.SongTitle)); } } private void watcher_PlayerStopped(Object sender, EventArgs e) { CurrentID3Atts = null; PostToForum(CreateSignature(Prefs.PatternStop, CurrentID3Atts)); } private void prefs_ConfigChanged(Object sender, EventArgs e) { if (Prefs.PluginActif) { if (!PluginStarted) StartPlugin(); if (CurrentID3Atts == null) return; PostToForum(CreateSignature(Prefs.PatternLecture, CurrentID3Atts)); } else PostToForum(CreateSignature(Prefs.PatternStop, (NameValueCollection)null)); } private bool ProxyUrlNotEmpty() { return (Prefs.ProxyUrl != null) && (Prefs.ProxyUrl.Length != 0); } private bool ProxyPortNotEmpty() { return (Prefs.ProxyPort != null) && (Prefs.ProxyPort.Length != 0); } private bool ProxyLoginNotEmpty() { return (Prefs.ProxyLogin != null) && (Prefs.ProxyLogin.Length != 0); } private bool ProxyPassNotEmpty() { return (Prefs.ProxyPassword != null) && (Prefs.ProxyPassword.Length != 0); } private bool NPIsInSignature() { return (Prefs.PatternStop.IndexOf(@"{NP}") != -1) || (Prefs.PatternLecture.IndexOf(@"{NP}") != -1); } private bool InfosDiscofeelAreHere(string[] infos) { return (infos != null && infos[1] != string.Empty && infos[1] != "0"); } private bool AttributesAreHere(NameValueCollection ID3) { return (ID3["ARTIST"] != string.Empty || ID3["TITLE"] != string.Empty || ID3["ALBUM"] != string.Empty || ID3["YEAR"] != string.Empty || ID3["TRACK"] != string.Empty); } #region Membres de IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) ClientWeb.Dispose(); disposed = true; } #endregion } }