示例#1
0
 // 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;
     }
 }
        // mbs notifications
        public void ReceiveNotification(string sourceFileUrl, NotificationType type)
        {
            switch (type)
            {
            case NotificationType.PluginStartup:
                //start a new spotify session
                SpotifySession = new SpotifyController();
                break;

            case NotificationType.TrackChanged:
                //build our search query
                string artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
                string title  = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);
                string q      = (artist + " " + title);
                SpotifyCurrentTrack = SpotifySession.Search(q);
                //reset and check if current track is in spotify library
                inMyLibrary = false;
                if (SpotifyCurrentTrack != null)
                {
                    inMyLibrary = SpotifySession.CheckTracks(SpotifyCurrentTrack.Id);
                }
                //refresh panel
                panel.Invalidate();
                break;
            }
        }
示例#3
0
        private string Entry()
        {
            string time   = DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss");
            string title  = _mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);
            string artist = _mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);

            return($"{time} - {title} - {artist}");
        }
示例#4
0
        /// <summary>
        /// Send the current track to the server.
        /// </summary>
        /// <param name="client">The websocket client.</param>
        public void Send(WebSocketClient client)
        {
            TrackChangedStruct data;

            data.artist = api.NowPlaying_GetFileTag(MetaDataType.Artist);
            data.album  = api.NowPlaying_GetFileTag(MetaDataType.Album);
            data.track  = api.NowPlaying_GetFileTag(MetaDataType.TrackTitle);

            client.Send("track.changed", data);
        }
示例#5
0
        public void ReceiveNotification(string src, NotificationType type)
        {
            if (type == NotificationType.PlayerScrobbleChanged)
            {
                if (Api.Player_GetScrobbleEnabled())
                {
                    Api.Player_SetScrobbleEnabled(false);
                }
                return;
            }

            if (type != NotificationType.TrackChanged && type != NotificationType.PlayStateChanged)
            {
                return;
            }

            var title       = Api.NowPlaying_GetFileTag(Settings.GetTag("ScrobbleBee-Title", MetaDataType.TrackTitle));
            var artist      = Api.NowPlaying_GetFileTag(Settings.GetTag("ScrobbleBee-Artist", MetaDataType.Artist));
            var album       = Api.NowPlaying_GetFileTag(Settings.GetTag("ScrobbleBee-Album", MetaDataType.Album));
            var albumArtist = Api.NowPlaying_GetFileTag(Settings.GetTag("ScrobbleBee-AlbumArtist", MetaDataType.AlbumArtist));
            var duration    = Api.NowPlaying_GetDuration();

            switch (type)
            {
            case NotificationType.TrackChanged:
                TryScrobble(lastTitle, lastArtist, lastAlbum, lastAlbumArtist, lastDuration);
                LastFm.Update(title, artist, album, albumArtist, duration);

                hasScrobbled = duration < 30000;
                started      = DateTime.UtcNow;
                played       = 0;

                lastTitle       = title;
                lastArtist      = artist;
                lastAlbum       = album;
                lastAlbumArtist = albumArtist;
                lastDuration    = duration;
                break;

            case NotificationType.PlayStateChanged:
                switch (Api.Player_GetPlayState())
                {
                case PlayState.Playing:
                    started = DateTime.UtcNow;
                    break;

                case PlayState.Paused:
                case PlayState.Stopped:
                    TryScrobble(title, artist, album, albumArtist, duration);
                    break;
                }
                break;
            }
        }
        private void UpdatePresence(string artist, string trackArtist, string track, string album, string duration,
                                    bool playing, int position, int volume, bool handleArtworks = false)
        {
            track       = Utility.Utf16ToUtf8(track + " ");
            artist      = Utility.Utf16ToUtf8("by " + artist);
            trackArtist = Utility.Utf16ToUtf8("by " + trackArtist);

            _rpcPresence.state   = Utility.AssureByteSize(trackArtist.Substring(0, trackArtist.Length - 1), 128);
            _rpcPresence.details = Utility.AssureByteSize(track.Substring(0, track.Length - 1), 128);

            string largeText = album + " " + artist;

            string genre = MbApiInterface.NowPlaying_GetFileTag(MetaDataType.Genre);

            _rpcPresence.largeImageText = largeText.Substring(0, largeText.Length - 1);

            if (!string.IsNullOrEmpty(genre))
            {
                _rpcPresence.largeImageText += $" ({genre})";
            }

            string cleanedAlbum = Utility.SanitizeAlbumName(Utility.ValidateEncoding(album));

            if (handleArtworks)
            {
                ProcessArtwork(cleanedAlbum);
            }

            long now = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            if (playing)
            {
                _rpcPresence.startTimestamp = now - position;

                string[] durations = duration.Split(':');
                long     end       = Convert.ToInt64(durations[0]) * 60 + Convert.ToInt64(durations[1]);

                _rpcPresence.endTimestamp   = _rpcPresence.startTimestamp + end;
                _rpcPresence.smallImageKey  = "playing";
                _rpcPresence.smallImageText = "Playing at " + volume + "%";
            }
            else
            {
                _rpcPresence.endTimestamp   = 0;
                _rpcPresence.startTimestamp = 0;
                _rpcPresence.smallImageKey  = "paused";
                _rpcPresence.smallImageText = "Paused";
            }

            DiscordRPC.UpdatePresence(ref _rpcPresence);
        }
