Пример #1
0
        public override void Update()
        {
            Process[] processes = Process.GetProcessesByName("vlc");

            if (processes.Length > 0)
            {
                string vlcTitle = string.Empty;

                foreach (Process process in processes)
                {
                    vlcTitle = process.MainWindowTitle;
                }

                // Check for a hyphen in the title. If a hyphen exists then we need to cut all of the text after the last
                // hyphen because that's the "VLC media player" text, which can vary based on language.
                // If no hyphen exists then VLC is not playing anything.
                int lastHyphen = vlcTitle.LastIndexOf("-", StringComparison.OrdinalIgnoreCase);

                if (lastHyphen > 0)
                {
                    vlcTitle = vlcTitle.Substring(0, lastHyphen).Trim();

                    string vlcExtension = System.IO.Path.GetExtension(vlcTitle);

                    if (Globals.SaveAlbumArtwork)
                    {
                        this.SaveBlankImage();
                    }

                    // Filter file extension
                    // VLC doesn't always have file extensions show in the title.
                    // The previous code would sometimes cut song titles prematurely if there was no extension in the title.
                    // If there's an extension, we'll trim it. Otherwise, we won't do anything to the string.
                    if (vlcExtension.Length > 0)
                    {
                        int lastDot = vlcTitle.LastIndexOf(vlcExtension);

                        if (lastDot > 0)
                        {
                            vlcTitle = vlcTitle.Substring(0, lastDot).Trim();
                        }
                    }

                    TextHandler.UpdateText(vlcTitle);
                }
                else
                {
                    TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("NoTrackPlaying"));
                }
            }
            else
            {
                if (Globals.SaveAlbumArtwork)
                {
                    this.SaveBlankImage();
                }

                TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("VLCIsNotRunning"));
            }
        }
Пример #2
0
 private void Snip_FormClosing(object sender, FormClosingEventArgs e)
 {
     // Empty file, clear artwork and save settings automatically when the form is being closed.
     TextHandler.UpdateTextAndEmptyFilesMaybe(LocalizedMessages.NoTrackPlaying);
     Globals.CurrentPlayer.SaveBlankImage();
     Settings.Save();
 }
Пример #3
0
        private void UpdateSpotifyTrackInformation_Elapsed(object sender, ElapsedEventArgs e)
        {
            string downloadedJson = this.DownloadJson("https://api.spotify.com/v1/me/player/currently-playing", SpotifyAddressContactType.API);

            if (!string.IsNullOrEmpty(downloadedJson))
            {
                dynamic jsonSummary = SimpleJson.DeserializeObject(downloadedJson);

                bool   isPlaying = (bool)jsonSummary.is_playing;
                string trackId   = (string)jsonSummary.item.id;

                if (isPlaying)
                {
                    // Only update if the track ID has changed or the user updates how the output format should look
                    if (trackId != this.lastTrackId || Globals.RewriteUpdatedOutputFormat)
                    {
                        Globals.RewriteUpdatedOutputFormat = false;
                        this.lastTrackId = trackId;

                        if (Globals.CacheSpotifyMetadata)
                        {
                            downloadedJson = this.ReadCachedJson(trackId);
                        }

                        // If there are multiple artists we want to join all of them together for display
                        string artists = string.Empty;

                        foreach (dynamic artist in jsonSummary.item.artists)
                        {
                            artists += artist.name.ToString() + ", ";
                        }

                        artists = artists.Substring(0, artists.LastIndexOf(',')); // Removes last comma

                        TextHandler.UpdateText(
                            jsonSummary.item.name.ToString(),
                            artists,
                            jsonSummary.item.album.name.ToString(),
                            jsonSummary.item.id.ToString(),
                            downloadedJson);

                        if (Globals.SaveAlbumArtwork)
                        {
                            this.DownloadSpotifyAlbumArtwork(jsonSummary.item.album);
                        }
                    }
                }
                else
                {
                    this.ResetSnipSinceSpotifyIsNotPlaying();
                }

                // Reset timer after it was potentially changed by rate limit
                // Since we should only reach this point if valid JSON was obtained this means
                // that the timer shouldn't reset unless there was a success.
                this.updateSpotifyTrackInformation.Enabled  = false;
                this.updateSpotifyTrackInformation.Interval = updateSpotifyTrackInformationDefaultInterval;
                this.updateSpotifyTrackInformation.Enabled  = true;
            }
        }
