private bool SpotifyConnect() { if (!SpotifyLocalAPI.IsSpotifyRunning()) { return(false); } if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { return(false); } bool successful; try { successful = _spotify.Connect(); } catch (Exception) { return(false); } if (!successful) { return(false); } _spotify.ListenForEvents = true; return(true); }
internal void UpdateStatus() { StatusResponse status; var nowPlayingTrack = new TrackModel(); var attemptsLeft = 3; while (attemptsLeft-- > 0) { try { status = _sApi.GetStatus(); nowPlayingTrack.SongTitle = status.Track.TrackResource.Name; nowPlayingTrack.ArtistName = status.Track.ArtistResource.Name; nowPlayingTrack.AlbumTitle = status.Track.AlbumResource.Name; nowPlayingTrack.AlbumArt = GetAlbumArtImage(status.Track); break; } catch (NullReferenceException) { if (ConnectToLocalSpotifyClient()) { continue; } else { ReportStateChange(true, SpotifyLocalAPI.IsSpotifyRunning() ? $"Error: { _errorStatusText }" : "Spotify is not running"); break; } } } _nowPlayingTrack = nowPlayingTrack; }
public MainForm() { InitializeComponent(); //Query.ConnectQueryAsync(); config = new SpotifyLocalAPIConfig { ProxyConfig = new ProxyConfig() }; spotify = new SpotifyLocalAPI(config); Task.Run(() => WebApi.RunAuthentication()); //Creates files needed SetFileLocation(false); CreatePlaylistFile(); //Sets the listners spotify.OnTrackTimeChange += OnTrackTimeChange; spotify.OnTrackChange += OnTrackChange; spotify.OnPlayStateChange += OnStateChange; Playlist.CreateBackgroundPlaylist(); UpdateSongInfo(); }
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; }); }
private void UpdateSpotify(GeneralProfileDataModel dataModel) { // Spotify if (!dataModel.Spotify.Running && SpotifyLocalAPI.IsSpotifyRunning()) { SetupSpotify(); } var status = _spotify.GetStatus(); if (status == null) { return; } dataModel.Spotify.Playing = status.Playing; dataModel.Spotify.Running = SpotifyLocalAPI.IsSpotifyRunning(); if (status.Track != null) { dataModel.Spotify.Artist = status.Track.ArtistResource?.Name; dataModel.Spotify.SongName = status.Track.TrackResource?.Name; dataModel.Spotify.Album = status.Track.AlbumResource?.Name; dataModel.Spotify.SongLength = status.Track.Length; } if (dataModel.Spotify.SongLength > 0) { dataModel.Spotify.SongPercentCompleted = (int)(status.PlayingPosition / dataModel.Spotify.SongLength * 100.0); } }
private bool ConnectInternal() { if (!SpotifyLocalAPI.IsSpotifyRunning()) { Utilities.WriteLineWithTime("Spotify isn't running. Trying to start it..."); try { SpotifyLocalAPI.RunSpotify(); } catch (Exception e) { Utilities.WriteLineWithTime($"Error starting spotify: {e.Message}"); return(false); } } if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { Utilities.WriteLineWithTime("Spotify Web Helper isn't running. Trying to start it..."); try { SpotifyLocalAPI.RunSpotifyWebHelper(); } catch (Exception e) { Utilities.WriteLineWithTime($"Error starting Spotify Web Helper: {e.Message}"); return(false); } } return(m_spotify.Connect()); }
/// <summary> /// Connects to the Spotify client. /// </summary> public override void Connect() { try { EnableControls = false; if (IsConnected) { Disconnect(); } _spotify = new SpotifyLocalAPI(); SpotifyLocalAPI.RunSpotify(); SpotifyLocalAPI.RunSpotifyWebHelper(); if (!SpotifyLocalAPI.IsSpotifyRunning()) { OnStatusUpdated("Error connecting to Spotify: Client not running"); return; } if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { OnStatusUpdated("Error connecting to Spotify: WebHelper not running"); return; } if (!_spotify.Connect()) { OnStatusUpdated("Error connecting to Spotify: Unknown error"); } else { ConnectEvents(); _currentResponse = _spotify.GetStatus(); UpdateCurrentTrackInfo(); _refreshTimer.Start(); if (_currentResponse.Playing) { _counterTimer.Start(); } else { _counterTimer.Stop(); } IsConnected = true; OnStatusUpdated("Successfully connected to Spotify"); } } catch (Exception ex) { OnStatusUpdated($"Fatal error connecting to Spotify: {ex.Message}"); } finally { EnableControls = true; } }
/// <summary> /// Checks if any of the services has a connection /// </summary> /// <returns>True if service has a connection, false if not</returns> static async Task <bool> CheckForConnection() { if (iTunesFeat) { if (iTunes.Version != null) { return(true); } } if (SpotifyFeat) { if (SpotifyLocalAPI.IsSpotifyRunning() && SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { return(true); } } if (FoobarFeat) { if (await Foobar.GetStatusAsync() != null) { return(true); } } return(false); }
public SpotifyLocalPlayerViewModel(IQueueController queueController, IRegionManager regionManager, ILoggerFacade logger, ISpotifySongSearch songService, IThreadHelper helper) { _treadHelper = helper; _songService = songService; _logger = logger; _api = new SpotifyLocalAPI(); _regionManager = regionManager; if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { SpotifyLocalAPI.RunSpotifyWebHelper(); } if (!SpotifyLocalAPI.IsSpotifyRunning()) { SpotifyLocalAPI.RunSpotify(); } _api.OnTrackChange += _api_OnTrackChange; _api.OnTrackTimeChange += TrackTimeChanged; _api.OnPlayStateChange += PlayStateChanged; bool retryConnect; _api.ListenForEvents = true; do { //TODO: urgent need dialog! var connected = _api.Connect(); retryConnect = !connected; } while (retryConnect); _queueController = queueController; _queueController.CurrentSongChangedEvent += QueueControllerOnCurrentSongChangedEvent; _queueController.IsPlayingChangedEvent += QueueControllerOnIsPlayingChangedEvent; //Task.Run(async () => await FetchStartUpSong()); }
public static void Connect() { if (!SpotifyLocalAPI.IsSpotifyInstalled()) { return; } for (var tries = 5; tries > 0; tries--) { if (RunSpotify()) { break; } System.Threading.Thread.Sleep(RunSpotifyInterval); } try { Instance.Connect(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private static bool RunSpotify() { if (!SpotifyLocalAPI.IsSpotifyRunning()) { try { foreach (var path in SpotifyPossiblePaths) { if (!File.Exists(path)) { continue; } Process.Start(path); break; } } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } } return(SpotifyLocalAPI.IsSpotifyRunning()); }
private void NowPlaying_Load(object sender, EventArgs e) { LCDForm._activeForm = this; if (SpotifyLocalAPI.IsSpotifyRunning()) { if (SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { _spotify = new SpotifyLocalAPI(); setEvents(); if (_spotify.Connect()) { StatusResponse status = _spotify.GetStatus(); if (status.Playing) { btn_play.BackgroundImage = Properties.Resources.pause; } else { btn_play.BackgroundImage = Properties.Resources.play; } SetForm(status.Track); progressBar1.Value = (int)status.PlayingPosition; LabelTimeIs.Text = FormatTime(status.PlayingPosition); _spotify.ListenForEvents = true; } } } }
public Form1() { InitializeComponent(); _spotify = new SpotifyLocalAPI(); _spotify.OnTrackTimeChange += _spotify_OnTrackTimeChange; updateDB(); }
public void Connect() { if (!SpotifyLocalAPI.IsSpotifyRunning()) { MessageBox.Show(@"Spotify isn't running!"); return; } bool sukses; try { sukses = _spotify.Connect(); } catch { sukses = false; } if (sukses) { btnConnect.Text = @"Sukses menyambungkan ke Spotify PC"; btnConnect.Enabled = false; _spotify.ListenForEvents = true; btnPlay.Enabled = true; btnPause.Enabled = true; SpotifyAPI.Local.Models.StatusResponse status = _spotify.GetStatus(); if (status.Track != null) { UpdateTrack(status.Track, ""); } } else { DialogResult res = MessageBox.Show(@"Gagal menyambungkan ke Spotify PC. Coba lagi?", @"Spotify", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { Connect(); } } }
public void FireUpTheLocalAPI() { if (SpotifyLocalAPI.IsSpotifyRunning() == false) { SpotifyLocalAPI.RunSpotify(); while (SpotifyLocalAPI.IsSpotifyRunning() == false) { } } if (SpotifyLocalAPI.IsSpotifyWebHelperRunning() == false) { SpotifyLocalAPI.RunSpotifyWebHelper(); while (SpotifyLocalAPI.IsSpotifyWebHelperRunning() == false) { } } if (SpotifyAPI != null) { Status = SpotifyAPI.GetStatus(); } else { localConnect(); Status = SpotifyAPI.GetStatus(); } }
public void Connect() { if (!SpotifyLocalAPI.IsSpotifyRunning()) { Console.WriteLine(@"Spotify isn't running!"); return; } if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { Console.WriteLine(@"SpotifyWebHelper isn't running!"); return; } bool successful = _spotify.Connect(); if (successful) { Console.WriteLine(@"Connection to Spotify successful"); _spotify.ListenForEvents = true; } else { Console.WriteLine(@"Couldn't connect to the spotify client"); Connect(); } }
public static SpotifyInstance TryFind(out SpotifyLocalAPI api) { var hwnd = User32.FindWindow("SpotifyMainWindow", null); if (hwnd == IntPtr.Zero) { api = null; return(null); } if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { SpotifyLocalAPI.RunSpotifyWebHelper(); } int processId; User32.GetWindowThreadProcessId(hwnd, out processId); var proc = System.Diagnostics.Process.GetProcessById(processId); var sl = new SpotifyLocalAPI { ListenForEvents = true }; Task.Run(() => sl.Connect()).GetAwaiter().GetResult(); api = sl; return(new SpotifyInstance(proc, hwnd, sl)); }
//! @endcond /// <summary> /// The implementation of the method that will actualy look for swipes. /// </summary> protected override void LookForGesture() { if (SpotifyLocalAPI.IsSpotifyRunning()) { // Swipe to right if (ScanPositions((p1, p2) => Math.Abs(p2.Y - p1.Y) < SwipeMaximalHeight, // Height (p1, p2) => p2.X - p1.X > -0.01f, // Progression to right (p1, p2) => Math.Abs(p2.X - p1.X) > SwipeMinimalLength, // Length SwipeMininalDuration, SwipeMaximalDuration)) // Duration { _spotify.Skip(); RaiseGestureDetected("Música seguinte"); return; } // Swipe to left if (ScanPositions((p1, p2) => Math.Abs(p2.Y - p1.Y) < SwipeMaximalHeight, // Height (p1, p2) => p2.X - p1.X <0.01f, // Progression to right (p1, p2) => Math.Abs(p2.X - p1.X)> SwipeMinimalLength, // Length SwipeMininalDuration, SwipeMaximalDuration)) // Duration { _spotify.Previous(); RaiseGestureDetected("Música anterior"); return; } } }
private void applyProxyBtn_Click(object sender, EventArgs e) { _config.ProxyConfig.Host = proxyHostTextBox.Text; _config.ProxyConfig.Port = (int)proxyPortUpDown.Value; _config.ProxyConfig.Username = proxyUsernameTextBox.Text; _config.ProxyConfig.Password = proxyPasswordTextBox.Text; bool connected = _spotify.ListenForEvents; if (connected) { // Reconnect using new proxy _spotify.ListenForEvents = false; _spotify.OnPlayStateChange -= _spotify_OnPlayStateChange; _spotify.OnTrackChange -= _spotify_OnTrackChange; _spotify.OnTrackTimeChange -= _spotify_OnTrackTimeChange; _spotify.OnVolumeChange -= _spotify_OnVolumeChange; _spotify.Dispose(); _spotify = new SpotifyLocalAPI(_config); _spotify.OnPlayStateChange += _spotify_OnPlayStateChange; _spotify.OnTrackChange += _spotify_OnTrackChange; _spotify.OnTrackTimeChange += _spotify_OnTrackTimeChange; _spotify.OnVolumeChange += _spotify_OnVolumeChange; connectBtn.Text = @"Reconnecting..."; Connect(); } }
/// <summary> /// Attempts a connection to a local Spotify Client & WebAPI /// </summary> /// <param name="webApiClientId">Your client id for your app</param> /// <returns>If the connection was successful or not to either client or WebAPI</returns> public bool Connect(string webApiClientId, int port = 8000) { m_spotify = new SpotifyLocalAPI(m_localProxyConfig); m_spotify.OnPlayStateChange += OnPlayChangedInternal; m_spotify.OnTrackChange += OnTrackChangedInternal; m_spotify.OnTrackTimeChange += OnTrackTimeChangedInternal; m_spotify.OnVolumeChange += OnVolumeChangedInternal; bool localSpotifySuccessfulConnect = ConnectSpotifyLocal(); bool webHelperSuccessfulConnect = ConnectSpotifyWebHelper(webApiClientId, port); if (localSpotifySuccessfulConnect) { InitializeLocalSpotify(); } if (webHelperSuccessfulConnect) { InitalizeWebHelper(); } if (!localSpotifySuccessfulConnect && !webHelperSuccessfulConnect) { Analysis.Log("Unable to connect to any Spotify API - Local or Web"); } IsConnected = localSpotifySuccessfulConnect || webHelperSuccessfulConnect; return(IsConnected); }
public void RunSpotify() { if (!IsRunning) { SpotifyLocalAPI.RunSpotify(); } }
/// <summary> /// Connectes to the WebHelper with your ClientId /// </summary> /// <param name="clientId">Custom client id</param> /// <returns></returns> private bool ConnectSpotifyWebHelper(string clientId, int port = 8000) { if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { Analysis.LogError("SpotifyWebHelper isn't running!"); return(false); } WebAPIFactory webApiFactory = new WebAPIFactory( "http://localhost", port, clientId, Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistReadPrivate | Scope.UserLibraryRead | Scope.UserReadPrivate | Scope.UserFollowRead | Scope.UserReadBirthdate | Scope.UserTopRead | Scope.PlaylistReadCollaborative | Scope.UserReadRecentlyPlayed | Scope.UserReadPlaybackState | Scope.UserModifyPlaybackState | Scope.Streaming, m_proxyConfig); try { m_webAPI = webApiFactory.GetWebApi().Result; } catch (Exception ex) { Analysis.LogError($"Unable to connect to WebAPI - {ex}"); } return(m_webAPI != null); }
public void SetupSpotify() { if (_spotifySetupBusy) { return; } _spotifySetupBusy = true; _spotify = new SpotifyLocalAPI(); // Connecting can sometimes use a little bit more conviction Task.Factory.StartNew(() => { var tryCount = 0; while (tryCount <= 10) { try { tryCount++; var connected = _spotify.Connect(); if (connected) { break; } Thread.Sleep(1000); } catch (WebException) { break; } } _spotifySetupBusy = false; }); }
/// <summary> /// Disconnects and removes any information from the service /// </summary> public void Disconnect() { if (m_spotify != null) { m_spotify.OnPlayStateChange -= OnPlayChangedInternal; m_spotify.OnTrackChange -= OnTrackChangedInternal; m_spotify.OnTrackTimeChange -= OnTrackTimeChangedInternal; m_spotify.OnVolumeChange -= OnVolumeChangedInternal; m_spotify.Dispose(); m_spotify = null; } if (m_webAPI != null) { m_webAPI.Dispose(); m_webAPI = null; } IsConnected = false; IsPlaying = false; IsMuted = false; CurrentTrack = null; CurrentTrackTime = 0f; Volume = null; SavedTracks = null; }
private bool ConnectToLocalSpotifyClient() { _sApi = new SpotifyLocalAPI(1000); if (!SpotifyLocalAPI.IsSpotifyRunning()) { ReportStateChange(true, "Spotify is not running"); StartSpotifyProcessWatcher(); return(false); } if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { ReportStateChange(true, "Spotify Web Helper not running"); return(false); } if (!_sApi.Connect()) { ReportStateChange(true, "Failed to connect to Spotify"); return(false); } else { _sApi.OnTrackChange += OnTrackChanged; _sApi.OnPlayStateChange += OnPlayStateChanged; _sApi.ListenForEvents = true; ReportStateChange(false); } return(true); }
public void Connect() { if (!SpotifyLocalAPI.IsSpotifyRunning()) { txt_message.Text = "Spotify no se está ejecutando!"; mensage_timer.Start(); return; } if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { txt_message.Text = "El proceso SpotifyWebHelper no está corriendo!"; mensage_timer.Start(); return; } bool successful = _spotify.Connect(); if (successful) { txt_message.Text = "Conexión con Spotify exitosa"; mensage_timer.Start(); pb_album.Enabled = false; pb_album.Cursor = Cursors.Arrow; UpdateInfos(); _spotify.ListenForEvents = true; } else { DialogResult res = MessageBox.Show(@"No se ha podido establecer conexion con el cliente de Spotify. Lo intentamos de nuevo?", @"Spotify", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { Connect(); } } }
/// <summary> /// Connects To Spotify Local /// </summary> public void ConnectToSpotify() { if (!SpotifyLocalAPI.IsSpotifyRunning()) { MessageBox.Show(@"Spotify isn't running!"); return; } if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { MessageBox.Show(@"SpotifyWebHelper isn't running!"); return; } bool successful = spotify.Connect(); if (successful) { connectBtn.BackgroundImage = new Bitmap(TeamspeakMusicBot_v3.Properties.Resources.SpotifyGreen); connectBtn.Enabled = false; lblConnect.Text = "Connected!"; Playlist.PlayNextSong(); spotify.ListenForEvents = true; new TS3Reader().LastLineListener(); } else { DialogResult res = MessageBox.Show(@"Couldn't connect to the spotify client. Retry?", @"Spotify", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { ConnectToSpotify(); } } }
public bool Spotify_Load(Form1 form) { if (!SpotifyLocalAPI.IsSpotifyRunning() || !SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { DialogResult result = MessageBox.Show("Unable to connect to spotify, retry?", "Spotify Toast", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { return(Spotify_Load(form)); } return(false); } cantLoad = this._spotify.Connect(); if (!cantLoad) { DialogResult result = MessageBox.Show("Unable to connect to spotify, retry?", "Spotify Toast", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { return(Spotify_Load(form)); } return(false); } timer.Tick += new EventHandler(this.FireTimer); form1 = form; this._spotify.ListenForEvents = true; this._spotify.SynchronizingObject = form1; _spotify.OnTrackChange += _spotify_OnTrackChange; _spotify.OnTrackTimeChange += _spotify_OnTrackTimeChange; _spotify.OnPlayStateChange += _spotify_OnPlayStateChange; return(true); }
public void Connect() { if (!SpotifyLocalAPI.IsSpotifyRunning()) { MessageBox.Show(@"Spotify isn't running!"); return; } if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) { MessageBox.Show(@"SpotifyWebHelper isn't running!"); return; } bool successful = _spotify.Connect(); if (successful) { connectBtn.Text = @"Connection to Spotify successful"; connectBtn.Enabled = false; UpdateInfos(); _spotify.ListenForEvents = true; } else { DialogResult res = MessageBox.Show(@"Couldn't connect to the spotify client. Retry?", @"Spotify", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { Connect(); } } }
public SpotifyRemote() { _spotify = new SpotifyLocalAPI { ListenForEvents = true }; _spotify.OnPlayStateChange += (s, e) => { // Match Remote.IsPlaying with client if (Status.Playing != IsPlaying) { IsPlaying = Status.Playing; } // Check if stopped playing because track ended if (!IsPlaying && Math.Abs(Status.PlayingPosition) < 0.0001) { OnTrackDone?.Invoke(this, EventArgs.Empty); } }; _spotify.OnTrackChange += (s, e) => { // Pause and trigger OnTrackDone if track was not changed by Remote if (_switching) { _switching = false; } else { OnTrackDone?.Invoke(this, EventArgs.Empty); } }; TryConnect(); IsPlaying = Status.Playing; }