/// <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> /// <param name="pickReasons"></param> /// <returns></returns> public virtual Song ToDto(LikeStatus likeStatus, SongPickReasons pickReasons) { return(new Song { Album = Album, Artist = Artist, CommunityRank = CommunityRank, CommunityRankStanding = CommunityRankStanding, Id = Id, SongLike = likeStatus, Name = Name, HebrewName = HebrewName, Number = Number, Uri = Uri, AlbumArtUri = AlbumArtUri, PurchaseUri = PurchaseUri, Genres = Genres, Tags = Tags, Lyrics = Lyrics, TotalPlays = TotalPlays, ReasonsPlayed = pickReasons, AlbumId = AlbumId, ArtistId = ArtistId, CommentCount = CommentCount, AlbumColors = AlbumColors, ContributingArtists = ContributingArtists }); }
/// <summary> /// Добавление лайка /// </summary> /// <param name="context">Конект данных</param> /// <param name="user">Пользователь</param> /// <param name="id">Id страницы</param> /// <param name="status">К какому типу страницы относится лайк(Проект или Статья)</param> /// <returns></returns> public async Task <int?> AddLike(IndieContext context, User user, int id, LikeStatus status) { switch (status) { case LikeStatus.Project: Like like = context.Likes.Include(x => x.Project).Where(x => x.Project.ProjectID == id && x.User == user).FirstOrDefault(); Project project = context.Projects.Where(x => x.ProjectID == id).FirstOrDefault(); if (like == null) { Like newlike = new Like { Project = project, User = user }; context.Likes.Add(newlike); project.Likes.Add(newlike); await context.SaveChangesAsync(); return(context.Likes.Where(x => x.Project == project).Count()); } else { project.Likes.Remove(like); context.Likes.Remove(like); await context.SaveChangesAsync(); return(context.Likes.Where(x => x.Project == project).Count()); } case LikeStatus.Article: Like LikeArticle = context.Likes.Include(x => x.Article).Where(x => x.Article.ID == id && x.User == user).FirstOrDefault(); Article article = context.Articles.Where(x => x.ID == id).FirstOrDefault(); if (LikeArticle == null) { Like newlike = new Like { Article = article, User = user }; context.Likes.Add(newlike); article.Likes.Add(newlike); await context.SaveChangesAsync(); return(context.Likes.Where(x => x.Article == article).Count()); } else { article.Likes.Remove(LikeArticle); context.Likes.Remove(LikeArticle); await context.SaveChangesAsync(); return(context.Likes.Where(x => x.Article == article).Count()); } } return(null); }
private async Task <int> UpdateLikeStatus(string songId, LikeStatus likeStatus) { var userId = GetUserIdOrThrow(); var song = await DbSession.LoadAsync <Song>(songId); if (song == null) { throw new InvalidOperationException("User attempted to update like status, but song wasn't found.") .WithData("User ID", userId) .WithData("Song ID", songId); } var isReversal = false; var isNoChange = false; var likeId = BitShuva.Chavah.Models.Like.GetLikeId(userId, songId); var existingLike = await DbSession.LoadAsync <Like>(likeId); if (existingLike != null) { isReversal = existingLike.Status != likeStatus; isNoChange = existingLike.Status == likeStatus; existingLike.Status = likeStatus; } else { var newLikeStatus = new Like { Status = likeStatus, SongId = songId, UserId = userId, Date = DateTime.UtcNow }; await DbSession.StoreAsync(newLikeStatus, likeId); if (likeStatus == LikeStatus.Like) { await StoreNewLikeActivity(song); } } // Update the community rank. var multiplier = isReversal ? 2 : isNoChange ? 0 : 1; var changePositiveOrNegative = likeStatus == LikeStatus.Like ? 1 : -1; song.CommunityRank += (multiplier * changePositiveOrNegative); await UpdateSongRankStanding(song); return(song.CommunityRank); }
private static void MigrateOldMusicCache() { // configure to use sqlite Dapper.SimpleCRUD.SetDialect(Dapper.SimpleCRUD.Dialect.SQLite); using (DAL.DALManager mgr = new DAL.DALManager(newDatabasePath)) { using (Microsoft.Data.Sqlite.SqliteConnection conn = new Microsoft.Data.Sqlite.SqliteConnection(string.Format("Data Source={0}", oldDatabasePath))) { conn.Open(); var cmd = new Microsoft.Data.Sqlite.SqliteCommand("SELECT * FROM MusicCache", conn); var reader = cmd.ExecuteReader(); while (reader.Read()) { string filename = reader["Filename"] + ""; string md5 = reader["MD5"] + ""; int played = Convert.ToInt32(reader["Played"]); int playedToEnd = Convert.ToInt32(reader["PlayedToEnd"]); DateTime lastPlayed = reader["LastPlayed"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(reader["LastPlayed"]); LikeStatus likeStatus = (LikeStatus)Convert.ToInt32(reader["LikeStatus"]); if (filename.StartsWith("/media/hdd/Dwight/Music/")) { filename = filename.Substring("/media/hdd/Dwight/Music/".Length); } var track = mgr.GetTrackByFilename(filename); if (track != null) { track.NrPlayed = played; track.NrPlayedToEnd = playedToEnd; track.LastPlayed = lastPlayed; track.LikeStatus = likeStatus; mgr.Set(track); var oldScrobbles = GetScrobblesFromOldTrack(md5, track.Id); mgr.SetAll(oldScrobbles); } else { Console.Error.WriteLine("Track with relative path " + filename + " not found"); } } } } }
// TODO: Not Tested public async Task <JObject> RatePlaylist(string playlistId, LikeStatus rating) { string url = GetYTMUrl(PrepareLikeEndpoint(rating)); var data = JObject.FromObject(new { target = JObject.FromObject(new { playlistId = playlistId }) }); var response = await Post <JObject>(url, data, authRequired : true); return(response); }
private string PrepareLikeEndpoint(LikeStatus status) { switch (status) { case LikeStatus.Like: return("like/like"); case LikeStatus.Dislike: return("like/dislike"); case LikeStatus.Indifferent: return("like/removelike"); default: throw new Exception($"Unsupported likestatus value {status}"); } }
public PaginatedUserActivityFeed ConverActivitiesToDTOModels(string currUserId, PaginatedList <UserActivity> activities) { PaginatedUserActivityFeed ret = new PaginatedUserActivityFeed(); var acts = activities.GroupBy(p => p.FeedType); foreach (var item in acts) { switch (item.Key) { case UserActivityType.Add_Post_To_Favourites: var ids = item.Select(p => p.SourceEntityId.Value); if (ids.Count() == 0) { break; } var FavPostActivities = _context.Set <Post>() .AsNoTracking() .Where(p => ids.Contains(p.Id) && p.IsPublished) .Select(p => new Post() { DateUtcAdd = p.DateUtcAdd, DateUtcModified = p.DateUtcModified, DateUtcPublished = p.DateUtcPublished, Description = p.Description, PostParts = p.PostParts, LikedUsers = p.LikedUsers, Content = p.Content, PrivacyStatus = p.PrivacyStatus, Title = p.Title, Collection = p.Collection, UserInfo = p.UserInfo }) .ToList(); foreach (var post in FavPostActivities) { post.Rating = GetPostRating(post.Id, 10); var postActivity = activities .FirstOrDefault(p => p.FeedType == UserActivityType.Add_Post_To_Favourites && p.ParentEntityId == post.Id); ret.Entities.Add(new UserActivityDTO <IActivityEntity>() { DateUtcActivity = postActivity.DateUtcModified, AppUserId = postActivity.AppUserId, FeedType = UserActivityType.Add_Post_To_Favourites, ParentEntityType = ParentEntityType.Post, ParentEntity = _mapper.Map <Post, PostActivityEntity>(post, opt => { opt.Items["AppUserId"] = currUserId; }), }); } break; case UserActivityType.Add_Review_To_Post: var revIds = item.Select(p => p.SourceEntityId.Value).ToArray(); if (revIds.Count() == 0) { break; } var ActivityReviews = _context.Set <Review>() .AsNoTracking() .Where(p => revIds.Contains(p.Id)) .Select(p => new { p.DateUtcAdd, p.DateUtcModified, p.DateUtcPublished, p.IsSoftDeleted, p.Id, p.Content, p.UserInfo, p.UserId, p.PostRate, PostId = p.PostId ?? 0, AuthorImageUrl = p.UserInfo.ProfilePicture.SmallPath, CommentCount = p.Comments.Count(), }); foreach (var review in ActivityReviews) { var reviewActivity = item .FirstOrDefault(p => p.SourceEntityId == review.Id); var reviewedPost = _context.Set <Post>() .AsNoTracking() .Select(p => new PostActivityEntity() { DateUtcPublished = p.DateUtcPublished, AuthorInfo = new BaseUserInfoDisplay() { AppUserId = p.UserInfoId, Name = p.UserInfo.Name, Username = p.UserInfo.UName, Surname = p.UserInfo.Surname, ProfileImage = _userProfileImageSettings.UserImageUrlTemplate.Replace("{#appUserId}", p.UserInfoId) }, Content = p.Content, Title = p.Title, IsCurrentUserLiked = userPostLikesIds.Contains(p.Id), PostParts = p.PostParts.Select(f => new PostPartDisplay() { Description = f.Description, Image = new BaseImageReturn() { Dimension = f.Image.ImageDimension, Extension = f.Image.FileExtension, LazyUrl = f.Image.BlurLazyPath, SmallUrl = f.Image.SmallPath, ThumbUrl = f.Image.ThumbPath, Url = f.Image.ResizedPath, }, Title = f.Title, Id = f.Id }).ToList(), Id = p.Id, }) .FirstOrDefault(p => p.Id == reviewActivity.ParentEntityId); reviewedPost.Rating = GetPostRating(reviewedPost.Id, 10); reviewedPost.FavouriteCount = _postCacheService.GetPostLikesCount(reviewedPost.Id) ?? _postDataService.GetPostLikeCount(reviewedPost.Id, cacheTreshold: 20); reviewedPost.ReviewCount = _postDataService.GetPostReviewsCount(reviewedPost.Id); LikeStatus ls = userReviewLikesIds.Contains(review.Id) ? LikeStatus.Like : LikeStatus.None; if (userReviewDislikesIds.Contains(review.Id)) { ls = LikeStatus.Dislike; } ReviewActivityEntity reviewActivityInfo = new ReviewActivityEntity() { CommentCount = review.CommentCount, DateUtcPublished = review.DateUtcPublished, PostId = review.PostId, LikeStatus = ls, DislikeCount = _reviewCacheService.GetReviewDislikeCount(review.Id) ?? _reviewDataService.GetReviewDislikeCount(review.Id, 10), Content = review.Content, Id = review.Id, PostRate = review.PostRate ?? 0, LikeCount = _reviewCacheService.GetReviewLikeCount(review.Id) ?? _reviewDataService.GetReviewLikeCount(review.Id, 100), AuthorInfo = new BaseUserInfoDisplay() { AppUserId = review.UserInfo.AppUserId, Name = review.UserInfo.Name, ProfileImage = review.AuthorImageUrl, Surname = review.UserInfo.Surname, Username = review.UserInfo.UName } }; ret.Entities.Add(new UserActivityDTO <IActivityEntity>() { Id = reviewActivity.Id, DateUtcActivity = reviewActivity.DateUtcModified, AppUserId = reviewActivity.AppUserId, FeedType = UserActivityType.Add_Review_To_Post, ParentEntityType = ParentEntityType.Post, ParentEntity = reviewedPost, PrimaryEntity = reviewActivityInfo }); } break; case UserActivityType.Like_Review_Of_Post: // Liked Review var reviewIds = item.Select(p => p.SourceEntityId.Value); if (reviewIds.Count() == 0) { break; } // Liked Reviews var ActivityLikeReviews = _context.Set <Review>() .Select(p => new Review() { DateUtcAdd = p.DateUtcAdd, DateUtcModified = p.DateUtcModified, DateUtcPublished = p.DateUtcPublished, IsSoftDeleted = p.IsSoftDeleted, UserLikes = p.UserLikes, Id = p.Id, Content = p.Content, UserInfo = p.UserInfo, UserId = p.UserId, PostRate = p.PostRate }) .AsNoTracking().Where(p => reviewIds.Contains(p.Id)).ToList(); // For Each Liked Review foreach (var review in ActivityLikeReviews) { // Belonging Activity var reviewActivity = item .FirstOrDefault(p => p.SourceEntityId == review.Id && p.FeedType == UserActivityType.Like_Review_Of_Post); // Reviewed Post var reviewedPost = _context.Set <Post>() .AsNoTracking() .Select(p => new PostActivityEntity() { DateUtcPublished = p.DateUtcPublished, AuthorInfo = new BaseUserInfoDisplay() { AppUserId = p.UserInfoId, Name = p.UserInfo.Name, Username = p.UserInfo.UName, Surname = p.UserInfo.Surname, ProfileImage = _userProfileImageSettings.UserImageUrlTemplate.Replace("{#appUserId}", p.UserInfo.AppUserId) }, Content = p.Content, IsCurrentUserLiked = userPostLikesIds.Contains(p.Id), PostParts = p.PostParts.Select(f => new PostPartDisplay() { Description = f.Description, Image = new BaseImageReturn() { Dimension = f.Image.ImageDimension, Extension = f.Image.FileExtension, LazyUrl = f.Image.BlurLazyPath, SmallUrl = f.Image.SmallPath, ThumbUrl = f.Image.ThumbPath, Url = f.Image.ResizedPath, }, Title = f.Title, Id = f.Id }).ToList(), Id = p.Id, ReviewCount = p.Reviews.Count() }) .FirstOrDefault(p => p.Id == reviewActivity.ParentEntityId); // Add Activity DTO to return List ret.Entities.Add(new UserActivityDTO <IActivityEntity>() { Id = reviewActivity.Id, DateUtcActivity = reviewActivity.DateUtcModified, AppUserId = reviewActivity.AppUserId, FeedType = UserActivityType.Like_Review_Of_Post, ParentEntityType = ParentEntityType.Post, ParentEntity = reviewedPost, PrimaryEntity = _mapper.Map <Review, ReviewActivityEntity>(review, opt => { opt.Items["AppUserId"] = currUserId; }) }); } break; case UserActivityType.Add_Comment_To_Review: // CommentsIds var commentIds = item.Select(p => p.SourceEntityId.Value); if (commentIds.Count() == 0) { break; } // Get User Likes From Cache // Comments from DB var ActivityComments = _context.Set <Comment>() .Select(p => new Comment() { DateUtcAdd = p.DateUtcAdd, DateUtcModified = p.DateUtcModified, IsSoftDeleted = p.IsSoftDeleted, Id = p.Id, Content = p.Content, CommentLikes = p.CommentLikes, }) .AsNoTracking().Where(p => commentIds.Contains(p.Id)).ToList(); // Each commentActivity get belonging Review foreach (var comment in ActivityComments) { var commentActivity = item .FirstOrDefault(p => p.SourceEntityId == comment.Id && p.FeedType == UserActivityType.Add_Comment_To_Review); var commentedReview = _context.Set <Review>() .AsNoTracking() .Select(f => new { Review = f, ReviewLikeCount = f.UserLikes.Where(p => p.LikeStatus == LikeStatus.Like).Count(), AuthorInfo = f.UserInfo, }) .Select(p => new CommentReviewActivityEntity() { AuthorInfo = new BaseUserInfoDisplay() { AppUserId = p.AuthorInfo.AppUserId, Name = p.AuthorInfo.Name, ProfileImage = _userProfileImageSettings.UserImageUrlTemplate.Replace("{#appUserId}", p.AuthorInfo.AppUserId), Surname = p.AuthorInfo.Surname, Username = p.AuthorInfo.UName }, Id = p.Review.Id, Content = p.Review.Content, IsUserLiked = this.userReviewLikesIds.Contains(p.Review.Id), LikeCount = p.ReviewLikeCount, }) .FirstOrDefault(p => p.Id == commentActivity.ParentEntityId); commentedReview.CommentCount = _reviewCacheService.GetReviewCommentCount(commentedReview.Id) ?? _reviewDataService.GetReviewCommentCount(commentedReview.Id, 20); commentedReview.LikeCount = _reviewCacheService.GetReviewLikeCount(commentedReview.Id) ?? _reviewDataService.GetReviewLikeCount(commentedReview.Id, cacheTreshold: 10); commentedReview.DislikeCount = _reviewCacheService.GetReviewDislikeCount(commentedReview.Id) ?? _reviewDataService.GetReviewDislikeCount(commentedReview.Id, 10); ret.Entities.Add(new UserActivityDTO <IActivityEntity>() { Id = commentActivity.Id, DateUtcActivity = commentActivity.DateUtcModified, AppUserId = commentActivity.AppUserId, FeedType = UserActivityType.Add_Comment_To_Review, ParentEntityType = ParentEntityType.Review, ParentEntity = commentedReview, PrimaryEntity = new CommentActivityEntity() { DateUtcAdded = comment.DateUtcAdd, DateUtcModified = comment.DateUtcModified, DislikeCount = comment.CommentLikes.Count(p => p.LikeStatus == LikeStatus.Dislike), LikeCount = comment.CommentLikes.Count(p => p.LikeStatus == LikeStatus.Like), Content = comment.Content, Id = comment.Id, IsUserDisliked = userCommentLikesIds.Contains(comment.Id), IsUserLiked = userCommentDislikesIds.Contains(comment.Id), } }); } break; case UserActivityType.Add_Comment_To_Comment: break; case UserActivityType.Like_Comment: break; case UserActivityType.Follow_User: break; case UserActivityType.Add_New_Collection: var colActIds = item.Select(p => p.SourceEntityId); if (colActIds.Count() == 0) { break; } var AddCollectionActivities = _context.Set <PostCollection>() .AsNoTracking() .Select(col => new { Collection = col, PostCount = col.Posts.Count(), col.ThumbFile, col.UserInfo }) .Where(p => colActIds.Contains(p.Collection.Id)).ToList(); var AddCollectionActivityDtos = AddCollectionActivities.Select(p => new AddCollectionActivityEntity() { DateUtcModified = p.Collection.DateUtcModified, UserInfo = new BaseUserInfoDisplay() { AppUserId = p.UserInfo.AppUserId, Name = p.UserInfo.Name, ProfileImage = _userProfileImageSettings.UserImageUrlTemplate.Replace("{#appUserId}", p.UserInfo.AppUserId), Surname = p.UserInfo.Surname, Username = p.UserInfo.UName }, Name = p.Collection.Name, Id = p.Collection.Id, PostsCount = p.PostCount, Description = p.Collection.Description, ThumbImageUrl = p.ThumbFile == null ? "" : p.ThumbFile.ThumbPath, UserInfoId = p.UserInfo.AppUserId, }); foreach (var col in AddCollectionActivityDtos) { var colActivity = activities .FirstOrDefault(p => p.FeedType == UserActivityType.Add_New_Collection && p.SourceEntityId == col.Id); ret.Entities.Add(new UserActivityDTO <IActivityEntity>() { Id = colActivity.Id, DateUtcActivity = colActivity.DateUtcModified, AppUserId = colActivity.AppUserId, FeedType = UserActivityType.Add_New_Collection, ParentEntityType = ParentEntityType.None, PrimaryEntity = col }); } break; case UserActivityType.Add_New_Post: var actIds = item.Select(p => p.SourceEntityId); if (actIds.Count() == 0) { break; } var AddPostActivities = _context.Set <Post>() .AsNoTracking() .Include(p => p.PostParts) .ThenInclude(p => p.Image) .Where(p => actIds.Contains(p.Id) && p.IsPublished) .Select(post => new { Post = post, post.PostParts, post.UserInfo, post.Collection, post.Groups }); var AddPostActivityDtos = AddPostActivities.Select(p => new PostActivityEntity() { DateUtcPublished = p.Post.DateUtcPublished, AuthorInfo = new BaseUserInfoDisplay() { AppUserId = p.UserInfo.AppUserId, Name = p.UserInfo.Name, ProfileImage = _userProfileImageSettings.UserImageUrlTemplate.Replace("{#appUserId}", p.UserInfo.AppUserId), Surname = p.UserInfo.Surname, Username = p.UserInfo.UName }, Content = p.Post.Content, Title = p.Post.Title, IsCurrentUserLiked = userPostLikesIds.Contains(p.Post.Id), Id = p.Post.Id, PostParts = p.PostParts.Select(f => new PostPartDisplay() { Description = f.Description, Id = f.Id, Title = f.Title, Image = new BaseImageReturn() { Dimension = f.Image.ImageDimension, Extension = f.Image.FileExtension, LazyUrl = f.Image.BlurLazyPath, ThumbUrl = f.Image.ThumbPath, SmallUrl = f.Image.SmallPath, Url = f.Image.ResizedPath, } }).ToList() }); foreach (var post in AddPostActivityDtos) { post.Rating = GetPostRating(post.Id, 10); post.CollectionInfo = post.CollectionInfo ?? new PostCollectionInfo() { }; post.IsCurrentUserLiked = userPostLikesIds.Contains(post.Id); post.FavouriteCount = _postCacheService.GetPostLikesCount(post.Id) ?? _postDataService.GetPostLikeCount(post.Id, cacheTreshold: 20); post.ReviewCount = _postDataService.GetPostReviewsCount(post.Id); var postActivity = activities .FirstOrDefault(p => p.FeedType == UserActivityType.Add_New_Post && p.SourceEntityId == post.Id); ret.Entities.Add(new UserActivityDTO <IActivityEntity>() { Id = postActivity.Id, DateUtcActivity = postActivity.DateUtcModified, AppUserId = postActivity.AppUserId, FeedType = UserActivityType.Add_New_Post, ParentEntityType = ParentEntityType.None, PrimaryEntity = post }); } break; case UserActivityType.Add_New_Post_To_Collection: break; case UserActivityType.Post_Got_In_Trends: break; default: break; } } ret.Entities = ret.Entities.OrderByDescending(p => p.DateUtcActivity).ToList().ToPaginatedList(activities.PageIndex, activities.PageSize, activities.TotalCount); return(ret); }
public JsonResult CommentLikeSubmit(string pid, string cid) { string message = string.Empty; string html = string.Empty; string _loginUser = User.Identity.Name.ToString(); int _postId = Convert.ToInt32(pid); int _pComId = Convert.ToInt32(cid); Post _post = db.Posts.Where(x => x.PostId == _postId).FirstOrDefault(); PostComment _postComment = db.PostComments.Where(x => x.CommentId == _pComId).FirstOrDefault(); User _CurrUser = db.Users.Where(x => x.UserName == _loginUser).FirstOrDefault(); if (!String.IsNullOrEmpty(pid) && _postComment != null) { try { bool isComLike = false; if (_postComment.LikeStatues.Count() > 0) { var vLikes = _postComment.LikeStatues.ToList(); var vUsr = from comlks in _postComment.LikeStatues.ToList() from comusr in comlks.Users.Where(x => x.UserName == _loginUser) select comlks; var _userLike = vUsr.FirstOrDefault(); if (_userLike != null) { isComLike = true; //for remove like _postComment.LikeStatues.Remove(_userLike); db.SaveChanges(); html = "Like"; } } if (isComLike == false) { int _cLkId = db.LikeStatues.Count(); _cLkId++; //for new like List <User> lstUser = new List <User>(); lstUser.Add(_CurrUser); LikeStatus _likeStatus = new LikeStatus(); _likeStatus.LikeId = "" + _cLkId; _likeStatus.Users = lstUser; List <LikeStatus> lstLike = new List <LikeStatus>(); lstLike.Add(_likeStatus); _postComment.LikeStatues = lstLike; db.PostComments.Attach(_postComment); db.Entry(_postComment).State = EntityState.Modified; db.SaveChanges(); html = "UnLike"; } } catch (Exception ex) { message = ex.Message; } } else { message = "Donot insert"; } return(Json(new { Html = html, Message = message }, JsonRequestBehavior.AllowGet)); }
// Add a property here? It should probably be added to .ToDto() /// <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> /// <param name="playedReason"></param> /// <returns></returns> public Song ToDto(LikeStatus likeStatus, SongPick playedReason) { return(ToDto(likeStatus, SongPickReasons.FromSoleReason(playedReason))); }