コード例 #1
0
        public async Task GetUserStatusAsync_Throws_UserStatusException_On_Throw(string username, UserStatus status, bool privileged)
        {
            var result = new GetStatusResponse(username, status, privileged);

            var waiter = new Mock <IWaiter>();

            waiter.Setup(m => m.Wait <GetStatusResponse>(It.IsAny <WaitKey>(), null, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(result));

            var serverConn = new Mock <IMessageConnection>();

            serverConn.Setup(m => m.WriteAsync(It.IsAny <byte[]>(), It.IsAny <CancellationToken>()))
            .Throws(new ConnectionException("foo"));

            using (var s = new SoulseekClient("127.0.0.1", 1, waiter: waiter.Object, serverConnection: serverConn.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                GetStatusResponse r = null;
                var ex = await Record.ExceptionAsync(async() => r = await s.GetUserStatusAsync(username));

                Assert.NotNull(ex);
                Assert.IsType <UserStatusException>(ex);
                Assert.IsType <ConnectionException>(ex.InnerException);
            }
        }
コード例 #2
0
        /// <summary>
        /// <para> This operation returns information about a job, including where
        /// the job is in the processing pipeline, the status of the results, and
        /// the signature value associated with the job. You can only return
        /// information about jobs you own. </para>
        /// </summary>
        ///
        /// <param name="getStatusRequest">Container for the necessary parameters
        ///           to execute the GetStatus service method on AmazonImportExport.</param>
        ///
        /// <returns>The response from the GetStatus service method, as returned
        ///         by AmazonImportExport.</returns>
        ///
        /// <exception cref="CanceledJobIdException"/>
        /// <exception cref="ExpiredJobIdException"/>
        /// <exception cref="InvalidAccessKeyIdException"/>
        /// <exception cref="InvalidJobIdException"/>
        public GetStatusResponse GetStatus(GetStatusRequest getStatusRequest)
        {
            IRequest <GetStatusRequest> request  = new GetStatusRequestMarshaller().Marshall(getStatusRequest);
            GetStatusResponse           response = Invoke <GetStatusRequest, GetStatusResponse> (request, this.signer, GetStatusResponseUnmarshaller.GetInstance());

            return(response);
        }
コード例 #3
0
        public async Task GetUserStatusAsync_Returns_Expected_Info(string username, UserStatus status, bool privileged)
        {
            var result = new GetStatusResponse(username, status, privileged);

            var waiter = new Mock <IWaiter>();

            waiter.Setup(m => m.Wait <GetStatusResponse>(It.IsAny <WaitKey>(), null, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(result));

            var serverConn = new Mock <IMessageConnection>();

            serverConn.Setup(m => m.WriteAsync(It.IsAny <byte[]>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);

            using (var s = new SoulseekClient("127.0.0.1", 1, waiter: waiter.Object, serverConnection: serverConn.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var stat = await s.GetUserStatusAsync(username);

                Assert.Equal(result.Username, stat.Username);
                Assert.Equal(result.Status, stat.Status);
                Assert.Equal(result.Privileged, stat.Privileged);
            }
        }
コード例 #4
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            GetStatusResponse response = new GetStatusResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("GetStatusResult", 2))
                    {
                        UnmarshallResult(context, response);
                        continue;
                    }

                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
                    }
                }
            }

            return(response);
        }
コード例 #5
0
 private void OnResponse(GetStatusResponse response)
 {
     if (response.RequestId != _requestId)
     {
         return;
     }
     _source.TrySetResult(response);
 }
コード例 #6
0
        public void Instantiates_With_The_Given_Data(string username, UserStatus status, bool privileged)
        {
            var r = new GetStatusResponse(username, status, privileged);

            Assert.Equal(username, r.Username);
            Assert.Equal(status, r.Status);
            Assert.Equal(privileged, r.Privileged);
        }
コード例 #7
0
        public void Parse_Throws_MessageException_On_Code_Mismatch()
        {
            var msg = new MessageBuilder()
                      .WriteCode(MessageCode.Peer.BrowseRequest)
                      .Build();

            var ex = Record.Exception(() => GetStatusResponse.Parse(msg));

            Assert.NotNull(ex);
            Assert.IsType <MessageException>(ex);
        }