Пример #4
0
        private void TogglePlayer(Globals.MediaPlayerSelection player)
        {
            this.toolStripMenuItemSpotify.Checked = player == Globals.MediaPlayerSelection.Spotify;
            this.toolStripMenuItemItunes.Checked  = player == Globals.MediaPlayerSelection.Itunes;

            Globals.CurrentPlayer.Unload();
            string playerName = string.Empty;

            switch (player)
            {
            case Globals.MediaPlayerSelection.Spotify:
                Globals.CurrentPlayer = new Spotify();
                playerName            = LocalizedMessages.Spotify;
                break;

            case Globals.MediaPlayerSelection.Itunes:
                Globals.CurrentPlayer = new Itunes();
                playerName            = LocalizedMessages.Itunes;
                break;

            default:
                break;
            }

            Globals.CurrentPlayer.Load();

            Globals.PlayerSelection = player;
            TextHandler.UpdateTextAndEmptyFilesMaybe(
                string.Format(
                    CultureInfo.InvariantCulture,
                    LocalizedMessages.SwitchedToPlayer,
                    playerName));
        }
Пример #5
0
        private void App_OnPlayerPlayingTrackChangedEvent(object sender)
        {
            IITTrack track = this.iTunesApplication.CurrentTrack;

            if (!string.IsNullOrEmpty(track.Artist) && !string.IsNullOrEmpty(track.Name) && string.IsNullOrEmpty(this.iTunesApplication.CurrentStreamTitle))
            {
                if (Globals.SaveAlbumArtwork)
                {
                    try
                    {
                        IITArtworkCollection artworkCollection = track.Artwork;
                        IITArtwork           artwork           = artworkCollection[1];

                        artwork.SaveArtworkToFile(this.DefaultArtworkFilePath);
                    }
                    catch
                    {
                        this.SaveBlankImage();
                        throw;
                    }
                }

                TextHandler.UpdateText(track.Name, track.Artist, track.Album);
            }
            else if (!string.IsNullOrEmpty(this.iTunesApplication.CurrentStreamTitle))
            {
                TextHandler.UpdateText(this.iTunesApplication.CurrentStreamTitle);
            }
        }
Пример #6
0
        private void App_OnPlayerStopEvent(object o)
        {
            if (Globals.SaveAlbumArtwork)
            {
                this.SaveBlankImage();
            }

            TextHandler.UpdateTextAndEmptyFilesMaybe(LocalizedMessages.NoTrackPlaying);
        }
Пример #7
0
        private void App_OnPlayerStopEvent(object o)
        {
            if (Globals.SaveAlbumArtwork)
            {
                this.SaveBlankImage();
            }

            TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("NoTrackPlaying"));
        }
Пример #8
0
        private void App_OnPlayerQuittingEvent()
        {
            if (Globals.SaveAlbumArtwork)
            {
                this.SaveBlankImage();
            }

            TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("iTunesNotRunning"));
        }
Пример #9
0
        private void ResetSinceSpotifyIsNotRunning()
        {
            if (Globals.SaveAlbumArtwork)
            {
                this.SaveBlankImage();
            }

            TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("SpotifyIsNotRunning"));

            this.Found      = false;
            this.NotRunning = true;
        }
Пример #10
0
        public override void Update()
        {
            Process[] processes = Process.GetProcessesByName("vlc");

            if (processes.Length > 0)
            {
                string vlcTitle = string.Empty;

                foreach (Process process in processes)
                {
                    vlcTitle = process.MainWindowTitle;
                }

                // Check for a hyphen in the title. If a hyphen exists then we need to cut all of the text after the last
                // hyphen because that's the "VLC media player" text, which can vary based on language.
                // If no hyphen exists then VLC is not playing anything.
                int lastHyphen = vlcTitle.LastIndexOf("-", StringComparison.OrdinalIgnoreCase);

                if (lastHyphen > 0)
                {
                    vlcTitle = vlcTitle.Substring(0, lastHyphen).Trim();

                    if (Globals.SaveAlbumArtwork)
                    {
                        this.SaveBlankImage();
                    }

                    // Filter file extension
                    int lastDot = vlcTitle.LastIndexOf('.');

                    if (lastDot > 0)
                    {
                        vlcTitle = vlcTitle.Substring(0, lastDot).Trim();
                    }

                    TextHandler.UpdateText(vlcTitle);
                }
                else
                {
                    TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("NoTrackPlaying"));
                }
            }
            else
            {
                if (Globals.SaveAlbumArtwork)
                {
                    this.SaveBlankImage();
                }

                TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("VLCIsNotRunning"));
            }
        }
