public ActionResult UnlikeComment(int?id)
        {
            int userId = int.Parse(User.Identity.Name);

            // Check if user liked this comment
            bool liked = db.CommentLikes.Where(l => l.commentId == id).Any(l => l.userId == userId);

            if (liked)
            {
                CommentLike like = db.CommentLikes.Where(l => l.commentId == id).Single(l => l.userId == userId);

                Comment comment = db.Comments.Find(id);
                comment.likes--;

                db.CommentLikes.Remove(like);
                db.SaveChanges();

                if (Request.QueryString["url"] == null)
                {
                    return(Redirect("/posts/details/" + comment.post.id));
                }
                else
                {
                    return(Redirect(Request.QueryString["url"]));
                }
            }

            return(Redirect("/"));
        }
Пример #2
0
        public IActionResult LikeComment(int commentId)
        {
            String[] authorization = Request.Headers["authorization"].ToString().Split(" ");
            String   token         = authorization[1];
            String   userId        = ((JwtSecurityToken) new JwtSecurityTokenHandler().ReadToken(token)).Claims.First(claim => claim.Type == "id").Value;

            try
            {
                var likeExists = _db.CommentLikes.SingleOrDefault(l => l.CommentId == commentId && l.UserId == Int32.Parse(userId));
                if (likeExists == null)
                {
                    var like = new CommentLike
                    {
                        CommentId = commentId,
                        UserId    = Int32.Parse(userId),
                    };
                    _db.CommentLikes.Add(like);
                    var numLikes = ++_db.Comments.Single(p => p.Id == commentId).Likes;
                    _db.SaveChanges();

                    return(Ok(new { message = "like success", numLikes }));
                }
                else
                {
                    _db.CommentLikes.Remove(likeExists);
                    var numLikes = --_db.Comments.Single(p => p.Id == commentId).Likes;
                    _db.SaveChanges();
                    return(Ok(new { message = "like deleted", numLikes }));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(500, $"Internal server error: {ex}"));
            }
        }