コード例 #8
0
        public ActionResult GetTheStatus()
        {
            var response = new GetStatusResponse
            {
                CheckedBy   = "Joes",
                Message     = "Looking good bruv",
                LastChecked = _systemTime.GetCurrent()
            };

            return(Ok(response));
        }
コード例 #9
0
        public void Parse_Throws_MessageReadException_On_Missing_Data()
        {
            var msg = new MessageBuilder()
                      .WriteCode(MessageCode.Server.GetStatus)
                      .Build();

            var ex = Record.Exception(() => GetStatusResponse.Parse(msg));

            Assert.NotNull(ex);
            Assert.IsType <MessageReadException>(ex);
        }
コード例 #10
0
        public ActionResult GetTheServerStatus()
        {
            var response = new GetStatusResponse
            {
                StatusMessage = "Looks Good Here!",
                LastChecked   = DateTime.Now,
                CheckedBy     = "Fred"
            };

            return(Ok(response));
        }
コード例 #11
0
        public dacGetStatusOutput GetStatus(ref SecurityHeaderType Security, RequestHeaderType RequestHeader, dacGetStatusInput dacGetStatusInput)
        {
            GetStatusRequest inValue = new GetStatusRequest();

            inValue.Security          = Security;
            inValue.RequestHeader     = RequestHeader;
            inValue.dacGetStatusInput = dacGetStatusInput;
            GetStatusResponse retVal = ((GetStatusV02)(this)).GetStatus(inValue);

            Security = retVal.Security;
            return(retVal.dacGetStatusOutput);
        }
コード例 #12
0
        public void Parse_Returns_Expected_Data(string username, UserStatus status, bool privileged)
        {
            var msg = new MessageBuilder()
                      .WriteCode(MessageCode.Server.GetStatus)
                      .WriteString(username)
                      .WriteInteger((int)status)
                      .WriteByte((byte)(privileged ? 1 : 0))
                      .Build();

            var r = GetStatusResponse.Parse(msg);

            Assert.Equal(username, r.Username);
            Assert.Equal(status, r.Status);
            Assert.Equal(privileged, r.Privileged);
        }
コード例 #13
0
ファイル: Controller.cs プロジェクト: tmauldin/mb-unit
        public Status GetStatus()
        {
            CheckProfileHasMaster();
            CheckProfileHasVM();

            Log(string.Format("Getting status of VM '{0}'.", profile.VM));

            GetStatusRequest request = new GetStatusRequest()
            {
                Vm = profile.VM
            };
            GetStatusResponse response = GetMasterClient().GetStatus(request);

            return(response.Status);
        }
コード例 #14
0
        private void GetStationStatusUICallback(object sender, SimpleEventArgs evt)
        {
            GetStatusResponse stationStatus = (GetStatusResponse)evt.param;

            long _usedSize = 0;

            foreach (DiskUsage _du in stationStatus.station_status.diskusage)
            {
                _usedSize += _du.used;
            }

            lblLocalStorageUsage.Text = string.Format("{0:0.0} MB", _usedSize / (1024 * 1024));
            lblDeviceName.Text        = stationStatus.station_status.computer_name;

            RestoreCursor();
        }
コード例 #15
0
        public string GetStatus()
        {
            var request = new GetStatusRequest()
            {
                Thread = grpcSbThread
            };
            GetStatusResponse response = null;

            if (connection.InvokeRpc(() =>
            {
                response = client.GetStatus(request);
            }))
            {
                return(response.Status);
            }
            return("");
        }
