예제 #1
0
        public async Task GetChannelByIdAsyncTest()
        {
            // Arrange
            var request = new CreateChannelRequest(SaasUserId)
            {
                Name           = "test",
                Description    = "test",
                WelcomeMessage = "test",
                Type           = ChannelType.Public
            };

            var channel = await _channelService.CreateChannelAsync(request);

            var channelMessagesCount = await _channelService.GetChannelMessageCountAsync(new ChannelRequest(SaasUserId, channel.Id));

            // Act
            var newChannel = await _channelService.GetChannelByIdAsync(new ChannelRequest(SaasUserId, channel.Id));

            var channelMembers = await _memberService.GetChannelMembersAsync(new ChannelRequest(SaasUserId, channel.Id));

            // Assert
            Assert.NotNull(channelMembers);
            Assert.NotEmpty(channelMembers);
            Assert.NotNull(newChannel);
            Assert.Equal(request.Name, newChannel.Name);
            Assert.Equal(request.Description, newChannel.Description);
            Assert.Equal(request.WelcomeMessage, newChannel.WelcomeMessage);
            Assert.Equal(request.Type, newChannel.Type);
            Assert.True(channelMessagesCount == 0);
        }
예제 #2
0
        public async Task <ChannelSummaryResponse> CreateChannelAsync(CreateChannelRequest createChannelRequest)
        {
            if (String.IsNullOrEmpty(createChannelRequest.Name))
            {
                throw new Exception(LanguageResources.RoomRequired);
            }

            try
            {
                var channel = await _channelService.CreateChannelAsync(createChannelRequest);

                var user = await _memberService.GetMemberSummaryBySaasUserIdAsync(createChannelRequest.SaasUserId);

                await _channelNotificationHub.OnAddChannel(user, channel, createChannelRequest.ClientConnectionId);

                //todo filter creator connection id on join channel
                await _channelNotificationHub.OnJoinChannel(user, channel);

                return(channel);
            }
            catch (NotFoundException ex)
            {
                _logger.Event(PropertyNames.EventId).With.Message("Exception: Channel {channelName} does not exist.", createChannelRequest.Name).Exception(ex).AsError();
                throw new Exception(String.Format(LanguageResources.RoomNotFound, createChannelRequest.Name));
            }
        }
예제 #3
0
        public async Task GetChannelSettingsAsyncTest()
        {
            // Arrange
            var request = new CreateChannelRequest(SaasUserId)
            {
                Name           = "test",
                Description    = "test",
                WelcomeMessage = "test",
                Type           = ChannelType.Public
            };

            var channel = await _channelService.CreateChannelAsync(request);

            var settings = new Settings
            {
                Id          = Guid.NewGuid(),
                ChannelId   = channel.Id,
                RawSettings = "test"
            };

            await UnitOfWork.SettingRepository.AddSettingsAsync(settings);

            // Act
            var newSettings = await _channelService.GetChannelSettingsAsync(channel.Id);

            // Assert
            Assert.NotNull(newSettings);
            Assert.Equal(settings.Id, newSettings.Id);
            Assert.Equal(settings.ChannelId, newSettings.ChannelId);
            Assert.Equal(settings.RawSettings, newSettings.RawSettings);
        }
