예제 #1
0
        public IResult Add(ChannelDto channelDto)
        {
            var userExist = _userService.GetById(channelDto.UserId);

            if (userExist == null)
            {
                return(new ErrorResult("Invalid user"));
            }

            var channel = new Channel
            {
                Name     = channelDto.Name,
                Verified = false,
                UserId   = channelDto.UserId
            };

            if (!_channelDal.Add(channel))
            {
                return(new ErrorResult("Channel cannot created!"));
            }

            channel.Slug = channel.Id.ToString();
            _channelDal.Update(channel);

            return(new SuccessResult("Channel created."));
        }
        public async Task <IEnumerable <ChannelDto> > GetChannels(bool isFastRun, CancellationToken cancellationToken)
        {
            var channelsList = new List <ChannelDto>();

            using (Browser browser = await _browserFactory.Create())
            {
                using Page page = await browser.NewPageAsync();
                await Login(page);

                IEnumerable <string> channelUrls = await GetChannelUrls(page);

                if (isFastRun)
                {
                    channelUrls = channelUrls.Take(1);
                }

                foreach (string url in channelUrls.TakeWhile(url => !cancellationToken.IsCancellationRequested))
                {
                    ChannelDto channel = await GetChannelDetails(page, url);

                    channelsList.Add(channel);
                }
            }

            return(channelsList);
        }
예제 #3
0
        public bool Handle(NewChannelRequest request, IOutputPort <NewChannelResponse> outputPort)
        {
            if (_userRepository.FindById(request.UserId) == null)
            {
                outputPort.Handle(new NewChannelResponse(new[] { new Error(404, "user not found") }));
                return(false);
            }
            if (_channelRepository.FindByUserId(request.UserId) != null)
            {
                outputPort.Handle(new NewChannelResponse(new[] { new Error(422, "user already have channel") }));
                return(false);
            }
            if (_channelRepository.FindByName(request.Name) != null)
            {
                outputPort.Handle(new NewChannelResponse(new[] { new Error(422, "channel name is busy") }));
                return(false);
            }
            var channelInfo = new ChannelDto()
            {
                UserId           = request.UserId,
                RegistrationDate = request.RegistrationDate,
                Description      = request.Description,
                Name             = request.Name,
            };
            ChannelDto createdChannel = _channelRepository.Create(channelInfo);

            outputPort.Handle(new NewChannelResponse(createdChannel));
            return(true);
        }
예제 #4
0
 public ChannelBuilder(AsUserBuilder builder, ChannelDto channel)
 {
     _builder            = builder;
     _channel            = channel;
     _group              = _builder._builder._group;
     _groupsModuleFacade = _builder._facade;
 }
예제 #5
0
        public async Task <long> CreateAsync(ChannelDto channel, CancellationToken cancellation = default)
        {
            var entity = Mapper.Map <ChannelDto, Channel>(channel);
            var result = await _channelStorage.CreateAsync(entity, cancellation);

            return(result.Id);
        }
        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)));
            }
        }
예제 #7
0
        /// <summary>
        /// 检查通道信息
        /// </summary>
        /// <param name="brandChannelDto"></param>
        /// <param name="channelDto"></param>
        /// <param name="retMsg"></param>
        /// <returns></returns>
        public bool CheckChannel(long id, out ChannelDto channelDto, out string retMsg)
        {
            var val = _pushChannelService;

            retMsg     = "";
            channelDto = CourseCacheLogic <string, ChannelDto> .Get("Channel_" + id,
                                                                    () =>
            {
                PushChannelDomainModel pushChannel = _pushChannelService.GetChannelByIdAsync(id).Result;
                return(_mapper.Map <ChannelDto>(pushChannel));
            });

            if (channelDto == null)
            {
                retMsg = string.Format("ChannelId:{0},未匹配到Push_Channel", id);
                return(false);
            }
            //通道是否有效
            if (!channelDto.IsActive)
            {
                retMsg = string.Format("ChannelId:{0},通道{1}状态无效", channelDto.Id, channelDto.ChannelName);
                return(false);
            }
            return(true);
        }