コード例 #16
0
        public ActionResult GetTheStatus()
        {
            GetStatusResponse response = null;

            // WTCYWYH - Write the code you wish you had.
            try
            {
                response = _statusService.GetCurrentStatus();
            }
            catch (Exception)
            {
                response = new GetStatusResponse
                {
                    Message   = "Status is unavailable",
                    CreatedAt = new DateTime() // January 1, year 1 at midnight.
                };
            }
            return(Ok(response));
        }
        public static GetStatusResponse Unmarshall(UnmarshallerContext context)
        {
            GetStatusResponse getStatusResponse = new GetStatusResponse();

            getStatusResponse.HttpResponse = context.HttpResponse;
            getStatusResponse.RequestId    = context.StringValue("GetStatus.RequestId");
            getStatusResponse.Success      = context.BooleanValue("GetStatus.Success");
            getStatusResponse.Code         = context.StringValue("GetStatus.Code");
            getStatusResponse.Message      = context.StringValue("GetStatus.Message");

            GetStatusResponse.GetStatus_Data data = new GetStatusResponse.GetStatus_Data();
            data.StatusCode        = context.IntegerValue("GetStatus.Data.StatusCode");
            data.TrustedScore      = context.FloatValue("GetStatus.Data.TrustedScore");
            data.SimilarityScore   = context.FloatValue("GetStatus.Data.SimilarityScore");
            data.AuditConclusions  = context.StringValue("GetStatus.Data.AuditConclusions");
            getStatusResponse.Data = data;

            return(getStatusResponse);
        }
コード例 #18
0
        public static GetStatusResponse GetStationStatus()
        {
            try
            {
                GetStatusResponse res = CloudServer.request <GetStatusResponse>(
                    new WebClient(),
                    StationMgmtURL + "station/status/get",
                    new Dictionary <object, object>
                {
                    { CloudServer.PARAM_API_KEY, CloudServer.APIKey },
                }
                    );

                return(res);
            }
            catch (WammerCloudException e)
            {
                ExtractApiRetMsg(e);

                throw;
            }
        }
コード例 #19
0
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            GetStatusResponse response = new GetStatusResponse();

            while (context.Read())
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("GetStatusResult", 2))
                    {
                        response.GetStatusResult = GetStatusResultUnmarshaller.GetInstance().Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context);
                    }
                }
            }


            return(response);
        }
コード例 #20
0
        private static void UnmarshallResult(XmlUnmarshallerContext context, GetStatusResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth += 2;
            }

            while (context.ReadAtDepth(originalDepth))
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("ArtifactList/member", targetDepth))
                    {
                        var unmarshaller = ArtifactUnmarshaller.Instance;
                        var item         = unmarshaller.Unmarshall(context);
                        response.ArtifactList.Add(item);
                        continue;
                    }
                    if (context.TestExpression("Carrier", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.Carrier = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("CreationDate", targetDepth))
                    {
                        var unmarshaller = DateTimeUnmarshaller.Instance;
                        response.CreationDate = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("CurrentManifest", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.CurrentManifest = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("ErrorCount", targetDepth))
                    {
                        var unmarshaller = IntUnmarshaller.Instance;
                        response.ErrorCount = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("JobId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.JobId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("JobType", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.JobType = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("LocationCode", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.LocationCode = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("LocationMessage", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.LocationMessage = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("LogBucket", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.LogBucket = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("LogKey", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.LogKey = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("ProgressCode", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.ProgressCode = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("ProgressMessage", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.ProgressMessage = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("Signature", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.Signature = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("SignatureFileContents", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.SignatureFileContents = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("TrackingNumber", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.TrackingNumber = unmarshaller.Unmarshall(context);
                        continue;
                    }
                }
            }

            return;
        }
コード例 #21
0
 /// <summary>
 /// Get the status of your service
 /// </summary>
 /// <returns> GetStatusResponse object</returns>
 /// <param name="request"> GetStatusRequest object</param>
 /// <param name='jsonRpcCallId'>
 /// The json rpc call identifier. This is a string generated by the client, which can be used to correlate the response to the request. Max length is 256 characters. A JSON-RPC id must be generated on a per call invocation basis. The Rogerthat platform uses the id of the call to store the call result for a certain amount of time so that if something fails during the communication, the same call (having the same JSON-RPC id) can be resent to the Rogerthat service, allowing to fetch the result, without actually executing the call again. This avoids annoying problems such as duplicate delivery of messages.
 /// 
 /// You should use a different JSON-RPC id for every call you make.
 /// 
 /// In case of an intermittent failure such as a network connectivity problem, you can retry the same call using the same JSON-RPC id, without running the risk of duplicate execution of your call (e.g. duplicate message delivery).
 /// </param>
 public GetStatusResponse GetStatus(GetStatusRequest request, string jsonRpcCallId)
 {
     GetStatusResponse result = new GetStatusResponse();
     WireRequest(0, jsonRpcCallId, "system.get_status", (writer) =>
         {
             request.Write(writer, false);
         }, (reader) =>
         {
             result.Read(reader);
         }
     );
     return result;
 }
