Exemplo n.º 1
0
 private void YODAHub_Message(ChatMessageDto message)
 {
     MessageReceived?.Invoke(
         this,
         new ChatEventArgs <ChatMessageDto>(new ChatEventContext(this), message)
         );
 }
Exemplo n.º 2
0
        /// <inheritdoc />
        Task IChatApi.SendMessage(ChatMessageDto chatMessage)
        {
            var arguments = new object[] { chatMessage };
            var func      = requestBuilder.BuildRestResultFuncForMethod("SendMessage", new Type[] { typeof(ChatMessageDto) });

            return((Task)func(Client, arguments));
        }
        public IHttpActionResult Get(int id)
        {
            ChatMessage    entity = this.service.Get(id, collections: false);
            ChatMessageDto dto    = ModelMapper.Map <ChatMessageDto>(entity);

            return(Ok(dto));
        }
Exemplo n.º 4
0
        private void Ready()
        {
            Receive <ChatCreatedEvent>(@event =>
            {
                var chat = new ChatDto()
                {
                    ChatId = @event.Id
                };
                chat.Participants = @event.Participants
                                    .Select(x => new ChatParticipantDto()
                {
                    Id = x.Id, Login = x.Login
                }).ToList();

                string path           = "chats/" + @event.Id;
                PushResponse response = client.Push(path, chat);
            });

            Receive <ChatMessageAddedEvent>(@event =>
            {
                string path = String.Format("chats/{0}/{1}", @event.ChatId, "messages");
                ChatMessageDto messageDto = new ChatMessageDto()
                {
                    MessageId = @event.MessageId,
                    Date      = @event.Date,
                    Message   = @event.Message,
                    UserId    = @event.Author.Id,
                    UserName  = @event.Author.Login
                };
                PushResponse response = client.Push(path, messageDto);
            });
        }
Exemplo n.º 5
0
        public async Task <ChatMessageDto> PostChatMessage(ChatMessageDto model)
        {
            var url    = CRMApiUri + "/ChatMessage";
            var result = await PostRequestToApi(url, model);

            return(result);
        }
Exemplo n.º 6
0
        public async Task <ChatMessageDto> PutChatMessage(int id, ChatMessageDto model)
        {
            var url    = CRMApiUri + "/ChatMessage/" + id;
            var result = await PutRequestToApi(url, model);

            return(result);
        }
Exemplo n.º 7
0
        public async Task PostChatMessage(string receiverId, ChatMessageNewDto chatMessageNew)
        {
            await ValidateMessagePosting(receiverId, chatMessageNew);

            var senderId = _currentUserService.GetUserId();

            var chatMessage = new ChatMessage
            {
                ReceiverId = receiverId,
                SenderId   = senderId,
                Timestamp  = _timeService.GetCurrentTime(),
                Content    = chatMessageNew.Content,
                ModuleId   = chatMessageNew.ModuleId
            };

            await _chatMessagesRepository.Create(chatMessage);

            var sender = await _userManager.FindByIdAsync(senderId);

            var chatMessageDto = new ChatMessageDto
            {
                SenderId   = chatMessage.SenderId,
                Timestamp  = chatMessage.Timestamp,
                SenderName = $"{sender.FirstName} {sender.LastName}",
                Content    = chatMessage.Content
            };

            await _hubsService.SendChatNotificationToUser(senderId, chatMessageDto);

            await _hubsService.SendChatNotificationToUser(receiverId, chatMessageDto);
        }
Exemplo n.º 8
0
        public async Task <BaseEntity> SaveAndReturnEntityAsync(ChatMessageDto entityDto)
        {
            var entity = _mapper.Map <ChatMessage>(entityDto);
            var result = await _repository.SaveAndReturnEntityAsync(entity);

            return(result);
        }
