public async Task UserAddedSong(AddSongToQueueCommand request) { PartyGoer partier = await _partyGoerService.GetCurrentPartyGoerAsync(); request.AddedBy = partier.GetUsername(); bool successfullyAddedSongToQueue = await _partyService.AddNewSongToQueue(request); if (successfullyAddedSongToQueue) { Party party = await _partyService.GetPartyWithAttendeeAsync(partier); // Update the view of the partier to the current playlist await Clients.Group(party.GetPartyCode()).SendAsync("UpdatePartyView", new { Song = party.GetCurrentSong(), Position = party.GetCurrentPositionInSong() }, party.GetHistory(), party.GetQueue() ); } else { await Clients.Client(Context.ConnectionId).SendAsync("UserModifiedPlaylist", new { error = true }); } }
public bool LeaveParty(PartyGoer attendee) { List <string> partyKeys = new List <string>(); foreach (var key in _parties.Keys) { if (_parties[key].IsListener(attendee)) { partyKeys.Add(key); } } if (partyKeys.Count > 1) { partyKeys.ForEach(p => _parties[p].LeaveParty(attendee)); throw new PartyGoerWasInMultiplePartiesException($"The user {attendee} was in {partyKeys.Count} but was successfully removed from them"); } if (partyKeys == null || partyKeys.Count == 0) { throw new Exception($"The attendee: {attendee.GetId()} is not currently in a party"); } _parties[partyKeys.First()].LeaveParty(attendee); return(true); }
public async Task <IActionResult> UpdateContribution(string partyCode, [FromBody] UpdateContributions updateContributions) { try { if (updateContributions.ContributionsToRemove == null) { updateContributions.ContributionsToRemove = new List <UserContribution>(); } if (updateContributions.NewContributions == null) { updateContributions.NewContributions = new List <UserContribution>(); } if (updateContributions != null && updateContributions.ContributionsToRemove.Count == 0 && updateContributions.NewContributions.Count == 0) { return(Ok()); } PartyGoer partyGoer = await _partyGoerService.GetCurrentPartyGoerAsync(); await _partyService.UpdateContributionsAsync(partyCode, updateContributions.NewContributions.Select(p => CreateContribution(partyGoer, p)).ToList(), updateContributions.ContributionsToRemove.Select(p => CreateContribution(partyGoer, p)).ToList()); } catch (Exception ex) { await _logService.LogExceptionAsync(ex, "Error occurred while trying to add contribution"); return(StatusCode(500)); } return(Ok()); }
public async Task <SpotibroModels.PlaylistContents> GetPlaylistContentsAsync(PartyGoer user, string playlistId) { var parameters = new ApiParameters { Parameters = new Dictionary <string, string> { { "fields", "items(track(id,name,album(images(url)),artists(name,id),explicit(),duration_ms()))" }, { "market", user.GetMarket() } }, Keys = new Dictionary <string, string> { { "{playlist_id}", playlistId }, } }; var response = await _spotifyHttpClient.SendHttpRequestAsync(user, _apiEndpoints[ApiEndpointType.GetPlaylistItems], parameters); response.EnsureSuccessStatusCode(); var playlistItems = await response.Content.ReadFromJsonAsync <PlaylistItems>(); playlistItems.Items.RemoveAll(p => p.Track == null); return(new SpotibroModels.PlaylistContents() { Tracks = playlistItems.Items.Select(p => _mapper.Convert(p.Track)).ToList() }); }
public bool LeaveParty(PartyGoer attendee) { List <Party> parties = _parties.FindAll(p => p.Listeners.Contains(attendee)); if (parties.Count > 1) { parties.ForEach(p => p.Listeners.RemoveAll(p => p == attendee)); throw new PartyGoerWasInMultiplePartiesException($"The user {attendee} was in {parties.Count} but was successfully removed from them"); } if (parties == null || parties.Count == 0) { throw new Exception($"The attendee: {attendee.Id} is not currently in a party"); } if (parties.First().Playlist != null) { parties.First().Playlist.RemoveListener(attendee); } parties.First().Listeners.RemoveAll(p => p.Id.Equals(attendee.Id, StringComparison.OrdinalIgnoreCase)); return(true); }
public async Task <IActionResult> EndParty() { PartyGoer host = new PartyGoer(User.FindFirstValue(ClaimTypes.NameIdentifier)); if (await _partyService.IsUserHostingAPartyAsync(host)) { if (await _partyService.EndPartyAsync(host)) { await _logService.LogUserActivityAsync(host.Id, $"User successfully ended party"); return(Ok()); } else { await _logService.LogUserActivityAsync(host.Id, $"User failed to end party"); return(BadRequest("There was an issue with deleting your party")); } } else { await _logService.LogUserActivityAsync(host.Id, $"User failed to end party because they weren't the host"); return(BadRequest("Unable to delete party. You are not hosting any parties")); } }
public async Task <List <Device> > GetUserDevicesAsync(PartyGoer partyGoer) { HttpResponseMessage response = await SendHttpRequestAsync(partyGoer.GetId(), _apiEndpoints[ApiEndpointType.GetUserDevices]); if (response.IsSuccessStatusCode) { JObject json = JObject.Parse(await response.Content.ReadAsStringAsync()); List <Device> devices = new List <Device>(); foreach (var item in json["devices"]) { devices.Add(new Device { Name = item["name"].ToString(), Active = item["is_active"].Value <bool>(), Id = item["id"].ToString() }); } return(devices); } else { SpotifyApiException exception = new SpotifyApiException("Unable to get users devices from Spotify"); await _logService.LogExceptionAsync(exception, await response.Content.ReadAsStringAsync()); throw exception; } }
public async Task <IEnumerable <ISpotifyQueryResult> > QuerySpotifyAsync(PartyGoer user, string searchQuery, SpotifyQueryType queryType, int limit) { try { switch (queryType) { case SpotifyQueryType.Track: return(await QuerySpotifyForTrackAsync(user, searchQuery, limit)); case SpotifyQueryType.Artist: return(await QuerySpotifyForArtistAsync(user, searchQuery, limit)); case SpotifyQueryType.Album: return(await QuerySpotifyForAlbumAsync(user, searchQuery, limit)); case SpotifyQueryType.Playlist: //return await QuerySpotifyForPlaylistAsync(user, searchQuery, limit); case SpotifyQueryType.All: //return await QuerySpotifyAsync<T>(user, searchQuery); default: throw new ArgumentException($"Argument SpotifyQuertyType of {queryType} not handled"); } } catch (Exception ex) { // TODO: Add custom exception to catch in clients to know that there was a problem with Spotifys API throw new Exception($"Error occurred while trying to query Spotify with query {searchQuery}", ex); } }
public async Task <bool> LeavePartyAsync(PartyGoer attendee) { try { if (await IsUserPartyingAsync(attendee)) { _partyRepository.LeaveParty(attendee); } if (await IsUserHostingAPartyAsync(attendee)) { await _partyRepository.RemoveHostFromPartyAsync(attendee); } return(true); } catch (PartyGoerWasInMultiplePartiesException ex) { await _logService.LogExceptionAsync(ex, "Error occurred in LeavePartyAsync"); return(true); } catch (Exception ex) { await _logService.LogExceptionAsync(ex, "Error occurred in LeavePartyAsync"); return(false); } }
public async Task <bool> LeavePartyAsync(PartyGoer attendee) { try { // Let's make sure he is part of the party if (await _partyRepository.IsUserInAPartyAsync(attendee)) { return(_partyRepository.LeaveParty(attendee)); } else { return(false); } } catch (PartyGoerWasInMultiplePartiesException ex) { await _logService.LogExceptionAsync(ex, "Error occurred in LeavePartyAsync"); return(true); } catch (Exception ex) { await _logService.LogExceptionAsync(ex, "Error occurred in LeavePartyAsync"); return(false); } }
public async Task <HttpResponseMessage> SendHttpRequestAsync(PartyGoer user, SpotifyEndpoint spotifyEndpoint, ApiParameters queryStringParameters, object requestBodyParameters) { await RefreshTokenForUserAsync(user.GetId()); string spotifyEndpointUrl = spotifyEndpoint.EndpointUrl; // look to see if spotifyendpoint has keys if (spotifyEndpoint?.Keys != null) { // we need to verify these keys exist in api parameters foreach (string key in spotifyEndpoint.Keys) { if (!queryStringParameters.Keys.ContainsKey(key)) { throw new Exception($"Endpoint: {spotifyEndpoint} says it contains a key: {key} but it is not found in parameters"); } spotifyEndpointUrl = spotifyEndpointUrl.Replace(key, queryStringParameters.Keys[key]); } } using (var requestMessage = new HttpRequestMessage(spotifyEndpoint.HttpMethod, spotifyEndpointUrl + AddQueryStrings(queryStringParameters))) { requestMessage.Headers.Authorization = await _spotifyAuthentication.GetAuthenticationHeaderForPartyGoerAsync(user.GetId()); if (requestBodyParameters != null) { requestMessage.Content = new StringContent(JsonConvert.SerializeObject(requestBodyParameters)); } return(await _httpClient.SendAsync(requestMessage)); } }
public async Task UserModifiedPlaylist(RearrangeQueueRequest queueRequest) { var partier = new PartyGoer(Context.UserIdentifier); bool successfullyRearrangedQueue = await _partyService.RearrangeQueue(queueRequest); if (successfullyRearrangedQueue) { Party party = await _partyService.GetPartyWithAttendeeAsync(partier); // Update the view of the partier to the current playlist await Clients.Group(party.PartyCode).SendAsync("UpdatePartyView", new { Song = party.Playlist.CurrentSong, Position = party.Playlist.CurrentPositionInSong() }, party.Playlist.History, party.Playlist.Queue ); } else { await Clients.Client(Context.ConnectionId).SendAsync("UserModifiedPlaylist", new { error = true }); } }
public async Task <IActionResult> SearchSpotify(string query) { PartyGoer user = new PartyGoer(User.FindFirstValue(ClaimTypes.NameIdentifier)); try { if (string.IsNullOrWhiteSpace(query)) { return(StatusCode(200)); } List <Song> songs = await _partyGoerService.SearchSpotifyForSongs(user.Id, query); return(new JsonResult(songs.Select(song => new SongModel { AlbumImageUrl = song.AlbumImageUrl, Artist = song.Artist, Length = song.Length, Title = song.Title, TrackUri = song.TrackUri }).ToList())); } catch (Exception ex) { return(StatusCode(500)); } }
public async Task <IActionResult> EndParty() { PartyGoer host = await _partyGoerService.GetCurrentPartyGoerAsync(); if (await _partyService.IsUserHostingAPartyAsync(host)) { if (await _partyService.EndPartyAsync(host)) { await _logService.LogUserActivityAsync(host, $"User successfully ended party"); return(Ok()); } else { await _logService.LogUserActivityAsync(host, $"User failed to end party"); return(BadRequest("There was an issue with deleting your party")); } } else { await _logService.LogUserActivityAsync(host, $"User failed to end party because they weren't the host"); return(BadRequest("Unable to delete party. You are not hosting any parties")); } }
public async Task <IActionResult> Authorized(string code) { try { PartyGoer newUser = await _authenticationService.AuthenticateUserWithAccessCodeAsync(code); if (!newUser.HasPremium()) { // TODO: create this return(RedirectToAction("NoPremium", "Error")); } // Get details from spotify of user var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, newUser.GetId())); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); await _logService.LogUserActivityAsync(newUser, "Successfully authenticated through Spotify"); return(RedirectToAction("App", "Party")); } catch (Exception) { // TODO: CHANGE THIS TO THE IDNEX PAGE ON HOME return(RedirectToAction("App", "Party")); } }
// Use this for initialization void Start() { playerx = Player.GetComponent <PartyGoer>(); skillone = chooseUpCard(); playerx.visible.Insert(0, skillone); stillAvailable_up.Remove(skillone); skilltwo = chooseDownCard(); playerx.visible.Insert(1, skilltwo); stillAvailable_down.Remove(skilltwo); skillthree = chooseLeftCard(); playerx.visible.Insert(2, skillthree); stillAvailable_left.Remove(skillthree); skillfour = chooseRightCard(); playerx.visible.Insert(3, skillfour); stillAvailable_right.Remove(skillfour); cardone = deck[playerx.visible[0]]; cardone.transform.position = new Vector3(160, 120, 0); cardtwo = deck[playerx.visible[1]]; cardtwo.transform.position = new Vector3(160, 40, 0); cardthree = deck[playerx.visible[2]]; cardthree.transform.position = new Vector3(100, 40, 0); cardfour = deck[playerx.visible[3]]; cardfour.transform.position = new Vector3(220, 40, 0); }
public async Task <int?> SaveUserAsync(PartyGoer partier) { string newUserSql = @"INSERT INTO Users(name, display_name) VALUES(@Name, @Name)"; string lastLoginSql = @"INSERT INTO LastLogin(user_id, time) VALUES(@UserId, NOW())"; await _connection.ExecuteAsync(newUserSql, new { Name = partier.GetSpotifyId() }); int?userId = await GetUserIdAsync(partier); if (!userId.HasValue) { throw new Exception($"User {partier.GetSpotifyId()} does not have an id after saving"); } await _connection.ExecuteAsync(lastLoginSql, new { UserId = userId.Value }); return(await GetUserIdAsync(partier)); }
public async Task <IActionResult> UpdateSongForParty([FromBody] PartyCodeDTO partyCode) { PartyGoer user = new PartyGoer(User.FindFirstValue(ClaimTypes.NameIdentifier)); if (await _partyService.IsUserHostingAPartyAsync(user)) { Party party = await _partyService.GetPartyWithHostAsync(user); await _logService.LogUserActivityAsync(user.Id, $"User updated song for party with code {partyCode.PartyCode}"); return(await UpdateCurrentSongForEveryoneInPartyAsync(party, user)); } else if (await _partyService.IsUserPartyingAsync(user)) { Party party = await _partyService.GetPartyWithAttendeeAsync(user); await _logService.LogUserActivityAsync(user.Id, $"User updated song for party with code {partyCode.PartyCode}"); return(await UpdateCurrentSongForEveryoneInPartyAsync(party, user)); } else { await _logService.LogUserActivityAsync(user.Id, $"User failed tp update song for party with code {partyCode.PartyCode}"); return(BadRequest($"You are currently not hosting a party or attending a party: {partyCode.PartyCode}")); } }
public async Task RequestSkipAsync(PartyGoer partyGoer) { if (IsHost(partyGoer)) { await NextTrackAsync(); } }
public async Task <int> LoginUser(PartyGoer user) { int?userId = await _userRepository.GetUserIdAsync(user); if (!userId.HasValue) { userId = await _userRepository.SaveUserAsync(user); if (userId.HasValue) { if (!_userIds.ContainsKey(user.GetSpotifyId())) { _userIds.Add(user.GetSpotifyId(), userId.Value); } } else { throw new Exception($"User {user.GetSpotifyId()} does not have a user id even after saving user"); } } await _userRepository.UpdateLastLoginTimeAsync(userId.Value); return(userId.Value); }
public void NukeQueue(PartyGoer partier) { if (IsHost(partier)) { _queue.Nuke(); } }
public bool DeletePartyWithHost(PartyGoer host) { List <string> partyKeys = new List <string>(); foreach (var key in _parties.Keys) { if (_parties[key].IsHost(host)) { partyKeys.Add(key); } } if (partyKeys.Count > 1) { throw new Exception($"Host: {host?.GetId()} is hosting {partyKeys.Count} parties. A host should only host 1 party at a time."); } if (partyKeys == null) { throw new Exception($"Host: {host?.GetId()} is not hosting a party"); } _parties.Remove(partyKeys.First()); return(true); }
public async Task ConnectToParty(string partyCode) { PartyGoer partier = await _partyGoerService.GetCurrentPartyGoerAsync(); if (!await _partyService.IsUserPartyingAsync(partier) && !await _partyService.IsUserHostingAPartyAsync(partier)) { await _partyService.JoinPartyAsync(new Domain.DTO.PartyCodeDTO { PartyCode = partyCode }, partier); await Groups.AddToGroupAsync(Context.ConnectionId, partyCode); await Clients.Group(partyCode).SendAsync("UpdateParty", $"{Context.UserIdentifier} has joined the party {partyCode}"); } // Add the partier to real-time connection group await Groups.AddToGroupAsync(Context.ConnectionId, partyCode); await Clients.GroupExcept(partyCode, new List <string> { Context.ConnectionId }).SendAsync("NewListener", Context.UserIdentifier); Party party = await _partyService.GetPartyWithAttendeeAsync(partier); // Update the view of the partier to the current playlist await Clients.Client(Context.ConnectionId).SendAsync("InitialPartyLoad", new { Song = party.GetCurrentSong(), Position = party.GetCurrentPositionInSong() }, party.GetHistory(), party.GetQueue(), new { PartyCode = party.GetPartyCode(), Listeners = ConvertToListenerModel(party.GetListeners()), Host = party.GetHost().GetId() } );; // check for explicit music if (!partier.CanListenToExplicitSongs() && party.HasExplicitTracks()) { await Clients.Client(Context.ConnectionId).SendAsync("ExplicitSong", "You have filtering explicit music turned on in Spotify and there are explicit songs in the queue. We will not play the explicit song for you but continue playback when a non explicit song comes on."); } await Clients.Client(Context.ConnectionId).SendAsync("InitializeWebPlayer", await _partyGoerService.GetPartyGoerAccessTokenAsync(partier)); // make sure that the users spotify is connected if (string.IsNullOrEmpty(await _spotifyHttpClient.GetUsersActiveDeviceAsync(partier.GetId()))) { await Clients.Client(Context.ConnectionId).SendAsync("ConnectSpotify", ""); } await _logService.LogUserActivityAsync(partier, $"Joined real time collobration in party with code {partyCode}"); return; }
public async Task <IActionResult> SuggestedSongs(int limit = 5) { PartyGoer user = new PartyGoer(User.FindFirstValue(ClaimTypes.NameIdentifier)); List <Song> recommendedSongs = await _partyGoerService.GetRecommendedSongsAsync(user.Id); return(new JsonResult(recommendedSongs)); }
public async Task <List <SpotibroModels.Artist> > GetUsersTopArtistsAsync(PartyGoer partier, int amount) { var response = await _spotifyHttpClient.SendHttpRequestAsync(partier, _apiEndpoints[ApiEndpointType.UsersTopArtists]); response.EnsureSuccessStatusCode(); return(_mapper.Convert((await response.Content.ReadFromJsonAsync <PagedObject <SpotifyModels.Artist> >()).Items)); }
public async Task <IActionResult> CheckSpotifyForConnection() { PartyGoer user = new PartyGoer(User.FindFirstValue(ClaimTypes.NameIdentifier)); string deviceName = await _partyGoerService.GetUsersActiveDeviceAsync(user.Id); return(new JsonResult(new { DeviceName = deviceName })); }
public void CannotUpdatePartyThatDoesntExist_ThrowsException() { PartyGoer partyGoer = new PartyGoer(PARTIER_NAME, EXPLICIT, MARKET, PRODUCT); Party party = new Party(partyGoer); Assert.Throws <Exception>(() => PartyRepository.UpdateParty(party)); }
public async Task AddSomeTracksFromPlaylistToQueueAsync(PartyGoer partyGoer, string playlistId, int amount) { SpotibroModels.PlaylistContents playlistTracks = await _partyGoerService.GetPlaylistItemsAsync(partyGoer, playlistId); Party party = await _partyRepository.GetPartyWithAttendeeAsync(partyGoer); await party.AddTracksRandomlyToQueueAsync(playlistTracks.Tracks.GetRandomNItems(amount)); }
public async Task WebPlayerInitialized(string device_id) { PartyGoer partyGoer = await _partyGoerService.GetCurrentPartyGoerAsync(); partyGoer.AddPerferredDeviceId(device_id); await _partyService.SyncListenerWithSongAsync(partyGoer); }
public void JoinParty(PartyGoer partyGoer) { _listeners.TryAdd(partyGoer.GetId(), partyGoer); if (_listeners.Count == 1) { _host = partyGoer; } }