Beispiel #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ctx"></param>
        public override void HandleBefore(IContext ctx)
        {
            var _ctx = (Context)ctx;

            if (_ctx.Response != null)
            {
                return;
            }
            else if (string.IsNullOrEmpty(_ctx.RequestHost))
            {
                _ctx.Response = new Error()
                {
                    errmsg = "request host not set"
                };
                return;
            }
            System.Net.Http.HttpClient httpclient;
            if (_ctx.Certificate == null)
            {
                httpclient = new System.Net.Http.HttpClient();
            }
            else
            {
                var handler = new System.Net.Http.HttpClientHandler();
                handler.ClientCertificateOptions = System.Net.Http.ClientCertificateOption.Manual;
                handler.SslProtocols             = System.Security.Authentication.SslProtocols.Tls12;
                handler.ClientCertificates.Add(_ctx.Certificate);
                httpclient = new System.Net.Http.HttpClient(handler);
            }
            httpclient.BaseAddress = new Uri(_ctx.RequestHost);
            if (_ctx.Method == System.Net.Http.HttpMethod.Post)
            {
                System.Net.Http.HttpContent content;
                if (_ctx.HttpRequestBody != null)
                {
                    content = new System.Net.Http.ByteArrayContent(_ctx.HttpRequestBody);
                }
                else if (!string.IsNullOrEmpty(_ctx.HttpRequestString))
                {
                    content = new System.Net.Http.StringContent(_ctx.HttpRequestString);
                }
                else
                {
                    content = null;
                }
                if (content != null && _ctx.HttpRequestHeaders != null)
                {
                    foreach (var item in _ctx.HttpRequestHeaders)
                    {
                        content.Headers.Add(item.Key, item.Value);
                    }
                }
                _ctx.HttpTask = httpclient.PostAsync(_ctx.RequestPath, content);
            }
            else
            {
                _ctx.HttpTask = httpclient.GetAsync(_ctx.RequestPath);
            }
        }
        protected override HTTPResponse PostRequest(string url, string clientIPAddress, byte[] gzippedPayload)
        {
            using (System.Net.Http.HttpClient httpClient = CreateHTTPClient(clientIPAddress))
            {
                System.Net.Http.ByteArrayContent content = CreatePostContent(gzippedPayload);
                System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> responseTask = responseTask = httpClient.PostAsync(url, content);
                responseTask.Wait();

                return(CreateHTTPResponse(responseTask.Result));
            }
        }
        private static System.Net.Http.ByteArrayContent CreatePostContent(byte[] gzippedPayload)
        {
            if (gzippedPayload == null || gzippedPayload.Length == 0)
            {
                return(new System.Net.Http.ByteArrayContent(new byte[] { }));
            }

            System.Net.Http.ByteArrayContent content = new System.Net.Http.ByteArrayContent(gzippedPayload);
            content.Headers.Add("Content-Encoding", "gzip");
            content.Headers.Add("Content-Length", gzippedPayload.Length.ToString());

            return(content);
        }
        public async Task <IActionResult> ScanPdf417(string blobRef, [FromQuery] bool?raw = false, [FromQuery] bool?veh = false, [FromQuery] bool?drv = false)
        {
            var res = this.Response;
            var req = this.Request;

            try
            {
                // always start off not caching whatever we send back
                res.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate, max-age=0";
                res.Headers["Pragma"]        = "no-cache"; // HTTP 1.0.
                res.Headers["Content-Type"]  = "application/json";

                if (!BlobStore.Exists(blobRef))
                {
                    return(NotFound($"Invalid, non-existent or expired blob reference specified: '{blobRef}'"));
                }

                var blobData = BlobStore.Get(blobRef);

                var client = new System.Net.Http.HttpClient();

                using (var content = new System.Net.Http.ByteArrayContent(blobData.Data))
                {
                    var barcodeServiceUrl = this.config["AppSettings:BarcodeService.URL"].TrimEnd('/');
                    var postUrl           = $"{barcodeServiceUrl}/scan/pdf417?raw={raw}&veh={veh}&drv={drv}";

                    var response = await client.PostAsync(postUrl, content);

                    var responseText = await response.Content.ReadAsStringAsync();

                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var json = JsonConvert.DeserializeObject(responseText);

                        return(Ok(ApiResponse.Payload(json)));
                    }
                    else
                    {
                        SessionLog.Error("Barcode failed. postUrl = {0}; contentLength: {1}; responseText={2}", postUrl ?? "(null)", blobData?.Data?.Length ?? -1, responseText ?? "(null)");

                        //return StatusCode((int)response.StatusCode, responseText);
                        //return new ContentResult() { Content = responseText, StatusCode = (int)response.StatusCode, ContentType = "text/plain" };
                        return(BadRequest(responseText));
                    }
                }
            }
            catch (Exception ex)
            {
                return(Ok(ApiResponse.Exception(ex)));
            }
        }
        async Task <FileVM> UploadContent(string httpPath, byte[] content)
        {
            try
            {
                var httpData    = new System.Net.Http.ByteArrayContent(content);
                var httpMessage = await Client.PutAsync(httpPath, httpData);

                if (!httpMessage.IsSuccessStatusCode)
                {
                    throw new Exception(await httpMessage.Content.ReadAsStringAsync());
                }

                var httpContent = await httpMessage.Content.ReadAsStreamAsync();

                var fileDTO = await System.Text.Json.JsonSerializer.DeserializeAsync <DTOs.File>(httpContent);

                var fileVM = GetDetails(fileDTO);
                return(fileVM);
            }
            catch (Exception ex) { throw new Exception($"Error while uploading file [{httpPath}] with oneDrive service", ex); }
        }
