コード例 #1
0
ファイル: Monitor.cs プロジェクト: ebt/doesnotwant
 public Monitor()
 {
     cSLlLocalAPI = new SpotifyLocalAPI();
     cSLlLocalAPI.OnPlayStateChange += CSLlLocalAPI_OnPlayStateChange;
     cSLlLocalAPI.OnTrackChange += CSLlLocalAPI_OnTrackChange;
     cMRERunning = new ManualResetEvent(false);
     cMREStop = new ManualResetEvent(false);
     cMREReady = new ManualResetEvent(true);
 }
コード例 #2
0
 public static void PreviousSong()
 {
     SpotifyLocalAPI _spotify = new SpotifyLocalAPI();
     if (!_spotify.Connect())
     {
         return;
     }
     _spotify.Previous();
     _spotify = null;
 }
コード例 #3
0
        public SpotifyService(ISettings settings)
        {
            this._settings = settings;

            if (SpotifyLocalAPI.IsSpotifyRunning() == false)
                SpotifyLocalAPI.RunSpotify();

            this._localApi = new SpotifyLocalAPI();
            this._localApi.Connect();
        }
コード例 #4
0
 public static void NextSong()
 {
     SpotifyLocalAPI _spotify = new SpotifyLocalAPI();
     if (!_spotify.Connect())
     {
         return;
     }
     _spotify.Skip();
     _spotify = null;
 }
コード例 #5
0
        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();
                }
            }
        }
コード例 #6
0
        public LocalControl()
        {
            InitializeComponent();

            _spotify = new SpotifyLocalAPI();
            _spotify.OnPlayStateChange += _spotify_OnPlayStateChange;
            _spotify.OnTrackChange += _spotify_OnTrackChange;
            _spotify.OnTrackTimeChange += _spotify_OnTrackTimeChange;
            _spotify.OnVolumeChange += _spotify_OnVolumeChange;
            _spotify.SynchronizingObject = this;

            artistLinkLabel.Click += (sender, args) => Process.Start(artistLinkLabel.Tag.ToString());
            albumLinkLabel.Click += (sender, args) => Process.Start(albumLinkLabel.Tag.ToString());
            titleLinkLabel.Click += (sender, args) => Process.Start(titleLinkLabel.Tag.ToString());
        }
コード例 #7
0
        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;
        }
コード例 #8
0
        internal async Task <string> QueryAsync(string request, bool oauth, bool cfid, int wait)
        {
            string parameters = "?&ref=&cors=&_=" + GetTimestamp();

            if (request.Contains("?"))
            {
                parameters = parameters.Substring(1);
            }

            if (oauth)
            {
                parameters += "&oauth=" + OauthKey;
            }
            if (cfid)
            {
                parameters += "&csrf=" + CfidKey;
            }

            if (wait != -1)
            {
                parameters += "&returnafter=" + wait;
                parameters += "&returnon=login%2Clogout%2Cplay%2Cpause%2Cerror%2Cap";
            }

            string address  = "http://" + Host + ":4380/" + request + parameters;
            string response = "";

            try
            {
                using (var wc = new ExtendedWebClient())
                {
                    if (SpotifyLocalAPI.IsSpotifyRunning())
                    {
                        response = "[ " + await wc.DownloadStringTaskAsync(new Uri(address)) + " ]";
                    }
                }
            }
            catch
            {
                return(string.Empty);
            }

            return(response);
        }
コード例 #9
0
        internal string Query(string request, bool oauth, bool cfid, int wait)
        {
            string parameters = "?&ref=&cors=&_=" + GetTimestamp();

            if (request.Contains("?"))
            {
                parameters = parameters.Substring(1);
            }

            if (oauth)
            {
                parameters += "&oauth=" + OauthKey;
            }
            if (cfid)
            {
                parameters += "&csrf=" + CfidKey;
            }

            if (wait != -1)
            {
                parameters += "&returnafter=" + wait;
                parameters += "&returnon=login%2Clogout%2Cplay%2Cpause%2Cerror%2Cap";
            }

            string address  = $"{_config.HostUrl}:{_config.Port}/{request}{parameters}";
            string response = "";

            try
            {
                using (var wc = new ExtendedWebClient())
                {
                    if (SpotifyLocalAPI.IsSpotifyRunning())
                    {
                        response = "[ " + wc.DownloadString(address) + " ]";
                    }
                }
            }
            catch
            {
                return(string.Empty);
            }

            return(response);
        }
コード例 #10
0
        public SpotifyApi(string pluginDir = null)
        {
            var pluginDirectory = pluginDir ?? Directory.GetCurrentDirectory();
            CacheFolder = Path.Combine(pluginDirectory, "Cache");

            // Create the cache folder, if it doesn't already exist
            if (!Directory.Exists(CacheFolder))
                Directory.CreateDirectory(CacheFolder);

            _localSpotify = new SpotifyLocalAPI();
            _localSpotify.OnTrackChange += (o, e) => CurrentTrack = e.NewTrack;
            _localSpotify.OnPlayStateChange += (o, e) => IsPlaying = e.Playing;
            ConnectToSpotify();

            _spotifyApi = new SpotifyWebAPI
            {
                UseAuth = false
            };
        }
