示例#1
0
        public async Task <ConversationDTO> AddConversation(ConversationDTO conversation, ApplicationUser invokingUser)
        {
            if (invokingUser == null)
            {
                return(null);
            }
            var users = await userFinder.FindUsersByNames(conversation.UserNames);

            if (!users.Any(u => u.Id == invokingUser.Id))
            {
                users.Add(invokingUser);
            }
            var dbConversation = new Conversation
            {
                IsGroup        = conversation.IsGroup,
                Participations = users.Select(u => new ConversationUser {
                    User = u
                }).ToList()
            };

            foreach (var convUser in dbConversation.Participations)
            {
                convUser.Conversation = dbConversation;
            }

            var added = await conversationManager.AddConversation(dbConversation);

            return(mapper.Map <ConversationDTO>(added));
        }
 public void ResolveUrl(ConversationDTO conversationDTO)
 {
     if (!conversationDTO.ConversationPhoto.StartsWith(_profilePhotosUrl))
     {
         conversationDTO.ConversationPhoto = $"{_profilePhotosUrl}/{conversationDTO.ConversationPhoto}";
     }
 }
        public ConversationDTO CreateConversation(ConversationDTO convDTO)
        {
            using (var uow = new UnitOfWork())
            {
                var conversationRepository = uow.GetRepository <Conversation>();
                var acountRepository       = uow.GetRepository <Account>();

                var existConv = conversationRepository.GetAll().FirstOrDefault(c => (
                                                                                   (c.UserOneId == convDTO.UserOne.Id && c.UserTwoId == convDTO.UserTwo.Id)));

                if (existConv != null)
                {
                    return(null);
                }
                else
                {
                    Account            acountOne = acountRepository.GetById(convDTO.UserOne.Id);
                    Account            acountTwo = acountRepository.GetById(convDTO.UserTwo.Id);
                    ConversationMapper cm        = new ConversationMapper();
                    convDTO.UserOne.FullName = acountOne.FirstName + " " + acountOne.LastName;
                    convDTO.UserTwo.FullName = acountTwo.FirstName + " " + acountTwo.LastName;
                    Conversation conversation = cm.MapFromDTO(convDTO);
                    conversation.UserOne = acountOne;
                    conversation.UserTwo = acountTwo;

                    Conversation add = conversationRepository.Add(conversation);
                    return(cm.MapToDTO(add));
                }
            }
        }
