Exemplo n.º 1
0
        private static void OldWay()
        {
            //Create the auth object
            auth = new AutorizationCodeAuth()
            {
                //Your client Id
                ClientId = "4ba8934628a54571b57ed84de51d1825",
                //Set this to localhost if you want to use the built-in HTTP Server
                RedirectUri = "http://localhost:8000",
                //How many permissions we need?
                Scope      = Scope.UserReadPrivate | Scope.PlaylistModifyPublic | Scope.PlaylistModifyPrivate,
                ShowDialog = true
            };
            //This will be called, if the user cancled/accept the auth-request
            auth.OnResponseReceivedEvent += auth_OnResponseReceivedEvent;
            //a local HTTP Server will be started (Needed for the response)
            auth.StartHttpServer(8000);
            //This will open the spotify auth-page. The user can decline/accept the request

            try
            {
                auth.DoAuth();
                Thread.Sleep(60000);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            auth.StopHttpServer();
            Console.WriteLine("Too long, didnt respond, exiting now...");
        }
Exemplo n.º 2
0
        private static void _callback(AutorizationCodeAuthResponse response)
        {
            var token = _auth.ExchangeAuthCode(response.Code, _clientSecret);

            Console.WriteLine(token.RefreshToken);

            _auth.StopHttpServer();
        }
Exemplo n.º 3
0
        public void RequestAuth(AutorizationCodeAuth.OnResponseReceived codeReceiveCallback)
        {
            if (AuthRequesting)
            {
                return;
            }

            AuthRequesting = true;

            AutorizationCodeAuth auth = new AutorizationCodeAuth();

            auth.ClientId    = ClientId;
            auth.RedirectUri = RedirUri;
            auth.Scope       = Scope;

            auth.OnResponseReceivedEvent += response =>
            {
                AuthRequesting = false;
                auth.StopHttpServer();
                codeReceiveCallback.Invoke(response);
            };

            auth.StartHttpServer(RedirPort);

            auth.DoAuth();

            int ms = 0;

            while (ms < 30000)
            {
                if (!AuthRequesting)
                {
                    break;
                }

                Thread.Sleep(100);
                ms += 100;
            }

            if (AuthRequesting)
            {
                auth.StopHttpServer();
                AuthRequesting = false;
            }
        }
Exemplo n.º 4
0
        private void Auth_OnResponseReceivedEvent(AutorizationCodeAuthResponse response)
        {
            _auth.StopHttpServer();

            Token token = _auth.ExchangeAuthCode(response.Code, "9fde3d021e9f424e8740f1ab3f755bf6");

            var spotify = new SpotifyWebAPI()
            {
                TokenType   = token.TokenType,
                AccessToken = token.AccessToken
            };

            var tracks     = spotify.GetPlaylistTracks(UserID, PlaylistID);
            var tracksList = new List <TrackModel>();

            tracks.Items = tracks.Items.Where(da => da.AddedAt >= AfterDate).ToList();

            if (tracks.Total >= 100)
            {
                for (int i = 100; i <= tracks.Total + 100; i += 100)
                {
                    tracks.Items.ForEach(track => Console.WriteLine(track.Track.Artists.FirstOrDefault().Name + " - " + track.Track.Name));
                    tracks.Items.ForEach(track => tracksList.Add(new TrackModel()
                    {
                        Artist = track.Track.Artists.FirstOrDefault().Name,
                        Album  = track.Track.Album.Name,
                        Name   = track.Track.Name,
                        Images = track.Track.Album.Images
                    }));
                    tracks       = spotify.GetPlaylistTracks(UserID, PlaylistID, "", 100, i);
                    tracks.Items = tracks.Items.OrderByDescending(d => d.AddedAt).Where(da => da.AddedAt >= AfterDate).ToList();
                }
            }
            else
            {
                tracks.Items.ForEach(track => Console.WriteLine(track.Track.Artists.FirstOrDefault().Name + " " + track.Track.Name));
                tracks.Items.ForEach(track => tracksList.Add(new TrackModel()
                {
                    Artist = track.Track.Artists.FirstOrDefault().Name,
                    Album  = track.Track.Album.Name,
                    Name   = track.Track.Name,
                    Images = track.Track.Album.Images
                }));
            }

            Parallel.ForEach(tracksList, (track) =>
            {
                new YoutubeSearchService().YoutubeSearchTrack(track).Wait();
            });

            Console.WriteLine("Gotovo bratishka at " + DateTime.Now.TimeOfDay);
            Console.ReadKey();
            //With the token object, you can now make API calls
        }
Exemplo n.º 5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="response"></param>
        private static void auth_OnResponseReceivedEvent(AutorizationCodeAuthResponse response)
        {
            //NEVER DO THIS! You would need to provide the ClientSecret.
            //You would need to do it e.g via a PHP-Script.
            Token token = auth.ExchangeAuthCode(response.Code, "714ba0785d9b41d3828a7ad30c782d52");

            //Stop the HTTP Server, done.
            auth.StopHttpServer();

            _tokenType   = token.TokenType;
            _accessToken = token.AccessToken;
        }
Exemplo n.º 6
0
        private void OnAuthResponseReceived(AutorizationCodeAuthResponse response)
        {
            var token = auth.ExchangeAuthCode(response.Code, Configuration.Comms.ClientSecret);

            if (string.IsNullOrWhiteSpace(token.Error))
            {
                Configuration.Comms.AuthToken = token;
            }
            else
            {
                MessageBox.Show($"Error authenticating: {token.Error}\n\n{token.ErrorDescription}", "Auth Error");
            }

            auth.StopHttpServer();
        }
Exemplo n.º 7
0
        public void Authenticate()
        {
            AutorizationCodeAuth authentication = new AutorizationCodeAuth
            {
                RedirectUri = new UriBuilder("http://127.0.0.1")
                {
                    Port = 7476
                }.Uri.OriginalString.TrimEnd('/'),
                ClientId = _clientId,
                Scope    = _scope,
                State    = "XSS"
            };

            // Try refreshing
            var token = authentication.RefreshToken(Properties.Settings.Default.RefreshToken, _clientSecret);

            if (token.Error == null)
            {
                WebAPI = ApiFromToken(token);
                return;
            }

            AutoResetEvent authenticationWaitFlag = new AutoResetEvent(false);

            WebAPI = null;
            authentication.OnResponseReceivedEvent += (response) =>
            {
                WebAPI = HandleSpotifyResponse(response, authentication);
                authenticationWaitFlag.Set();
            };

            try
            {
                authentication.StartHttpServer(7476);

                authentication.DoAuth();

                authenticationWaitFlag.WaitOne(TimeSpan.FromSeconds(_timeout));
                if (WebAPI == null)
                {
                    throw new TimeoutException($"No valid response received for the last {_timeout} seconds");
                }
            }
            finally
            {
                authentication.StopHttpServer();
            }
        }
Exemplo n.º 8
0
        private static void auth_OnResponseReceivedEvent(AutorizationCodeAuthResponse response)
        {
            //NEVER DO THIS! You would need to provide the ClientSecret.
            //You would need to do it e.g via a PHP-Script.
            token = auth.ExchangeAuthCode(response.Code, MYSPOTIFY_SECRET);

            SPOTIFY_INST = new SpotifyWebAPI()
            {
                TokenType   = token.TokenType,
                AccessToken = token.AccessToken
            };

            //With the token object, you can now make API calls

            //Stop the HTTP Server, done.
            auth.StopHttpServer();
        }
Exemplo n.º 9
0
        public Task <SpotifyWebAPI> GetWebApi()
        {
            var authentication = new AutorizationCodeAuth
            {
                RedirectUri = $"{_redirectUrl}:{_listeningPort}",
                ClientId    = _clientId,
                Scope       = _scope,
                State       = _xss
            };

            AutoResetEvent authenticationWaitFlag = new AutoResetEvent(false);
            SpotifyWebAPI  spotifyWebApi          = null;

            authentication.OnResponseReceivedEvent += (response) =>
            {
                var state = response.State;
                var token = authentication.ExchangeAuthCode(response.Code, _clientSecret);
                spotifyWebApi = HandleSpotifyResponse(state, token);



                authenticationWaitFlag.Set();
            };

            try
            {
                authentication.StartHttpServer(_listeningPort);

                authentication.DoAuth();

                authenticationWaitFlag.WaitOne(_timeout);
                if (spotifyWebApi == null)
                {
                    throw new TimeoutException($"No valid response received for the last {_timeout.TotalSeconds} seconds");
                }
            }
            finally
            {
                authentication.StopHttpServer();
            }

            return(Task.FromResult(spotifyWebApi));
        }
Exemplo n.º 10
0
        private static void auth_OnResponseReceivedEvent(AutorizationCodeAuthResponse response)
        {
            //Stop the HTTP Server, done.
            auth.StopHttpServer();

            //NEVER DO THIS! You would need to provide the ClientSecret.
            //You would need to do it e.g via a PHP-Script.
            Token token = auth.ExchangeAuthCode(response.Code, "94486431428d4c0b95ea40897c73b13f");

            Console.WriteLine($"{token.AccessToken}");
            Console.WriteLine($"{token.RefreshToken}");
            Console.ReadKey();
            //var spotify = new SpotifyWebApiClass()
            //{
            //    TokenType = token.TokenType,
            //    AccessToken = token.AccessToken
            //};

            //With the token object, you can now make API calls
        }
Exemplo n.º 11
0
        private static void Authorize(CommandLineApplication command)
        {
            var clientIdOption = command.Option("-c|--clientId <clientId>", "The application client id", CommandOptionType.SingleValue);

            var clientSecretOption = command.Option("-k|--clientSecret <clientSecret>", "The application client secret", CommandOptionType.SingleValue);

            var scopeOption = command.Option("-s|--scope <scope>", "The application client secret", CommandOptionType.MultipleValue);

            var outputOption = command.Option("-o|--output <path>", "Path to output token as json", CommandOptionType.SingleValue);

            var browserPathOption = command.Option("-b|--browser <path>", "Path to the browser to start", CommandOptionType.SingleValue);

            command.OnExecute(
                () =>
            {
                TaskCompletionSource <string> tcs = new TaskCompletionSource <string>();

                Scope scope = scopeOption.Values
                              .Select(v => Enum.Parse <Scope>(v))
                              .Aggregate(new Scope(), (a, s) => a | s);

                var auth = new AutorizationCodeAuth()
                {
                    ClientId      = clientIdOption.Value(),
                    RedirectUri   = "http://localhost",
                    Scope         = scope,
                    ShowDialog    = true,
                    OpenUriAction = uri => Process.Start(new ProcessStartInfo {
                        FileName = browserPathOption.Value(), Arguments = uri
                    })
                };

                auth.OnResponseReceivedEvent += response =>
                {
                    Token token = auth.ExchangeAuthCode(response.Code, clientSecretOption.Value());
                    string json = JsonConvert.SerializeObject(token);
                    tcs.SetResult(json);
                };

                try
                {
                    try
                    {
                        auth.StartHttpServer();
                        auth.DoAuth();

                        Task.WaitAll(new[] { tcs.Task }, TimeSpan.FromSeconds(30));

                        using (var stream = File.OpenWrite(outputOption.Value()))
                        {
                            using (var writer = new StreamWriter(stream))
                            {
                                writer.Write(tcs.Task.Result);
                            }
                        }

                        Console.WriteLine($"Successfully wrote token to '{outputOption.Value()}'");

                        return(0);
                    }
                    finally
                    {
                        auth.StopHttpServer();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Failed to retrieve token: '{e.Message}'");

                    return(-1);
                }
            }
                );
        }