예제 #1
0
        public async Task SendMessage(SendMessageDto message)
        {
            if (message.Message.StartsWith("/"))
            {
                string[] strMessage = message.Message.Split(' ');

                switch (strMessage[0])
                {
                case "/to":
                    message.Command = "/to";
                    await webSocketMessageHandler.SendMessageToAll(JsonSerializer.Serialize(message), message.Channel);

                    break;

                case "/private":
                    message.Command = "/private";
                    await webSocketMessageHandler.SendMessage(strMessage[1], JsonSerializer.Serialize(message), message.Channel);

                    await webSocketMessageHandler.SendMessage(message.UserName, JsonSerializer.Serialize(message), message.Channel);

                    break;

                default:
                    break;
                }
            }
            else
            {
                await webSocketMessageHandler.SendMessageToAll(JsonSerializer.Serialize(message), message.Channel);
            }
        }
예제 #2
0
        public async Task <IActionResult> SendChatMessage(SendMessageDto sendMessageDto)
        {
            IDatabaseContext context = _getDatabaseContext();
            int currentUserId        = HttpContext.GetUserId();

            List <EventParticipation> eventParticipations = await context.EventParticipations.Where(e => e.EventId == sendMessageDto.EventId).ToListAsync();

            EventParticipation currentUserParticipation = eventParticipations.FirstOrDefault(e => e.ParticipantId == currentUserId);

            if (currentUserParticipation == null)
            {
                return(BadRequest(RequestStringMessages.UserNotPartOfEvent));
            }

            var message = new ChatMessage
            {
                AuthorId = currentUserId,
                EventId  = sendMessageDto.EventId,
                Content  = sendMessageDto.Content,
                SentDate = DateTime.UtcNow
            };

            context.ChatMessages.Add(message);

            currentUserParticipation.LastReadMessageSentDate = message.SentDate;

            await context.SaveChangesAsync();

            _auditLogger.LogInformation("{0}(): Sent a new chat message (containing {1} characters) to the event {2}", nameof(SendChatMessage), sendMessageDto.Content.Length, sendMessageDto.EventId);

            // TODO Push-Notifications eventParticipations.Where(e => e.ParticipantId != currentUserId).ForEach(p => SendNotification(p));

            return(Ok(new EventChatMessage(message.Id, currentUserId, message.Content, message.SentDate)));
        }
예제 #3
0
        private async Task SendToAdmin(SendMessageDto dto)
        {
            var groupName = dto.Conference.Id.ToString();

            _logger.LogDebug($"Sending message {dto.MessageUuid} to group {groupName}");
            await Clients.Group(groupName)
            .ReceiveMessage(dto.Conference.Id, dto.From, dto.To, dto.Message, dto.Timestamp, dto.MessageUuid);
        }
 public ServiceResult <bool> SendMessage(SendMessageDto request)
 {
     return(new ServiceResult <bool>
     {
         Result = true,
         StatusCode = StatusCodeType.Success
     });
 }
예제 #5
0
        public async Task <IActionResult> SendMessage(int groupId, SendMessageDto request)
        {
            var sendMessageToGroupResult = await _mediatR.Send(new SendMessageToGroupCommand(groupId, request.Message));

            await _messageHubContext.Clients.Groups(sendMessageToGroupResult.GroupId.ToString()).SendAsync(HubMethodNames.MessageReceived, sendMessageToGroupResult);

            return(Ok(sendMessageToGroupResult));
        }
        public async Task <Message> PostMessage(string conversationId, SendMessageDto messageDto)
        {
            var    currentTime  = DateTime.Now;
            string messageId    = GenerateMessageId(messageDto, currentTime);
            var    messageDtoV2 = new SendMessageDtoV2(messageDto.Text, messageDto.SenderUsername, messageId);

            return(await PostMessage(conversationId, messageDtoV2));
        }
