public async Task <ChannelResponse> UpdateChannelAsync(UpdateChannelRequest request)
        {
            var channel = await UnitOfWork.ChannelRepository.GetChannelByIdAsync(request.ChannelId);

            Ensure.That(channel)
            .WithException(x => new NotFoundException(new ErrorDto(ErrorCode.NotFound, "Channel does not exist.")))
            .IsNotNull();

            var profile = await UnitOfWork.MemberRepository.GetMemberBySaasUserIdAsync(request.SaasUserId);

            if (channel.CreatorId != profile.Id)
            {
                throw new AccessForbiddenException(new ErrorDto(ErrorCode.ForbiddenError, "Access forbidden."));
            }

            var permanentChannelImageUrl = await CopyImageToDestinationContainerAsync(request.PhotoUrl);

            channel.Description    = request.Topic;
            channel.WelcomeMessage = request.WelcomeMessage;
            channel.Name           = request.Name;
            channel.PhotoUrl       = permanentChannelImageUrl;
            channel.Updated        = DateTimeOffset.UtcNow;

            await UnitOfWork.ChannelRepository.UpdateChannelAsync(channel);

            return(channel.ToChannelResponse(_configuration));
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            UpdateChannelRequest request;

            try
            {
                request = new UpdateChannelRequest
                {
                    ChannelId            = ChannelId,
                    UpdateChannelDetails = UpdateChannelDetails,
                    IfMatch       = IfMatch,
                    OpcRequestId  = OpcRequestId,
                    OpcRetryToken = OpcRetryToken
                };

                response = client.UpdateChannel(request).GetAwaiter().GetResult();
                WriteOutput(response, CreateWorkRequestObject(response.OpcWorkRequestId));
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
        public async Task Step3_ShouldUpdateChannel()
        {
            // Arrange
            var updateChannelRequest = new UpdateChannelRequest
            {
                ChannelId      = _testChannel.Id,
                Name           = $"new_{_testChannel.Name}",
                Description    = $"new_{_testChannel.Description}",
                RequestId      = "EA701C57-477D-42E3-B660-E510F7F8C72F",
                WelcomeMessage = $"new_{_testChannel.WelcomeMessage}"
            };

            // Subscribe event
            ChannelSummaryResponse channelSummaryResponse = null;

            void OnChannelUpdated(ChannelSummaryResponse response)
            {
                channelSummaryResponse = response;
            }

            _userSignalRClient.ChannelUpdated += OnChannelUpdated;

            // Act
            await _adminSignalRClient.UpdateChannelAsync(updateChannelRequest);

            // Unsubscribe events
            _userSignalRClient.ChannelUpdated -= OnChannelUpdated;

            // Assert
            channelSummaryResponse.Id.Should().Be(updateChannelRequest.ChannelId);
            channelSummaryResponse.Description.Should().BeEquivalentTo(updateChannelRequest.Description);
            channelSummaryResponse.Name.Should().BeEquivalentTo(updateChannelRequest.Name);
            channelSummaryResponse.WelcomeMessage.Should().BeEquivalentTo(updateChannelRequest.WelcomeMessage);
        }
示例#4
0
        /// <summary>
        /// Updates the properties of the specified Channel.
        /// If the Channel is Active the Update operation will asynchronously apply the new configuration
        /// parameters to the Channel and the Channel may become temporarily unavailable. Otherwise, the
        /// new configuration will be applied the next time the Channel becomes Active.
        ///
        /// </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/UpdateChannel.cs.html">here</a> to see an example of how to use UpdateChannel API.</example>
        public async Task <UpdateChannelResponse> UpdateChannel(UpdateChannelRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called updateChannel");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/channels/{channelId}".Trim('/')));
            HttpMethod         method         = new HttpMethod("PUT");
            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 <UpdateChannelResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"UpdateChannel failed with error: {e.Message}");
                throw;
            }
        }
