Example #1
0
        public async Task <List <string> > GetPlaylistTrackIDs(string playListID)
        {
            List <string> data = new List <string>();

            PrivateProfile profile = await api.GetPrivateProfileAsync();

            Paging <SimplePlaylist> playlists = await api.GetUserPlaylistsAsync(profile.Id);

            do
            {
                playlists.Items.ForEach(playlist =>
                {
                    if (playlist.Id.Equals(playListID))
                    {
                        FullPlaylist playlistData = api.GetPlaylist(profile.Id, playlist.Id);
                        do
                        {
                            playlistData.Tracks.Items.ForEach(track =>
                            {
                                data.Add(track.Track.Id);
                            });
                        } while (playlistData.Tracks.HasNextPage());
                    }
                });
            } while (playlists.HasNextPage());

            return(data);
        }
Example #2
0
        public FullPlaylist CreateAPlaylist(CreatePlaylistModel model)
        {
            Token          token   = GetToken();
            PrivateProfile profile = GetMe(token);

            if (profile.Id == null && token.RefreshToken != null)
            {
                string oldRefreshToken = token.RefreshToken;
                token = RefreshToken(token.RefreshToken, Constants.ClientSecret);
                token.RefreshToken = oldRefreshToken;
                _tokenService.SetToken(token);
                profile = GetMe(token);
            }

            SpotifyAPI.Web.SpotifyWebAPI api = new SpotifyWebAPI()
            {
                AccessToken = token.AccessToken, TokenType = token.TokenType
            };
            FullPlaylist fullPlaylist = api.CreatePlaylist(profile.Id, model.Name);

            if (fullPlaylist.HasError())
            {
                throw new Exception("Playlist can not be created");
            }

            return(fullPlaylist);
        }
Example #3
0
    // Use this for initialization
    void Start()
    {
        ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;

        ImplicitGrantAuth();

        context = _spotify.GetPlayback();

        Debug.Log("Device Id: " + context.Device.Id);

        shuffleState = context.ShuffleState;

        repeatState = context.RepeatState;

        privateProfile = _spotify.GetPrivateProfile();

        Debug.Log(privateProfile.Country);

        audioVisualizer = GameObject.Find("AudioVisualizer");

        audioVisualizerScript = audioVisualizer.GetComponent <AudioVisualizer>();

        featuredPlaylistTabScript = FeaturedPlaylistTab.GetComponent <FeaturedPlaylistTabScript>();

        searchResultsScript = searchResultsTab.GetComponent <SearchResultsScript>();

        currentSongScript = CurrentSongGameObject.GetComponent <CurrentSong>();

        recordPlayerScript = recordPlayer.GetComponent <RecordPlayer>();

        //Ignore collisions between character controller and vinyls
        Physics.IgnoreLayerCollision(8, 9);

        OnClicked += SendAudioAnaylisToParticleVisualizer;
    }
Example #4
0
            // Utility to convert Section into Object[]
            public static object[] ConvertProfileToObjectArray(PrivateProfile profile)
            {
                // Copy Section Names
                string[] section_names = new string[profile.Sections.Count];
                profile.Sections.Keys.CopyTo(section_names, 0);

                // Copy Entries
                string[][][] entries = new string[profile.Sections.Count][][];
                var          i       = 0;

                foreach (var section_name in profile.Sections.Keys)
                {
                    // Copy Entries in this Section
                    entries[i] = new string[profile.Sections[section_name].Entries.Count][];
                    var j = 0;
                    foreach (var key in profile.Sections[section_name].Entries.Keys)
                    {
                        // for Entry
                        entries[i][j++] = new string[] { key, profile.Sections[section_name].Entries[key] };
                    }
                    i++;
                }

                // RETURN
                return(new object[]
                {
                    section_names,
                    entries,
                    profile.GetRawLines()
                });
            }