Пример #11
0
        private void App_OnPlayerQuittingEvent()
        {
            if (Globals.SaveAlbumArtwork)
            {
                this.SaveBlankImage();
            }

            TextHandler.UpdateTextAndEmptyFilesMaybe(
                string.Format(
                    CultureInfo.InvariantCulture,
                    Globals.ResourceManager.GetString("PlayerIsNotRunning"),
                    Globals.ResourceManager.GetString("iTunes")));
        }
Пример #12
0
 private void ResetSnipSinceSpotifyIsNotPlaying()
 {
     // Prevent writing a blank image if we already did
     if (!this.SavedBlankImage)
     {
         if (Globals.SaveAlbumArtwork)
         {
             this.SaveBlankImage();
         }
     }
     this.spotifyProcess = null;
     TextHandler.UpdateTextAndEmptyFilesMaybe(LocalizedMessages.NoTrackPlaying);
 }
Пример #13
0
        private void App_OnPlayerQuittingEvent()
        {
            if (Globals.SaveAlbumArtwork)
            {
                this.SaveBlankImage();
            }

            TextHandler.UpdateTextAndEmptyFilesMaybe(
                string.Format(
                    CultureInfo.InvariantCulture,
                    LocalizedMessages.PlayerIsNotRunning,
                    LocalizedMessages.iTunes));
        }
Пример #14
0
        private void ToggleVLC()
        {
            this.toolStripMenuItemSpotify.Checked    = false;
            this.toolStripMenuItemItunes.Checked     = false;
            this.toolStripMenuItemWinamp.Checked     = false;
            this.toolStripMenuItemFoobar2000.Checked = false;
            this.toolStripMenuItemVlc.Checked        = true;

            Globals.CurrentPlayer.Unload();
            Globals.CurrentPlayer = new VLC();
            Globals.CurrentPlayer.Load();

            Globals.PlayerSelection = Globals.MediaPlayerSelection.VLC;
            TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("SwitchedToVLC"));
        }
Пример #15
0
        private void App_OnPlayerQuittingEvent()
        {
            if (Globals.SaveAlbumArtwork)
            {
                this.SaveBlankImage();
            }

            if (Globals.EmptyFileIfNoTrackPlaying)
            {
                TextHandler.UpdateTextAndEmptyFile(Globals.ResourceManager.GetString("iTunesNotRunning"));
            }
            else
            {
                TextHandler.UpdateText(Globals.ResourceManager.GetString("iTunesNotRunning"));
            }
        }
Пример #16
0
        private void UpdateCSRFTokenTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (this.spotifyPort > 0)
            {
                // CSRF token path
                string csrfAddress = "/simplecsrf/token.json";

                string downloadedJson = this.DownloadJson(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "{0}:{1}{2}",
                        this.spotilocalAddress,
                        this.spotifyPort,
                        csrfAddress),
                    SpotifyAddressContactType.CSRF);

                // Set the token to be blank until filled
                this.csrfToken = string.Empty;

                if (!string.IsNullOrEmpty(downloadedJson))
                {
                    dynamic jsonSummary = SimpleJson.DeserializeObject(downloadedJson);

                    if (jsonSummary != null)
                    {
                        // If Spotify is running this value will be null
                        if (jsonSummary.running == null)
                        {
                            this.csrfToken = jsonSummary.token.ToString();
                            this.updateCSRFTokenTimer.Interval = 3600 * 1000; // We got what we wanted
                        }
                        else
                        {
                            this.ResetSnipSinceSpotifyIsNotRunning();
                            this.updateCSRFTokenTimer.Interval = 1000; // Run continously until token is obtained
                        }
                    }
                }
            }
            else
            {
                // Let the user know that we're searching for SpotifyWebHelper.
                TextHandler.UpdateTextAndEmptyFilesMaybe(LocalizedMessages.LocatingSpotifyWebHelper);

                this.DetectSpotifyWebHelperPort();
            }
        }
Пример #17
0
        private void ResetSnipSinceSpotifyIsNotRunning()
        {
            if (this.spotifyWindowFound)
            {
                this.spotifyWindowFound = false;
            }

            // Prevent writing a blank image if we already did
            if (!this.SavedBlankImage)
            {
                if (Globals.SaveAlbumArtwork)
                {
                    this.SaveBlankImage();
                }
            }

            TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("SpotifyIsNotRunning"));
        }