예제 #4
0
        public async Task GetAllChannelsAsyncTest()
        {
            // Arrange
            var request = new CreateChannelRequest(SaasUserId)
            {
                Name           = Guid.NewGuid() + "test",
                Description    = "test",
                WelcomeMessage = "test",
                Type           = ChannelType.Public
            };

            var channel = await _channelService.CreateChannelAsync(request);

            // Act
            var channels = await _channelService.GetAllChannelsAsync();

            var channelMessagesCount = await _channelService.GetChannelMessageCountAsync(new ChannelRequest(SaasUserId, channels.First().Id));

            // Assert
            Assert.NotNull(channels);
            Assert.NotEmpty(channels);
            Assert.Equal(request.Name, channels.First().Name);
            Assert.Equal(request.Description, channels.First().Description);
            Assert.Equal(request.WelcomeMessage, channels.First().WelcomeMessage);
            Assert.Equal(request.Type, channels.First().Type);
            Assert.Equal(_memberId, channels.First().CreatorId);
            Assert.True(channelMessagesCount == 0);
            Assert.True(channels.First().MembersCount == 1);
        }
        public async Task <OperationResultResponse <Guid?> > ExeсuteAsync(CreateChannelRequest request)
        {
            if (await _workspaceUserRepository
                .WorkspaceUsersExist(new List <Guid>()
            {
                _httpContextAccessor.HttpContext.GetUserId()
            }, request.WorkspaceId))
            {
                return(_responseCreator.CreateFailureResponse <Guid?>(HttpStatusCode.Forbidden));
            }

            ValidationResult validationResult = await _validator.ValidateAsync(request);

            if (!validationResult.IsValid)
            {
                return(_responseCreator.CreateFailureResponse <Guid?>(HttpStatusCode.BadRequest,
                                                                      validationResult.Errors.Select(vf => vf.ErrorMessage).ToList()));
            }

            OperationResultResponse <Guid?> response = new();

            response.Body = await _channelRepository.CreateAsync(await _channelMapper.MapAsync(request));

            _httpContextAccessor.HttpContext.Response.StatusCode = (int)HttpStatusCode.Created;
            response.Status = OperationResultStatusType.FullSuccess;

            if (response.Body is null)
            {
                response = _responseCreator.CreateFailureResponse <Guid?>(HttpStatusCode.BadRequest);
            }

            return(response);
        }
예제 #6
0
        /// <summary>
        /// Creates a Channel to establish replication from a source to a target.
        ///
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/mysql/CreateChannel.cs.html">here</a> to see an example of how to use CreateChannel API.</example>
        public async Task <CreateChannelResponse> CreateChannel(CreateChannelRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called createChannel");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/channels".Trim('/')));
            HttpMethod         method         = new HttpMethod("POST");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/json");
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false);
                }
                this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage);

                return(Converter.FromHttpResponseMessage <CreateChannelResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"CreateChannel failed with error: {e.Message}");
                throw;
            }
        }
예제 #7
0
        public async Task <DbChannel> MapAsync(CreateChannelRequest request)
        {
            if (request is null)
            {
                return(null);
            }

            Guid createdBy = _httpContextAccessor.HttpContext.GetUserId();
            Guid channelId = Guid.NewGuid();

            ICollection <DbChannelUser> dbChannelUsers = request.Users?
                                                         .Select(u => _channelUserMapper.Map(channelId, u.UserId, u.IsAdmin, createdBy))
                                                         .ToHashSet();

            dbChannelUsers.Add(_channelUserMapper.Map(channelId, createdBy, true, createdBy));

            (bool _, string resizedContent, string extension) = request.Image is null
        ? (false, null, null)
        : (await _resizeHelper.ResizeAsync(request.Image.Content, request.Image.Extension));

            return(new()
            {
                Id = channelId,
                WorkspaceId = request.WorkspaceId,
                Name = request.Name,
                IsPrivate = request.IsPrivate,
                IsActive = true,
                ImageContent = resizedContent,
                ImageExtension = extension,
                CreatedBy = createdBy,
                CreatedAtUtc = DateTime.UtcNow,
                Users = dbChannelUsers.ToHashSet()
            });
        }
예제 #8
0
        /// <summary>
        /// Creates a new Channel.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the CreateChannel service method.</param>
        ///
        /// <returns>The response from the CreateChannel service method, as returned by MediaPackage.</returns>
        /// <exception cref="Amazon.MediaPackage.Model.ForbiddenException">
        /// The client is not authorized to access the requested resource.
        /// </exception>
        /// <exception cref="Amazon.MediaPackage.Model.InternalServerErrorException">
        /// An unexpected error occurred.
        /// </exception>
        /// <exception cref="Amazon.MediaPackage.Model.NotFoundException">
        /// The requested resource does not exist.
        /// </exception>
        /// <exception cref="Amazon.MediaPackage.Model.ServiceUnavailableException">
        /// An unexpected error occurred.
        /// </exception>
        /// <exception cref="Amazon.MediaPackage.Model.TooManyRequestsException">
        /// The client has exceeded their resource or throttling limits.
        /// </exception>
        /// <exception cref="Amazon.MediaPackage.Model.UnprocessableEntityException">
        /// The parameters sent in the request are not valid.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mediapackage-2017-10-12/CreateChannel">REST API Reference for CreateChannel Operation</seealso>
        public virtual CreateChannelResponse CreateChannel(CreateChannelRequest request)
        {
            var marshaller   = CreateChannelRequestMarshaller.Instance;
            var unmarshaller = CreateChannelResponseUnmarshaller.Instance;

            return(Invoke <CreateChannelRequest, CreateChannelResponse>(request, marshaller, unmarshaller));
        }
