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 CreateOrEditChannel()
        {
            var editableChannel = fillTestDbHelper.Channels.FirstOrDefault();
            var validUser       = editableChannel.ChannelUsers.FirstOrDefault(channelUser => channelUser.ChannelUserRole >= ChannelUserRole.Administrator);
            var invalidUser     = editableChannel.ChannelUsers.FirstOrDefault(channelUser => channelUser.ChannelUserRole == ChannelUserRole.Subscriber);

            editableChannel.ChannelName = "Edited channel name";
            var actualChannel = await createChannelsService.CreateOrEditChannelAsync(ChannelConverter.GetChannel(editableChannel), validUser.UserId, null);

            Assert.True(editableChannel.ChannelName == actualChannel.ChannelName);
            await Assert.ThrowsAsync <PermissionDeniedException>(async() =>
                                                                 await createChannelsService.CreateOrEditChannelAsync(ChannelConverter.GetChannel(editableChannel), invalidUser.UserId, null));

            var users              = fillTestDbHelper.Users.Skip(1);
            var creator            = fillTestDbHelper.Users.FirstOrDefault();
            var newExpectedChannel = new ChannelVm
            {
                About        = RandomExtensions.NextString(10),
                ChannelName  = "Created channel",
                ChannelUsers = users.Select(user => new ChannelUserVm
                {
                    UserId          = user.Id,
                    ChannelUserRole = ChannelUserRole.Subscriber
                }).ToList()
            };
            var newActualChannel = await createChannelsService.CreateOrEditChannelAsync(newExpectedChannel, creator.Id, newExpectedChannel.ChannelUsers);

            Assert.True(newExpectedChannel.ChannelUsers.Count() + 1 == newActualChannel.ChannelUsers.Count());
        }
Esempio n. 3
0
 public ChannelNodeNotice(ChannelVm channel, long requestorId, IEnumerable <ChannelUserVm> subscribers)
 {
     Channel     = channel;
     Subscribers = subscribers?.ToList();
     RequestorId = requestorId;
     NoticeCode  = Enums.NodeNoticeCode.Channels;
 }
        public async Task <Response> CreateResponseAsync()
        {
            try
            {
                ChannelVm editableChannel = await loadChannelsService.GetChannelByIdAsync(request.Channel.ChannelId.Value);

                ChannelVm channel = await updateChannelsService.EditChannelAsync(request.Channel, clientConnection.UserId.GetValueOrDefault()).ConfigureAwait(false);

                if (editableChannel.ChannelName != channel.ChannelName)
                {
                    var systemMessageInfo = SystemMessageInfoFactory.CreateNameChangedMessageInfo(editableChannel.ChannelName, channel.ChannelName);
                    var message           = await systemMessagesService.CreateMessageAsync(ObjectsLibrary.Enums.ConversationType.Channel, channel.ChannelId.Value, systemMessageInfo);

                    conversationsNoticeService.SendSystemMessageNoticeAsync(message);
                }
                IEnumerable <long> usersId = await loadChannelsService.GetChannelUsersIdAsync(channel.ChannelId.GetValueOrDefault()).ConfigureAwait(false);

                conversationsNoticeService.SendChannelNoticeAsync(channel, usersId.ToList(), clientConnection);
                UsersConversationsCacheService.Instance.UpdateUsersChannelsAsync(usersId.ToList());
                nodeNoticeService.SendChannelNodeNoticeAsync(channel, clientConnection.UserId.GetValueOrDefault(), null);
                BlockSegmentVm segment = await BlockSegmentsService.Instance.CreateChannelSegmentAsync(channel, NodeSettings.Configs.Node.Id).ConfigureAwait(false);

                BlockGenerationHelper.Instance.AddSegment(segment);
                return(new ChannelsResponse(request.RequestId, channel));
            }
            catch (PermissionDeniedException ex)
            {
                Logger.WriteLog(ex, request);
                return(new ResultResponse(request.RequestId, "Channel not found or user does not have access to the channel.", ObjectsLibrary.Enums.ErrorCode.PermissionDenied));
            }
        }