コード例 #22
0
        private static void UnmarshallResult(XmlUnmarshallerContext context, GetStatusResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth += 2;
            }

            while (context.Read())
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("JobId", targetDepth))
                    {
                        response.JobId = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("JobType", targetDepth))
                    {
                        response.JobType = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("AwsShippingAddress", targetDepth))
                    {
                        response.AwsShippingAddress = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("LocationCode", targetDepth))
                    {
                        response.LocationCode = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("LocationMessage", targetDepth))
                    {
                        response.LocationMessage = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("ProgressCode", targetDepth))
                    {
                        response.ProgressCode = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("ProgressMessage", targetDepth))
                    {
                        response.ProgressMessage = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("Carrier", targetDepth))
                    {
                        response.Carrier = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("TrackingNumber", targetDepth))
                    {
                        response.TrackingNumber = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("LogBucket", targetDepth))
                    {
                        response.LogBucket = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("LogKey", targetDepth))
                    {
                        response.LogKey = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("ErrorCount", targetDepth))
                    {
                        response.ErrorCount = IntUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("Signature", targetDepth))
                    {
                        response.Signature = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("SignatureFileContents", targetDepth))
                    {
                        response.SignatureFileContents = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("CurrentManifest", targetDepth))
                    {
                        response.CurrentManifest = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("CreationDate", targetDepth))
                    {
                        response.CreationDate = DateTimeUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return;
                }
            }



            return;
        }