예제 #9
0
        public async Task UpdateChannelAsync()
        {
            // Arrange
            var request = new CreateChannelRequest(SaasUserId, "name", ChannelType.Public)
            {
                Description    = "test",
                WelcomeMessage = "test"
            };

            var channel = await _channelService.CreateChannelAsync(request);

            var updatedRequest = new UpdateChannelRequest(SaasUserId, channel.Id, "test2")
            {
                Description    = "test2",
                WelcomeMessage = "test2"
            };

            // Act
            var updatedChannel = await _channelService.UpdateChannelAsync(updatedRequest);

            var channelMessagesCount = await _channelService.GetChannelMessagesCountAsync(channel.Id);

            // Assert
            Assert.NotNull(updatedChannel);
            Assert.NotNull(updatedChannel.Updated);
            Assert.Equal(updatedRequest.Name, updatedChannel.Name);
            Assert.Equal(updatedRequest.Description, updatedChannel.Description);
            Assert.Equal(updatedRequest.WelcomeMessage, updatedChannel.WelcomeMessage);
            Assert.Equal(_memberId, updatedChannel.CreatorId);
            Assert.True(channelMessagesCount == 0);
            Assert.True(updatedChannel.MembersCount == 1);
        }
예제 #10
0
        public async Task GetMyChannelsAsyncTest()
        {
            // Arrange
            var request = new CreateChannelRequest(SaasUserId)
            {
                Name           = "test",
                Description    = "test",
                WelcomeMessage = "test",
                Type           = ChannelType.Public
            };

            var channel = await _channelService.CreateChannelAsync(request);

            // Act
            var channels = await _channelService.GetMyChannelsAsync(new UserRequest(SaasUserId));

            // Assert
            Assert.NotNull(channels);
            Assert.NotEmpty(channels);
            Assert.Equal(request.Name, channels.First().Name);
            Assert.Equal(request.Description, channels.First().Description);
            Assert.Equal(request.WelcomeMessage, channels.First().WelcomeMessage);
            Assert.Equal(request.Type, channels.First().Type);
            Assert.Equal(_memberId, channels.First().CreatorId);
        }
예제 #11
0
        public async Task Step2_ShouldCreateChannel()
        {
            // Arrange
            var admin = await _adminSignalRClient.AddClientAsync();

            var client = await _userSignalRClient.AddClientAsync();

            // Subscribe event
            ChannelSummaryResponse createdChannel = null;

            void OnChannelCreated(ChannelSummaryResponse channelSummaryResponse)
            {
                createdChannel = channelSummaryResponse;
            }

            _adminSignalRClient.ChannelCreated += OnChannelCreated;

            // Subscribe event
            MemberSummaryResponse  joinedMember  = null;
            ChannelSummaryResponse joinedChannel = null;

            void OnMemberJoined(MemberSummaryResponse memberSummary, ChannelSummaryResponse channelSummaryResponse)
            {
                joinedMember  = memberSummary;
                joinedChannel = channelSummaryResponse;
            }

            _adminSignalRClient.MemberJoined += OnMemberJoined;

            var createChannelRequest = new CreateChannelRequest
            {
                Name           = "channel_name_without_spaces",
                Description    = "channel description",
                WelcomeMessage = "welcome message",
                Type           = ChannelType.Private,
                RequestId      = "3433E3F8-E363-4A07-8CAA-8F759340F769",
                AllowedMembers = new List <string>
                {
                    admin.MemberId.ToString(),
                client.MemberId.ToString()
                }
            };

            // Act
            _testChannel = await _adminSignalRClient.CreateChannelAsync(createChannelRequest);

            // Unsubscribe events
            _adminSignalRClient.ChannelCreated -= OnChannelCreated;
            _adminSignalRClient.MemberJoined   -= OnMemberJoined;

            // Assert
            createdChannel.Should().NotBeNull();
            createdChannel.Should().BeEquivalentTo(_testChannel);

            joinedMember.Should().NotBeNull();

            joinedChannel.Should().NotBeNull();
            joinedChannel.Should().BeEquivalentTo(_testChannel);
        }
