private async void AuthOnAuthReceived(object sender, AuthorizationCode payload) { AuthorizationCodeAuth auth = (AuthorizationCodeAuth)sender; auth.Stop(); Token token = await auth.ExchangeCode(payload.Code); api = new SpotifyWebAPI { AccessToken = token.AccessToken, TokenType = token.TokenType }; songInfo = await CurrentPlayingsong(api); if (songInfo == "") { return; } HappiWebApi happiapi = new HappiWebApi(_HappiapiKey); GetLyrics(happiapi, songInfo); }
public async void refreshtoken(string codeToken, bool tellPeople, Action <bool, bool, string, string> callback = null) { initialized = false; if (_spotify == null) { _spotify = new SpotifyWebAPI(); } AuthorizationCodeAuth auth = getAuth(); Token token = await auth.RefreshToken(codeToken); _spotify.AccessToken = token.AccessToken; _spotify.TokenType = token.TokenType; if (!token.HasError()) { initialized = true; } else { Console.WriteLine(token.Error + " - " + token.ErrorDescription); } if (callback != null) { callback(initialized, tellPeople, token.AccessToken, token.RefreshToken); } }
private static string _secretId = ""; //""; static void Main(string[] args) { _clientId = string.IsNullOrEmpty(_clientId) ? System.Environment.GetEnvironmentVariable("SPOTIFY_CLIENT_ID") : _clientId; _secretId = string.IsNullOrEmpty(_secretId) ? System.Environment.GetEnvironmentVariable("SPOTIFY_SECRET_ID") : _secretId; Console.WriteLine("####### Spotify API Example #######"); Console.WriteLine("This example uses AuthorizationCodeAuth."); Console.WriteLine( "Tip: If you want to supply your ClientID and SecretId beforehand, use env variables (SPOTIFY_CLIENT_ID and SPOTIFY_SECRET_ID)"); AuthorizationCodeAuth auth = new AuthorizationCodeAuth(_clientId, _secretId, "http://localhost:4002", "http://localhost:4002", Scope.PlaylistReadPrivate | Scope.PlaylistReadCollaborative); auth.AuthReceived += AuthOnAuthReceived; auth.Start(); auth.OpenBrowser(); /* ImplictGrantAuth auth = new ImplictGrantAuth("26d287105e31491889f3cd293d85bfea", "http://localhost:4002", "http://localhost:4002"); * auth.Start(); * auth.OpenBrowser();*/ Console.ReadLine(); auth.Stop(0); }
public SpotifyLoad() { auth = new AuthorizationCodeAuth( _clientId, _clientSecret, "http://localhost:4002", "http://localhost:4002", Scope.UserReadCurrentlyPlaying | Scope.UserModifyPlaybackState ); auth.AuthReceived += async(sender, payload) => { auth.Stop(); token = await auth.ExchangeCode(payload.Code); api = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; Thread t = new Thread(spotifyDataLoop); t.Start(); }; auth.Start(); // Starts an internal HTTP Server auth.OpenBrowser(); }
private static async Task <SpotifyWebAPI> AuthSpotifyApi() { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); AuthorizationCodeAuth auth = new AuthorizationCodeAuth( config.GetSection("SpotifyApi:ClientId").Value, config.GetSection("SpotifyApi:ClientSecret").Value, "http://localhost:6410", "http://localhost:6410", SpotifyAPI.Web.Enums.Scope.PlaylistReadCollaborative); auth.AuthReceived += async(sender, payload) => { auth.Stop(); Token token = await auth.ExchangeCode(payload.Code); _spotifyWeb = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; // Do requests with API client }; auth.Start(); // Starts an internal HTTP Server auth.OpenBrowser(); return(_spotifyWeb); }
private void iniciarModoStream() { try { Log.Instance.ImprimirMensaje("Intentando conectar cuenta de Spotify", TipoMensaje.Info, "Spotify.iniciarModoStream()"); Programa.HayInternet(true); Stopwatch crono = Stopwatch.StartNew(); auth = new AuthorizationCodeAuth( clavePublica, clavePrivada, "http://localhost:4002/", "http://localhost:4002/", Scope.UserReadEmail | Scope.UserReadPrivate | Scope.Streaming | Scope.UserReadPlaybackState ); auth.AuthReceived += (sender, payload) => { auth.Stop(); Token token = auth.ExchangeCode(payload.Code).Result; tokenActual = token; _spotify = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; crono.Stop(); if (_spotify.AccessToken != null) { cuentaLista = true; cuentaVinculada = true; Programa.config.AppSettings.Settings["VinculadoConSpotify"].Value = "true"; Log.Instance.ImprimirMensaje("Conectado sin errores como " + _spotify.GetPrivateProfile().DisplayName, TipoMensaje.Correcto, crono); } else { cuentaLista = false; cuentaVinculada = false; Log.Instance.ImprimirMensaje("Se ha conectado pero el token es nulo", TipoMensaje.Error, crono); Programa.config.AppSettings.Settings["VinculadoConSpotify"].Value = "false"; } CodigoRefresco = token.RefreshToken; Programa.tareaRefrescoToken = new Thread(Programa.Refresco); Programa.tareaRefrescoToken.Start(); }; auth.Start(); auth.OpenBrowser(); } catch (NullReferenceException) { Programa.HayInternet(false); Console.WriteLine("Algo fue mal"); System.Windows.Forms.MessageBox.Show(Programa.textosLocal.GetString("error_internet")); } catch (HttpRequestException) { Programa.HayInternet(false); Console.WriteLine("No tienes internet"); System.Windows.Forms.MessageBox.Show(Programa.textosLocal.GetString("error_internet")); } }
public void Connect() { auth = new AuthorizationCodeAuth(_clientId, _secretId, _localAddress, _localAddress, Scope.UserReadPlaybackState); auth.AuthReceived += Auth_AuthReceived; auth.Start(); //string uri = auth.GetUri(); auth.OpenBrowser(); }
protected override void GotAuth(Token token, AuthorizationCodeAuth auth = null) { base.GotAuth(token, auth); if (m_expireRoutine != null) { m_expireRoutine = StartCoroutine(AwaitTokenExpire(token.ExpiresIn, token.CreateDate)); } }
private async void AuthOnAuthReceived(object sender, AuthorizationCode payload) { _authorizationCodeAuth = (AuthorizationCodeAuth)sender; _authorizationCodeAuth.Stop(); _token = await _authorizationCodeAuth.ExchangeCode(payload.Code); RenewNextTokenRenewal(); }
public ActionResult Code(string code) { AuthorizationCodeAuth auth = new AuthorizationCodeAuth(Settings.ClientId, Settings.ClientSecret, code, Settings.Url); ApiContext api = new ApiContext(auth); _token = api.Token; return(RedirectToAction("Data")); }
private void OnAuthorizationRecieved(object sender, AuthorizationCode payload) { AuthorizationCodeAuth auth = sender as AuthorizationCodeAuth; auth.Stop(); SAPIModels.Token token = auth.ExchangeCode(payload.Code).Result; Analysis.Log($"Gained the initial Spotify authorization at '{token.CreateDate}", Analysis.LogLevel.Vital); Configure(token, auth); }
private void StartPoller(AuthorizationCodeAuth auth, Token token) { CoverManager coverManager = new CoverManager(); NowPlayingTrackInfoProvider trackInfoProvider = new SpotifyNowPlayingTrackInfoProvider(webApi, auth, token); poller = new TrackInfoPoller(trackInfoProvider, coverManager, this); Thread pollerThread = new Thread(new ThreadStart(poller.PollAndUpdate)); pollerThread.Start(); }
private async void AuthOnAuthReceived(object Sender, AuthorizationCode Payload) { AuthorizationCodeAuth Auth = (AuthorizationCodeAuth)Sender; Auth.Stop(); Token ReceivedToken = await Auth.ExchangeCode(Payload.Code); OnAuthCodeReceived(ReceivedToken.AccessToken, ReceivedToken.TokenType); }
private async void AuthOnAuthReceived(object sender, AuthorizationCode payload) { _authorizationCodeAuth = (AuthorizationCodeAuth)sender; _authorizationCodeAuth.Stop(); _token = await _authorizationCodeAuth.ExchangeCode(payload.Code); // remember when to renew the 60 minutes token (10 minutes upfront) _nextTokenRenewal = DateTimeOffset.UtcNow.AddSeconds(_token.ExpiresIn).AddMinutes(-10); }
private async void AuthOnAuthReceived(object sender, AuthorizationCode payload) { AuthorizationCodeAuth auth = (AuthorizationCodeAuth)sender; auth.Stop(); Token token = await auth.ExchangeCode(payload.Code); this.Start(token); }
// ReSharper disable once UnusedParameter.Local public static void Main(string[] args) { _clientId = string.IsNullOrEmpty(_clientId) ? Environment.GetEnvironmentVariable("SPOTIFACE_CLIENT_ID") : _clientId; _secretId = string.IsNullOrEmpty(_secretId) ? Environment.GetEnvironmentVariable("SPOTIFACE_SECRET") : _secretId; var auth = new AuthorizationCodeAuth(_clientId, _secretId, "http://*****:*****@"..\..\..\..\..\src\"), "video_emotion_color_demo.py"); while (true) { using (ZFrame reply = socket.ReceiveFrame()) { emotionStack.Add(reply.ReadString()); Console.WriteLine("RECIEVED {0}", emotionStack[emotionStack.Count - 1]); } socket.Send(new ZFrame("Thanks")); PlaybackContext playbackContext = _spotify.GetPlayback(); var isReadyForNewSong = !playbackContext.IsPlaying || playbackContext.ProgressMs >= (playbackContext.Item.DurationMs - CHANGE_SONG_BUFFER_MS); Console.WriteLine("{0} ms before next song!", playbackContext.Item.DurationMs - CHANGE_SONG_BUFFER_MS - playbackContext.ProgressMs); if (isReadyForNewSong) { Console.WriteLine("READY FOR A NEW SONG"); string mostCommon = emotionStack.GroupBy(v => v).OrderByDescending(g => g.Count()).First().Key; if (mostCommon != lastMostCommon) { Console.WriteLine("Most common since last time was {0}", mostCommon); lastMostCommon = mostCommon; _spotify.ResumePlayback(contextUri: _playlistMap[mostCommon], offset: 0, positionMs: 0); _spotify.SetShuffle(true); emotionStack.Clear(); } } } } }
internal SpotifyAuthentication() { bool initialized = false; var client_id = "7b2f38e47869431caeda389929a1908e"; var secret_id = "c3a86330ef844c16be6cb46d5e285a45"; _authenFactory = new AuthorizationCodeAuth( client_id, secret_id, "http://localhost:8800", "http://localhost:8800", Scope.UserReadCurrentlyPlaying | Scope.UserModifyPlaybackState | Scope.AppRemoteControl | Scope.UserReadPlaybackState ); _authenFactory.AuthReceived += async(s, p) => { var ath = (AuthorizationCodeAuth)s; ath.Stop(); var token = await ath.ExchangeCode(p.Code); _refreshToken = token.RefreshToken; if (_client == null) { _client = new SpotifyWebAPI() { AccessToken = token.AccessToken, TokenType = "Bearer" }; } else { _client.AccessToken = token.AccessToken; } if (!initialized) { ClientReady?.Invoke(this, _client); } initialized = true; }; _authenFactory.Start(); _authenFactory.OpenBrowser(); _refreshTokenWorker = new Timer(); _refreshTokenWorker.Interval = 30 * (1000 * 60); _refreshTokenWorker.Elapsed += async(s, e) => { var token = await _authenFactory.RefreshToken(_refreshToken); _client.AccessToken = token.AccessToken; }; _refreshTokenWorker.Start(); }
public void RetrieveAuthCode(AuthCodeReceivedDelegate OnAuthCodeReceived) { this.OnAuthCodeReceived = OnAuthCodeReceived; string ClientId = Environment.GetEnvironmentVariable("SPLACK_SPOTIFY_CLIENT_ID"); string SecretId = Environment.GetEnvironmentVariable("SPLACK_SPOTIFY_SECRET_ID"); AuthorizationCodeAuth Auth = new AuthorizationCodeAuth(ClientId, SecretId, "http://localhost:4002", "http://localhost:4002", Scope.UserReadCurrentlyPlaying); Auth.AuthReceived += AuthOnAuthReceived; Auth.Start(); Auth.OpenBrowser(); }
SpotifyConfiguration() { bool initialized = false; var client_id = "7b2f38e47869431caeda389929a1908e"; var secret_id = "c3a86330ef844c16be6cb46d5e285a45"; AuthenFactory = new AuthorizationCodeAuth( client_id, secret_id, "http://localhost:8888", "http://localhost:8888", SpotifyAPI.Web.Enums.Scope.AppRemoteControl ); AuthenFactory.AuthReceived += async(s, p) => { var ath = (AuthorizationCodeAuth)s; ath.Stop(); var token = await ath.ExchangeCode(p.Code); initialized = true; RefreshToken = token.RefreshToken; if (Client == null) { Client = new SpotifyWebAPI() { AccessToken = token.AccessToken, TokenType = "Bearer" }; } else { Client.AccessToken = token.AccessToken; } IsAvailable = true; }; AuthenFactory.Start(); AuthenFactory.OpenBrowser(); while (!initialized) { System.Threading.Thread.Sleep(1000); } AuthenFactory.Stop(); _refreshTokenWorker = new Timer(); _refreshTokenWorker.Interval = 30 * (1000 * 60); _refreshTokenWorker.Elapsed += async(s, e) => { var token = await AuthenFactory.RefreshToken(RefreshToken); Client.AccessToken = token.AccessToken; }; _refreshTokenWorker.Start(); }
private AuthorizationCodeAuth getAuth() { AuthorizationCodeAuth auth = new AuthorizationCodeAuth( _spotifyConfig.clientId, _spotifyConfig.clientSecret, _spotifyConfig.returnUrl, _spotifyConfig.returnUrl, (Scope.UserModifyPlaybackState | Scope.UserReadPlaybackState | Scope.UserReadCurrentlyPlaying) ); return(auth); }
private static async void AuthOnAuthReceived(object sender, AuthorizationCode payload) { AuthorizationCodeAuth auth = (AuthorizationCodeAuth)sender; auth.Stop(); Token token = await auth.ExchangeCode(payload.Code); api = new SpotifyWebAPI { AccessToken = token.AccessToken, TokenType = token.TokenType }; }
private Token RefreshToken(string refreshToken) { AuthorizationCodeAuth auth = new AuthorizationCodeAuth( Settings.ClientId, Settings.ClientSecret, Settings.RedirectUri, Settings.RedirectUri, Scope.None, Settings.StateKey ); return(auth.RefreshToken(refreshToken).Result); }
public SpotifyAPI(string clientId, string secretId, string redirectUrl = SPOTIFY_API_DEFAULT_REDIRECT_URL) { _lastFmApi = new LastFMAPI(); if (!string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(secretId)) { _auth = new AuthorizationCodeAuth(clientId, secretId, redirectUrl, redirectUrl, Scope.Streaming | Scope.PlaylistReadCollaborative | Scope.UserReadCurrentlyPlaying | Scope.UserReadRecentlyPlayed | Scope.UserReadPlaybackState); _auth.AuthReceived += AuthOnAuthReceived; _auth.Start(); } }
public SpotifyAPI(string clientId, string secretId, string redirectUrl = "http://localhost:4002") { _clientId = clientId; _secretId = secretId; if (!string.IsNullOrEmpty(_clientId) && !string.IsNullOrEmpty(_secretId)) { var auth = new AuthorizationCodeAuth(_clientId, _secretId, redirectUrl, redirectUrl, Scope.Streaming | Scope.PlaylistReadCollaborative | Scope.UserReadCurrentlyPlaying | Scope.UserReadRecentlyPlayed | Scope.UserReadPlaybackState); auth.AuthReceived += AuthOnAuthReceived; auth.Start(); auth.OpenBrowser(); } }
private System.Collections.IEnumerator AwaitTokenRefresh(AuthorizationCodeAuth auth, float expireSeconds, string refreshToken, DateTime tokenCreationTime) { DateTime renewDateTime = tokenCreationTime.AddSeconds(expireSeconds); TimeSpan differenceTime = renewDateTime - DateTime.Now; ///Remove some time at the end so we renew while the old tokens are valid TimeSpan margin = TimeSpan.FromSeconds(AUTH_TOKEN_MARGIN_SECONDS); differenceTime = differenceTime.Subtract(margin); Analysis.Log($"Waiting '{Math.Round(differenceTime.TotalSeconds, MidpointRounding.ToEven)}' seconds until refreshing Spotify authorization (Reauth at '{renewDateTime.Subtract(margin)}')", Analysis.LogLevel.All); yield return(new WaitForSeconds((float)differenceTime.TotalSeconds)); Task.Run(async() => await RefreshTokenAndConfigure(auth, refreshToken)); }
protected override void GotAuth(SAPIModels.Token token, AuthorizationCodeAuth auth) { base.GotAuth(token, auth); if (string.IsNullOrEmpty(m_refreshToken) && !string.IsNullOrEmpty(token.RefreshToken)) { m_refreshToken = token.RefreshToken; } if (ReuseAuthTokens && auth != null && token != null) { EventManager.QueueEvent(new RunRefreshToken(auth, (float)token.ExpiresIn, token.CreateDate, m_refreshToken)); } }
public static void Run(List <string> trackNames) { tracks = trackNames; AuthorizationCodeAuth auth = new AuthorizationCodeAuth(Credentials.SP_id, Credentials.SP_key, "http://localhost:4002", "http://localhost:4002", Scope.PlaylistModifyPrivate); auth.AuthReceived += AuthOnAuthReceived; auth.Start(); auth.OpenBrowser(); Console.ReadLine(); auth.Stop(0); }
private AuthorizationCodeAuth CreateAuthorization() { string _clientId = "d561c6c5f0be4ff29a5b64ceb9e703da"; string _secretId = "534e8567260842519f58461101208a83"; AuthorizationCodeAuth auth = new AuthorizationCodeAuth(_clientId, _secretId, "http://localhost:4002", "http://localhost:4002", Scope.PlaylistReadPrivate | Scope.PlaylistReadCollaborative | Scope.PlaylistModifyPublic | Scope.UserReadCurrentlyPlaying | Scope.UserReadPlaybackState ); return(auth); }
public static Token AddTocken(AuthorizationCodeAuth auth) { Token token = new Token(); string url5 = "https://accounts.spotify.com/api/token"; var clientid = "d959c53d82124f4a89b0b8f463152037"; var clientsecret = "3605d0cde2d74c07822299c0359f840f"; //request to get the access token var token2 = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", clientid, clientsecret))); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url5); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Accept = "application/json"; webRequest.Headers.Add("Authorization", "Basic " + token2); //webRequest.Headers.Add("Authorization: Basic " + encode_clientid_clientsecret); var request = ("grant_type=client_credentials"); byte[] req_bytes = Encoding.ASCII.GetBytes(request); webRequest.ContentLength = req_bytes.Length; Stream strm = webRequest.GetRequestStream(); strm.Write(req_bytes, 0, req_bytes.Length); strm.Close(); HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse(); String json = ""; using (Stream respStr = resp.GetResponseStream()) { using (StreamReader rdr = new StreamReader(respStr, Encoding.UTF8)) { //should get back a string i can then turn to json and parse for accesstoken json = rdr.ReadToEnd(); Console.WriteLine(json); Console.WriteLine(token.AccessToken); rdr.Close(); token = JsonConvert.DeserializeObject <Token>(json); ; } } return(token); }
static void Main(string[] args) { var configuration = new MapperConfiguration(cfg => { cfg.AddProfile(new PlaylistMapper()); }); var serviceProvider = new ServiceCollection() .AddAutoMapper(typeof(Program)) .AddSingleton <IValidator, Validator>() .AddSingleton <IProcessFactory, ProcessFactory>() .AddSingleton <IAPIProcess, ApiProcess>() .AddSingleton <SpotifyWebAPI>() .AddTransient <IProcess, GetPlaylistProcess>() .AddTransient <IProcess, ClearPlaylistProcess>() .AddTransient <IProcess, ReorderProcess>() .AddTransient <IServiceCollection, ServiceCollection>() .BuildServiceProvider(); string _clientId = "eca82f597115423cac9d1125e0fb97c4"; string _secretId = "17a6e5916bb3424eb50f29e4816521a4"; AuthorizationCodeAuth auth = new AuthorizationCodeAuth( _clientId, _secretId, "http://localhost:4200", "http://localhost:4200", Scope.PlaylistReadPrivate | Scope.PlaylistReadCollaborative | Scope.PlaylistModifyPrivate | Scope.PlaylistModifyPublic ); auth.AuthReceived += async(sender, payload) => { auth.Stop(); Token token = await auth.ExchangeCode(payload.Code); var apiProcess = serviceProvider.GetService <IAPIProcess>(); ClearPlaylistRequest request = new ClearPlaylistRequest { PlaylistUri = "6KPMCEavSTefLEx5JH3edt", Token = token }; IResponseMessage responseMessage = apiProcess.RunCommand <ClearPlaylistRequest>(request); }; auth.Start(); // Starts an internal HTTP Server auth.OpenBrowser(); Console.ReadLine(); }