예제 #1
0
        public async Task <IActionResult> Edit(int id, [Bind("UserLikeId,IsLiked")] UserLike userLike)
        {
            if (id != userLike.UserLikeId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(userLike);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserLikeExists(userLike.UserLikeId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(userLike));
        }
예제 #2
0
        public async Task DeleteLike(UserLike like)
        {
            // see: https://stackoverflow.com/questions/23315542/finding-an-element-in-a-dbset-with-a-composite-primary-key
            var likeEntity = await _context.Likes.FindAsync(like.SourceUserId, like.LikedUserId);

            _context.Likes.Remove(like);
        }
예제 #3
0
        public async Task <bool> LikeUpload(string myId, int uploadId)
        {
            try
            {
                ToonUser user = await _context.Users.FirstOrDefaultAsync(u => u.Id == myId);

                Upload upload = await _context.Upload.FirstOrDefaultAsync(u => u.Id == uploadId);

                UserLike like = new UserLike()
                {
                    ToonUser = user,
                    Upload   = upload
                };

                if (user.Likes.Count(l => l.Id == uploadId) == 0)
                {
                    upload.Likes.Add(like);
                    await _context.SaveChangesAsync();

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"*** ERROR *** - Error liking media - {ex.Message}");
                throw;
            }
        }
예제 #4
0
        public async Task <ActionResult> AddLike(string username)
        {
            var liker = await _likesRepository.GetUserWithLikes(User.GetUserId());

            var likee = await _userRepository.GetUserByUsernameAsync(username);

            var erroneousActionResult = await ValidateLikeAsync(liker, likee);

            if (erroneousActionResult is not null)
            {
                return(erroneousActionResult);
            }

            var userLike = new UserLike
            {
                LikerId = liker.Id,
                LikeeId = likee.Id
            };

            liker.LikedUsers.Add(userLike);

            // TODO: figure out a better way to save changes, as we now have two repos, each of them could potentially save the changes
            if (!await _userRepository.SaveAllAsync())
            {
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }

            return(Ok());
        }
예제 #5
0
        public bool Like(int linkId, int userId)
        {
            try
            {
                UserLike userLike = db.userLikes.Include(p => p.link)
                                    .FirstOrDefault(p => p.userid == userId && p.linkid == linkId);
                userLike.link.like--;

                db.userLikes.Remove(userLike);
                db.SaveChanges();
                return(false);
            }
            catch
            {
                UserLike userLike = new UserLike();
                userLike.linkid = linkId;
                userLike.userid = userId;
                db.userLikes.Add(userLike);
                var link = db.link.FirstOrDefault(p => p.id == linkId);
                link.like++;
                db.Entry(link).State = EntityState.Modified;
                db.SaveChanges();
                return(true);
            }
        }
예제 #6
0
        public async Task <IActionResult> Match(string username)
        {
            string accessToken = await HttpContext.GetTokenAsync("access_token");

            AspNetUser currentUser = null;
            HttpClient client      = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            string userString = await client.GetStringAsync(Configuration["URLAPI"] + "api/Account/getUserInfo");

            currentUser = JsonConvert.DeserializeObject <AspNetUser>(userString);

            AspNetUser user = _context.AspNetUsers.Where(d => d.UserName == username).Single();

            UserLike likeCurrentUser = _context.UserLikes.Where(d => d.Id == currentUser.Id && d.Id1 == user.Id).SingleOrDefault();
            UserLike likeUser        = _context.UserLikes.Where(d => d.Id == user.Id && d.Id1 == currentUser.Id).SingleOrDefault();

            if (likeCurrentUser != null && likeUser != null)
            {
                return(new JsonResult("match"));
            }
            else
            {
                return(new JsonResult("nMatch"));
            }
        }
        public void GetLikes(Action <List <UserLike> > onRequestDone)
        {
            facebookClient.GraphRequest("me/likes", new NSMutableDictionary(), "GET", Handler((request, obj) => {
                List <UserLike> likesList = new List <UserLike>();
                if (request.ResponseText != null)
                {
                    var data = JsonObject.Parse(request.ResponseText.ToString());
                    var jv   = data["data"];
                    foreach (JsonValue item in jv)
                    {
                        var like         = new UserLike();
                        like.Id          = item["id"];
                        like.Category    = item["category"];
                        like.Name        = item["name"];
                        like.CreatedTime = item["created_time"];

                        likesList.Add(like);
                    }
                }

                if (onRequestDone != null)
                {
                    onRequestDone(likesList);
                }
            }
                                                                                              ));
        }
예제 #8
0
        public async Task LoveAsync(int albumId)
        {
            int userId = int.Parse(httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value);

            this.logger.LogInformation($"Checking to see if {nameof(User)} with {nameof(User.Id)} = {userId} already liked {nameof(Album)} with {nameof(Album.Id)} = {albumId}");
            UserLike alreadyExistingLike = await db.UserLikes
                                           .AsNoTracking()
                                           .FirstOrDefaultAsync(ul => ul.UserId == userId && ul.AlbumId == albumId);

            if (alreadyExistingLike != null)
            {
                this.logger.LogInformation($"{nameof(User)} with {nameof(User.Id)} already reacted to {nameof(Album)} with {nameof(Album.Id)} = {albumId}");
                db.UserLikes.Remove(alreadyExistingLike);
                await db.SaveChangesAsync();
            }

            this.logger.LogInformation($"Checking to see if {nameof(User)} with {nameof(User.Id)} = {userId} already loved {nameof(Album)} with {nameof(Album.Id)} = {albumId}");
            UserLove alreadyExistingLove = await db.UserLoves
                                           .AsNoTracking()
                                           .FirstOrDefaultAsync(ul => ul.UserId == userId && ul.AlbumId == albumId);

            if (alreadyExistingLove == null)
            {
                this.logger.LogInformation($"{nameof(User)} with {nameof(User.Id)} = {userId} loved {nameof(Album)} with {nameof(Album.Id)} = {albumId}");
                UserLove love = new UserLove
                {
                    AlbumId = albumId,
                    UserId  = userId
                };

                await db.UserLoves.AddAsync(love);

                await db.SaveChangesAsync();
            }
        }
예제 #9
0
            public async Task <bool> Handle(Command request, CancellationToken cancellationToken)
            {
                var user = await dataContext.Users.FirstOrDefaultAsync(x => x.Id == currentUser.UserId);

                if (user is null)
                {
                    throw new HttpContextException(HttpStatusCode.NotFound, new { User = "******" });
                }

                var advertise = await dataContext.Advertise.FirstOrDefaultAsync(x => x.UniqueId == request.AdvertiseId);

                if (advertise is null)
                {
                    throw new HttpContextException(System.Net.HttpStatusCode.NotFound, new { Advertise = "Advertise is not found" });
                }

                var userLike = new UserLike
                {
                    Advertise = advertise,
                    AppUser   = user
                };
                await dataContext.UserLikes.AddAsync(userLike);

                return(await dataContext.SaveChangesAsync() > 0);
            }
예제 #10
0
        public async Task <IActionResult> GetLike()
        {
            string accessToken = await HttpContext.GetTokenAsync("access_token");

            AspNetUser currentuser = null;
            HttpClient client      = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            string userString = await client.GetStringAsync(Configuration["URLAPI"] + "api/Account/getUserInfo");

            currentuser = JsonConvert.DeserializeObject <AspNetUser>(userString);

            List <AspNetUser> othersuser = await _context.AspNetUsers.Where(u => u.Id != currentuser.Id).ToListAsync();

            List <AspNetUser> usermatch = new List <AspNetUser>();

            foreach (AspNetUser user in othersuser)
            {
                UserLike likeCurrentUser = _context.UserLikes.Where(d => d.Id == currentuser.Id && d.Id1 == user.Id).SingleOrDefault();
                UserLike likeUser        = _context.UserLikes.Where(d => d.Id == user.Id && d.Id1 == currentuser.Id).SingleOrDefault();

                if (likeCurrentUser != null && likeUser != null)
                {
                    usermatch.Add(user);
                }
            }

            return(new JsonResult(usermatch));
        }
예제 #11
0
        public async Task<LikeResult> RateProfile(User user, string login, bool like)
        {
            var likeQuery = await this.databaseContext.UsersLikes
                .Include(x => x.Liker)
                .Include(x => x.LikedUser)
                .FirstOrDefaultAsync(x => x.LikedUser.Login == login && x.Liker.Id == user.Id);
            if (likeQuery == null)
            {
                likeQuery = new UserLike()
                {
                    LikedUser = await this.databaseContext.Users.FirstOrDefaultAsync(x => x.Login == login),
                    Liker = user,
                };
                await this.databaseContext.AddAsync(likeQuery);
            }

            likeQuery.IsLiked = like;
            await this.databaseContext.SaveChangesAsync();
            LikeResult likeResult =  new LikeResult()
            {
                IsLiked = like,
                Likes = await this.databaseContext.UsersLikes
                    .Include(x => x.LikedUser)
                    .LongCountAsync(x => x.IsLiked && x.LikedUser.Login == login)
            };
            return likeResult;
        }
예제 #12
0
        public async Task <ActionResult> AddLike(int id)
        {
            var sourceUserId = User.GetUserId();
            var likedUser    = await _userService.GetByIdAsync(id);

            var sourceUser = await _likeService.GetUserWithLikes(sourceUserId);

            if (likedUser == null)
            {
                return(NotFound());
            }
            if (sourceUser.Id == id)
            {
                return(BadRequest("You cannot like userSelf"));
            }
            var userLike = await _likeService.GetUserLike(sourceUserId, likedUser.Id);

            if (userLike != null)
            {
                return(BadRequest("you already liked this user!!!"));
            }
            userLike = new UserLike
            {
                SourceUserId = sourceUserId,
                LikedUserId  = likedUser.Id
            };
            sourceUser.LikedUsers.Add(userLike);
            if (await _userService.SaveAllChangesAsync())
            {
                return(Ok());
            }
            return(BadRequest("Failed to like user!!!"));
        }
예제 #13
0
        public async Task <ActionResult> AddLike(string username)
        {
            var sourceUserId = User.GetUserId();
            var likedUser    = await _unitOfWork.UserRepository.GetUserByUsernameAsync(username);

            var sourceUser = await _unitOfWork.LikesRepository.GetUserWithLikes(sourceUserId);

            if (likedUser == null)
            {
                return(NotFound());
            }
            if (sourceUser.UserName == username)
            {
                return(BadRequest("You cannot like yourself"));
            }
            var userLike = await _unitOfWork.LikesRepository.GetUserLike(sourceUserId, likedUser.Id);

            if (userLike != null)
            {
                return(BadRequest("You already like this user"));
            }
            userLike = new UserLike
            {
                SourceUserId = sourceUserId,
                LikedUserId  = likedUser.Id
            };
            sourceUser.LikedUsers.Add(userLike);

            if (await _unitOfWork.Complete())
            {
                return(Ok());
            }

            return(BadRequest("Failed to like user"));
        }
예제 #14
0
        // GET: UserLike/Create
        public async Task <IActionResult> CreateLike(LikedUserViewModel model)
        {
            var loggedUser = await GetCurrentUserAsync();

            var chosenPup = await _context.ApplicationUser
                            .SingleOrDefaultAsync(l => l.Id == model.LikedUser.Id);

            //If Liked was clicked(True)
            if (model.isLikedUser == "Like")
            {
                UserLike liked = new UserLike()
                {
                    CurrentUser = loggedUser, IsLiked = true, LikedUser = chosenPup
                };
                _context.Add(liked);
                _context.SaveChanges();
            }
            if (model.isLikedUser == "Skip")
            {
                UserLike liked = new UserLike()
                {
                    CurrentUser = loggedUser, IsLiked = false, LikedUser = chosenPup
                };
                _context.Add(liked);
                _context.SaveChanges();
            }

            return(RedirectToAction("Index", new { controller = "RandomGenerateUser", action = "Index", pupId = chosenPup.Id }));
        }
예제 #15
0
        public async Task <JsonResult> Like(int Id)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);

            string username = user.UserName;

            var requestedArticle = _articleService.GetById(Id);
            int likeCount        = requestedArticle.LikeCount;

            bool result = false;

            if (!_userLikeService.CheckUserLikeExists(username, Id))
            {
                UserLike ul = new UserLike {
                    Username = username, ArticleId = Id
                };
                requestedArticle.LikeCount++;
                if (_articleService.Update(requestedArticle))
                {
                    likeCount++;
                }

                result = _userLikeService.Create(ul);
            }

            return(Json(new { result = result, likecount = likeCount }));
        }
