async Task <InitializeResult> Initialize()
        {
            Log("Sending '{0}' message.", Methods.InitializeName);

            var message = CreateInitializeParams(client, rootPath);

            InitializeResult result = null;

            try {
                result = await jsonRpc.InvokeWithParameterObjectAsync(Methods.Initialize, message);

                await client.OnServerInitializedAsync();
            } catch (Exception ex) {
                await client.OnServerInitializeFailedAsync(ex);

                throw;
            }

            try {
                Log("Sending '{0}' message.", Methods.InitializedName);

                await jsonRpc.NotifyWithParameterObjectAsync(Methods.Initialized, new InitializedParams());
            } catch (Exception ex) {
                LogError("Sending Initialized notification to server failed.", ex);
            }

            Log("Initialized.", Id);

            return(result);
        }
Пример #2
0
        async Task <object> RequestCompletionsInternal(CompletionParams completionParams, CancellationToken token)
        {
            SumType <CompletionItem[], CompletionList>?result =
                await jsonRpc.InvokeWithParameterObjectAsync(Methods.TextDocumentCompletion, completionParams, token);

            if (result == null)
            {
                return(null);
            }

            return(result.Value.Match <object> (
                       completionItems => completionItems,
                       completionList => completionList));
        }
Пример #3
0
 /// <summary>
 /// Called when we want to update a client's volume on snapserver
 /// </summary>
 /// <param name="id">client id</param>
 /// <param name="volume">new volume object</param>
 private async Task _SetClientVolumeAsync(string id, Volume volume)
 {
     Debug("Sending Client.SetVolume - id {0}, volume {1}", id, volume);
     ClientVolumeCommandResult result =
         await m_JsonRpc.InvokeWithParameterObjectAsync<ClientVolumeCommandResult>("Client.SetVolume",
             new ClientVolumeCommand() {id = id, volume = volume}); // update the server
     _ClientVolumeChanged(id, result.volume); // update our local data to reflect the new value
 }
Пример #4
0
        /// <summary>
        /// RPCに接続する
        /// </summary>
        /// <param name="ws">WebSocket</param>
        /// <returns></returns>
        private async Task ConnectRpcAsync(ClientWebSocket ws)
        {
            Rpc = new JsonRpc(new WebSocketMessageHandler(ws));

            Rpc.Disconnected += (s, e) =>
            {
                // 切断されたときの処理
                if (Logger != null)
                {
                    Logger.LogWarning($"切断されました {ToString()}");
                    isWebSocketConnected = false;
                    var t = RunAsync();
                }
            };
            Rpc.AddLocalRpcMethod(ChannelMessage, new Action <JToken, CancellationToken>((@params, cancellationToken) =>
            {
                // 受信したときの処理
                var p = @params as dynamic;

                // 受信したメッセージ(json)をイベントに送る
                OnGetMessage(new TextEventArgs(p.message.ToString()));
            }));

            Rpc.StartListening();

            await Rpc.InvokeWithParameterObjectAsync <object>("subscribe", new { channel = ChannelName });
        }
        public async Task <bool> ConnectAsync(Uri ownerUri, string connectionStr)
        {
            var connectionOptions = new Dictionary <string, string>();

            connectionOptions.Add("ConnectionString", connectionStr);

            var connectionDetails = new ConnectionDetails()
            {
                Options = connectionOptions
            };
            var connectionParams = new ConnectParams()
            {
                OwnerUri = ownerUri.ToString(), Connection = connectionDetails
            };

            return(await _rpc.InvokeWithParameterObjectAsync <bool>("connection/connect", connectionParams));
        }
Пример #6
0
 public static Task <TResult> InvokeWithParameterObjectAsync <TArgument, TResult> (
     this JsonRpc jsonRpc,
     LspRequest <TArgument, TResult> request,
     TArgument argument,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return(jsonRpc.InvokeWithParameterObjectAsync <TResult> (request.Name, argument, cancellationToken));
 }
Пример #7
0
        private async Task <R> InvokeWithParametersAsync <R>(string request, object parameters, CancellationToken t) where R : class
        {
            await _readyTcs.Task.ConfigureAwait(false);

            if (_rpc != null)
            {
                return(await _rpc.InvokeWithParameterObjectAsync <R>(request, parameters, t).ConfigureAwait(false));
            }
            return(null);
        }
