Exemple #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;
     }
 }
Exemple #2
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;
     }
 }
Exemple #3
0
        /// <inheritdoc/>
        public string GetCover()
        {
            var embeddedArtwork = _api.NowPlaying_GetArtwork();

            if (!string.IsNullOrEmpty(embeddedArtwork))
            {
                return(embeddedArtwork);
            }

            if (_api.ApiRevision < 17)
            {
                return(string.Empty);
            }

            var apiData = _api.NowPlaying_GetDownloadedArtwork();

            return(!string.IsNullOrEmpty(apiData) ? apiData : string.Empty);
        }
        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);
            }
        }
        private async void ProcessArtwork(string album, string hash = "")
        {
            var assetList = await Discord.GetAssetList().ReadAsStringAsync();

            var artworkData = MbApiInterface.NowPlaying_GetArtwork();

            var dataUri = "data:image/png;base64," + artworkData;

            var albumAssured = Utility.AssureByteSize(album, 32); //Asset keys larger than 32 bytes will cause an exception.

            if (assetList.Contains(albumAssured))
            {
                _rpcPresence.largeImageKey = albumAssured;
                return;
            }
            else
            {
                _rpcPresence.largeImageKey = "temp_uploading";
                await Discord.UploadAsset(albumAssured, dataUri);

                _rpcPresence.largeImageKey = albumAssured;
            }
        }
        // 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:
                try
                {
                    var artist = _mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
                    if (string.IsNullOrWhiteSpace(artist))
                    {
                        artist = _pluginSettings.DefaultArtistName;
                    }

                    using (var sw =
                               new StreamWriter(_pluginSettings.ArtistNameOutputPath, false))
                    {
                        sw.Write(artist);
                    }

                    var title = _mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);
                    if (string.IsNullOrWhiteSpace(title))
                    {
                        title = _pluginSettings.DefaultTrackTitle;
                    }
                    using (var sw =
                               new StreamWriter(_pluginSettings.TrackTitleOutputPath, false))
                    {
                        sw.Write(title);
                    }

                    var album = _mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album);
                    if (string.IsNullOrWhiteSpace(album))
                    {
                        album = _pluginSettings.DefaultAlbumName;
                    }
                    using (var sw =
                               new StreamWriter(_pluginSettings.AlbumNameOutputPath, false))
                    {
                        sw.Write(album);
                    }

                    var artwork = _mbApiInterface.NowPlaying_GetArtwork();
                    if (string.IsNullOrWhiteSpace(artwork))
                    {
                        artwork = _pluginSettings.DefaultCoverArt;
                    }

                    var resizedArtworkImage = ImageHelper.ResizedArtworkImage(artwork,
                                                                              _pluginSettings.ArtworkOutputWidth,
                                                                              _pluginSettings.ArtworkOutputHeight);
                    resizedArtworkImage.Save(_pluginSettings.ArtworkOutputPath);
                }
                catch (UnauthorizedAccessException unauthorizedAccessException)
                {
                    UIHelper.DisplayExceptionDialog(unauthorizedAccessException,
                                                    "Plugin does not have permission to store files in defined output folder.");
                }
                catch (DirectoryNotFoundException directoryNotFoundException)
                {
                    UIHelper.DisplayExceptionDialog(directoryNotFoundException,
                                                    "Invalid output file path, Please check plugin settings.");
                }
                catch (IOException ioException)
                {
                    UIHelper.DisplayExceptionDialog(ioException,
                                                    @"Invalid output file, Please check plugin settings");
                }
                catch (Exception ex)
                {
                    UIHelper.DisplayExceptionDialog(ex);
                }

                break;
            }
        }
