public static void PreviousSong()
 {
     SpotifyLocalAPI _spotify = new SpotifyLocalAPI();
     if (!_spotify.Connect())
     {
         return;
     }
     _spotify.Previous();
     _spotify = null;
 }
 public static void NextSong()
 {
     SpotifyLocalAPI _spotify = new SpotifyLocalAPI();
     if (!_spotify.Connect())
     {
         return;
     }
     _spotify.Skip();
     _spotify = null;
 }
        public void Execute(IJobExecutionContext context)
        {
            SpotifyModel sm = new SpotifyModel();
            _auth = new ImplicitGrantAuth
            {
                RedirectUri = "http://localhost:8000",
                ClientId = "26d287105e31491889f3cd293d85bfea",
                Scope =
                    Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistReadPrivate | Scope.UserLibrarayRead |
                    Scope.UserReadPrivate | Scope.UserFollowRead | Scope.UserReadBirthdate,
                State = "XSS"
            };
            _auth.OnResponseReceivedEvent += _auth_OnResponseReceivedEvent;

            _auth.StartHttpServer(8000);
            _auth.DoAuth();

            _spotifyLocal = new SpotifyLocalAPI();

            if (!SpotifyLocalAPI.IsSpotifyRunning())
            {
                return;
            }
            if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning())
            {
                return;
            }

            bool successful = _spotifyLocal.Connect();
            if (successful)
            {
                UpdateInfos();
                SpotifyModel spotifyModel = new SpotifyModel();
                var dictDetails = GetDictionaryDetails(_currentTrack.TrackResource.Name).Keys.ToList();
                if (Winner)
                {
                    dictDetails.Sort();
                    var winner = dictDetails[0];
                    var temp = "";
                    if (_currentTrack.TrackType != "ad")
                    {
                        temp = _currentTrack.TrackResource.Name + " - " + _currentTrack.ArtistResource.Name;
                    }
                    while (!temp.Equals(winner))
                    {
                        _spotifyLocal.Skip();
                        UpdateInfos();
                        temp = _currentTrack.TrackResource.Name + " - " + _currentTrack.ArtistResource.Name;
                        Thread.Sleep(100);
                    }
                    Winner = false;
                    spotifyModel.Truncate();
                }
            }
        }
        private static async Task<SpotifyLocalAPI> ConnectToSpotify()
        {
            var spotify = new SpotifyLocalAPI();

            while (!SpotifyLocalAPI.IsSpotifyRunning())
            {
                await Task.Delay(1000);
            }

            bool successful = spotify.Connect();
            if (successful)
                Console.WriteLine("Connected to spottify");
            else
                throw new NotSupportedException("Cannot connect to spotify");

            return spotify;
        }
        public static void PlayPause()
        {
            SpotifyLocalAPI _spotify = new SpotifyLocalAPI();
            if (!_spotify.Connect())
            {
                return;
            }
            StatusResponse status = _spotify.GetStatus();
            if (status == null)
            {
                return;
            }

            if (status.Playing)
            {
                _spotify.Pause();
            }
            else
            {
                _spotify.Play();
            }

            _spotify = null;
        }
