public Task AuthorizeAsync()
        {
            var tcs = new TaskCompletionSource <bool>();

            var auth = new ImplicitGrantAuth(ClientId, "http://localhost:4002", "http://localhost:4002", Scope.UserReadPrivate | Scope.PlaylistReadPrivate | Scope.UserLibraryRead |
                                             Scope.PlaylistModifyPrivate | Scope.PlaylistModifyPublic | Scope.PlaylistReadCollaborative);

            auth.AuthReceived += async(_, payload) =>
            {
                auth.Stop();

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

                IsAuthorized = true;
                var profile = await spotify.GetPrivateProfileAsync();

                Profile = new Profile
                {
                    Id       = profile.Id,
                    Username = profile.DisplayName
                };

                tcs.SetResult(true);
            };

            auth.Start();
            auth.OpenBrowser();

            return(tcs.Task);
        }
    static void CredentialsAuth(string ClientID)
    {
        ImplicitGrantAuth auth = new ImplicitGrantAuth(
            ClientID,
            "http://localhost:4002",
            "http://localhost:4002",
            Scope.UserLibraryModify | Scope.PlaylistModifyPrivate |
            Scope.PlaylistModifyPublic | Scope.PlaylistReadPrivate |
            Scope.PlaylistReadPrivate | Scope.PlaylistReadCollaborative |
            Scope.UserLibraryRead | Scope.UserLibraryModify |
            Scope.UserReadPrivate | Scope.UserReadEmail
            );

        auth.AuthReceived += (sender, payload) =>
        {
            auth.Stop();
            spotify = new SpotifyWebAPI()
            {
                TokenType   = payload.TokenType,
                AccessToken = payload.AccessToken
            };

            profile = spotify.GetPrivateProfile();

            completed = true;
        };
        auth.Start();
        auth.OpenBrowser();
    }
Пример #3
0
        public async Task <DateTime> ConnectAsync()
        {
            try
            {
                if (!HasInitialConfig())
                {
                    return(DateTime.Now);
                }

                ImplicitGrantAuth auth = new ImplicitGrantAuth(
                    _botConfig.SpotifyClientId,
                    _botConfig.SpotifyRedirectUri,
                    _botConfig.SpotifyServerUri,
                    Scope.UserReadCurrentlyPlaying
                    | Scope.UserReadPlaybackState
                    | Scope.UserModifyPlaybackState);

                auth.AuthReceived += OnAuthReceived;
                auth.Start();
                auth.OpenBrowser();
            }
            catch (Exception ex)
            {
                await _errHndlrInstance.LogError(ex, "TwitchBotApplication", "Connect()", false);
            }

            return(DateTime.Now);
        }
Пример #4
0
        public void Login(Action onSucces)
        {
            var auth = new ImplicitGrantAuth(
                _settingsProvider.SpotifyClientId,
                _settingsProvider.SpotifyRedirectUri,
                _settingsProvider.SpotifyRedirectUri,
                Scope.UserReadPrivate |
                Scope.PlaylistModifyPrivate |
                Scope.PlaylistModifyPublic |
                Scope.PlaylistReadCollaborative |
                Scope.PlaylistReadPrivate
                );

            auth.AuthReceived += (sender, payload) =>
            {
                auth.Stop();

                Api = new SpotifyWebAPI()
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };

                onSucces.Invoke();
            };

            auth.Start();
            auth.OpenBrowser();
        }
Пример #5
0
        public async static Task <SpotifyWebAPI> UserLogin(string apikey)
        {
            return(await Task.Run(async() => {
                var auth = new ImplicitGrantAuth(
                    apikey,
                    "http://localhost:4002",
                    "http://localhost:4002",
                    Scope.UserReadPrivate
                    );
                SpotifyWebAPI api = null;
                auth.AuthReceived += async(sender, payload) =>
                {
                    auth.Stop(); // `sender` is also the auth instance
                    api = new SpotifyWebAPI()
                    {
                        TokenType = payload.TokenType,
                        AccessToken = payload.AccessToken
                    };
                };

                auth.Start(); // Starts an internal HTTP Server
                auth.OpenBrowser();
                while (api == null)
                {
                    await Task.Delay(100);
                }

                return api;
            }));
        }
