public async Task MessageReveived(string groupName, ChatMessageResponce data)
 {
     await hubContext.Clients.Group(groupName).SendAsync(ChatAction.messageReceived.ToString(), data);
 }
Exemplo n.º 2
0
        public async Task <ChatMessageDTO> SendMessage(ChatMessageDTO message)
        {
            var targetDialog = await uow.GetRepository <ChatDialog>().GetAsync(message.DialogId);

            if (targetDialog == null)
            {
                var user = await uow.GetRepository <UserProfile>().GetAsync(u => u.Id == message.ClientId);

                targetDialog = mapper.Map <ChatDialog>(await StartChatWithUser(mapper.Map <UserProfileDTO>(user)));
            }

            var currentUserId = (await currentUser.GetCurrentUserProfile())?.Id;

            if (!currentUserId.HasValue || message == null)
            {
                return(null);
            }

            var clientMessageId = message.ClientId;

            message.ReceivedDate = DateTime.Now;
            message.SenderId     = currentUserId.Value;

            var a = mapper.Map <ChatMessage>(message);

            var newMessage = await uow.GetRepository <ChatMessage>().CreateAsync(a);

            await uow.SaveAsync();

            if (newMessage == null)
            {
                return(null);
            }

            var dialogId = newMessage.DialogId.Value;
            var text     = newMessage.Body;


            if (text.Length > 155)
            {
                text = text.Substring(0, 150);
            }

            var responce = new ChatMessageResponce()
            {
                SenderId  = currentUserId.Value,
                DialogId  = dialogId,
                MessageId = newMessage.Id,
                Text      = text
            };

            // отправляем уведомление о сообщении в диалог
            await signalRChatService.MessageReveived($"{targetDialog.DialogType.ToString()}{dialogId}", responce);

            //отправляем уведомление каждому участнику диалога
            foreach (var participant in targetDialog.DialogParticipants)
            {
                if (participant.ParticipantId != currentUserId.Value)
                {
                    await signalRChatService.MessageReveived($"{ChatGroup.direct.ToString()}{participant.ParticipantId}", responce);

                    await signalRNavigationService.NumberOfMessagesChanges($"{Group.notification.ToString()}{participant.ParticipantId}", await this.GetNumberOfUnreadMessages((int)participant.ParticipantId));
                }
            }

            return(mapper.Map <ChatMessageDTO>(newMessage, opt => opt.AfterMap((src, dest) => ((ChatMessageDTO)dest).ClientId = clientMessageId)));
        }