public void AddMember(User user, Server.Model.Conversation.Conversation conversation)
        {
            try
            {
#if net452
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromMinutes(2)
                }))
                {
#endif
                var convM = new ConversationUser
                {
                    UserId         = user.Id,
                    ConversationId = conversation.Id,
                    JoinDate       = DateTime.Now
                };
                if (!Exists(convM, e => e.ConversationId == conversation.Id && e.UserId == user.Id))
                {
                    Db.Set <ConversationUser>().Add(convM);
                    Db.SaveChanges();
                }
#if net452
                scope.Complete();
            }
#endif
            }
            catch (Exception ex)
            {
                LogEventManager.Logger.Error(ex.Message, ex);
                throw;
            }
        }
        public async Task <ConversationUser> Update(ConversationUser conversationUser)
        {
            var result = dataContext.ConversationUsers.Update(conversationUser);
            await dataContext.SaveChangesAsync();

            return(result.Entity);
        }
 public List <ChatConversation> GetChatConversations(string app_Id, string chatId, int pageIndex, int pageSize)
 {
     try {
         var chat = _chats.Find <Chat> (c => c.AppId == app_Id && c.Id == chatId).Project <Chat> (Builders <Chat> .Projection
                                                                                                  .Slice("ChatConversations", (pageIndex * pageSize), pageSize)).FirstOrDefault();
         var query = from conversation in chat.ChatConversations.AsQueryable()
                     join user in _users.AsQueryable() on
                     conversation.UserId equals user.Id into ConversationUser
                     orderby conversation.Date descending
                     select new ChatConversation()
         {
             Id     = conversation.Id,
             UserId = conversation.UserId,
             Text   = conversation.Text,
             FileId = conversation.FileId,
             Date   = conversation.Date,
             ParentConversationId    = conversation.ParentConversationId,
             ChatConversationReaders = conversation.ChatConversationReaders,
             User = ConversationUser.FirstOrDefault()
         };
         return(query.Reverse().ToList());
     } catch (Exception ex) {
         _logger.LogError(ex, "GetChatConversations ChatRepository Exception");
         return(null);
     }
 }
        public ConversationUser Create(ConversationUser conversationUser)
        {
            // Check
            if (!_context.Conversations.Any(x => x.Id == conversationUser.ConversationId))
            {
                throw new Exception("Conversation not found");
            }

            if (!_context.Users.Any(x => x.Id == conversationUser.UserId))
            {
                throw new Exception("User not found");
            }

            if (_context.ConversationUsers.Any(
                    x => (x.ConversationId == conversationUser.ConversationId && x.UserId == conversationUser.UserId)))
            {
                throw new Exception("Member already exist");
            }

            // Add
            _context.ConversationUsers.Add(conversationUser);
            _context.SaveChanges();

            // Ok
            return(conversationUser);
        }
        public async Task <List <ChatConversation> > GetUnReadChatConversationsAsync(string app_Id, string chatId, string userId)
        {
            try {
                var chat = await _chats.Find <Chat> (c => c.AppId == app_Id && c.Id == chatId)
                           //.Project<Chat>(Builders<Chat>.Projection
                           //.Slice(c => c.ChatConversations.Find(conv => conv.UserId!=userId && !conv.ChatConversationReaders.Any(reader => reader.UserId == userId)),0)).FirstOrDefaultAsync();
                           .FirstOrDefaultAsync();

                var query = from conversation in chat.ChatConversations.AsQueryable()
                            where conversation.UserId != userId && !conversation.ChatConversationReaders.Any(reader => reader.UserId == userId)
                            join user in _users.AsQueryable() on
                            conversation.UserId equals user.Id into ConversationUser
                            orderby conversation.Date descending
                            select new ChatConversation()
                {
                    Id     = conversation.Id,
                    UserId = conversation.UserId,
                    Text   = conversation.Text,
                    FileId = conversation.FileId,
                    Date   = conversation.Date,
                    ParentConversationId    = conversation.ParentConversationId,
                    ChatConversationReaders = conversation.ChatConversationReaders,
                    User = ConversationUser.Select(conversationUser => new User()
                    {
                        Id = conversationUser.Id, FullName = conversationUser.FullName
                    }).FirstOrDefault()
                };
                return(await Task.FromResult(query.Reverse().ToList()));
            } catch (Exception ex) {
                _logger.LogError(ex, "GetUnReadChatConversationsAsync ChatRepository Exception");
                return(null);
            }
        }
 private ConversationUserServiceResultDto Ok(ConversationUser conversationUser)
 {
     return(new ConversationUserServiceResultDto()
     {
         Entity = MapToDto(conversationUser),
         Success = true
     });
 }
        private async Task AddUsersToConversation(List <int> userIds, int conversationId)
        {
            userIds.ForEach(id => {
                var conversationUser = new ConversationUser(conversationId, id);
                _context.ConversationUsers.Add(conversationUser);
            });

            await _context.SaveChangesAsync();
        }
        private async Task <ConversationUserServiceResultDto> DeleteUserAsync(ConversationUser conversationUser)
        {
            if (conversationUser == null)
            {
                return(Fail(ConversationUserServiceFailCauses.NoUsersFound));
            }
            var deleted = await _conversationUserRepository.DeleteAsync(conversationUser);

            return(Ok(deleted));
        }
        private async Task CreateConversationUser(Conversation conversation, CancellationToken cancellationToken)
        {
            var conversationUser = new ConversationUser
            {
                ConversationId = conversation.Id,
                UserId         = _currentUser.UserId,
                IsDisabled     = false
            };

            await _context.ConversationUsers.AddAsync(conversationUser);

            await _context.SaveChangesAsync(cancellationToken);
        }
        public void Delete(ConversationUser conversationUser)
        {
            // Find
            if (!_context.ConversationUsers.Any(
                    x => x.ConversationId == conversationUser.ConversationId && x.UserId == conversationUser.UserId))
            {
                throw new Exception("Member not found");
            }

            // Delete
            _context.ConversationUsers.Remove(conversationUser);
            _context.SaveChanges();
        }
        public async void JoinUserToConversation(int conversationId, long userId, string signalRConnectionId)
        {
            var cu = new ConversationUser()
            {
                JoinedDate          = DateTime.UtcNow,
                ConversationId      = conversationId,
                UserId              = userId,
                SignalRConnectionId = signalRConnectionId
            };

            _commandContext.ConversationUsers.Add(cu);
            await _commandContext.SaveChangesAsync();
        }