Beispiel #6
0
        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="textParams">请求文本参数</param>
        /// <param name="headerParams">请求头部参数</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(string url, IDictionary <string, string> textParams, IDictionary <string, string> headerParams)
        {
            HttpWebRequest req = GetWebRequest(url, "POST", headerParams);

            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            byte[]           postData  = Encoding.UTF8.GetBytes(BuildQuery(textParams));
            System.IO.Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();


            try
            {
                var client = new System.Net.Http.HttpClient();
                //client.DefaultRequestHeaders.Add("content-type", "application/x-www-form-urlencoded;charset=utf-8");
                System.Net.Http.ByteArrayContent content = new System.Net.Http.ByteArrayContent(postData);

                var list = new List <KeyValuePair <string, string> >();
                foreach (var item in textParams)
                {
                    list.Add(new KeyValuePair <string, string>(item.Key, item.Value));
                }
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*"));
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36");
                var result = client.PostAsync(new Uri(url), new System.Net.Http.FormUrlEncodedContent(list)).Result;
                var str    = result.Content.ReadAsStringAsync().Result;

                return(str);
            }
            catch (Exception ex)
            {
            }

            HttpWebResponse rsp      = (HttpWebResponse)req.GetResponse();
            Encoding        encoding = Encoding.GetEncoding(rsp.CharacterSet);

            return(GetResponseAsString(rsp, encoding));
        }
Beispiel #7
0
        public static void SendToApi()
        {
            string[] uploadfiles = new string[] { "D:\\2d.jpg", "d:\\140317.ajk" }; //上传文件路径
            string url = "http://localhost:49840//api/fileapi"; //服务地址

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                using (var content = new System.Net.Http.MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据
                {
                    //循环添加文件至列表
                    foreach (var path in uploadfiles)
                    {
                        var fileContent = new System.Net.Http.ByteArrayContent(System.IO.File.ReadAllBytes(path));
                        fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                        {
                            FileName = System.IO.Path.GetFileName(path),//此处可以自定义文件名
                        };
                        content.Add(fileContent);
                    }
                    var result = client.PostAsync(url, content).Result;//提交post请求
                }

            }
        }
        public async System.Threading.Tasks.Task <System.Text.Json.JsonElement> SendFilesAsync(System.Collections.Generic.Dictionary <System.String, System.Collections.Generic.List <SoftmakeAll.SDK.Communication.REST.File> > FormData)
        {
            if (System.String.IsNullOrWhiteSpace(this.URL))
            {
                throw new System.Exception(SoftmakeAll.SDK.Communication.REST.EmptyURLErrorMessage);
            }

            this.HasRequestErrors = false;

            using (System.Net.Http.HttpClient HttpClient = new System.Net.Http.HttpClient())
            {
                if (this.Headers.Count > 0)
                {
                    foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> Header in this.Headers)
                    {
                        HttpClient.DefaultRequestHeaders.Add(Header.Key, Header.Value);
                    }
                }
                this.AddAuthorizationHeader(HttpClient);

                using (System.Net.Http.MultipartFormDataContent MultipartFormDataContent = new System.Net.Http.MultipartFormDataContent())
                {
                    if ((FormData != null) && (FormData.Count > 0))
                    {
                        foreach (System.Collections.Generic.KeyValuePair <System.String, System.Collections.Generic.List <SoftmakeAll.SDK.Communication.REST.File> > Item in FormData)
                        {
                            if ((!(System.String.IsNullOrWhiteSpace(Item.Key))) && (Item.Value != null) && (Item.Value.Any()))
                            {
                                foreach (SoftmakeAll.SDK.Communication.REST.File File in Item.Value)
                                {
                                    System.Net.Http.ByteArrayContent ByteArrayContent = new System.Net.Http.ByteArrayContent(File.Contents);
                                    if (!(System.String.IsNullOrWhiteSpace(File.ContentType)))
                                    {
                                        ByteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(File.ContentType);
                                    }
                                    MultipartFormDataContent.Add(ByteArrayContent, Item.Key, File.Name);
                                }
                            }
                        }
                    }

                    if (this.Timeout > 0)
                    {
                        HttpClient.Timeout = System.TimeSpan.FromMilliseconds(this.Timeout);
                    }

                    try
                    {
                        System.Net.Http.HttpResponseMessage HttpResponseMessage;
                        switch (this.Method)
                        {
                        case "PATCH":
                        {
                            HttpResponseMessage = await HttpClient.PatchAsync(this.URL, MultipartFormDataContent);

                            break;
                        }

                        case "POST":
                        {
                            HttpResponseMessage = await HttpClient.PostAsync(this.URL, MultipartFormDataContent);

                            break;
                        }

                        case "PUT":
                        {
                            HttpResponseMessage = await HttpClient.PutAsync(this.URL, MultipartFormDataContent);

                            break;
                        }

                        default: throw new System.NotSupportedException($"Method {this.Method} is not supported for sending files. Plese use PATCH, POST or PUT.");
                        }
                        this._StatusCode      = HttpResponseMessage.StatusCode;
                        this.HasRequestErrors = false;

                        System.Byte[] APIResult = await HttpResponseMessage.Content.ReadAsByteArrayAsync();

                        if (APIResult == null)
                        {
                            return(new System.Text.Json.JsonElement());
                        }

                        return(System.Text.Encoding.UTF8.GetString(APIResult).ToJsonElement());
                    }
                    catch (System.Exception ex)
                    {
                        this.HasRequestErrors = ex.InnerException == null;
                        this._StatusCode      = System.Net.HttpStatusCode.InternalServerError;
                        return(new System.Text.Json.JsonElement());
                    }
                }
            }
        }