示例#5
0
        /// <summary>
        /// Updates an existing Channel.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the UpdateChannel service method.</param>
        ///
        /// <returns>The response from the UpdateChannel 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/UpdateChannel">REST API Reference for UpdateChannel Operation</seealso>
        public virtual UpdateChannelResponse UpdateChannel(UpdateChannelRequest request)
        {
            var marshaller   = UpdateChannelRequestMarshaller.Instance;
            var unmarshaller = UpdateChannelResponseUnmarshaller.Instance;

            return(Invoke <UpdateChannelRequest, UpdateChannelResponse>(request, marshaller, unmarshaller));
        }
示例#6
0
        public void NotEqualsMemberIdAndChannelCreatorId_ShouldThrowIfMemberIsNotChannelCreator()
        {
            // Arrange
            var request = new UpdateChannelRequest("F9253C29-F09C-4B67-AF7F-E600BC153FD3", new Guid("60621580-7C10-48F0-B7F2-734735AD4A7C"), "name");

            var channel = new Channel {
                CreatorId = request.ChannelId
            };

            _channelRepositoryMock.Setup(x => x.GetChannelAsync(It.Is <Guid>(id => id.Equals(request.ChannelId))))
            .ReturnsAsync(channel)
            .Verifiable();

            var member = new Member {
                Id = new Guid("14C8640C-9D55-47D9-8D0B-D726703CFBE9")
            };

            _memberRepositoryMock.Setup(x => x.GetMemberBySaasUserIdAsync(It.IsAny <string>()))
            .ReturnsAsync(member)
            .Verifiable();

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

            // Assert
            act.Should().Throw <NetKitChatAccessForbiddenException>().And.Message.Should()
            .Be($"Unable to update channel { nameof(request.ChannelId)}:{ request.ChannelId}. Channel owner required.");

            VerifyMocks();
        }
示例#7
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);
        }
示例#8
0
        public async Task <ChannelResponse> UpdateChannelAsync(UpdateChannelRequest request)
        {
            var channel = await UnitOfWork.ChannelRepository.GetChannelAsync(request.ChannelId);

            if (channel == null)
            {
                throw new NetKitChatNotFoundException($"Unable to update channel. Channel {nameof(request.ChannelId)}:{request.ChannelId} is not found.");
            }

            var member = await UnitOfWork.MemberRepository.GetMemberBySaasUserIdAsync(request.SaasUserId);

            if (member.Id != channel.CreatorId)
            {
                throw new NetKitChatAccessForbiddenException($"Unable to update channel {nameof(request.ChannelId)}:{request.ChannelId}. Channel owner required.");
            }
            if (channel.Type == ChannelType.Direct)
            {
                throw new NetKitChatInvalidOperationException($"Unable to update direct channel {nameof(request.ChannelId)}:{request.ChannelId}.");
            }

            var permanentChannelImageUrl = await _cloudImageProvider.CopyImageToDestinationContainerAsync(request.PhotoUrl);

            channel.Description    = request.Description;
            channel.WelcomeMessage = request.WelcomeMessage;
            channel.Name           = request.Name;
            channel.PhotoUrl       = permanentChannelImageUrl;
            channel.Updated        = _dateTimeProvider.GetUtcNow();

            await UnitOfWork.ChannelRepository.UpdateChannelAsync(channel);

            return(DomainModelsMapper.MapToChannelResponse(channel));
        }
示例#9
0
        /// <summary>
        /// Initiates the asynchronous execution of the UpdateChannel operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the UpdateChannel 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/UpdateChannel">REST API Reference for UpdateChannel Operation</seealso>
        public virtual Task <UpdateChannelResponse> UpdateChannelAsync(UpdateChannelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = UpdateChannelRequestMarshaller.Instance;
            var unmarshaller = UpdateChannelResponseUnmarshaller.Instance;

            return(InvokeAsync <UpdateChannelRequest, UpdateChannelResponse>(request, marshaller,
                                                                             unmarshaller, cancellationToken));
        }
        public async Task <IActionResult> UpdateChannelAsync(Guid channelId, [FromBody] UpdateChannelRequest request)
        {
            request.ChannelId  = channelId;
            request.SaasUserId = GetCurrentUserId();
            var channel = await _channelService.UpdateChannelAsync(request);

            return(Ok(channel));
        }
        /// <summary>
        /// Updates an existing Channel.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the UpdateChannel service method.</param>
        ///
        /// <returns>The response from the UpdateChannel 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/UpdateChannel">REST API Reference for UpdateChannel Operation</seealso>
        public virtual UpdateChannelResponse UpdateChannel(UpdateChannelRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = UpdateChannelRequestMarshaller.Instance;
            options.ResponseUnmarshaller = UpdateChannelResponseUnmarshaller.Instance;

            return(Invoke <UpdateChannelResponse>(request, options));
        }
        /// <summary>
        /// Initiates the asynchronous execution of the UpdateChannel operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the UpdateChannel 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/UpdateChannel">REST API Reference for UpdateChannel Operation</seealso>
        public virtual Task <UpdateChannelResponse> UpdateChannelAsync(UpdateChannelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = UpdateChannelRequestMarshaller.Instance;
            options.ResponseUnmarshaller = UpdateChannelResponseUnmarshaller.Instance;

            return(InvokeAsync <UpdateChannelResponse>(request, options, cancellationToken));
        }