예제 #8
0
        public void BindChannelInfo(ChannelDto channelDto, ChannelChangeEventHandler onChangeChannelInfoHandler)
        {
            _onChangeChannelInfoHandler = onChangeChannelInfoHandler;
            _lastLineId = channelDto.Id;

            ShowDto(channelDto);
        }
예제 #9
0
 private async Task SaveIfDoesNotExist(ChannelDto channelDto)
 {
     if (!_channelApplicationService.Exists(channelDto))
     {
         await _channelApplicationService.Create(channelDto);
     }
 }
        public IActionResult Add([FromBody] ChannelDto channelDto)
        {
            var result = _channelService.Add(channelDto);

            return(result.Success
                ? Ok(result.Message)
                : BadRequest(result.Message));
        }
예제 #11
0
        public async Task <ActionResult <ChannelWithIdDto> > Add([FromBody] ChannelDto channelDto)
        {
            var channel = _mapper.Map <Channel>(channelDto);

            var addedChannel = await _channelRepository.AddAsync(channel);

            return(Ok(_mapper.Map <ChannelWithIdDto>(addedChannel)));
        }
예제 #12
0
        public void given_channel_created()
        {
            ChannelDto dto = CreateChannelDto(FOO_CHANNEL_NAME_CREATED);

            _channelsToReplicate = new List <ChannelDto>(_channelsToReplicate)
            {
                dto
            };
        }
예제 #13
0
 public Channel(ChannelDto channel)
 {
     this.id        = channel.id;
     this.name      = channel.name;
     this.adminId   = channel.adminId;
     this.guid      = channel.guid;
     this.isPrivate = channel.isPrivate;
     this.usersId   = channel.usersId.Split("|".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries).Select(userId => int.Parse(userId));
 }
        public bool Handle(SearchRequest request, IOutputPort <SearchResponse> outputPort)
        {
            IEnumerable <VideoDto> videos  = _videoRepository.FindByName(request.SearchQuery);
            ChannelDto             channel = _channelRepository.FindByName(request.SearchQuery);

            outputPort.Handle(new SearchResponse(videos, channel));

            return(true);
        }
예제 #15
0
        public ChannelDto Create(ChannelDto channelInfo)
        {
            var channel = _mapper.Map <Channel>(channelInfo);

            _database.Channels.Add(channel);
            _database.SaveChanges();

            return(_mapper.Map <ChannelDto>(channel));
        }
예제 #16
0
        public async Task LeaveChannel(ChannelDto channelDto)
        {
            channelDto.Id = Context.ConnectionId;
            ChannelHandler.ChannelDictionary.Remove(channelDto.Id);
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, channelDto.ChannelName);

            await Clients.OthersInGroup(channelDto.Id).UserLeftChannel(channelDto);

            await Clients.Others.UsersInGroup(ChannelHandler.NumberOfUsersInChannel(channelDto.ChannelName));
        }
        private ReplicateResult Replicate(ChannelDto channelDto)
        {
            var newChannel = new Channel(channelDto, _entityFactory);

            LookUpCourses(ref newChannel);

            _db.Channels.Add(newChannel);

            return(ReplicateResult.BuildChannelCreated(newChannel.Name));
        }
예제 #18
0
        public async Task JoinChannel(ChannelDto channelDto)
        {
            channelDto.Id = Context.ConnectionId;
            ChannelHandler.ChannelDictionary.Add(channelDto.Id, channelDto.ChannelName);
            await Groups.AddToGroupAsync(Context.ConnectionId, channelDto.ChannelName);

            await Clients.OthersInGroup(channelDto.ChannelName).UserJoinedChannel(channelDto);

            await Clients.Others.UsersInGroup(ChannelHandler.NumberOfUsersInChannel(channelDto.ChannelName));
        }
