public async Task <Chat> CreateChat(string recieverUserId)
        {
            //check if already chat created
            Chat chat = await chatRepository.GetChatWith(CurrentUserId, recieverUserId);

            if (chat != null) // already created
            {
                return(chat);
            }
            //if not created
            chat       = new Chat();
            chat.Users = new List <AppUser>();
            var sender = await userManager.FindByIdAsync(CurrentUserId);

            var reciever = await userManager.FindByIdAsync(recieverUserId);

            if (sender != null && reciever != null)
            {
                chat.Users.Add(sender);
                chat.Users.Add(reciever);
                await chatRepository.Add(chat);

                await chatRepository.Save();

                return(chat);
            }
            return(null);
        }
        public async Task <IActionResult> CreateMessage(int userId, [FromBody] MessageForCreationDto messageForCreationDto)
        {
            var sender = await _repo.GetUser(userId);

            if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            messageForCreationDto.SenderId = userId;
            var recipient = await _repo.GetUser(messageForCreationDto.RecipientId);

            if (recipient == null)
            {
                return(BadRequest("Could not find user"));
            }
            var message = _mapper.Map <Message>(messageForCreationDto);

            _repo.Add(message);
            if (await _repo.SaveAll())
            {
                var messageToReturn = _mapper.Map <MessageToReturnDto>(message);
                return(CreatedAtRoute("GetMessage", new { id = message.Id }, messageToReturn));
            }
            throw new Exception("Creating message failed");
        }
        public ActionMessage CreatePrivate(string roomName, Enums.ChatType result, string userId)
        {
            var response = new ActionMessage();

            var chat = new Chat()
            {
                ChatType = result,
                Name     = roomName,
            };

            chatRepository.Add(chat);

            var chatroomId = chatRepository.GetByName(roomName).Id;

            CreateChatUser(userId, chatroomId);

            return(response);
        }
示例#4
0
        [HttpPost("createChat")]//now work work yet
        public IActionResult CreateChat(int id, string name, string type)
        {
            IActionResult result       = new ObjectResult(false);
            GenericResult createResult = null;

            var authenticationHeader = Request?.Headers["Authorization"];
            var token   = authenticationHeader?.FirstOrDefault().Split(' ')[1];
            var subject = _jwtFormater.GetSubject(token);

            var user = _userRepository.GetSingleByUsername(subject);

            try
            {
                var chat = new Chat()
                {
                    Name        = name,
                    DateCreated = DateTime.Now.ToString(),
                    Type        = type
                };
                _chatRepository.Add(chat);
                _chatRepository.Commit();

                var cu = new ChatUser()
                {
                    ChatId = chat.Id,
                    UserId = user.Id
                };
                var cu1 = new ChatUser()
                {
                    ChatId = chat.Id,
                    UserId = id
                };
                _chatUserRepository.Add(cu);
                _chatUserRepository.Add(cu1);
                _chatUserRepository.Commit();

                createResult = new GenericResult()
                {
                    Succeeded = true,
                    Message   = chat.Id + ""
                };
            }
            catch (Exception e)
            {
                createResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = e.Message
                };
            }

            result = new ObjectResult(createResult);
            return(result);
        }
示例#5
0
 public void CreateChat(Chat chat)
 {
     if (chat is DirectChat)
     {
         var chats = chatRepository.GetWithActiveUser(chat.Users.First().UserId, chat.Users.Last().UserId);
         if (chats.Any(ch => ch is DirectChat))
         {
             throw new ArgumentException("Между данными пользователями уже есть чат");
         }
     }
     chatRepository.Add(chat);
 }
        public IActionResult Post([FromBody] Chat chat)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            _chatRepo.Add(chat);
            if (_chatRepo.SaveAll())
            {
                return(Created("", chat));
            }
            return(BadRequest($"failed to add new chat"));
        }
示例#7
0
        public IActionResult Post([FromBody] ChatMessageModel value)
        {
            var message = new ChatMessage
            {
                Body     = value.Body,
                Seen     = false,
                SentDate = DateTime.Now.ToUniversalTime(),
                Title    = value.Title,
                UserFrom = _userRepository.Get(value.UserFrom),
                UserTo   = _userRepository.Get(value.UserTo)
            };

            _chatRepository.Add(message);
            return(Ok());
        }
示例#8
0
        public async Task SendMessageToGroup(string groupName, string message, string username, string conId)
        {
            var data = new Chat
            {
                Message  = message,
                RoomName = groupName,
                Username = username
            };

            if (await _redisHandler.IsCached($"Room:StartedGame:{groupName}"))
            {
                var gameRoom = JsonConvert.DeserializeObject <StartedGame>(await _redisHandler.GetFromCache($"Room:StartedGame:{groupName}"));
                if (gameRoom.word.WordName == message)
                {
                    data.Answer = true;

                    if (await _chatRepository.CountWhere(x => x.Answer == true && x.RoomName == groupName) == 0)
                    {
                        gameRoom.userList.FirstOrDefault(x => x.Username == username).GamePoint += 10;
                        await Clients.Client(conId).SendAsync("DisableChat", true);
                    }
                    else if (await _chatRepository.CountWhere(x => x.Answer == true && x.RoomName == groupName) == 1)
                    {
                        gameRoom.userList.FirstOrDefault(x => x.Username == username).GamePoint += 8;
                        await Clients.Client(conId).SendAsync("DisableChat", true);
                    }
                    else if (await _chatRepository.CountWhere(x => x.Answer == true && x.RoomName == groupName) == 2)
                    {
                        gameRoom.userList.FirstOrDefault(x => x.Username == username).GamePoint += 5;
                        await Clients.Client(conId).SendAsync("DisableChat", true);
                    }
                    else if (await _chatRepository.CountWhere(x => x.Answer == true && x.RoomName == groupName) > 2)
                    {
                        gameRoom.userList.FirstOrDefault(x => x.Username == username).GamePoint += 3;
                        await Clients.Client(conId).SendAsync("DisableChat", true);
                    }
                    gameRoom.userList[0].GamePoint += 2;

                    await _redisHandler.RemoveFromCache($"Room:StartedGame:{groupName}");

                    await _redisHandler.AddToCache($"Room:StartedGame:{groupName}", TimeSpan.FromMinutes(10), JsonConvert.SerializeObject(gameRoom));
                }
            }

            await _chatRepository.Add(data);

            await Clients.Group(groupName).SendAsync("GroupMessage", data);
        }