Пример #3
0
        public async Task <IActionResult> PutCommentLike(int id, CommentLike commentLike)
        {
            if (id != commentLike.Id)
            {
                return(BadRequest());
            }

            _context.Entry(commentLike).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CommentLikeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Пример #4
0
        public async Task <IActionResult> AddCommentLike([FromBody] VideoCommentVM vm)
        {
            if (vm.VideoCommentId <= 0)
            {
                return(NotFound());
            }

            var user = await _userManager.FindByIdAsync(User.Identity.Name);

            if (user == null)
            {
                return(NotFound());
            }

            CommentLike commentLike = new CommentLike
            {
                UserId         = user.Id,
                VideoCommentId = vm.VideoCommentId
            };

            await _vclRepository.AddAsync(commentLike);

            await _vclRepository.CommitAsync();

            return(CreatedAtRoute("FindUserLikedComment", new
            {
                controller = "CardDetail",
                id = commentLike.VideoCommentId
            }, null));
        }
        public ActionResult LikeComment(int?id)
        {
            int userId = int.Parse(User.Identity.Name);

            // Check if user didn't liked this comment
            bool liked = db.CommentLikes.Where(l => l.commentId == id).Any(l => l.userId == userId);

            if (!liked)
            {
                CommentLike like = new CommentLike();
                like.commentId = (int)id;
                like.userId    = userId;
                like.createdAt = DateTime.Now;

                Comment comment = db.Comments.Find(id);
                comment.likes++;

                db.CommentLikes.Add(like);
                db.SaveChanges();

                if (Request.QueryString["url"] == null)
                {
                    return(Redirect("/posts/details/" + comment.post.id));
                }
                else
                {
                    return(Redirect(Request.QueryString["url"]));
                }
            }

            return(Redirect("/"));
        }
Пример #6
0
        //________________________________________________________________________________
        public async Task <IActionResult> DisLikeComment(int?id)
        {
            var currentUserId = Tools.GetCurrentUserId(User);

            ViewBag.UserId = currentUserId;

            var comment        = _context.Comments.FirstOrDefault(c => c.Id == id);
            var commentDislike = _context.CommentLikes.FirstOrDefault(cl => !cl.IsLike && cl.ApplicationStoreUserId == currentUserId && cl.CommentId == id);
            var commentLike    = _context.CommentLikes.FirstOrDefault(cl => cl.IsLike && cl.ApplicationStoreUserId == currentUserId && cl.CommentId == id);

            if (commentDislike == null)
            {
                if (commentLike != null)
                {
                    commentLike.IsLike = false;
                }
                else
                {
                    var newCommentLike = new CommentLike()
                    {
                        IsLike = false,
                        ApplicationStoreUserId = currentUserId,
                        CommentId = (int)id
                    };
                    _context.CommentLikes.Add(newCommentLike);
                }

                await _context.SaveChangesAsync();
            }
            return(RedirectToAction(nameof(Details), new RouteValueDictionary(
                                        new { controller = "Home", action = nameof(Details), Id = comment.ApplicationPublishId })));
        }
Пример #7
0
        public async Task Comments(string content, int postId, string userId)
        {
            var post = await db.Posts.FindAsync(postId);

            var user = await db.People.FindAsync(userId);

            var newComment = new Comment
            {
                Content = content,
                Post    = post,
                User    = user
            };
            var defaultLike = new CommentLike
            {
                Comment = newComment,
                User    = user,
                IsLike  = false
            };

            db.CommentLikes.Add(defaultLike);
            db.Comments.Add(newComment);
            await db.SaveChangesAsync();

            await Clients.All.SendAsync("ContentComment", newComment.Content, newComment.User.UserName, newComment.Created.ToString("MM/dd/yyyy"), newComment.CommentId, user.Id, defaultLike.IsLike.ToString().ToLower());
        }
        public IActionResult AddLikeToComment(int commentId)
        {
            var userName = User.Identity.Name;
            var user     = db.Users.FirstOrDefault(u => u.Email == userName);
            var comment  = db.Comments.FirstOrDefault(c => c.Id == commentId);

            if (user == null || comment == null)
            {
                return(NotFound());
            }

            var existingLike = db.CommentsLikes.FirstOrDefault(cl => cl.User.Id == user.Id && cl.Comment.Id == comment.Id);

            if (existingLike != null)
            {
                return(BadRequest());
            }

            var like = new CommentLike {
                Comment = comment, User = user
            };

            db.CommentsLikes.Add(like);
            comment.Rating += 1;
            db.SaveChanges();

            return(Ok());
        }
        public async Task <int> CommentDislike(int?id)
        {
            if (id == null)
            {
                return(-1);
            }
            Comment comment = await _db.Comments.FindAsync(id);

            if (comment == null)
            {
                return(-1);
            }
            User currentUser = await _userManager.GetUserAsync(User);

            CommentLike commentLike = _db.CommentLikes.Where(p => p.UserId == currentUser.Id && p.CommentId == id).FirstOrDefault();

            if (currentUser.Id != comment.UserId)
            {
                Notification notification = _db.Notifications.Where(n => n.NotificationFromId == currentUser.Id && n.NotificationToId == comment.UserId && n.PostId == comment.PostId && n.NotificationTypeId == 2).FirstOrDefault();
                _db.Notifications.Remove(notification);
            }
            _db.CommentLikes.Remove(commentLike);
            await _db.SaveChangesAsync();

            int newLikesCount = _db.CommentLikes.Where(p => p.CommentId == id).Count();

            return(newLikesCount);
        }
Пример #10
0
        public async Task Comment(int commentId, string userId, bool isLike)
        {
            var comment = await db.Comments.FirstOrDefaultAsync(c => c.CommentId == commentId);

            var user = await db.People.FindAsync(userId);

            var existLike = await db.CommentLikes.FirstOrDefaultAsync(c => c.CommentId == commentId && c.UserId == userId);

            if (existLike == null)
            {
                var like = new CommentLike
                {
                    Comment = comment,
                    User    = user,
                    IsLike  = !isLike
                };
                await db.CommentLikes.AddAsync(like);

                await db.SaveChangesAsync();
            }
            else
            {
                existLike.IsLike = !existLike.IsLike;//update exist like
                await db.SaveChangesAsync();
            }

            comment.LikesCount = LikeCounter(commentId);
            await db.SaveChangesAsync();

            var curentUserLike = await db.CommentLikes.FirstOrDefaultAsync(c => c.Comment == comment && c.User == user);

            await Clients.All.SendAsync("CommentLikes", comment.LikesCount, curentUserLike.IsLike, commentId);
        }
Пример #11
0
        public void Equals_DifferentComment_False()
        {
            // Arrange
            Comment comment1 = new Comment()
            {
                Text = "Comment 1"
            };
            Comment comment2 = new Comment()
            {
                Text = "Comment 2"
            };

            CommentLike commentLike1 = new CommentLike {
                Id = System.Guid.Empty, IsLiked = true, Comment = comment1
            };
            CommentLike commentLike2 = new CommentLike {
                Id = System.Guid.Empty, IsLiked = true, Comment = comment2
            };

            // Act
            // Assert
            Assert.IsFalse(commentLike1.Equals(commentLike2));
            Assert.AreNotEqual(commentLike1, commentLike2);
            Assert.AreNotSame(commentLike1, commentLike2);
        }
Пример #12
0
        public void CanExecuteExplicitFalse()
        {
            // Arrange
            CommentLike commentLike = new CommentLike
            {
                IsLiked = true
            };
            RelayCommand relayCommand = new RelayCommand
                                        (
                execute: o =>
            {
                CommentLike changeCommentLike = o as CommentLike;
                if (changeCommentLike != null)
                {
                    changeCommentLike.IsLiked = false;
                }
            },
                canExecute: o => (o as CommentLike).IsLiked == false
                                        );
            bool expectedCanExecute = false;

            // Act
            bool actualCanExecute = relayCommand.CanExecute(commentLike);

            // Assert
            Assert.AreEqual(expectedCanExecute, actualCanExecute);
        }
Пример #13
0
        public void DeleteUser_AndPhotoAndPhotoLikeAndCommentAndCommentLike_Cascade()
        {
            // Arrange
            Photo photo1 = new Photo()
            {
                Path = "1/54/23.jpg"
            };
            Photo photo2 = new Photo()
            {
                Path = "1/54/24.jpg"
            };

            User user1 = new User()
            {
                NickName = "John",
                Password = "******",
                Photos   = new List <Photo> {
                    photo1, photo2
                }
            };
            Comment comment = new Comment()
            {
                Text  = "Comment text",
                Date  = DateTime.Now,
                Photo = photo1,
                User  = user1
            };
            CommentLike commentLike = new CommentLike()
            {
                IsLiked = true, Comment = comment
            };
            PhotoLike photoLike = new PhotoLike()
            {
                IsLiked = true, Photo = photo1
            };
            User user2 = new User()
            {
                NickName = "Adam", Password = "******", CommentLikes = new List <CommentLike> {
                    commentLike
                }
            };

            // Act
            dbContext.Users.Add(user1);
            dbContext.Users.Add(user2);
            dbContext.Users.Remove(user1);
            dbContext.SaveChanges();

            // Assert
            CollectionAssert.Contains(dbContext.Users.ToArray(), user2);
            CollectionAssert.DoesNotContain(dbContext.Users.ToArray(), user1);
            CollectionAssert.DoesNotContain(dbContext.Photos.ToArray(), photo2);
            CollectionAssert.DoesNotContain(dbContext.Photos.ToArray(), photo1);
            CollectionAssert.DoesNotContain(dbContext.PhotoLike.ToArray(), photoLike);
            CollectionAssert.DoesNotContain(dbContext.Comments.ToArray(), comment);
            CollectionAssert.DoesNotContain(dbContext.CommentLike.ToArray(), commentLike);

            CollectionAssert.DoesNotContain(dbContext.Users.First(u => u.NickName == user2.NickName).CommentLikes.ToArray(), commentLike);
        }
 public static CommentLikeViewModel Create(CommentLike commentLike)
 {
     return(new CommentLikeViewModel()
     {
         CommentId = commentLike.CommentId,
         User = UserViewModelMinified.Create(commentLike.User)
     });
 }
Пример #15
0
        public async Task <HttpResponseMessage> LikeComment([FromUri] int postId, [FromUri] int commentId)
        {
            var post = this.Data.GroupPosts.Find(postId);

            if (post == null)
            {
                return(await this.NotFound().ExecuteAsync(new CancellationToken()));
            }

            var comment = this.Data.Comments.Find(commentId);

            if (comment == null)
            {
                return(await this.NotFound().ExecuteAsync(new CancellationToken()));
            }
            if (!post.Comments.Contains(comment))
            {
                return(await this.NotFound().ExecuteAsync(new CancellationToken()));
            }

            var currentUserId = User.Identity.GetUserId();
            var currentUser   = this.Data.Users.FirstOrDefault(x => x.Id == currentUserId);

            if (currentUser == null)
            {
                return(await this.BadRequest("Invalid user token! Please login again!")
                       .ExecuteAsync(new CancellationToken()));
            }

            if (comment.Likes.Any(l => l.Author == currentUser))
            {
                return(await this.BadRequest("You have already liked this comment.")
                       .ExecuteAsync(new CancellationToken()));
            }

            if (!post.Owner.Members.Contains(currentUser) && currentUser != post.Owner.Owner)
            {
                return(await this.BadRequest("Not allowed. You must be member of the group.")
                       .ExecuteAsync(new CancellationToken()));
            }

            var like = new CommentLike()
            {
                Author = currentUser
            };

            comment.Likes.Add(like);
            this.Data.SaveChanges();

            var commentPreview = this.Data.Comments
                                 .Where(c => c.Id == comment.Id)
                                 .Select(CommentViewModel.Create)
                                 .FirstOrDefault();

            commentPreview.Liked = true;

            return(await this.Ok(commentPreview).ExecuteAsync(new CancellationToken()));
        }
Пример #16
0
        public ActionResult Delete(int CommentId, string UserId)
        {
            CommentLike ToDelete = db.CommentLikes.Find(CommentId, UserId);

            db.CommentLikes.Remove(ToDelete);
            db.Comments.Find(CommentId).LikeCount--;
            db.SaveChanges();
            return(Redirect("/Posts/Show/" + db.Comments.Find(CommentId).PostId));
        }
Пример #17
0
        public void Equals_NullValue_Exception()
        {
            // Arrange
            CommentLike commentLike1 = new CommentLike();
            CommentLike commentLike2 = null;

            // Act
            // Assert
            Assert.ThrowsException <System.ArgumentNullException>(() => commentLike1.Equals(commentLike2));
        }
Пример #18
0
        public ActionResult Like(CommentLikeInputModel input)
        {
            if (this.ModelState.IsValid)
            {
                var comment = this.Data.Comments.GetById(input.CommentId);
                if (comment == null || comment.IsDeleted)
                {
                    return(this.HttpNotFound());
                }

                var userId = this.User.Identity.GetUserId();
                if (comment.AuthorId == userId)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }

                var isLiked =
                    this.Data.CommentLikes.All()
                    .Any(l => l.UserId == userId && l.CommentId == input.CommentId && !l.IsDeleted);

                if (isLiked)
                {
                    return(this.Dislike(input));
                }

                var newLike = new CommentLike {
                    UserId = userId, CommentId = input.CommentId
                };

                this.Data.CommentLikes.Add(newLike);
                this.Data.SaveChanges();

                var likesCount = this.Data.CommentLikes.All().Count(a => a.CommentId == input.CommentId);

                input.IsLiked    = true;
                input.LikesCount = likesCount;

                var newNotification = new Notification
                {
                    NotificationType = NotificationType.LikePost,
                    ItemId           = comment.Id,
                    SenderId         = userId,
                    ReceiverId       = comment.AuthorId
                };

                this.Data.Notifications.Add(newNotification);
                this.Data.SaveChanges();

                this.UpdateNotificationsCount(comment.Author);

                return(this.PartialView(input));
            }

            return(this.JsonError("Comment id is required"));
        }
 public void UpdateCommentLike(CommentLike commentLike)
 {
     Requires.NotNull(commentLike);
     Requires.NotNull(commentLike.CommentId);
     using (var context = DataContext.Instance())
     {
         var rep = context.GetRepository <CommentLike>();
         rep.Update("SET Datime=@0 WHERE CommentId=@1 AND UserId=@2",
                    commentLike.Datime, commentLike.CommentId, commentLike.UserId);
     }
 }