Esempio n. 5
0
        public async Task <Response> CreateResponseAsync()
        {
            try
            {
                request.Channel.ChannelId = null;
                request.Channel.Tag       = null;
                ChannelVm channel = await createChannelsService.CreateChannelAsync(request.Channel, clientConnection.UserId.GetValueOrDefault(), request.Subscribers).ConfigureAwait(false);

                List <long> usersId = await loadChannelsService.GetChannelUsersIdAsync(channel.ChannelId.GetValueOrDefault()).ConfigureAwait(false);

                conversationsNoticeService.SendChannelNoticeAsync(channel, usersId, clientConnection);
                UsersConversationsCacheService.Instance.UpdateUsersChannelsAsync(usersId);
                nodeNoticeService.SendChannelNodeNoticeAsync(channel, clientConnection.UserId.Value, request.Subscribers);
                BlockSegmentVm segment = await BlockSegmentsService.Instance.CreateChannelSegmentAsync(channel, NodeSettings.Configs.Node.Id).ConfigureAwait(false);

                BlockGenerationHelper.Instance.AddSegment(segment);
                return(new ChannelsResponse(request.RequestId, channel));
            }
            catch (UserNotFoundException ex)
            {
                Logger.WriteLog(ex, request);
                return(new ResultResponse(request.RequestId, "Users not found.", ErrorCode.ObjectDoesNotExists));
            }
            catch (UserBlockedException ex)
            {
                Logger.WriteLog(ex, request);
                return(new ResultResponse(request.RequestId, "The user is blacklisted by another user.", ErrorCode.UserBlocked));
            }
        }
Esempio n. 6
0
 public static Channel GetChannel(Channel editable, ChannelVm edited)
 {
     editable.ChannelName = edited.ChannelName ?? editable.ChannelName;
     editable.About       = edited.About ?? editable.About;
     editable.Photo       = edited.Photo ?? editable.Photo;
     editable.Deleted     = edited.Deleted.GetValueOrDefault(editable.Deleted);
     return(editable);
 }
Esempio n. 7
0
 public static Channel GetChannel(ChannelVm channel)
 {
     return(new Channel
     {
         About = channel.About,
         ChannelId = channel.ChannelId.GetValueOrDefault(),
         ChannelName = channel.ChannelName,
         Photo = channel.Photo,
         Tag = channel.Tag
     });
 }
        public async Task <ChannelVm> CreateChannelAsync(ChannelVm channel, long creatorId, IEnumerable <ChannelUserVm> subscribers)
        {
            ChannelUser channelUser = new ChannelUser
            {
                ChannelUserRole = ChannelUserRole.Creator,
                SubscribedTime  = DateTime.UtcNow.ToUnixTime(),
                UserId          = creatorId,
                Deleted         = false
            };

            if (subscribers != null && await loadUsersService.IsUserBlacklisted(creatorId, subscribers.Select(opt => opt.UserId)).ConfigureAwait(false))
            {
                throw new UserBlockedException();
            }

            List <ChannelUser> channelUsers = new List <ChannelUser>()
            {
                channelUser
            };

            if (subscribers != null)
            {
                channelUsers.AddRange(ChannelConverter.GetChannelUsers(subscribers.Where(opt => opt.UserId != creatorId)));
            }
            List <UserVm> users = await loadUsersService.GetUsersByIdAsync(channelUsers.Select(opt => opt.UserId)).ConfigureAwait(false);

            if (users.Count() < channelUsers.Count())
            {
                throw new UserNotFoundException();
            }
            Channel newChannel = new Channel
            {
                ChannelId    = channel.ChannelId.GetValueOrDefault(await poolsService.GetChannelIdAsync().ConfigureAwait(false)),
                About        = channel.About,
                Deleted      = false,
                ChannelName  = channel.ChannelName,
                CreationTime = DateTime.UtcNow.ToUnixTime(),
                Photo        = channel.Photo,
                Tag          = string.IsNullOrWhiteSpace(channel.Tag) ? RandomExtensions.NextString(10, "QWERTYUIOPASDFGHJKLZXCVBNM1234567890") : channel.Tag,
                NodesId      = users.Select(opt => opt.NodeId.GetValueOrDefault()).Distinct().ToArray()
            };

            using (MessengerDbContext context = contextFactory.Create())
            {
                newChannel.ChannelUsers = channelUsers;
                var entityEntry = await context.Channels.AddAsync(newChannel).ConfigureAwait(false);

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

                var createdChannel = ChannelConverter.GetChannel(entityEntry.Entity);
                createdChannel.SubscribersCount = newChannel.ChannelUsers.Count();
                return(createdChannel);
            }
        }
