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

            // Chek if user didn't liked this post
            bool liked = db.PostLikes.Where(l => l.postId == id).Any(l => l.userId == userId);

            if (!liked)
            {
                PostLike like = new PostLike();
                like.postId    = (int)id;
                like.userId    = int.Parse(User.Identity.Name);
                like.createdAt = DateTime.Now;

                Post post = db.Posts.Find(id);
                post.likes++;

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

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

            return(Redirect("/"));
        }
        public async Task <PostLikeResponse> SaveAsync(int PostId)
        {
            var post = _PostRepository.GetByID(PostId);

            var liked = new PostLike
            {
                IPAddress = WebHelpers.GetRemoteIP,
                PostId    = PostId,
                UserAgent = WebHelpers.GetUserAgent,
                UserLike  = true
            };

            var postLikes = await ListAsync(new PostLikeQuery(PostId, liked.IPAddress, 1, 1));

            var dupe = postLikes.Items.FirstOrDefault();

            if (dupe == null)
            {
                return(await SaveAsync(liked));
            }
            else
            {
                liked.UserLike = !dupe.UserLike;
                return(await UpdateAsync(dupe.Id, liked));
            }
        }
示例#3
0
        public int LikePost(PostLike like)
        {
            var result = _unitOfWork.BlogPostSchoolRepository.LikePost(like);

            _unitOfWork.Save();
            return(_unitOfWork.BlogPostSchoolRepository.GetLikeCount(result.PostId));
        }
        public ActionResult UnlikePost(int?id)
        {
            int userId = int.Parse(User.Identity.Name);

            // Chek if user didn't liked this post
            bool liked = db.PostLikes.Where(l => l.postId == id).Any(l => l.userId == userId);

            if (liked)
            {
                PostLike like = db.PostLikes.Where(l => l.postId == id).Single(l => l.userId == userId);

                Post post = db.Posts.Find(id);
                post.likes--;

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

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

            return(Redirect("/"));
        }
示例#5
0
        public IActionResult Like(int postId)
        {
            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.PostLikes.SingleOrDefault(l => l.PostId == postId && l.UserId == Int32.Parse(userId));
                if (likeExists == null)
                {
                    var like = new PostLike
                    {
                        PostId = postId,
                        UserId = Int32.Parse(userId),
                    };
                    _db.PostLikes.Add(like);
                    var numLikes = ++_db.Posts.Single(p => p.Id == postId).Likes;
                    _db.SaveChanges();

                    return(Ok(new { message = "like success", numLikes }));
                }
                else
                {
                    _db.PostLikes.Remove(likeExists);
                    var numLikes = --_db.Posts.Single(p => p.Id == postId).Likes;
                    _db.SaveChanges();
                    return(Ok(new { message = "like deleted", numLikes }));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(500, $"Internal server error: {ex}"));
            }
        }
        public async Task AddAsync(PostLike entity)
        {
            await DbContextManager.BeginTransactionAsync();

            var spParameters = new SqlParameter[2];

            spParameters[0] = new SqlParameter()
            {
                ParameterName = "userid", Value = entity.UserId
            };
            spParameters[1] = new SqlParameter()
            {
                ParameterName = "postid", Value = entity.PostId
            };

            await DbContextManager.StoreProc <StoreProcResult>("[dbo].spInsertLike", spParameters);

            try
            {
                await DbContextManager.CommitAsync();
            }
            catch (Exception e)
            {
                DbContextManager.RollbackTransaction();
            }
        }
示例#7
0
        public async Task <IActionResult> LikePost(int userId, int postId)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            //Primary Key userid+postid
            var postLikees = await _repo.GetPostLikes(postId);

            var like = new PostLike {
                UserId = userId,
                PostId = postId
            };

            if (postLikees.Contains(userId))
            {
                _mainRepo.Delete <PostLike>(like);
            }
            else
            {
                _mainRepo.Add <PostLike>(like);
            }

            try {
                if (await _mainRepo.SaveAll())
                {
                    return(NoContent());
                }
            }catch {
                return(BadRequest("Failed"));
            }

            return(BadRequest("Failed"));
        }
