public void Delete(Guid id)
        {
            LikeModel like = Context.Likes.Find(id);

            Context.Likes.Remove(like);
            Context.SaveChanges();
        }
Example #2
0
        public async Task <IActionResult> Like(int?id)
        {
            var userName  = _userManager.GetUserName(HttpContext.User);
            var likefound = await _context.LikeModels.FirstOrDefaultAsync(k => k.UserName == userName);

            var dislikefound = await _context.DislikeModels.FirstOrDefaultAsync(k => k.UserName == userName);

            var article = await _context.Articles.FirstOrDefaultAsync(k => k.ArticleId == id);

            var likeModel = new LikeModel();
            var url       = "/Article/Details/" + id;

            if (likefound == null)
            {
                if (dislikefound != null)
                {
                    await UnDislike(id);
                }
                article.LikeCount  += 1;
                likeModel.ArticleId = article.ArticleId;
                likeModel.UserName  = userName;
                _context.Add(likeModel);
                _context.Update(article);
                await _context.SaveChangesAsync();

                return(LocalRedirect(url));
            }
            return(LocalRedirect(url));
        }
Example #3
0
        public LikeModel GetContentLikes(int contentType, int contentId)
        {
            // If like is for a post.
            if (contentType == 0)
            {
                Post post = postRepo.ById(contentId);

                // If the current user does not have access to the post, return null.
                if (post.PrivacyLevel > friendRepo.RelationshipTier(currentProfile.id, post.ProfileId))
                {
                    return(null);
                }
            }

            LikeModel likeModel = new LikeModel
            {
                ContentId   = contentId,
                ContentType = contentType,
                Count       = likeRepo.CountByContentId(contentType, contentId),
                HasLiked    = likeRepo.HasLiked(contentType, contentId, currentProfile.id),
                DateTime    = likeRepo.ByTypeAndProfileId(contentType, contentId, currentProfile.id).DateTime
            };

            return(likeModel);
        }
Example #4
0
        public ActionResult Like(long id)
        {
            bool success = false;

            try
            {
                long      currentProfileId = 0;
                var       objLike          = new Like();
                LikeModel objLikeModel     = new LikeModel();
                if (_repoUserProfile != null)
                {
                    if (CurrentUser != null)
                    {
                        currentProfileId = _repoUserProfile.GetSingle(x => x.UserId == CurrentUser.UserId).Id;
                    }
                }
                objLike = _repoLike.GetSingle(x => x.ProfileId == currentProfileId && x.EntityName == "comment" && x.EntityId == id);
                if (objLike == null)
                {
                    objLikeModel.EntityName = "comment";
                    objLikeModel.EntityId   = id;
                    objLikeModel.ProfileId  = currentProfileId;
                    objLike = LikeMap.Map(objLikeModel);
                    _repoLike.Add(objLike);
                    _repoLike.Save();
                }
                success = true;
            }
            catch (Exception e)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(e);
                success = false;
            }
            return(Json(new { success = success }));
        }
        public IActionResult LikeTarget(string targetGuid)
        {
            var    likeBiz  = new LikeBiz();
            var    tmpModel = likeBiz.GetOneLikeModelByUserId(UserID, targetGuid);
            string likeState;
            bool   result;

            if (tmpModel != null)
            {
                likeState                = tmpModel.Enable ? "取消点赞" : "点赞";
                tmpModel.Enable          = !tmpModel.Enable;
                tmpModel.LastUpdatedDate = DateTime.Now;
                tmpModel.LastUpdatedBy   = UserID;
                result = likeBiz.UpdateModel(tmpModel);
            }
            else
            {
                likeState = "点赞";
                var model = new LikeModel
                {
                    LikeGuid      = Guid.NewGuid().ToString("N"),
                    TargetGuid    = targetGuid,
                    CreatedBy     = UserID,
                    LastUpdatedBy = UserID,
                    OrgGuid       = ""
                };
                result = likeBiz.InsertModel(model);
            }
            if (result)
            {
                var upRes = new HotExBiz().UpdateLikeTotalAsync(targetGuid, likeState == "点赞");
            }
            return(result ? Success($"{likeState}操作成功!") : Failed(ErrorCode.DataBaseError, $"{likeState}操作失败!"));
        }