示例#7
0
        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);
        }
示例#8
0
 public void ReceiveNotification(string sourceFileUrl, NotificationType type)
 {
     switch (type)
     {
     case NotificationType.TrackChanged:
         string title   = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);
         string album   = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album);
         string comment = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Comment);
         string artist  = comment != "" ? comment : mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist).Replace(";", ",");
         string artwork = mbApiInterface.NowPlaying_GetArtwork() ?? "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY/j//z8ABf4C/qc1gYQAAAAASUVORK5CYII=";     // base64
         string json    = $"{{ \"title\": \"{ title }\", \"artist\": \"{ artist }\", \"album\": \"{ album }\", \"artwork\": \"{ artwork }\" }}";
         sendRequest("http://localhost:55432/api/music", json);
         break;
     }
 }
示例#9
0
        // 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.PluginStartup:
                // perform startup initialisation
                switch (mbApiInterface.Player_GetPlayState())
                {
                case PlayState.Playing:
                    Console.WriteLine("//////////////////////////////////////////\n//////////////////////////////");
                    MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    break;

                case PlayState.Paused:
                    // ...
                    break;
                }
                break;

            case NotificationType.TrackChanged:
                string artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
                // ...
                break;
            }
        }
示例#10
0
 public GetNowPlaying()
 {
     Get["/now-playing"] = _ =>
     {
         MusicBeeApiInterface mbApi = MbApiInstance.Instance.MusicBeeApiInterface;
         return(mbApi.NowPlaying_GetFileTag(MetaDataType.TrackTitle));
     };
 }
示例#11
0
        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;
            }
        }
示例#12
0
        public void ReceiveNotification(string src, NotificationType type)
        {
            if (type != NotificationType.TrackChanged && type != NotificationType.PlayStateChanged)
            {
                return;
            }

            string title    = Api.NowPlaying_GetFileTag(Settings.Title);
            string artist   = Api.NowPlaying_GetFileTag(Settings.Artist);
            string album    = Api.NowPlaying_GetFileTag(Settings.Album);
            int    duration = Api.NowPlaying_GetDuration();

            switch (type)
            {
            case NotificationType.TrackChanged:
                TryScrobble(lastTitle, lastArtist, lastAlbum, lastDuration);
                LastFM.Update(title, artist, album, (duration / 1000).ToString());

                hasScrobbled = duration < 30000;
                started      = DateTime.UtcNow;
                played       = 0;

                lastTitle    = title;
                lastArtist   = artist;
                lastAlbum    = album;
                lastDuration = duration;
                break;

            case NotificationType.PlayStateChanged:
                switch (Api.Player_GetPlayState())
                {
                case PlayState.Playing:
                    started = DateTime.UtcNow;
                    break;

                case PlayState.Paused:
                case PlayState.Stopped:
                    TryScrobble(title, artist, album, duration);
                    break;
                }
                break;
            }
        }
示例#13
0
        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();

            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 / 1000, 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 / 1000, 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;
            }
        }
示例#15
0
        // 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.PluginStartup:
                // Setup Plugin



                break;

            case NotificationType.PlayCountersChanged:
                string artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
                string song   = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);


                break;
            }
        }