示例#8
0
        public async Task <ActionResult <Post> > LikePost(int id, int userId)
        {
            var post = await _context.Posts.FindAsync(id);

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

            var hasPostLike = _context.PostLikes.Any(x => x.PostId == id && x.UserId == userId);

            if (hasPostLike)
            {
                return(post);
            }

            var postLike = new PostLike
            {
                PostId = id,
                UserId = userId
            };

            _context.PostLikes.Add(postLike);
            await _context.SaveChangesAsync();

            return(post);
        }
        public async Task <int> PostDislike(int?id)
        {
            if (id == null)
            {
                return(-1);
            }
            Post post = await _db.Posts.FindAsync(id);

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

            PostLike postLike = _db.PostLikes.Where(p => p.UserId == currentUser.Id && p.PostId == id).FirstOrDefault();

            if (currentUser.Id != post.UserId)
            {
                Notification notification = _db.Notifications.Where(n => n.NotificationFromId == currentUser.Id && n.NotificationToId == post.UserId && n.PostId == post.Id && n.NotificationTypeId == 1).FirstOrDefault();
                _db.Notifications.Remove(notification);
            }
            _db.PostLikes.Remove(postLike);
            await _db.SaveChangesAsync();

            int newLikesCount = _db.PostLikes.Where(p => p.PostId == id).Count();

            return(newLikesCount);
        }