예제 #12
0
        /// <summary>
        /// Initiates the asynchronous execution of the CreateChannel operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the CreateChannel operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mediapackage-2017-10-12/CreateChannel">REST API Reference for CreateChannel Operation</seealso>
        public virtual Task <CreateChannelResponse> CreateChannelAsync(CreateChannelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = CreateChannelRequestMarshaller.Instance;
            var unmarshaller = CreateChannelResponseUnmarshaller.Instance;

            return(InvokeAsync <CreateChannelRequest, CreateChannelResponse>(request, marshaller,
                                                                             unmarshaller, cancellationToken));
        }
예제 #13
0
        private Channel joinChannel(Channel channel, bool fetchInitialMessages = false)
        {
            if (channel == null)
            {
                return(null);
            }

            channel = getChannel(channel, addToJoined: true);

            // ensure we are joined to the channel
            if (!channel.Joined.Value)
            {
                channel.Joined.Value = true;

                switch (channel.Type)
                {
                case ChannelType.Multiplayer:
                    // join is implicit. happens when you join a multiplayer game.
                    // this will probably change in the future.
                    joinChannel(channel, fetchInitialMessages);
                    return(channel);

                case ChannelType.PM:
                    var createRequest = new CreateChannelRequest(channel);
                    createRequest.Success += resChannel =>
                    {
                        if (resChannel.ChannelID.HasValue)
                        {
                            channel.Id = resChannel.ChannelID.Value;

                            handleChannelMessages(resChannel.RecentMessages);
                            channel.MessagesLoaded = true;     // this will mark the channel as having received messages even if there were none.
                        }
                    };

                    api.Queue(createRequest);
                    break;

                default:
                    var req = new JoinChannelRequest(channel);
                    req.Success += () => joinChannel(channel, fetchInitialMessages);
                    req.Failure += ex => LeaveChannel(channel);
                    api.Queue(req);
                    return(channel);
                }
            }
            else
            {
                if (fetchInitialMessages)
                {
                    fetchInitalMessages(channel);
                }
            }

            CurrentChannel.Value ??= channel;

            return(channel);
        }
        public async Task <IActionResult> CreateChannelAsync([FromBody] CreateChannelRequest request)
        {
            var userId = GetCurrentUserId();

            request.SaasUserId = userId;
            var channel = await _channelService.CreateChannelAsync(request);

            return(Ok(channel));
        }
        /// <summary>
        /// Creates a new Channel.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the CreateChannel service method.</param>
        ///
        /// <returns>The response from the CreateChannel service method, as returned by MediaPackage.</returns>
        /// <exception cref="Amazon.MediaPackage.Model.ForbiddenException">
        /// The client is not authorized to access the requested resource.
        /// </exception>
        /// <exception cref="Amazon.MediaPackage.Model.InternalServerErrorException">
        /// An unexpected error occurred.
        /// </exception>
        /// <exception cref="Amazon.MediaPackage.Model.NotFoundException">
        /// The requested resource does not exist.
        /// </exception>
        /// <exception cref="Amazon.MediaPackage.Model.ServiceUnavailableException">
        /// An unexpected error occurred.
        /// </exception>
        /// <exception cref="Amazon.MediaPackage.Model.TooManyRequestsException">
        /// The client has exceeded their resource or throttling limits.
        /// </exception>
        /// <exception cref="Amazon.MediaPackage.Model.UnprocessableEntityException">
        /// The parameters sent in the request are not valid.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mediapackage-2017-10-12/CreateChannel">REST API Reference for CreateChannel Operation</seealso>
        public virtual CreateChannelResponse CreateChannel(CreateChannelRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = CreateChannelRequestMarshaller.Instance;
            options.ResponseUnmarshaller = CreateChannelResponseUnmarshaller.Instance;

            return(Invoke <CreateChannelResponse>(request, options));
        }
        /// <summary>
        /// Initiates the asynchronous execution of the CreateChannel operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the CreateChannel operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/mediapackage-2017-10-12/CreateChannel">REST API Reference for CreateChannel Operation</seealso>
        public virtual Task <CreateChannelResponse> CreateChannelAsync(CreateChannelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = CreateChannelRequestMarshaller.Instance;
            options.ResponseUnmarshaller = CreateChannelResponseUnmarshaller.Instance;

            return(InvokeAsync <CreateChannelResponse>(request, options, cancellationToken));
        }
