Exemple #1
0
        public async Task <TLeaderboard> GetTrophyLeaderboardAsync()
        {
            try
            {
                await RequestSemaphore.WaitAsync();

                await CheckConnectionStatusAsync();

                await Writer.WriteLineAsync("getleaderboard");

                await CheckServerResponseAsync();

                string leaderboardString = await Reader.ReadLineAsync();

                string[] parts         = leaderboardString.Split(':');
                string[] playerStrings = parts[0].Split(';');
                string[] teamStrings   = parts[1].Split(";");

                var players = playerStrings.Select(playerString => TLbPlayer.Parse(ScrapClient, playerString))
                              .ToArray();

                var teams = teamStrings.Select(teamString => TLbTeam.Parse(ScrapClient, teamString))
                            .ToArray();

                return(new TLeaderboard(players, teams));
            }
            finally
            {
                RequestSemaphore.Release();
            }
        }
Exemple #2
0
        private async Task AddSongsToGenreDictionaryAsync(
            SavedTrackWithGenre genreTrack,
            ConcurrentDictionary <string, string> genreIdDict,
            ConcurrentDictionary <string, Collection <string> > newSongsDict,
            CancellationToken cancellationToken)
        {
            await RequestSemaphore.WaitAsync();

            cancellationToken.ThrowIfCancellationRequested();
            logger.LogInformation($"Adding {genreTrack.Track.Name} to genreList");

            foreach (string genre in genreTrack.Genres)
            {
                foreach (KeyValuePair <string, string> genres in genreIdDict)
                {
                    // If the genre exists in any playlist genre, AND isn't already in the newSongsDict.
                    if (genres.Value.Contains(genre) && (!newSongsDict[genres.Key].Contains(genre)))
                    {
                        newSongsDict[genres.Key].Add(genreTrack.Track.Id);
                    }
                }
            }

            RequestSemaphore.Release();
        }
Exemple #3
0
        private async Task MoveNewSongsIntoPlaylistsAsync(
            ConcurrentDictionary <string, Collection <string> > newPlaylistSongsDict,
            CancellationToken cancellationToken)
        {
            await RequestSemaphore.WaitAsync();

            cancellationToken.ThrowIfCancellationRequested();
            List <Task> tasks = new List <Task>();

            // Wanted to change this to Collection<>, but was getting some issues with the unlikeList concat.
            Collection <string> unlikeList = new Collection <string>();

            foreach (KeyValuePair <string, Collection <string> > entry in newPlaylistSongsDict)
            {
                logger.LogInformation($"Moving tracks to playlist: {entry.Key}");
                tasks.Add(Api.AddPlaylistTracksAsync(entry.Key, entry.Value));

                // Concat returns an IEnumerable, which for some reason can't be put into a collection.
                unlikeList = new Collection <string>(unlikeList.Concat(entry.Value).ToList());
            }

            await Task.WhenAll(tasks);

            logger.LogInformation("Unliking moved songs.");

            // Casting back to Collection due to needing to use an IEnumerable earlier.
            await Api.RemoveSavedTracksAsync(unlikeList);

            RequestSemaphore.Release();
        }
Exemple #4
0
        public async Task <SavedTrackWithGenre> GetGenreFromSongAsync(
            SavedTrackWithGenre genreTrack,
            CancellationToken cancellationToken)
        {
            await RequestSemaphore.WaitAsync();

            cancellationToken.ThrowIfCancellationRequested();
            Collection <string> genres = new();

            foreach (var artist in genreTrack.Track.Artists)
            {
                // Could async this too if performance is really taking a hit, but it probably isn't necessary.
                logger.LogInformation($"Getting Genres for artist {artist} for song {genreTrack.Track.Name}");

                // This call specifically seems to give me trouble when trying to leverage async.
                var fullArtist = await Api.GetArtistAsync(artist.Id);

                if (fullArtist.Genres != null)
                {
                    // There was some weird behavior with using IEnumerable here where Linq's ConcatNIterator couldn't
                    // be cast into a collection when assigning back to genreTracks. This will have to do for the meantime.
                    genres = new Collection <string>(genres.Concat(fullArtist.Genres).ToList());
                }
            }

            genreTrack.Genres = genres;

            cancellationToken.ThrowIfCancellationRequested();
            RequestSemaphore.Release();
            return(genreTrack);
        }
Exemple #5
0
        public override Message OnReceiveMessage(Message message)
        {
            if (message.GetType() != typeof(Response))
            {
                throw new NotImplementedException();
            }

            var response = (Response)message;

            lock (ReceivedResponses) {
                // if duplicated response, ignore
                if (ReceivedResponses.ContainsKey(response.Request.SeqNum))
                {
                    return(null);
                }

                ReceivedResponses.Add(response.Request.SeqNum, response);
            }

            // if it receives at least one response for a blocking request then unblock ( can only send one and then block, so it will always unblock properly? )
            if (response.Request.GetType() == typeof(ReadRequest) ||
                response.Request.GetType() == typeof(TakeRequest))
            {
                if (RequestSemaphore.TryGetValue(response.Request.SeqNum, out var semaphore))
                {
                    semaphore.Release();
                    return(null);
                }

                throw new NotImplementedException("No semaphore was allocated.");
            }
            return(null);
        }
Exemple #6
0
        private async Task <PrivateProfile> GetUserAsync(CancellationToken cancellationToken)
        {
            await RequestSemaphore.WaitAsync();

            cancellationToken.ThrowIfCancellationRequested();
            logger.LogInformation($"Requesting {user?.Id ?? "user"}'s Private profile.");
            PrivateProfile profile = await Api.GetPrivateProfileAsync();

            RequestSemaphore.Release();
            return(profile);
        }
