public async Task ConnectWebApi(bool keepRefreshToken = true) { _securityStore = SecurityStore.Load(pluginDirectory); AuthorizationCodeAuth auth = new AuthorizationCodeAuth(_securityStore.ClientId, _securityStore.ClientSecret, "http://localhost:4002", "http://localhost:4002", Scope.PlaylistReadPrivate | Scope.PlaylistReadCollaborative | Scope.UserReadCurrentlyPlaying | Scope.UserReadPlaybackState | Scope.UserModifyPlaybackState | Scope.Streaming | Scope.UserFollowModify); if (_securityStore.HasRefreshToken && keepRefreshToken) { Token token = await auth.RefreshToken(_securityStore.RefreshToken); _spotifyApi = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; } else { auth.AuthReceived += async(sender, payload) => { auth.Stop(); Token token = await auth.ExchangeCode(payload.Code); _securityStore.RefreshToken = token.RefreshToken; _securityStore.Save(pluginDirectory); _spotifyApi = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; }; auth.Start(); auth.OpenBrowser(); } }
public SpotifyAPI(string clientId, string secretId, string redirectUrl = "http://localhost:4002", Boolean authed = false) { _clientId = clientId; _secretId = secretId; if (!authed) { System.Diagnostics.Debug.WriteLine("Authorizing for the first time"); auth = new AuthorizationCodeAuth( _clientId, _secretId, redirectUrl, redirectUrl, Scope.UserReadPrivate | Scope.UserReadCurrentlyPlaying | Scope.UserTopRead | Scope.Streaming | Scope.UserModifyPlaybackState | Scope.UserLibraryModify | Scope.UserReadPlaybackState | Scope.PlaylistReadPrivate | Scope.PlaylistModifyPrivate | Scope.PlaylistModifyPublic | Scope.UserLibraryRead ); auth.AuthReceived += async(sender, payload) => { auth.Stop(); token = await auth.ExchangeCode(payload.Code); api = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; App.Current.Properties["TokenType"] = api.TokenType; App.Current.Properties["AccessToken"] = api.AccessToken; }; auth.Start(); auth.OpenBrowser(); authed = true; } }
private void connectBtn_Click(object sender2, EventArgs e) { String clientId = clientIdTB.Text; String clientSecret = clientSecretTB.Text; if (clientId.Length > 0 && clientSecret.Length > 0) { AuthorizationCodeAuth auth = new AuthorizationCodeAuth( clientId, clientSecret, "http://localhost:4002", "http://localhost:4002", Scope.PlaylistModifyPrivate | Scope.PlaylistModifyPublic | Scope.UserLibraryModify ); auth.AuthReceived += async(sender, payload) => { auth.Stop(); Token token = await auth.ExchangeCode(payload.Code); SpotifyAPI = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; }; auth.Start(); // Starts an internal HTTP Server auth.OpenBrowser(); } else { messageLbl.Text = "Need both client secret and client Id. These can be found on your spotify developer page (free to create account)."; } }
public async Task <TokenResponse> ExchangeAccessCodeAsync(string code) { var token = await _authentication.ExchangeCode(code); UpdateToken(token); return(Mapping.MapToken(token)); }
public Task GetEmpty() { string state = Request.QueryString["state"]; AuthorizationCodeAuth.Instances.TryGetValue(state, out SpotifyAuthServer <AuthorizationCodeResponse> auth); string code = null; string error = Request.QueryString["error"]; if (error == null) { code = Request.QueryString["code"]; } AuthorizationCodeResponse authcode = new AuthorizationCodeResponse { Code = code, Error = error }; AuthorizationCodeAuth au = (AuthorizationCodeAuth)auth; Task.Factory.StartNew(async() => auth?.TriggerAuth(await au.ExchangeCode(authcode.Code))); return(HttpContext.SendStandardHtmlAsync(200, (tw) => { tw.WriteLine("<script>window.close()</script>"); tw.Flush(); })); }
public async void Init() { var _clientId = "4dab4bc197084c7db90f8201c5990abe"; var _secretId = "e5f5c68a50ff48068eb1bfea84cc57a4"; AuthorizationCodeAuth auth = new AuthorizationCodeAuth(_clientId, _secretId, "http://localhost:4002", "http://localhost:4002", Scope.PlaylistReadPrivate | Scope.PlaylistReadCollaborative); auth.Start(); // Starts an internal HTTP Server auth.OpenBrowser(); auth.AuthReceived += async(sender, payload) => { auth.Stop(); Token token = await auth.ExchangeCode(payload.Code); SpotifyWebAPI api = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; // Do requests with API client profile = await api.GetPrivateProfileAsync(); if (!profile.HasError()) { Console.WriteLine(profile.DisplayName); } }; }
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 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 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 }; var result = GetsongInfo(); if (!result.IsSuccess) { Console.WriteLine("Song Not found."); return; } songinfo = result.Date; GetLyrics(songinfo); }
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")); } }
private async void AuthOnAuthReceived(object sender, AuthorizationCode payload) { _authorizationCodeAuth = (AuthorizationCodeAuth)sender; _authorizationCodeAuth.Stop(); _token = await _authorizationCodeAuth.ExchangeCode(payload.Code); RenewNextTokenRenewal(); }
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 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); }
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 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 }; }
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(); }
private async void OnAuthReceived(object sender, AuthorizationCode payload) { try { auth.Stop(); var token = await auth.ExchangeCode(payload.Code); UpdateAccessToken(token); } catch (Exception e) { initExcpt = e; } }
private async void OnAuthReceived(object sender, AuthorizationCode payload) { AuthorizationCodeAuth auth = (AuthorizationCodeAuth)sender; auth.Stop(); Token token; token = await auth.ExchangeCode(payload.Code); spotify = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; }
private async void Auth_AuthReceived(object sender, AuthorizationCode payload) { AuthorizationCodeAuth auth = (AuthorizationCodeAuth)sender; auth.Stop(); _token = await auth.ExchangeCode(payload.Code); _api = new SpotifyWebAPI { AccessToken = _token.AccessToken, TokenType = _token.TokenType }; RunSpotifyApi(); }
private void AuthorizeSpotifyToken() { AuthorizationCodeAuth auth = this.CreateAuthorization(); auth.AuthReceived += async(sender, payload) => { auth.Stop(); Token token = await auth.ExchangeCode(payload.Code); this.CreateTokenFile(token); this.isAuthenticated = true; }; auth.Start(); auth.OpenBrowser(); }
private static async void AuthOnAuthReceived(object sender, AuthorizationCode payload) { AuthorizationCodeAuth auth = (AuthorizationCodeAuth)sender; auth.Stop(); SpotifyAPI.Web.Models.Token token = await auth.ExchangeCode(payload); SpotifyWebAPI api = new SpotifyWebAPI { AccessToken = token.AccessToken, TokenType = token.TokenType }; PrintUsefulData(api); }
public ActionResult Index(string code = null) { AuthorizationCodeAuth auth = new AuthorizationCodeAuth( Settings.RedirectUri, Settings.RedirectUri, Scope.None, Settings.StateKey); auth.ClientId = Settings.ClientId; auth.SecretId = Settings.ClientSecret; Token token = auth.ExchangeCode(code).Result; _tokenService.SetToken(token.AccessToken, token.RefreshToken, token.ExpiresIn, TokenCredentialType.Auth); _sessionService.SetToken(token.ToCustomToken(TokenCredentialType.Auth)); bool chromeToken = Convert.ToBoolean(_sessionService.getSession("ChromeToken")); if (chromeToken) { _sessionService.DeleteSession("ChromeToken"); return(Redirect(string.Format("~/?access_token={0}&refresh_token={1}&expires_in={2}", token.AccessToken, token.RefreshToken, token.ExpiresIn))); } if (Convert.ToBoolean(_sessionService.getSession("fromIframe"))) { _sessionService.DeleteSession("fromIframe"); return(RedirectToAction("CloseIframe", "Authorize")); } var returnUrl = _sessionService.GetReturnUrl(); if (returnUrl != null && !string.IsNullOrEmpty(returnUrl)) { if (HasUserAuthorized(returnUrl)) { return(Redirect("~/")); } else { return(Redirect(returnUrl)); } } return(Redirect("~/")); }
/// <summary> /// Authorize with the Spotify Web API to retrieve a Refresh Token. /// This token is then to be used for any subsequent calls to <see cref="RunStatus(Status)"/> /// </summary> /// <param name="opts_">CLI arguments</param> /// <returns>1 for errors, 0 otherwise</returns> static int RunAuthorize(Authorize opts_) { SysConsole.WriteLine("Authorizing with SpotifyWebAPI"); Token token = null; var auth = new AuthorizationCodeAuth(opts_.ClientId, opts_.ClientSecret, "http://localhost:" + opts_.Port, "http://localhost:" + opts_.Port, Scope.UserReadPrivate); auth.AuthReceived += (object sender_, AuthorizationCode payload_) => { auth.Stop(); var exchange = auth.ExchangeCode(payload_.Code); exchange.Wait(10000); if (!exchange.IsCompleted) { throw new Exception("Timeout during authorization process!"); } token = exchange.Result; }; SysConsole.WriteLine("Starting authorization process"); auth.Start(); auth.OpenBrowser(); SysConsole.Write("Waiting for authorzation to complete..."); while (token == null) { SysConsole.Write("."); Task.Delay(500).Wait(); } string settings = "ClientId=" + opts_.ClientId + "\r\n"; settings += "ClientSecret=" + opts_.ClientSecret + "\r\n"; settings += "RefreshToken=" + token.RefreshToken + "\r\n"; Clipboard.SetText(settings); SysConsole.WriteLine(""); SysConsole.WriteLine("Token received. Set the following settings in your web parser parent measure:"); SysConsole.WriteLine("---"); SysConsole.WriteLine(settings); SysConsole.WriteLine("---"); SysConsole.WriteLine("(the settings have been copied to your clipboard as well)"); return(0); }
public static async void DoAuthAsync() { AuthorizationCodeAuth auth = new AuthorizationCodeAuth( clientId, clientSecret, // "https://concert-companion.appspot.com", // "https://concert-companion.appspot.com", "concert-companion:/", // "http://localhost:4002", "http://localhost:4002", Scope.UserFollowRead | Scope.UserReadPrivate | Scope.UserTopRead | Scope.UserReadEmail | Scope.PlaylistReadCollaborative ); auth.AuthReceived += async(sender, payload) => { auth.Stop(); Token token = await auth.ExchangeCode(payload.Code); SpotifyWebAPI api = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; PrivateProfile profile = api.GetPrivateProfile(); Paging <FullArtist> artists = api.GetUsersTopArtists(); UserProfile userProfile = new UserProfile() { Id = profile.Id, Name = profile.DisplayName, Email = profile.Email, TopArtists = artists.Items.Select(artist => new Artist() { Id = artist.Id, Name = artist.Name }).ToList() }; SaveUser(userProfile); // Do requests with API client }; Console.WriteLine("Starting the server"); auth.Start(); // Starts an internal HTTP Server Console.WriteLine("Opening the browser"); auth.OpenBrowser(); }
private static void AuthSpotify() { s_SpotifyAuth.AuthReceived += async(_, payload) => { s_SpotifyAuth.Stop(); var token = await s_SpotifyAuth.ExchangeCode(payload.Code); s_SpotifyAPI = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken }; s_SpotifyToken = token; s_SpotifyConnected = true; }; s_SpotifyAuth.Start(); s_SpotifyAuth.OpenBrowser(); }
private async void LoggedInSuccessfully(object sender, AuthorizationCode payload) { AuthorizationCodeAuth auth = (AuthorizationCodeAuth)sender; auth.Stop(); Dispatcher.Invoke(DispatcherPriority.Render, new Action(() => GoToMainPage())); Token token = await auth.ExchangeCode(payload.Code); webApi = new SpotifyWebAPI { AccessToken = token.AccessToken, TokenType = token.TokenType }; StartPoller(auth, token); }
private async void AuthOnAuthReceived(object sender, AuthorizationCode payload) { _authorizationCodeAuth = (AuthorizationCodeAuth)sender; _authorizationCodeAuth.Stop(); try { _token = await _authorizationCodeAuth.ExchangeCode(payload.Code); _refreshToken = _token.RefreshToken; _connectionDialogOpened = false; } catch { // ignored } }
private async void AuthAPI() { //Source: //https://github.com/JohnnyCrazy/SpotifyAPI-NET //If token isn't set, or has expired if (m_instance.m_authToken == null || m_instance.m_authToken.IsExpired()) { string redirectURI = "http://localhost:4002"; AuthorizationCodeAuth auth = new AuthorizationCodeAuth( m_instance.m_clientID, m_instance.m_clientSecret, redirectURI, redirectURI, m_accessScopes); auth.AuthReceived += async(sender, payload) => { auth.Stop(); //Sender is also the auth instance m_instance.m_authToken = await auth.ExchangeCode(payload.Code); m_spotifyWebAPI = new SpotifyWebAPI() { //TokenType = payload.TokenType, TokenType = m_instance.m_authToken.TokenType, //AccessToken = payload.AccessToken AccessToken = m_instance.m_authToken.AccessToken, UseAuth = true }; m_instance.m_pollingTask = Task.Run(PollSongChange);//Start the song change polling m_instance.m_onAuthComplete.Invoke(GetLatestTrack()); }; auth.Start(); //Starts an internal http server auth.OpenBrowser(); //Opens brower to authenticate app } }