Пример #20
0
        public void Equals_TheSameInstance_True()
        {
            // Arrange
            CommentLike commentLike = new CommentLike();

            // Act
            // Assert
            Assert.IsTrue(commentLike.Equals(commentLike));
            Assert.AreEqual(commentLike, commentLike);
            Assert.AreSame(commentLike, commentLike);
        }
        /// <summary>
        /// Adds a like to the comment
        /// </summary>
        /// <param name="commentId">The Id of the comment to be liked</param>
        /// <param name="userId">The user who is making the request</param>
        /// <returns>Nothing</returns>
        public async Task AddLikeToComment(int commentId, string userId)
        {
            CommentLike newLike = new CommentLike()
            {
                CommentId = commentId,
                UserId    = userId
            };

            _context.Entry(newLike).State = EntityState.Added;
            await _context.SaveChangesAsync();
        }
Пример #22
0
        public async Task <bool> LikeOrDislikeCommentAsync(int userId, int commentId)
        {
            using (var transaction = _photoSNDbContext.Database.BeginTransaction())
            {
                try
                {
                    var user = await _photoSNDbContext.Users.FindAsync(userId);

                    if (user == null)
                    {
                        throw new ArgumentException($"User with id {userId} does not exist.");
                    }
                    var comment = await _photoSNDbContext.Comments.FindAsync(commentId);

                    if (comment == null)
                    {
                        throw new ArgumentException($"Comment with id {commentId} does not exist.");
                    }

                    var existingCommentLike = await _photoSNDbContext.CommentLikes
                                              .FirstOrDefaultAsync(cl => cl.User == user && cl.Comment == comment);

                    bool isLikedNow;
                    if (existingCommentLike == null)
                    {
                        var newCommentLike = new CommentLike
                        {
                            CommentId = commentId,
                            UserId    = userId,
                            Created   = DateTime.Now
                        };
                        await _photoSNDbContext.CommentLikes.AddAsync(newCommentLike);

                        isLikedNow = true;
                    }
                    else
                    {
                        _photoSNDbContext.CommentLikes.Remove(existingCommentLike);
                        isLikedNow = false;
                    }

                    await _photoSNDbContext.SaveChangesAsync();

                    await transaction.CommitAsync();

                    return(isLikedNow);
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    throw e;
                }
            }
        }
