public async Task RemoveUsersFromGroupsAsync(List <long> usersId, Guid groupId, long userId) { using (MessengerDbContext context = contextFactory.Create()) { var contactsCondition = PredicateBuilder.New <Contact>(); contactsCondition = usersId.Aggregate(contactsCondition, (current, value) => current.Or(opt => opt.ContactUserId == value).Expand()); var contacts = await context.Contacts .Where(opt => opt.UserId == userId) .Where(contactsCondition) .ToListAsync() .ConfigureAwait(false); var group = await context.Groups.FirstOrDefaultAsync(opt => opt.GroupId == groupId && opt.UserId == userId).ConfigureAwait(false); if (contacts.Count < usersId.Count || group == null) { throw new ObjectDoesNotExistsException(); } var contactGroups = await context.ContactsGroups .Where(opt => opt.GroupId == group.GroupId && contacts.Select(p => p.ContactId).Contains(opt.ContactId)) .ToListAsync() .ConfigureAwait(false); context.ContactsGroups.RemoveRange(contactGroups); await context.SaveChangesAsync().ConfigureAwait(false); } }
public async Task <List <UserVm> > FindUsersByStringQueryAsync(string stringQuery, long?navigationUserId = 0, bool?direction = true) { using (MessengerDbContext context = contextFactory.Create()) { ExpressionsHelper helper = new ExpressionsHelper(); var query = context.Users .Include(opt => opt.Emails) .Include(opt => opt.Phones) .Include(opt => opt.BlackList) .Where(opt => opt.NodeId == NodeSettings.Configs.Node.Id && opt.Deleted == false && !opt.Deleted && opt.Confirmed == true); if (direction.GetValueOrDefault()) { query = query.OrderBy(opt => opt.Id) .Where(opt => opt.Id > navigationUserId.GetValueOrDefault()); } else { query = query.OrderByDescending(opt => opt.Id) .Where(opt => opt.Id < navigationUserId.GetValueOrDefault()); } List <User> users = await query.Where(helper.GetUserExpression(stringQuery)) .ToListAsync().ConfigureAwait(false); return(UserConverter.GetUsersVm(users)); } }
public async Task <bool> IsEmailExistsAsync(string email) { using (MessengerDbContext context = contextFactory.Create()) { return(await context.Emails.AnyAsync(opt => opt.EmailAddress.ToLower() == email.ToLowerInvariant()).ConfigureAwait(false)); } }
public async Task <PendingMessageDto> AddUserPendingMessageAsync(long receiverId, object content, Guid?messageId) { PendingMessage pendingMessage = new PendingMessage { Content = ObjectSerializer.ObjectToJson(content), ExpiredAt = DateTime.UtcNow.AddDays(1).ToUnixTime(), ReceiverId = receiverId, MessageId = messageId, SentAt = DateTime.UtcNow.ToUnixTime() }; using (MessengerDbContext context = contextFactory.Create()) { await context.PendingMessages.AddAsync(pendingMessage).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); } return(new PendingMessageDto { Content = pendingMessage.Content, ExpiredAt = pendingMessage.ExpiredAt, Id = pendingMessage.Id, ReceiverId = pendingMessage.ReceiverId.Value, SentAt = pendingMessage.SentAt }); }
private async Task <bool> ValidateVoiceMessageAttachmentAsync(AttachmentVm attachment) { using (MessengerDbContext context = contextFactory.Create()) { if (attachment.Payload is string) { var existingFile = await context.FilesInfo .FirstOrDefaultAsync(file => file.Id == (string)attachment.Payload && file.Deleted == false).ConfigureAwait(false); return(existingFile?.Size <= 1024 * 1024 * 2); } else if (attachment.Payload is FileInfoVm fileInfo) { var existingFile = await context.FilesInfo .FirstOrDefaultAsync(file => file.Id == fileInfo.FileId && file.Deleted == false).ConfigureAwait(false); return(existingFile?.Size <= 1024 * 1024 * 2); } if (attachment.Payload is JObject jsonObject) { var fileMessage = jsonObject.ToObject <FileInfoVm>(); return(!string.IsNullOrEmpty(fileMessage.FileId) && fileMessage.Size.GetValueOrDefault() <= 1024 * 1024 * 2); } else { return(false); } } }
public async Task <List <ChannelDto> > CreateOrUpdateUserChannelsAsync(List <ChannelDto> channels) { using (MessengerDbContext context = contextFactory.Create()) { var channelsCondition = PredicateBuilder.New <Channel>(); channelsCondition = channels.Aggregate(channelsCondition, (current, value) => current.Or(opt => opt.ChannelId == value.ChannelId).Expand()); List <Channel> existingChannels = await context.Channels .Include(opt => opt.ChannelUsers) .Where(channelsCondition) .ToListAsync() .ConfigureAwait(false); for (int i = 0; i < existingChannels.Count; i++) { ChannelDto editedChannel = channels.FirstOrDefault(opt => opt.ChannelId == existingChannels[i].ChannelId); existingChannels[i] = ChannelConverter.GetChannel(existingChannels[i], editedChannel); if (!editedChannel.ChannelUsers.IsNullOrEmpty()) { existingChannels[i].ChannelUsers = ChannelConverter.GetChannelUsers(editedChannel.ChannelUsers).ToList(); } } context.UpdateRange(existingChannels); List <ChannelDto> nonExistingChannels = channels.Where(channelDto => !existingChannels.Any(channel => channelDto.ChannelId == channel.ChannelId))?.ToList(); List <Channel> newChannels = ChannelConverter.GetChannels(nonExistingChannels); await context.AddRangeAsync(newChannels).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); return(ChannelConverter.GetChannelsDto(newChannels.Concat(existingChannels))); } }
public async Task <List <ValuePair <UserDto, byte[]> > > GetPollVotedUsersAsync(Guid pollId, long conversationId, ConversationType conversationType, byte optionId, long?requestorId, int limit = 30, long navigationUserId = 0) { using (MessengerDbContext context = contextFactory.Create()) { var poll = await context.Polls.FirstOrDefaultAsync(opt => opt.PollId == pollId && opt.ConversationType == conversationType && opt.ConvertsationId == conversationId) .ConfigureAwait(false); if (requestorId.GetValueOrDefault() != poll.CreatorId && !poll.ResultsVisibility && !await conversationsService.IsUserInConversationAsync(conversationType, conversationId, requestorId.GetValueOrDefault()).ConfigureAwait(false)) { throw new PermissionDeniedException(); } List <PollOptionVote> votes = await context.PollsOptionsVotes .Include(opt => opt.User) .Include(opt => opt.User.Phones) .Include(opt => opt.User.Emails) .Include(opt => opt.User.BlackList) .Where(opt => opt.ConversationId == conversationId && opt.ConversationType == conversationType && opt.PollId == pollId && opt.OptionId == optionId && opt.UserId > navigationUserId) .OrderBy(opt => opt.UserId) .Take(limit) .ToListAsync() .ConfigureAwait(false); return(votes.Select(vote => new ValuePair <UserDto, byte[]>(UserConverter.GetUserDto(vote.User), vote.Sign)).ToList()); } }
public async Task <TokenVm> RefreshTokenPairAsync(long userId, string refreshToken) { using (MessengerDbContext context = contextFactory.Create()) { Token target = await context.Tokens .FirstOrDefaultAsync(token => token.RefreshToken == refreshToken && token.UserId == userId && !token.User.Deleted) .ConfigureAwait(false); if (target != null) { target.AccessToken = RandomExtensions.NextString(64); target.RefreshToken = RandomExtensions.NextString(64); target.AccessTokenExpirationTime = DateTime.UtcNow.AddHours(ACCESS_LIFETIME_HOUR).ToUnixTime(); target.RefreshTokenExpirationTime = DateTime.UtcNow.AddHours(REFRESH_LIFETIME_HOUR).ToUnixTime(); context.Tokens.Update(target); await context.SaveChangesAsync().ConfigureAwait(false); return(TokenConverter.GetTokenVm(target)); } else { throw new InvalidTokenException(); } } }
public async Task <List <TokenVm> > GetAllUsersTokensAsync(IEnumerable <long> usersId, bool requireDeviceToken = true) { var tokensCondition = PredicateBuilder.New <Token>(); if (requireDeviceToken) { tokensCondition = usersId.Aggregate(tokensCondition, (current, value) => current.Or(opt => opt.UserId == value && opt.DeviceTokenId != null && opt.AccessTokenExpirationTime > DateTime.UtcNow.ToUnixTime()).Expand()); } else { tokensCondition = usersId.Aggregate(tokensCondition, (current, value) => current.Or(opt => opt.UserId == value && opt.AccessTokenExpirationTime > DateTime.UtcNow.ToUnixTime()).Expand()); } using (MessengerDbContext context = contextFactory.Create()) { var tokens = await context.Tokens .AsNoTracking() .Where(tokensCondition) .ToListAsync() .ConfigureAwait(false); return(TokenConverter.GetTokensVm(tokens)); } }
public async Task <List <ChannelUserVm> > GetChannelUsersAsync(long channelId, long?navigationUserId, long?requestorId) { using (MessengerDbContext context = contextFactory.Create()) { if (navigationUserId == null) { navigationUserId = 0; } if (requestorId != null) { ChannelUser requestorChannelUser = await context.ChannelUsers .FirstOrDefaultAsync(opt => opt.ChannelUserRole >= ChannelUserRole.Administrator && opt.ChannelId == channelId && opt.UserId == requestorId) .ConfigureAwait(false); if (requestorChannelUser == null) { throw new PermissionDeniedException(); } } var channelUsers = await context.ChannelUsers .OrderByDescending(opt => opt.ChannelUserRole) .ThenBy(opt => opt.UserId) .Where(opt => opt.ChannelId == channelId && opt.UserId > navigationUserId && opt.Deleted == false) .ToListAsync() .ConfigureAwait(false); return(ChannelConverter.GetChannelUsers(channelUsers)); } }
public async Task <List <ChannelVm> > FindChannelsByStringQueryAsync(string searchQuery, long?navigationId, bool?direction = true) { ExpressionsHelper helper = new ExpressionsHelper(); var searchExpression = helper.GetChannelExpression(searchQuery); using (MessengerDbContext context = contextFactory.Create()) { var query = context.Channels .AsNoTracking() .Where(opt => !opt.Deleted) .Where(searchExpression); if (direction.GetValueOrDefault()) { query = query.OrderBy(opt => opt.ChannelId) .Where(opt => opt.ChannelId > navigationId.GetValueOrDefault()); } else { query = query.OrderByDescending(opt => opt.ChannelId) .Where(opt => opt.ChannelId < navigationId.GetValueOrDefault()); } var channels = await query.ToListAsync().ConfigureAwait(false); return(ChannelConverter.GetChannels(channels)); } }
public async Task <ChannelVm> EditChannelAsync(ChannelVm channel, long editorUserId) { using (MessengerDbContext context = contextFactory.Create()) { ChannelUser channelUser = await context.ChannelUsers .Include(opt => opt.Channel) .FirstOrDefaultAsync(opt => opt.ChannelId == channel.ChannelId && opt.UserId == editorUserId && opt.ChannelUserRole >= ChannelUserRole.Administrator) .ConfigureAwait(false); if (channelUser != null) { if (channelUser.ChannelUserRole == ChannelUserRole.Administrator && (channelUser.Banned || channelUser.Deleted)) { throw new PermissionDeniedException(); } channelUser.Channel = ChannelConverter.GetChannel(channelUser.Channel, channel); context.Update(channelUser.Channel); await context.SaveChangesAsync().ConfigureAwait(false); var editedChannel = ChannelConverter.GetChannel(channelUser.Channel); editedChannel.UserRole = channelUser.ChannelUserRole; editedChannel.SubscribersCount = await context.ChannelUsers.CountAsync(opt => opt.Deleted == false && opt.ChannelId == channel.ChannelId).ConfigureAwait(false); return(editedChannel); } throw new PermissionDeniedException(); } }
public async Task UpdateChannelLastReadedMessageAsync(MessageDto message, long userId) { try { using (MessengerDbContext context = contextFactory.Create()) { ChannelUser channelUser = await context.ChannelUsers.FirstOrDefaultAsync(opt => opt.ChannelId == message.ConversationId && opt.UserId == userId).ConfigureAwait(false); var oldMessage = await context.Messages .AsNoTracking() .FirstOrDefaultAsync(opt => opt.GlobalId == channelUser.LastReadedGlobalMessageId && opt.ChannelId == channelUser.ChannelId) .ConfigureAwait(false); if (oldMessage != null && oldMessage.SendingTime > message.SendingTime) { return; } channelUser.LastReadedGlobalMessageId = message.GlobalId; context.ChannelUsers.Update(channelUser); await context.SaveChangesAsync().ConfigureAwait(false); } } catch (Exception ex) { Logger.WriteLog(ex); } }
public async Task <QRCodeContent> CreateQRCodeAsync(long userId, long nodeId) { var sequence = RandomExtensions.NextBytes(192); string sequenceStr = Convert.ToBase64String(sequence); QRCode qrCode = new QRCode { UserId = userId, SequenceHash = GetSequenceHashSha512(sequenceStr) }; using (MessengerDbContext context = contextFactory.Create()) { bool isUserExists = await context.Users.AnyAsync(user => user.Id == userId).ConfigureAwait(false); if (!isUserExists) { throw new ObjectDoesNotExistsException($"User with Id: {userId} does not found."); } await context.QRCodes.AddAsync(qrCode).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); return(new QRCodeContent(qrCode.Id, qrCode.UserId, nodeId, sequenceStr)); } }
public async Task <FileInfoVm> SaveFileAsync(long?userId, string filename, string url, long fileSize, byte[] fileHash, string storageType, ImageMetadata imageMetadata = null) { using (MessengerDbContext context = contextFactory.Create()) { FileInfo newFile = new FileInfo { Id = RandomExtensions.NextString(64), FileName = filename, Url = url, UploaderId = userId, UploadDate = DateTime.UtcNow.ToUnixTime(), NodeId = NodeSettings.Configs.Node.Id, Size = fileSize, Hash = fileHash, Storage = storageType, NumericId = await poolsService.GetFileIdAsync().ConfigureAwait(false), ImageMetadata = imageMetadata }; await context.FilesInfo.AddAsync(newFile).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); return(FileInfoConverter.GetFileInfoVm(newFile, false)); } }
public async Task <ValuePair <TokenVm, string> > UserIdPasswordCreateTokenPairAsync(long userId, string password, string deviceTokenId) { byte[] passwordHash = CreateUsersService.GetSha512Hash(password); using (MessengerDbContext context = contextFactory.Create()) { User targetUser = await context.Users.FirstOrDefaultAsync(user => user.Id == userId && user.Sha512Password.SequenceEqual(passwordHash) && !user.Deleted) .ConfigureAwait(false); if (targetUser != null) { string accessToken = RandomExtensions.NextString(64); string refreshToken = RandomExtensions.NextString(64); Token tokenPair = new Token() { UserId = userId, AccessToken = accessToken, RefreshToken = refreshToken, AccessTokenExpirationTime = DateTime.UtcNow.AddHours(ACCESS_LIFETIME_HOUR).ToUnixTime(), RefreshTokenExpirationTime = DateTime.UtcNow.AddHours(REFRESH_LIFETIME_HOUR).ToUnixTime(), DeviceTokenId = deviceTokenId }; string newPassword = RandomExtensions.NextString(CreateUsersService.PASSWORD_LENGTH); targetUser.Sha512Password = CreateUsersService.GetSha512Hash(newPassword); context.Users.Update(targetUser); await context.Tokens.AddAsync(tokenPair).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); return(new ValuePair <TokenVm, string>(TokenConverter.GetTokenVm(tokenPair), newPassword)); } } throw new UserNotFoundException(); }
public async Task <List <ChannelDto> > CreateChannelsAsync(List <ChannelDto> channels) { if (channels == null || !channels.Any()) { return(channels); } var channelsCondition = PredicateBuilder.New <Channel>(); var resultChannels = new List <Channel>(); channelsCondition = channels.Aggregate(channelsCondition, (current, value) => current.Or(opt => opt.ChannelId == value.ChannelId).Expand()); using (MessengerDbContext context = contextFactory.Create()) { var existingChannels = await context.Channels.Where(channelsCondition).ToListAsync().ConfigureAwait(false); var nonExistingChannels = channels.Where(channel => !existingChannels.Any(exChannel => exChannel.ChannelId == channel.ChannelId)); resultChannels.AddRange(existingChannels); if (nonExistingChannels != null) { var newChannels = ChannelConverter.GetChannels(nonExistingChannels.ToList()); await context.Channels.AddRangeAsync(newChannels).ConfigureAwait(false); resultChannels.AddRange(newChannels); await context.SaveChangesAsync().ConfigureAwait(false); } return(ChannelConverter.GetChannelsDto(resultChannels)); } }
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(); } }
private async Task <List <MessageDto> > SaveChannelMessagesAsync(IEnumerable <MessageDto> messages) { using (MessengerDbContext context = contextFactory.Create()) { var messagesCondition = PredicateBuilder.New <Message>(); messagesCondition = messages.Aggregate(messagesCondition, (current, value) => current.Or(opt => opt.ChannelId == value.ConversationId && opt.GlobalId == value.GlobalId).Expand()); List <Message> existingMessages = await context.Messages.Where(messagesCondition).ToListAsync().ConfigureAwait(false); IEnumerable <MessageDto> nonExistingMessages = messages.Where(opt => !existingMessages.Any(p => p.GlobalId == opt.GlobalId && p.ChannelId == opt.ConversationId)); var newMessages = MessageConverter.GetMessages(nonExistingMessages); await context.AddRangeAsync(newMessages.OrderBy(opt => opt.SendingTime)).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); var groupedMessages = newMessages.GroupBy(opt => opt.ChannelId.GetValueOrDefault()); foreach (var group in groupedMessages) { var lastMessage = group.OrderByDescending(opt => opt.SendingTime).FirstOrDefault(); if (lastMessage != null) { ConversationsService.UpdateConversationLastMessageId(group.Key, ConversationType.Channel, lastMessage.GlobalId); } } return(messages.ToList()); } }
public async Task UpdateLastReadedMessageIdAsync(Guid messageId, long userId, long chatId) { try { using (MessengerDbContext context = contextFactory.Create()) { var targetChatUser = await context.ChatUsers .Where(chatUser => chatUser.ChatId == chatId && chatUser.UserId == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); var updatingMessage = await context.Messages.FirstOrDefaultAsync(opt => opt.ChatId == chatId && opt.GlobalId == messageId).ConfigureAwait(false); var oldMessage = await context.Messages.FirstOrDefaultAsync(opt => opt.ChatId == chatId && opt.GlobalId == targetChatUser.LastReadedGlobalMessageId).ConfigureAwait(false); if (oldMessage != null && oldMessage.SendingTime > updatingMessage.SendingTime) { return; } targetChatUser.LastReadedGlobalMessageId = messageId; context.Update(targetChatUser); await context.SaveChangesAsync().ConfigureAwait(false); } } catch (Exception ex) { Logger.WriteLog(ex); } }
public async Task <PollDto> GetPollAsync(Guid pollId, long conversationId, ConversationType conversationType) { using (MessengerDbContext context = contextFactory.Create()) { var poll = await context.Polls .Include(opt => opt.Options) .ThenInclude(opt => opt.PollOptionVotes) .FirstOrDefaultAsync(opt => opt.PollId == pollId && opt.ConvertsationId == conversationId && opt.ConversationType == conversationType) .ConfigureAwait(false); if (poll == null) { var nodeId = await conversationsService.GetConversationNodeIdAsync(conversationType, conversationId).ConfigureAwait(false); var connection = connectionsService.GetNodeConnection(nodeId); if (connection != null) { var loadedPoll = await nodeRequestSender.GetPollInformationAsync(conversationId, conversationType, pollId, connection).ConfigureAwait(false); loadedPoll = await SavePollAsync(loadedPoll).ConfigureAwait(false); return(loadedPoll); } } return(PollConverter.GetPollDto(poll)); } }
public async Task DeleteUserInformationAsync(long userId) { try { using (MessengerDbContext context = contextFactory.Create()) { User user = await context.Users .Include(opt => opt.Emails) .Include(opt => opt.Phones) .Include(opt => opt.Tokens) .FirstOrDefaultAsync(opt => opt.Id == userId) .ConfigureAwait(false); user.Phones = null; user.Emails = null; user.About = null; user.Birthday = null; user.City = null; user.Country = null; user.Sha512Password = null; user.Photo = null; user.NameSecond = null; user.NameFirst = "unknown"; user.Tokens = null; context.Update(user); await context.SaveChangesAsync().ConfigureAwait(false); } } catch (Exception ex) { Logger.WriteLog(ex); } }
public async Task <PendingMessageDto> AddNodePendingMessageAsync(long nodeId, object content, TimeSpan lifetime) { if (nodeId == NodeSettings.Configs?.Node?.Id) { return(null); } PendingMessage pendingMessage = new PendingMessage { Content = Convert.ToBase64String(ObjectSerializer.ObjectToByteArray(content)), ExpiredAt = DateTime.UtcNow.AddSeconds(lifetime.TotalSeconds).ToUnixTime(), NodeId = nodeId, SentAt = DateTime.UtcNow.ToUnixTime() }; using (MessengerDbContext context = contextFactory.Create()) { if (!await context.Nodes.AnyAsync(opt => opt.Id == nodeId).ConfigureAwait(false)) { return(null); } await context.PendingMessages.AddAsync(pendingMessage).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); } return(new PendingMessageDto { Content = pendingMessage.Content, ExpiredAt = pendingMessage.ExpiredAt, Id = pendingMessage.Id, NodeId = pendingMessage.NodeId, SentAt = pendingMessage.SentAt }); }
public async Task <string> AddNewOperationAsync(long nodeId, long userId) { using (MessengerDbContext context = contextFactory.Create()) { long currentTime = DateTime.UtcNow.ToUnixTime(); var uncomplededOperation = await context.ChangeUserNodeOperations .FirstOrDefaultAsync(opt => !opt.Completed && opt.UserId == userId && opt.ExpirationTime > currentTime).ConfigureAwait(false); if (uncomplededOperation != null) { context.Remove(uncomplededOperation); } ChangeUserNodeOperation operation = new ChangeUserNodeOperation { NodeId = nodeId, UserId = userId, OperationId = RandomExtensions.NextString(64), Completed = false, RequestTime = currentTime, ExpirationTime = currentTime + (long)TimeSpan.FromDays(1).TotalSeconds }; await context.AddAsync(operation).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); return(operation.OperationId); } }
private async Task <bool> ValidateMediaAttachment(AttachmentVm mediaAttachment) { using (MessengerDbContext context = contextFactory.Create()) { if (mediaAttachment.Payload is string) { return(await context.FilesInfo .AnyAsync(file => file.Id == (string)mediaAttachment.Payload && file.Deleted == false).ConfigureAwait(false)); } else if (mediaAttachment.Payload is FileInfoVm fileInfo) { return(await context.FilesInfo .AnyAsync(file => file.Id == fileInfo.FileId && file.Deleted == false).ConfigureAwait(false)); } if (mediaAttachment.Payload is JObject jsonObject) { var fileMessage = jsonObject.ToObject <FileInfoVm>(); return(!string.IsNullOrEmpty(fileMessage.FileId)); } else { return(false); } } }
public async Task <List <FileInfoVm> > GetFilesInfoAsync(DateTime navigationTime, long?uploaderId = null, int limit = 100) { using (MessengerDbContext context = contextFactory.Create()) { IQueryable <FileInfo> query; if (uploaderId == null) { query = from file in context.FilesInfo .Where(fileInfo => fileInfo.Deleted == false) select file; } else { query = from file in context.FilesInfo .Where(fileInfo => fileInfo.Deleted == false) where file.UploaderId == uploaderId select file; } List <FileInfo> filesInfo = await query .AsNoTracking() .Take(limit) .OrderBy(file => file.UploadDate) .Where(file => file.UploadDate >= navigationTime.ToUnixTime()) .ToListAsync() .ConfigureAwait(false); return(FileInfoConverter.GetFilesInfoVm(filesInfo, uploaderId != null)); } }
public async Task <bool> IsUserBlacklisted(long targetUserId, IEnumerable <long> usersId) { using (MessengerDbContext context = contextFactory.Create()) { ExpressionStarter <User> usersCondition = PredicateBuilder.New <User>(); usersCondition = usersId.Aggregate(usersCondition, (current, value) => current.Or(user => user.Id == value).Expand()); User targetUser = await context.Users .AsNoTracking() .Include(user => user.BlackList) .Include(user => user.ReverseBlackList) .FirstOrDefaultAsync(user => user.Id == targetUserId) .ConfigureAwait(false); foreach (long userId in usersId) { if (targetUser.ReverseBlackList.Any(opt => opt.Uid == userId) || targetUser.BlackList.Any(opt => opt.BadUid == userId)) { return(true); } } return(false); } }
public async Task <List <long> > DeleteFilesAsync(IEnumerable <string> filesId, long userId) { using (MessengerDbContext context = contextFactory.Create()) { var filesCondition = PredicateBuilder.New <FileInfo>(); filesCondition = filesId.Aggregate(filesCondition, (current, value) => current.Or(file => file.Id == value).Expand()); List <FileInfo> filesInfo = await context.FilesInfo .Where(filesCondition) .Where(file => file.UploaderId == userId && file.Deleted == false) .ToListAsync() .ConfigureAwait(false); if (filesInfo.Count < filesId.Count()) { throw new ObjectDoesNotExistsException(); } filesInfo.ForEach(fileInfo => fileInfo.Deleted = true); context.UpdateRange(filesInfo); await context.SaveChangesAsync().ConfigureAwait(false); return(filesInfo.Select(file => file.NumericId).ToList()); } }
public async Task <bool> IsPhoneExistsAsync(string phone) { using (MessengerDbContext context = contextFactory.Create()) { return(await context.Phones.AnyAsync(opt => opt.PhoneNumber == phone).ConfigureAwait(false)); } }
public async Task <List <KeyVm> > AddNewUserKeysAsync(IEnumerable <KeyVm> keys, long userId) { try { using (MessengerDbContext context = contextFactory.Create()) { var publicKeys = KeyConverter.GetKeys(keys); publicKeys.ForEach(key => key.UserId = userId); await context.Keys.AddRangeAsync(publicKeys).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); return(KeyConverter.GetKeysVm(publicKeys)); } } catch (DbUpdateException ex) { if (ex.InnerException is PostgresException postgresException) { if (postgresException.ConstraintName == "IX_Keys_KeyId_UserId") { throw new ObjectAlreadyExistsException(); } } throw new Exception("Error while saving key", ex); } }