public ProxyUsersCommunicationsNodeRequestHandler(NodeRequest request, NodeConnection current, IAppServiceProvider serviceProvider) { this.request = (ProxyUsersCommunicationsNodeRequest)request; this.current = current; clientRequestService = new ClientRequestService(serviceProvider.NoticeService); this.serviceProvider = serviceProvider; }
public BatchPhonesSearchNodeRequestHandler(NodeRequest request, NodeConnection current, ILoadUsersService loadUsersService, IPrivacyService privacyService) { this.request = (BatchPhonesSearchNodeRequest)request; this.current = current; this.loadUsersService = loadUsersService; this.privacyService = privacyService; }
public GetMessagesRequestHandler(NodeRequest request, NodeConnection current, ILoadMessagesService loadMessagesService, IConversationsService conversationsService) { this.request = (GetMessagesNodeRequest)request; this.current = current; this.loadMessagesService = loadMessagesService; this.conversationsService = conversationsService; }
public async Task <NodeKeysDto> GetNodePublicKeyAsync(NodeConnection nodeConnection, long?keyId = null) { NodeRequest nodeRequest = keyId == null ? new GetPublicKeyNodeRequest() : new GetPublicKeyNodeRequest(keyId.Value); SendRequest(nodeConnection, nodeRequest); try { NodeResponse response = await GetResponseAsync(nodeRequest).ConfigureAwait(false); switch (response.ResponseType) { case Enums.NodeResponseType.PublicKey: { PublicKeyNodeResponse nodeKeysResponse = (PublicKeyNodeResponse)response; return(new NodeKeysDto { NodeId = (nodeConnection.Node?.Id).GetValueOrDefault(), KeyId = nodeKeysResponse.KeyId, PublicKey = nodeKeysResponse.PublicKey, ExpirationTime = nodeKeysResponse.ExpirationTime, SignPublicKey = nodeKeysResponse.SignPublicKey }); } default: return(null); } } catch (ResponseException ex) { Logger.WriteLog(ex); return(null); } }
public async Task <NodeResponse> GetResponseAsync(NodeRequest request, int timeoutMilliseconds = 10 * 1000) { try { TaskCompletionSource <NodeResponse> taskCompletionSource = new TaskCompletionSource <NodeResponse>(TaskCreationOptions.RunContinuationsAsynchronously); NodeDataReceiver.ResponseTasks.AddOrUpdate(request.RequestId, taskCompletionSource, (value, newValue) => { return(newValue); }); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(timeoutMilliseconds); cancellationTokenSource.Token.ThrowIfCancellationRequested(); var responseWaitTask = Task.Factory.StartNew( () => taskCompletionSource.Task, cancellationTokenSource.Token, TaskCreationOptions.RunContinuationsAsynchronously, TaskScheduler.Current); var responseTask = await responseWaitTask.ConfigureAwait(false); if (await Task.WhenAny(responseTask, Task.Delay(timeoutMilliseconds)).ConfigureAwait(false) == responseTask) { var response = await responseTask.ConfigureAwait(false); return(response); } else { throw new ResponseException("Response timed out."); } } catch (TaskCanceledException) { throw new ResponseException("Response timed out."); } }
private async void SendRequestAsync(List <NodeConnection> nodes, NodeRequest request) { foreach (var node in nodes) { byte[] requestData = Array.Empty <byte>(); try { if (node.IsEncryptedConnection) { requestData = Encryptor.SymmetricDataEncrypt( ObjectSerializer.ObjectToByteArray(request), NodeData.Instance.NodeKeys.SignPrivateKey, node.SymmetricKey, MessageDataType.Request, NodeData.Instance.NodeKeys.Password); } else { requestData = ObjectSerializer.ObjectToByteArray(request); } await node.NodeWebSocket.SendAsync( requestData, WebSocketMessageType.Binary, true, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { Logger.WriteLog(ex, request); } } }
/////////////////////////////////////////////////////////////////////////////////////// private UnityWebRequest CreateWWWRequest(NodeRequest req) { var downloader = new DownloadHandlerBuffer(); var uploader = !req.data.Exists() ? null : new UploadHandlerRaw(req.data.ToUTF8()); var www = new UnityWebRequest(); //req.fullURL, req.method.ToUpper(), hDownload, hUpload); if (req.isJSON) { www.SetRequestHeader("Content-Type", "application/json"); } if (req.isAuth) { www.SetRequestHeader("Authorization", _authCodeB64); } www.url = req.fullURL; www.method = req.method.ToUpper(); www.downloadHandler = downloader; www.uploadHandler = uploader; req.www = www; return(www); }
/// <summary> /// The build requested no build service. /// </summary> /// <param name="nodeRequest"> /// The node request. /// </param> public void BuildRequestedNoBuildService(NodeRequest nodeRequest) { var name = MethodBase.GetCurrentMethod().Name; dynamic eventArgs = new DscEventArgs(name, this.GetMessageForMethod(name)); eventArgs.NodeRequest = nodeRequest; this.EventManager.CreateEvent(eventArgs); }
private void SendRequest(NodeConnection node, NodeRequest request) { try { SendRequestAsync(new List <NodeConnection> { node }, request); } catch (Exception ex) { Logger.WriteLog(ex); } }
private void VerifyResponse(UnityWebRequest www, NodeRequest req) { var promise = req.promise; var res = req.res; string text = www.downloadHandler.text; if (www.error.Exists()) { JSONNode errJSON = new JSONNode(); if (text.Exists() && text.StartsWith("{")) { errJSON = JSON.Parse(text); } NotifyError(req, www.error, text, errJSON); return; } if (!text.Exists()) { NotifyError(req, "Server did not respond any 'text' data."); return; } res.text = text; if (!text.StartsWith("{") && !text.StartsWith("[")) { NotifyError(req, "Response does not contain JSON data!", text); return; } if (!res.isJSON) { promise.Resolve(res); return; } JSONNode json; try { json = JSON.Parse(text); } catch (Exception err) { NotifyError(req, "Malformed JSON: " + err.Message); return; } res.json = json; promise.Resolve(res); }
public GetObjectsInfoNodeRequestHandler(NodeRequest request, NodeConnection nodeConnection, ILoadChatsService loadChatsService, ILoadUsersService loadUsersService, ILoadChannelsService loadChannelsService, IPrivacyService privacyService, IFilesService filesService) { this.request = (GetObjectsInfoNodeRequest)request; this.nodeConnection = nodeConnection; this.loadChatsService = loadChatsService; this.loadUsersService = loadUsersService; this.loadChannelsService = loadChannelsService; this.privacyService = privacyService; this.filesService = filesService; }
public void DoPush(IEnumerable <string> userIds, NodeRequest nodeRequest, DataAccess.WF_WORKFLOW_INST mainRow, IUnitOfData source) { //throw new NotImplementedException(); if (userIds == null || userIds.Count() == 0) { return; } var workflowSource = source as WorkflowDbContext; if (workflowSource == null) { return; } var workflowDefName = workflowSource.WF_WORKFLOW_DEF.FirstOrDefault(m => m.WD_SHORT_NAME == mainRow.WI_WD_NAME).WD_NAME; foreach (var userId in userIds) { var selectsql = string.Format("SELECT NickName FROM Ataw_Users WHERE UserID=@USERID"); var param = new SqlParameter("@USERID", userId); string nickName = source.QueryObject(selectsql, param).ToString(); SnsActiveService sns = new SnsActiveService(); sns.SetUnitOfData(source); string title = string.Format(ObjectUtil.SysCulture, "待处理流程到达:" + "<a class='ACT-A-HREF' href='$windefault$module/workflow/workflowDef$Detail${0}'>{1}</a>" + "<br/>" + "<a class='ACT-A-HREF' href='$winworkflow$inst$${2}'>{3}-{4}</a>", Convert.ToBase64String(Encoding.Default.GetBytes("{\"keys\":\"" + mainRow.WI_WD_NAME + "\"}")), workflowDefName, mainRow.WI_ID, mainRow.WI_NAME, mainRow.WI_CURRENT_STEP_NAME); sns.InsertActive(new ActiveModel() { ItemType = ActivityItemType.MyWork.ToString(), PrivacyStatus = PrivacyType.ToMyself.ToString(), SourceId = mainRow.WI_ID, SubContent = title, UserId = userId, UserName = nickName }); } source.ApplyFun.Add((tran) => { NodeServerPusher.Notify(userIds, null); return(0); }); }
private IEnumerator __Send() { while (_pendingRequests.Count > 0) { NodeRequest req = _currentRequest = _pendingRequests.Shift(); yield return(new WaitForEndOfFrame()); var www = CreateWWWRequest(req); if (www == null) { yield break; } yield return(www.Send()); VerifyResponse(www, req); } _currentRequest = null; }
public NodePromise SendAPI(string partURL, string queries = null, object jsonData = null, string method = "GET") { var req = new NodeRequest(); req.isJSON = true; req.isAuth = true; var res = req.res = new NodeResponse(); res.isJSON = true; res.req = req; //Support for Shortcut "HttpMethod::URL" url links: if (partURL.Contains("::")) { string[] partSplit = partURL.Split("::"); method = partSplit[0]; partURL = partSplit[1]; } return(Send(urlCurrent + partURL, queries, jsonData, method, req)); }
public async Task <IHttpActionResult> Post(string nodeName, Hashtable nodeData) { var node = await this.NodeRepository.Include(n => n.Roles).FindNodeByName(nodeName); var request = new NodeRequest { NodeName = nodeName, BuildMof = true, NodeData = nodeData }; this.Logging.BootstrapUpdateReceived(nodeName, nodeData); NodeDetailResult newNode; if (node == null) { newNode = await this.NodeService.CreateNode(request); } else { node.IncludeConfigurationProperties(this.Context); newNode = await this.NodeService.UpdateNode(request); } var map = new TypeMapping(typeof(NodeDetailResult), typeof(BootstrapResultView)); map.PropertyResolvers.Add( new DestinationMemberPropertyResolver <BootstrapResultView>( m => m.NodeData, () => newNode.NodeView.ToNodeData())); map.PropertyResolvers.Add( new DestinationMemberPropertyResolver <BootstrapResultView>(m => m.NodeName, () => nodeName)); map.PropertyResolvers.Add( new DestinationMemberPropertyResolver <BootstrapResultView>(m => m.Build, () => newNode.Build)); map.PropertyResolvers.Add(new DestinationMemberPropertyResolver <BootstrapResultView>(d => d.LocalAgentProperties, () => newNode.NodeView.LocalAgentProperties)); var view = map.Map(newNode.NodeView.BootstrapProperties) as BootstrapResultView; return(this.Ok(view)); }
private static void NotifyError(NodeRequest req, string errMessage, string text = null, JSONNode json = null) { //traceError("NodeJSManager - Error loading from URL: " + req.fullURL); var err = new NodeError(req.fullURL + " : " + errMessage); err.json = json; err.text = text; err.request = req; err.response = req.res; #if UNITY_EDITOR if (err.Message.Contains("Generic")) { traceError("Error Response: " + req.www.downloadHandler.text + "\n==========\n" + req.GetStackTrace() + "\n==========\n"); } else { traceError(err.Message + "\n" + req.GetStackTrace()); } #endif req.promise.Reject(err); }
public GetPollInformationNodeRequestHandler(NodeRequest request, NodeConnection current, IPollsService pollsService) { this.request = (GetPollInformationNodeRequest)request; this.current = current; this.pollsService = pollsService; }
public IPromise <NodeResponse> Send(string fullURL, string queries = null, object jsonData = null, string method = "GET", NodeRequest req = null) { req = req != null ? req : new NodeRequest(); req.promise = new Promise <NodeResponse>(); //Prepare the promise: var res = req.res != null ? req.res : new NodeResponse(); req.fullURL = fullURL; req.queries = queries; req.method = method; if (jsonData != null) { if (jsonData is string) { req.data = (string)jsonData; } else { req.data = JsonConvert.SerializeObject(jsonData); } req.isJSON = true; } //Bind the Request and Response to eachother: res.req = req; req.res = res; #if UNITY_EDITOR req.stackTrace = Environment.StackTrace; #endif _pendingRequests.Add(req); //If it's not busy on a current Request, process this one immediately if (_currentRequest == null) { StartCoroutine(__Send()); //Start the WWW request: } return(req.promise); }
private async void HandleRequest(NodeRequest request, NodeConnection current) { try { ICommunicationHandler requestHandler = null; switch (request.RequestType) { case NodeRequestType.CheckToken: { requestHandler = new CheckTokenRequestHandler(request, current, appServiceProvider.TokensService, appServiceProvider.LoadUsersService); } break; case NodeRequestType.Connect: { requestHandler = new ConnectRequestHandler( request, current, appServiceProvider.ConnectionsService, appServiceProvider.NodesService, appServiceProvider.NodeNoticeService); } break; case NodeRequestType.GetInfoBlocks: { requestHandler = new GetInfoBlocksRequestHandler(request, current); } break; case NodeRequestType.GetMessages: { requestHandler = new GetMessagesRequestHandler(request, current, appServiceProvider.LoadMessagesService, appServiceProvider.ConversationsService); } break; case NodeRequestType.Proxy: { requestHandler = new ProxyUsersCommunicationsNodeRequestHandler(request, current, appServiceProvider); } break; case NodeRequestType.GetUsers: case NodeRequestType.GetChats: case NodeRequestType.GetChannels: case NodeRequestType.GetFiles: { requestHandler = new GetObjectsInfoNodeRequestHandler(request, current, appServiceProvider.LoadChatsService, appServiceProvider.LoadUsersService, appServiceProvider.LoadChannelsService, appServiceProvider.PrivacyService, appServiceProvider.FilesService); } break; case NodeRequestType.Search: { requestHandler = new SearchNodeRequestHandler(request, current, appServiceProvider.LoadChatsService, appServiceProvider.LoadUsersService, appServiceProvider.LoadChannelsService, appServiceProvider.PrivacyService); } break; case NodeRequestType.GetFullChatInformation: { requestHandler = new GetFullChatInformationNodeRequestHandler(request, current, appServiceProvider.LoadChatsService); } break; case NodeRequestType.GetChatUsersInformation: { requestHandler = new GetChatUsersInformationNodeRequestHandler(request, current, appServiceProvider.LoadChatsService); } break; case NodeRequestType.GetPublicKey: { requestHandler = new GetPublicKeyNodeRequestHandler(request, current, appServiceProvider.KeysService); } break; case NodeRequestType.GetPolls: { requestHandler = new GetPollInformationNodeRequestHandler(request, current, appServiceProvider.PollsService); } break; case NodeRequestType.BatchPhonesSearch: { requestHandler = new BatchPhonesSearchNodeRequestHandler(request, current, appServiceProvider.LoadUsersService, appServiceProvider.PrivacyService); } break; case NodeRequestType.GetConversationsUsers: { requestHandler = new GetConversationsUsersNodeRequestHandler(request, current, appServiceProvider.LoadChannelsService, appServiceProvider.LoadChatsService); } break; } if (requestHandler.IsObjectValid()) { await requestHandler.HandleAsync().ConfigureAwait(false); } else { ResultNodeResponse response = new ResultNodeResponse(request.RequestId, ErrorCode.InvalidRequestData); SendResponse(response, current); } } catch (Exception ex) { Logger.WriteLog(ex); } }
/// <summary> /// The build requested no build service. /// </summary> /// <param name="nodeRequest"> /// The node request. /// </param> public void BuildRequestedNoBuildService(NodeRequest nodeRequest) { }
public void ManualCompletePush(string manualUserId, NodeRequest nodeRequest, DataAccess.WF_WORKFLOW_INST mainRow, IUnitOfData source) { // throw new NotImplementedException(); }
public GetPublicKeyNodeRequestHandler(NodeRequest request, NodeConnection current, IKeysService keysService) { this.request = (GetPublicKeyNodeRequest)request; this.current = current; this.keysService = keysService; }
public GetChatUsersInformationNodeRequestHandler(NodeRequest request, NodeConnection current, ILoadChatsService loadChatsService) { this.request = (GetChatUsersInformationNodeRequest)request; this.current = current; this.loadChatsService = loadChatsService; }
/// <summary> /// The update node. /// </summary> /// <param name="nodeRequest"> /// The node request. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public async Task <NodeDetailResult> UpdateNode(NodeRequest nodeRequest) { return((await this.UpdateNode(new List <NodeRequest> { nodeRequest })).FirstOrDefault()); }