示例#13
0
 public async Task <ChannelSummaryResponse> UpdateChannelAsync(UpdateChannelRequest request)
 {
     return(await CheckAccessTokenAndExecute(new TaskReference <ChannelSummaryResponse>(async() =>
     {
         request.SaasUserId = Context.GetSaasUserId();
         return await _channelSocketService.UpdateChannelAsync(request);
     }),
                                             request.RequestId));
 }
示例#14
0
 /// <summary> Save all changes to this channel. </summary>
 public override async Task Save()
 {
     var request = new UpdateChannelRequest(Id)
     {
         Name     = Name,
         Position = Position,
         Bitrate  = Bitrate
     };
     await Client.ClientAPI.Send(request).ConfigureAwait(false);
 }
示例#15
0
        public async Task <IActionResult> UpdateChannelAsync(Guid channelId, [FromBody] TransportModels.Request.Channel.UpdateChannelRequest request)
        {
            var updateChannelRequest = new UpdateChannelRequest(GetCurrentSaasUserId(), channelId, request.Name)
            {
                PhotoUrl       = request.PhotoUrl,
                Description    = request.Description,
                WelcomeMessage = request.WelcomeMessage
            };
            var channel = await _channelSocketService.UpdateChannelAsync(updateChannelRequest);

            return(Ok(channel));
        }
示例#16
0
 public async Task <ChannelSummaryResponse> UpdateChannelAsync(UpdateChannelRequest request)
 {
     return(await ValidateAndExecuteAsync(request, new UpdateChannelRequestValidator(), new TaskReference <ChannelSummaryResponse>(async() =>
     {
         var updateChannelRequest = new DomainRequest.Channel.UpdateChannelRequest(Context.GetSaasUserId(), request.ChannelId, request.Name)
         {
             PhotoUrl = request.PhotoUrl,
             Description = request.Description,
             WelcomeMessage = request.WelcomeMessage
         };
         return await _channelSocketService.UpdateChannelAsync(updateChannelRequest);
     }),
                                          request.RequestId));
 }
示例#17
0
        /// <summary> Edits this channel, changing only non-null attributes. </summary>
        public async Task Edit(string name = null, string topic = null, int?position = null)
        {
            if (name != null || topic != null)
            {
                var request = new UpdateChannelRequest(Id)
                {
                    Name     = name ?? Name,
                    Topic    = topic ?? Topic,
                    Position = Position
                };
                await Client.ClientAPI.Send(request).ConfigureAwait(false);
            }

            if (position != null)
            {
                Channel[] channels      = Server.AllChannels.Where(x => x.Type == Type).OrderBy(x => x.Position).ToArray();
                int       oldPos        = Array.IndexOf(channels, this);
                var       newPosChannel = channels.Where(x => x.Position > position).FirstOrDefault();
                int       newPos        = (newPosChannel != null ? Array.IndexOf(channels, newPosChannel) : channels.Length) - 1;
                if (newPos < 0)
                {
                    newPos = 0;
                }
                int minPos;

                if (oldPos < newPos) //Moving Down
                {
                    minPos = oldPos;
                    for (int i = oldPos; i < newPos; i++)
                    {
                        channels[i] = channels[i + 1];
                    }
                    channels[newPos] = this;
                }
                else //(oldPos > newPos) Moving Up
                {
                    minPos = newPos;
                    for (int i = oldPos; i > newPos; i--)
                    {
                        channels[i] = channels[i - 1];
                    }
                    channels[newPos] = this;
                }
                Channel after = minPos > 0 ? channels.Skip(minPos - 1).FirstOrDefault() : null;
                await Server.ReorderChannels(channels.Skip(minPos), after).ConfigureAwait(false);
            }
        }
