예제 #1
0
        public async Task <ActionResult> SendChatMessage(string message)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(message))
                {
                    return(JsonError(Resources.Chat.errorEmptyMessage));
                }

                var userId = User.Identity.GetUserId();
                if (string.IsNullOrEmpty(userId))
                {
                    return(JsonError(Resources.Chat.errorUserNotFoundMessage));
                }

                var sender = await ChatHub.Cache.GetChatUser(userId);

                if (sender == null)
                {
                    return(JsonError(Resources.Chat.errorUserNotFoundMessage));
                }

                var chatData = await ChatHub.Cache.GetMessages();

                var result = ChatHelper.ValidateMessage(chatData.OrderBy(x => x.Id), sender, message);
                if (result != null)
                {
                    var hub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext <NotificationHub>();
                    if (hub != null)
                    {
                        await hub.Clients.User(sender.Id).SendNotification(result);
                    }

                    return(JsonError(result.Notification));
                }

                var chatItem = new ChatMessageData
                {
                    UserId     = sender.Id.ToString(),
                    Message    = HttpUtility.HtmlEncode(ChatHelper.FilterText(message)),
                    IsEnabled  = true,
                    Timestamp  = DateTime.UtcNow,
                    UserName   = sender.UserName,
                    ChatHandle = sender.ChatHandle,
                    Flair      = sender.RoleCss,
                    Avatar     = sender.Avatar,
                    KarmaTotal = sender.KarmaTotal
                };

                await ChatHub.Cache.AddMessage(chatItem);

                var chathub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext <ChatHub>();
                if (chathub != null)
                {
                    await chathub.Clients.All.broadcastMessage(new
                    {
                        Id         = chatItem.Id,
                        UserName   = chatItem.UserName,
                        ChatHandle = chatItem.ChatHandle,
                        Flair      = chatItem.Flair,
                        Timestamp  = chatItem.Timestamp.ToString("MM/dd/yyyy HH:mm:ss"),
                        Avatar     = chatItem.Avatar,
                        Message    = chatItem.Message,
                        KarmaTotal = chatItem.KarmaTotal
                    });
                }
                return(JsonSuccess());
            }
            catch (Exception)
            {
                return(JsonError(Resources.Chat.errorUnknownMessage));
            }
        }