Example #5
0
        private async void InitialSetup()
        {
            if (!Dispatcher.CheckAccess())
            {
                this.Dispatcher.Invoke(() => InitialSetup());
                return;
            }

            authButton.IsEnabled = false;
            profile = await spotify.GetPrivateProfileAsync();

            userName.Text    = profile.DisplayName;
            userCountry.Text = profile.Country;
            userEmail.Text   = profile.Email;
            accountType.Text = profile.Product;

            if (profile.Images != null && profile.Images.Count > 0)
            {
                using (WebClient wc = new WebClient())
                {
                    byte[] imageBytes = await wc.DownloadDataTaskAsync(new Uri(profile.Images[0].Url));

                    userIcon.Source = ByteArrayToImage(imageBytes);
                }
            }
            Mouse.OverrideCursor = Cursors.Arrow;
            runButton.IsEnabled  = true;
        }
Example #6
0
            // ACT
            public override void Act(out object[] actual)
            {
                // Read, Update & Write PrivateProfile
                using (var profile = new PrivateProfile(this.FilePath, false))
                {
                    // Print Profile
                    Console.WriteLine();
                    Console.WriteLine("Before Change:");
                    PrivateProfileTests.PrintProfile(profile);

                    // ACT (1): Change Profile
                    this.ChangeProfile(profile);

                    // Print Profile
                    Console.WriteLine();
                    Console.WriteLine("After Change:");
                    PrivateProfileTests.PrintProfile(profile);

                    // ACT (2): Write to File
                    profile.Write();
                }

                // Re-Read PrivateProfile
                using (var profile = new PrivateProfile(this.FilePath))
                {
                    // Print Profile
                    Console.WriteLine();
                    Console.WriteLine("Re-Read Profile:");
                    PrivateProfileTests.PrintProfile(profile);

                    // SET Actual
                    actual = PrivateProfileTestParameter.ConvertProfileToObjectArray(profile);
                }
            }