示例#4
0
        public async Task <ActionResult> StartConversation([FromBody] ConversationDTO participants)
        {
            try
            {
                await _repository.StartConversation(participants);

                var message = new MessageDTO
                {
                    senderUsername   = $"{participants.Sender.Username}",
                    clientuniqueid   = participants.Sender.Id.ToString(),
                    receiverUsername = $"{participants.Receiver.Username}",
                    receiverId       = participants.Receiver.Id.ToString(),
                    message          = participants.Text,
                    type             = "sent",
                    date             = DateTime.Now
                };

                await _repository.SendMessage(message);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
示例#5
0
        public async Task CreateOrSendConversation(string firstPerson, string secondPerson)
        {
            var conversation = await _conversationService.GetConversation(firstPerson, secondPerson);

            if (conversation != null)
            {
                await _hubContext.Clients.User(firstPerson).SendAsync("IfExistConversation", conversation.Id);

                await _hubContext.Clients.User(secondPerson).SendAsync("IfExistConversation", conversation.Id);
            }
            else
            {
                ConversationDTO newConversationDTO = new ConversationDTO()
                {
                    Id            = null,
                    FirstPerson   = firstPerson,
                    SecondPerson  = secondPerson,
                    TimeToCreated = DateTime.Now,
                    Anonymouse    = true
                };

                await _conversationService.AddConversation(newConversationDTO);

                var existConversation = await _conversationService.GetConversation(firstPerson, secondPerson);

                await _hubContext.Clients.User(firstPerson).SendAsync("SetConservationId", existConversation.Id);

                await _hubContext.Clients.User(secondPerson).SendAsync("SetConservationId", existConversation.Id);
            }
        }
示例#6
0
        public async Task <Result <IEnumerable <ConversationDTO> > > GetConversations(string userId)
        {
            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(Result <IEnumerable <ConversationDTO> > .CreateFailed(
                           HttpStatusCode.NotFound, "User not found"));
            }

            var conversations = await _context.Conversations
                                .Where(x => x.FromUser == user || x.ToUser == user)
                                .Include(x => x.ToUser)
                                .Include(x => x.FromUser)
                                .OrderByDescending(x => x.LastMessageDate)
                                .Distinct()
                                .ToListAsync();

            if (conversations == null)
            {
                return(Result <IEnumerable <ConversationDTO> > .CreateFailed(
                           HttpStatusCode.NotFound, "Conversations not found"));
            }
            return(Result <IEnumerable <ConversationDTO> > .CreateSuccessful(ConversationDTO.ToConversationDTOList(conversations, user)));
        }
示例#7
0
        public async Task <ActionResult> StartConversation([FromBody] ConversationDTO participants)
        {
            try
            {
                await _repository.StartConversation(participants);

                var message = new Message
                {
                    Sender     = $"{participants.Sender.Student.FirstName} {participants.Sender.Student.LastName}",
                    SenderId   = participants.Sender.Id,
                    Receiver   = $"{participants.Receiver.Student.FirstName} {participants.Receiver.Student.LastName}",
                    ReceiverId = participants.Receiver.Id,
                    Content    = participants.FirstMessage
                };

                await _repository.SendMessage(message);

                await _repository.SetTimeToLiveForStream(participants.Sender.Id, participants.Receiver.Id);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
示例#8
0
        public async Task <IActionResult> GetConversationOfUsers(string userId2)
        {
            var user1 = await userManager.GetUserAsync(HttpContext.User);

            ConversationDTO conversation = null;

            try
            {
                if (user1 != null)
                {
                    conversation = await _chatService.GetConversationOfUsers(user1.Id, userId2);
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            if (conversation != null)
            {
                return(Ok(conversation));
            }

            return(StatusCode(StatusCodes.Status400BadRequest));
        }
示例#9
0
        public ConversationViewModel(IMessageService messageService, IConversationService conversationService)
        {
            _messageService      = messageService;
            _conversationService = conversationService;
            _messageService.OnReceivedMessage += MessageService_OnReceivedMessage;
            ConversationDTO = DataContainer.ConversationDTO;
            CurrentUser     = DataContainer.User;

            MapMessages();
        }
        public IHttpActionResult Delete(int id)
        {
            var             messengerService = new MessengerService();
            ConversationDTO convDTO          = messengerService.RemoveConversation(id);

            if (convDTO == null)
            {
                return(BadRequest("This conversation does not exist in DB"));
            }
            return(Ok(convDTO));
        }
        public IHttpActionResult Post(ConversationDTO conversationDTO)
        {
            var             messengerService = new MessengerService();
            ConversationDTO convDTO          = messengerService.CreateConversation(conversationDTO);

            if (convDTO == null)
            {
                return(NotFound());
            }

            return(Ok(convDTO));
        }
示例#12
0
        public async Task <ActionResult <ConversationDTO> > CreateConversation(ConversationDTO conversation)
        {
            var user = await userFinder.FindByClaimsPrincipal(User);

            var added = await conversationManager.AddConversation(conversation, user);

            if (added == null)
            {
                return(Conflict());
            }
            return(CreatedAtAction(nameof(GetConversation), new { id = added.Id }, added));
        }
 public HttpResponseMessage MarkUnRead(ConversationDTO postData)
 {
     try
     {
         InternalMessagingController.Instance.MarkUnRead(postData.ConversationId, UserInfo.UserID);
         return(Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }));
     }
     catch (Exception exc)
     {
         Logger.Error(exc);
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
     }
 }
示例#14
0
        public async Task <bool> DeleteConversationAsync(ConversationDTO conversationDTO)
        {
            var conversation = _conversationParser.ParseConversation(conversationDTO);

            if (conversation is PrivateConversation)
            {
                return(await _conversationRepository.DeleteConversationAsync((PrivateConversation)conversation));
            }
            else
            {
                return(await _conversationRepository.DeleteConversationAsync((GroupConversation)conversation));
            }
        }
 public HttpResponseMessage DeleteUserFromConversation(ConversationDTO postData)
 {
     try
     {
         InternalMessagingController.Instance.DeleteUserFromConversation(postData.ConversationId, this.UserInfo.UserID);
         return(this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }));
     }
     catch (Exception ex)
     {
         var message = "An unexpected error occurred while attempting to delete a user from a conversation, consult the server logs for more information.";
         Logger.Error(message, ex);
         return(this.Request.CreateResponse(HttpStatusCode.InternalServerError, message));
     }
 }
示例#16
0
        public ConversationDTO ParseConversation(GroupConversation conversation)
        {
            var conversationDTO = new ConversationDTO()
            {
                Id = conversation.Id,
                ConversationType  = conversation.ConversationType,
                ConversationPhoto = _defaultGroupPhotoName,
                ConversationName  = conversation.Name,
            };

            _photosUrlResolver.ResolveUrl(conversationDTO);

            return(conversationDTO);
        }
示例#17
0
        public async Task <bool> DeleteConversationAsync(ConversationDTO conversationDTO)
        {
            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.PutAsync($"{_apiURL}/Delete",
                                                         new StringContent(
                                                             JsonConvert.SerializeObject(conversationDTO),
                                                             Encoding.UTF8, "application/json"
                                                             ));

                var jsonResponse = await response.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <bool>(jsonResponse));
            }
        }