Exemple #6
0
    void work()
    {
        uint refreshrate = (uint)spinRefreshRate.Value;
        string tmp, currentsong = string.Empty;

        switch (currentWork) {
        case WorkType.VLC:
            #region VLC
            string hostname = txtVlcHostname.Text;
            uint port = (uint)spinVlcPort.Value;
            string password = txtVlcPassword.Text;
            VlcController conn;

            try
            {
                conn = new VlcController(hostname, port);
                conn.Authenticate(password);
                if (!conn.Authenticated)
                {
                    Application.Invoke(delegate{ SetStatus("Wrong password, please retry!");});
                    stop();
                }

                Application.Invoke(delegate{ SetStatus("VLC worker running");});

                while (true)
                {
                    tmp = conn.GetCurrentSongTitle();
                    if(tmp!= currentsong)
                    {
                        currentsong = tmp;
                        File.WriteAllText(filepath, tmp);
                    }
                    Thread.Sleep ((int)refreshrate);
                }
            }
            catch(SocketException ex)
            {
                Application.Invoke(delegate{ SetStatus("Can't connect to the VLC server / Connection aborted by the server");});
                stop();
            }

            break;
            #endregion
        case WorkType.Spotify:
            #region Spotify
            spotify = new SpotifyLocalAPI();

            if (!SpotifyLocalAPI.IsSpotifyRunning())
            {
                Application.Invoke(delegate{ SetStatus("Spotify isn't running!");});
                stop();
            }
            else if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning())
            {
                Application.Invoke(delegate{ SetStatus("SpotifyWebHelper isn't running!");});
                stop();
            }
            else if (!spotify.Connect())
            {
                Application.Invoke(delegate{ SetStatus("Can't connect to the SpotifyWebHelper.");});
                stop();
            }

            Application.Invoke(delegate{ SetStatus("Spotify worker running");});

            while (true)
            {
                StatusResponse status =  spotify.GetStatus();
                if(status != null && status.Track != null)
                {
                    tmp = status.Track.TrackResource.Uri;

                    if(tmp != currentsong)
                    {
                        string format, formatted;

                        currentsong = tmp;

                        format = txtSpotifyFormat.Text;
                        format = format.Replace("%t", FormatterCodes.Title);
                        format = format.Replace("%a", FormatterCodes.Artist);
                        format = format.Replace("%A", FormatterCodes.Album);

                        formatted = format.Replace(FormatterCodes.Title, status.Track.TrackResource.Name);
                        formatted = formatted.Replace(FormatterCodes.Artist, status.Track.ArtistResource.Name);
                        formatted = formatted.Replace(FormatterCodes.Album, status.Track.AlbumResource.Name);

                        File.WriteAllText(filepath, formatted);
                    }
                }

                Thread.Sleep ((int)refreshrate);
            }
            #endregion
        default:
            Application.Invoke (delegate {SetStatus ("Error: Invalid work selected");});
            stop ();
            break;
        }
    }
 static SpotifyController()
 {
     Spotify = new SpotifyLocalAPI();
     Spotify.Connect();
 }
Exemple #8
0
        public bool SpotifyConnect(bool prompt)
        {
            if (prompt)
            {
                overrideAutoSpot = true;
            }

            spotify = new SpotifyLocalAPI();
            spotify.OnTrackChange += Spotify_OnTrackChange;
            spotify.OnPlayStateChange += Spotify_OnPlayStateChange;
            spotify.ListenForEvents = true;

            if (!SpotifyLocalAPI.IsSpotifyRunning())
            {
                if (prompt)
                {
                    MessageBox.Show(@"Spotify isn't running!");
                }

                return false;
            }
            if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning())
            {
                if (prompt)
                {
                    MessageBox.Show(@"SpotifyWebHelper isn't running!");
                }
                return false;
            }

            bool successful = spotify.Connect();
            if (!successful)
            {
                // Reset connection first
                SpotifyDisconnect();

                if (prompt)
                {
                    DialogResult res = MessageBox.Show(@"Couldn't connect to the spotify client. Retry?", @"Spotify", MessageBoxButtons.YesNo);
                    if (res == DialogResult.Yes)
                        SpotifyConnect(true);
                }
            }

            SpotifyConnected = successful;
            return successful;
        }