예제 #16
0
        public async Task <BaseResponse <Song> > LikeSong(int userId, int songId)
        {
            var song = await FindFirstOrDefault(s => s.Id.Equals(songId));

            song.Hearts += 1;

            var userLike = new UserLike {
                Song = song, SongId = songId, UserId = userId
            };

            try
            {
                await _userLikeRepository.Add(userLike);

                var result = await UpdateSong(songId, song);

                if (!result.Success)
                {
                    return(result);
                }

                return(new BaseResponse <Song>(song));
            }
            catch (Exception e)
            {
                return(new BaseResponse <Song>($"An error occurred when liking the song: {e.Message}"));
            }
        }
예제 #17
0
        public async Task <bool> DoesUserAlreadyLike(string userId, int userLikeId)
        {
            ToonUser user = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);

            UserLike like = user.Likes.FirstOrDefault(l => l.Id == userLikeId);

            return(like != null);
        }
예제 #18
0
        public async Task <IActionResult> DeleteSearch(string username)
        {
            string accessToken = await HttpContext.GetTokenAsync("access_token");

            AspNetUser currentUser = null;
            HttpClient client      = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            string userString = await client.GetStringAsync(Configuration["URLAPI"] + "api/Account/getUserInfo");

            string us = username;

            currentUser = JsonConvert.DeserializeObject <AspNetUser>(userString);

            AspNetUser user = _context.AspNetUsers.Where(d => d.UserName == username).Single();

            if (user == null)
            {
                return(BadRequest());
            }
            else
            {
                try
                {
                    UserLike       userLike = _context.UserLikes.Where(d => d.Id == currentUser.Id && d.Id1 == user.Id).Single();
                    Talk           talk     = _context.Talks.Where(t => t.Id == currentUser.Id && t.IdUser2Talk == user.Id).SingleOrDefault();
                    List <Message> messages = null;
                    if (talk == null)
                    {
                        talk = _context.Talks.Where(t => t.Id == user.Id && t.IdUser2Talk == currentUser.Id).SingleOrDefault();
                    }
                    if (talk != null)
                    {
                        messages = _context.Messages.Where(m => m.TalkId == talk.TalkId).ToList();
                    }
                    if (messages != null)
                    {
                        foreach (Message message in messages)
                        {
                            _context.Remove(message);
                        }
                    }
                    if (talk != null)
                    {
                        _context.Talks.Remove(talk);
                    }
                    _context.UserLikes.Remove(userLike);
                    _context.SaveChanges();
                    return(Ok());
                }
                catch (Exception)
                {
                    return(BadRequest());
                }
            }
        }