Пример #23
0
        public void Equals_TheSameReference_True()
        {
            // Arrange
            CommentLike commentLike1 = new CommentLike();
            CommentLike commentLike2 = commentLike1;

            // Act
            // Assert
            Assert.IsTrue(commentLike1.Equals(commentLike2));
            Assert.AreEqual(commentLike1, commentLike2);
            Assert.AreSame(commentLike1, commentLike2);
        }
        public void TryGetUserLike()
        {
            // Arrange
            CommentLikeRepository commentLikeRepository     = new CommentLikeRepository(dbContext);
            CommentLike           expectedCommentLikeFromDb = dbContext.CommentLike.First();

            // Act
            CommentLike actualCommentLikeFromDb = commentLikeRepository.TryGetUserLike(expectedCommentLikeFromDb.Comment, expectedCommentLikeFromDb.User);

            // Assert
            Assert.AreEqual(expectedCommentLikeFromDb, actualCommentLikeFromDb);
        }
Пример #25
0
        public void Equals_DifferentType_False()
        {
            // Arrange
            CommentLike commentLike = new CommentLike();
            Subject     subject     = new Subject();

            // Act
            // Assert
            Assert.IsFalse(commentLike.Equals(subject));
            Assert.AreNotEqual(commentLike, subject);
            Assert.AreNotSame(commentLike, subject);
        }