Exemplo n.º 9
0
        public ActionResult SendMessage(string userid, string sendtext)
        {
            var result = new StandardJsonResult <bool>();

            result.Try(() => {
                Guid messageid    = Guid.NewGuid();
                userid            = userid.Replace(",", "|");
                userid            = userid + "|" + BCSession.User.UserID;
                ChatMessageDto cd = new ChatMessageDto()
                {
                    EnterpriseID = BCSession.User.EnterpriseID,
                    IsRead       = ReadStatus.NoRead,
                    Message      = sendtext,
                    MessageID    = messageid,
                    Recipients   = userid,
                    SendTime     = DateTime.Now,
                    SendUserID   = BCSession.User.UserID,
                    SendUserName = BCSession.User.UserName,
                };
                result.Value = serrvice.ProcessChatMessage(cd);
                if (!result.Value)
                {
                    result.Message = "发送失败";
                }
                result.Message = "发送成功";
            });
            if (!result.Success)
            {
                result.Message = "发送失败";
            }
            return(result);
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Post([FromBody] ChatMessageDto chatMessage)
        {
            if (chatMessage.Id != 0)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "Identity insert is not permitted."));
            }

            return(await SaveAndReturnEntityAsync(async() => await _chatMessageService.SaveAndReturnEntityAsync(chatMessage)));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Put(int id, [FromBody] ChatMessageDto chatMessage)
        {
            if (id == 0 || chatMessage.Id == 0)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "Id needs to be greater than 0."));
            }

            return(await SaveAndReturnEntityAsync(async() => await _chatMessageService.SaveAndReturnEntityAsync(chatMessage)));
        }
Exemplo n.º 12
0
 private void InsertMessage(ChatMessageDto message)
 {
     try
     {
         _chatService.Create(message);
     }
     catch (Exception ex)
     {
         return;
     }
 }
        // messenger id van dto vervangen met current principal id
        public IHttpActionResult Post([FromBody] ChatMessageDto dto)
        {
            dto.Timestamp = dto.Timestamp ?? DateTime.Now;

            ChatMessage entity = ModelMapper.Map <ChatMessage>(dto);

            this.service.Add(entity);
            dto = ModelMapper.Map <ChatMessageDto>(entity);

            return(Ok(dto));
        }
Exemplo n.º 14
0
        private void OnMessage(ChatMessageDto message)
        {
            OnUserUpdate(message.UserInfo);

            _messages.Enqueue(message);
            var action = OnChatMessage;

            if (action != null)
            {
                MainThread.Post(() => action(message));
            }
        }
Exemplo n.º 15
0
        private void SendServerMessage(string message)
        {
            var dto = new ChatMessageDto
            {
                IsSystemMessage = true,
                Message         = message,
                SourceColour    = null,
                Source          = null,
                Timestamp       = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
            };

            _eventSender.SendEvent(ServerEvent.ChatMessage, dto, null);
        }
Exemplo n.º 16
0
        public async Task SendChatMessage(ChatMessageDto chatMessageDto)
        {
            try
            {
                await _chatApiService.SendMessage(chatMessageDto);

                _chatsForUser.Edit(l => l.AddOrUpdate(chatMessageDto));
            }
            catch (Exception ex)
            {
                _logger.Error(nameof(SendChatMessage), ex);
                throw;
            }
        }
 public string Send([FromBody] ChatMessageDto messageDto)
 {
     try
     {
         var message = new ChatMessage(messageDto);
         _dbContext.ChatMessages.Add(message);
         _dbContext.SaveChanges();
         return("Meddelandet har skickats!");
     }
     catch
     {
         return("Något gick fel!");
     }
 }
Exemplo n.º 18
0
        public async Task SendChatMessageAsync(ChatMessageDto chatMessageDto)
        {
            var chatMessageEntity = mapper.Map <ChatMessageEntity>(chatMessageDto);
            await chatMessageRepository.InsertAsync(chatMessageEntity);

            await gameRepository.AddMessageIdToGameAsync(chatMessageDto.GameId, chatMessageEntity.Id);

            var chatMessageToSendDto = mapper.Map <ChatMessageToSendDto>(chatMessageEntity);
            var sender = await userRepository.GetAsync(chatMessageDto.UserId);

            chatMessageToSendDto.UserName = sender.Login;

            var groupName = chatMessageDto.GameId.ToString();
            await Clients.Group(groupName).SendAsync("SendChatMessage", chatMessageToSendDto);
        }
Exemplo n.º 19
0
        public async Task SendMessage(string message)
        {
            var formatedMessage = new ChatMessageDto()
            {
                Message   = message,
                Timestamp = DateTime.Now.ToString("HH:mm:ss tt"),
                User      = new UserHub()
                {
                    UserName = Context.User.Identity.Name,
                    Role     = Context.User.Identities.First().Claims.ToArray()[1].Value
                }
            };

            await Clients.All.SendAsync("NewMessage", JsonSerializer.Serialize(formatedMessage));
        }