Пример #6
0
        static void Main(string[] args)
        {
            parameters = args;

            ImplicitGrantAuth auth = new ImplicitGrantAuth(
                "6124e12cbb1c4e779faf7f0b52f42c51",
                "http://localhost:4002",
                "http://localhost:4002",
                Scope.UserReadPrivate | Scope.PlaylistModifyPublic | Scope.PlaylistModifyPrivate
                );

            auth.AuthReceived += async(sender, payload) =>
            {
                Console.Clear();
                auth.Stop();
                _spotify = new SpotifyWebAPI()
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };
                _user = _spotify.GetPublicProfile("sergiorgiraldo");
                DoThings();
            };
            auth.Start();
            auth.OpenBrowser();
            Console.ReadLine();
            auth.Stop(0);
        }
Пример #7
0
        public Task <bool> ConnectToSpotifyOAuth()
        {
            _taskComplete = new TaskCompletionSource <bool>();
            ImplicitGrantAuth auth = new ImplicitGrantAuth(
                _planetOfSoundClientId,
                "http://localhost:4002",
                "http://localhost:4002",
                Scope.UserModifyPlaybackState
                );

            auth.AuthReceived += async(sender, payload) =>
            {
                auth.Stop(); // `sender` is also the auth instance

                // Get the Spotify API object (needs the access token)
                _spotify = new SpotifyWebAPI
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };

                _taskComplete.SetResult(true);
            };

            auth.Start(); // Starts an internal HTTP Server
            auth.OpenBrowser();

            return(_taskComplete.Task);
        }
Пример #8
0
        async static void Example()
        {
            //getting country of user
            string name         = RegionInfo.CurrentRegion.EnglishName;
            var    analysedtext = await RazerApi.AnalyseText(File.ReadAllText("test.txt"));

            var auth = new ImplicitGrantAuth(
                "7f08980f1dae4f3d98a40d44ef235b03",
                "http://localhost:4002",
                "http://localhost:4002",
                Scope.UserReadPrivate
                );

            auth.AuthReceived += async(sender, payload) =>
            {
                auth.Stop(); // `sender` is also the auth instance
                var api = new SpotifyWebAPI()
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };
                // FeaturedPlaylists playlists = api.GetFeaturedPlaylists();
                //Console.WriteLine(playlists.Message);
                //playlists.Playlists.Items.ForEach(playlist => Console.WriteLine(playlist.Name));

                //getting playlists from categories and outputting names and links of the playlist.
                CategoryPlaylist playlists = api.GetCategoryPlaylists("party");
                playlists.Playlists.Items.ForEach(playlist => Console.WriteLine("Playlist Name: " + playlist.Name + ",\nLink: " + playlist.Uri));

                // Do requests with API client
                var newsapiresults = await NewsApi.SearchByKeyword("bitcoin", name);

                if (newsapiresults == null)
                {
                    return;
                }
                Debug.WriteLine(newsapiresults);
                Debug.WriteLine(newsapiresults.totalResults);
                foreach (var result in newsapiresults.articles)
                {
                    //Console.WriteLine();
                    Debug.WriteLine(result.title);
                }


                var spotifyresults = await api.SearchItemsAsync("drake", SearchType.All);

                if (spotifyresults == null)
                {
                    return;
                }

                Console.WriteLine(spotifyresults);
            };

            auth.Start(); // Starts an internal HTTP Server
            auth.OpenBrowser();
        }