Exemple #9
0
        public frmMain()
        {
            InitializeComponent();

            int previousId = 0;     // The id of the hotkey.
            RegisterHotKey(this.Handle, previousId, (int)KeyModifier.Alt, Keys.Left.GetHashCode());
            int playstateId = 1;     // The id of the hotkey.
            RegisterHotKey(this.Handle, playstateId, (int)KeyModifier.Alt, Keys.Space.GetHashCode());
            int skipId = 2;     // The id of the hotkey.
            RegisterHotKey(this.Handle, skipId, (int)KeyModifier.Alt, Keys.Right.GetHashCode());
            int hideId = 3;     // The id of the hotkey.
            RegisterHotKey(this.Handle, hideId, (int)KeyModifier.Alt, Keys.Down.GetHashCode());
            int showId = 4;     // The id of the hotkey.
            RegisterHotKey(this.Handle, showId, (int)KeyModifier.Alt, Keys.Up.GetHashCode());
            int muteId = 5;     // The id of the hotkey.
            RegisterHotKey(this.Handle, muteId, (int)KeyModifier.Alt, Keys.M.GetHashCode());

            localSpotify = new SpotifyLocalAPI();
            localSpotify.OnPlayStateChange += spotify_OnPlayStateChange;
            localSpotify.OnTrackChange += spotify_OnTrackChange;
            localSpotify.OnTrackTimeChange += spotify_OnTrackTimeChange;
            localSpotify.OnVolumeChange += spotify_OnVolumeChange;
            localSpotify.SynchronizingObject = this;
            localSpotify.ListenForEvents = true;

            btnPlayPause.FlatAppearance.MouseOverBackColor = btnPlayPause.BackColor;
            btnPlayPause.BackColorChanged += (s, e) => {
                btnPlayPause.FlatAppearance.MouseOverBackColor = btnPlayPause.BackColor;
            };
            btnNext.FlatAppearance.MouseOverBackColor = btnNext.BackColor;
            btnNext.BackColorChanged += (s, e) => {
                btnNext.FlatAppearance.MouseOverBackColor = btnNext.BackColor;
            };
            btnPrevious.FlatAppearance.MouseOverBackColor = btnPrevious.BackColor;
            btnPrevious.BackColorChanged += (s, e) => {
                btnPrevious.FlatAppearance.MouseOverBackColor = btnPrevious.BackColor;
            };

            btnPlayPause.FlatAppearance.MouseDownBackColor = btnPlayPause.BackColor;
            btnPrevious.BackColorChanged += (s, e) => {
                btnPrevious.FlatAppearance.MouseDownBackColor = btnPrevious.BackColor;
            };
            btnNext.FlatAppearance.MouseDownBackColor = btnNext.BackColor;
            btnNext.BackColorChanged += (s, e) => {
                btnNext.FlatAppearance.MouseDownBackColor = btnNext.BackColor;
            };
            btnPrevious.FlatAppearance.MouseDownBackColor = btnPrevious.BackColor;
            btnPrevious.BackColorChanged += (s, e) => {
                btnPrevious.FlatAppearance.MouseDownBackColor = btnPrevious.BackColor;
            };

            if (!SpotifyLocalAPI.IsSpotifyRunning())
            {
                SpotifyLocalAPI.RunSpotify();
                Thread.Sleep(5000);
            }

            if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning())
            {
                SpotifyLocalAPI.RunSpotifyWebHelper();
                Thread.Sleep(4000);
            }

            if (!localSpotify.Connect())
            {
                Boolean retry = true;
                while (retry)
                {
                    DialogResult result = MessageBox.Show("SpotifyLocalApiClass couldn't load!\nYou like to Retry?", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                    if (result == DialogResult.Retry)
                    {
                        if (localSpotify.Connect())
                            retry = false;
                        else
                            retry = true;
                    }
                    else
                    {
                        this.Close();
                        return;
                    }
                }
            }
        }
        public void Start()
        {
            if (!api.IsSpotifyRunning())
            {
                DialogResult q = MessageBox.Show("Spotify is not running! Would you like to start it now?", "Spotify not running!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (q == DialogResult.Yes)
                {
                    api.RunSpotify();
                    if (!api.IsSpotifyWebHelperRunning())
                        api.RunSpotifyWebHelper();

                }
                else if (q == DialogResult.No)
                {
                    Environment.Exit(0);
                }
            }

            _spotify = new api();

            _spotify.Connect();

            _spotify.OnTrackChange += new api.TrackChangeEventHandler(onTrackChange);
            _spotify.ListenForEvents = true;

            _currentTrack = _spotify.GetStatus().Track;

            WriteWithColor("+---------------------------+\n| ######################### |\n| ###### Spotify? ######### |\n| ######### Shut up! ###### |\n| ######################### |\n+---------------------------+", ConsoleColor.Gray);
            WriteWithColor("  Created by iUltimateLP @ GitHub [Compiled 10/28/15]", ConsoleColor.Gray);
            WriteWithColor("\nType 'help' for help.", ConsoleColor.Gray);

            checkAdStateTimer = new System.Timers.Timer();
            checkAdStateTimer.Interval = 500;
            checkAdStateTimer.Elapsed += new System.Timers.ElapsedEventHandler(CheckAdStateTimer_Elapsed);
            checkAdStateTimer.Enabled = true;

            KeepConsoleRunning();
        }
 public JsonResult VoteSkip(string SongRecommendation, string SongThatWasPlaying)
 {
     _spotifyLocal = new SpotifyLocalAPI();
     bool successful = _spotifyLocal.Connect();
     string ip = Request.UserHostAddress;
     SpotifyModel spotifyModel = new SpotifyModel();
     if (successful && spotifyModel.IsValidVote(ip))
     {
         spotifyModel.CreateVoteEntry(SongRecommendation, DateTime.Now, SongThatWasPlaying, ip);
     }
     return Json(true, JsonRequestBehavior.AllowGet);
 }
        public SpotifyModel GetSpotifyModel()
        {
            _auth = new ImplicitGrantAuth
            {
                RedirectUri = "http://localhost:8000",
                ClientId = "26d287105e31491889f3cd293d85bfea",
                Scope = Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistReadPrivate | Scope.UserLibrarayRead | Scope.UserReadPrivate | Scope.UserFollowRead | Scope.UserReadBirthdate,
                State = "XSS"
            };
            _auth.OnResponseReceivedEvent += _auth_OnResponseReceivedEvent;

            _auth.StartHttpServer(8000);
            _auth.DoAuth();

            SpotifyModel sm = new SpotifyModel();
            _spotifyLocal = new SpotifyLocalAPI();

            if (!SpotifyLocalAPI.IsSpotifyRunning())
            {
                return sm;
            }
            if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning())
            {
                return sm;
            }

            bool successful = _spotifyLocal.Connect();
            if (successful)
            {
                UpdateInfos();
                _spotifyLocal.ListenForEvents = true;
                sm.IsPlaying = true;
                try
                {
                    sm.SongTitle = _currentTrack.TrackResource.Name;
                    sm.VotedItemsDictionary = GetDictionaryDetails(sm.SongTitle);
                    sm.SongArtist = _currentTrack.ArtistResource.Name;

                    Bitmap derp = new Bitmap(_currentTrack.GetAlbumArt(AlbumArtSize.Size320));
                    Byte[] imgFile;
                    var stream = new MemoryStream();
                    derp.Save(stream, ImageFormat.Png);
                    imgFile = stream.ToArray();
                    sm.SongAlbumArt = _currentTrack.GetAlbumArtUrl(AlbumArtSize.Size320);
                    sm.IsPlaying = true;
                    stream.Close();
                    sm.Tracks = GetPlaylists();
                    int index = 0;
                    foreach (var track in sm.Tracks)
                    {
                        if (track.title.Equals(_currentTrack.TrackResource.Name))
                        {
                            break;
                        }
                        index++;
                    }
                    if (index == 0)
                        index++;
                    sm.PreviousSongAlbumArt = sm.Tracks[index - 1].albumArt;
                    sm.PreviousSongTitle = sm.Tracks[index - 1].title;
                    sm.PreviousSongArtist = sm.Tracks[index - 1].artist;
                    if (index + 1 >= sm.Tracks.Count)
                        index = 0;
                    else
                        index++;
                    sm.NextSongAlbumArt = sm.Tracks[index].albumArt;
                    sm.NextSongTitle = sm.Tracks[index].title;
                    sm.NextSongArtist = sm.Tracks[index].artist;

                    _auth = null;
                    _spotifyLocal = null;
                    _spotify = null;
                }
                catch (Exception e)
                {
                }
            }

            if (Winner)
            {
                sm.Truncate();
                Winner = false;
            }

            string ip = Request.UserHostAddress;
            sm.IsValidIP = sm.IsValidVote(ip);
            return sm;
        }
        void InitializeComponent()
        {
            _trayIcon = new NotifyIcon
            {
                BalloonTipIcon = ToolTipIcon.Info,
                BalloonTipTitle = "Resume Spotify",
                Text = "Resume playback on Spotify",
                Icon = Resources.Play,
                Visible = true
            };

            _trayIconContextMenu = new ContextMenuStrip();

            _delayMenutItems = new[]
            {
                new ToolStripMenuItem
                {
                    Size = new Size(152, 22),
                    Text = "Resume after 5 minutes",
                    Tag = 1000 * 60 * 5,
                    Checked = true
                },
                new ToolStripMenuItem
                {
                    Size = new Size(152, 22),
                    Text = "Resume after 30 minutes",
                    Tag = 1000 * 60 * 30
                },
                new ToolStripMenuItem
                {
                    Size = new Size(152, 22),
                    Text = "Resume after 1 hour",
                    Tag = 1000 * 60 * 60
                },
                new ToolStripMenuItem
                {
                    Size = new Size(152, 22),
                    Text = "Resume after 2 hours",
                    Tag = 1000 * 60 * 60 * 2
                },
                new ToolStripMenuItem
                {
                    Size = new Size(152, 22),
                    Text = "Resume after 4 hours",
                    Tag = 1000 * 60 * 60 * 4
                }
            };
            foreach (var delayMenuItem in _delayMenutItems)
                delayMenuItem.Click += delayMenuItem_Click;

            _closeMenuItem = new ToolStripMenuItem
            {
                Size = new Size(152, 22),
                Text = "Exit",
                Image = Resources.Exit
            };
            _closeMenuItem.Click += closeMenuItem_Click;

            _resumeTimer = new System.Timers.Timer();
            _resumeTimer.Elapsed += resumeTimer_Elapsed;

            _trayIconContextMenu.SuspendLayout();
            _trayIconContextMenu.Items.AddRange(_delayMenutItems.Concat(new[] { _closeMenuItem }).Cast<ToolStripItem>().ToArray());
            _trayIconContextMenu.Size = new Size(153, 70);
            _trayIconContextMenu.ResumeLayout(false);

            _trayIcon.ContextMenuStrip = _trayIconContextMenu;

            _spotifyLocalApi = new SpotifyLocalAPI();
            _spotifyLocalApi.Connect();
            _spotifyLocalApi.ListenForEvents = true;
            _spotifyLocalApi.OnPlayStateChange += spotifyLocalAPI_OnPlayStateChange;

            _resumeTimer.Stop();
            _resumeTimer.Interval = (int)_delayMenutItems.Single(x => x.Checked).Tag;
            _resumeTimer.Start();
        }
        public bool TryConnect(SpotifyLocalAPI spotifyLocalApi)
        {
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    return spotifyLocalApi.Connect();
                }
                catch { ;} //try 5 times
            }

            MessageBox.Show("Spotfiy is closed or cannot connected", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            Stop();
            return false;
        }
        public void SetupSpotify()
        {
            if (_spotifySetupBusy)
                return;

            _spotifySetupBusy = true;
            _spotify = new SpotifyLocalAPI {ListenForEvents = true};
            _spotify.OnPlayStateChange += UpdateSpotifyPlayState;
            _spotify.OnTrackChange += UpdateSpotifyTrack;
            _spotify.OnTrackTimeChange += UpdateSpotifyTrackTime;

            // Connecting can sometimes use a little bit more conviction
            Task.Factory.StartNew(() =>
            {
                var tryCount = 0;
                while (tryCount <= 10)
                {
                    tryCount++;
                    var connected = _spotify.Connect();
                    if (connected)
                        break;
                    Thread.Sleep(1000);
                }
                _spotifySetupBusy = false;
            });
        }