Exemple #7
0
        private void UpdateDiscordPresence(PlayState playerGetPlayState)
        {
            Debug.WriteLine("DiscordBee: Updating Presence with PlayState {0}...", playerGetPlayState);
            var          metaDataDict     = GenerateMetaDataDictionary();
            RichPresence _discordPresence = new RichPresence
            {
                Assets     = new Assets(),
                Party      = new Party(),
                Timestamps = new Timestamps()
            };

            // Discord allows only strings with a min length of 2 or the update fails
            // so add some exotic space (Mongolian vowel separator) to the string if it is smaller
            // Discord also disallows strings bigger than 128bytes so handle that as well
            string padString(string input)
            {
                if (!string.IsNullOrEmpty(input))
                {
                    if (input.Length < 2)
                    {
                        return(input + "\u180E");
                    }
                    if (Encoding.UTF8.GetBytes(input).Length > 128)
                    {
                        byte[] buffer     = new byte[128];
                        char[] inputChars = input.ToCharArray();
                        Encoding.UTF8.GetEncoder().Convert(
                            chars: inputChars,
                            charIndex: 0,
                            charCount: inputChars.Length,
                            bytes: buffer,
                            byteIndex: 0,
                            byteCount: buffer.Length,
                            flush: false,
                            charsUsed: out _,
                            bytesUsed: out int bytesUsed,
                            completed: out _);
                        return(Encoding.UTF8.GetString(buffer, 0, bytesUsed));
                    }
                }
                return(input);
            }

            // Button Functionality
            if (_settings.ShowButton)
            {
                var uri = _layoutHandler.RenderUrl(_settings.ButtonUrl, metaDataDict);
                Debug.WriteLine($"Url: {uri}");

                // Validate the URL again.
                if (ValidationHelpers.ValidateUri(uri))
                {
                    _discordPresence.Buttons = new Button[]
                    {
                        new Button
                        {
                            Label = padString(_settings.ButtonLabel),
                            Url   = uri
                        }
                    };
                }
            }

            void SetImage(string name, bool forceHideSmallImage = false)
            {
                if (_settings.TextOnly)
                {
                    _discordPresence.Assets.LargeImageKey  = null;
                    _discordPresence.Assets.LargeImageText = null;
                    _discordPresence.Assets.SmallImageKey  = null;
                    _discordPresence.Assets.SmallImageText = null;
                }
                else
                {
                    _discordPresence.Assets.LargeImageKey  = AssetManager.ASSET_LOGO;
                    _discordPresence.Assets.LargeImageText = padString(_layoutHandler.Render(_settings.LargeImageText, metaDataDict, _settings.Separator));

                    if (_settings.ShowPlayState && !forceHideSmallImage)
                    {
                        _discordPresence.Assets.SmallImageKey  = padString(name);
                        _discordPresence.Assets.SmallImageText = padString(_layoutHandler.Render(_settings.SmallImageText, metaDataDict, _settings.Separator));
                    }
                    else
                    {
                        _discordPresence.Assets.SmallImageKey  = null;
                        _discordPresence.Assets.SmallImageText = null;
                    }
                }
            }

            _discordPresence.State = padString(_layoutHandler.Render(_settings.PresenceState, metaDataDict, _settings.Separator));

            var t = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1));

            if (_settings.ShowTime)
            {
                if (_settings.ShowRemainingTime)
                {
                    // show remaining time
                    // subtract current track position from total duration for position seeking
                    var totalRemainingDuration = _mbApiInterface.NowPlaying_GetDuration() - _mbApiInterface.Player_GetPosition();
                    _discordPresence.Timestamps.EndUnixMilliseconds = (ulong)(Math.Round(t.TotalSeconds) + Math.Round(totalRemainingDuration / 1000.0));
                }
                else
                {
                    // show elapsed time
                    _discordPresence.Timestamps.StartUnixMilliseconds = (ulong)(Math.Round(t.TotalSeconds) - Math.Round(_mbApiInterface.Player_GetPosition() / 1000.0));
                }
            }

            switch (playerGetPlayState)
            {
            case PlayState.Playing:
                SetImage(AssetManager.ASSET_PLAY, _settings.ShowOnlyNonPlayingState);
                break;

            case PlayState.Stopped:
                SetImage(AssetManager.ASSET_STOP);
                _discordPresence.Timestamps.Start = null;
                _discordPresence.Timestamps.End   = null;
                break;

            case PlayState.Paused:
                SetImage(AssetManager.ASSET_PAUSE);
                _discordPresence.Timestamps.Start = null;
                _discordPresence.Timestamps.End   = null;
                break;

            case PlayState.Undefined:
            case PlayState.Loading:
                break;
            }

            _discordPresence.Details = padString(_layoutHandler.Render(_settings.PresenceDetails, metaDataDict, _settings.Separator));

            var trackcnt = -1;
            var trackno  = -1;

            try
            {
                trackcnt = int.Parse(_layoutHandler.Render(_settings.PresenceTrackCnt, metaDataDict, _settings.Separator));
                trackno  = int.Parse(_layoutHandler.Render(_settings.PresenceTrackNo, metaDataDict, _settings.Separator));
            }
#pragma warning disable RCS1075 // Avoid empty catch clause that catches System.Exception.
            catch (Exception)
#pragma warning restore RCS1075 // Avoid empty catch clause that catches System.Exception.
            {
                // ignored
            }

            if (trackcnt < trackno || trackcnt <= 0 || trackno <= 0)
            {
                _discordPresence.Party = null;
            }
            else
            {
                _discordPresence.Party = new Party
                {
                    ID   = "aaaa",
                    Max  = trackcnt,
                    Size = trackno
                };
            }

            if (!_settings.UpdatePresenceWhenStopped && (playerGetPlayState == PlayState.Paused || playerGetPlayState == PlayState.Stopped))
            {
                Debug.WriteLine("Clearing Presence...", "DiscordBee");
                _discordClient.ClearPresence();
            }
            else
            {
                Debug.WriteLine("Setting new Presence...", "DiscordBee");
                Task.Run(() => _discordClient.SetPresence(_discordPresence, GetAlbumCoverData(_mbApiInterface.NowPlaying_GetArtwork(), metaDataDict)));
            }
        }