Example #7
0
        public void IgnoreDuplicatedEntryPropertyTest(string content, string expected)
        {
            // for Input Types (Stream, File)
            foreach (var inputType in Enum.GetValues(typeof(InputTypes)))
            {
                // OUTPUT
                Debug.WriteLine("");
                Debug.WriteLine(inputType.ToString(), DebugInfo.ShortName);

                // using PrivateProfile
                using (var profile = new PrivateProfile(true))
                {
                    // ARRANGE & ACT
                    switch (inputType)
                    {
                    case InputTypes.Stream:
                        // Stream:

                        // ARRANGE
                        // (None)

                        // ACT
                        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
                        {
                            // ACT: Read from Stream
                            profile.Read(stream);
                        }
                        break;

                    case InputTypes.File:
                        // File:

                        // File Path
                        var filepath = @$ ".\{nameof(IgnoreDuplicatedEntryPropertyTest)}.ini";
Example #8
0
        private async void InitialSetup()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(InitialSetup));
                return;
            }

            authButton.Enabled = false;
            profile            = await spotify.GetPrivateProfileAsync();

            nameLabel.Text    = profile.DisplayName;
            countryLabel.Text = profile.Country;
            emailLabel.Text   = profile.Email;
            accountLabel.Text = profile.Product;

            if (profile.Images != null && profile.Images.Count > 0)
            {
                using (WebClient wc = new WebClient())
                {
                    byte[] imageBytes = await wc.DownloadDataTaskAsync(new Uri(profile.Images[0].Url));

                    using (MemoryStream stream = new MemoryStream(imageBytes))
                        pictureBox.Image = System.Drawing.Image.FromStream(stream);
                }
            }
        }
Example #9
0
        public async Task <PrivateProfile> GetPrivateProfileAsync()
        {
            if (_privateProfile != null)
            {
                return(_privateProfile);
            }

            await _semaphore.WaitAsync();

            try
            {
                if (Api == null)
                {
                    return(null);
                }

                if (_privateProfile != null)
                {
                    return(_privateProfile);
                }

                _privateProfile = await Api.GetPrivateProfileAsync();

                return(_privateProfile);
            }

            finally
            {
                _semaphore.Release();
            }
        }
Example #10
0
        public void SaveUser(PrivateProfile user)
        {
            var dProfile = new dPrivateProfile
            {
                Id          = user.Id,
                Birthdate   = user.Birthdate,
                Country     = user.Country,
                DisplayName = user.DisplayName,
                Email       = user.Email,
                product     = user.Product,
                Type        = user.Type
            };

            //lets send the user to the database
            using (var db = new AiApiDbContext())
            {
                // if we don't find the user in the data base
                if (db.PrivateProfiles.Find(dProfile.Id) == null)
                {
                    db.PrivateProfiles.Add(dProfile);
                }

                db.SaveChanges();
            }
        }
Example #11
0
        private void createSpotifyPlaylists()
        {
            String fileName = fileNameTB.Text;

            if (fileName != null && fileName.Length > 0)
            {
                messageLbl.Text = "";
                XDocument doc = XDocument.Load(fileName);;

                List <XElement> tracksXml = doc.Root.Element("dict").Element("dict").Elements("dict").ToList();;

                List <FullTrack> spotifyTracks = new List <FullTrack>();
                for (int i = 0; i < tracksXml.Count; i++)
                {
                    XElement track  = tracksXml[i];
                    String   name   = getNode(track, "Name").Value;
                    String   artist = getNode(track, "Artist").Value;
                    String   album  = getNode(track, "Album").Value;
                    ProgressLbl.Text = String.Format("Searching for ({0}/{1} -> Name: {2}  Artist: {3}  Album: {4} ", i + 1, tracksXml.Count, name, artist, album);

                    FullTrack spotifyTrack = searchSpotify(name, artist, album);

                    if (spotifyTrack != null)
                    {
                        spotifyTracks.Add(spotifyTrack);
                    }
                    else
                    {
                        AddTrackToErrorLog(name, artist, album);
                    }
                }

                PrivateProfile profile = SpotifyAPI.GetPrivateProfile();
                if (!profile.HasError())
                {
                    String       playlistName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
                    FullPlaylist playlist     = SpotifyAPI.CreatePlaylist(profile.Id, playlistName);
                    if (!playlist.HasError())
                    {
                        messageLbl.Text += "\n\nPlaylist-URI: " + playlist.Uri;
                        foreach (FullTrack spotifyTrack in spotifyTracks)
                        {
                            SpotifyAPI.AddPlaylistTrack(playlist.Id, spotifyTrack.Uri);
                        }
                    }
                    else
                    {
                        messageLbl.Text += "\n\nERROR: " + playlist.Error.Message;
                    }
                }
                else
                {
                    messageLbl.Text += "\n\nERROR: " + profile.Error.Message;
                }
            }
            else
            {
                messageLbl.Text += "Please Choose a file";
            }
        }
Example #12
0
        private async void button1_ClickAsync(object sender, EventArgs e)
        {
            WebAPIFactory webApiFactory = new WebAPIFactory(
                "http://localhost",
                8000,
                "47c0cc6d128c4eb587f7a85a398d0a96",
                Scope.PlaylistReadCollaborative | Scope.PlaylistReadPrivate |
                Scope.UserReadPrivate |
                Scope.PlaylistModifyPrivate | Scope.PlaylistModifyPublic,
                TimeSpan.FromSeconds(20));

            try
            {
                //This will open the user's browser and returns once
                //the user is authorized.
                _spotifyWebAPI = await webApiFactory.GetWebApi();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            if (_spotifyWebAPI == null)
            {
                return;
            }

            //Change Status Label
            statusInfoLabel.Text      = "Connected";
            statusInfoLabel.ForeColor = Color.Green;

            //Get Profile & Playlists
            _profile = _spotifyWebAPI.GetPrivateProfile();
            GetPlaylists();
        }
    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();
    }
Example #14
0
        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);
                }
            };
        }
        public void AllLibraryToPlaylist(SpotifyWebAPI spotify)
        {
            //saves all track ids to list

            var tracksUri = HelperFunctions.GetSavedTracksUris(spotify);

            Console.WriteLine($"Number of tracks: {tracksUri.Count}");


            // gets user id
            PrivateProfile user = spotify.GetPrivateProfile();

            if (user.HasError())
            {
                Console.WriteLine("\n\nProfileID not read properly. Cannot create playlist.\n\n");
            }
            var userId = user.Id;

            //creates new empty playlist
            FullPlaylist playlist = spotify.CreatePlaylist(userId, "Library to Playlist");

            //error notification
            Console.WriteLine(playlist.HasError()
                ? "/n/nError while creating playlist.\n\n"
                : "Playlist created and named \"Library to Playlist\"");


            //inserts playlist tracks to playlist
            HelperFunctions.InsertTracks(spotify, tracksUri, playlist.Id);

            Console.WriteLine("\nWarning: there may be less songs added to playlist than are present in library, because they might be not available");
            Console.WriteLine("\nTask ended. Press any key to exit. . .");
        }
        public async void Init()
        {
            var webApiFactory = new WebAPIFactory(
                "http://localhost",
                8000,
                ConfigurationManager.AppSettings["SpotifyClientID"],
                Scope.UserReadPrivate,
                TimeSpan.FromSeconds(20)
                );

            try
            {
                //This will open the user's browser and returns once
                //the user is authorized.
                _spotify = await webApiFactory.GetWebApi();

                _user            = _spotify.GetPrivateProfile();
                tracksToDownload = new List <string>();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (_spotify == null)
            {
                return;
            }
        }
Example #17
0
        public ActionResult Playlists()
        {
            CustomToken token = ViewBag.Token;

            if (token.IsTokenEmpty())
            {
                return(PartialView("~/Views/Shared/_LoginMessage.cshtml"));
            }

            PrivateProfile profile = GetMe(token);

            if (profile == null || profile.Id == null)
            {
                return(null);
            }

            var playlists = base.GetPlaylists(token, profile.Id);

            if (playlists != null && playlists.Items != null && playlists.Items.Count > 0)
            {
                return(PartialView("~/Views/Shared/_PlaylistList.cshtml", playlists.Items));
            }

            return(null);
        }
Example #18
0
        public JsonResult Playlists(PlaylistModel model)
        {
            CustomToken token = ViewBag.Token;

            if (token.IsTokenEmpty())
            {
                return(null);
            }
            PrivateProfile profile = GetMe(token);

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

            var tracksIds = model.trackId.Split(',');

            List <ErrorResponse> errorResponses = new List <ErrorResponse>();

            foreach (var tracksId in tracksIds)
            {
                errorResponses.Add(api.AddPlaylistTrack(profile.Id, model.playlistId, string.Format("spotify:track:{0}", tracksId)));
            }

            return(Json(errorResponses.FirstOrDefault(e => e.Error == null), JsonRequestBehavior.DenyGet));
        }
Example #19
0
        private void Populate_Artists()
        {
            PrivateProfile      user    = _spotify.GetPrivateProfile();
            Paging <FullArtist> artists = _spotify.GetUsersTopArtists(limit: 28);

            BitmapImage userArt = new BitmapImage();

            userArt.BeginInit();
            try { userArt.UriSource = new Uri(user.Images[0].Url, UriKind.Absolute); }
            catch { userArt.UriSource = new Uri("https://source.unsplash.com/random/600x600", UriKind.Absolute); }
            userArt.EndInit();

            foreach (FullArtist artist in artists.Items)
            {
                Grid grid = new Grid();

                // Get the image URL
                BitmapImage bimage = new BitmapImage();
                bimage.BeginInit();
                bimage.UriSource = new Uri(artist.Images[1].Url, UriKind.Absolute);
                bimage.EndInit();

                // Bind the image to a brush
                ImageBrush imageBrush = new ImageBrush();
                imageBrush.ImageSource = bimage;
                imageBrush.Stretch     = System.Windows.Media.Stretch.UniformToFill;

                // Create the image container
                Ellipse ellipse = new Ellipse();
                ellipse.Height            = 100;
                ellipse.Width             = 100;
                ellipse.Fill              = imageBrush;
                ellipse.Margin            = new Thickness(0, 10, 0, 0);
                ellipse.VerticalAlignment = System.Windows.VerticalAlignment.Top;

                // Create the song text
                TextBlock tBlock = new TextBlock();

                tBlock.Text                = artist.Name;
                tBlock.FontSize            = 16;
                tBlock.Margin              = new Thickness(0, 0, 0, 35);
                tBlock.VerticalAlignment   = System.Windows.VerticalAlignment.Bottom;
                tBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                tBlock.Foreground          = (SolidColorBrush) new BrushConverter().ConvertFromString("#FFC8C8C8");

                // Create the event handlers
                SeveralTracks tracks = _spotify.GetArtistsTopTracks(artist.Id, user.Country);
                grid.MouseEnter += new MouseEventHandler((s, e) => Preview_Song(s, e, tracks.Tracks[0].Id, bimage, grid));
                grid.MouseLeave += new MouseEventHandler((s, e) => Stop_Preview(s, e, userArt, grid));
                grid.MouseDown  += ((s, e) => Open_Artist(s, e, tracks));

                grid.Cursor = Cursors.Hand;

                grid.Children.Add(ellipse);
                grid.Children.Add(tBlock);

                uArtists.Children.Add(grid);
            }
        }
Example #20
0
        public JsonResult NowPlaying()
        {
            Dictionary <string, string> nowPlaying = new Dictionary <string, string>();

            if (User.Identity.IsAuthenticated)
            {
                string accessToken = HttpContext.GetTokenAsync("access_token").Result;

                try
                {
                    // For usage visit: https://github.com/JohnnyCrazy/SpotifyAPI-NET/
                    SpotifyWebAPI spotifyAPI = new SpotifyWebAPI
                    {
                        AccessToken = accessToken,
                        TokenType   = "Bearer"
                    };

                    PrivateProfile  profile = spotifyAPI.GetPrivateProfileAsync().Result;
                    PlaybackContext context = spotifyAPI.GetPlayback();
                    if (!profile.HasError())
                    {
                        nowPlaying.Add("SpotifyName", profile.DisplayName);
                        nowPlaying.Add("SpotifyAvatar", profile.Images.FirstOrDefault().Url);
                        nowPlaying.Add("SpotifyProfileUrl", "https://open.spotify.com/user/" + profile.Id);
                    }

                    if (context.Item != null && (context.IsPlaying))
                    {
                        nowPlaying.Add("SongName", context.Item.Name);
                        nowPlaying.Add("SongUrl", context.Item.Href);
                        nowPlaying.Add("ArtistName", context.Item.Artists.FirstOrDefault().Name);
                        nowPlaying.Add("ArtistUrl", context.Item.Artists.FirstOrDefault().Href);
                        nowPlaying.Add("NowPlaying", nowPlaying["SongName"] + " by " + nowPlaying["ArtistName"]);
                        nowPlaying.Add("AlbumArt", context.Item.Album.Images.FirstOrDefault().Url);
                        nowPlaying.Add("AlbumUrl", context.Item.Album.ExternalUrls["spotify"]);
                        nowPlaying.Add("IsPlaying", "true");
                    }
                    else
                    {
                        nowPlaying.Add("SongName", null);
                        nowPlaying.Add("SongUrl", null);
                        nowPlaying.Add("ArtistName", null);
                        nowPlaying.Add("ArtistUrl", null);
                        nowPlaying.Add("NowPlaying", null);
                        nowPlaying.Add("AlbumArt", null);
                        nowPlaying.Add("AlbumUrl", null);
                        nowPlaying.Add("IsPlaying", "false");
                    }
                    GeniusService geniusService = new GeniusService(nowPlaying["SongName"], nowPlaying["ArtistName"]);
                    nowPlaying.Add("Lyrics", geniusService.Lyrics);
                    nowPlaying.Add("LyricsContribution", geniusService.Url);
                }
                catch (Exception ex)
                {
                    // show the users some error
                }
            }
            return(new JsonResult(nowPlaying));
        }
Example #21
0
            // Change Profile
            public override void ChangeProfile(PrivateProfile profile)
            {
                // ACT: Remove Entry
                this.result = profile.Remove(this.Section, this.Key);

                // Print return value of Remove() method
                Console.WriteLine($"Return value of Remove() method = {this.result}");
            }
Example #22
0
 public async Task <PrivateProfile> GetUserProflie()
 {
     if (privateProfile == null)
     {
         privateProfile = await spotifyWebApi.GetPrivateProfileAsync();
     }
     return(privateProfile);
 }
Example #23
0
 public void Handle(avatarUpdated message)
 {
     if (_ppToBeConfirmed != null)
     {
         _initialPP = _ppToBeConfirmed;
         NotifyOfPropertyChange(null);
         _ppToBeConfirmed = null;
     }
 }
Example #24
0
        private static string GetCountryOfProfile(PrivateProfile profile, string profileCountryCode)
        {
            if (profile != null && !string.IsNullOrEmpty(profile.Country))
            {
                profileCountryCode = profile.Country;
            }

            return(profileCountryCode);
        }
        public async void GetToken(CredentialsAuth auth)
        {
            Token token = await auth.GetToken();

            webAPI = new SpotifyWebAPI {
                AccessToken = token.AccessToken, TokenType = token.TokenType
            };
            user = await webAPI.GetPrivateProfileAsync();
        }
Example #26
0
        private void InitialSetup()
        {
            Auth.Visibility        = Visibility.Hidden;
            AuthDetails.Visibility = Visibility.Visible;
            PrivateProfile pf       = _spotify.GetPrivateProfile();
            string         username = pf.DisplayName != null && pf.DisplayName != "" ? pf.DisplayName : pf.Id;

            AuthUser.Content = username;
        }
Example #27
0
        public IEnumerable <ResponseMessage> GetSpotifyUserDetails(IncomingMessage message, IValidHandle matchedHandle)
        {
            PrivateProfile spotifyPrivateProfile = this._spotifyPlugin.GetSpotifyUser();

            yield return(message.ReplyToChannel(
                             $"I am {spotifyPrivateProfile.DisplayName} : ID {spotifyPrivateProfile.Id} : Email address {spotifyPrivateProfile.Email}"
                             , (Attachment)null
                             ));
        }
Example #28
0
 private void GetSetPrivateProfile()
 {
     if (this.spotifyPrivateProfile == null)
     {
         this.CheckOrRefreshToken();
         PrivateProfile privateProfile = this._spotifyBase.SpotifyWebApi.GetPrivateProfile();
         this.spotifyPrivateProfile = privateProfile;
     }
 }
Example #29
0
        public void ShouldGetPrivateProfile_WithAuth()
        {
            PrivateProfile profile = GetFixture <PrivateProfile>("private-user.json");

            _mock.Setup(client => client.DownloadJson <PrivateProfile>(It.IsAny <string>())).Returns(profile);

            _spotify.UseAuth = true;
            Assert.AreEqual(profile, _spotify.GetPrivateProfile());
            _mock.Verify(client => client.DownloadJson <PrivateProfile>(It.Is <string>(str => ContainsValues(str, "/me"))), Times.Exactly(1));
        }
Example #30
0
        /// <summary>
        /// Deletes and rewrites the Top Artists and Top Tracks from spotify. Asynchnonously while also launching up two new threads.
        /// </summary>
        /// <param name="user">The user to get this information for.</param>
        public void SyncTopList(PrivateProfile user)
        {
            Thread artistThread = null;
            Thread trackThread  = null;

            try
            {
                //the new thread for the artists objects
                artistThread = new Thread(async() =>
                {
                    await GetUsersTopArtistsShortTerm(user.Id);
                    await GetUsersTopArtistsMeduimTerm(user.Id);
                    await GetUsersTopArtistsLongTerm(user.Id);

                    AiThreadManager.RemoveThread(artistThread);
                });

                AiThreadManager.AddThread(artistThread);

                //the new thread for the track objects
                trackThread = new Thread(async() =>
                {
                    await GetUsersTopTracksShortTerm(user.Id);
                    await GetUsersTopTracksMeduimTerm(user.Id);
                    await GetUsersTopTracksLongTerm(user.Id);

                    AiThreadManager.RemoveThread(trackThread);
                });

                AiThreadManager.AddThread(trackThread);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
            }
            finally
            {
                using (var db = new AiApiDbContext())
                {
                    db.TopSyncDates.Add(new sTopSync()
                    {
                        UserId  = user.Id,
                        SyncTop = SpotifyTopOptions.Artists
                    });

                    db.TopSyncDates.Add(new sTopSync()
                    {
                        UserId  = user.Id,
                        SyncTop = SpotifyTopOptions.Tracks
                    });

                    db.SaveChangesAsync();
                }
            }
        }