예제 #19
0
        public void DisLikePost(Guid userId, Guid postId)
        {
            var userLike = new UserLike()
            {
                UserId = userId,
                PostId = postId
            };

            DBContext.Delete(userLike.GetDeleteQuery());
        }
예제 #20
0
        public async Task <IActionResult> Create([Bind("UserLikeId,IsLiked")] UserLike userLike)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userLike);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(userLike));
        }
예제 #21
0
        public void Like(Guid userId, Guid postId)
        {
            var userLike = new UserLike()
            {
                UserId      = userId,
                PostId      = postId,
                CreatedDate = DateTime.Now
            };

            DBContext.Create(userLike.GetInsertQuery());
        }
예제 #22
0
        public async Task <IActionResult> Like(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var post = await _context.Posts
                       .Include(p => p.Group)
                       .Include(p => p.User)
                       .Include(p => p.Comments)
                       .Include(p => p.Attachments)
                       .Include(p => p.Images)
                       .SingleOrDefaultAsync(m => m.Id == id);

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

            ApplicationUser user = UserHelper.GetCurrentUser(User.Identity.Name);

            UserLike oldLike = await _context.UserLikes.Where(ul => ul.PostId == id && ul.UserId == user.Id).FirstOrDefaultAsync();

            if (oldLike != null)
            {
                List <string> errors = new List <string>();
                errors.Add("You have already liked this post");

                TempData.Add("errors", errors);

                return(RedirectToAction("Details", new { id }));
            }

            UserLike like = new UserLike
            {
                UserId = user.Id,
                PostId = post.Id
            };

            post.Likes++;

            if (ModelState.IsValid)
            {
                _context.Update(post);
                _context.Add(like);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Details", new { id = post.Id }));
            }

            return(RedirectToAction(nameof(Index)));
        }
