private void UpdateLikeStatus(Guid clientId, string songId, SongLike likeStatus) { var user = this.RavenDb .Query<User>() .FirstOrDefault(u => u.ClientIdentifier == clientId); if (user != null) { var existingLike = this.RavenDb .Query<Like>() .FirstOrDefault(l => l.SongId == songId && l.UserId == user.Id); if (existingLike != null) { existingLike.LikeStatus = likeStatus; } else { var newLikeStatus = new Like() { LikeStatus = likeStatus, SongId = songId, UserId = user.Id, Date = DateTime.Now }; this.RavenDb.Store(newLikeStatus); } // Update the community rank. var songInDb = this.RavenDb .Query<Song>() .FirstOrDefault(s => s.Id == songId); if (songInDb != null) { songInDb.CommunityRank += likeStatus == SongLike.Like ? 1 : -1; user.Preferences.Update(songInDb, likeStatus); // Update song.CommunityRankStanding var communityRankStats = this.RavenDb .Query<Song, Songs_CommunityRankIndex>() .As<Songs_CommunityRankIndex.Results>() .FirstOrDefault(); if (communityRankStats != null) { var averageSongRank = Math.Max(0, (double)communityRankStats.RankSum / communityRankStats.SongCount); var newStanding = Match.Value(songInDb.CommunityRank) .With(v => v <= -5, CommunityRankStanding.VeryPoor) .With(v => v <= -1, CommunityRankStanding.Poor) .With(v => v <= averageSongRank, CommunityRankStanding.Normal) .With(v => v <= averageSongRank * 2, CommunityRankStanding.Good) .With(v => v <= averageSongRank * 3, CommunityRankStanding.Great) .With(v => v <= averageSongRank * 4, CommunityRankStanding.Best) .Evaluate(); songInDb.CommunityRankStanding = newStanding; } } } }
/// <summary> /// Creates a new song object that's ready to be sent as a data transfer object over to the client. /// </summary> /// <param name="likeStatus">The like status for the song.</param> /// <returns></returns> public Song ToDto(SongLike likeStatus) { return new Song { Album = this.Album, Artist = this.Artist, CommunityRank = this.CommunityRank, Id = this.Id, SongLike = likeStatus, Name = this.Name, Number = this.Number, Genre = this.Genre, Description = this.Description, Country = this.Country, PurchaseUri = this.PurchaseUri, AlbumArtUri = GetAlbumArtUri(), Uri = GetSongUri() }; }