Exemple #1
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
            };
        }
Exemple #2
0
        async static void RunTest()
        {
            //getting country of user
            string name         = GetRegion();
            var    analysedtext = await RazorAPI.AnalyseText("test", 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
                };
                var profile = await api.GetPrivateProfileAsync();

                Console.WriteLine(JsonConvert.SerializeObject(profile, Formatting.Indented));
                // 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;
                }
                Console.WriteLine(newsapiresults);
                Console.WriteLine(newsapiresults.totalResults);
                foreach (var result in newsapiresults.articles)
                {
                    //Console.WriteLine();
                    Console.WriteLine(result.title);
                }


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

                if (spotifyresults == null)
                {
                    return;
                }

                Console.WriteLine(JsonConvert.SerializeObject(spotifyresults, Formatting.Indented));
            };

            auth.Start(); // Starts an internal HTTP Server
            auth.OpenBrowser();
        }
        public SpotifyModel GetSpotifyModel()
        {
            _auth = new ImplicitGrantAuth
            {
                RedirectUri = "http://localhost:8000",
                ClientId = "26d287105e31491889f3cd293d85bfea",
                Scope = Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistReadPrivate | Scope.UserLibrarayRead | Scope.UserReadPrivate | Scope.UserFollowRead | Scope.UserReadBirthdate,
                State = "XSS"
            };
            _auth.OnResponseReceivedEvent += _auth_OnResponseReceivedEvent;

            _auth.StartHttpServer(8000);
            _auth.DoAuth();

            SpotifyModel sm = new SpotifyModel();
            _spotifyLocal = new SpotifyLocalAPI();

            if (!SpotifyLocalAPI.IsSpotifyRunning())
            {
                return sm;
            }
            if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning())
            {
                return sm;
            }

            bool successful = _spotifyLocal.Connect();
            if (successful)
            {
                UpdateInfos();
                _spotifyLocal.ListenForEvents = true;
                sm.IsPlaying = true;
                try
                {
                    sm.SongTitle = _currentTrack.TrackResource.Name;
                    sm.VotedItemsDictionary = GetDictionaryDetails(sm.SongTitle);
                    sm.SongArtist = _currentTrack.ArtistResource.Name;

                    Bitmap derp = new Bitmap(_currentTrack.GetAlbumArt(AlbumArtSize.Size320));
                    Byte[] imgFile;
                    var stream = new MemoryStream();
                    derp.Save(stream, ImageFormat.Png);
                    imgFile = stream.ToArray();
                    sm.SongAlbumArt = _currentTrack.GetAlbumArtUrl(AlbumArtSize.Size320);
                    sm.IsPlaying = true;
                    stream.Close();
                    sm.Tracks = GetPlaylists();
                    int index = 0;
                    foreach (var track in sm.Tracks)
                    {
                        if (track.title.Equals(_currentTrack.TrackResource.Name))
                        {
                            break;
                        }
                        index++;
                    }
                    if (index == 0)
                        index++;
                    sm.PreviousSongAlbumArt = sm.Tracks[index - 1].albumArt;
                    sm.PreviousSongTitle = sm.Tracks[index - 1].title;
                    sm.PreviousSongArtist = sm.Tracks[index - 1].artist;
                    if (index + 1 >= sm.Tracks.Count)
                        index = 0;
                    else
                        index++;
                    sm.NextSongAlbumArt = sm.Tracks[index].albumArt;
                    sm.NextSongTitle = sm.Tracks[index].title;
                    sm.NextSongArtist = sm.Tracks[index].artist;

                    _auth = null;
                    _spotifyLocal = null;
                    _spotify = null;
                }
                catch (Exception e)
                {
                }
            }

            if (Winner)
            {
                sm.Truncate();
                Winner = false;
            }

            string ip = Request.UserHostAddress;
            sm.IsValidIP = sm.IsValidVote(ip);
            return sm;
        }
        //***********************************************************************************************************************************************************************************************************

        /// <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);
            }
        }