Exemple #7
0
        public async Task <Paging <SavedTrack> > GetUserLikedTracksAsync(CancellationToken cancellationToken)
        {
            await RequestSemaphore.WaitAsync();

            cancellationToken.ThrowIfCancellationRequested();
            logger.LogInformation($"Getting {user?.Id ?? "User"}'s Liked tracks.");
            Paging <SavedTrack> tracks = await Api.GetSavedTracksAsync(options.MaxSongResults);

            cancellationToken.ThrowIfCancellationRequested();
            RequestSemaphore.Release();
            return(tracks);
        }
Exemple #8
0
        private async Task <string> GetPlaylistDescriptionsAsync(
            string playlist,
            CancellationToken cancellationToken)
        {
            await RequestSemaphore.WaitAsync();

            cancellationToken.ThrowIfCancellationRequested();
            logger.LogInformation($"Getting Playlist description for playlistID: {playlist}");
            FullPlaylist fullPlaylist = await Api.GetPlaylistAsync(playlist);

            RequestSemaphore.Release();
            return(fullPlaylist.Description);
        }
Exemple #9
0
        private async Task <Paging <SimplePlaylist> > GetUserPlaylistsAsync(CancellationToken cancellationToken)
        {
            await RequestSemaphore.WaitAsync();

            cancellationToken.ThrowIfCancellationRequested();

            user ??= await GetUserAsync(cancellationToken);

            string userId = user.Id;

            logger.LogInformation($"Getting playlists from {userId}.");
            Paging <SimplePlaylist> playlists = await Api.GetUserPlaylistsAsync(userId, options.MaxPlaylistResults);

            RequestSemaphore.Release();
            return(playlists);
        }
Exemple #10
0
        private async Task SendHeartbeatAsync()
        {
            try
            {
                await RequestSemaphore.WaitAsync();

                await CheckConnectionStatusAsync();

                await Writer.WriteLineAsync("keepalive");
                await CheckServerResponseAsync();
                await CheckServerResponseAsync();
            }
            finally
            {
                RequestSemaphore.Release();
            }
        }
Exemple #11
0
        public async Task <Player> GetPlayerByIdAsync(string playerId)
        {
            try
            {
                await RequestSemaphore.WaitAsync();

                await CheckConnectionStatusAsync();

                await Writer.WriteLineAsync($"getplayerdata:{playerId}");

                await CheckServerResponseAsync();

                string playerString = await Reader.ReadLineAsync();

                return(Player.Parse(ScrapClient, playerString));
            }
            finally
            {
                RequestSemaphore.Release();
            }
        }
Exemple #12
0
        public async Task <int> GetDailyUsedApiCallsAsync()
        {
            try
            {
                await RequestSemaphore.WaitAsync();

                await CheckConnectionStatusAsync();

                await Writer.WriteLineAsync("apirequests");

                await CheckServerResponseAsync();

                string response = await Reader.ReadLineAsync();

                return(int.Parse(response));
            }
            finally
            {
                RequestSemaphore.Release();
            }
        }
Exemple #13
0
        public async Task <string[]> GetPlayerIdsByNameAsync(string playerName)
        {
            try
            {
                await RequestSemaphore.WaitAsync();

                await CheckConnectionStatusAsync();

                await Writer.WriteLineAsync($"getplayersbyname:{Formatter.ToFormatted(playerName)}");

                await CheckServerResponseAsync();

                string response = await Reader.ReadLineAsync();

                string[] playerIds = response.Split(':', StringSplitOptions.RemoveEmptyEntries);
                return(playerIds);
            }
            finally
            {
                RequestSemaphore.Release();
            }
        }
Exemple #14
0
        public async Task <XPLbPlayer[]> GetPlayerXPLeaderboardAsync()
        {
            try
            {
                await RequestSemaphore.WaitAsync();

                await CheckConnectionStatusAsync();

                await Writer.WriteLineAsync("xpleaderboard");

                await CheckServerResponseAsync();

                string leaderboardString = await Reader.ReadLineAsync();

                string[] xpLbPlayerStrings = leaderboardString.Split(";");
                return(xpLbPlayerStrings.Select(xpLbPlayerString => XPLbPlayer.Parse(ScrapClient, xpLbPlayerString))
                       .ToArray());
            }
            finally
            {
                RequestSemaphore.Release();
            }
        }
Exemple #15
0
        public async Task <Member[]> GetTeamMembersAsync(string teamId)
        {
            try
            {
                await RequestSemaphore.WaitAsync();

                await CheckConnectionStatusAsync();

                await Writer.WriteLineAsync($"getteambyid:{teamId}");

                await CheckServerResponseAsync();

                string response = await Reader.ReadLineAsync();

                string[] memberStrings = response.Split(';');
                return(memberStrings.Select(memberString => Member.Parse(ScrapClient, memberString))
                       .ToArray());
            }
            finally
            {
                RequestSemaphore.Release();
            }
        }
Exemple #16
0
        public async Task <Team[]> GetTeamsAsync()
        {
            try
            {
                await RequestSemaphore.WaitAsync();

                await CheckConnectionStatusAsync();

                await Writer.WriteLineAsync("getteams");

                await CheckServerResponseAsync();

                string response = await Reader.ReadLineAsync();

                string[] teamStrings = response.Split(';');
                return(teamStrings.Select(teamString => Team.Parse(ScrapClient, teamString))
                       .ToArray());
            }
            finally
            {
                RequestSemaphore.Release();
            }
        }
Exemple #17
0
 // Wait for response. Disposes and removes semaphore.
 private void WaitForResponse(int requestSeqNum)
 {
     RequestSemaphore[requestSeqNum].Wait();
     RequestSemaphore[requestSeqNum].Dispose();
     RequestSemaphore.Remove(requestSeqNum);
 }