Пример #26
0
        public IHttpActionResult LikeComment([FromUri] int postId, [FromUri] int commentId)
        {
            var post = this.Data.Posts.Find(postId);

            if (post == null)
            {
                return(this.NotFound());
            }

            var comment = post.Comments.FirstOrDefault(c => c.Id == commentId);

            if (comment == null)
            {
                return(this.NotFound());
            }

            var currentUserId = User.Identity.GetUserId();
            var currentUser   = this.Data.Users.FirstOrDefault(x => x.Id == currentUserId);

            if (currentUser == null)
            {
                return(this.BadRequest("Invalid user token! Please login again!"));
            }

            var postCommentLikes = this.Data.CommentLikes
                                   .Where(cl => cl.Comment.Id == comment.Id);

            if (!comment.Author.Friends.Contains(currentUser) &&
                !post.Owner.Friends.Contains(currentUser) &&
                comment.Author != currentUser)
            {
                return(this.BadRequest("Not allowed. Either wall-owner or author must be friends."));
            }

            if (postCommentLikes.Any(l => l.Author.Id == currentUserId))
            {
                return(this.BadRequest("Comment is already liked."));
            }

            var newLikeToAdd = new CommentLike()
            {
                Author = currentUser
            };

            comment.Likes.Add(newLikeToAdd);
            this.Data.SaveChanges();

            var commentLikeViewModel = this.Data.Comments.Where(c => c.Id == commentId)
                                       .Select(LikedCommentViewModel.Create);

            return(this.Ok(commentLikeViewModel));
        }
        public void DeleteByValue()
        {
            // Arrange
            CommentLikeRepository commentLikeRepository = new CommentLikeRepository(dbContext);
            CommentLike           commentLikeToDelete   = dbContext.CommentLike.First();

            // Act
            commentLikeRepository.Delete(commentLikeToDelete);
            dbContext.SaveChanges();

            // Assert
            CollectionAssert.DoesNotContain(dbContext.CommentLike.ToArray(), commentLikeToDelete);
        }
        public void GetByWrongId_Null()
        {
            // Arrange
            CommentLikeRepository commentLikeRepository = new CommentLikeRepository(dbContext);
            Guid        wrongId = default(Guid);
            CommentLike expectedCommentLikeFromDb = null;

            // Act
            CommentLike actualCommentLikeFromDb = commentLikeRepository.Get(wrongId);

            // Assert
            Assert.AreEqual(expectedCommentLikeFromDb, actualCommentLikeFromDb);
        }
        public void GetById()
        {
            // Arrange
            CommentLikeRepository commentLikeRepository = new CommentLikeRepository(dbContext);
            Guid        idToSearch          = dbContext.CommentLike.First().Id;
            CommentLike expectedCommentLike = dbContext.CommentLike.Find(idToSearch);

            // Act
            CommentLike commentLikeFromDb = commentLikeRepository.Get(idToSearch);

            // Assert
            Assert.AreEqual(expectedCommentLike, commentLikeFromDb);
        }
 public void AddCommentLike(CommentLike commentLike)
 {
     Requires.NotNull(commentLike);
     Requires.NotNull(commentLike.CommentId);
     using (var context = DataContext.Instance())
     {
         context.Execute(System.Data.CommandType.Text,
                         "IF NOT EXISTS (SELECT * FROM {databaseOwner}{objectQualifier}Connect_ApiBrowser_CommentLikes " +
                         "WHERE CommentId=@0 AND UserId=@1) " +
                         "INSERT INTO {databaseOwner}{objectQualifier}Connect_ApiBrowser_CommentLikes (CommentId, UserId, Datime) " +
                         "SELECT @0, @1, @2", commentLike.CommentId, commentLike.UserId, commentLike.Datime);
     }
 }
Пример #31
0
 public static Db.CommentLike ToEntity(CommentLike commentLike)
 {
     return commentLike == null ? null :
         new Db.CommentLike
         {
             CommentId = commentLike.CommentId,
             CommentLikeId = commentLike.CommentLikeId,
             User = null,
             UserId = commentLike.UserId,
             CreatedBy = commentLike.CreatedBy,
             CreatedDate = commentLike.CreatedDate,
             ModifiedBy = commentLike.ModifiedBy,
             ModifiedDate = commentLike.ModifiedDate
         };
 }
 public CommentLike Add(CommentLike toAdd)
 {
     this.likes.Add(toAdd);
     this.likes.SaveChanges();
     return toAdd;
 }
 public CommentLike Delete(CommentLike toDelete)
 {
     this.likes.Delete(toDelete);
     this.likes.SaveChanges();
     return toDelete;
 }