コード例 #23
0
        /// <summary>
        ///     Handles incoming messages.
        /// </summary>
        /// <param name="sender">The <see cref="IMessageConnection"/> instance from which the message originated.</param>
        /// <param name="message">The message.</param>
        public async void HandleMessage(object sender, byte[] message)
        {
            var code = new MessageReader <MessageCode.Server>(message).ReadCode();

            Diagnostic.Debug($"Server message received: {code}");

            try
            {
                switch (code)
                {
                case MessageCode.Server.ParentMinSpeed:
                case MessageCode.Server.ParentSpeedRatio:
                case MessageCode.Server.WishlistInterval:
                    SoulseekClient.Waiter.Complete(new WaitKey(code), IntegerResponse.FromByteArray <MessageCode.Server>(message));
                    break;

                case MessageCode.Server.Login:
                    SoulseekClient.Waiter.Complete(new WaitKey(code), LoginResponse.FromByteArray(message));
                    break;

                case MessageCode.Server.RoomList:
                    SoulseekClient.Waiter.Complete(new WaitKey(code), RoomList.FromByteArray(message));
                    break;

                case MessageCode.Server.PrivilegedUsers:
                    SoulseekClient.Waiter.Complete(new WaitKey(code), PrivilegedUserList.FromByteArray(message));
                    break;

                case MessageCode.Server.NetInfo:
                    var netInfo = NetInfo.FromByteArray(message);

                    try
                    {
                        await SoulseekClient.DistributedConnectionManager.AddParentConnectionAsync(netInfo.Parents).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Debug($"Error handling NetInfo message: {ex.Message}");
                    }

                    break;

                case MessageCode.Server.ConnectToPeer:
                    ConnectToPeerResponse connectToPeerResponse = default;

                    try
                    {
                        connectToPeerResponse = ConnectToPeerResponse.FromByteArray(message);

                        if (connectToPeerResponse.Type == Constants.ConnectionType.Transfer)
                        {
                            // ensure that we are expecting at least one file from this user before we connect. the response
                            // doesn't contain any other identifying information about the file.
                            if (!SoulseekClient.Downloads.IsEmpty && SoulseekClient.Downloads.Values.Any(d => d.Username == connectToPeerResponse.Username))
                            {
                                var(connection, remoteToken) = await SoulseekClient.PeerConnectionManager.GetTransferConnectionAsync(connectToPeerResponse).ConfigureAwait(false);

                                var download = SoulseekClient.Downloads.Values.FirstOrDefault(v => v.RemoteToken == remoteToken && v.Username == connectToPeerResponse.Username);

                                if (download != default(Transfer))
                                {
                                    SoulseekClient.Waiter.Complete(new WaitKey(Constants.WaitKey.IndirectTransfer, download.Username, download.Filename, download.RemoteToken), connection);
                                }
                            }
                            else
                            {
                                throw new SoulseekClientException($"Unexpected transfer request from {connectToPeerResponse.Username} ({connectToPeerResponse.IPAddress}:{connectToPeerResponse.Port}); Ignored");
                            }
                        }
                        else if (connectToPeerResponse.Type == Constants.ConnectionType.Peer)
                        {
                            await SoulseekClient.PeerConnectionManager.GetOrAddMessageConnectionAsync(connectToPeerResponse).ConfigureAwait(false);
                        }
                        else if (connectToPeerResponse.Type == Constants.ConnectionType.Distributed)
                        {
                            await SoulseekClient.DistributedConnectionManager.AddChildConnectionAsync(connectToPeerResponse).ConfigureAwait(false);
                        }
                        else
                        {
                            throw new MessageException($"Unknown Connect To Peer connection type '{connectToPeerResponse.Type}'");
                        }
                    }
                    catch (Exception ex)
                    {
                        Diagnostic.Debug($"Error handling ConnectToPeer response from {connectToPeerResponse?.Username} ({connectToPeerResponse?.IPAddress}:{connectToPeerResponse.Port}): {ex.Message}");
                    }

                    break;

                case MessageCode.Server.AddUser:
                    var addUserResponse = AddUserResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, addUserResponse.Username), addUserResponse);
                    break;

                case MessageCode.Server.GetStatus:
                    var statsResponse = GetStatusResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, statsResponse.Username), statsResponse);
                    UserStatusChanged?.Invoke(this, new UserStatusChangedEventArgs(statsResponse));
                    break;

                case MessageCode.Server.PrivateMessage:
                    var pm = PrivateMessage.FromByteArray(message);
                    PrivateMessageReceived?.Invoke(this, pm);

                    if (SoulseekClient.Options.AutoAcknowledgePrivateMessages)
                    {
                        await SoulseekClient.AcknowledgePrivateMessageAsync(pm.Id, CancellationToken.None).ConfigureAwait(false);
                    }

                    break;

                case MessageCode.Server.GetPeerAddress:
                    var peerAddressResponse = GetPeerAddressResponse.FromByteArray(message);
                    SoulseekClient.Waiter.Complete(new WaitKey(code, peerAddressResponse.Username), peerAddressResponse);
                    break;

                default:
                    Diagnostic.Debug($"Unhandled server message: {code}; {message.Length} bytes");
                    break;
                }
            }
            catch (Exception ex)
            {
                Diagnostic.Warning($"Error handling server message: {code}; {ex.Message}", ex);
            }
        }