Exemplo n.º 20
0
 public IEnumerable <ChatMessageDto> ListChatMessages(string uid)
 {
     return(_db.ChatRooms.FirstOrDefault(room => room.Id == uid).Messages
            .OrderByDescending(msg => msg.Created)
            .Select(message =>
     {
         ChatMessageDto dto = new ChatMessageDto();
         dto.Id = message.Id;
         dto.Text = message.Text;
         dto.ChatRoomId = uid;
         dto.Username = message.Username;
         dto.Created = message.Created.ToString("yyyy.MM.dd. HH:mm:ss");
         return dto;
     }));
 }
Exemplo n.º 21
0
        public async Task Handle(ChatMessageReceivedNotification notification, CancellationToken cancellationToken)
        {
            var(_, participants, message, channel, messagesCount) = notification;

            ChatMessageSender?sender = null;

            if (!message.Options.IsAnonymous)
            {
                sender = message.Sender;
            }

            var channelId = ChannelSerializer.Encode(channel).ToString();

            var messageDto = new ChatMessageDto(messagesCount - 1, channelId, sender, message.Message,
                                                message.Timestamp, message.Options);

            var participantGroups = participants.Select(CoreHubGroups.OfParticipant);
            await _hubContext.Clients.Groups(participantGroups).ChatMessage(messageDto, cancellationToken);
        }
Exemplo n.º 22
0
        public IResponse <string> Validate(ChatMessageDto dto)
        {
            var response = new Response <string>();

            if (dto.Id == Guid.Empty)
            {
                response.Errors.Add("invalid game instance");
            }
            if (string.IsNullOrWhiteSpace(dto.Text) || dto.Text.Length > 500)
            {
                response.Errors.Add("invalid message text");
            }

            var gameInstance = GameInstanceLogic.Get(dto.Id);

            if (gameInstance == null || !gameInstance.Users.Any(x => x.UserId == RequestContext.UserId))
            {
                response.Errors.Add("That game is invalid.");
            }
            return(response);
        }
Exemplo n.º 23
0
        public async Task SendMessage(ChatMessageDto dto)
        {
            var validationResults = GameInstanceValidator.Validate(dto);

            if (!validationResults.IsValid)
            {
                throw new Exception(string.Join(',', validationResults.Errors));
            }

            var messageToSave = new GameInstanceUserMessage();

            messageToSave.Text           = dto.Text;
            messageToSave.UserId         = RequestContext.UserId;
            messageToSave.GameInstanceId = dto.Id;
            var entity      = GameInstanceUserMessageLogic.Save(messageToSave);
            var responseDto = GameInstanceMapper.Map(entity);

            responseDto.UserEmail = RequestContext.Email;

            await Clients.Group(dto.Id.ToString()).SendAsync("ReceiveMessage", responseDto);
        }
        private void AuthorizePost(HttpActionContext actionContext)
        {
            int participantId;

            string controller = actionContext.ControllerContext.ControllerDescriptor.ControllerName;

            switch (controller)
            {
            case "ChatMessage":
                ChatMessageDto message = (ChatMessageDto)actionContext.ActionArguments["dto"];
                Session        session = this.Sessions.Get(message.SessionId, collections: true);

                this.AuthorizeParticipant(session.Participants);

                return;

            default:        // to prevent the dto from being null
                participantId = -1;
                break;
            }

            this.AuthorizeParticipant(participantId);
        }
Exemplo n.º 25
0
        public async Task SendMessage()
        {
            if (!string.IsNullOrEmpty(NewMessage) && CurrentRoom.Id > 0)
            {
                var msg = new ChatMessageDto
                {
                    UserId     = CurrentUser.Id,
                    ChatRoomId = CurrentRoom.Id,
                    Message    = NewMessage,
                    Time       = DateTime.Now,
                    UserName   = CurrentUser.Name
                };
                msg.Id = ChatFacade.SendMessageToChatRoom(CurrentUser, msg);
                Messages.Add(msg);
                NewMessage = "";

                await Service.ChangeViewModelForConnectionsAsync((ChatViewModel viewModel) => { viewModel.Messages.Add(msg); },
                                                                 ChatFacade
                                                                 .GetAllUsersFromChatRoom(CurrentRoom.Id)
                                                                 .Select(s => s.ConnectionId)
                                                                 .ToList());
            }
        }