예제 #17
0
 public async Task <ChannelSummaryResponse> CreateChannelAsync(CreateChannelRequest request)
 {
     return(await CheckAccessTokenAndExecute(new TaskReference <ChannelSummaryResponse>(async() =>
     {
         request.SaasUserId = Context.GetSaasUserId();
         request.ClientConnectionId = Context.ConnectionId;
         return await _channelSocketService.CreateChannelAsync(request);
     }),
                                             request.RequestId));
 }
예제 #18
0
        public Task <ChatSummaryModel> CreateChatAsync(IEnumerable <string> participantsIds)
        {
            var dto = new CreateChannelRequest
            {
                AllowedMembers = participantsIds.ToList(),
            };

            var request = new PostCreateChatRequest(_chatConfig.ApiUrl, _jsonSerializer, dto);

            return(_httpClient.GetModelAsync <ChatSummaryModel, ChannelSummaryResponse>(request, _logger, Mapper.DtoToChatSummary));
        }
예제 #19
0
        public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done)
        {
            Logger.Trace("CreateChannel()");

            var newChannel = ChannelsManager.CreateNewChannel(Client);
            var builder = CreateChannelResponse.CreateBuilder()
                .SetObjectId(request.ObjectId)
                .SetChannelId(newChannel.BnetEntityID);

            done(builder.Build());
        }
        public async Task <OpenChannelResponse> OpenChannel(NodeInfo nodeUri, Money amount, FeeRate feeRate, CancellationToken cancellation)
        {
            var payload = new CreateChannelRequest
            {
                NodeURI       = nodeUri.ToString(),
                ChannelAmount = amount,
                FeeRate       = feeRate
            };

            return(await Post <CreateChannelRequest, OpenChannelResponse>("channels", payload, cancellation));
        }
예제 #21
0
        public async Task <IActionResult> CreateChannelAsync([FromBody] TransportModels.Request.Channel.CreateChannelRequest request)
        {
            var createChannelRequest = new CreateChannelRequest(GetCurrentSaasUserId(), request.Name, request.Type)
            {
                AllowedMembers = request.AllowedMembers,
                Description    = request.Description,
                PhotoUrl       = request.PhotoUrl,
                WelcomeMessage = request.WelcomeMessage
            };
            var channel = await _channelSocketService.CreateChannelAsync(createChannelRequest);

            return(Ok(channel));
        }
예제 #22
0
        // PartyService just used ChannelService to create a new channel for the party.

        public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done)
        {
            Logger.Trace("CreateChannel()");
            
            var channel = ChannelsManager.CreateNewChannel((BNetClient)this.Client);

            // This is an object creator, so we have to map the remote object ID
            this.Client.MapLocalObjectID(channel.DynamicId, request.ObjectId);
            var builder = CreateChannelResponse.CreateBuilder()
                .SetObjectId(channel.DynamicId)
                .SetChannelId(channel.BnetEntityID);

            done(builder.Build());
        }
예제 #23
0
        // PartyService just uses ChannelService to create a new channel for the party.
        public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action <CreateChannelResponse> done)
        {
            Logger.Trace("CreateChannel()");
            var channel = ChannelManager.CreateNewChannel((BNetClient)this.Client, request.ObjectId);
            var builder = CreateChannelResponse.CreateBuilder()
                          .SetObjectId(channel.DynamicId)
                          .SetChannelId(channel.BnetEntityId);

            done(builder.Build());

            // Set the client that requested the creation of channel as the owner
            channel.SetOwner((BNetClient)Client);

            Logger.Warn("Created a new channel {0}:{1} for toon {2}", channel.BnetEntityId.High, channel.BnetEntityId.Low, Client.CurrentToon.Name);
        }
