Exemplo n.º 1
0
        public async Task <bool> UpdatePartyPlaylistForEveryoneInPartyAsync(Party party, PartyGoer user)
        {
            try
            {
                if (party is null)
                {
                    throw new Exception($"Obtaining a party with ID {party.Id} returned null from the database");
                }

                if (!party.Host.Id.Equals(user.Id, StringComparison.CurrentCultureIgnoreCase) &&
                    !party.Listeners.Exists(p => p.Id.Equals(user.Id, StringComparison.CurrentCultureIgnoreCase)))
                {
                    throw new Exception($"A non host or party attendee tried to change the song for the party with ID {party.Id}. Attempted user ID: {user.Id}");
                }

                List <Task <List <string> > > topTrackUrisTasks = new List <Task <List <string> > >();

                topTrackUrisTasks.Add(_spotifyHttpClient.GetUserTopTrackIdsAsync(user.Id, 5));

                foreach (PartyGoer attendee in party.Listeners)
                {
                    topTrackUrisTasks.Add(_spotifyHttpClient.GetUserTopTrackIdsAsync(attendee.Id, 5));
                }

                var recommendTrackUris = await _spotifyHttpClient.GetRecommendedTrackUrisAsync(user.Id, GetNNumberOfTrackUris(topTrackUrisTasks.SelectMany(p => p.Result).ToList(), 5));

                List <Task <ServiceResult <UpdateSongError> > > updateSongForPartyTask = new List <Task <ServiceResult <UpdateSongError> > >();
                foreach (PartyGoer attendee in party.Listeners)
                {
                    updateSongForPartyTask.Add(_spotifyHttpClient.UpdateSongForPartyGoerAsync(attendee.Id, recommendTrackUris, 0));
                }

                await Task.WhenAll(updateSongForPartyTask);

                // Verify all the updates worked
                foreach (Task <ServiceResult <UpdateSongError> > task in updateSongForPartyTask)
                {
                    if (!task.Result.Success)
                    {
                        return(false);
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                await _logService.LogExceptionAsync(ex, "Error occurred in UpdatePartyPlaylistForEveryoneInPartyAsync");

                return(false);
            }
        }