Example #6
0
        static void GetCompleted(int state, List <UserInfoModel> list)
        {
            //通知完成
            Console.WriteLine($"[{pageindex}/{totalpage}] GetCompleted:" + list.Count);
            //保存数据
            data.AddRange(list);
            File.WriteAllText(savename, JsonConvert.SerializeObject(data));
            //判断是否还有数据
            pageindex++;
            if (pageindex <= totalpage)
            {
                //还有数据
                ulist = WeiboHelper.GetPageLikeLinks(mid, pageindex);
                GetWeiboUser getWeiboUser = new GetWeiboUser(ulist.UserLinks, 30);
                getWeiboUser.GetCompleted += GetCompleted;

                getWeiboUser.Get();
            }
            else
            {
                timer.Change(Timeout.Infinite, 1000);
                //没有
                Console.WriteLine($"抓取已完成,耗时 {time} 秒。总计 {totalpage} 页数据,抓取到用户 {data.Count} 位。");
                File.WriteAllText(savename, JsonConvert.SerializeObject(data));
                Console.WriteLine($"数据保存在程序启动目录:{savename}");
                time      = 0;
                pageindex = 1;
                data.Clear();
            }
        }
Example #7
0
        /// <summary>
        /// Deleting like for an item
        /// </summary>
        /// <param name="likeModel"></param>
        /// <returns></returns>
        public async Task <IHttpActionResult> UnLike(LikeModel like)
        {
            like.UserID    = CurrentUser.UserID;
            like.CreatedOn = DateTime.Now;
            ModelState.Remove("post.PostedBy");
            ModelState.Remove("post.PostedDate");
            like.PostedByName   = CurrentUser.FullName;
            like.PostedByAvatar = CurrentUser.ProfilePicture;

            if (ModelState.IsValid)
            {
                try
                {
                    BroadcastLike model = _post.UnLike(like);
                    await _broadcaster.UnLike(model, like.broadCastType);

                    return(Ok(model.TotalLikes));
                }
                catch (Exception ex)
                {
                    Logs.Error("Error removing like to item", ex);
                    return(BadRequest(ex.Message));
                }
            }
            else
            {
                return(BadRequest(ModelState.JsonValidation()));
            }
        }
Example #8
0
        public dynamic SetLike([FromBody] LikeModel model)
        {
            string itemName = ItemFacade.GetItemNameFromEncodedId(model.id);

            if (model == null || ItemFacade.CheckPageOrItemExist(model.pageId, itemName) == false)
            {
                return(new
                {
                    success = false
                });
            }

            var metadata = ItemFacade.GetItemMetadata(model.pageId, itemName);

            if (metadata == null)
            {
                ItemFacade.CreateDefaultItemMetadata(model.pageId, itemName, ref metadata);
            }
            metadata.like = model.like;
            ItemFacade.SaveItemMetadata(model.pageId, itemName, metadata);

            return(new
            {
                success = true,
                itemId = model.id,
                like = metadata.like
            });
        }