예제 #23
0
        public async Task <bool> AddLike(UserLike like)
        {
            var result = _context.Likes.AddAsync(like);

            if (result.IsCompletedSuccessfully)
            {
                await _context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }
예제 #24
0
        public async Task Like(string postId, string userId)
        {
            var userLike = new UserLike()
            {
                PostId = postId,
                UserId = userId,
            };

            await this.dbContext.UserLikes.AddAsync(userLike);

            await this.dbContext.SaveChangesAsync();
        }
예제 #25
0
        public async Task AddLikeToCommentAsync(string userId, int commentId)
        {
            var userLike = new UserLike()
            {
                UserId    = userId,
                CommentId = commentId,
            };

            await this.likeRepository.AddAsync(userLike);

            await this.likeRepository.SaveChangesAsync();
        }
예제 #26
0
        /// <summary>
        /// 修改 (可能有其他业务逻辑检查)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultInfo Update(UserLike model)
        {
            ResultInfo ri = new ResultInfo();

            if (Edit(model))
            {
                ri.Ok  = true;
                ri.Msg = "修改成功";
            }

            return(ri);
        }
예제 #27
0
        public LacesResponse LikeProduct(ProductRequest request)
        {
            LacesResponse response = new LacesResponse();

            try
            {
                if (request.SecurityString == ConfigurationManager.AppSettings[Constants.APP_SETTING_SECURITY_TOKEN])
                {
                    // Confirm user and product exist
                    LacesDataModel.User.User       user    = new LacesDataModel.User.User(request.UserId);
                    LacesDataModel.Product.Product product = new LacesDataModel.Product.Product(request.ProductId);

                    UserLike like = new UserLike();
                    like.UserId      = user.UserId;
                    like.ProductId   = product.ProductId;
                    like.CreatedDate = DateTime.Now;

                    if (like.Add())
                    {
                        response.Success = true;
                        response.Message = "Operation completed.";
                    }
                    else
                    {
                        response.Success = false;
                        response.Message = "An error occurred when communicating with the database.";
                    }
                }
                else
                {
                    response.Success = false;
                    response.Message = "Invalid security token.";
                }
            }
            catch (Exception ex)
            {
                response         = new LacesResponse();
                response.Success = false;

                if (ex.Message.Contains("find user") || ex.Message.Contains("find product") || ex.Message.Contains("find like"))
                {
                    response.Message = ex.Message;
                }
                else
                {
                    response.Message = "An unexpected error has occurred; please verify the format of your request.";
                }
            }

            return(response);
        }
        public JsonResult AddLike(string userId, Guid imageId)
        {
            var userLike = new UserLike
            {
                UserLikesId = Guid.NewGuid(),
                Id          = userId,
                ImageId     = imageId
            };

            _context.UserLikes.Add(userLike);
            _context.SaveChanges();

            return(Json(new { Message = string.Empty }, JsonRequestBehavior.AllowGet));
        }
예제 #29
0
        public async Task <bool> RemoveLike(UserLike like)
        {
            try
            {
                _context.Likes.Remove(like);
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                return(false);
            }

            return(true);
        }
예제 #30
0
        public object LikePictures(UserLike like)
        {
            int id     = GetUserIdFromJWT();
            var select = _context.Pictures.Where(p => p.ID == like.PictureID).Single();

            select.Likes += 1;
            like.UserID   = id;
            _context.UserLikes.Add(like);
            _context.SaveChanges();
            return(new
            {
                status = 0
            });
        }