private void BtnTwitch_Click(object sender, RoutedEventArgs e) { // Tries to connect to the twitch service given the credentials in the settings or disconnects System.Windows.Controls.MenuItem item = (System.Windows.Controls.MenuItem)sender; if (item.Tag.ToString().Equals("Connect")) { // Connects TwitchHandler.BotConnect(); } else if (item.Tag.ToString().Equals("Disconnect")) { // Disconnects TwitchHandler.Client.Disconnect(); } }
private void WriteSong(string _artist, string _title, string _extra, string cover = null, bool forceUpdate = false, string _trackId = null, string _trackUrl = null) { _currentId = _trackId; if (_artist.Contains("Various Artists, ")) { _artist = _artist.Replace("Various Artists, ", ""); _artist = _artist.Trim(); } // get the songPath which is default the directory where the exe is, else get the user set directory _root = string.IsNullOrEmpty(Settings.Directory) ? Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) : Settings.Directory; _songPath = _root + "/Songify.txt"; _coverTemp = _root + "/tmp.png"; _coverPath = _root + "/cover.png"; if (_firstRun) { File.WriteAllText(_songPath, ""); } // if all those are empty we expect the player to be paused if (string.IsNullOrEmpty(_artist) && string.IsNullOrEmpty(_title) && string.IsNullOrEmpty(_extra)) { // read the text file if (!File.Exists(_songPath)) { File.Create(_songPath).Close(); } File.WriteAllText(_songPath, Settings.CustomPauseText); if (Settings.SplitOutput) { WriteSplitOutput(Settings.CustomPauseText, _title, _extra); } DownloadCover(null); TxtblockLiveoutput.Dispatcher.Invoke( DispatcherPriority.Normal, new Action(() => { TxtblockLiveoutput.Text = Settings.CustomPauseText; })); return; } // get the output string CurrSong = Settings.OutputString; if (_selectedSource == PlayerType.SpotifyWeb) { // this only is used for Spotify because here the artist and title are split // replace parameters with actual info CurrSong = CurrSong.Format( artist => _artist, title => _title, extra => _extra, uri => _trackId ).Format(); if (ReqList.Count > 0) { RequestObject rq = ReqList.Find(x => x.TrackID == _currentId); if (rq != null) { CurrSong = CurrSong.Replace("{{", ""); CurrSong = CurrSong.Replace("}}", ""); CurrSong = CurrSong.Replace("{req}", rq.Requester); } else { int start = CurrSong.IndexOf("{{", StringComparison.Ordinal); int end = CurrSong.LastIndexOf("}}", StringComparison.Ordinal) + 2; if (start >= 0) { CurrSong = CurrSong.Remove(start, end - start); } } } else { try { int start = CurrSong.IndexOf("{{", StringComparison.Ordinal); int end = CurrSong.LastIndexOf("}}", StringComparison.Ordinal) + 2; if (start >= 0) { CurrSong = CurrSong.Remove(start, end - start); } } catch (Exception ex) { Logger.LogExc(ex); } } } else { // used for Youtube and Nightbot // replace parameters with actual info // get the first occurance of "}" to get the seperator from the custom output ({artist} - {title}) // and replace it //int pFrom = CurrSong.IndexOf("}", StringComparison.Ordinal); //string result = CurrSong.Substring(pFrom + 2, 1); //CurrSong = CurrSong.Replace(result, ""); // artist is set to be artist and title in this case, {title} and {extra} are empty strings CurrSong = CurrSong.Format( artist => _artist, title => _title, extra => _extra, uri => _trackId ).Format(); try { int start = CurrSong.IndexOf("{{", StringComparison.Ordinal); int end = CurrSong.LastIndexOf("}}", StringComparison.Ordinal) + 2; if (start >= 0) { CurrSong = CurrSong.Remove(start, end - start); } } catch (Exception ex) { Logger.LogExc(ex); } } // Cleanup the string (remove double spaces, trim and add trailing spaces for scroll) CurrSong = CleanFormatString(CurrSong); this._title = _title; this._artist = _artist; // read the text file if (!File.Exists(_songPath)) { File.Create(_songPath).Close(); File.WriteAllText(_songPath, CurrSong); } if (new FileInfo(_songPath).Length == 0) { File.WriteAllText(_songPath, CurrSong); } string[] temp = File.ReadAllLines(_songPath); // if the text file is different to _currSong (fetched song) or update is forced if (temp[0].Trim() != CurrSong.Trim() || forceUpdate || _firstRun) { // write song to the text file File.WriteAllText(_songPath, CurrSong); try { ReqList.Remove(ReqList.Find(x => x.TrackID == _prevId)); Application.Current.Dispatcher.Invoke(() => { foreach (Window window in Application.Current.Windows) { if (window.GetType() != typeof(Window_Queue)) { continue; } //(qw as Window_Queue).dgv_Queue.ItemsSource. (window as Window_Queue)?.dgv_Queue.Items.Refresh(); } }); } catch (Exception) { // ignored } if (Settings.SplitOutput) { WriteSplitOutput(_artist, _title, _extra); } // if upload is enabled if (Settings.Upload) { UploadSong(CurrSong.Trim(), cover); } if (_firstRun) { _prevSong = CurrSong.Trim(); _firstRun = false; } else { if (_prevSong == CurrSong.Trim()) { return; } } //Write History if (Settings.SaveHistory && !string.IsNullOrEmpty(CurrSong.Trim()) && CurrSong.Trim() != Settings.CustomPauseText) { _prevSong = CurrSong.Trim(); int unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; //save the history file string historyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) + "/" + "history.shr"; XDocument doc; if (!File.Exists(historyPath)) { doc = new XDocument(new XElement("History", new XElement("d_" + DateTime.Now.ToString("dd.MM.yyyy")))); doc.Save(historyPath); } doc = XDocument.Load(historyPath); if (!doc.Descendants("d_" + DateTime.Now.ToString("dd.MM.yyyy")).Any()) { doc.Descendants("History").FirstOrDefault() ?.Add(new XElement("d_" + DateTime.Now.ToString("dd.MM.yyyy"))); } XElement elem = new XElement("Song", CurrSong.Trim()); elem.Add(new XAttribute("Time", unixTimestamp)); XElement x = doc.Descendants("d_" + DateTime.Now.ToString("dd.MM.yyyy")).FirstOrDefault(); x?.Add(elem); doc.Save(historyPath); } //Upload History if (Settings.UploadHistory && !string.IsNullOrEmpty(CurrSong.Trim()) && CurrSong.Trim() != Settings.CustomPauseText) { _prevSong = CurrSong.Trim(); int unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; // Upload Song try { string extras = Settings.Uuid + "&tst=" + unixTimestamp + "&song=" + HttpUtility.UrlEncode(CurrSong.Trim(), Encoding.UTF8); string url = "https://songify.rocks/song_history.php/?id=" + extras; // Create a new 'HttpWebRequest' object to the mentioned URL. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); myHttpWebRequest.UserAgent = Settings.Webua; // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable. HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); if (myHttpWebResponse.StatusCode != HttpStatusCode.OK) { Logger.LogStr("MAIN: Upload Song:" + myHttpWebResponse.StatusCode); } myHttpWebResponse.Close(); } catch (Exception ex) { Logger.LogExc(ex); // Writing to the statusstrip label LblStatus.Dispatcher.Invoke( DispatcherPriority.Normal, new Action(() => { LblStatus.Content = "Error uploading Songinformation"; })); } } // Update Song Queue, Track has been player. All parameters are optional except track id, playerd and o. o has to be the value "u" if (_trackId != null) { WebHelper.UpdateWebQueue(_trackId, "", "", "", "", "1", "u"); } // Send Message to Twitch if checked if (Settings.AnnounceInChat && TwitchHandler.Client.IsConnected) { TwitchHandler.SendCurrSong("Now playing: " + CurrSong.Trim()); } _prevId = _currentId; //Save Album Cover if (Settings.DownloadCover) { DownloadCover(cover); } if (File.Exists(_coverPath) && new FileInfo(_coverPath).Length > 0) { img_cover.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.CreateOptions = BitmapCreateOptions.IgnoreImageCache; image.UriSource = new Uri(_coverPath); image.EndInit(); img_cover.Source = image; })); } } // write song to the output label TxtblockLiveoutput.Dispatcher.Invoke( DispatcherPriority.Normal, new Action(() => { TxtblockLiveoutput.Text = CurrSong.Trim(); })); }
private void MetroWindowLoaded(object sender, RoutedEventArgs e) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += MyHandler; if (File.Exists(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) + "/log.log")) { File.Delete(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) + "/log.log"); } if (File.Exists(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) + "/Debug.log")) { File.Delete(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) + "/Debug.log"); } if (Settings.AutoClearQueue) { ReqList.Clear(); WebHelper.UpdateWebQueue("", "", "", "", "", "1", "c"); } Settings.MsgLoggingEnabled = false; // Load Config file if one exists if (File.Exists(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) + "/config.xml")) { ConfigHandler.LoadConfig(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) + "/config.xml"); } // Add sources to combobox AddSourcesToSourceBox(); // Create systray menu and icon and show it _menuItem1.Text = @"Exit"; _menuItem1.Click += MenuItem1Click; _menuItem2.Text = @"Show"; _menuItem2.Click += MenuItem2Click; _contextMenu.MenuItems.AddRange(new[] { _menuItem2, _menuItem1 }); _notifyIcon.Icon = Properties.Resources.songify; _notifyIcon.ContextMenu = _contextMenu; _notifyIcon.Visible = true; _notifyIcon.DoubleClick += MenuItem2Click; _notifyIcon.Text = @"Songify"; // set the current theme ThemeHandler.ApplyTheme(); // start minimized in systray (hide) if (Settings.Systray) { MinimizeToSysTray(); } // get the software version from assembly Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); _version = fvi.FileVersion; // generate UUID if not exists, expand the window and show the telemetrydisclaimer if (Settings.Uuid == "") { Width = 588 + 200; Height = 247.881 + 200; Settings.Uuid = Guid.NewGuid().ToString(); TelemetryDisclaimer(); } else { // start the timer that sends telemetry every 5 Minutes TelemetryTimer(); } // check for update AutoUpdater.Mandatory = true; AutoUpdater.UpdateMode = Mode.ForcedDownload; AutoUpdater.AppTitle = "Songify"; AutoUpdater.RunUpdateAsAdmin = false; AutoUpdater.Start("https://songify.rocks/update.xml"); // set the cbx index to the correct source cbx_Source.SelectedIndex = Settings.Source; _selectedSource = cbx_Source.SelectedValue.ToString(); cbx_Source.SelectionChanged += Cbx_Source_SelectionChanged; // text in the bottom right LblCopyright.Content = "Songify v" + _version.Substring(0, 5) + " Copyright ©"; if (_selectedSource == PlayerType.SpotifyWeb) { if (string.IsNullOrEmpty(Settings.AccessToken) && string.IsNullOrEmpty(Settings.RefreshToken)) { TxtblockLiveoutput.Text = "Please link your Spotify account\nSettings -> Spotify"; } else { ApiHandler.DoAuthAsync(); } img_cover.Visibility = Visibility.Visible; } else { img_cover.Visibility = Visibility.Hidden; } if (Settings.TwAutoConnect) { TwitchHandler.BotConnect(); } // automatically start fetching songs SetFetchTimer(); }