예제 #7
0
        public async Task SendMessage(Guid conferenceId, string message, string to, Guid messageUuid)
        {
            var userName = await GetObfuscatedUsernameAsync(Context.User.Identity.Name);

            _logger.LogTrace($"{userName} is attempting to SendMessages");
            // this determines if the message is from admin
            var isSenderAdmin = IsSenderAdmin();

            _logger.LogDebug($"{userName} is sender admin: {isSenderAdmin}");
            var isRecipientAdmin = await IsRecipientAdmin(to);

            _logger.LogDebug($"{userName} is recipient admin: {isSenderAdmin}");
            // only admins and participants in the conference can send or receive a message within a conference channel
            var from = Context.User.Identity.Name.ToLowerInvariant();
            var participantUsername = isSenderAdmin ? to : from;
            var isAllowed           =
                await IsAllowedToSendMessageAsync(conferenceId, isSenderAdmin, isRecipientAdmin, participantUsername);

            if (!isAllowed)
            {
                return;
            }

            var dto = new SendMessageDto
            {
                Conference = new Conference {
                    Id = conferenceId
                },
                From                = from,
                To                  = to,
                Message             = message,
                ParticipantUsername = participantUsername,
                Timestamp           = DateTime.UtcNow,
                MessageUuid         = messageUuid
            };

            _logger.LogDebug($"Message validation passed for message {dto.MessageUuid}");
            // send to admin channel
            await SendToAdmin(dto);

            // determine participant username
            dto.Conference = await GetConference(conferenceId);
            await SendToParticipant(dto);

            _logger.LogDebug($"Pushing message to Video API history {dto.MessageUuid}");
            await _videoApiClient.AddInstantMessageToConferenceAsync(conferenceId, new AddInstantMessageRequest
            {
                From         = from,
                To           = to,
                Message_text = message
            });

            if (isSenderAdmin)
            {
                _logger.LogDebug($"Admin has responded, notifying admin channel");
                await Clients.Group(VhOfficersGroupName).AdminAnsweredChat(conferenceId, to.ToLower());
            }
        }
        private async Task SendToAdmin(SendMessageDto dto, string fromId)
        {
            var groupName = dto.Conference.Id.ToString();

            _logger.LogDebug("Sending message {MessageUuid} to group {GroupName}", dto.MessageUuid, groupName);
            var from = string.IsNullOrEmpty(fromId) ? dto.From : fromId;
            await Clients.Group(groupName)
            .ReceiveMessage(dto.Conference.Id, from, dto.To, dto.Message, dto.Timestamp, dto.MessageUuid);
        }
예제 #9
0
        private async Task SendToParticipant(SendMessageDto dto)
        {
            var participant = dto.Conference.Participants.Single(x =>
                                                                 x.Username.Equals(dto.ParticipantUsername, StringComparison.InvariantCultureIgnoreCase));

            var username = await _userProfileService.GetObfuscatedUsernameAsync(participant.Username);

            _logger.LogDebug($"Sending message {dto.MessageUuid} to group {username}");
            await Clients.Group(participant.Username.ToLowerInvariant())
            .ReceiveMessage(dto.Conference.Id, dto.From, dto.To, dto.Message, dto.Timestamp, dto.MessageUuid);
        }
        public async void Given_AChatId_AndAText_ItSends_TheMessage()
        {
            var request = new SendMessageDto()
            {
                Text = "bla",
                ToId = 494523457
            };

            var controller             = new SendmessageController(_secrets);
            IHttpActionResult response = await controller.Post(request);
        }
예제 #11
0
 protected override Task SendMessage(SendMessageDto message)
 {
     Debug.WriteLine("");
     Debug.WriteLine("_________________");
     Debug.WriteLine($"Chat Id: {message.ChatId}");
     Debug.WriteLine("Text:");
     Debug.WriteLine(message.Text);
     Debug.WriteLine("_________________");
     Debug.WriteLine("");
     return(Task.CompletedTask);
 }
예제 #12
0
        public async Task SendMessage_GivenInvalidModel_ReturnsErrorMessage(SendMessageDto data)
        {
            var service = new MessageService(_userRepository.Object, _messageRepository.Object, _errorRepository.Object,
                                             _auditRepository.Object);

            var result = await service.SendMessage(data);

            Assert.False(result.Success);
            Assert.False(result.Data);
            Assert.NotNull(result.Errors);
            Assert.Equal("Model validation errors!", result.Message);
        }
        public async Task PostMessageReturns500WhenUnknownExceptionIsThrown()
        {
            conversationsStoreMock.Setup(store => store.TryGetMessage(It.IsAny <string>(), It.IsAny <string>()))
            .ThrowsAsync(new UnknownException());

            SendMessageDto newMessage = new SendMessageDto(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());

            IActionResult result = await conversationController.PostMessage(
                Guid.NewGuid().ToString(), newMessage);

            TestUtils.AssertStatusCode(HttpStatusCode.InternalServerError, result);
        }
        public async Task PostMessageReturns503WhenStorageIsUnavailable()
        {
            conversationsStoreMock.Setup(store => store.TryGetMessage(It.IsAny <string>(), It.IsAny <string>()))
            .ThrowsAsync(new StorageErrorException("Test Failure"));

            SendMessageDto newMessage = new SendMessageDto(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());

            IActionResult result = await conversationController.PostMessage(
                Guid.NewGuid().ToString(), newMessage);

            TestUtils.AssertStatusCode(HttpStatusCode.ServiceUnavailable, result);
        }
        public async void IfYouCant_ContactTheId_ItReturns_BadRequest()
        {
            var request = new SendMessageDto()
            {
                Text = "bla",
                ToId = 11
            };

            var controller             = new SendmessageController(_secrets);
            IHttpActionResult response = await controller.Post(request);

            Assert.IsType <BadRequestErrorMessageResult>(response);
        }