Пример #9
0
        private async void btnExport_Click(object sender, EventArgs e)
        {
            var auth = new ImplicitGrantAuth(
                _clientId,
                "http://*****:*****@"SpotifyPlaylist.m3u", true))
                {
                    foreach (var song in _tracks)
                    {
                        Console.WriteLine(song.Uri);
                        file.WriteLine(song.Uri);
                    }
                }

                Console.WriteLine("DONE");
            };
        }
        public void Authorise(string _clientId)
        {
            ImplicitGrantAuth auth = new ImplicitGrantAuth(_clientId,
                                                           "http://localhost:4002", "http://localhost:4002",
                                                           Scope.UserLibraryModify | Scope.PlaylistModifyPrivate | Scope.PlaylistModifyPublic);

            auth.AuthReceived += (sender, payload) =>
            {
                auth.Stop();
                _spotify.TokenType   = payload.TokenType;
                _spotify.AccessToken = payload.AccessToken;
            };
            auth.Start();
            auth.OpenBrowser();
        }
        //private static SpotifyWebAPI _spotify;
        public MainWindow()
        {
            InitializeComponent();
            //_spotify = new SpotifyWebAPI()
            //{
            //    UseAuth = false,
            //};
            //FullTrack track = _spotify.GetTrack("da3e0a9c9ef44b03b0867f5fcef7c155");
            //Console.WriteLine(track.Name);

            ImplicitGrantAuth auth = new ImplicitGrantAuth("da3e0a9c9ef44b03b0867f5fcef7c155", "http://localhost:4002", "http://localhost:4002", Scope.UserReadPrivate);

            auth.AuthReceived += (sender, playload) =>
            {
                auth.Stop();
                SpotifyWebAPI api = new SpotifyWebAPI()
                {
                    TokenType = playload.TokenType, AccessToken = playload.AccessToken
                };
            };

            auth.Start();
            auth.OpenBrowser();

            //CredentialsAuth auth = new CredentialsAuth("da3e0a9c9ef44b03b0867f5fcef7c155", "8cf189c167384e71abda96d728bf305f");
            //Token token = await auth.GetToken();
            //SpotifyWebAPI api = new SpotifyWebAPI() { TokenType = token.TokenType, AccessToken = token.AccessToken };


            //TokenSwapWebAPIFactory webAPIFactory;
            //SpotifyWebAPI spotify;

            //webAPIFactory = new TokenSwapWebAPIFactory("INSERT LINK TO YOUR index.php HERE")
            //{
            //    Scope = Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistModifyPrivate,
            //    AutoRefresh = true

            //};

            //try
            //{
            //    spotify = webAPIFactory.GetWebApiAsync().Result;
            //}
            //catch (Exception ex)
            //{

            //}
        }
Пример #12
0
        public static void Example()
        {
            //getting country of user
            string name = RegionInfo.CurrentRegion.EnglishName;

            Console.WriteLine(name);

            var auth = new ImplicitGrantAuth(
                "7f08980f1dae4f3d98a40d44ef235b03",
                "http://localhost:4002",
                "http://localhost:4002",
                Scope.UserReadPrivate
                );

            auth.AuthReceived += async(sender, payload) =>
            {
                auth.Stop();     // `sender` is also the auth instance
                var api = new SpotifyWebAPI()
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };
                // Do requests with API client
                var newsapiresults = await NewsApi.SearchByKeyword("bitcoin", name);

                if (newsapiresults == null)
                {
                    return;
                }
                Debug.WriteLine(newsapiresults);
                Debug.WriteLine(newsapiresults.totalResults);
                foreach (var result in newsapiresults.articles)
                {
                    Console.WriteLine(result.title);
                    Console.WriteLine();
                }
                var spotifyresults = await api.SearchItemsAsync("drake", SearchType.All);

                if (spotifyresults == null)
                {
                    return;
                }
            };
            auth.Start();     // Starts an internal HTTP Server
            auth.OpenBrowser();
        }