Пример #18
0
        private void ResetSnipSinceSpotifyIsNotPlaying()
        {
            if (!this.snipReset)
            {
                // Prevent writing a blank image if we already did
                if (!this.SavedBlankImage)
                {
                    if (Globals.SaveAlbumArtwork)
                    {
                        this.SaveBlankImage();
                    }
                }

                TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("NoTrackPlaying"));

                this.LastTitle = string.Empty;

                this.snipReset = true;
            }
        }
Пример #19
0
        private void ResetSnipSinceGPMDPIsNotPlaying()
        {
            if (!this.gpmdpReset)
            {
                // Prevent writing a blank image if we already did
                if (!this.SavedBlankImage)
                {
                    if (Globals.SaveAlbumArtwork)
                    {
                        this.SaveBlankImage();
                    }
                }

                TextHandler.UpdateTextAndEmptyFilesMaybe(LocalizedMessages.NoTrackPlaying);

                this.LastTitle = string.Empty;

                this.gpmdpReset = true;
            }
        }
Пример #20
0
        // TODO: Re-write this to download the artwork link supplied in the primary JSON file instead of using the old embedded web link.
        private void HandleSpotifyAlbumArtwork(string songTitle)
        {
            string albumId = string.Empty;

            try
            {
                if (!string.IsNullOrEmpty(this.json))
                {
                    dynamic jsonSummary = SimpleJson.DeserializeObject(json);

                    if (jsonSummary != null)
                    {
                        jsonSummary = SimpleJson.DeserializeObject(jsonSummary.tracks["items"].ToString());

                        foreach (dynamic jsonTrack in jsonSummary)
                        {
                            string modifiedTitle = TextHandler.UnifyTitles(songTitle);
                            string foundTitle    = TextHandler.UnifyTitles(jsonTrack.name.ToString());

                            if (foundTitle == modifiedTitle)
                            {
                                dynamic jsonAlbum = SimpleJson.DeserializeObject(jsonTrack["album"].ToString());
                                albumId = jsonAlbum.uri.ToString();

                                break;
                            }
                        }

                        if (!string.IsNullOrEmpty(albumId))
                        {
                            albumId = albumId.Substring(albumId.LastIndexOf(':') + 1);
                            this.DownloadSpotifyAlbumArtwork(albumId);
                        }
                    }
                }
            }
            catch (FileNotFoundException)
            {
                this.SaveBlankImage();
            }
        }
Пример #21
0
        private void ToggleGPMDP()
        {
            this.toolStripMenuItemSpotify.Checked    = false;
            this.toolStripMenuItemItunes.Checked     = false;
            this.toolStripMenuItemWinamp.Checked     = false;
            this.toolStripMenuItemFoobar2000.Checked = false;
            this.toolStripMenuItemVlc.Checked        = false;
            this.toolStripMenuItemGPMDP.Checked      = true;
            this.toolStripMenuItemQuodLibet.Checked  = false;

            Globals.CurrentPlayer.Unload();
            Globals.CurrentPlayer = new GPMDP();
            Globals.CurrentPlayer.Load();

            Globals.PlayerSelection = Globals.MediaPlayerSelection.GPMDP;
            TextHandler.UpdateTextAndEmptyFilesMaybe(
                string.Format(
                    CultureInfo.InvariantCulture,
                    LocalizedMessages.SwitchedToPlayer,
                    LocalizedMessages.GPMDP));
        }
Пример #22
0
        private void ToggleQuodLibet()
        {
            this.toolStripMenuItemSpotify.Checked    = false;
            this.toolStripMenuItemItunes.Checked     = false;
            this.toolStripMenuItemWinamp.Checked     = false;
            this.toolStripMenuItemFoobar2000.Checked = false;
            this.toolStripMenuItemVlc.Checked        = false;
            this.toolStripMenuItemGPMDP.Checked      = false;
            this.toolStripMenuItemQuodLibet.Checked  = true;

            Globals.CurrentPlayer.Unload();
            Globals.CurrentPlayer = new QuodLibet();
            Globals.CurrentPlayer.Load();

            Globals.PlayerSelection = Globals.MediaPlayerSelection.QuodLibet;
            TextHandler.UpdateTextAndEmptyFilesMaybe(
                string.Format(
                    CultureInfo.InvariantCulture,
                    Globals.ResourceManager.GetString("SwitchedToPlayer"),
                    Globals.ResourceManager.GetString("QuodLibet")));
        }
