// receive event notifications from MusicBee // you need to set about.ReceiveNotificationFlags = PlayerEvents to receive all notifications, and not just the startup event public void ReceiveNotification(string sourceFileUrl, NotificationType type) { // perform some action depending on the notification type switch (type) { case NotificationType.TrackChanged: var sendmap = new Dictionary <string, string>(); sendmap.Add("title", mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle)); sendmap.Add("albumartist", mbApiInterface.NowPlaying_GetFileTag(MetaDataType.AlbumArtist)); sendmap.Add("artist", mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist)); sendmap.Add("trackcount", mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.PlayCount)); sendmap.Add("album", mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album)); sendmap.Add("albumart", mbApiInterface.NowPlaying_GetArtwork()); sendmap.Add("composer", mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Composer)); var json = new JavaScriptSerializer().Serialize(sendmap.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString())); Task.Run(() => { try { var bary = Encoding.UTF8.GetBytes(json); var pipe = new NamedPipeClientStream("NowPlayingTunesV2PIPE"); pipe.Connect(1000); //set timeout 1000msec. pipe.Write(bary, 0, bary.Count()); pipe.Close(); } catch { } }); break; } }
private Track GetTrack() { var trackInfo = new NowPlayingTrackInfo( mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle), mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist), mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album), new TimeSpan(0, 0, 0, 0, mbApiInterface.NowPlaying_GetDuration()), new Uri(mbApiInterface.NowPlaying_GetFileProperty( FilePropertyType.Url), UriKind.Absolute) ); Track track = new Track(trackInfo); return(track); }
// Provides easy access to MusicBee metadata by enum name private Dictionary <string, Func <string> > GetMetaDataDelegates() { var dictionary = new Dictionary <string, Func <string> >(); foreach (MetaDataType enumVal in Enum.GetValues(typeof(MetaDataType))) { string enumName = Enum.GetName(typeof(MetaDataType), enumVal); dictionary[enumName] = () => mbApiInterface.NowPlaying_GetFileTag(enumVal); } foreach (FilePropertyType enumVal in Enum.GetValues(typeof(FilePropertyType))) { string enumName = Enum.GetName(typeof(FilePropertyType), enumVal); dictionary[enumName] = () => mbApiInterface.NowPlaying_GetFileProperty(enumVal); } return(dictionary); }
public Dictionary <string, string> GenerateMetaDataDictionary(string fileUrl = null) { var ret = new Dictionary <string, string>(Enum.GetNames(typeof(MetaDataType)).Length + Enum.GetNames(typeof(FilePropertyType)).Length); foreach (MetaDataType elem in Enum.GetValues(typeof(MetaDataType))) { ret.Add(elem.ToString(), string.IsNullOrWhiteSpace(fileUrl) ? _mbApiInterface.NowPlaying_GetFileTag(elem) : _mbApiInterface.Library_GetFileTag(fileUrl, elem)); } foreach (FilePropertyType elem in Enum.GetValues(typeof(FilePropertyType))) { ret.Add(elem.ToString(), string.IsNullOrWhiteSpace(fileUrl) ? _mbApiInterface.NowPlaying_GetFileProperty(elem) : _mbApiInterface.Library_GetFileProperty(fileUrl, elem)); } ret.Add("Extension", Path.GetExtension(string.IsNullOrWhiteSpace(fileUrl) ? _mbApiInterface.NowPlaying_GetFileUrl() : fileUrl).TrimStart('.').ToUpper()); ret.Add("PlayState", _mbApiInterface.Player_GetPlayState().ToString()); ret.Add("Volume", Convert.ToInt32(_mbApiInterface.Player_GetVolume() * 100.0f).ToString()); return(ret); }
public void ReceiveNotification(string sourceFileUrl, NotificationType type) { // musicbee api stuff string artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist); string trackTitle = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle); string duration = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Duration); bool getSongLength = mbApiInterface.Player_GetShowTimeRemaining(); string songLength = getSongLength.ToString(); int position = mbApiInterface.Player_GetPosition(); // create new variables so we can modify them for certain situations string songName = trackTitle; string songArtist = artist; // check if there is no artist so we can replace it with Unknown if (string.IsNullOrEmpty(artist)) { songName = trackTitle; songArtist = "Unknown"; } // perform some action depending on the notification type switch (type) { case NotificationType.PluginStartup: // perform startup initialization case NotificationType.PlayStateChanged: switch (mbApiInterface.Player_GetPlayState()) { case PlayState.Playing: UpdatePlayedPresence(songName, songArtist, duration, position / 1000); break; case PlayState.Paused: UpdatePausedPresence(); break; } break; case NotificationType.TrackChanged: UpdatePlayedPresence(songName, songArtist, duration, 0); break; } }
public void ReceiveNotification(string sourceFileUrl, NotificationType type) { string artist = MbApiInterface.NowPlaying_GetFileTag(MetaDataType.AlbumArtist); string trackArtist = MbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist); string trackTitle = MbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle); string album = MbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album); string duration = MbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Duration); int volume = Convert.ToInt32(MbApiInterface.Player_GetVolume() * 100.0f); int position = MbApiInterface.Player_GetPosition() / 1000; if (string.IsNullOrEmpty(artist)) { artist = "[artist empty]"; } switch (type) { case NotificationType.PlayStateChanged: switch (MbApiInterface.Player_GetPlayState()) { case PlayState.Playing: UpdatePresence(artist, trackArtist, trackTitle, album, duration, true, position, volume); break; case PlayState.Paused: UpdatePresence(artist, trackArtist, trackTitle, album, duration, false, 0, volume); break; } break; case NotificationType.TrackChanged: UpdatePresence(artist, trackArtist, trackTitle, album, duration, true, 0, volume, true); break; case NotificationType.VolumeLevelChanged: if (MbApiInterface.Player_GetPlayState() == PlayState.Playing) { UpdatePresence(artist, trackArtist, trackTitle, album, duration, true, position, volume); } break; } }
// receive event notifications from MusicBee // you need to set about.ReceiveNotificationFlags = PlayerEvents to receive all notifications, and not just the startup event public void ReceiveNotification(string sourceFileUrl, NotificationType type) { string artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist); string trackTitle = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle); string duration = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Duration); // mbApiInterface.NowPlaying_GetDuration(); int position = mbApiInterface.Player_GetPosition(); string song = artist + " - " + trackTitle; if (string.IsNullOrEmpty(artist)) { song = trackTitle; } // perform some action depending on the notification type PlayState state = mbApiInterface.Player_GetPlayState(); switch (type) { case NotificationType.PluginStartup: // perform startup initialisation case NotificationType.PlayStateChanged: switch (state) { case PlayState.Playing: UpdatePresence(song, duration, position / 1000, state); break; case PlayState.Paused: UpdatePresence(song, duration, 0, state: state); break; case PlayState.Stopped: UpdatePresence(song, duration, 0, state); break; } break; case NotificationType.TrackChanged: UpdatePresence(song, duration, 0, state); break; } }
// receive event notifications from MusicBee // you need to set about.ReceiveNotificationFlags = PlayerEvents to receive all notifications, and not just the startup event public void ReceiveNotification(string sourceFileUrl, NotificationType type) { string artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist); string trackTitle = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle); string album = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album); string duration = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Duration); // mbApiInterface.NowPlaying_GetDuration(); int position = mbApiInterface.Player_GetPosition(); // Check if there isn't an artist for the current song. If so, replace it with "(unknown artist)". if (string.IsNullOrEmpty(artist)) { artist = "(unknown artist)"; } // perform some action depending on the notification type switch (type) { case NotificationType.PluginStartup: // perform startup initialisation case NotificationType.PlayStateChanged: switch (mbApiInterface.Player_GetPlayState()) { case PlayState.Playing: UpdatePresence(artist, trackTitle, album, duration, true); break; case PlayState.Paused: UpdatePresence(artist, trackTitle, album, duration, false); break; } break; case NotificationType.TrackChanged: UpdatePresence(artist, trackTitle, album, duration, true); break; } }
private async void SendRequest() { if (isSending) { return; } isSending = true; while (isSending) { try { if (string.IsNullOrEmpty(settings.RequestUri)) { return; } string payload = Regex.Replace(settings.Content, @"{(\w+):(\w+)}", match => { switch (match.Groups[1].Value) { case "property": { if (Enum.TryParse(match.Groups[2].Value, out FilePropertyType field)) { return(HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileProperty(field))); } break; } case "tag": { if (Enum.TryParse(match.Groups[2].Value, out MetaDataType field)) { return(HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileTag(field))); } break; } } return(match.Value); }); HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(settings.RequestMethod), settings.RequestUri); StringContent content = new StringContent(payload, Encoding.UTF8, settings.MediaType); request.Content = content; foreach (var pair in settings.Headers) { request.Headers.Add(pair.Key, pair.Value); } var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { isSending = false; } } catch { await Task.Delay(3000); } } }
public async Task LoadSong(string hashed, string songFileExt) { string filetype = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Kind).Replace(" audio file", ""); string samplerate = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.SampleRate); string bitrate = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Bitrate); string channels = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Channels); string properties = ""; string nextSong = mbApiInterface.NowPlayingList_GetFileTag(mbApiInterface.NowPlayingList_GetNextIndex(1), MetaDataType.TrackTitle) + " by " + mbApiInterface.NowPlayingList_GetFileTag(mbApiInterface.NowPlayingList_GetNextIndex(1), MetaDataType.Artist); nextSong = nextSong == " by " || nextSong == null ? "End of List" : nextSong; if (filetype == "FLAC") { using (FlacFile file = new FlacFile(mbApiInterface.NowPlaying_GetFileUrl())) { properties = filetype + " " + file.StreamInfo.BitsPerSample.ToString() + " bit, " + samplerate + ", " + bitrate + ", " + channels; } } else { properties = filetype + " " + samplerate + ", " + bitrate + ", " + channels; } string[] temp = null; mbApiInterface.NowPlayingList_QueryFilesEx("", ref temp); int size = temp.Count(); try { await mediaChannel.LoadAsync( new MediaInformation() { ContentId = HttpUtility.UrlPathEncode(mediaContentURL + hashed + songFileExt), StreamType = StreamType.Buffered, Duration = mbApiInterface.NowPlaying_GetDuration() / 1000, Metadata = new MusicTrackMediaMetadata { Artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist), Title = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle), AlbumName = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album), Images = new[] { new GoogleCast.Models.Image { Url = mediaContentURL + hashed + ".jpg" } }, }, CustomData = new Dictionary <string, string>() { { "Properties", properties }, { "Position", (mbApiInterface.NowPlayingList_GetCurrentIndex() + 1).ToString() + " / " + size.ToString() }, { "Next", nextSong } } }); filenameStack.Push(hashed.ToString()); } catch (OperationCanceledException) { Debug.WriteLine("Requested to close"); } catch (Exception e) { Debug.WriteLine(e.Message); } }
/// <inheritdoc/> public NowPlayingDetails GetPlayingTrackDetails() { var nowPlayingTrack = new NowPlayingDetails { AlbumArtist = _api.NowPlaying_GetFileTag(MetaDataType.AlbumArtist).Cleanup(), Genre = _api.NowPlaying_GetFileTag(MetaDataType.Genre).Cleanup(), TrackNo = _api.NowPlaying_GetFileTag(MetaDataType.TrackNo).Cleanup(), TrackCount = _api.NowPlaying_GetFileTag(MetaDataType.TrackCount).Cleanup(), DiscNo = _api.NowPlaying_GetFileTag(MetaDataType.DiscNo).Cleanup(), DiscCount = _api.NowPlaying_GetFileTag(MetaDataType.DiscCount).Cleanup(), Grouping = _api.NowPlaying_GetFileTag(MetaDataType.Grouping).Cleanup(), Publisher = _api.NowPlaying_GetFileTag(MetaDataType.Publisher).Cleanup(), RatingAlbum = _api.NowPlaying_GetFileTag(MetaDataType.RatingAlbum).Cleanup(), Composer = _api.NowPlaying_GetFileTag(MetaDataType.Composer).Cleanup(), Comment = _api.NowPlaying_GetFileTag(MetaDataType.Comment).Cleanup(), Encoder = _api.NowPlaying_GetFileTag(MetaDataType.Encoder).Cleanup(), Kind = _api.NowPlaying_GetFileProperty(FilePropertyType.Kind).Cleanup(), Format = _api.NowPlaying_GetFileProperty(FilePropertyType.Format).Cleanup(), Size = _api.NowPlaying_GetFileProperty(FilePropertyType.Size).Cleanup(), Channels = _api.NowPlaying_GetFileProperty(FilePropertyType.Channels).Cleanup(), SampleRate = _api.NowPlaying_GetFileProperty(FilePropertyType.SampleRate).Cleanup(), Bitrate = _api.NowPlaying_GetFileProperty(FilePropertyType.Bitrate).Cleanup(), DateModified = _api.NowPlaying_GetFileProperty(FilePropertyType.DateModified).Cleanup(), DateAdded = _api.NowPlaying_GetFileProperty(FilePropertyType.DateAdded).Cleanup(), LastPlayed = _api.NowPlaying_GetFileProperty(FilePropertyType.LastPlayed).Cleanup(), PlayCount = _api.NowPlaying_GetFileProperty(FilePropertyType.PlayCount).Cleanup(), SkipCount = _api.NowPlaying_GetFileProperty(FilePropertyType.SkipCount).Cleanup(), Duration = _api.NowPlaying_GetFileProperty(FilePropertyType.Duration).Cleanup(), }; return(nowPlayingTrack); }
// Receive event notifications from MusicBee. public void ReceiveNotification(string sourceFileUrl, NotificationType type) { // Get the MusicBee settings path for later. string dataPath = mbApiInterface.Setting_GetPersistentStoragePath(); // Prepare the HTTP client instance for later. HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", userToken); // Set the authorization headers. System.Threading.Tasks.Task <HttpResponseMessage> submitListenResponse; // Perform some action depending on the notification type. switch (type) { case NotificationType.PluginStartup: // Perform startup initialisation. // Get the metadata of the track selected by MusicBee on startup to know what to scrobble. artist = HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist)); track = HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle)); release = HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album)); // Get the current playcount to see if it changes or if the song was skipped. previousPlaycount = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.PlayCount); // Re-scrobble any offline scrobbles. try { string[] offlineScrobbles = Directory.GetFiles(String.Concat(dataPath, settingsSubfolder, "scrobbles")); for (int i = 0; i < offlineScrobbles.Length; i++) { if (!String.IsNullOrEmpty(userToken)) // But only if the user token is configured. { try { submitListenResponse = httpClient.PostAsync("https://api.listenbrainz.org/1/submit-listens", new StringContent(File.ReadAllText(offlineScrobbles[i]), Encoding.UTF8, "application/json")); if (submitListenResponse.Result.IsSuccessStatusCode) // If the re-scrobble succeedes, remove the file. { try { File.Delete(offlineScrobbles[i]); } catch (IOException) // Handle the case where the saved scrobble is opened. { // Do nothing, the file will be removed on the next run. } } } catch // Handle the connectivity issues exception. { // Do nothing, the file will be re-scrobbled on the next run. } } } } catch (DirectoryNotFoundException) // Handle the "no offline scroble directory" exception. { // Do nothing, there's just nothing to re-scrobble. } //switch (mbApiInterface.Player_GetPlayState()) //{ // case PlayState.Playing: // case PlayState.Paused: // artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist); // break; //} break; case NotificationType.TrackChanged: // Update the metadata on track change. artist = HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist)); track = HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle)); release = HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album)); // Get the current playcount to see if it changes or if the song was skipped. previousPlaycount = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.PlayCount); break; case NotificationType.PlayCountersChanged: // This is emitted each time either a play count OR a skip count increases. // Scrobble the track but only if the user token is configured and the song wasn't skipped. if (!String.IsNullOrEmpty(userToken) && !(previousPlaycount == mbApiInterface.Library_GetFileProperty(sourceFileUrl, FilePropertyType.PlayCount))) { timestamp = DateTime.UtcNow - new DateTime(1970, 1, 1); // Get the timestamp in epoch. // Prepare the scrobble. string submitListenJson = "{\"listen_type\": \"single\", \"payload\": [ { \"listened_at\": " + (int)timestamp.TotalSeconds + ",\"track_metadata\": {\"artist_name\": \"" + artist + "\", \"track_name\": \"" + track + "\", \"release_name\": \"" + release + "\", \"additional_info\": {\"listening_from\": \"MusicBee\"} } } ] }"; // Set the scrobble JSON. // Post the scrobble. for (int i = 0; i < 5; i++) // In case of temporary errors do up to 5 retries. { try { submitListenResponse = httpClient.PostAsync("https://api.listenbrainz.org/1/submit-listens", new StringContent(submitListenJson, Encoding.UTF8, "application/json")); if (submitListenResponse.Result.IsSuccessStatusCode) // If the scrobble succeedes, exit the loop. { break; } else // If the scrobble fails save it for a later resubmission and log the error. { // Log the timestamp, the failed scrobble and the error message in the error file. string errorTimestamp = DateTime.Now.ToString(); // Create the folder where the error log will be stored. Directory.CreateDirectory(String.Concat(dataPath, settingsSubfolder)); File.AppendAllText(String.Concat(dataPath, settingsSubfolder, "error.log"), errorTimestamp + " " + submitListenJson + Environment.NewLine); File.AppendAllText(String.Concat(dataPath, settingsSubfolder, "error.log"), errorTimestamp + " " + submitListenResponse.Result.Content.ReadAsStringAsync().Result + Environment.NewLine); // In case there's a problem with the scrobble JSON, the error is permanent so do not retry. if (submitListenResponse.Result.StatusCode.ToString() == "BadRequest") { // Save the scrobble to a file and exit the loop. SaveScrobble(timestamp.TotalSeconds.ToString(), submitListenJson); break; } // If this is the last retry save the scrobble. if (i == 4) { SaveScrobble(timestamp.TotalSeconds.ToString(), submitListenJson); } } } catch // When offline, save the scrobble for a later resubmission and exit the loop. { SaveScrobble(timestamp.TotalSeconds.ToString(), submitListenJson); break; } } } break; } }
public string CurrentTrackUrl() { return(_mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Url)); }