Пример #8
0
        public Task <MessageActionItem?> ShowMessage(string message, MessageActionItem[] actions, MessageType messageType)
        {
            var parameters = new ShowMessageRequestParams {
                type    = messageType,
                message = message,
                actions = actions
            };

            return(_rpc.InvokeWithParameterObjectAsync <MessageActionItem?>("window/showMessageRequest", parameters));
        }
Пример #9
0
 //---------------------------------------------------------------------------------
 /// <summary>
 /// Get all of the stacks available in the current location
 /// </summary>
 //---------------------------------------------------------------------------------
 public StackInfo[] GetStacks()
 {
     return(DoRpcCall(() =>
     {
         var requestParams = new NonStackRequestParams(Directory.GetCurrentDirectory());
         var result = _server.InvokeWithParameterObjectAsync <StackInfoRequestResponse>("getStackInfoFromFilePath", requestParams).Result;
         return result.StackInfo.ToArray();
     }));
 }
Пример #10
0
        public async Task <string> ShowMessageAsync(string message, string[] actions, TraceEventType eventType)
        {
            var parameters = new ShowMessageRequestParams {
                type    = eventType.ToMessageType(),
                message = message,
                actions = actions.Select(a => new MessageActionItem {
                    title = a
                }).ToArray()
            };
            var result = await _rpc.InvokeWithParameterObjectAsync <MessageActionItem?>("window/showMessageRequest", parameters);

            return(result?.title);
        }
Пример #11
0
        public async Task <MessageActionItem> ShowMessageRequestAsync(string message, MessageType messageType, string[] actionItems)
        {
            ShowMessageRequestParams parameter = new ShowMessageRequestParams
            {
                Message = message,
                Type    = (int)messageType,
                Actions = actionItems.Select(a => new MessageActionItem {
                    Title = a
                }).ToArray()
            };
            JToken response = await rpc.InvokeWithParameterObjectAsync <JToken>(Methods.WindowShowMessageRequestName, parameter).ConfigureAwait(false);;

            return(response.ToObject <MessageActionItem>());
        }
        public async Task <string[]> GetExpansionsAsync(
            string line,
            string lastWord,
            CancellationToken token)
        {
            var message = new TabExpansionParams {
                Line     = line,
                LastWord = lastWord
            };
            TabExpansionResult result = await rpc.InvokeWithParameterObjectAsync <TabExpansionResult> (
                Methods.TabExpansionName,
                message,
                token);

            return(result.Expansions);
        }
Пример #13
0
        /// <summary>
        /// Executes the asynchronous on a different thread, and waits for the result.
        /// </summary>
        /// <remarks> 19.09.2020. </remarks>
        /// <exception cref="ClientNotConnectedException"> Thrown when a Client Not Connected error
        ///                                                condition occurs. </exception>
        /// <typeparam name="T"> Generic type parameter. </typeparam>
        /// <param name="method">     The method. </param>
        /// <param name="parameters"> Options for controlling the operation. </param>
        /// <param name="token">      A token that allows processing to be cancelled. </param>
        /// <returns> A T. </returns>
        internal async Task <T> InvokeAsync <T>(string method, object parameters, CancellationToken token)
        {
            if (_socket?.State != WebSocketState.Open)
            {
                throw new ClientNotConnectedException($"WebSocketState is not open! Currently {_socket?.State}!");
            }

            Logger.Debug($"Invoking request[{method}, params: {parameters}] {MetaData?.Origin}");

            _requestTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
            var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, _requestTokenSource.Token);
            var resultString      = await _jsonRpc.InvokeWithParameterObjectAsync <T>(method, parameters, linkedTokenSource.Token);

            linkedTokenSource.Dispose();
            _requestTokenSource.Dispose();
            _requestTokenSource = null;
            return(resultString);
        }