示例#9
0
        public async Task SendMessage(string user, string message)
        {
            try
            {
                var msgToSave = new ChatMessage
                {
                    User    = user,
                    Message = message,
                    Sent    = DateTime.UtcNow
                };
                _repo.Add(msgToSave);
                await _repo.SaveAllAsync();

                await Clients.All.SendAsync("ReceiveMessage", msgToSave);
            }
            catch { }
        }
示例#10
0
        public async Task <ChatVM> ObterOuCriarPeloIdDoContatoAsync(Guid id)
        {
            var userId  = _user.GetUserId();
            var contato = await _clienteRepository.GetByIdAsync(id);

            var chat = await _chatRepository.GetChatAsync(id, userId);

            if (chat == null)
            {
                var chatId = Guid.NewGuid();
                chat = new Chat()
                {
                    Id       = chatId,
                    Nome     = _user.GetUserId().ToString() + " x " + id.ToString(),
                    Dialogos = new List <Dialogo>(),
                    Clientes = new List <ChatCliente>()
                    {
                        new ChatCliente()
                        {
                            ChatId = chatId, ClienteId = id
                        },
                        new ChatCliente()
                        {
                            ChatId = chatId, ClienteId = userId
                        }
                    },
                };
                _chatRepository.Add(chat);
                await _chatRepository.SaveChangesAsync();
            }


            ChatVM model = new ChatVM()
            {
                Id              = chat.Id,
                Cliente         = _mapper.Map <ContatoViewModel>(contato),
                ClienteId       = id,
                Dialogo         = _mapper.Map <List <DialogoVM> >(chat.Dialogos),
                LastMessageTime = chat.Dialogos.OrderBy(q => q.DataHoraCriacao).LastOrDefault()?.DataHoraCriacao ?? DateTime.Now,
                Unread          = 0
            };

            return(model);
        }
示例#11
0
        public void CreateChat(string name, string guid)
        {
            var userElasticResult = _userRepository.Get(guid);

            if (!userElasticResult.Success)
            {
                Clients.Caller.onCreateChatCaller(
                    JsonConvert.SerializeObject(new { error = true, message = UserErrorMessage }));
                return;
            }

            var user = userElasticResult.Value;

            var chatElasticResult = _chatRepository.Add(name, guid);

            if (!chatElasticResult.Success)
            {
                Clients.Caller.onCreateChatCaller(
                    JsonConvert.SerializeObject(new { error = true, message = chatElasticResult.Message }));
                return;
            }

            var chat = chatElasticResult.Value;

            // Add User to new Chat
            var chatUserElasticResult = _chatUserRepository.Add(chat.Guid, user.Guid);

            if (!chatUserElasticResult.Success)
            {
                Clients.Caller.OnCreateChat(
                    JsonConvert.SerializeObject(new { error = true, message = chatUserElasticResult.Message }));
                return;
            }

            // Add all the connection ids of the user to the new chat
            foreach (var connectionId in user.ConnectionIds)
            {
                Groups.Add(connectionId, chat.Guid);
            }

            Clients.Clients(user.ConnectionIds.ToArray()).OnCreateChatCaller(JsonConvert.SerializeObject(chat));
        }
示例#12
0
        public async Task <ContactDto> AddContact(string userLogin, string contactLogin, string key, string iv)
        {
            var user = await _userRepository.GetAsync(userLogin);

            var contact = await _userRepository.GetAsync(contactLogin);

            if (contact == null)
            {
                throw new Exception($"Nie znaleziono użytkownika z loginem {contactLogin}");
            }

            user.Contacts.Add(contact);
            await _userRepository.UpdateAsync(user);

            var awaitedUser = new AwaitedUser(user.Login, key, iv);
            await _userRepository.AddAwaitedUserAsync(awaitedUser, user, contact);

            var chat = new Conversation(user, contact);
            await _chatRepository.Add(chat);

            return(_mapper.Map <ContactDto>(contact));
        }
示例#13
0
 public void Send(string name, string message)
 {
     _repository.Add(name, message);
     Clients.All.addMessage(name, message);
 }
示例#14
0
 public IActionResult Post(Chat chat)
 {
     _chatRepo.Add(chat);
     return(CreatedAtAction("GetChat", new { id = chat.Id }, chat));
 }
示例#15
0
        public async Task <ServiceResult <Chat> > Create(Chat chat)
        {
            var chatEntity = await chatRepository.Add(chat);

            return(new ServiceResult <Chat>(chatEntity));
        }