Esempio n. 9
0
 public async void SendChannelNodeNoticeAsync(ChannelVm channel, long requestorId, IEnumerable <ChannelUserVm> subscribers)
 {
     try
     {
         ChannelNodeNotice notice = new ChannelNodeNotice(channel, requestorId, subscribers);
         await SendNoticeToNodesAsync(notice, channel.NodesId).ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         Logger.WriteLog(ex);
     }
 }
Esempio n. 10
0
        public async Task <MessageDto> CreateChannelMessageAsync(MessageDto message)
        {
            try
            {
                using (MessengerDbContext context = contextFactory.Create())
                {
                    ChannelUser senderChannelUser = await context.ChannelUsers
                                                    .Include(opt => opt.Channel)
                                                    .FirstOrDefaultAsync(opt =>
                                                                         opt.ChannelId == message.ConversationId &&
                                                                         opt.UserId == message.SenderId &&
                                                                         opt.ChannelUserRole >= ChannelUserRole.Administrator)
                                                    .ConfigureAwait(false);

                    if (senderChannelUser == null)
                    {
                        UserVm user = await LoadUsersService.GetUserAsync(message.SenderId.GetValueOrDefault()).ConfigureAwait(false);

                        if (user == null)
                        {
                            throw new UserNotFoundException(message.SenderId.GetValueOrDefault());
                        }
                        ChannelVm channel = await LoadChannelsService.GetChannelByIdAsync(message.ConversationId).ConfigureAwait(false);

                        if (channel == null)
                        {
                            throw new ConversationNotFoundException(message.ConversationId);
                        }
                        throw new PermissionDeniedException();
                    }
                    if (senderChannelUser.ChannelUserRole == ChannelUserRole.Administrator && (senderChannelUser.Banned || senderChannelUser.Deleted))
                    {
                        throw new PermissionDeniedException();
                    }
                    message.NodesIds = senderChannelUser.Channel.NodesId?.ToList();
                    SaveMessageAsync(message);
                    return(message);
                }
            }
            catch (PostgresException ex)
            {
                if (ex.ConstraintName == "FK_Messages_Channels_ChannelId")
                {
                    throw new ConversationNotFoundException(message.ConversationId);
                }
                else if (ex.ConstraintName == "Messages_SenderId_fkey")
                {
                    throw new UserNotFoundException(message.SenderId.GetValueOrDefault());
                }
                throw new MessageException("Database error.", ex);
            }
        }