예제 #24
0
        // PartyService just uses ChannelService to create a new channel for the party.
        public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done)
        {
            Logger.Trace("CreateChannel()");
            var channel = ChannelManager.CreateNewChannel((MooNetClient)this.Client, request.ObjectId);
            var builder = CreateChannelResponse.CreateBuilder()
                .SetObjectId(channel.DynamicId)
                .SetChannelId(channel.BnetEntityId);

            done(builder.Build());

            // Set the client that requested the creation of channel as the owner
            channel.SetOwner((MooNetClient)Client);

            Logger.Debug("Created a new channel {0}:{1} for toon {2}", channel.BnetEntityId.High, channel.BnetEntityId.Low, Client.CurrentToon.Name);
        }
예제 #25
0
 public CreateChannelRequestHandler(
     Request request,
     ClientConnection clientConnection,
     INodeNoticeService nodeNoticeService,
     IConversationsNoticeService conversationsNoticeService,
     ILoadChannelsService loadChannelsService,
     ICreateChannelsService createChannelsService)
 {
     this.request                    = (CreateChannelRequest)request;
     this.clientConnection           = clientConnection;
     this.nodeNoticeService          = nodeNoticeService;
     this.conversationsNoticeService = conversationsNoticeService;
     this.loadChannelsService        = loadChannelsService;
     this.createChannelsService      = createChannelsService;
 }
        /// <inheritdoc/>
        public Channel CreateChannel(CreateChannelRequest channelRequest)
        {
            Preconditions.NotNull("channelRequest", channelRequest);

            var request = new HttpRequest();

            request.Method = "POST";
            request.Url    = this.UrlProvider.ChannelsUrl;
            request.AddOAuthAuthorization(this.AccessToken);
            request.SetJsonBody(channelRequest);

            var response = this.HttpClient.GetJsonResponse <ChannelResponse>(request);

            return(response.ToChannel());
        }
예제 #27
0
        // PartyService just used ChannelService to create a new channel for the party.

        public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done)
        {
            Logger.Trace("CreateChannel()");
            
            var channel = ChannelsManager.CreateNewChannel((BNetClient)this.Client, request.ObjectId);

            var builder = CreateChannelResponse.CreateBuilder()
                .SetObjectId(channel.DynamicId)
                .SetChannelId(channel.BnetEntityId);

            done(builder.Build());
            
            // Add the client that requested the creation of channel as the owner
            channel.AddOwner((BNetClient)Client);
        }
예제 #28
0
 public async Task <ChannelSummaryResponse> CreateChannelAsync(CreateChannelRequest request)
 {
     return(await ValidateAndExecuteAsync(request, new CreateChannelRequestValidator(), new TaskReference <ChannelSummaryResponse>(async() =>
     {
         var createChannelRequest = new DomainRequest.Channel.CreateChannelRequest(Context.GetSaasUserId(), request.Name, request.Type)
         {
             AllowedMembers = request.AllowedMembers,
             Description = request.Description,
             PhotoUrl = request.PhotoUrl,
             WelcomeMessage = request.WelcomeMessage
         };
         return await _channelSocketService.CreateChannelAsync(createChannelRequest);
     }),
                                          request.RequestId));
 }
예제 #29
0
        static ChannelAuth CreateChannel(
            string appId, string channelId,
            string regionId, string endpoint, string accessKeyId,
            string accessKeySecret)
        {
            try
            {
                IClientProfile profile = DefaultProfile.GetProfile(
                    regionId, accessKeyId, accessKeySecret);
                IAcsClient client = new DefaultAcsClient(profile);

                CreateChannelRequest request = new CreateChannelRequest();
                request.AppId     = appId;
                request.ChannelId = channelId;

                // Strongly recomment to set the RTC endpoint,
                // because the exception is not the "right" one if not set.
                // For example, if access-key-id is invalid:
                //      1. if endpoint is set, exception is InvalidAccessKeyId.NotFound
                //      2. if endpoint isn't set, exception is SDK.InvalidRegionId
                // that's caused by query endpoint failed.
                // @remark SDk will cache endpoints, however it will query endpoint for the first
                //      time, so it's good for performance to set the endpoint.
                DefaultProfile.AddEndpoint(regionId, regionId, request.Product, endpoint);

                // Use HTTP, x3 times faster than HTTPS.
                request.Protocol = Aliyun.Acs.Core.Http.ProtocolType.HTTP;

                CreateChannelResponse response = client.GetAcsResponse(request);

                ChannelAuth auth = new ChannelAuth();
                auth.AppId      = appId;
                auth.ChannelId  = channelId;
                auth.Nonce      = response.Nonce;
                auth.Timestamp  = (Int64)response.Timestamp;
                auth.ChannelKey = response.ChannelKey;
                auth.Recovered  = false;
                auth.RequestId  = response.RequestId;

                return(auth);
            }
            catch (Exception ex)
            {
                return(RecoverForError(ex, appId, channelId));
            }
        }
