Beispiel #1
0
        private async Task OnReceiveMessageHandler(string roomId, string message, string loginToken)
        {
            var messageContent = message.Replace("\u0000", string.Empty).Trim();
            var websockets     = new Dictionary <string, WebSocket>();

            var userModel = _userService.Get(new GetByLoginTokenRequest
            {
                LoginToken = loginToken
            }).User;

            var messageModel = new LearningRoomMessageModel
            {
                CreatedByNickName    = userModel.NickName,
                Content              = messageContent,
                CreatedOn            = DateTimeUtil.GetNow(),
                IsCreatedByRequester = false
            };

            if (_websockets.TryGetValue(roomId, out websockets))
            {
                var bufferToMember = new ArraySegment <byte>(ConvertTools.StringToBytes(JsonConvert.SerializeObject(messageModel)));
                websockets
                .Where(w => !w.Key.Equals(loginToken))
                .Select(w => w.Value)
                .ToList()
                .ForEach(async w => await w.SendAsync(bufferToMember,
                                                      WebSocketMessageType.Text, true, CancellationToken.None));

                messageModel.IsCreatedByRequester = true;
                var bufferToRequester = new ArraySegment <byte>(ConvertTools.StringToBytes(JsonConvert.SerializeObject(messageModel)));
                await websockets
                .FirstOrDefault(w => w.Key.Equals(loginToken)).Value
                .SendAsync(bufferToRequester,
                           WebSocketMessageType.Text, true, CancellationToken.None);
            }

            try
            {
                await _learningRoomService.CreateChatMessage(loginToken, roomId, messageContent);

                LogService.Info <ChatMessageHub>(
                    "Message Saved" + Environment.NewLine +
                    "Message: " + messageContent + Environment.NewLine +
                    "Room Id: " + roomId + Environment.NewLine +
                    "login Token: " + loginToken);
            }
            catch (Exception e)
            {
                LogService.Info <ChatMessageHub>(
                    e.Message + Environment.NewLine +
                    e.StackTrace);
            }
        }
Beispiel #2
0
        public async Task <IActionResult> SaveMessage([FromBody] NewMessageRequestModel model)
        {
            try
            {
                await _learningRoomService.CreateChatMessage(model.loginToken, model.roomId, model.content);

                return(Ok(@"Save Message successfully."));
            }
            catch (Exception e)
            {
                LogService.Info <ChatMessageHub>(
                    e.Message + Environment.NewLine +
                    e.StackTrace);
                return(BadRequest(e.Message));
            }
        }