示例#18
0
        public void NoChannel_ShouldThrowIfChannelDoesNotExist()
        {
            // Arrange
            var request = new UpdateChannelRequest("F9253C29-F09C-4B67-AF7F-E600BC153FD3", new Guid("60621580-7C10-48F0-B7F2-734735AD4A7C"), "name");

            _channelRepositoryMock.Setup(x => x.GetChannelAsync(It.IsAny <Guid>()))
            .ReturnsAsync((Channel)null)
            .Verifiable();

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

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

            VerifyMocks();
        }
示例#19
0
        public static async Task <ChannelSummaryResponse> UpdateChannelAsync(SignalRClient signalRClient, Guid channelId)
        {
            // Update the channel called test
            var updateChannelRequest = new UpdateChannelRequest
            {
                ChannelId      = channelId,
                Name           = Guid.NewGuid() + "test",
                Topic          = "test",
                WelcomeMessage = "test",
                Type           = ChannelType.Public,
                AllowedMembers = new List <Guid>(),
                RequestId      = Guid.NewGuid().ToString(),
                PhotoUrl       = "https://softeqnonamemessaging.blob.core.windows.net/temp/1000_abf08299411.jpg"
            };

            Console.WriteLine("Updating the channel.");
            var updatedChannel = await signalRClient.UpdateChannelAsync(updateChannelRequest);

            Console.WriteLine("Channel was updated.");
            Console.WriteLine();

            return(updatedChannel);
        }
示例#20
0
        public async Task <ChannelSummaryResponse> UpdateChannelAsync(UpdateChannelRequest request)
        {
            if (String.IsNullOrEmpty(request.Name))
            {
                throw new Exception(LanguageResources.RoomRequired);
            }

            if (request.Name.Contains(' '))
            {
                throw new Exception(LanguageResources.RoomInvalidNameSpaces);
            }

            try
            {
                var channel = await _channelService.GetChannelByIdAsync(new ChannelRequest(request.SaasUserId, request.ChannelId));

                var member = await _memberService.GetMemberSummaryBySaasUserIdAsync(request.SaasUserId);

                if (channel.CreatorId != member.Id)
                {
                    throw new Exception(String.Format(LanguageResources.RoomAccessPermission, channel.Name));
                }

                await _channelService.UpdateChannelAsync(request);

                var channelSummary = await _channelService.GetChannelSummaryAsync(new ChannelRequest(request.SaasUserId, request.ChannelId));

                await _channelNotificationHub.OnUpdateChannel(member, channelSummary);

                return(channelSummary);
            }
            catch (NotFoundException ex)
            {
                _logger.Event(PropertyNames.EventId).With.Message("Exception: Channel {channelName} does not exist.", request.Name).Exception(ex).AsError();
                throw new Exception(String.Format(LanguageResources.RoomNotFound, request.Name));
            }
        }
示例#21
0
 public async Task <ChannelResponse> UpdateChannelAsync(UpdateChannelRequest model)
 {
     return(await _connection.InvokeAsync <ChannelResponse>("UpdateChannelAsync", model));
 }