Beispiel #9
0
        public static async System.Threading.Tasks.Task UploadImageCompany(Context c, Android.Net.Uri logo, Android.Net.Uri stand, Android.Net.Uri photo1, Android.Net.Uri photo2, Android.Net.Uri photo3, Android.Net.Uri photo4, Android.Net.Uri photo5, String Email)
        {
            //variable

            try
            {
                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                System.Net.Http.MultipartFormDataContent content = new System.Net.Http.MultipartFormDataContent();

                //read file into upfilebytes array
                if (logo != null)
                {
                    var ilogo = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, logo));
                    System.Net.Http.ByteArrayContent clogo = new System.Net.Http.ByteArrayContent(ilogo);
                    content.Add(clogo, "logo", "logo.jpg");
                }
                if (stand != null)
                {
                    var istand = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, stand));
                    System.Net.Http.ByteArrayContent cstand = new System.Net.Http.ByteArrayContent(istand);
                    content.Add(cstand, "stand", "stand.jpg");
                }
                if (photo1 != null)
                {
                    var iphoto1 = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, photo1));
                    System.Net.Http.ByteArrayContent cphoto1 = new System.Net.Http.ByteArrayContent(iphoto1);
                    content.Add(cphoto1, "photo1", "p1.jpg");
                }
                if (photo2 != null)
                {
                    var iphoto2 = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, photo2));
                    System.Net.Http.ByteArrayContent cphoto2 = new System.Net.Http.ByteArrayContent(iphoto2);
                    content.Add(cphoto2, "photo2", "p2.jpg");
                }
                if (photo3 != null)
                {
                    var iphoto3 = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, photo3));
                    System.Net.Http.ByteArrayContent cphoto3 = new System.Net.Http.ByteArrayContent(iphoto3);
                    content.Add(cphoto3, "photo3", "p3.jpg");
                }
                if (photo4 != null)
                {
                    var iphoto4 = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, photo4));
                    System.Net.Http.ByteArrayContent cphoto4 = new System.Net.Http.ByteArrayContent(iphoto4);
                    content.Add(cphoto4, "photo4", "p4.jpg");
                }
                if (photo5 != null)
                {
                    var iphoto5 = File.ReadAllBytes(Droid.Modules.ImagesHelp.GetPathToImage(c, photo5));
                    System.Net.Http.ByteArrayContent cphoto5 = new System.Net.Http.ByteArrayContent(iphoto5);
                    content.Add(cphoto5, "photo5", "p5.jpg");
                }
                //create new HttpClient and MultipartFormDataContent and add our file, and StudentId


                System.Net.Http.StringContent studentIdContent = new System.Net.Http.StringContent(Email);

                content.Add(studentIdContent, "Email");


                //upload MultipartFormDataContent content async and store response in response var
                var response =
                    await client.PostAsync(url + "UploadPhotoCompany", content);

                //read response result as a string async into json var
                var responsestr = response.Content.ReadAsStringAsync().Result;

                //debug
                Android.Widget.Toast.MakeText(c, responsestr, Android.Widget.ToastLength.Long).Show();
            }
            catch (Exception e)
            {
                //debug
                Debug.WriteLine("Exception Caught: " + e.ToString());
            }
        }