コード例 #11
0
        internal async Task <string> QueryAsync(string baseUrl, bool oauth, bool cfid, int wait, NameValueCollection @params = null)
        {
            string parameters = BuildQueryString(oauth, cfid, wait, @params);
            string address    = $"{_config.HostUrl}:{_config.Port}/{baseUrl}?{parameters}";
            string response   = "";

            try
            {
                using (ExtendedWebClient wc = new ExtendedWebClient())
                {
                    if (SpotifyLocalAPI.IsSpotifyRunning())
                    {
                        response = "[ " + await wc.DownloadStringTaskAsync(new Uri(address)).ConfigureAwait(false) + " ]";
                    }
                }
            }
            catch
            {
                return(string.Empty);
            }

            return(response);
        }
コード例 #12
0
        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;
        }
コード例 #13
0
        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;
            });
        }
コード例 #14
0
 static SpotifyController()
 {
     Spotify = new SpotifyLocalAPI();
     Spotify.Connect();
 }
コード例 #15
0
ファイル: Form1.cs プロジェクト: picolino0/CRUtils
 public void SpotifyDisconnect()
 {
     spotify.OnTrackChange -= Spotify_OnTrackChange;
     spotify.OnPlayStateChange -= Spotify_OnPlayStateChange;
     spotify = null;
     SpotifyConnected = false;
     overrideAutoSpot = true;
 }
コード例 #16
0
ファイル: Form1.cs プロジェクト: picolino0/CRUtils
        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;
        }
コード例 #17
0
        private async void ClientListener(string clientKey, CancellationToken token)
        {
            var spotify = new SpotifyLocalAPI();
            var redisClient = new RedisClient(clientKey);
            if (!TryConnect(spotify))
            {
                return;
            }

            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    redisClient.Delete($"Connected:{CurrentInstance}");
                    return;
                }

                var status = spotify.GetStatus();
                var track = redisClient.Get<string>("TrackChange");
                if (status.Track.TrackResource.Uri != track)
                {
                    spotify.PlayURL(track);
                }

                var state = redisClient.GetBoolean("PlayStateChange");
                if (status.Playing != state)
                {
                    if (state != null && state == true)
                    {
                        spotify.Play();
                    }
                    else if (state != null)
                    {
                        spotify.Pause();
                    }
                }

                UpdateUsers(redisClient);
                await Task.Delay(WaitMillisecondsDelay);
            }
        }
コード例 #18
0
 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);
 }
コード例 #19
0
ファイル: SnapSpotify.cs プロジェクト: WinSnap/SnapCore
 public override void Initialize()
 {
     _spotify = new SpotifyLocalAPI();
     _spotify.OnPlayStateChange += SpotifyOnOnPlayStateChange;
     _spotify.OnTrackChange += SpotifyOnOnTrackChange;
 }
コード例 #20
0
        private async void ServerListener(string clientKey, CancellationToken token)
        {
            var redisClient = new RedisClient(clientKey);
            var spotify = new SpotifyLocalAPI();
            if (!TryConnect(spotify))
            {
                return;
            }

            var serverInfo = redisClient.Get<UserInfo>("ServerInstance");
            var hasOldInstance = serverInfo != null;
            var oldInstanceNotTimedOut = serverInfo?.Connected > DateTime.UtcNow.AddSeconds(-30);
            var isNotCurrentInstance = serverInfo?.Instance != CurrentInstance;
            if ( hasOldInstance && oldInstanceNotTimedOut && isNotCurrentInstance)
            {
                MessageBox.Show($"Already have a server for {clientKey}\n\nUncheck is server checkbox and try again.", caption: "Warning", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Warning);
                Stop();
                return;
            }

            spotify.ListenForEvents = true;

            spotify.OnTrackChange += args =>
            {
                redisClient.Set("TrackChange", args.NewTrack.TrackResource.Uri);
            };

            spotify.OnPlayStateChange += args =>
            {
                redisClient.Set("PlayStateChange", args.Playing);
            };

            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    redisClient.Delete($"Connected:{CurrentInstance}");
                    return;
                }

                UpdateUsers(redisClient);
                await Task.Delay(WaitMillisecondsDelay);
            }
        }
コード例 #21
0
        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;
        }
コード例 #22
0
 private void ConfigureEvents(SpotifyLocalAPI spotify)
 {
     spotify.OnTrackChange += Spotify_OnTrackChange;
     spotify.ListenForEvents = true;
 }
コード例 #23
0
 // from displaying both "upcoming" and "current" song stats
 public SpotifyControl()
 {
     _spotify = new SpotifyLocalAPI();
     _spotify.OnPlayStateChange += spotify_OnPlayStateChange;
     _spotify.OnTrackChange += spotify_OnTrackChange;
 }
コード例 #24
0
        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();
        }
コード例 #25
0
ファイル: YAWIP.cs プロジェクト: lyserbin/YAWIP
    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;
        }
    }
コード例 #26
0
        private async void init()
        {
            _spotifyLocal = new SpotifyLocalAPI();


            connectLocal();
            //connectWeb();

        }
コード例 #27
0
        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();
        }
コード例 #28
0
ファイル: frmMain.cs プロジェクト: lftkv/spoti
        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;
                    }
                }
            }
        }
コード例 #29
0
        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;
        }