예제 #19
0
        public ChannelDto Insert(ChannelDto channel)
        {
            var res = SimpleCrud.Current.Insert(channel);

            if (res != 1)
            {
                return(null);
            }
            return(SimpleCrud.Current.Get <ChannelDto>(new { name = channel.name, guid = channel.guid }) as ChannelDto);
        }
        public async Task Handle_QuestionWithoutAnswers_ShouldSendMessageWithOneAttachment()
        {
            // Arrange
            var questionId   = Guid.NewGuid();
            var actionParams = new AnswerSlackActionParams
            {
                User = new ItemInfo {
                    Id = "userId", Name = "userName"
                },
                ButtonParams = new AnswerActionButtonParams {
                    QuestionId = questionId.ToString()
                }
            };

            var question = new Question
            {
                Id   = questionId,
                Text = "blabla"
            };

            var channel = new ChannelDto {
                Id = "channelId"
            };
            string actualChannelId = null;
            List <AttachmentDto> actualAttachments = null;

            _questionServiceMock.Setup(m => m.GetQuestionAsync(It.IsAny <string>()))
            .ReturnsAsync(question);
            _slackClientMock.Setup(m => m.OpenDirectMessageChannelAsync(It.IsAny <string>()))
            .ReturnsAsync(channel);
            _slackClientMock.Setup(m =>
                                   m.SendMessageAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <IList <AttachmentDto> >()))
            .Returns(Task.CompletedTask)
            .Callback((string channelId, string message, List <AttachmentDto> attachments) =>
            {
                actualChannelId   = channelId;
                actualAttachments = attachments;
            });

            // Act
            await _handler.Handle(actionParams);

            // Assert
            Assert.Equal(actualChannelId, channel.Id);
            Assert.Single(actualAttachments);
            _questionServiceMock.Verify(m => m.GetQuestionAsync(It.Is <string>(q => q == questionId.ToString())),
                                        Times.Once);
            _questionServiceMock.VerifyNoOtherCalls();
            _slackClientMock.Verify(
                m => m.OpenDirectMessageChannelAsync(It.Is <string>(id => id == actionParams.User.Id)), Times.Once);
            _slackClientMock.Verify(
                m => m.SendMessageAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <IList <AttachmentDto> >()),
                Times.Once);
            _slackClientMock.VerifyNoOtherCalls();
        }
예제 #21
0
            public ChannelBuilder CreateChannel(string channelName)
            {
                var channel = new ChannelDto(Guid.NewGuid());

                _builder.AddChannel(channel);
                _builder.AddBuildAction(
                    async() => await _facade.SendAsync(new CreateChannelCommand(_userIdContext, _group.GroupId,
                                                                                channel.ChannelId, channelName))
                    );
                return(new ChannelBuilder(this, channel));
            }
예제 #22
0
        public async Task <bool> UpdateAsync(ChannelDto channel, CancellationToken cancellation = default)
        {
            var entity = await _channelStorage.FindByIdAsync(channel.Id, cancellation);

            if (entity == null)
            {
                return(false);
            }
            Mapper.Map(channel, entity);
            return(await _channelStorage.UpdateAsync(entity) > 0);
        }
예제 #23
0
        public void CreateChannel(ChannelDto channel)
        {
            ValidateDto(channel);

            //TODO в одной тиме не должно быть двух каналов с одинаковым названием
            Execute.NonQuery(uow =>
            {
                //ValidateDbEntity(channel.MapToDbEntity(), uow, DomainModelValidation.ValidationType.OnCreate);
                uow.Repository <IChannelRepository>().Create(channel.MapToDbEntity());
            });
        }
예제 #24
0
        public async Task <ChannelDto> GetAsync(Guid id)
        {
            Channel channel = await _channelRepository.Select
                              .IncludeMany(r => r.Tags, r => r.Where(u => u.Status == true))
                              .Where(a => a.Id == id)
                              .WhereCascade(r => r.IsDeleted == false).ToOneAsync();

            ChannelDto channelDto = _mapper.Map <ChannelDto>(channel);

            channelDto.ThumbnailDisplay = _currentUser.GetFileUrl(channelDto.Thumbnail);
            return(channelDto);
        }