Пример #13
0
        static void Main()
        {
            //start menu
            Console.WriteLine("Main menu");
            Console.WriteLine("Save Saved Tracks to Playlist");
            Console.WriteLine("Type number of selected option and press enter");
            Console.WriteLine("Select what do you want to do:");
            Console.WriteLine("[1] Save all tracks from library to playlist or update existing");
            Console.WriteLine("[2] Tracks features");
            Console.WriteLine("[0] Close");

            //gets user input
            if (short.TryParse(Console.ReadLine(), out short select))
            {
                Controller.Select = select;
            }
            else
            {
                Console.WriteLine("It's not a number!");
                Console.WriteLine("\nPress any key to continue. . .");
                Console.ReadKey();
                Environment.Exit(0);
            }

            if (Controller.Select != 1 && Controller.Select != 2)
            {
                Environment.Exit(0);
            }

            var auth = new ImplicitGrantAuth(AuthorizationCredits.Authcode, "http://localhost:4002", "http://localhost:4002", Scope.UserLibraryRead | Scope.UserReadPrivate | Scope.PlaylistModifyPublic);

            auth.AuthReceived += AuthOnAuthReceived;
            auth.Start();
            auth.OpenBrowser();
            Controller.WaitEvent.WaitOne();
            Console.WriteLine("Closing connection...");
            auth.Stop();
            Console.WriteLine("Connection closed.");
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Пример #14
0
        public static void SpotifyInit()
        {
            //  SpotifyAPI.Web.Auth.ImplictGrantAuth
            var auth =
                new ImplicitGrantAuth(ClientId, "http://localhost:8080", "http://localhost:8080",
                                      Scope.PlaylistReadCollaborative);

            auth.AuthReceived += (_, payload) =>
            {
                auth.Stop(); // `sender` is also the auth instance
                Api = new SpotifyWebAPI {
                    TokenType = payload.TokenType, AccessToken = payload.AccessToken
                };
                // Do requests with API client
                var profile = Api.GetPrivateProfile();
                UserId = profile.Id;
            };
            auth.Start(); // Starts an internal HTTP Server

            auth.OpenBrowser();
        }
Пример #15
0
        private async Task <SpotifyWebAPI> InitialiseFromBrowser()
        {
            var source = new TaskCompletionSource <Token>();

            void OnImplicitGrantAuthOnAuthReceived(object sender, Token payload)
            {
                implicitGrantAuth.Stop();

                if (payload.HasError())
                {
                    source.SetException(new SpotifyWebApiException(payload.Error, payload.ErrorDescription));
                    return;
                }

                source.SetResult(payload);
            }

            implicitGrantAuth.AuthReceived += OnImplicitGrantAuthOnAuthReceived;

            implicitGrantAuth.Start();
            implicitGrantAuth.OpenBrowser();

            try
            {
                var token = await source.Task;

                settingsProvider.TokenType   = token.TokenType;
                settingsProvider.AccessToken = token.AccessToken;

                return(new SpotifyWebAPI
                {
                    AccessToken = token.AccessToken,
                    TokenType = token.TokenType
                });
            }
            finally
            {
                implicitGrantAuth.AuthReceived -= OnImplicitGrantAuthOnAuthReceived;
            }
        }
Пример #16
0
        static async void SpotifyAuth(string[] args)
        {
            ImplicitGrantAuth auth = new ImplicitGrantAuth(
                "2993fe290e1744158bdec14aa8016ebd",
                "http://localhost:4002",
                "http://localhost:4002",
                Scope.UserReadPlaybackState | Scope.UserModifyPlaybackState | Scope.UserReadCurrentlyPlaying
                );

            auth.AuthReceived += async(sender, payload) =>
            {
                auth.Stop(); // `sender` is also the auth instance
                _spotify = new SpotifyWebAPI()
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };
                // Do requests with API client
            };
            auth.Start(); // Starts an internal HTTP Server
            auth.OpenBrowser();
        }