Пример #14
0
        private Task <T> SendCoreAsync <T>(string name, object arguments, CancellationToken?cancellationToken = null)
        {
            cancellationToken = cancellationToken ?? CancellationToken.None;
            try {
                // the arguments might have sensitive data in it -- don't include arguments here
                using (Log.CriticalOperation($"name=REQ,Method={name}")) {
                    return(_rpc.InvokeWithParameterObjectAsync <T>(name, arguments, cancellationToken.Value));
                }
            }
            catch (ObjectDisposedException ex) {
                Log.Fatal(ex, "SendName={Name}", name);
#if DEBUG
                Log.Verbose($"Arguments={(arguments != null ? arguments.ToJson(true) : null)}");
#endif
                throw;
            }
            catch (Exception ex) {
                Log.Fatal(ex, "SendName={Name}", name);
                throw;
            }
        }
        public async Task SendMessageToServer()
        {
            string text = await rpc.InvokeWithParameterObjectAsync <string>("GetText");

            MessageService.ShowMessage("Text from language server:", text);
        }
Пример #16
0
        private async static Task OfferAsync(IHttpContext context)
        {
            var offer = await context.GetRequestDataAsync <RTCSessionDescriptionInit>();

            logger.LogDebug($"SDP Offer={offer.sdp}");

            var jsonOptions = new JsonSerializerOptions();

            jsonOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());

            CancellationTokenSource cts = new CancellationTokenSource();

            var ws = new ClientWebSocket();
            await ws.ConnectAsync(new Uri(KURENTO_JSONRPC_URL), cts.Token);

            logger.LogDebug($"Successfully connected web socket client to {KURENTO_JSONRPC_URL}.");

            try
            {
                using (var jsonRpc = new JsonRpc(new WebSocketMessageHandler(ws)))
                {
                    jsonRpc.AddLocalRpcMethod("ping", new Action(() =>
                    {
                        logger.LogDebug($"Ping received");
                    }
                                                                 ));

                    jsonRpc.AddLocalRpcMethod("onEvent", new Action <KurentoEvent>((evt) =>
                    {
                        logger.LogDebug($"Event received type={evt.type}, source={evt.data.source}");
                    }
                                                                                   ));

                    jsonRpc.StartListening();

                    // Check the server is there.
                    var pingResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.ping.ToString(),
                        new { interval = KEEP_ALIVE_INTERVAL_MS },
                        cts.Token);

                    logger.LogDebug($"Ping result={pingResult.value}.");

                    // Create a media pipeline.
                    var createPipelineResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.create.ToString(),
                        new { type = "MediaPipeline" },
                        cts.Token);

                    logger.LogDebug($"Create media pipeline result={createPipelineResult.value}, sessionID={createPipelineResult.sessionId}.");

                    var sessionID     = createPipelineResult.sessionId;
                    var mediaPipeline = createPipelineResult.value;

                    // Create a WebRTC end point.
                    var createEndPointResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.create.ToString(),
                        new
                    {
                        type = "WebRtcEndpoint",
                        constructorParams = new { mediaPipeline = mediaPipeline },
                        sessionId         = sessionID
                    },
                        cts.Token);

                    logger.LogDebug($"Create WebRTC endpoint result={createEndPointResult.value}.");

                    var webRTCEndPointID = createEndPointResult.value;

                    // Connect the WebRTC end point to itself to create a loopback connection (no result for this operation).
                    await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.invoke.ToString(),
                        new
                    {
                        @object         = webRTCEndPointID,
                        operation       = "connect",
                        operationParams = new { sink = webRTCEndPointID },
                        sessionId       = sessionID
                    },
                        cts.Token);

                    // Subscribe for events from the WebRTC end point.
                    var subscribeResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.subscribe.ToString(),
                        new
                    {
                        @object   = webRTCEndPointID,
                        type      = "IceCandidateFound",
                        sessionId = sessionID
                    },
                        cts.Token);

                    logger.LogDebug($"Subscribe to WebRTC endpoint subscription ID={subscribeResult.value}.");

                    var subscriptionID = subscribeResult.value;

                    subscribeResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.subscribe.ToString(),
                        new
                    {
                        @object   = webRTCEndPointID,
                        type      = "OnIceCandidate",
                        sessionId = sessionID
                    },
                        cts.Token);

                    logger.LogDebug($"Subscribe to WebRTC endpoint subscription ID={subscribeResult.value}.");

                    // Send SDP offer.
                    var processOfferResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.invoke.ToString(),
                        new
                    {
                        @object         = webRTCEndPointID,
                        operation       = "processOffer",
                        operationParams = new { offer = offer.sdp },
                        sessionId       = sessionID
                    },
                        cts.Token);

                    logger.LogDebug($"SDP answer={processOfferResult.value}.");

                    RTCSessionDescriptionInit answerInit = new RTCSessionDescriptionInit
                    {
                        type = RTCSdpType.answer,
                        sdp  = processOfferResult.value
                    };

                    context.Response.ContentType = "application/json";
                    using (var responseStm = context.OpenResponseStream(false, false))
                    {
                        await JsonSerializer.SerializeAsync(responseStm, answerInit, jsonOptions);
                    }

                    // Tell Kurento to start ICE.
                    var gatherCandidatesResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.invoke.ToString(),
                        new
                    {
                        @object   = webRTCEndPointID,
                        operation = "gatherCandidates",
                        sessionId = sessionID
                    },
                        cts.Token);

                    logger.LogDebug($"Gather candidates result={gatherCandidatesResult.value}.");
                }
            }
            catch (RemoteInvocationException invokeExcp)
            {
                logger.LogError($"JSON RPC invoke exception, error code={invokeExcp.ErrorCode}, msg={invokeExcp.Message}.");
            }
        }