示例#22
0
        public async Task ShouldUpdateChannel()
        {
            // Arrange
            var request = new UpdateChannelRequest("F9253C29-F09C-4B67-AF7F-E600BC153FD3", new Guid("A2BE089F-696C-4097-80EA-ABDAF31D098D"), "name")
            {
                Description    = "Description",
                WelcomeMessage = "Welcome Message",
                PhotoUrl       = "PhotoUrl"
            };

            var channelCreator = new Member {
                Id = new Guid("137FE248-7BE7-46A1-8D4D-258AD4A1418D")
            };

            var channel = new Channel {
                CreatorId = channelCreator.Id
            };

            _channelRepositoryMock.Setup(x => x.GetChannelAsync(It.Is <Guid>(id => id.Equals(request.ChannelId))))
            .ReturnsAsync(channel)
            .Verifiable();

            _memberRepositoryMock.Setup(x => x.GetMemberBySaasUserIdAsync(It.Is <string>(saasUserId => saasUserId.Equals(request.SaasUserId))))
            .ReturnsAsync(channelCreator)
            .Verifiable();

            const string cloudPhotoUrl = "cloudPhotoUrl";

            _cloudImageProviderMock.Setup(x => x.CopyImageToDestinationContainerAsync(It.Is <string>(photoUrl => photoUrl.Equals(request.PhotoUrl))))
            .ReturnsAsync(cloudPhotoUrl)
            .Verifiable();

            var utcNow = DateTimeOffset.UtcNow;

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

            Channel channelToUpdate = null;

            _channelRepositoryMock.Setup(x => x.UpdateChannelAsync(It.Is <Channel>(c => c.Equals(channel))))
            .Callback <Channel>(x => channelToUpdate = x)
            .Returns(Task.CompletedTask)
            .Verifiable();

            var mappedChannel = new ChannelResponse();

            _domainModelsMapperMock.Setup(x => x.MapToChannelResponse(It.Is <Channel>(c => c.Equals(channel))))
            .Returns(mappedChannel)
            .Verifiable();

            // Act
            var result = await _channelService.UpdateChannelAsync(request);

            // Assert
            VerifyMocks();

            channelToUpdate.Description.Should().BeEquivalentTo(request.Description);
            channelToUpdate.WelcomeMessage.Should().BeEquivalentTo(request.WelcomeMessage);
            channelToUpdate.Name.Should().BeEquivalentTo(request.Name);
            channelToUpdate.PhotoUrl.Should().BeEquivalentTo(cloudPhotoUrl);
            channelToUpdate.Updated.Should().Be(utcNow);

            result.Should().BeEquivalentTo(mappedChannel);
        }
示例#23
0
 public async Task <ChannelSummaryResponse> UpdateChannelAsync(UpdateChannelRequest request)
 {
     return(await _connection.InvokeAsync <ChannelSummaryResponse>(UpdateChannelCommandName, request));
 }
示例#24
0
 public Task <ChannelSummaryResponse> UpdateChannelAsync(UpdateChannelRequest request)
 {
     return(SendAndHandleExceptionsAsync <ChannelSummaryResponse>(ServerMethods.UpdateChannelAsync, request));
 }
示例#25
0
        /// <summary> Edits this channel, changing only non-null attributes. </summary>
        public async Task Edit(string name = null, string topic = null, int? position = null)
        {
            if (name != null || topic != null)
            {
                var request = new UpdateChannelRequest(Id)
                {
                    Name = name ?? Name,
                    Topic = topic ?? Topic,
                    Position = Position
                };
                await Client.ClientAPI.Send(request).ConfigureAwait(false);
            }

            if (position != null)
            {
                Channel[] channels = Server.AllChannels.Where(x => x.Type == Type).OrderBy(x => x.Position).ToArray();
                int oldPos = Array.IndexOf(channels, this);
                var newPosChannel = channels.Where(x => x.Position > position).FirstOrDefault();
                int newPos = (newPosChannel != null ? Array.IndexOf(channels, newPosChannel) : channels.Length) - 1;
                if (newPos < 0)
                    newPos = 0;
                int minPos;

                if (oldPos < newPos) //Moving Down
                {
                    minPos = oldPos;
                    for (int i = oldPos; i < newPos; i++)
                        channels[i] = channels[i + 1];
                    channels[newPos] = this;
                }
                else //(oldPos > newPos) Moving Up
                {
                    minPos = newPos;
                    for (int i = oldPos; i > newPos; i--)
                        channels[i] = channels[i - 1];
                    channels[newPos] = this;
                }
                Channel after = minPos > 0 ? channels.Skip(minPos - 1).FirstOrDefault() : null;
                await Server.ReorderChannels(channels.Skip(minPos), after).ConfigureAwait(false);
            }
        }