예제 #16
0
        public void SendMessage(SendMessageDto dto, MessageBuilderContext mbContext)
        {
            var dict    = BuildDictionary(mbContext);
            var message = dict.Aggregate(mbContext.SendText, (current, value) =>
                                         current.Replace(value.Key, value.Value));

            MessageResource.Create(
                body: message,
                from: new Twilio.Types.PhoneNumber(dto.FromNumber),
                statusCallback: new Uri($"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Headers["X-Original-Host"]}{_httpContextAccessor.HttpContext.Request.Path}/status"),
                to: new Twilio.Types.PhoneNumber(dto.ToNumber)
                );
        }
예제 #17
0
        protected virtual async Task SendMessage(SendMessageDto message)
        {
            var                 client            = new HttpClient();
            string              messageSerialized = JsonConvert.SerializeObject(message);
            HttpContent         content           = new StringContent(messageSerialized, Encoding.UTF8, "application/json");
            HttpResponseMessage response          = await client.PostAsync(new Uri(_apiSendMessage), content);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new ServiceException("Bot integration failed. Response: " +
                                           await response.Content.ReadAsStringAsync());
            }
        }
예제 #18
0
        public IActionResult Message()
        {
            var data  = redis.GetList <RequestList>("receive_msg");
            var model = new SendMessageDto
            {
                Id         = Guid.NewGuid().ToString("N"),
                SendTime   = DateTime.Now,
                RequestUrl = "http://www.win4000.com",
                ViewUrl    = "http://reptile.t.cn"
            };

            ViewBag.Data = data;
            return(View(model));
        }
예제 #19
0
        public IActionResult Message(SendMessageDto model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var link = redis.ExistUrlBackLink("receive_msg", model.RequestUrl);

            if (!string.IsNullOrEmpty(link))
            {
                return(Redirect(link));
            }

            SendMessage(model);
            TempData["Message"] = "添加成功,请稍后查看....";
            return(RedirectToAction("Index"));
        }
예제 #20
0
        public IActionResult Send([FromBody] SendMessageDto sendMessageDto)
        {
            var user = HttpContext.Items["User"] as User;

            if (user == null || string.IsNullOrEmpty(sendMessageDto.Body) || string.IsNullOrEmpty(sendMessageDto.Recipent))
            {
                return(BadRequest());
            }
            try
            {
                _messageService.SaveMessage(sendMessageDto, user.Username);
            }
            catch (ApplicationException e)
            {
                return(NotFound());
            }
            return(Ok());
        }
예제 #21
0
        public void SaveMessage(SendMessageDto sendMessageDto, string sender)
        {
            if (!_context.Users.Any(u => u.Username == sendMessageDto.Recipent))
            {
                throw new ApplicationException("Sender not found");
            }
            var message = new Message
            {
                Body      = sendMessageDto.Body,
                Recipent  = sendMessageDto.Recipent,
                Sender    = sender,
                Timestamp = DateTime.UtcNow,
                Signature = sendMessageDto.Signature
            };

            _context.Messages.Add(message);
            _context.SaveChanges();
        }
        public async void OnGenericException_ItReturns_InternalServerError()
        {
            var request = new SendMessageDto()
            {
                Text = "bla",
                ToId = 11
            };

            var controller = new SendmessageController(new Secrets()
            {
                Telegram = new TelegramSecrets()
                {
                    Id = "banana"
                }
            });
            IHttpActionResult response = await controller.Post(request);

            Assert.IsType <ExceptionResult>(response);
        }
        private async Task <IHttpActionResult> SendMessage(SendMessageDto request)
        {
            _telegramBotClient = new TelegramBotClient(_botClientId);
            try
            {
                await _telegramBotClient.SendTextMessageAsync(request.ToId, request.Text, parseMode : ParseMode.Html);

                return(Ok());
            }
            catch (ApiRequestException ex)
            {
                if (ex.ErrorCode == 400)
                {
                    return(BadRequest(ex.Message));
                }

                return(InternalServerError(ex));
            }
        }
        public async Task <IActionResult> PostMessage(string id, [FromBody] SendMessageDto messageDto)
        {
            try
            {
                var message = await conversationService.PostMessage(id, messageDto);

                return(Ok(message));
            }
            catch (StorageErrorException e)
            {
                logger.LogError(Events.StorageError, e,
                                "Could not reach storage to add message, conversationId {conversationId}", id);
                return(StatusCode(503, $"Could not reach storage to add message, conversationId {id}"));
            }
            catch (Exception e)
            {
                logger.LogError(Events.InternalError, e,
                                "Failed to add message to conversation, conversationId: {conversationId}", id);
                return(StatusCode(500, $"Failed to add message to conversation, conversationId: {id}"));
            }
        }