示例#16
0
        public Dictionary <string, string> GenerateMetaDataDictionary()
        {
            var ret = new Dictionary <string, string>(Enum.GetNames(typeof(MetaDataType)).Length);

            foreach (MetaDataType elem in Enum.GetValues(typeof(MetaDataType)))
            {
                ret.Add(elem.ToString(), _mbApiInterface.NowPlaying_GetFileTag(elem));
            }

            return(ret);
        }
        internal void getSongData()
        {
            string artist       = mbApiInterface_.NowPlaying_GetFileTag(MetaDataType.Artist);
            string album        = mbApiInterface_.NowPlaying_GetFileTag(MetaDataType.Album);
            string title        = mbApiInterface_.NowPlaying_GetFileTag(MetaDataType.TrackTitle);
            string artwork      = mbApiInterface_.NowPlaying_GetArtwork();
            string ratingString = mbApiInterface_.NowPlaying_GetFileTag(MetaDataType.Rating);
            string lyrics       = mbApiInterface_.NowPlaying_GetLyrics();

            float rating = 0;

            if (ratingString != "")
            {
                rating = Convert.ToSingle(ratingString);
            }

            foreach (Screen screen in lcdScreenList_)
            {
                screen.songChanged(artist, album, title, rating, artwork, mbApiInterface_.NowPlaying_GetDuration(), mbApiInterface_.Player_GetPosition(), lyrics);
            }
        }
示例#18
0
        private void SetDisplayValues()
        {
            displayUpdater.ClearAll();
            displayUpdater.Type = MediaPlaybackType.Music;
            SetArtworkThumbnail(null);
            string url = mbApiInterface.NowPlaying_GetFileUrl();

            if (url != null)
            {
                musicProperties.AlbumArtist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.AlbumArtist);
                musicProperties.AlbumTitle  = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album);
                uint value;
                if (UInt32.TryParse(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackCount), out value))
                {
                    musicProperties.AlbumTrackCount = value;
                }
                musicProperties.Artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
                musicProperties.Title  = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);
                if (string.IsNullOrEmpty(musicProperties.Title))
                {
                    musicProperties.Title = url.Substring(url.LastIndexOfAny(new char[] { '/', '\\' }) + 1);
                }
                if (UInt32.TryParse(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackNo), out value))
                {
                    musicProperties.TrackNumber = value;
                }
                //musicProperties.Genres = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Genres).Split(new string[] {"; "}, StringSplitOptions.RemoveEmptyEntries);
                PictureLocations pictureLocations;
                string           pictureUrl;
                byte[]           imageData;
                mbApiInterface.Library_GetArtworkEx(url, 0, true, out pictureLocations, out pictureUrl, out imageData);
                SetArtworkThumbnail(imageData);
            }
            displayUpdater.Update();
        }
示例#19
0
        public Dictionary <string, string> GenerateMetaDataDictionary()
        {
            var ret = new Dictionary <string, string>(Enum.GetNames(typeof(MetaDataType)).Length);

            foreach (MetaDataType elem in Enum.GetValues(typeof(MetaDataType)))
            {
                ret.Add(elem.ToString(), _mbApiInterface.NowPlaying_GetFileTag(elem));
            }
            ret.Add("PlayState", _mbApiInterface.Player_GetPlayState().ToString());
            ret.Add("Volume", Convert.ToInt32(_mbApiInterface.Player_GetVolume() * 100.0f).ToString());

            return(ret);
        }
示例#20
0
        public string RetrieveLyrics(string sourceFileUrl, string artist, string trackTitle, string album,
                                     bool synchronisedPreferred, string provider)
        {
            if (provider != ProviderName)
            {
                return(null);
            }

            var id          = 0;
            var specifiedId = _mbApiInterface.Library_GetFileTag(sourceFileUrl, MetaDataType.Custom10)
                              ?? _mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Custom10);

            if (specifiedId != null && specifiedId.StartsWith("netease="))
            {
                specifiedId = specifiedId.Substring("netease=".Length);
                int.TryParse(specifiedId, out id);
            }

            if (id == 0)
            {
                var searchResult = QueryWithFeatRemoved(trackTitle, artist);
                if (searchResult == null)
                {
                    return(null);
                }
                id = searchResult.id;
            }

            if (id == 0)
            {
                return(null);
            }

            var lyricResult = RequestLyric(id);

            if (lyricResult.lrc?.lyric == null)
            {
                return(null);
            }
            if (lyricResult.tlyric?.lyric == null || _config.format == NeteaseConfig.OutputFormat.Original)
            {
                return(lyricResult.lrc.lyric); // No need to process translation
            }
            if (_config.format == NeteaseConfig.OutputFormat.Translation)
            {
                return(lyricResult.tlyric?.lyric ?? lyricResult.lrc.lyric);
            }
            // translation
            return(LyricProcessor.InjectTranslation(lyricResult.lrc.lyric, lyricResult.tlyric.lyric));
        }
        // 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;
            }
        }
示例#22
0
        // 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);
        }