Esempio n. 11
0
        public async Task CreateChannelWithoutSubs()
        {
            var user            = fillTestDbHelper.Users.FirstOrDefault();
            var expectedChannel = new ChannelVm
            {
                About       = RandomExtensions.NextString(10),
                ChannelName = "Created channel"
            };
            var actualChannel = await createChannelsService.CreateChannelAsync(expectedChannel, user.Id, null);

            Assert.True(expectedChannel.ChannelName == actualChannel.ChannelName &&
                        expectedChannel.About == actualChannel.About &&
                        actualChannel.ChannelUsers.Count == 1);
        }
        public async Task <ChannelVm> CreateOrEditChannelAsync(ChannelVm channel, long requestorId, IEnumerable <ChannelUserVm> subscribers)
        {
            using (MessengerDbContext context = contextFactory.Create())
            {
                bool isExistsChannel = await context.Channels.AnyAsync(opt => opt.ChannelId == channel.ChannelId).ConfigureAwait(false);

                if (isExistsChannel)
                {
                    return(await updateChannelsService.EditChannelAsync(channel, requestorId).ConfigureAwait(false));
                }
                else
                {
                    return(await CreateChannelAsync(channel, requestorId, subscribers).ConfigureAwait(false));
                }
            }
        }
        public async Task HandleAsync()
        {
            var editableChannel = await loadChannelsService.GetChannelByIdAsync(notice.Channel.ChannelId.Value).ConfigureAwait(false);

            ChannelVm channel = await createChannelsService.CreateOrEditChannelAsync(notice.Channel, notice.RequestorId, notice.Subscribers).ConfigureAwait(false);

            if (editableChannel?.ChannelName == channel.ChannelName)
            {
                var systemMessageInfo = SystemMessageInfoFactory.CreateNameChangedMessageInfo(editableChannel.ChannelName, channel.ChannelName);
                var message           = await systemMessagesService.CreateMessageAsync(ObjectsLibrary.Enums.ConversationType.Channel, channel.ChannelId.Value, systemMessageInfo);

                conversationsNoticeService.SendSystemMessageNoticeAsync(message);
            }
            IEnumerable <long> usersId = await loadChannelsService.GetChannelUsersIdAsync(channel.ChannelId.GetValueOrDefault()).ConfigureAwait(false);

            conversationsNoticeService.SendChannelNoticeAsync(channel, usersId.ToList());
        }
        public async Task <Response> CreateResponseAsync()
        {
            List <ChannelUserVm>  resultChannelsUsers = new List <ChannelUserVm>();
            List <BlockSegmentVm> segments            = new List <BlockSegmentVm>();

            foreach (long channelId in request.ChannelsId)
            {
                try
                {
                    ChannelVm channel = await loadChannelsService.GetChannelByIdAsync(channelId).ConfigureAwait(false);

                    var existingUsers = await loadChannelsService.GetChannelUsersAsync(channelId, null, null).ConfigureAwait(false);

                    if (!existingUsers.Any(opt => opt.ChannelUserRole == ChannelUserRole.Creator))
                    {
                        var nodeConnection = connectionsService.GetNodeConnection(channel.NodesId.FirstOrDefault(id => id != NodeSettings.Configs.Node.Id));
                        if (nodeConnection != null)
                        {
                            await nodeRequestSender.GetChannelInformationAsync(channelId, nodeConnection).ConfigureAwait(false);
                        }
                    }
                    List <ChannelUserVm> channelUsers =
                        await updateChannelsService.AddUsersToChannelAsync(request.UsersId.ToList(), channelId, clientConnection.UserId.GetValueOrDefault()).ConfigureAwait(false);

                    resultChannelsUsers.AddRange(channelUsers);
                    BlockSegmentVm segment = await BlockSegmentsService.Instance.CreateChannelUsersSegmentAsync(
                        channelUsers,
                        NodeSettings.Configs.Node.Id,
                        channelId,
                        NodeData.Instance.NodeKeys.SignPrivateKey,
                        NodeData.Instance.NodeKeys.SymmetricKey,
                        NodeData.Instance.NodeKeys.Password,
                        NodeData.Instance.NodeKeys.KeyId).ConfigureAwait(false);

                    segments.Add(segment);
                    conversationsNoticeService.SendNewChannelNoticesAsync(channelUsers, channelId, clientConnection);
                    nodeNoticeService.SendChannelUsersNodeNoticeAsync(channelUsers, clientConnection.UserId.Value, channel);
                }
                catch (Exception ex)
                {
                    Logger.WriteLog(ex, request);
                }
            }
            BlockGenerationHelper.Instance.AddSegments(segments);
            return(new ChannelUsersResponse(request.RequestId, null, resultChannelsUsers, null));
        }
Esempio n. 15
0
        public static ChannelDto GetChannelDto(ChannelVm channelVm)
        {
            if (channelVm == null)
            {
                return(null);
            }

            return(new ChannelDto
            {
                About = channelVm.About,
                ChannelId = channelVm.ChannelId.GetValueOrDefault(),
                Photo = channelVm.Photo,
                Tag = channelVm.Tag,
                NodesId = channelVm.NodesId?.ToArray(),
                ChannelName = channelVm.ChannelName,
                ChannelUsers = channelVm.ChannelUsers?.Select(channelUser => GetChannelUserDto(channelUser)).ToList()
            });
        }
