Exemplo n.º 1
0
        public async Task <IActionResult> SendFriendRequest(string receiverId)
        {
            //Get receiver from id
            User receiver = await _context.Users.FirstOrDefaultAsync(u => u.Id == receiverId);

            //Check if user exists
            if (receiver == null)
            {
                return(BadRequest("No such user"));
            }

            //Get own userid
            var userId = GetUserId().Result;
            //HttpContext.User.Claims.FirstOrDefault(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;

            //User me = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);

            bool          isFriends = _friend.CheckIfFriends(userId, receiverId);
            FriendRequest request   = _friend.GetRequestIfExists(userId, receiverId);

            if (isFriends)
            {
                return(BadRequest("Allerede venner."));
            }

            if (request == null)
            {
                request = new FriendRequest()
                {
                    Id       = userId + ":" + receiverId,
                    IsActive = true
                };
                _context.FriendRequests.Add(request);
                await _context.SaveChangesAsync();

                return(Ok());
            }

            if (request.Id.StartsWith(userId) && request.IsActive == false)
            {
                request.IsActive = true;
            }
            else if (request.Id.StartsWith(receiverId) && request.IsActive == false)
            {
                request.Id       = userId + ":" + receiverId;
                request.IsActive = true;
            }
            else if (request.Id.StartsWith(userId) && request.IsActive == true)
            {
                return(BadRequest("Request finnes allerede."));
            }
            else if (request.Id.StartsWith(receiverId) && request.IsActive == true)
            {
                _context.Friends.Add(_friend.MakeFriendship(userId, receiverId));
                request.IsActive = false;
            }
            await _context.SaveChangesAsync();

            return(Ok());
        }