示例#18
0
        public async Task <IEnumerable <Message> > GetConversationMessagesAsync(ConversationDTO conversationDTO)
        {
            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.PostAsync(_apiURL,
                                                          new StringContent(
                                                              JsonConvert.SerializeObject(conversationDTO),
                                                              Encoding.UTF8, "application/json"
                                                              ));

                var jsonResponse = await response.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <IEnumerable <Message> >(jsonResponse));
            }
        }
示例#19
0
        public ConversationDTO ParseConversation(GroupConversation conversation, Message message, int userId)
        {
            var conversationDTO = new ConversationDTO()
            {
                Id = conversation.Id,
                ConversationType        = conversation.ConversationType,
                ConversationPhoto       = _defaultGroupPhotoName,
                ConversationLastMessage = (message.SenderId == userId) ? $"You: {message.MessageContent}" : message.MessageContent,
                ConversationName        = conversation.Name,
                LastMessageSendTime     = message.SendTime
            };

            _photosUrlResolver.ResolveUrl(conversationDTO);

            return(conversationDTO);
        }
        public ConversationDTO MapToDTO(Conversation source)
        {
            ConversationDTO target = new ConversationDTO();

            target.Id = source.Id;

            AccountSimpleMapper accountMapper = new AccountSimpleMapper();

            target.UserOne = accountMapper.MapToDTO(source.UserOne);
            target.UserTwo = accountMapper.MapToDTO(source.UserTwo);

            MessageMapper messageMapper = new MessageMapper();

            target.Messages = new HashSet <MessageDTO>();

            return(target);
        }
示例#21
0
        public ConversationDTO ParseConversation(PrivateConversation conversation, Message message, int userId)
        {
            var otherUser       = (userId == conversation.User1Id) ? conversation.User2 : conversation.User1;
            var conversationDTO = new ConversationDTO()
            {
                Id = conversation.Id,
                ConversationType        = conversation.ConversationType,
                ConversationPhoto       = otherUser.PhotoFileName,
                ConversationLastMessage = (message.SenderId == userId) ? $"You: {message.MessageContent}" : message.MessageContent,
                ConversationName        = otherUser.Username,
                LastMessageSendTime     = message.SendTime
            };

            _photosUrlResolver.ResolveUrl(conversationDTO);

            return(conversationDTO);
        }
示例#22
0
        public ConversationDTO ParseConversation(PrivateConversation conversation, int crtUserId)
        {
            if (conversation is null)
            {
                return(null);
            }

            var otherUser       = (crtUserId == conversation.User1Id) ? conversation.User2 : conversation.User1;
            var conversationDTO = new ConversationDTO()
            {
                Id = conversation.Id,
                ConversationType = conversation.ConversationType,
                ConversationName = otherUser.Username
            };

            return(conversationDTO);
        }