Пример #23
0
        private void DownloadJson(string spotifyTitle)
        {
            // Prevent redownloading JSON if it's already attempting to
            if (!this.downloadingJson)
            {
                this.downloadingJson = true;

                using (WebClient jsonWebClient = new WebClient())
                {
                    try
                    {
                        // There are certain characters that can cause issues with Spotify's search
                        spotifyTitle = TextHandler.UnifyTitles(spotifyTitle);

                        jsonWebClient.Encoding = System.Text.Encoding.UTF8;

                        jsonWebClient.Headers.Add(string.Format("Authorization: Bearer {0}", this.token));

                        var downloadedJson = jsonWebClient.DownloadString(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "https://api.spotify.com/v1/search?q={0}&type=track",
                                HttpUtility.UrlEncode(spotifyTitle)));

                        if (!string.IsNullOrEmpty(downloadedJson))
                        {
                            this.json = downloadedJson;
                        }
                    }
                    catch (WebException)
                    {
                        this.json = string.Empty;
                        this.SaveBlankImage();
                    }
                }

                this.downloadingJson = false;
            }
        }
Пример #24
0
        private void ResetSnipSinceSpotifyIsNotRunning()
        {
            // Prevent writing a blank image if we already did
            if (!this.SavedBlankImage)
            {
                if (Globals.SaveAlbumArtwork)
                {
                    this.SaveBlankImage();
                }
            }

            this.Handle            = IntPtr.Zero;
            this.processId         = 0;
            this.moduleBaseAddress = 0;
            this.moduleLength      = 0;

            TextHandler.UpdateTextAndEmptyFilesMaybe(
                string.Format(
                    CultureInfo.InvariantCulture,
                    LocalizedMessages.PlayerIsNotRunning,
                    LocalizedMessages.Spotify));
        }
Пример #25
0
        private void ResetSnipSinceSpotifyIsNotRunning()
        {
            if (this.spotifyWindowFound)
            {
                this.spotifyWindowFound = false;
            }

            // Prevent writing a blank image if we already did
            if (!this.SavedBlankImage)
            {
                if (Globals.SaveAlbumArtwork)
                {
                    this.SaveBlankImage();
                }
            }

            TextHandler.UpdateTextAndEmptyFilesMaybe(
                string.Format(
                    CultureInfo.InvariantCulture,
                    LocalizedMessages.PlayerIsNotRunning,
                    LocalizedMessages.Spotify));
        }
Пример #26
0
        public override void Update()
        {
            if (!this.Found)
            {
                this.Handle = UnsafeNativeMethods.FindWindow("SpotifyMainWindow", null);

                this.Found      = true;
                this.NotRunning = false;
            }
            else
            {
                // Make sure the process is still valid.
                if (this.Handle != IntPtr.Zero && this.Handle != null)
                {
                    int windowTextLength = UnsafeNativeMethods.GetWindowText(this.Handle, this.Title, this.Title.Capacity);

                    string spotifyTitle = this.Title.ToString();

                    this.Title.Clear();

                    // If the window title length is 0 then the process handle is not valid.
                    if (windowTextLength > 0)
                    {
                        // Only update if the title has actually changed.
                        // This prevents unnecessary calls and downloads.
                        if (spotifyTitle != this.LastTitle)
                        {
                            if (spotifyTitle == "Spotify")
                            {
                                if (Globals.SaveAlbumArtwork)
                                {
                                    this.SaveBlankImage();
                                }

                                TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("NoTrackPlaying"));
                            }
                            else
                            {
                                this.DownloadJson(spotifyTitle);

                                dynamic jsonSummary = SimpleJson.DeserializeObject(this.json);

                                if (jsonSummary != null)
                                {
                                    var numberOfResults = jsonSummary.tracks.total;

                                    if (numberOfResults > 0)
                                    {
                                        jsonSummary = SimpleJson.DeserializeObject(jsonSummary.tracks["items"].ToString());

                                        TextHandler.UpdateText(
                                            jsonSummary[0].name.ToString(),
                                            jsonSummary[0].artists[0].name.ToString(),
                                            jsonSummary[0].album.name.ToString());

                                        if (Globals.SaveAlbumArtwork)
                                        {
                                            this.HandleSpotifyAlbumArtwork(jsonSummary[0].name.ToString());
                                        }
                                    }
                                    else
                                    {
                                        // In the event of an advertisement (or any song that returns 0 results)
                                        // then we'll just write the whole title as a single string instead.
                                        TextHandler.UpdateText(spotifyTitle);
                                    }
                                }
                            }

                            this.LastTitle = spotifyTitle;
                        }
                    }
                    else
                    {
                        if (!this.NotRunning)
                        {
                            this.ResetSinceSpotifyIsNotRunning();
                        }
                    }
                }
                else
                {
                    if (!this.NotRunning)
                    {
                        this.ResetSinceSpotifyIsNotRunning();
                    }
                }
            }
        }