Beispiel #10
0
        /// <summary>
        /// Parses the speech.
        /// </summary>
        /// <param name="speech">The speech.</param>
        /// <returns>Task&lt;ParseResult&gt;.</returns>
        /// <exception cref="ArgumentNullException">speech - No speech data given.</exception>
        public async Task <ParseResult> ParseSpeech(byte[] speech)
        {
            if (speech == null || speech.Length == 0)
            {
                throw new ArgumentNullException(nameof(speech), "No speech data given.");
            }

            using (_logger.BeginScope("WitAiClient.ParseSpeech"))
            {
                var uri = $"{_configSnapshot.Value.BaseUrl}{_configSnapshot.Value.SpeechResource}"
                          .Replace("{version}", _configSnapshot.Value.ApiVersion);

                _logger.LogDebug($"POST {uri} with {speech.Length} bytes");

                using (var content = new System.Net.Http.ByteArrayContent(speech))
                {
                    content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("audio/wav");

                    _logger.LogDebug(content.Headers.ContentType.ToString());

                    using (var response = await uri
                                          .WithClient(_client)
                                          .AllowAnyHttpStatus()
                                          .WithOAuthBearerToken(_configSnapshot.Value.ApiKey)
                                          .PostAsync(content))
                    {
                        var data = await response.Content.ReadAsStringAsync();

                        if (!response.IsSuccessStatusCode)
                        {
                            _logger.LogDebug(data);
                            response.EnsureSuccessStatusCode();
                        }


                        _logger.LogDebug($"response data: {data}");

                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject <ParseWitMessageResponse>(data);

                        var ret = new ParseResult {
                            ErrorMessage = result.ErrorMessage
                        };

                        if (result.Entities != null)
                        {
                            foreach (var entity in result.Entities)
                            {
                                _logger.LogDebug(
                                    "ParsedEntity: {name} {values}",
                                    entity.Key,
                                    string.Join(";", entity.Value.Select(v => v.Value)));

                                var entities = entity.Value.Select(e => new Entity
                                {
                                    Value      = e.Value.ToString(),
                                    Confidence = e.Confidence
                                });

                                ret.Entities.Add(new ParsedEntity
                                {
                                    Name   = entity.Key,
                                    Values = entities.ToList()
                                });
                            }
                        }

                        return(ret);
                    }
                }
            }
        }