예제 #30
0
        public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done)
        {
            Logger.Trace("CreateChannel()");
            //Logger.Debug("request:\n{0}", request.ToString());
            
            var channel = ChannelsManager.CreateNewChannel();
            // This is an object creator, so we have to map the remote object ID
            this.Client.MapLocalObjectID(channel.ID, request.ObjectId);
            var builder = CreateChannelResponse.CreateBuilder()
                .SetObjectId(channel.ID)
                .SetChannelId(channel.BnetEntityID);

            done(builder.Build());

            channel.Add((Client)this.Client);
            channel.NotifyChannelState((Client)this.Client);
        }
예제 #31
0
        public void ShouldThrowIfMemberDoesNotExist()
        {
            // Arrange
            _memberRepositoryMock.Setup(x => x.GetMemberBySaasUserIdAsync(It.IsAny <string>()))
            .ReturnsAsync((Member)null)
            .Verifiable();

            var request = new CreateChannelRequest("864EB62D-D833-47FA-8A88-DDBFE76AE6A7", "channel name", ChannelType.Public);

            // Act
            Func <Task> act = async() => { await _channelService.CreateChannelAsync(request); };

            // Assert
            act.Should().Throw <NetKitChatNotFoundException>()
            .And.Message.Should().Be($"Unable to create channel. Member with {nameof(request.SaasUserId)}:{request.SaasUserId} is not found.");

            VerifyMocks();
        }
예제 #32
0
        public void ShouldThrowIfAllowedMemberNotFound()
        {
            // Arrange
            var allowedMember = new Member
            {
                Id = Guid.Parse("1AB5626B-B311-4862-A0F1-AFD21D9F421B")
            };

            var request = new CreateChannelRequest("864EB62D-D833-47FA-8A88-DDBFE76AE6A7", "channel name", ChannelType.Private)
            {
                AllowedMembers = new List <string> {
                    allowedMember.Id.ToString()
                }
            };

            var member = new Member {
                Id = new Guid("85B1E28A-3E29-48C5-B85B-1563EEB60742")
            };

            _memberRepositoryMock.SetupSequence(x => x.GetMemberBySaasUserIdAsync(It.IsAny <string>()))
            .ReturnsAsync(member)
            .ReturnsAsync(null);

            _cloudImageProviderMock.Setup(x => x.CopyImageToDestinationContainerAsync(It.IsAny <string>()))
            .ReturnsAsync((string)null)
            .Verifiable();

            _memberRepositoryMock.Setup(x => x.GetMemberByIdAsync(It.IsAny <Guid>()))
            .ReturnsAsync((Member)null)
            .Verifiable();

            _dateTimeProviderMock.Setup(x => x.GetUtcNow())
            .Returns(DateTimeOffset.UtcNow)
            .Verifiable();

            // Act
            Func <Task> act = async() => { await _channelService.CreateChannelAsync(request); };

            // Assert
            act.Should().Throw <NetKitChatNotFoundException>()
            .And.Message.Should().Be($"Unable to add member to channel. Member memberId:{allowedMember.Id} not found.");

            VerifyMocks();
        }
예제 #33
0
        public async Task CloseChannelAsyncTest()
        {
            // Arrange
            var request = new CreateChannelRequest(SaasUserId, "name", ChannelType.Public)
            {
                Description    = "test",
                WelcomeMessage = "test"
            };

            var channel = await _channelService.CreateChannelAsync(request);

            // Act
            await _channelService.CloseChannelAsync(SaasUserId, channel.Id);

            var newChannel = await _channelService.GetChannelByIdAsync(channel.Id);

            // Assert
            Assert.NotNull(newChannel);
            Assert.True(newChannel.IsClosed);
        }