Example #9
0
        public static LikeModel GetPageLikeLinks(string mid, int page = 1)
        {
            string likehtml = XHttp.GetHttpResult($"https://weibo.com/aj/v6/like/big?ajwvr=6&mid={mid}&page={page}&__rnd=1531705846965");

            likehtml = likehtml.Replace("\\", "");
            var result = new LikeModel();

            //提取总页数
            Regex regtotalpage     = new Regex("\"totalpage\":(?<totalpage>.*),\"pagenum\"");
            var   regtotalpagemath = regtotalpage.Match(likehtml);

            int.TryParse(regtotalpagemath.Groups["totalpage"].Value, out int totalpage);
            result.TotalPage = totalpage;
            Regex           reg     = new Regex(@"<a\b[^<>]*?\bhref[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<url>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            MatchCollection matches = reg.Matches(likehtml);

            foreach (Match match in matches)
            {
                string data = (match.Groups["url"].Value);
                if (!string.IsNullOrEmpty(data) && result.UserLinks.IndexOf(data) == -1 && data.IndexOf("http") != -1)
                {
                    result.UserLinks.Add(data);
                }
            }
            return(result);
        }
        public async Task <ProjectModel> ToggleProjectLikeByUserId(string projectID, string userID)
        {
            ProjectModel DbProjectModel = await GetSingleProjectByProjectId(projectID);

            if (DbProjectModel != null)
            {
                LikeModel likeProject = _context.LikeModel.FirstOrDefault(p => p.ProjectId == projectID && p.LikedBy == userID);

                if (likeProject != null)
                {
                    await Task.Run(() => _context.LikeModel.Remove(likeProject));

                    DbProjectModel.likeNumber -= 1;
                    return(await UpdateProjectByProjectIdAsync(projectID, DbProjectModel));
                }
                else
                {
                    var record = new LikeModel
                    {
                        LikedBy   = userID,
                        ProjectId = projectID
                    };

                    await _context.LikeModel.AddAsync(record);

                    DbProjectModel.likeNumber += 1;
                    return(await UpdateProjectByProjectIdAsync(projectID, DbProjectModel));
                }
            }
            return(null);
        }
Example #11
0
        public LikeModel ToLikeModelFrom(LikeObject likeObject)
        {
            var like = new LikeModel();

            like.Post      = ToPostModelFrom(likeObject.Post);
            like.Author    = ToUserModelFrom(likeObject.Author);
            like.WhenLiked = likeObject.When;

            return(like);
        }
Example #12
0
 public void LikePost(LikeModel comment, int id)
 {
     // Method uses established internal connection
     using (IDbConnection dbConnection = Connection)
     {
         dbConnection.Open();
         string query = $"INSERT INTO likes (users_id, messages_id, created_date, updated_date) VALUES ({id}, @message_id, NOW(), NOW())";
         dbConnection.Execute(query, comment);
     }
 }
Example #13
0
        public LikeTable ToLikeFrom(LikeModel from)
        {
            var like = new LikeTable();

            //like.AuthorId = from.Author.Id;
            like.Id = from.Id;
            //like.UserId = from.User.Id;

            return(like);
        }
Example #14
0
        public LikeModel ToLikeModelFrom(LikeTable from)
        {
            var like = new LikeModel();

            like.Id = from.Id;
            //like.Author = ToUserModelFrom( from.Author);
            //like.Post = ToPostModelFrom ( from.Post );

            return(like);
        }
Example #15
0
        public IHttpActionResult UnLike([FromBody] LikeModel model)
        {
            var userId = User.Identity.GetUserId();

            if (_service.IsLikeExist(userId, model.photoId))
            {
                _service.UnLike(userId, model.photoId);
            }
            return(Ok());
        }
Example #16
0
        public IActionResult Post([FromBody] LikeModel model)
        {
            var like = new LikeModel
            {
                likeCount = model.likeCount
            };
            var result = context.PostLikesCount(like);

            return(Ok(like));
        }
Example #17
0
 public async Task <IActionResult> RemoveLike([FromBody] LikeModel model)
 {
     try
     {
         return(Ok(await _service.RemoveLike(model)));
     }
     catch (Exception e)
     {
         return(BadRequest(e.Message));
     }
 }
Example #18
0
        public static Like Map(LikeModel objModel)
        {
            return new Like
            {
                Id = objModel.Id,
                EntityId = objModel.EntityId,
                EntityName = objModel.EntityName,
                ProfileId = objModel.ProfileId
            };

        }
        private void AddLikeInComment(long commentId, bool isLike)
        {
            LikeModel like = new LikeModel();

            like.Comment = databaseContext.Comments.FirstOrDefault(x => x.ID == commentId);
            like.User    = GetCurrentUser();
            like.isLike  = isLike;

            databaseContext.Likes.Add(like);
            databaseContext.SaveChanges();
        }
Example #20
0
        public void CreateLike(LinkModel link, UserModel user)
        {
            var like = new LikeModel
            {
                User    = user,
                Link    = link,
                IsLiked = true
            };

            _context.Likes.Add(like);
            _context.SaveChanges();
        }
Example #21
0
        public async Task <int> Like(int id, string _userid)
        {
            LikeModel m = new LikeModel();

            m.IcerikID = id;
            m.UserID   = _userid;
            await _unitOfWork.Likes.AddAsync(m);

            await _unitOfWork.CommitAsync();

            return(id);
        }
Example #22
0
        public async Task <Kwet> RemoveLike(LikeModel kwet)
        {
            var unlikedKwet = await _repository.Get(kwet.KwetId);

            var like = unlikedKwet.Likes.SingleOrDefault(x => x.userId == kwet.Id);

            if (like == null)
            {
                throw new LikeNotFoundException();
            }
            unlikedKwet.Likes.Remove(like);
            return(await _repository.Update(unlikedKwet));
        }
Example #23
0
        static void Main(string[] args)
        {
            Console.Title = "WeiboLike";
            timer         = new Timer(new TimerCallback(TimerUp), null, Timeout.Infinite, 1000);

            while (true)
            {
                //Console.WriteLine("请输入用户ID:");
                //string uid = Console.ReadLine();
                //if (string.IsNullOrEmpty(uid))
                //{
                //    continue;
                //}
                //Console.WriteLine("请输入微博ID:");
                //string weiboid = Console.ReadLine();
                //if (string.IsNullOrEmpty(weiboid))
                //{
                //    continue;
                //}
                Console.WriteLine("请粘贴微博URL链接:");
                string[] uidweiboid = WeiboHelper.GetUidWeiboID(Console.ReadLine());
                if (string.IsNullOrEmpty(uidweiboid[0]) || string.IsNullOrEmpty(uidweiboid[1]))
                {
                    Console.WriteLine("从链接获取uid/微博id失败,请重试。");
                    continue;
                }

                Console.WriteLine("正在获取Mid...");
                mid = WeiboHelper.GetMid(uidweiboid[0], uidweiboid[1]);
                if (string.IsNullOrEmpty(mid))
                {
                    Console.WriteLine("没有获取到Mid,请重试。");

                    continue;
                }
                Console.WriteLine("已获取到MID:" + mid);
                Console.WriteLine("请输入微博数据保存文件名:");
                savename = Console.ReadLine() + ".json";
                Console.WriteLine("开始抓取本条微博的点赞用户数据...");
                timer.Change(0, 1000);
                //第一步获取点赞基本数据
                ulist     = WeiboHelper.GetPageLikeLinks(mid, 1);
                totalpage = ulist.TotalPage;

                GetWeiboUser getWeiboUser = new GetWeiboUser(ulist.UserLinks, 60);
                getWeiboUser.GetCompleted += GetCompleted;
                getWeiboUser.Get();

                Console.ReadKey();
            }
        }
Example #24
0
        private async Task AddImageLike(PostIdRequest request, CancellationToken cancellationToken)
        {
            var like = new LikeModel()
            {
                PostId  = request.PostId,
                UserId  = request.UserId,
                IsLiked = true
            };
            await _likeDbContext.Likes.AddAsync(like, cancellationToken);

            await _likeDbContext.SaveChangesAsync(cancellationToken);

            WritingInformationLog($"added like :like id = {like.Id} by: user id {like.UserId}");
        }
Example #25
0
        public async Task <IActionResult> UnlikeKweet(Guid kweetId, [FromBody] LikeModel likeModel,
                                                      [FromHeader(Name = "Authorization")] string jwt)
        {
            try
            {
                await _kweetService.UnlikeKweet(kweetId, likeModel.UserId, likeModel.Username, jwt);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Example #26
0
        //A method to post like counts to db
        public bool PostLikesCount(LikeModel model)
        {
            //LikeModel model = new LikeModel();
            bool hasRow = false;

            using (MySqlConnection connection = GetConnection())
            {
                connection.Open();
                MySqlCommand    command    = new MySqlCommand("UPDATE tbl_like SET likesCount = " + model.likeCount, connection);
                MySqlDataReader dataReader = command.ExecuteReader();
                hasRow = dataReader.HasRows;
                return(hasRow);
            }
        }
Example #27
0
        public async Task <Kwet> LikeKwet(LikeModel kwet)
        {
            var likedKwet = await _repository.Get(kwet.KwetId);

            if (likedKwet.Likes == null)
            {
                likedKwet.Likes = new List <Likes>();
            }
            likedKwet.Likes.Add(new Likes()
            {
                userId = kwet.Id, Name = kwet.UserName
            });
            return(await _repository.Update(likedKwet));
        }
Example #28
0
        public IActionResult Like(LikeViewModel model)
        {
            //Check if like is already registered in system
            int id = (int)HttpContext.Session.GetInt32("id");

            if (ModelState.IsValid && messageFactory.CheckLikes(model.message_id, id) == null)
            {
                LikeModel newLike = new LikeModel
                {
                    message_id = model.message_id
                };
                messageFactory.LikePost(newLike, id);
            }
            return(RedirectToAction("Index"));
        }
        public ActionResult LikePartial(string code)
        {
            if (code.Length == 2)
            {
                code = '0' + code;
            }
            long count = dbSpec.GetLikesCount(code);
            //long count = 15;

            LikeModel model = new LikeModel {
                Code = code, Count = count
            };

            return(PartialView(model));
        }
Example #30
0
        public async Task <ActionResult <Like> > Post([FromBody] LikeModel likeModel)
        {
            User user = await db.Users.FirstOrDefaultAsync(x => x.Nickname == likeModel.NicknameUser);

            Like like = new Like
            {
                UserId = user.Id,
                ItemId = likeModel.IdItem
            };

            db.Likes.Add(like);
            await db.SaveChangesAsync();

            return(Ok());
        }