Exemple #1
0
        public async Task <ChatVm> EditChatAsync(EditChatVm editChat, long userId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                IQueryable <Chat> query = from chat in context.Chats
                                          join chatUser in context.ChatUsers on chat.Id equals chatUser.ChatId
                                          join chatUsers in context.ChatUsers on chat.Id equals chatUsers.ChatId
                                          where chat.Id == editChat.Id &&
                                          chatUser.UserId == userId &&
                                          chatUser.UserRole >= UserRole.Admin &&
                                          chat.Deleted == false &&
                                          chatUser.Banned == false &&
                                          chatUser.Deleted == false &&
                                          chatUsers.Banned == false &&
                                          chatUsers.Deleted == false
                                          select chat;
                Chat targetChat = await query
                                  .FirstOrDefaultAsync()
                                  .ConfigureAwait(false);

                if (targetChat != null)
                {
                    targetChat = ChatConverter.GetChat(targetChat, editChat);
                    await context.SaveChangesAsync().ConfigureAwait(false);

                    return(ChatConverter.GetChatVm(targetChat));
                }
                throw new PermissionDeniedException();
            }
        }
Exemple #2
0
        public async Task <ChatVm> NewOrEditChatAsync(ChatVm targetChat)
        {
            if (targetChat == null)
            {
                return(null);
            }

            try
            {
                using (MessengerDbContext context = contextFactory.Create())
                {
                    var query = from chat in context.Chats
                                where chat.Id == targetChat.Id
                                select chat;
                    Chat editableChat = await query.Include(opt => opt.ChatUsers).FirstOrDefaultAsync().ConfigureAwait(false);

                    if (editableChat == null)
                    {
                        editableChat = ChatConverter.GetChat(targetChat);
                        if (targetChat.Users != null)
                        {
                            editableChat.ChatUsers = ChatUserConverter.GetChatUsers(targetChat.Users).ToList();
                        }

                        await context.AddAsync(editableChat).ConfigureAwait(false);
                    }
                    else
                    {
                        editableChat = ChatConverter.GetChat(editableChat, new EditChatVm
                        {
                            About    = targetChat.About,
                            Name     = targetChat.Name,
                            Photo    = targetChat.Photo,
                            Public   = targetChat.Public,
                            Security = targetChat.Security,
                            Visible  = targetChat.Visible
                        });
                        if (!targetChat.Users.IsNullOrEmpty())
                        {
                            editableChat.ChatUsers = ChatUserConverter.GetChatUsers(targetChat.Users);
                        }

                        context.Update(editableChat);
                    }
                    await context.SaveChangesAsync().ConfigureAwait(false);

                    return(ChatConverter.GetChatVm(editableChat));
                }
            }
            catch (DbUpdateException ex)
            {
                Logger.WriteLog(ex);
                return(targetChat);
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
                return(null);
            }
        }
 public async Task <ChatVm> GetChatByIdAsync(long chatId)
 {
     using (MessengerDbContext context = contextFactory.Create())
     {
         return(ChatConverter.GetChatVm(await context.Chats
                                        .AsNoTracking()
                                        .Include(chat => chat.ChatUsers)
                                        .FirstOrDefaultAsync(chat => chat.Id == chatId)
                                        .ConfigureAwait(false)));
     }
 }
Exemple #4
0
        public async Task <ChatVm> CreateChatAsync(ChatVm chatVm, long userId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                List <ChatUser> chatUsers = new List <ChatUser>();
                using (var transaction = await context.Database.BeginTransactionAsync().ConfigureAwait(false))
                {
                    if (chatVm.Users != null && await loadUsersService.IsUserBlacklisted(userId, chatVm.Users.Select(opt => opt.UserId)).ConfigureAwait(false))
                    {
                        throw new UserBlockedException();
                    }
                    Chat newChat = ChatConverter.GetChat(chatVm);
                    newChat.Tag = RandomExtensions.NextString(10, "QWERTYUIOPASDFGHJKLZXCVBNM1234567890");
                    newChat.Id  = await poolsService.GetChatIdAsync().ConfigureAwait(false);

                    if (chatVm.Users != null)
                    {
                        chatUsers.AddRange(chatVm.Users.Where(opt => opt.UserId != userId).Select(chatUser => new ChatUser
                        {
                            Banned    = chatUser.Banned.GetValueOrDefault(false),
                            Deleted   = chatUser.Deleted.GetValueOrDefault(false),
                            Joined    = DateTime.UtcNow.ToUnixTime(),
                            UserId    = chatUser.UserId,
                            UserRole  = chatUser.UserRole.GetValueOrDefault(UserRole.User),
                            InviterId = userId
                        }));
                    }
                    if (!chatUsers.Any(opt => opt.UserId == userId))
                    {
                        chatUsers.Add(new ChatUser
                        {
                            Banned   = false,
                            Deleted  = false,
                            Joined   = DateTime.UtcNow.ToUnixTime(),
                            UserId   = userId,
                            UserRole = UserRole.Creator
                        });
                    }
                    newChat.ChatUsers = chatUsers;
                    IEnumerable <UserVm> users = await loadUsersService.GetUsersByIdAsync(chatUsers.Select(chatUser => chatUser.UserId)).ConfigureAwait(false);

                    IEnumerable <long> nodesId = users.Select(user => user.NodeId ?? 0).Distinct();
                    newChat.NodesId = nodesId.ToArray();
                    await context.Chats.AddAsync(newChat).ConfigureAwait(false);

                    await context.SaveChangesAsync().ConfigureAwait(false);

                    transaction.Commit();
                    newChat.ChatUsers = chatUsers;
                    return(ChatConverter.GetChatVm(newChat));
                }
            }
        }