예제 #25
0
 public static Channel GetChannel(Channel editable, ChannelDto edited)
 {
     editable.ChannelName  = edited.ChannelName ?? editable.ChannelName;
     editable.About        = edited.About ?? editable.About;
     editable.Photo        = edited.Photo ?? editable.Photo;
     editable.Deleted      = edited.Deleted;
     editable.CreationTime = edited.CreationTime;
     editable.NodesId      = edited.NodesId;
     editable.Tag          = edited.Tag;
     editable.ChannelUsers = !edited.ChannelUsers.IsNullOrEmpty() ? GetChannelUsers(edited.ChannelUsers) : editable.ChannelUsers;
     return(editable);
 }
        public bool Merge(ChannelDto channel, EntityFactory entityFactory)
        {
            var changed = false;

            if (Url != channel.Url)
            {
                Url     = channel.Url;
                changed = true;
            }

            ChannelCourse[] missingCourses = FindMissingCourses(channel, entityFactory);
            ChannelCourse[] extraCourses   = FindExtraCourses(channel).ToArray();
            (ChannelCourse c, CourseDto dto)[] existingCourses = FindExistingCourses(channel).ToArray();
        public Channel(ChannelDto channelDto, EntityFactory entityFactory)
        {
            Name = channelDto.Name;
            Url  = channelDto.Url;

            ChannelCourses = channelDto.Courses
                             .Select(courseDto =>
            {
                Course course = entityFactory.CreateCourse(courseDto);
                return(entityFactory.CreateChannelCourse(channel: this, course));
            })
                             .ToList();
        }
        private ReplicateResult Replicate(ChannelDto channelDto, Channel channelDb)
        {
            bool channelModified = channelDb.Merge(channelDto, _entityFactory);

            if (channelModified)
            {
                LookUpCourses(ref channelDb);
            }

            return(channelModified
                       ? ReplicateResult.BuildChannelUpdated(channelDb.Name)
                       : ReplicateResult.BuildChannelUnchanged(channelDb.Name));
        }
예제 #29
0
        public async Task <PartialViewResult> CreateOrEditModal(int?id)
        {
            ChannelDto dto;

            if (id.HasValue)
            {
                dto = await _channelAppService.Get(new EntityDto(id.Value));
            }
            else
            {
                dto = new ChannelDto();
            }
            return(PartialView("_CreateOrEditModal", dto));
        }
        public async Task HandleAsync()
        {
            bool hasException = true;
            List <ChannelUserVm> channelUsers = null;

            while (hasException)
            {
                try
                {
                    channelUsers = await createChannelsService.CreateOrEditChannelUsersAsync(notice.ChannelUsers, notice.RequestorId).ConfigureAwait(false);

                    hasException = false;
                }
                catch (UserNotFoundException)
                {
                    List <long>   usersId = notice.ChannelUsers.Select(opt => opt.UserId).Append(notice.RequestorId).ToList();
                    List <UserVm> users   = await nodeRequestSender.GetUsersInfoAsync(usersId, null, current).ConfigureAwait(false);

                    await crossNodeService.CreateNewUsersAsync(users).ConfigureAwait(false);

                    hasException = true;
                }
                catch (ConversationNotFoundException)
                {
                    ChannelDto channel = await nodeRequestSender.GetChannelInformationAsync(notice.ChannelId, current).ConfigureAwait(false);

                    await createChannelsService.CreateOrUpdateUserChannelsAsync(new List <ChannelDto> {
                        channel
                    }).ConfigureAwait(false);

                    hasException = true;
                }
                catch (Exception ex)
                {
                    Logger.WriteLog(ex);
                    hasException = false;
                }
            }
            BlockSegmentVm segment = await BlockSegmentsService.Instance.CreateChannelUsersSegmentAsync(
                channelUsers,
                current.Node.Id,
                notice.ChannelId,
                NodeData.Instance.NodeKeys.SignPrivateKey,
                NodeData.Instance.NodeKeys.SymmetricKey,
                NodeData.Instance.NodeKeys.Password,
                NodeData.Instance.NodeKeys.KeyId).ConfigureAwait(false);

            BlockGenerationHelper.Instance.AddSegment(segment);
        }