示例#23
0
        public async Task StartConversation(ConversationDTO participants)
        {
            string   senderSetKey   = $"rentee:{participants.Sender.Id}:chats";
            string   receiverSetKey = $"renterer:{participants.Receiver.Id}:chats";
            Rentee   sender         = participants.Sender;
            Renterer receiver       = participants.Receiver;

            var senderSetValue   = JsonSerializer.Serialize(participants.Receiver);
            var receiverSetValue = JsonSerializer.Serialize(participants.Sender);

            double score = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

            SortedSetEntry[] senderSetEntry   = new SortedSetEntry[] { new SortedSetEntry(senderSetValue, score) };
            SortedSetEntry[] receiverSetEntry = new SortedSetEntry[] { new SortedSetEntry(receiverSetValue, score) };

            IDatabase redisDB = _redisConnection.GetDatabase();
            await redisDB.SortedSetAddAsync(senderSetKey, senderSetEntry);

            await redisDB.SortedSetAddAsync(receiverSetKey, receiverSetEntry);
        }
        public IEnumerable <ConversationDTO> getConversationByUserId(int userID)
        {
            using (var uow = new UnitOfWork())
            {
                var conversationRepository = uow.GetRepository <Conversation>();
                var conversations          = conversationRepository.FindBy(conv => conv.UserOneId == userID || conv.UserTwoId == userID);

                List <ConversationDTO> list = new List <ConversationDTO>();
                ConversationMapper     conversationMapper = new ConversationMapper();


                foreach (var conv in conversations)
                {
                    ConversationDTO convDTO = conversationMapper.MapToDTO(conv);
                    list.Add(convDTO);
                }

                return(list);
            }
        }
示例#25
0
        public Conversation ParseConversation(ConversationDTO conversationDTO)
        {
            Conversation pc;

            if (conversationDTO.ConversationType == ConversationType.Private)
            {
                pc = new PrivateConversation()
                {
                    Id = conversationDTO.Id
                };
            }
            else
            {
                pc = new GroupConversation()
                {
                    Id = conversationDTO.Id
                };
            }

            return(pc);
        }
示例#26
0
        public static ConversationDTO ToDto(this Conversation conv, int profileId)
        {
            if (conv == null)
            {
                return(null);
            }
            ConversationDTO dto = new ConversationDTO
            {
                Id       = conv.Id,
                Messages = new List <MessageDTO>(),
                FriendId = conv.Member1Id == profileId ? conv.Member2Id : conv.Member1Id
            };

            if (conv.Messages != null)
            {
                foreach (var msg in conv.Messages.OrderBy(x => x.Date))
                {
                    dto.Messages.Add(msg.ToDto(profileId));
                }
            }
            return(dto);
        }
        public ConversationDTO RemoveConversation(int convID)
        {
            using (var uow = new UnitOfWork())
            {
                var conversationRepo = uow.GetRepository <Conversation>();

                Conversation conv = conversationRepo.GetById(convID);

                if (conv == null)
                {
                    return(null);
                }
                else
                {
                    ConversationMapper cm      = new ConversationMapper();
                    ConversationDTO    convDTO = cm.MapToDTO(conv);
                    conversationRepo.Delete(convID);
                    uow.SaveChanges();
                    return(convDTO);
                }
            }
        }
示例#28
0
        public async Task <ConversationDTO> GetConversationById(int conversationId)
        {
            ConversationDTO conversation = new ConversationDTO();

            if (conversationId > 0)
            {
                conversation = await(from c in _db.Conversations
                                     where c.ConversationId == conversationId
                                     join m in _db.ConversationMessages on
                                     c.ConversationId equals m.ConversationId into messageResult
                                     select new ConversationDTO
                {
                    ConversationId = c.ConversationId,
                    AdId           = c.AdId,
                    SellerId       = c.SellerId,
                    SellerName     = c.SellerName,
                    BuyerId        = c.BuyerId,
                    BuyerName      = c.BuyerName,
                    Messages       = messageResult.ToList()
                }).FirstOrDefaultAsync();
            }

            return(conversation);
        }
示例#29
0
        public async Task <ActionResult <bool> > DeleteConversation(ConversationDTO conversationDTO)
        {
            bool deleted = await _conversationService.DeleteConversationAsync(conversationDTO);

            return(Ok(deleted));
        }
        public async Task <IActionResult> GetConversations()
        {
            try
            {
                var currentUserId = User.GetUserId().Value;
                var users         = await _messageService.GetInterlocutorsAsync(currentUserId);//_context.Users.AsNoTracking().Where(u => usersId.Contains(u.Id)).ToDictionaryAsync(u => u.Id);


                return(Ok((await _messageService.GetConversation(currentUserId)).Select(g => ConversationDTO.Create(g, users, currentUserId))));
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error during conversation download");
                return(NotFound());
            }
        }
 public HttpResponseMessage DeleteUserFromConversation(ConversationDTO postData)
 {
     try
     {
         InternalMessagingController.Instance.DeleteUserFromConversation(postData.ConversationId, UserInfo.UserID);
         return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" });
     }
     catch (Exception exc)
     {
         Logger.Error(exc);
         return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
     }
 }