Пример #27
0
        private void UpdateSpotifyTrackInformation_Elapsed(object sender, ElapsedEventArgs e)
        {
            // Get a list of all spotify.exe processes
            Process[] processes = Process.GetProcessesByName("spotify");

            // Array must be greater than 0 to continue (as in a process was successfully found)
            if (processes.Length > 0)
            {
                // We know Spotify is running at least
                this.spotifyRunning = true;

                // Only loop through and get the process handle if it's not set
                if (this.spotifyHandle == IntPtr.Zero)
                {
                    // Loop through all processes that matched spotify.exe
                    foreach (Process localSpotifyProcess in processes)
                    {
                        StringBuilder className = new StringBuilder(64);

                        UnsafeNativeMethods.GetClassName(localSpotifyProcess.MainWindowHandle, className, className.Capacity);

                        string classNameText = className.ToString();

                        // Spotify's main window that has the song name in the titlebar uses the Chrome_WidgetWin_0 class
                        // We also need to verify that the titlebar has something in it due to multiple processes sharing the same class
                        // From everything I've seen the titlebar will _always_ have at least some text
                        if (classNameText == "Chrome_WidgetWin_0" && localSpotifyProcess.MainWindowTitle.Length > 0)
                        {
                            this.spotifyHandle = localSpotifyProcess.MainWindowHandle;
                        }
                    }
                }
            }
            else
            {
                this.ResetSnipSinceSpotifyIsNotPlaying();
            }

            if (this.spotifyRunning == true && this.spotifyHandle != IntPtr.Zero)
            {
                // We'll limit the window title string to 256 characters
                // The length really doesn't matter since we're just storing what appears and comparing it
                // Even if it gets cut off it should compare well up to 256 characters
                StringBuilder stringBuilder = new StringBuilder(256);

                // Get the window title of Spotify and store it in stringBuilder
                UnsafeNativeMethods.GetWindowText(this.spotifyHandle, stringBuilder, stringBuilder.Capacity);

                // Convert the StringBuilder to a regular string
                string spotifyTitle = stringBuilder.ToString();

                if (spotifyTitle.Length > 0)
                {
                    if (spotifyTitle != this.LastTitle || Globals.RewriteUpdatedOutputFormat)
                    {
                        Globals.RewriteUpdatedOutputFormat = false;

                        if (spotifyTitle == "Spotify" || spotifyTitle == "Spotify Free" || spotifyTitle == "Spotify Premium")
                        {
                            if (Globals.SaveAlbumArtwork)
                            {
                                this.SaveBlankImage();
                            }

                            TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("NoTrackPlaying"));
                        }
                        else
                        {
                            string downloadedJson = this.DownloadJson("https://api.spotify.com/v1/me/player/currently-playing", SpotifyAddressContactType.API);

                            if (!string.IsNullOrEmpty(downloadedJson))
                            {
                                dynamic jsonSummary = SimpleJson.DeserializeObject(downloadedJson);

                                string currentlyPlayingType = (string)jsonSummary.currently_playing_type;

                                // Spotify does not provide any detailed information for anything other than actual songs.
                                // Podcasts have types of "episode" but do not contain any useful data unfortunately.
                                if (currentlyPlayingType == "track")
                                {
                                    bool   isPlaying = (bool)jsonSummary.is_playing;
                                    string trackId   = (string)jsonSummary.item.id;

                                    if (isPlaying)
                                    {
                                        if (Globals.CacheSpotifyMetadata)
                                        {
                                            downloadedJson = this.ReadCachedJson(trackId);
                                        }

                                        // If there are multiple artists we want to join all of them together for display
                                        string artists = string.Empty;

                                        foreach (dynamic artist in jsonSummary.item.artists)
                                        {
                                            artists += artist.name.ToString() + ", ";
                                        }

                                        artists = artists.Substring(0, artists.LastIndexOf(',')); // Removes last comma

                                        TextHandler.UpdateText(
                                            jsonSummary.item.name.ToString(),
                                            artists,
                                            jsonSummary.item.album.name.ToString(),
                                            trackId,
                                            downloadedJson);

                                        if (Globals.SaveAlbumArtwork)
                                        {
                                            this.DownloadSpotifyAlbumArtwork(jsonSummary.item.album);
                                        }
                                    }
                                    else
                                    {
                                        this.ResetSnipSinceSpotifyIsNotPlaying();
                                    }
                                }
                                else
                                {
                                    this.ResetSnipSinceSpotifyIsNotPlaying();
                                }

                                // Reset timer after it was potentially changed by rate limit
                                // Since we should only reach this point if valid JSON was obtained this means
                                // that the timer shouldn't reset unless there was a success.
                                this.updateSpotifyTrackInformation.Enabled  = false;
                                this.updateSpotifyTrackInformation.Interval = updateSpotifyTrackInformationDefaultInterval;
                                this.updateSpotifyTrackInformation.Enabled  = true;
                            }
                        }

                        this.LastTitle = spotifyTitle;
                    }
                }
            }
        }