Exemplo n.º 26
0
        public async Task <ApiResponse <ChatMessageDto> > SaveMessageAsync(Guid userId, AddChatMessageDto chatMessage)
        {
            var newMessage = new ChatMessage
            {
                Id             = Guid.NewGuid(),
                UserId         = userId,
                MessageContent = chatMessage.MessageContent,
                MessageSubject = chatMessage.MessageSubject,
                ReceiverId     = chatMessage.ReceiverId,
                SenderId       = chatMessage.SenderId
            };

            var savedMessage = await _chatMessagesRepository.AddAsync(newMessage);

            if (savedMessage != null)
            {
                var addedMessage = new ChatMessageDto
                {
                    Id             = savedMessage.Id,
                    SenderId       = savedMessage.SenderId,
                    ReceiverId     = savedMessage.ReceiverId,
                    MessageSubject = savedMessage.MessageSubject,
                    MessageContent = savedMessage.MessageContent
                };

                return(new ApiResponse <ChatMessageDto>
                {
                    Result = addedMessage
                });
            }

            else
            {
                return(new ApiResponse <ChatMessageDto>()
                       .SetAsFailureResponse(Errors.Chat.ChatMessageCannotBeSaved()));
            }
        }
Exemplo n.º 27
0
        public async Task <ChatMessageDto> AddChatMessage([FromBody] ChatMessageDto chatMessageDto)
        {
            ChatRoom room    = _db.ChatRooms.FirstOrDefault(room => room.Id == chatMessageDto.ChatRoomId);
            var      message = new ChatMessage()
            {
                Id       = Guid.NewGuid().ToString(),
                Text     = chatMessageDto.Text,
                ChatRoom = room,
                Username = chatMessageDto.Username,
                Created  = DateTime.Now
            };

            room.Messages.Add(message);

            _db.Update(room);
            _db.SaveChanges();


            chatMessageDto.Id      = message.Id;
            chatMessageDto.Created = message.Created.ToString("yyyy.MM.dd. HH.mm.ss");
            await _hub.Clients.All.SendAsync("NewChatMessage", chatMessageDto);

            return(chatMessageDto);
        }
Exemplo n.º 28
0
        public HttpResponseMessage SendMessage(ChatMessageDto message)
        {
            var responce = this.Request.CreateResponse(HttpStatusCode.OK);

            return(responce);
        }
Exemplo n.º 29
0
        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next.Invoke(context);

                return;
            }

            CancellationToken ct            = context.RequestAborted;
            WebSocket         currentSocket = await context.WebSockets.AcceptWebSocketAsync();

            var     socketId        = Guid.NewGuid().ToString();
            UserDto userFromSession = GetUserFromSesion(context);
            RoomDto roomFromSession = GetRoomFromSesion(context);


            WebSocketConfig config = new WebSocketConfig()
            {
                Id = socketId, RoomId = roomFromSession.Id, UserId = userFromSession.Id
            };

            _sockets.TryAdd(config, currentSocket);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }

                var response = await ReceiveStringAsync(currentSocket, ct);

                ChatMessageDto message = JsonConvert.DeserializeObject <ChatMessageDto>(response);
                UserDto        user    = GetUser(message.UserID);
                message.CreatedAt = DateTime.Now;
                InsertMessage(message);
                if (message.User == null)
                {
                    message.User = new UserDto();
                }
                message.User.Name = user != null ? user.Name : "---";

                if (config.UserId == Guid.Empty ||  config.RoomId == Guid.Empty)
                {
                    config.UserId = message.UserID;
                    config.RoomId = message.RoomID;
                }

                if (string.IsNullOrEmpty(response))
                {
                    if (currentSocket.State != WebSocketState.Open)
                    {
                        break;
                    }

                    continue;
                }

                foreach (var socket in _sockets)
                {
                    if (socket.Value.State != WebSocketState.Open)
                    {
                        continue;
                    }
                    if (socket.Key.RoomId == config.RoomId)
                    {
                        string messageToSend = JsonConvert.SerializeObject(message, Formatting.Indented);
                        await SendStringAsync(socket.Value, messageToSend, ct);
                    }
                }
            }

            WebSocket dummy;

            _sockets.TryRemove(config, out dummy);

            await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct);

            currentSocket.Dispose();
        }
Exemplo n.º 30
0
        /// <summary>
        /// Broadcasts the chat message to all the clients
        /// </summary>
        /// <param name="message"></param>
        public void SendMessage(ChatMessageDto message)
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext("ChatRHub");

            context.Clients.All.pushNewMessage(message.Id, message.ParticipantId, message.ParticipantName, message.Content, message.Time);
        }