public void RcpMethod_ExistingVoidMethod_Invoked()
        {
            // ARRANGE
            var jsonRpcMethodRequest = new JsonRpcRequest
            {
                Id     = 1,
                Method = "TestMethod",
                Params = new List <string>()
            };
            var     jsonRpcMethod = jsonRpcMethodRequest.ToString();
            JObject result        = null;

            _webSocketMock.Setup(m => m.SendAsync(It.IsAny <string>()))
            .Returns(Task.CompletedTask)
            .Callback((string s) =>
            {
                _webSocketMock.Setup(m => m.WebSocketState).Returns(JsonRpcWebSocketState.Closed);
                result = JObject.Parse(s);
            });

            _webSocketMock.Setup(
                m => m.ReceiveAsync(CancellationToken.None))
            .Returns(() =>
                     Task.FromResult((MessageType.Text, new ArraySegment <byte>(Encoding.UTF8.GetBytes(jsonRpcMethod)))));


            // ACT
            _webSocketConnection.HandleMessagesAsync(_webSocketMock.Object, CancellationToken.None)
            .Wait(100);

            // ASSERT
            Assert.That(_webSocketService.MethodsInvoked, Contains.Item("TestMethod"));
            Assert.That(result, Is.Not.Null);
            Assert.That(jsonRpcMethodRequest.Id, Is.EqualTo(result["id"].Value <int>()));
        }
Exemple #2
0
        private async Task <JsonRpcResponse> SendJsonRpcAsync(JsonRpcRequest request, CancellationToken cancellationToken)
        {
            // Send request to server:
            String response = await m_resolver.CallAsync(cancellationToken,
                                                         async (ep, ct) => await s_httpClient.GetStringAsync(ep + $"?jsonrpc={request.ToString()}").WithCancellation(cancellationToken).ConfigureAwait(false));

            // Get response from server:
            return(JsonRpcResponse.Parse(response));
        }
Exemple #3
0
        public JsonRpcResponse <T> MakeRequest <T>(string rpcMethod, object parameters, string id = "KodiJSON-RPC", int timeout = 50000)
        {
            var jsonRpcRequest = new JsonRpcRequest
            {
                Id         = id,
                Method     = rpcMethod,
                Parameters = parameters
            };

            if (Convert.ToBoolean(ConfigurationManager.AppSettings["Debug"]))
            {
                Console.WriteLine(jsonRpcRequest.ToString());
            }

            var res = _service.Host.Contains("http://") ? _service.Host : "http://" + _service.Host;
            var uri = $"{res}:{_service.Port}/jsonrpc";

            var webRequest = (HttpWebRequest)WebRequest.Create(uri);

            webRequest.ContentType = "application/json-rpc";
            webRequest.KeepAlive   = false;
            webRequest.Method      = "POST";
            webRequest.Timeout     = timeout;
            webRequest.Credentials = new NetworkCredential(_service.Username, _service.Password);

            try
            {
                using (var requestStream = webRequest.GetRequestStream())
                {
                    using (var requestWriter = new StreamWriter(requestStream))
                    {
                        requestWriter.Write(jsonRpcRequest.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                throw new RpcException("There was a problem sending the request to Kodi.", e);
            }

            try
            {
                string json;

                using (var webResponse = webRequest.GetResponse())
                {
                    using (var responseStream = webResponse.GetResponseStream())
                    {
                        if (responseStream == null)
                        {
                            throw new RpcException("Response stream is empty.");
                        }

                        using (var responseReader = new StreamReader(responseStream, Encoding.UTF8))
                        {
                            json = responseReader.ReadToEnd();
                        }
                    }
                }

                var rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json);

                if (rpcResponse.Error == null)
                {
                    return(rpcResponse);
                }

                var internalServerErrorException = new RpcInternalServerErrorException(rpcResponse.Error)
                {
                    RpcErrorCode = rpcResponse.Error.Code
                };

                throw internalServerErrorException;
            }
            catch (WebException e)
            {
                var webResponse = e.Response as HttpWebResponse;

                if (webResponse != null)
                {
                    switch (webResponse.StatusCode)
                    {
                    case HttpStatusCode.InternalServerError:
                    {
                        using (var stream = webResponse.GetResponseStream())
                        {
                            if (stream == null)
                            {
                                throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", e);
                            }

                            using (var reader = new StreamReader(stream))
                            {
                                var result = reader.ReadToEnd();
                                reader.Dispose();

                                try
                                {
                                    var jsonRpcResponseObject = JsonConvert.DeserializeObject <JsonRpcResponse <object> >(result);

                                    var internalServerErrorException = new RpcInternalServerErrorException(jsonRpcResponseObject.Error.Message, e)
                                    {
                                        RpcErrorCode = jsonRpcResponseObject.Error.Code
                                    };

                                    throw internalServerErrorException;
                                }
                                catch (JsonException)
                                {
                                    throw new RpcException(result, e);
                                }
                            }
                        }
                    }

                    default:
                        throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", e);
                    }
                }

                if (e.Message == "The operation has timed out")
                {
                    throw new RpcRequestTimeoutException(e.Message);
                }

                throw new RpcException("An unknown web exception occured while trying to read the JSON response", e);
            }
            catch (JsonException e)
            {
                throw new RpcResponseDeserializationException(
                          "There was a problem deserializing the response from Kodi.", e);
            }
            catch (ProtocolViolationException e)
            {
                throw new RpcException("Unable to connect to the server.", e);
            }
            catch (Exception e)
            {
                throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method} with request object {jsonRpcRequest}:  \nException: {e.Message}"); // with parameters: {qryParams}. \nException: {e.Message}");
            }
        }