Пример #17
0
        public static void Main()
        {
            auth = new ImplicitGrantAuth(
                _clientId,
                "http://localhost:4002/callback",
                "http://localhost:4002/callback",
                Scope.UserReadPrivate
                );
            auth.AuthReceived += (sender, payload) =>
            {
                auth.Stop(); // `sender` is also the auth instance
                _spotify = new SpotifyWebAPI()
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };
                // Do requests with API client
            };
            auth.Start(); // Starts an internal HTTP Server
            auth.OpenBrowser();



            PrivateProfile profile = _spotify.GetPrivateProfile();

            if (profile.HasError())
            {
                Console.WriteLine("Error Status: " + profile.Error.Status);
                Console.WriteLine("Error Msg: " + profile.Error.Message);
            }


            FullTrack track = _spotify.GetTrack("3FFjdo3CSKqeGx3nlN0WWv?si=4xDdGmMaTJ-FpPDdQi8MRA");

            Console.WriteLine(track.Name);        //Yeay! We just printed a tracks name.
            Console.WriteLine(track.Popularity);  //Yeay! We just printed a tracks name.
            Console.WriteLine(track.TrackNumber); //Yeay! We just printed a tracks name.
            Console.ReadLine();
        }
Пример #18
0
        private void AuthenticateSpotify()
        {
            ImplicitGrantAuth auth = new ImplicitGrantAuth(
                APIKeys.spotifyClientID,
                "http://localhost:4002",
                "http://localhost:4002",
                Scope.UserReadPlaybackState | Scope.UserModifyPlaybackState
                );

            auth.AuthReceived += async(sender, payload) =>
            {
                auth.Stop();
                spotifyWebAPI = new SpotifyWebAPI()
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };
            };
            auth.Start();
            auth.OpenBrowser();
            StartSpotifySeekerLogic();
        }
Пример #19
0
        private async void btnUpload_Click(object sender, EventArgs e)
        {
            _failedTofindSongs           = new List <MusicItem>();
            _completelyFailedTofindSongs = new List <MusicItem>();

            var auth = new ImplicitGrantAuth(
                _clientId,
                "http://localhost:4002",
                "http://localhost:4002",
                Scope.UserLibraryModify | Scope.PlaylistModifyPrivate
                );

            auth.Start();
            auth.OpenBrowser();

            auth.AuthReceived += async(s, payload) =>
            {
                auth.Stop();
                _spotifyAPI = new SpotifyWebAPI()
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };

                String       line;
                String       artist = "testing";
                Boolean      found  = false;
                StreamReader file   = new StreamReader(_playlistLocation);

                List <MusicItem> musicItems = new List <MusicItem>();

                while ((line = file.ReadLine()) != null && !String.IsNullOrWhiteSpace(line))
                {
                    //line example: D:\Users\Paul\Music\Paul Music\Plus44\When Your Heart Stops Beating\12-plus_44-chapter_xiii.mp3
                    string[] artistPlusSong = null;
                    string[] slashPlusRest  = null;

                    try
                    {
                        artistPlusSong = line.Split(new string[] { "Paul Music\\" }, StringSplitOptions.None);
                        slashPlusRest  = artistPlusSong[1].Split('\\');
                        var musicItem = new MusicItem(line, slashPlusRest[0], Path.GetFileNameWithoutExtension(slashPlusRest[1]));
                        musicItems.Add(musicItem);
                        artist = slashPlusRest[0].ToLower();
                    }
                    catch (System.IndexOutOfRangeException ex)
                    {
                        System.Console.WriteLine(line);
                    }
                }

                FullPlaylist playlist = null;

                if (!debug)
                {
                    playlist = await _spotifyAPI.CreatePlaylistAsync(_spotifyAPI.GetPrivateProfile().Id, artist, false);
                }

                foreach (var music in musicItems) // find the song on Spotify and add to playlist
                {
                    String query = String.Format("artist:{0} track:{1}", music.artist, music.title);
                    await doSearch(query, music, _failedTofindSongs, playlist?.Id ?? "");
                }

                // need to try searching with tags instead of filename
                foreach (var failedMusic in _failedTofindSongs)
                {
                    var tFile = TagLib.File.Create(failedMusic.line);

                    if (!String.IsNullOrWhiteSpace(tFile.Tag.FirstAlbumArtist))
                    {
                        failedMusic.artist = tFile.Tag.FirstAlbumArtist;
                    }
                    else if (!String.IsNullOrWhiteSpace(tFile.Tag.FirstPerformer))
                    {
                        failedMusic.artist = tFile.Tag.FirstPerformer;
                    }
                    else if (!String.IsNullOrWhiteSpace(tFile.Tag.FirstArtist))
                    {
                        failedMusic.artist = tFile.Tag.FirstArtist;
                    }
                    else
                    {
                        Console.WriteLine(failedMusic.artist + " not in tags");
                    }

                    if (!String.IsNullOrWhiteSpace(tFile.Tag.Title))
                    {
                        failedMusic.title = tFile.Tag.Title;
                    }
                    else
                    {
                        Console.WriteLine(failedMusic.title + " not in tags");
                    }

                    String q = String.Format("artist:{0} track:{1}", failedMusic.artist, failedMusic.title);
                    await doSearch(q, failedMusic, _completelyFailedTofindSongs, playlist?.Id ?? "");
                }

                Console.WriteLine("LIST OF COMPLETELY FAILED: ");
                foreach (var failed in _completelyFailedTofindSongs)
                {
                    Console.WriteLine(failed.line);
                }

                //todo do tag online lookup
            };
        }