Beispiel #11
0
        static public int RunBotSession(
            byte[] kalmitElmApp,
            Func <byte[], byte[]> getFileFromHashSHA256,
            string processStoreDirectory,
            Action <string> logEntry,
            Action <LogEntry.ProcessBotEventReport> logProcessBotEventReport,
            string botConfiguration,
            string sessionId,
            string botSource)
        {
            var botId = Kalmit.CommonConversion.StringBase16FromByteArray(Kalmit.CommonConversion.HashSHA256(kalmitElmApp));

            var botSessionClock = System.Diagnostics.Stopwatch.StartNew();

            /*
             * Implementat store and process based on Kalmit Web Host
             * from https://github.com/Viir/Kalmit/blob/640078f59bea3fa2ba1af43372933cff304b8c94/implement/PersistentProcess/PersistentProcess.WebHost/Startup.cs
             * */

            var process = new Kalmit.PersistentProcess.PersistentProcessWithHistoryOnFileFromElm019Code(
                new EmptyProcessStore(), kalmitElmApp);

            var processStore = new ProcessStoreInFileDirectory(
                processStoreDirectory,
                () =>
            {
                var time          = DateTimeOffset.UtcNow;
                var directoryName = time.ToString("yyyy-MM-dd");
                return(System.IO.Path.Combine(directoryName, directoryName + "T" + time.ToString("HH") + ".composition.jsonl"));
            });

            (DateTimeOffset time, string statusDescriptionForOperator, InterfaceToBot.BotResponse.DecodeEventSuccessStructure response)? lastBotStep = null;

            var botSessionTaskCancellationToken = new System.Threading.CancellationTokenSource();
            var activeBotTasks = new ConcurrentDictionary <InterfaceToBot.StartTask, System.Threading.Tasks.Task>();

            bool pauseBot = false;

            (string text, DateTimeOffset time)lastConsoleUpdate = (null, DateTimeOffset.MinValue);

            void updatePauseContinue()
            {
                if (DotNetConsole.KeyAvailable)
                {
                    var inputKey = DotNetConsole.ReadKey();

                    if (inputKey.Key == ConsoleKey.Enter)
                    {
                        pauseBot = false;
                        displayStatusInConsole();
                    }
                }

                if (Windows.IsKeyDown(Windows.VK_CONTROL) && Windows.IsKeyDown(Windows.VK_MENU))
                {
                    pauseBot = true;
                    displayStatusInConsole();
                }
            }

            void cleanUpBotTasksAndPropagateExceptions()
            {
                foreach (var(request, engineTask) in activeBotTasks.ToList())
                {
                    if (engineTask.Exception != null)
                    {
                        throw new Exception("Bot task '" + request.taskId + "' has failed with exception", engineTask.Exception);
                    }

                    if (engineTask.IsCompleted)
                    {
                        activeBotTasks.TryRemove(request, out var _);
                    }
                }
            }

            var displayLock = new object();

            void displayStatusInConsole()
            {
                lock (displayLock)
                {
                    cleanUpBotTasksAndPropagateExceptions();

                    var textToDisplay = string.Join("\n", textLinesToDisplayInConsole());

                    var time = DateTimeOffset.UtcNow;

                    if (lastConsoleUpdate.text == textToDisplay && time < lastConsoleUpdate.time + TimeSpan.FromSeconds(1))
                    {
                        return;
                    }

                    DotNetConsole.Clear();
                    DotNetConsole.WriteLine(textToDisplay);

                    lastConsoleUpdate = (textToDisplay, time);
                }
            }

            IEnumerable <string> textLinesToDisplayInConsole()
            {
                //  TODO: Add display bot configuration.

                yield return
                    ("Bot " + UserInterface.BotIdDisplayText(botId) +
                     " in session '" + sessionId + "'" +
                     (pauseBot ?
                      " is paused. Press the enter key to continue." :
                      " is running. Press CTRL + ALT keys to pause the bot."));

                if (!lastBotStep.HasValue)
                {
                    yield break;
                }

                var lastBotStepAgeInSeconds = (int)((DateTimeOffset.UtcNow - lastBotStep.Value.time).TotalSeconds);

                yield return
                    ("Last bot event was " + lastBotStepAgeInSeconds + " seconds ago at " + lastBotStep.Value.time.ToString("HH-mm-ss.fff") + ". " +
                     "There are " + activeBotTasks.Count + " tasks in progress.");

                yield return("Status message from bot:\n");

                yield return(lastBotStep.Value.statusDescriptionForOperator);

                yield return("");
            }

            long lastRequestToReactorTimeInSeconds = 0;

            async System.Threading.Tasks.Task requestToReactor(RequestToReactorUseBotStruct useBot)
            {
                lastRequestToReactorTimeInSeconds = (long)botSessionClock.Elapsed.TotalSeconds;

                var toReactorStruct = new RequestToReactorStruct {
                    UseBot = useBot
                };

                var serializedToReactorStruct = Newtonsoft.Json.JsonConvert.SerializeObject(toReactorStruct);

                var reactorClient = new System.Net.Http.HttpClient();

                reactorClient.DefaultRequestHeaders.UserAgent.Add(
                    new System.Net.Http.Headers.ProductInfoHeaderValue(new System.Net.Http.Headers.ProductHeaderValue("windows-console", BotEngine.AppVersionId)));

                var content = new System.Net.Http.ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(serializedToReactorStruct));

                var response = await reactorClient.PostAsync("https://reactor.botengine.org/api/", content);

                var responseString = await response.Content.ReadAsStringAsync();
            }

            void fireAndForgetReportToReactor(RequestToReactorUseBotStruct report)
            {
                lastRequestToReactorTimeInSeconds = (long)botSessionClock.Elapsed.TotalSeconds;

                System.Threading.Tasks.Task.Run(() =>
                {
                    try
                    {
                        requestToReactor(report).Wait();
                    }
                    catch { }
                });
            }

            fireAndForgetReportToReactor(new RequestToReactorUseBotStruct
            {
                StartSession = new RequestToReactorUseBotStruct.StartSessionStruct
                {
                    botId = botId, sessionId = sessionId, botSource = BotSourceIsPublic(botSource) ? botSource : null
                }
            });

            var createVolatileHostAttempts = 0;

            var volatileHosts = new ConcurrentDictionary <string, Kalmit.CSharpScriptContext>();

            InterfaceToBot.Result <InterfaceToBot.TaskResult.RunInVolatileHostError, InterfaceToBot.TaskResult.RunInVolatileHostComplete> ExecuteRequestToRunInVolatileHost(
                InterfaceToBot.Task.RunInVolatileHostStructure runInVolatileHost)
            {
                if (!volatileHosts.TryGetValue(runInVolatileHost.hostId, out var volatileHost))
                {
                    return(new InterfaceToBot.Result <InterfaceToBot.TaskResult.RunInVolatileHostError, InterfaceToBot.TaskResult.RunInVolatileHostComplete>
                    {
                        Err = new InterfaceToBot.TaskResult.RunInVolatileHostError
                        {
                            hostNotFound = new object(),
                        }
                    });
                }

                var stopwatch = System.Diagnostics.Stopwatch.StartNew();

                var fromHostResult = volatileHost.RunScript(runInVolatileHost.script);

                stopwatch.Stop();

                return(new InterfaceToBot.Result <InterfaceToBot.TaskResult.RunInVolatileHostError, InterfaceToBot.TaskResult.RunInVolatileHostComplete>
                {
                    Ok = new InterfaceToBot.TaskResult.RunInVolatileHostComplete
                    {
                        exceptionToString = fromHostResult.Exception?.ToString(),
                        returnValueToString = fromHostResult.ReturnValue?.ToString(),
                        durationInMilliseconds = stopwatch.ElapsedMilliseconds,
                    }
                });
            }

            void processBotEvent(InterfaceToBot.BotEvent botEvent)
            {
                var       eventTime             = DateTimeOffset.UtcNow;
                Exception processEventException = null;
                string    serializedEvent       = null;
                string    serializedResponse    = null;
                string    compositionRecordHash = null;

                try
                {
                    serializedEvent = SerializeToJsonForBot(botEvent);

                    var processEventResult = process.ProcessEvents(
                        new[]
                    {
                        serializedEvent
                    });

                    compositionRecordHash = Kalmit.CommonConversion.StringBase16FromByteArray(processEventResult.Item2.serializedCompositionRecordHash);

                    processStore.AppendSerializedCompositionRecord(processEventResult.Item2.serializedCompositionRecord);

                    serializedResponse = processEventResult.responses.Single();

                    var botResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <InterfaceToBot.BotResponse>(serializedResponse);

                    if (botResponse.DecodeEventSuccess == null)
                    {
                        throw new Exception("Bot reported decode error: " + botResponse.DecodeEventError);
                    }

                    var statusDescriptionForOperator =
                        botResponse.DecodeEventSuccess?.ContinueSession?.statusDescriptionForOperator ??
                        botResponse.DecodeEventSuccess?.FinishSession?.statusDescriptionForOperator;

                    lastBotStep = (eventTime, statusDescriptionForOperator, botResponse.DecodeEventSuccess);

                    foreach (var startTask in botResponse.DecodeEventSuccess?.ContinueSession?.startTasks ?? Array.Empty <InterfaceToBot.StartTask>())
                    {
                        var engineTask = System.Threading.Tasks.Task.Run(() => startTaskAndProcessEvent(startTask), botSessionTaskCancellationToken.Token);

                        activeBotTasks[startTask] = engineTask;
                    }
                }
                catch (Exception exception)
                {
                    processEventException = exception;
                }

                logProcessBotEventReport(new LogEntry.ProcessBotEventReport
                {
                    time                  = eventTime,
                    exception             = processEventException,
                    serializedResponse    = serializedResponse,
                    compositionRecordHash = compositionRecordHash,
                });

                if (processEventException != null)
                {
                    throw new Exception("Failed to process bot event.", processEventException);
                }

                displayStatusInConsole();
            }

            //  TODO: Get the bot requests from the `init` function.

            processBotEvent(new InterfaceToBot.BotEvent {
                SetBotConfiguration = botConfiguration ?? ""
            });

            while (true)
            {
                displayStatusInConsole();

                updatePauseContinue();

                var millisecondsToNextNotification =
                    (lastBotStep?.response?.ContinueSession?.notifyWhenArrivedAtTime?.timeInMilliseconds - botSessionClock.ElapsedMilliseconds) ?? 1000;

                System.Threading.Thread.Sleep((int)Math.Min(1000, Math.Max(10, millisecondsToNextNotification)));

                var lastRequestToReactorAgeInSeconds = (long)botSessionClock.Elapsed.TotalSeconds - lastRequestToReactorTimeInSeconds;

                if (30 <= lastRequestToReactorAgeInSeconds)
                {
                    fireAndForgetReportToReactor(new RequestToReactorUseBotStruct
                    {
                        ContinueSession = new RequestToReactorUseBotStruct.ContinueSessionStruct
                        {
                            sessionId = sessionId, statusDescriptionForOperator = lastBotStep?.statusDescriptionForOperator
                        }
                    });
                }

                if (pauseBot)
                {
                    continue;
                }

                var botStepTime = DateTimeOffset.UtcNow;

                var lastBotStepAgeMilli =
                    botStepTime.ToUnixTimeMilliseconds() - lastBotStep?.time.ToUnixTimeMilliseconds();

                if (lastBotStep?.response?.FinishSession != null)
                {
                    logEntry("Bot has finished.");
                    botSessionTaskCancellationToken.Cancel();
                    return(0);
                }

                if (lastBotStep?.response?.ContinueSession?.notifyWhenArrivedAtTime?.timeInMilliseconds <= botSessionClock.ElapsedMilliseconds ||
                    !(lastBotStepAgeMilli < 10_000))
                {
                    processBotEvent(new InterfaceToBot.BotEvent
                    {
                        ArrivedAtTime = new InterfaceToBot.TimeStructure {
                            timeInMilliseconds = botSessionClock.ElapsedMilliseconds
                        },
                    });
                }
            }

            void startTaskAndProcessEvent(InterfaceToBot.StartTask startTask)
            {
                var taskResult = performTask(startTask.task);

                processBotEvent(new InterfaceToBot.BotEvent
                {
                    TaskComplete = new InterfaceToBot.ResultFromTaskWithId
                    {
                        taskId     = startTask.taskId,
                        taskResult = taskResult,
                    },
                });
            }

            InterfaceToBot.TaskResult performTask(InterfaceToBot.Task task)
            {
                if (task?.CreateVolatileHost != null)
                {
                    var volatileHostId = System.Threading.Interlocked.Increment(ref createVolatileHostAttempts).ToString();

                    volatileHosts[volatileHostId] = new Kalmit.CSharpScriptContext(getFileFromHashSHA256);

                    return(new InterfaceToBot.TaskResult
                    {
                        CreateVolatileHostResponse = new InterfaceToBot.Result <object, InterfaceToBot.TaskResult.CreateVolatileHostComplete>
                        {
                            Ok = new InterfaceToBot.TaskResult.CreateVolatileHostComplete
                            {
                                hostId = volatileHostId,
                            },
                        },
                    });
                }

                if (task?.ReleaseVolatileHost != null)
                {
                    volatileHosts.TryRemove(task?.ReleaseVolatileHost.hostId, out var volatileHost);

                    return(new InterfaceToBot.TaskResult {
                        CompleteWithoutResult = new object()
                    });
                }

                if (task?.RunInVolatileHost != null)
                {
                    var result = ExecuteRequestToRunInVolatileHost(task?.RunInVolatileHost);

                    return(new InterfaceToBot.TaskResult
                    {
                        RunInVolatileHostResponse = result,
                    });
                }

                return(null);
            }
        }