Пример #28
0
        public override void Update()
        {
            if (!this.Found)
            {
                System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("foobar2000");

                if (processes.Length > 0)
                {
                    this.Handle = processes[0].MainWindowHandle;
                }

                foreach (var process in processes)
                {
                    process.Dispose();
                }

                processes = null;

                this.Found      = true;
                this.NotRunning = false;
            }
            else
            {
                // Make sure the process is still valid.
                if (this.Handle != IntPtr.Zero && this.Handle != null)
                {
                    int windowTextLength = UnsafeNativeMethods.GetWindowText(this.Handle, this.Title, this.Title.Capacity);

                    string foobar2000Title = this.Title.ToString();

                    this.Title.Clear();

                    // If the window title length is 0 then the process handle is not valid.
                    if (windowTextLength > 0)
                    {
                        // Only update the system tray text and text file text if the title changes.
                        if (foobar2000Title != this.LastTitle || Globals.RewriteUpdatedOutputFormat)
                        {
                            Globals.RewriteUpdatedOutputFormat = false;

                            if (foobar2000Title.StartsWith("foobar2000", StringComparison.OrdinalIgnoreCase))
                            {
                                TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("NoTrackPlaying"));
                            }
                            else
                            {
                                // Winamp window titles look like "[%album artist% - ]['['%album%[ CD%discnumber%][ #%tracknumber%]']' ]%title%[ '//' %track artist%]".
                                // Require that the user use ATF and replace the format with something like:
                                // %artist% – %title%
                                string   windowTitleFull = System.Text.RegularExpressions.Regex.Replace(foobar2000Title, @"\s+\[foobar2000.+\]", string.Empty);
                                string[] windowTitle     = windowTitleFull.Split('–');

                                // Album artwork not supported by foobar2000
                                if (Globals.SaveAlbumArtwork)
                                {
                                    this.SaveBlankImage();
                                }

                                if (windowTitle.Length > 1)
                                {
                                    string artist    = windowTitle[0].Trim();
                                    string songTitle = windowTitle[1].Trim();

                                    TextHandler.UpdateText(songTitle, artist);
                                }
                                else
                                {
                                    TextHandler.UpdateText(windowTitle[0].Trim());
                                }
                            }

                            this.LastTitle = foobar2000Title;
                        }
                    }
                    else
                    {
                        if (!this.NotRunning)
                        {
                            if (Globals.SaveAlbumArtwork)
                            {
                                this.SaveBlankImage();
                            }

                            TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("foobar2000IsNotRunning"));

                            this.Found      = false;
                            this.NotRunning = true;
                        }
                    }
                }
                else
                {
                    if (!this.NotRunning)
                    {
                        if (Globals.SaveAlbumArtwork)
                        {
                            this.SaveBlankImage();
                        }

                        TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("foobar2000IsNotRunning"));

                        this.Found      = false;
                        this.NotRunning = true;
                    }
                }
            }
        }