Exemple #12
0
        private async Task AssignTicketToUser(AssignTicketCommand request, CancellationToken cancellationToken)
        {
            var conversationUser = new ConversationUser
            {
                ConversationId = request.ConversationId,
                UserId         = _currentUser.UserId,
                IsDisabled     = false
            };

            await _context.ConversationUsers.AddAsync(conversationUser);

            await _context.SaveChangesAsync(cancellationToken);
        }
        public void UpdateSeen(ConversationUser conversationUser, Message message)
        {
            // Check
            if (conversationUser.ConversationId != message.ConversationId)
            {
                throw new Exception("Conversation is not match");
            }

            var updatedConversationUser = conversationUser;

            updatedConversationUser.SeenMessageId = message.Id;

            // Update
            _context.ConversationUsers.Update(conversationUser);
            _context.SaveChanges();
        }
        public async Task <List <ChatConversation> > GetChatConversationsAsync(ChatHistoryFilterModel filter)
        {
            try {
                /* TO DO
                 *  optimize the query with aggregation framework*/
                var chat = await _chats.Find(c => c.Id == filter.ChatId).FirstOrDefaultAsync();

                if (filter.DirectionType == KeysetFilterModelType.Next)
                {
                    chat.ChatConversations = chat.ChatConversations
                                             .Where(conversation => conversation.Date.CompareTo(filter.EdgeDateTime) > 0)
                                             .OrderBy(o => o.Date).Take(filter.Limit).ToList();
                }
                else
                {
                    chat.ChatConversations = chat.ChatConversations
                                             .Where(conversation => conversation.Date.CompareTo(filter.EdgeDateTime) < 0)
                                             .OrderByDescending(o => o.Date).Take(filter.Limit).Reverse().ToList();
                }
                var query = from conversation in chat.ChatConversations.AsQueryable()
                            join user in _users.AsQueryable() on
                            conversation.UserId equals user.Id into ConversationUser
                            select new ChatConversation()
                {
                    Id     = conversation.Id,
                    UserId = conversation.UserId,
                    Text   = conversation.Text,
                    FileId = conversation.FileId,
                    Date   = conversation.Date,
                    ParentConversationId    = conversation.ParentConversationId,
                    ChatConversationReaders = conversation.ChatConversationReaders,
                    User = ConversationUser.Select(conversationUser => new User()
                    {
                        Id = conversationUser.Id, FullName = conversationUser.FullName
                    }).FirstOrDefault()
                };
                return(await Task.FromResult(query.ToList()));

                //return await Task.FromResult(query.Skip(pageIndex * pageSize).Take(pageSize).ToList());
            } catch (Exception ex) {
                _logger.LogError(ex, "GetChatConversationsAsync ChatRepository Exception");
                return(null);
            }
        }
        private static async Task <Guid> CreateSampleTicket(ApplicationDbContext context, string customerUserId, string[] organizationUserIds, string[] ticketUserIds, bool isClosedTicket)
        {
            var createdOrganizationId = await CreateSampleOrganization(context, organizationUserIds);

            var ticket = new Conversation
            {
                Title          = "My First Ticket",
                OrganizationId = createdOrganizationId,
                IsClosed       = isClosedTicket
            };

            await context.Conversations.AddAsync(ticket);

            await context.SaveChangesAsync();

            foreach (var userId in ticketUserIds)
            {
                var ticketUser = new ConversationUser
                {
                    ConversationId = ticket.Id,
                    UserId         = userId,
                    IsDisabled     = false
                };

                await context.ConversationUsers.AddAsync(ticketUser);
            }

            await context.SaveChangesAsync();

            var ticketMessage = new ConversationMessage
            {
                ConversationId = ticket.Id,
                UserId         = customerUserId,
                Message        = "Hello from first ticket"
            };

            await context.ConversationMessages.AddAsync(ticketMessage);

            await context.SaveChangesAsync();

            return(ticket.Id);
        }
 private ConversationUserDto MapToDto(ConversationUser conversationUser)
 {
     return(_mapper.Map <ConversationUser, ConversationUserDto>(conversationUser));
 }