Пример #20
0
        //***********************************************************************************************************************************************************************************************************

        /// <summary>
        /// Connect to the Spotify Web API
        /// </summary>
        /// <param name="timeout_ms">Connection timeout in ms</param>
        /// <param name="forceReauthenticate">if true, force the user to reauthenticate to the player application</param>
        /// <returns>true on connection success, otherwise false</returns>
        /// see: https://johnnycrazy.github.io/SpotifyAPI-NET/SpotifyWebAPI/auth/#implicitgrantauth
        /// Use https://developer.spotify.com/dashboard/ to get a Client ID
        /// It should be noted, "http://*****:*****@"(\?|\&|#)([^=]+)\=([^&]+)"); // Extract the fields from the returned URL
                                MatchCollection matches = regex.Matches(urlFinal);
                                foreach (Match match in matches)
                                {
                                    if (match.Value.Contains("access_token"))
                                    {
                                        accessToken = match.Value.Replace("#access_token=", "");
                                    }
                                    else if (match.Value.Contains("token_type"))
                                    {
                                        tokenType = match.Value.Replace("&token_type=", "");
                                    }
                                    else if (match.Value.Contains("expires_in"))
                                    {
                                        ConnectionTokenExpirationTime = new TimeSpan(0, 0, int.Parse(match.Value.Replace("&expires_in=", "")));
                                    }
                                }

                                _spotifyWeb = new SpotifyWebAPI()
                                {
                                    TokenType = tokenType, AccessToken = accessToken
                                };
                                waitForAuthFinish.Set();        // Signal that the authentication finished

                                authWindowClosedByProgram = true;
                                authWindow.Close();
                            }
                            else
                            {
                                authWindow.WindowState = WindowState.Normal;
                                userInteractionWaiting = true;
                            }
                        };

                        authWindow.Closed += (sender, args) =>
                        {
                            waitForWindowClosed.Set();
                            if (!authWindowClosedByProgram)
                            {
                                waitForAuthFinish.Set();
                            }
                        };

                        webBrowser.Navigate(url);       // Navigate to spotifys login page to begin authentication. If credentials exist, you are redirected to an URL containing the access_token.
                        authWindow.ShowDialog();
                    }));
                    newThread.SetApartmentState(ApartmentState.STA);
                    newThread.Start();

                    waitForAuthFinish.WaitOne(timeout_ms);
                    if (userInteractionWaiting)
                    {
                        waitForWindowClosed.WaitOne(); waitForAuthFinish.WaitOne(timeout_ms);
                    }
                }
            });

            if (_spotifyWeb == null)
            {
                IsConnected = false; return(false);
            }
            else
            {
                _wasConnectionTokenExpiredEventRaised = false; IsConnected = true; return(true);
            }
        }