コード例 #24
0
        private async Task <GetStatusResponse> GetContextStatus(GetStatusRequest requestItem)
        {
            if (string.IsNullOrEmpty(requestItem.Context) || string.IsNullOrEmpty(requestItem.Nonce))
            {
                return(null);
            }

            var cacheItem = await _cacheItemRepository.GetAsync(requestItem.Context, false);

            if (cacheItem == null || cacheItem.Nonce != requestItem.Nonce || cacheItem.Status == CacheItemStatus.Popped)
            {
                return(null);
            }

            var result = new GetStatusResponse
            {
                Status  = cacheItem.Status,
                Context = requestItem.Context
            };

            if (cacheItem.SecurityCode != null && cacheItem.Status == CacheItemStatus.WaitingForApproval)
            {
                // TODO: refactor to entity
                result.Payload = new
                {
                    data = new
                    {
                        pin = cacheItem.SecurityCode
                    }
                }
            }
            ;

            if (cacheItem.Status != CacheItemStatus.Finished)
            {
                return(result);
            }

            await _cacheItemRepository.UpdateAsync(cacheItem.Context,
                                                   item => { item.Status = CacheItemStatus.Popped; });

            if (!string.IsNullOrEmpty(cacheItem.Error))
            {
                result.Payload = new AuthResult <object>(_localizationService.GetLocalizedString(cacheItem.Error));
                return(result);
            }

            var action = cacheItem.ChallengeType.ToString();

            if (cacheItem.FlowType == FlowType.Authorize)
            {
                result.Payload = await _userHandlerAdapter.OnSuccessLoginAsync(cacheItem.DID, cacheItem.PublicKey);
            }
            else
            {
                switch (cacheItem.ChallengeType)
                {
                case ChallengeType.Login
                    when cacheItem.FlowType == FlowType.Fido2Login &&
                    string.IsNullOrWhiteSpace(cacheItem.Fido2CredentialId):
                {
                    var errorMessage = _localizationService.GetLocalizedString("Error_UserNotFound");
                    result.Payload = new AuthResult <object>(errorMessage);
                    break;
                }

                case ChallengeType.Login
                    when !string.IsNullOrWhiteSpace(cacheItem.Fido2CredentialId) &&
                    cacheItem.Fido2SignatureCounter.HasValue:
                {
                    result.Payload = await _userHandlerAdapter.OnSuccessLoginByFido2Async(
                        cacheItem.Fido2CredentialId,
                        cacheItem.Fido2SignatureCounter.Value);

                    break;
                }

                case ChallengeType.Login:
                    result.Payload = await _userHandlerAdapter.OnSuccessLoginByPublicKeyAsync(cacheItem.PublicKey);

                    break;

                case ChallengeType.LinkOnLogin:
                    action         = ChallengeType.Link.ToString();
                    result.Payload = SetPartialRegisterResult(cacheItem);
                    break;

                case ChallengeType.Register
                    when await _userHandlerAdapter.IsUserExistsAsync(cacheItem.PublicKey):
                {
                    var errorMessage = _localizationService.GetLocalizedString("Error_PhoneAlreadyConnected");
                    result.Payload = new AuthResult <object>(errorMessage);
                    return(result);
                }

                case ChallengeType.Register
                    when string.IsNullOrWhiteSpace(cacheItem.Fido2CredentialId):
                {
                    result.Payload = SetPartialRegisterResult(cacheItem);
                    break;
                }

                case ChallengeType.Register:
                    result.Payload = new
                    {
                        data = new
                        {
                            pubKey = cacheItem.PublicKey,
                            fido2SignatureCounter = cacheItem.Fido2SignatureCounter.ToString(),
                            fido2CredentialId     = cacheItem.Fido2CredentialId
                        }
                    };
                    if (cacheItem.InitialChallengeType == ChallengeType.Login &&
                        cacheItem.ChallengeType == ChallengeType.Register)
                    {
                        action = ChallengeType.Link.ToString();
                    }
                    break;

                //
                // TODO: fix needed at web-ui-sdk to avoid error in console if data is undefined
                //
                case ChallengeType.Recover:
                case ChallengeType.Link:
                    result.Payload = new
                    {
                        data = new { }
                    };
                    break;
                }
            }

            result.Metadata = _jwtService.GenerateDataJwt(new Dictionary <string, object>
            {
                {
                    "data", new
                    {
                        action,
                        authType = cacheItem.GetAuthType()
                    }
                }
            });

            return(result);
        }
コード例 #25
0
 private static HealthInfo Healthy(GetStatusResponse response)
 {
     return(new HealthInfo(HealthStatus.Healthy, response.Details));
 }
コード例 #26
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="UserStatusChangedEventArgs"/> class.
 /// </summary>
 /// <param name="getStatusResponse">The status response which generated the event.</param>
 public UserStatusChangedEventArgs(GetStatusResponse getStatusResponse)
 {
     Username   = getStatusResponse.Username;
     Status     = getStatusResponse.Status;
     Privileged = getStatusResponse.Privileged;
 }