示例#10
0
        public async Task <IActionResult> PutPostLike(Guid id, PostLike postLike)
        {
            if (id != postLike.PostId)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
        public IHttpActionResult LikePost(int postId)
        {
            var currentUserId = this.UserIdProvider.GetUserId();
            var currentUser   = this.Data.Users.Find(currentUserId);
            var post          = this.Data.Posts.Find(postId);

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

            if (this.HasAuthorization(currentUser, post))
            {
                return(this.BadRequest("Unable to like that post. You can like posts of your friends or on their wall."));
            }

            if (post.Likes.Any(p => p.UserId == currentUserId))
            {
                return(this.BadRequest("You have already like this post."));
            }

            PostLike postLike = new PostLike
            {
                PostId = post.Id,
                UserId = currentUserId
            };

            this.Data.PostLikes.Add(postLike);
            this.Data.SaveChanges();

            return(this.Ok());
        }
示例#12
0
        private LikePost SaveLike(string id)
        {
            var postId         = int.Parse(id);
            var baseContext    = Context.Request.GetHttpContext();
            var postRepository = new PostRepository();
            var item           = postRepository.GetById(postId);
            var liked          = new PostLike
            {
                IPAddress = baseContext.Request.UserHostAddress,
                PostId    = item.Id,
                UserAgent = baseContext.Request.UserAgent,
                UserLike  = true
            };
            var dupe = item.PostLikes.FirstOrDefault(e => e.IPAddress == liked.IPAddress);

            if (dupe == null)
            {
                item.PostLikes.Add(liked);
            }
            else
            {
                dupe.UserLike = !dupe.UserLike;
            }
            postRepository.SaveChanges();
            var post = postRepository.GetById(postId);

            return(new LikePost
            {
                LikeCount = post.PostLikes.Count(e => e.UserLike)
            });
        }
        public async Task <PostLikeResponse> SaveAsync(PostLike PostLike)
        {
            _PostLikeRepository.Insert(PostLike);
            await _unitOfWork.CompleteAsync();

            return(new PostLikeResponse(PostLike));
        }
示例#14
0
        public dynamic AddPostLike(PostLike like)
        {
            var newLike = new PostLike
            {
                PostId  = like.PostId,
                LikedBy = Context.User.Identity.Name
            };
            //tìm post có id = postcomment.PostId
            var filter = Builders <Post> .Filter.Eq(x => x.Id, like.PostId);

            //update newLike vào PostLikes
            var update = Builders <Post> .Update.Push(x => x.PostLikes, newLike);

            //tìm document phù hợp rồi update
            con.Posts.FindOneAndUpdate(filter, update);

            //Hiển thị
            //Lấy thông tin đã update trong db truyển ra view hiển thị
            Post     post    = con.Posts.Find(x => x.Id == like.PostId).FirstOrDefault();
            PostLike dislike = new List <PostLike>(post.PostLikes).FirstOrDefault();
            var      ret     = new
            {
                PostId        = dislike.PostId,
                LikedBy       = dislike.LikedBy,
                NumOfPostLike = post.PostLikes.Count
            };

            GetPosts();
            //Clients.All.loadNewLikes(post);
            return(ret);
        }
        public ActionResult Like(int id)
        {
            string   uid     = User.Identity.GetUserId();
            Profile  profile = db1.Profiles.Where(x => x.USERID == uid).FirstOrDefault();
            PostLike like    = db2.PostLikes.Where(x => x.PostID == id && x.ProfileID == profile.ID).FirstOrDefault();

            if (like == null)
            {
                PostLike newlike = new PostLike();
                Post     update  = db.Posts.ToList().Find(x => x.ID == id);
                update.Likes     += 1;
                newlike.PostID    = id;
                newlike.Liked     = true;
                newlike.ProfileID = profile.ID;
                db.SaveChanges();
                db2.PostLikes.Add(newlike);
                db2.SaveChanges();
                return(RedirectToAction("HomePage", "UserHomePage"));
            }
            else if (like.Liked == true)
            {
                return(RedirectToAction("HomePage", "UserHomePage"));
            }
            else
            {
                return(RedirectToAction("HomePage", "UserHomePage"));
            }
        }
        public IHttpActionResult Post(PostLike post)
        {
            var p = db.Posts.Find(post.postId);

            if (p == null)
            {
                return(NotFound());
            }
            var postlike = db.PostLikes.SingleOrDefault(a => a.postId == post.postId && a.userId == post.userId);

            if (postlike == null)
            {
                db.PostLikes.Add(post);
                db.SaveChanges();
            }
            else
            {
                if (postlike.like == true)
                {
                    postlike.like = false;
                }
                else
                {
                    postlike.like = true;
                }
                db.SaveChanges();
            }
            return(Ok());
        }
示例#17
0
        public List <PostLike> GetPostCommentList(int owenerId)
        {
            List <PostLike> likeList = new List <PostLike>();

            GenarateConnection();
            using (Connection)
            {
                Connection.Open();
                string query = "select * from Comment where OwenerID=@OwenerID ORDER BY ID DESC;";
                Command = new SqlCommand(query, Connection);
                Command.Parameters.Clear();

                Command.Parameters.Add("@OwenerID", SqlDbType.VarChar);
                Command.Parameters["@OwenerID"].Value = owenerId;
                Reader = Command.ExecuteReader();
                if (Reader.HasRows)
                {
                    while (Reader.Read())
                    {
                        PostLike postLike = new PostLike();
                        postLike.ID       = Convert.ToInt32(Reader["ID"].ToString());
                        postLike.PostID   = Convert.ToInt32(Reader["PostID"].ToString());
                        postLike.OwenerID = Convert.ToInt32(Reader["OwenerID"].ToString());
                        postLike.SignupID = Convert.ToInt32(Reader["PersonID"].ToString());
                        postLike.DateTime = Convert.ToDateTime(Reader["DateTime"].ToString());
                        likeList.Add(postLike);
                    }
                }
                return(likeList);
            }
        }
示例#18
0
        public async Task <IActionResult> Edit(Guid id, [Bind("PostId,LikeId")] PostLike postLike)
        {
            if (id != postLike.PostId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(postLike);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PostLikeExists(postLike.PostId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["LikeId"] = new SelectList(_context.Like, "Id", "Id", postLike.LikeId);
            ViewData["PostId"] = new SelectList(_context.Post, "Id", "Id", postLike.PostId);
            return(View(postLike));
        }
        View GetView(PostLike item, int position, View convertView, ViewGroup parent)
        {
            View view = convertView;

            if (view == null)
            {
                view = Activity.LayoutInflater.Inflate(Resource.Layout.PostLikeItem, null);
            }

            view.FindViewById <TextView>(Resource.Id.lblName).Text = item.Username;

            var profileImageView = view.FindViewById <ImageViewAsync>(Resource.Id.imgProfile);

            profileImageView.Tag?.CancelPendingTask(item.ProfileUrl);
            var task = ImageService.Instance.LoadUrl(item.ProfileUrl)
                       .Retry(3, 300)
                       .LoadingPlaceholder(Resource.Drawable.DefProfPic.ToString(), ImageSource.CompiledResource)
                       .Transform(new CircleTransformation())
                       .Into(profileImageView);

            profileImageView.Tag = new ImageLoaderHelper(task);


            return(view);
        }
示例#20
0
        public async Task <Result <object> > Handle(AddLikeToPostRequest request, CancellationToken cancellationToken)
        {
            var post = await _forumDbContext.Posts.FindAsync(request.PostId);

            if (post == null)
            {
                return(Result <object> .Failure(nameof(request.PostId), "Post doesn't exist"));
            }

            var like = await _forumDbContext.PostLikes
                       .SingleOrDefaultAsync(pl => pl.PostId == request.PostId && pl.UserId == request.UserId);

            if (like != null)
            {
                return(Result <object> .Failure(nameof(request.PostId), "This post was liked"));
            }

            var postLike = new PostLike {
                PostId = post.Id, UserId = request.UserId
            };
            await _forumDbContext.PostLikes.AddAsync(postLike);

            await _forumDbContext.SaveChangesAsync();

            return(Result <object> .Success());
        }
示例#21
0
        public List <PostLike> GetAllFriendRequestList(int id)
        {
            List <PostLike> friendList = new List <PostLike>();

            GenarateConnection();
            string query = "select * from Friend where A_PersonID=@ID and Status=@Status ORDER BY ID DESC;";

            Command = new SqlCommand(query, Connection);
            Command.Parameters.Clear();

            Command.Parameters.Add("@ID", SqlDbType.VarChar);
            Command.Parameters["@ID"].Value = id;
            Command.Parameters.Add("@Status", SqlDbType.VarChar);
            Command.Parameters["@Status"].Value = 1;

            Connection.Open();
            Reader = Command.ExecuteReader();

            if (Reader.HasRows)
            {
                while (Reader.Read())
                {
                    PostLike postLike = new PostLike();
                    postLike.ID       = Convert.ToInt32(Reader["ID"].ToString());
                    postLike.SignupID = Convert.ToInt32(Reader["R_PersonID"].ToString());
                    postLike.DateTime = Convert.ToDateTime(Reader["DateTime"].ToString());
                    friendList.Add(postLike);
                }
            }
            Connection.Close();
            return(friendList);
        }
示例#22
0
        public int Like(PostLikeModel model)
        {
            try
            {
                var postLike = new PostLike()
                {
                    PostId  = model.PostId,
                    Status  = true,
                    LikedBy = model.UserId,
                    LikedOn = UnixTimeBaseClass.UnixTimeNow
                };

                _db.PostLikes.Add(postLike);
                _db.SaveChanges();

                return(postLike.PostLikeId);
            }
            catch (Exception ex)
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                string json             = js.Serialize(model);
                Log.Error("Post Like - Add- " + json, ex);
                throw;
            }
        }
示例#23
0
        public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath, PostLike item)
        {
            var cell = tableView.DequeueReusableCell("LikeCell", indexPath) as LikeCell;

            cell.SetData(item);
            cell.SelectionStyle = UITableViewCellSelectionStyle.None;
            return(cell);
        }
示例#24
0
 public static PostLikeViewModel Create(PostLike postLike)
 {
     return(new PostLikeViewModel()
     {
         PostId = postLike.PostId,
         User = UserViewModelMinified.Create(postLike.User)
     });
 }
        public void PostLike(PostLike post)
        {
            Db.Posts.Where(x => x.Id == post.PostId)
            .FirstOrDefault()
            .PostLikes.Add(post);

            Db.SaveChanges();
        }
示例#26
0
        public async Task OnPostLike(string id, PostLike postLike)
        {
            postLike.Like();

            await _mediatorHandler.PublishEvent(new PostLikedEvent(postLike.LikeCounter));

            await _repository.OnPostLike(id, postLike);
        }
示例#27
0
        public ActionResult Delete(int PostId, string UserId)
        {
            PostLike ToDelete = db.PostLikes.Find(PostId, UserId);

            db.PostLikes.Remove(ToDelete);
            db.Posts.Find(PostId).LikeCount--;
            db.SaveChanges();
            return(Redirect("/Posts/Show/" + PostId));
        }
        public void PostDislike(PostLike post)
        {
            var postLikeToDelete = Db.PostLikes
                                   .Where(x => x.PostId == post.PostId && x.User == post.User)
                                   .FirstOrDefault();

            Db.PostLikes.Remove(postLikeToDelete);
            Db.SaveChanges();
        }
 public async Task AddLike(PostLike postLike)
 {
     if (postLike == null || postLike.PostId == Guid.Empty)
     {
         throw new ArgumentNullException(nameof(postLike));
     }
     _appDbContext.PostLikes.Add(postLike);
     await _appDbContext.SaveAsync();
 }
示例#30
0
        public async Task BannPost()
        {
            Post post = new Post
            {
                Id                = Guid.NewGuid().ToString(),
                Title             = "Test",
                ApplicationUserId = Guid.NewGuid().ToString(),
            };

            BlockedPost blockedPost = new BlockedPost
            {
                PostId            = post.Id,
                ApplicationUserId = post.ApplicationUserId,
                IsBlocked         = false,
            };

            FavouritePost favouritePost = new FavouritePost
            {
                ApplicationUserId = post.ApplicationUserId,
                IsFavourite       = true,
                PostId            = post.Id,
            };

            UserAction userAction = new UserAction
            {
                Action = UserActionsType.CreatePost,
                PostId = post.Id,
            };

            PostLike postLike = new PostLike
            {
                PostId  = post.Id,
                UserId  = post.ApplicationUserId,
                IsLiked = true,
            };

            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

            using (var db = new ApplicationDbContext(options))
            {
                IEditorPostService commentService = new EditorPostService(db);
                db.Posts.Add(post);
                db.BlockedPosts.Add(blockedPost);
                db.FavouritePosts.Add(favouritePost);
                db.UserActions.Add(userAction);
                db.PostsLikes.Add(postLike);
                await db.SaveChangesAsync();

                var result = await commentService.BannPost(post.Id);

                Assert.True(result);
                Assert.Equal(1, db.BlockedPosts.Count());
                Assert.Equal(PostStatus.Banned, db.Posts.FirstOrDefault(x => x.Id == post.Id).PostStatus);
                Assert.Equal(0, db.UserActions.Count());
            }
        }
示例#31
0
 public static Db.PostLike ToEntity(PostLike postLike)
 {
     return postLike == null ? null :
         new Db.PostLike
         {
             PostId = postLike.PostId,
             PostLikeId = postLike.PostLikeId,
             UserId = postLike.UserId,
             CreatedBy = postLike.CreatedBy,
             CreatedDate = postLike.CreatedDate,
             ModifiedBy = postLike.ModifiedBy,
             ModifiedDate = postLike.ModifiedDate
         };
 }