Пример #17
0
 public static async Task <EntityServiceResult> MakeCall(JsonRpc jsonRpc, int startIndex, int pageSize, int sortOption, string sortColumnName)
 {
     return(await jsonRpc.InvokeWithParameterObjectAsync <EntityServiceResult>("CallEntityService", new EntityServiceRequest("CampaignService", "GetEntities", new object[] { startIndex, pageSize, sortOption, sortColumnName })));
 }
Пример #18
0
 public static async Task <EntityServiceResult> MakeCall(JsonRpc jsonRpc)
 {
     return(await jsonRpc.InvokeWithParameterObjectAsync <EntityServiceResult>("CallEntityService", new EntityServiceRequest("CampaignService", "GetCount", null)));
 }
Пример #19
0
 Task <object> ExecuteCommandInternal(ExecuteCommandParams executeCommandParams)
 {
     return(jsonRpc.InvokeWithParameterObjectAsync(Methods.WorkspaceExecuteCommand, executeCommandParams));
 }
Пример #20
0
 public Task <string[]> GetFileContentInMemoryAsync(string filename) =>
 rpc.InvokeWithParameterObjectAsync <string[]>(
     Methods.WorkspaceExecuteCommand.Name,
     TestUtils.ServerCommand(CommandIds.FileContentInMemory, TestUtils.GetTextDocumentIdentifier(filename)));
            public async Task <ResponseType?> ExecuteRequestAsync <RequestType, ResponseType>(string methodName, RequestType request, CancellationToken cancellationToken) where RequestType : class
            {
                var result = await _clientRpc.InvokeWithParameterObjectAsync <ResponseType>(methodName, request, cancellationToken : cancellationToken).ConfigureAwait(false);

                return(result);
            }
Пример #22
0
 Task <SymbolInformation[]> RequestWorkspaceSymbolsInternal(WorkspaceSymbolParams param, CancellationToken token)
 {
     return(jsonRpc.InvokeWithParameterObjectAsync(Methods.WorkspaceSymbol, param, token));
 }