예제 #34
0
        private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            var request = new CreateChannelRequest
            {
                ChannelName = ChannelNameBox.Text,
                TeamId      = HttpApi.SelectedTeam.Id,
                UserId      = HttpApi.LoggedInUser.Id
            };

            try
            {
                var channel = await HttpApi.Channel.SaveAsync(request, HttpApi.AuthToken);

                callback(channel);
            }
            catch (ApiException ex)
            {
                await ex.ShowErrorDialog();
            }
        }
예제 #35
0
        public async Task PinChannelAsync_ShouldChangeIsPinnedStatus()
        {
            var createChannelRequest = new CreateChannelRequest(SaasUserId, "name", ChannelType.Public)
            {
                Description    = "test",
                WelcomeMessage = "test"
            };
            var channel = await _channelService.CreateChannelAsync(createChannelRequest);

            await _channelService.PinChannelAsync(SaasUserId, channel.Id, true);

            var pinnedChannel = await _channelService.GetChannelSummaryAsync(SaasUserId, channel.Id);

            pinnedChannel.IsPinned.Should().BeTrue();

            await _channelService.PinChannelAsync(SaasUserId, channel.Id, false);

            var unPinnedChannel = await _channelService.GetChannelSummaryAsync(SaasUserId, channel.Id);

            unPinnedChannel.IsPinned.Should().BeFalse();
        }
예제 #36
0
 public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done)
 {
     ProtoOutputBuffer.Write(request.GetType(), request.ToString());
 }
예제 #37
0
파일: ChannelOwnerImpl.cs 프로젝트: fry/d3
		public override void CreateChannel(Google.ProtocolBuffers.IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done) {
			throw new NotImplementedException();
		}
예제 #38
0
        /// <summary> Creates a new channel. </summary>
        public async Task<Channel> CreateChannel(string name, ChannelType type)
        {
            if (name == null) throw new ArgumentNullException(nameof(name));
            if (type == null) throw new ArgumentNullException(nameof(type));

            var request = new CreateChannelRequest(Id) { Name = name, Type = type.Value };
            var response = await Client.ClientAPI.Send(request).ConfigureAwait(false);

            var channel = AddChannel(response.Id);
            channel.Update(response);
            return channel;
        }
예제 #39
0
        public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done)
        {
            done(new CreateChannelResponse.Builder
                     {
                         ChannelId = request.ChannelId.ToBuilder().SetHigh(0x604ac77c9aa0d7d).SetLow(0x9be5ecbd0000279f).Build(),
                         ObjectId = 67093
                     }.Build());

            client.ListenerId = request.ObjectId;

            var notification = new AddNotification.Builder
                                   {
                                       Self = new Member.Builder
                                                  {
                                                      Identity = new Identity.Builder
                                                                     {
                                                                         AccountId = new EntityId.Builder
                                                                                         {
                                                                                             High = HighId.Account,
                                                                                             Low = 0
                                                                                         }.Build(),
                                                                         GameAccountId = new EntityId.Builder
                                                                                             {
                                                                                                 High = HighId.GameAccount,
                                                                                                 Low = 5200929,
                                                                                             }.Build(),
                                                                         ToonId = new EntityId.Builder
                                                                                      {
                                                                                          High = HighId.Toon,
                                                                                          Low = 2,
                                                                                      }.Build()
                                                                     }.Build(),
                                                      State = new MemberState.Builder
                                                                  {
                                                                      Privileges = 64511,
                                                                  }.AddRole(2).Build(),

                                                  }.Build(),

                                       ChannelState = new ChannelState.Builder
                                                          {
                                                              MaxMembers = 8,
                                                              MinMembers = 1,
                                                              MaxInvitations = 12,
                                                              PrivacyLevel = ChannelState.Types.PrivacyLevel.PRIVACY_LEVEL_OPEN_INVITATION
                                                          }.Build()
                                   }.AddMember(new Member.Builder
                                   {
                                       Identity = new Identity.Builder
                                       {
                                           ToonId = new EntityId.Builder
                                           {
                                               High = HighId.Toon,
                                               Low = 2,
                                           }.Build()
                                       }.Build(),
                                       State = new MemberState.Builder
                                       {
                                           Privileges = 64511,
                                       }.AddRole(2).Build(),
                                   }.Build());

            ChannelSubscriber.CreateStub(client).NotifyAdd(controller, notification.Build(), r => { });
        }