Beispiel #12
0
        private static async System.Threading.Tasks.Task PostAsync(ServiceResponse response, Uri uri, List <Tuple <string, string> > UriSubstitutes, List <Tuple <string, string> > headers, List <Tuple <string, string> > postDataSubstitutes, byte[] bytes, System.Collections.Generic.Dictionary <string, string> apiArgs, int maxResponseLength = 10000000)
        {
            Settings.Request request        = response.Request;
            bool             binaryResponse = request.response.type == "binary";
            string           fileName       = null;

            if (apiArgs.ContainsKey("fileName"))
            {
                fileName = apiArgs["fileName"];
            }

            if (uri == null)
            {
                uri = MakeUri(request, apiArgs, UriSubstitutes);
            }
            if (headers == null)
            {
                headers = MakeHeaders(request);
            }
            List <string> texts = MakePostDataSubstitutes(request, null, bytes, apiArgs, postDataSubstitutes);

            System.Net.Http.HttpContent requestContent;
            if (texts == null)
            {
                await MakePostCurl(uri, headers, bytes, request.response.jq, binaryResponse);

                requestContent = new System.Net.Http.ByteArrayContent(bytes);
            }
            else
            {
                if (texts.Count == 1 && !isMultipart(headers))
                {
                    await MakePostCurl(uri, headers, texts, request.response.jq, binaryResponse);

                    if (texts[0] == null) // Houndify text intent
                    {
                        requestContent = new System.Net.Http.ByteArrayContent(bytes);
                    }
                    else
                    {
                        requestContent = new System.Net.Http.StringContent(texts[0]);
                    }
                    await SystemNetAsync(response, "POST", uri, headers, requestContent, binaryResponse, maxResponseLength);

                    return;
                }
                else
                {
                    List <KeyValuePair <string, string> > lkvp = new List <KeyValuePair <string, string> >();
                    foreach (string s in texts)
                    {
                        lkvp.Add(new KeyValuePair <string, string>(s.Substring(0, s.IndexOf("=")), s.Substring(s.IndexOf("=") + 1)));
                    }
                    await MakePostMultiPartCurl(uri, headers, lkvp, request.response.jq, binaryResponse);

                    System.Net.Http.MultipartFormDataContent multiPartRequestContent = new System.Net.Http.MultipartFormDataContent();
                    foreach (KeyValuePair <string, string> kvp in lkvp)
                    {
                        System.Net.Http.HttpContent ht;
                        switch (kvp.Key)
                        {
                        case "file":
                            ht = new System.Net.Http.ByteArrayContent(bytes);
                            ht.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");     // optional for HPE Haven?
                            multiPartRequestContent.Add(ht, "\"file\"", "\"" + fileName + "\"");
                            break;

                        default:
                            ht = new System.Net.Http.StringContent(kvp.Value);
                            ht.Headers.ContentType = null;
                            multiPartRequestContent.Add(ht, '"' + kvp.Key + '"');
                            break;
                        }
                    }
                    await SystemNetAsync(response, "POST", uri, headers, multiPartRequestContent, binaryResponse, maxResponseLength);

                    response.FileName = "curl-" + httpCallCount;
                    return;
                }
            }
#if WINDOWS_UWP
            if (Options.options.Services.APIs.PreferSystemNet)
            {
                await SystemNetAsync("POST", uri, headers, new System.Net.Http.ByteArrayContent(requestContent), binaryResponse, maxResponseLength);
            }
            else
            {
                await WindowsWebAsync("POST", new Uri(requestUri), audioBytes, sampleRate, contentType, headerValue);
            }
#else
            await SystemNetAsync(response, "POST", uri, headers, requestContent, binaryResponse, maxResponseLength);
#endif
            response.FileName = "curl-" + httpCallCount;
        }
        public async Task <bool> SetImage(string url, Image img)
        {
            if (url == null || url.Length == 0)
            {
                throw new System.ArgumentNullException("Url");
            }

            if (!url.StartsWith("/"))
            {
                url = "/" + url;
            }

            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl).Append(url);

            var client_ = new System.Net.Http.HttpClient();

            try
            {
                byte[] imageToSend = null;
                if (img != null)
                {
                    using (var memoryStream = new System.IO.MemoryStream())
                    {
                        try
                        {
                            img.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                        catch
                        {
                            Bitmap bitmap = (Bitmap)img;
                            bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                        imageToSend = memoryStream.ToArray();
                    }
                }
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    System.Net.Http.HttpContent content = new System.Net.Http.ByteArrayContent(imageToSend);

                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");

                    var content_ = new System.Net.Http.MultipartFormDataContent();
                    content_.Add(content);
                    request_.Content = content_;
                    request_.Method  = new System.Net.Http.HttpMethod("PUT");
                    request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        foreach (var item_ in response_.Content.Headers)
                        {
                            headers_[item_.Key] = item_.Value;
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            return(true);
                        }
                        else if (status_ == "304")
                        {
                            return(true);
                        }
                        else
                        {
                            if (status_ != "200" && status_ != "204")
                            {
                                return(false);
                            }
                        }
                        return(false);
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
Beispiel #14
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public Task <string> Handle()
        {
            var rlt = Task.Run <string>(() => { return(""); });

            Result = new ApiResult <IResponse> {
                node = XCore.WebNode, code = "-1", success = false, message = "unkown error"
            };
            if (string.IsNullOrEmpty(ApiHost))
            {
                Result.code    = "400";
                Result.message = "request host not set";
            }
            else if (string.IsNullOrEmpty(ApiPath))
            {
                Result.code    = "400";
                Result.message = "request path not set";
            }
            else
            {
                System.Net.Http.HttpClient http = null;
                Task <System.Net.Http.HttpResponseMessage> task = null;
                if (Certificate == null)
                {
                    http = new System.Net.Http.HttpClient();
                }
                else
                {
                    var handler = new System.Net.Http.HttpClientHandler();
                    handler.ClientCertificateOptions = System.Net.Http.ClientCertificateOption.Manual;
                    handler.SslProtocols             = System.Security.Authentication.SslProtocols.Tls12;
                    handler.ClientCertificates.Add(Certificate);
                    http = new System.Net.Http.HttpClient(handler);
                }
                http.BaseAddress = new System.Uri(ApiHost);
                if (Method == "GET")
                {
                    var query = RequestBody as string;
                    if (!string.IsNullOrEmpty(query))
                    {
                        var link = ApiPath.IndexOf('?') < 0 ? '?' : '&';
                        ApiPath += query[0] == '?' || query[0] == '&' ? query : link + query;
                    }
                    if (HttpRequestHeaders != null)
                    {
                        foreach (var kv in HttpRequestHeaders)
                        {
                            http.DefaultRequestHeaders.Add(kv.Key, kv.Value);
                        }
                    }
                    task = http.GetAsync(ApiPath);
                }
                else
                {
                    System.Net.Http.HttpContent content = null;
                    var text  = RequestBody as string;
                    var bytes = RequestBody as byte[];
                    if (bytes != null)
                    {
                        content = new System.Net.Http.ByteArrayContent(bytes);
                    }
                    else if (!string.IsNullOrEmpty(text))
                    {
                        content = new System.Net.Http.StringContent(text, Encoding, ContentType);
                    }
                    else if (RequestBody != null)
                    {
                        content = new System.Net.Http.StringContent(Json.ToString(RequestBody), Encoding, ContentType);
                    }
                    else
                    {
                        content = new System.Net.Http.ByteArrayContent(new byte[0]);
                    }
                    if (HttpRequestHeaders != null)
                    {
                        foreach (var kv in HttpRequestHeaders)
                        {
                            content.Headers.Add(kv.Key, kv.Value);
                        }
                    }
                    task = http.PostAsync(ApiPath, content);
                }

                task.Result.Content.ReadAsStringAsync().ContinueWith((res) =>
                {
                    ResponseBody        = res.Result;
                    HttpResponseHeaders = new Dictionary <string, string>();
                    foreach (var item in task.Result.Headers)
                    {
                        var em = item.Value.GetEnumerator();
                        if (em.MoveNext())
                        {
                            HttpResponseHeaders.Add(item.Key.ToLower(), em.Current);
                        }
                    }
                    rlt = Task.Run <string>(() => { return(res.Result); });
                }).Wait();
            }
            return(rlt);
        }