Пример #23
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Kurento Echo Test Client");
            logger = AddConsoleLogger();

            CancellationTokenSource cts = new CancellationTokenSource();

            var ws = new ClientWebSocket();
            await ws.ConnectAsync(new Uri(KURENTO_JSONRPC_URL), cts.Token);

            logger.LogDebug($"Successfully connected web socket client to {KURENTO_JSONRPC_URL}.");

            try
            {
                using (var jsonRpc = new JsonRpc(new WebSocketMessageHandler(ws)))
                {
                    jsonRpc.AddLocalRpcMethod("ping", new Action(() =>
                    {
                        logger.LogDebug($"Ping received");
                    }
                                                                 ));

                    jsonRpc.AddLocalRpcMethod("onEvent", new Action <KurentoEvent>((evt) =>
                    {
                        logger.LogDebug($"Event received type={evt.type}, source={evt.data.source}");
                    }
                                                                                   ));

                    jsonRpc.StartListening();

                    // Check the server is there.
                    var pingResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.ping.ToString(),
                        new { interval = KEEP_ALIVE_INTERVAL_MS },
                        cts.Token);

                    logger.LogDebug($"Ping result={pingResult.value}.");

                    // Create a media pipeline.
                    var createPipelineResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.create.ToString(),
                        new { type = "MediaPipeline" },
                        cts.Token);

                    logger.LogDebug($"Create media pipeline result={createPipelineResult.value}, sessionID={createPipelineResult.sessionId}.");

                    var sessionID     = createPipelineResult.sessionId;
                    var mediaPipeline = createPipelineResult.value;

                    // Create a WebRTC end point.
                    var createEndPointResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.create.ToString(),
                        new
                    {
                        type = "WebRtcEndpoint",
                        constructorParams = new { mediaPipeline = mediaPipeline },
                        sessionId         = sessionID
                    },
                        cts.Token);

                    logger.LogDebug($"Create WebRTC endpoint result={createEndPointResult.value}.");

                    var webRTCEndPointID = createEndPointResult.value;

                    // Connect the WebRTC end point to itself to create a loopback connection (no result for this operation).
                    await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.invoke.ToString(),
                        new
                    {
                        @object         = webRTCEndPointID,
                        operation       = "connect",
                        operationParams = new { sink = webRTCEndPointID },
                        sessionId       = sessionID
                    },
                        cts.Token);

                    // Subscribe for events from the WebRTC end point.
                    var subscribeResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.subscribe.ToString(),
                        new
                    {
                        @object   = webRTCEndPointID,
                        type      = "IceCandidateFound",
                        sessionId = sessionID
                    },
                        cts.Token);

                    logger.LogDebug($"Subscribe to WebRTC endpoint subscription ID={subscribeResult.value}.");

                    var subscriptionID = subscribeResult.value;

                    subscribeResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.subscribe.ToString(),
                        new
                    {
                        @object   = webRTCEndPointID,
                        type      = "OnIceCandidate",
                        sessionId = sessionID
                    },
                        cts.Token);

                    logger.LogDebug($"Subscribe to WebRTC endpoint subscription ID={subscribeResult.value}.");

                    var pc    = CreatePeerConnection();
                    var offer = pc.createOffer(null);
                    await pc.setLocalDescription(offer);

                    // Send SDP offer.
                    var processOfferResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.invoke.ToString(),
                        new
                    {
                        @object         = webRTCEndPointID,
                        operation       = "processOffer",
                        operationParams = new { offer = offer.sdp },
                        sessionId       = sessionID
                    },
                        cts.Token);

                    logger.LogDebug($"SDP answer={processOfferResult.value}.");

                    var setAnswerResult = pc.setRemoteDescription(new RTCSessionDescriptionInit
                    {
                        type = RTCSdpType.answer,
                        sdp  = processOfferResult.value
                    });

                    logger.LogDebug($"Set WebRTC peer connection answer result={setAnswerResult}.");

                    // Tell Kurento to start ICE.
                    var gatherCandidatesResult = await jsonRpc.InvokeWithParameterObjectAsync <KurentoResult>(
                        KurentoMethodsEnum.invoke.ToString(),
                        new
                    {
                        @object   = webRTCEndPointID,
                        operation = "gatherCandidates",
                        sessionId = sessionID
                    },
                        cts.Token);

                    logger.LogDebug($"Gather candidates result={gatherCandidatesResult.value}.");

                    Console.ReadLine();
                }
            }
            catch (RemoteInvocationException invokeExcp)
            {
                logger.LogError($"JSON RPC invoke exception, error code={invokeExcp.ErrorCode}, msg={invokeExcp.Message}.");
            }
        }
 public Task <TResult> InvokeWithParameterObjectAsync <TResult>(string targetName, object argument = null, CancellationToken cancellationToken = default)
 => _rpc.InvokeWithParameterObjectAsync <TResult>(targetName, argument, cancellationToken);