示例#23
0
        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 async void ReceiveNotification(string sourceFileUrl, NotificationType type)
        {
            switch (type)
            {
            case NotificationType.TrackChanged:

                _trackMissing = 0;
                _num          = 0;
                _searchTerm   = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle) + " + " + mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);

                if (_auth == 1)
                {
                    mbApiInterface.MB_RefreshPanels();
                    await TrackSearch();
                }

                panel.Invalidate();
                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)
        {
            // perform some action depending on the notification type
            switch (type)
            {
            case NotificationType.PluginStartup:
                // perform startup initialisation
                switch (mbApiInterface.Player_GetPlayState())
                {
                case PlayState.Playing:
                case PlayState.Paused:
                    // ...
                    break;
                }
                break;

            case NotificationType.TrackChanged:
                string artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
                // ...
                break;
            }
        }
示例#26
0
        private void SetDisplayValues()
        {
            // displayUpdater.ClearAll();
            if (displayUpdater.Type != MediaPlaybackType.Music)
            {
                displayUpdater.Type = MediaPlaybackType.Music;
            }
            // SetArtworkThumbnail(null);
            var url = mbApiInterface.NowPlaying_GetFileUrl();

            if (url != null)
            {
                musicProperties.AlbumArtist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.AlbumArtist);
                musicProperties.AlbumTitle  = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album);

                if (TryParse(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackCount), out var value))
                {
                    musicProperties.AlbumTrackCount = value;
                }

                musicProperties.Artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.MultiArtist);
                musicProperties.Title  = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);

                if (string.IsNullOrEmpty(musicProperties.Title))
                {
                    musicProperties.Title = url.Substring(url.LastIndexOfAny(new[] { '/', '\\' }) + 1);
                }

                if (TryParse(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackNo), out value))
                {
                    musicProperties.TrackNumber = value;
                }
                // musicProperties.Genres = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Genres).Split(new string[] {"; "}, StringSplitOptions.RemoveEmptyEntries);
                mbApiInterface.Library_GetArtworkEx(url, 0, true, out _, out _, out var imageData);
                SetArtworkThumbnail(imageData);
            }
            else
            {
                SetArtworkThumbnail(null);
            }

            displayUpdater.Update();
        }
示例#27
0
        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);
            }
        }
示例#29
0
        // 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.PluginStartup:
                // perform startup initialisation
                artist  = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
                track   = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);
                release = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album);

                //switch (mbApiInterface.Player_GetPlayState())
                //{
                //    case PlayState.Playing:
                //    case PlayState.Paused:
                //        artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
                //        break;
                //}
                break;

            case NotificationType.TrackChanged:
                artist  = HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist));
                track   = HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle));
                release = HttpUtility.JavaScriptStringEncode(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album));
                break;

            case NotificationType.PlayCountersChanged:
                if (!String.IsNullOrEmpty(userToken))                       // If the user token is configured.
                {
                    timestamp = DateTime.UtcNow - new DateTime(1970, 1, 1); // Get the timestamp in epoch.

                    // Prepare and post the scrobble.
                    HttpClient httpClient = new HttpClient();
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", userToken);      // Set the authorization headers.
                    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\"} } } ] }";

                    for (int i = 0; i < 5; i++)     // In case of temporary errors do up to 5 retries.
                    {
                        try
                        {
                            var 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 log it and the error.
                            {
                                // Log the timestamp and the error message in the error file.
                                string dataPath       = mbApiInterface.Setting_GetPersistentStoragePath();
                                string errorTimestamp = DateTime.Now.ToString();
                                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")
                                {
                                    break;
                                }
                            }
                        }
                        catch (HttpRequestException)
                        {
                            // Nothing to do here for now, implement offline scrobbling in the future.
                        }
                    }
                }
                break;
            }
        }
示例#30
0
        /// <inheritdoc/>
        public NowPlayingTrack GetPlayingTrackInfoLegacy()
        {
            var url   = _api.NowPlaying_GetFileUrl().Cleanup();
            var title = _api.NowPlaying_GetFileTag(MetaDataType.TrackTitle).Cleanup();

            var nowPlayingTrack = new NowPlayingTrack
            {
                Artist = _api.NowPlaying_GetFileTag(MetaDataType.Artist).Cleanup(),
                Album  = _api.NowPlaying_GetFileTag(MetaDataType.Album).Cleanup(),
                Year   = _api.NowPlaying_GetFileTag(MetaDataType.Year).Cleanup(),
            };

            nowPlayingTrack.SetTitle(title, url);
            return(nowPlayingTrack);
        }