Пример #29
0
        public override void Update()
        {
            if (!this.Found)
            {
                this.Handle = UnsafeNativeMethods.FindWindow("Winamp v1.x", null);

                this.Found      = true;
                this.NotRunning = false;
            }
            else
            {
                // Make sure the process is still valid.
                if (this.Handle != IntPtr.Zero && this.Handle != null)
                {
                    int windowTextLength = UnsafeNativeMethods.GetWindowText(this.Handle, this.Title, this.Title.Capacity);

                    string winampTitle = this.Title.ToString();

                    this.Title.Clear();

                    // If the window title length is 0 then the process handle is not valid.
                    if (windowTextLength > 0)
                    {
                        // Only update the system tray text and text file text if the title changes.
                        if (winampTitle != this.LastTitle || Globals.RewriteUpdatedOutputFormat)
                        {
                            Globals.RewriteUpdatedOutputFormat = false;

                            if (winampTitle.Contains("- Winamp [Stopped]") || winampTitle.Contains("- Winamp [Paused]"))
                            {
                                TextHandler.UpdateTextAndEmptyFilesMaybe(Globals.ResourceManager.GetString("NoTrackPlaying"));
                            }
                            else
                            {
                                // Winamp window titles look like "#. Artist - Track - Winamp".
                                // Require that the user use ATF and replace the format with something like:
                                // %artist% – %title%
                                string   windowTitleFull = winampTitle.Replace("- Winamp", string.Empty);
                                string[] windowTitle     = windowTitleFull.Split('–');

                                // Album artwork not supported by Winamp
                                if (Globals.SaveAlbumArtwork)
                                {
                                    this.SaveBlankImage();
                                }

                                if (windowTitle.Length > 1)
                                {
                                    string artist    = windowTitle[0].Trim();
                                    string songTitle = windowTitle[1].Trim();

                                    TextHandler.UpdateText(songTitle, artist);
                                }
                                else
                                {
                                    TextHandler.UpdateText(windowTitle[0].Trim());
                                }
                            }

                            this.LastTitle = winampTitle;
                        }
                    }
                    else
                    {
                        if (!this.NotRunning)
                        {
                            if (Globals.SaveAlbumArtwork)
                            {
                                this.SaveBlankImage();
                            }

                            TextHandler.UpdateTextAndEmptyFilesMaybe(
                                string.Format(
                                    CultureInfo.InvariantCulture,
                                    Globals.ResourceManager.GetString("PlayerIsNotRunning"),
                                    Globals.ResourceManager.GetString("Winamp")));

                            this.Found      = false;
                            this.NotRunning = true;
                        }
                    }
                }
                else
                {
                    if (!this.NotRunning)
                    {
                        if (Globals.SaveAlbumArtwork)
                        {
                            this.SaveBlankImage();
                        }

                        TextHandler.UpdateTextAndEmptyFilesMaybe(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                Globals.ResourceManager.GetString("PlayerIsNotRunning"),
                                Globals.ResourceManager.GetString("Winamp")));

                        this.Found      = false;
                        this.NotRunning = true;
                    }
                }
            }
        }
Пример #30
0
        private void ContactSpotifyLocalServerTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            string trackInformation = this.GetTrackInformation();

            // We should only be here if Spotify actually is running
            if (!string.IsNullOrEmpty(trackInformation))
            {
                // Get the handle so that hotkeys can be used
                this.GetSpotifyWindowHandle();

                dynamic jsonSummary = SimpleJson.DeserializeObject(trackInformation);

                if (jsonSummary != null)
                {
                    bool spotifyPlaying = Convert.ToBoolean(jsonSummary.playing);

                    if (!spotifyPlaying)
                    {
                        this.ResetSnipSinceSpotifyIsNotPlaying();
                    }
                    else
                    {
                        string fullTrackId = jsonSummary.track.track_resource.uri.ToString();
                        string trackId     = fullTrackId.Substring(fullTrackId.LastIndexOf(':') + 1); // + 1 to not include :

                        // Only update if the title has changed or the user updates how the output format should look
                        if (trackId != this.LastTitle || Globals.RewriteUpdatedOutputFormat)
                        {
                            Globals.RewriteUpdatedOutputFormat = false;

                            string json = string.Empty;

                            if (Globals.CacheSpotifyMetadata)
                            {
                                json = this.ReadCachedJson(trackId);
                            }
                            else
                            {
                                json = this.DownloadJson(
                                    string.Format(
                                        CultureInfo.InvariantCulture,
                                        "https://api.spotify.com/v1/tracks/{0}",
                                        trackId),
                                    SpotifyAddressContactType.API);
                            }

                            jsonSummary = SimpleJson.DeserializeObject(json);

                            // If there are multiple artists we want to join all of them together for display
                            string artists = string.Empty;

                            foreach (dynamic artist in jsonSummary.artists)
                            {
                                artists += artist.name.ToString() + ", ";
                            }

                            artists = artists.Substring(0, artists.LastIndexOf(',')); // Removes last comma

                            TextHandler.UpdateText(
                                jsonSummary.name.ToString(),
                                artists,
                                jsonSummary.album.name.ToString(),
                                jsonSummary.id.ToString());

                            if (Globals.SaveAlbumArtwork)
                            {
                                this.DownloadSpotifyAlbumArtwork(jsonSummary.album);
                            }

                            // Set the last title to the track id as these are unique values that only change when the track changes
                            this.LastTitle = trackId;

                            this.snipReset = false;
                        }
                    }
                }
            }
        }