Exemple #1
0
        public async Task <IEnumerable <ConversationDataModel> > GetUserChats(string deviceId, string userId, int maxParticipants = 100)
        {
            var result = _dbContext
                         .UsersConversations
                         .Include(x => x.Conversation.Participants)
                         .ThenInclude(x => x.User)
                         .Include(x => x.Conversation.Roles)
                         .ThenInclude(x => x.Role)
                         .Include(x => x.Conversation.BannedUsers)
                         .Include(x => x.Conversation.PublicKey)
                         .Include(x => x.Conversation.LastMessages)
                         .ThenInclude(x => x.Message)
                         .ThenInclude(x => x.Event.Actor)
                         .Include(x => x.Conversation.LastMessages)
                         .ThenInclude(x => x.Message)
                         .ThenInclude(x => x.Event.UserInvolved)
                         .Where(chat => chat.UserID == userId && (chat.DeviceId == null || chat.DeviceId == deviceId))
                         .Select(x => x.Conversation);

            foreach (var chat in result)
            {
                if (chat.Participants != null)
                {
                    chat.participants = chat.Participants.Take(maxParticipants).Select(x => x.User);

                    foreach (var p in chat.participants)
                    {
                        p.ChatRole        = chat.Roles.FirstOrDefault(x => x.UserId == p.Id);
                        p.IsBlockedInChat = chat.BannedUsers.FirstOrDefault(x => x.UserID == p.Id) != null;
                    }

                    chat.DeviceId = chat.Participants.FirstOrDefault(x => x.UserID == userId)?.DeviceId;
                }

                chat.ClientLastMessage =
                    chat.LastMessages?.FirstOrDefault(x => x.UserID == userId)?.Message?.MessageID ?? 0;

                chat.LastMessage = await messages.SingleOrDefaultAsync(new GetMostRecentMessageSpec(chat.Id));

                chat.UnreadCount = await messages.CountAsync(new UnreadMessagesCountSpec(userId, chat.Id, chat.ClientLastMessage));

                chat.IsMessagingRestricted = chat.BannedUsers?.Any(x => x.UserID == userId) ?? false;
                chat.Role = chat.Roles?.FirstOrDefault(x => x.UserId == userId);
            }

            return(await result
                   .ToListAsync());
        }