Example #1
0
        public async Task SendMessage(int roomId, string text)
        {
            // Validation
            if (roomId <= 0)
            {
                await ReturnError("Could not send message", "You must specify a room.");

                return;
            }

            if (text.IsNullOrWhitespace())
            {
                await ReturnError("Could not send message", "Text must not be null or whitespace.");

                return;
            }

            // Permission
            Room room = null;
            await Task.Run(() => room = _roomService.GetRoom(roomId));

            if (room == null || !RoomPermissionHelper.CanAddMessage(_context.CurrentUser, room))
            {
                await ReturnError("Could not send message", "You do not have permission, the room may have been deleted.");

                return;
            }

            // Trim message if necessary
            if (text.Length > 2000)
            {
                text = text.Substring(0, 2000);
            }

            // Add message to room
            int messageId = -1;
            await Task.Run(() => messageId = _roomService.AddMessage(_context.CurrentUser, room, text));

            // Html encode the text of the message
            text = HtmlEncoder.Default.Encode(text);

            // Notify all in group
            Models.Message hubMessage = new Models.Message
            {
                Id               = messageId,
                UserName         = _context.CurrentUser.UserName,
                UserId           = _context.CurrentUser.Id,
                Text             = text,
                IsDeleted        = false,
                ModifiedId       = _context.CurrentUser.Id,
                ModifiedUserName = _context.CurrentUser.UserName
            };
            await Clients.Group(roomId.ToString()).SendAsync("ReceiveMessage", hubMessage);
        }
Example #2
0
        public async Task <IActionResult> AddMessage([FromBody] Message message, [FromRoute] string rid)
        {
            var IdUserIsOffline = await _roomService.AddMessage(message, rid);

            //Если пользователь Offline отправим ему уведомление
            //if (IdUserIsOffline != null)
            //будем отправлять всем уведомления
            {
                await _bus.PublishAsync(new UserNotificationMessage
                {
                    UserId           = IdUserIsOffline,
                    Creator          = "Chat",
                    Title            = "У вас есть не прочитанное сообщение в чате",
                    NotificationType = 0,
                    Severity         = 0,
                    Text             = message.Text
                });
            }

            await _hubContext.Clients.All.SendAsync("alertOnSendedMessageAllUsers", (object)message);

            return(NoContent());
        }