Esempio n. 16
0
        public async Task CreateChannelWithSubs()
        {
            var users           = fillTestDbHelper.Users.Skip(1);
            var creator         = fillTestDbHelper.Users.FirstOrDefault();
            var expectedChannel = new ChannelVm
            {
                About        = RandomExtensions.NextString(10),
                ChannelName  = "Created channel",
                Tag          = "TAGTAGTAG",
                NodesId      = RandomExtensions.GetRandomInt64Sequence(3, 0).ToList(),
                ChannelUsers = users.Select(user => new ChannelUserVm
                {
                    UserId          = user.Id,
                    ChannelUserRole = ChannelUserRole.Subscriber
                }).ToList()
            };
            var actualChannel = await createChannelsService.CreateChannelAsync(expectedChannel, creator.Id, expectedChannel.ChannelUsers);

            Assert.True(expectedChannel.ChannelUsers.Count() + 1 == actualChannel.ChannelUsers.Count());
        }
        public async void SendNewChannelNoticesAsync(IEnumerable <ChannelUserVm> channelUsers, long channelId, ClientConnection clientConnection)
        {
            try
            {
                ChannelVm channel = await loadChannelsService.GetChannelByIdAsync(channelId).ConfigureAwait(false);

                ChannelNotice notice = new ChannelNotice(channel);
                foreach (var channelUser in channelUsers)
                {
                    var clientConnections = connectionsService.GetUserClientConnections(channelUser.UserId);
                    if (clientConnections != null)
                    {
                        await SendNoticeToClientsAsync(clientConnections.Where(opt => opt != clientConnection), notice).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
Esempio n. 18
0
        public async Task <Response> CreateResponseAsync()
        {
            try
            {
                List <ChannelUserVm> editedChannelUsers = await updateChannelsService.EditChannelUsersAsync(
                    request.Users, clientConnection.UserId.GetValueOrDefault(), request.ChannelId).ConfigureAwait(false);

                ChannelVm channel = await loadChannelsService.GetChannelByIdAsync(request.ChannelId).ConfigureAwait(false);

                nodeNoticeService.SendChannelUsersNodeNoticeAsync(editedChannelUsers, clientConnection.UserId.GetValueOrDefault(), channel);
                UsersConversationsCacheService.Instance.UpdateUsersChannelsAsync(editedChannelUsers.Select(opt => opt.UserId));
                BlockSegmentVm segment = await BlockSegmentsService.Instance.CreateChannelUsersSegmentAsync(
                    editedChannelUsers,
                    NodeSettings.Configs.Node.Id,
                    request.ChannelId,
                    NodeData.Instance.NodeKeys.SignPrivateKey,
                    NodeData.Instance.NodeKeys.SymmetricKey,
                    NodeData.Instance.NodeKeys.Password,
                    NodeData.Instance.NodeKeys.KeyId).ConfigureAwait(false);

                nodeNoticeService.SendBlockSegmentsNodeNoticeAsync(new List <BlockSegmentVm> {
                    segment
                });
                BlockGenerationHelper.Instance.AddSegment(segment);
                return(new ChannelUsersResponse(
                           request.RequestId,
                           editedChannelUsers.Where(opt => opt.ChannelUserRole.GetValueOrDefault() >= ChannelUserRole.Administrator && opt.Banned == false),
                           editedChannelUsers.Where(opt => opt.ChannelUserRole.GetValueOrDefault() == ChannelUserRole.Subscriber && opt.Banned == false),
                           editedChannelUsers.Where(opt => opt.Banned == true)));
            }
            catch (PermissionDeniedException ex)
            {
                Logger.WriteLog(ex);
                return(new ResultResponse(request.RequestId, "Channel not found or user does not have access to the channel.", ErrorCode.PermissionDenied));
            }
        }
 public async void SendChannelNoticeAsync(ChannelVm channel, List <long> usersId, ClientConnection clientConnection = null)
 {
     try
     {
         List <ClientConnection> clientsConnections = new List <ClientConnection>();
         foreach (long userId in usersId)
         {
             var clientConnections = connectionsService.GetUserClientConnections(userId);
             if (clientConnections != null)
             {
                 clientsConnections.AddRange(clientConnections.Where(opt => opt != clientConnection));
             }
         }
         ChannelVm channelClone = (ChannelVm)channel.Clone();
         channelClone.ChannelUsers = null;
         channelClone.UserRole     = null;
         ChannelNotice notice = new ChannelNotice(channelClone);
         await SendNoticeToClientsAsync(clientsConnections, notice).ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         Logger.WriteLog(ex);
     }
 }
Esempio n. 20
0
 public async void SendChannelUsersNodeNoticeAsync(IEnumerable <ChannelUserVm> channelUsers, long requestorId, ChannelVm channel)
 {
     try
     {
         ChannelUsersNodeNotice notice = new ChannelUsersNodeNotice(channelUsers, requestorId, channel.ChannelId.GetValueOrDefault());
         await SendNoticeToNodesAsync(notice).ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         Logger.WriteLog(ex);
     }
 }