예제 #25
0
        public async Task <IActionResult> Send([FromBody] SendMessageDto message)
        {
            try
            {
                var document = new DocumentDto
                {
                    StockId   = message.StockId,
                    Name      = message.Name,
                    Price     = message.Price,
                    UpdatedAt = DateTime.UtcNow
                };

                await _topicClient.SendAsync(new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(document))));

                return(StatusCode(200));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(StatusCode(500, e.Message));
            }
        }
예제 #26
0
        public async Task <IActionResult> Save([FromBody] SendMessageDto message)
        {
            try
            {
                var document = new DocumentDto
                {
                    StockId   = message.StockId,
                    Name      = message.Name,
                    Price     = message.Price,
                    UpdatedAt = DateTime.UtcNow
                };

                await new DocumentDbService().SaveDocumentAsync(document);

                return(StatusCode(200));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(StatusCode(500, e.Message));
            }
        }
예제 #27
0
        public async Task AddListMessages()
        {
            string participant1          = RandomString();
            string participant2          = RandomString();
            var    createConversationDto = new CreateConversationDto
            {
                Participants = new[] { participant1, participant2 }
            };

            await Task.WhenAll(
                chatServiceClient.CreateProfile(new CreateProfileDto {
                Username = participant1, FirstName = "Participant", LastName = "1"
            }),
                chatServiceClient.CreateProfile(new CreateProfileDto {
                Username = participant2, FirstName = "Participant", LastName = "2"
            })
                );

            var conversationDto = await chatServiceClient.AddConversation(createConversationDto);

            var message1 = new SendMessageDto("Hello", participant1);
            var message2 = new SendMessageDto("What's up?", participant1);
            var message3 = new SendMessageDto("Not much!", participant2);
            await chatServiceClient.SendMessage(conversationDto.Id, message1);

            await chatServiceClient.SendMessage(conversationDto.Id, message2);

            await chatServiceClient.SendMessage(conversationDto.Id, message3);

            ListMessagesDto listMessagesDto = await chatServiceClient.ListMessages(conversationDto.Id);

            Assert.AreEqual(3, listMessagesDto.Messages.Count);
            Assert.AreEqual(message3.Text, listMessagesDto.Messages[0].Text);
            Assert.AreEqual(message2.Text, listMessagesDto.Messages[1].Text);
            Assert.AreEqual(message1.Text, listMessagesDto.Messages[2].Text);
        }
예제 #28
0
        public async Task <IActionResult> PostMessage(string id, [FromBody] SendMessageDto messageDto)
        {
            try
            {
                var message = new Message(messageDto.Text, messageDto.SenderUsername, DateTime.UtcNow);
                await conversationsStore.AddMessage(id, message);

                logger.LogInformation(Events.ConversationMessageAdded,
                                      "Message has been added to conversation {conversationId}, sender: {senderUsername}", id, messageDto.SenderUsername);
                return(Ok(message));
            }
            catch (StorageErrorException e)
            {
                logger.LogError(Events.StorageError, e,
                                "Could not reach storage to add message, conversationId {conversationId}", id);
                return(StatusCode(503));
            }
            catch (Exception e)
            {
                logger.LogError(Events.InternalError, e,
                                "Failed to add message to conversation, conversationId: {conversationId}", id);
                return(StatusCode(500));
            }
        }
예제 #29
0
        public async Task SendMessage(string conversationId, SendMessageDto messageDto)
        {
            try
            {
                HttpResponseMessage response =
                    await httpClient.PostAsync($"api/conversation/{conversationId}",
                                               new StringContent(JsonConvert.SerializeObject(messageDto), Encoding.UTF8, "application/json"));

                if (!response.IsSuccessStatusCode)
                {
                    throw new ChatServiceException("Failed to retrieve user profile", response.ReasonPhrase, response.StatusCode);
                }
            }
            catch (JsonException e)
            {
                throw new ChatServiceException("Failed to deserialize the response", e,
                                               "Serialization Exception", HttpStatusCode.InternalServerError);
            }
            catch (Exception e)
            {
                throw new ChatServiceException("Failed to reach chat service", e,
                                               "Internal Server Error", HttpStatusCode.InternalServerError);
            }
        }
예제 #30
0
        public async Task <IActionResult> SendMessage(SendMessageDto dto)
        {
            var message = new Message()
            {
                SenderUserId   = dto.SenderUserId,
                ReceiverUserId = dto.ReceiverUserId,
                Content        = dto.Content,
            };

            var server = await _trackerService.GetCurrentClientServerByUserId(dto.ReceiverUserId);

            if (_configuration["MyIP"] != server.ServerIp)
            {
                await _messagerService.PassThroughMessage(server.ServerIp, message);

                return(Ok());
            }

            await _dbContext.AddAsync(message);

            await _dbContext.SaveChangesAsync();

            return(Ok());
        }