Exemple #5
0
        public async Task <ChatVm> AddUsersToChatAsync(IEnumerable <long> usersId, long chatId, long userId)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                using (var transaction = await context.Database.BeginTransactionAsync().ConfigureAwait(false))
                {
                    Chat chat = await context.Chats.FirstOrDefaultAsync(opt => opt.Id == chatId).ConfigureAwait(false);

                    if (chat == null)
                    {
                        throw new ConversationNotFoundException(chatId);
                    }
                    User requestingUser = await context.Users.FindAsync(userId).ConfigureAwait(false);

                    if (requestingUser == null || requestingUser.Deleted)
                    {
                        throw new AddUserChatException();
                    }
                    ChatUser chatUser = await context.ChatUsers
                                        .FirstOrDefaultAsync(opt => opt.ChatId == chatId && opt.UserId == userId).ConfigureAwait(false);

                    List <ChatUserVm> addedUsers = new List <ChatUserVm>();
                    if (chat.Deleted)
                    {
                        throw new ConversationIsNotValidException();
                    }
                    if (chatUser != null && chatUser.Banned)
                    {
                        throw new ChatUserBlockedException();
                    }
                    if (usersId.Count() == 1 && usersId.FirstOrDefault() == userId)
                    {
                        if (chat.Type == (int)ChatType.Private)
                        {
                            throw new AddUserChatException();
                        }
                        if (chatUser == null)
                        {
                            chatUser = ChatUserConverter.GetNewChatUser(chatId, userId, null);
                            await context.AddAsync(chatUser).ConfigureAwait(false);
                        }
                        else if (chatUser.Deleted)
                        {
                            chatUser.Deleted = false;
                            chatUser.User    = requestingUser;
                            context.Update(chatUser);
                        }
                        if (!chat.NodesId.Contains(NodeSettings.Configs.Node.Id))
                        {
                            createMessagesService.DownloadMessageHistoryAsync(chat.NodesId.FirstOrDefault(), chat.Id, ConversationType.Chat, null, false);
                        }
                        chat.NodesId = chat.NodesId.Append(requestingUser.NodeId.Value).Distinct().ToArray();
                        addedUsers.Add(ChatUserConverter.GetChatUserVm(chatUser));
                    }
                    else
                    {
                        if ((chatUser?.Deleted).GetValueOrDefault(true))
                        {
                            throw new AddUserChatException();
                        }

                        if (await loadUsersService.IsUserBlacklisted(userId, usersId).ConfigureAwait(false))
                        {
                            throw new UserBlockedException();
                        }

                        ExpressionStarter <User> usersCondition = PredicateBuilder.New <User>();
                        usersCondition = usersId.Aggregate(usersCondition,
                                                           (current, value) => current.Or(opt => opt.Id == value).Expand());
                        List <User> existingUsers = await context.Users
                                                    .AsNoTracking()
                                                    .Where(usersCondition)
                                                    .ToListAsync()
                                                    .ConfigureAwait(false);

                        ExpressionStarter <ChatUser> chatUsersCondition = PredicateBuilder.New <ChatUser>();
                        chatUsersCondition = existingUsers.Select(opt => opt.Id).Aggregate(chatUsersCondition,
                                                                                           (current, value) => current.Or(opt => opt.UserId == value && opt.ChatId == chatId).Expand());
                        List <ChatUser> validChatUsers = await context.ChatUsers
                                                         .Where(chatUsersCondition)
                                                         .Include(opt => opt.User)
                                                         .ToListAsync()
                                                         .ConfigureAwait(false);

                        foreach (ChatUser user in validChatUsers)
                        {
                            if (!user.Banned && user.Deleted)
                            {
                                user.Deleted = false;
                                addedUsers.Add(ChatUserConverter.GetChatUserVm(user));
                            }
                        }
                        context.UpdateRange(validChatUsers);
                        List <long>     newChatUsersId = existingUsers.Select(opt => opt.Id).Except(validChatUsers.Select(opt => opt.UserId)).ToList();
                        List <ChatUser> newChatUsers   = newChatUsersId.Select(id => ChatUserConverter.GetNewChatUser(chatId, id, userId)).ToList();
                        chat.NodesId = chat.NodesId?.Concat(existingUsers.Select(opt => opt.NodeId.GetValueOrDefault())).Distinct().ToArray()
                                       ?? existingUsers.Select(opt => opt.NodeId.GetValueOrDefault()).Distinct().ToArray();
                        await context.ChatUsers
                        .AddRangeAsync(newChatUsers)
                        .ConfigureAwait(false);

                        /* foreach (ChatUser user in newChatUsers)
                         * {
                         *   user.User = existingUsers.FirstOrDefault(opt => opt.Id == user.UserId);
                         * }*/
                        addedUsers.AddRange(ChatUserConverter.GetChatUsersVm(newChatUsers));
                    }
                    context.Update(chat);
                    transaction.Commit();
                    await context.SaveChangesAsync()
                    .ConfigureAwait(false);

                    ChatVm resultChat = ChatConverter.GetChatVm(chat);
                    resultChat.Users = addedUsers;
                    return(resultChat);
                }
            }
        }