Exemple #17
0
        //[AllowAnonymous]
        public async Task <ActionResult <ApiConversation> > PostConversation(ApiConversationCreateModel model)
        {
            var inputDbConversation = new Conversation
            {
                Title   = model.Title,
                Created = _systemClock.UtcNow
            };

            //if (User.Identity.IsAuthenticated)
            //{
            //    _logger.LogDebug(new EventId(5, "Testing EventId"), "Forbid result returned");
            //    return Forbid();
            //}
            //else
            //{
            //    _logger.LogDebug(new EventId(5, "Testing EventId"), "Challenge result returned");
            //    return Challenge();
            //}

            _context.Conversations.Add(inputDbConversation);

            //ApplicationUser applicationUser = await _context.Users.FindAsync(Guid.Parse(User.Identity.GetSubjectId()));
            var currentUserId    = Guid.Parse(User.Identity.GetSubjectId());
            var currentUserEntry = _context.Entry(new ApplicationUser {
                Id = currentUserId
            });

            currentUserEntry.State = EntityState.Unchanged;//TODO: here it sometime crashes on "The instance of entity type 'ApplicationUser' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values."

            var conversationUser = new ConversationUser
            {
                Conversation = inputDbConversation,
                User         = currentUserEntry.Entity
            };

            _context.ConversationUsers.Add(conversationUser);

            await _context.SaveChangesAsync();

            //if (!User.IsAuthenticated())
            //{
            //    await _signInManager.SignInAsync(applicationUser, false);
            //}

            var resultModel = new ApiConversation(inputDbConversation.Id)
            {
                Created           = inputDbConversation.Created,
                IsPublic          = inputDbConversation.IsPublic,
                Title             = inputDbConversation.Title,
                ConversationUsers = new List <ApiConversationUser>
                {
                    new ApiConversationUser(
                        conversationUser.Id,
                        conversationUser.UserId,
                        conversationUser.ConversationId,
                        new ApiUser(currentUserId, User.FindFirstValue(ClaimTypes.NameIdentifier), UserStatus.Online)
                        )
                    {
                        Nickname = null
                    }
                }
            };

            return(CreatedAtAction("GetConversation", new { id = conversationUser.Id }, resultModel));
        }