private static async Task <HttpContent> ConvertResponseContentAsync(Windows.Web.Http.IHttpContent content)
    {
        var responseStream = await content.ReadAsInputStreamAsync();

        var result = new StreamContent(responseStream.AsStreamForRead());

        CopyHeaders(content.Headers, result.Headers);
        return(result);
    }
Exemple #2
0
        public static async Task <JToken> PostDataAsync(Uri uri, Windows.Web.Http.IHttpContent content)
        {
            var json = await PostAsync(uri, content);

            var    o     = JObject.Parse(json);
            JToken token = null;

            if (!string.IsNullOrEmpty(json) &&
                !o.TryGetValue("data", out token) &&
                o.TryGetValue("message", out _))
            {
                throw new CoolapkMessageException(o);
            }
            else
            {
                return(token);
            }
        }
Exemple #3
0
        public static async Task <JToken> PostDataAsync(DataUriType type, Windows.Web.Http.IHttpContent content, params object[] args)
        {
            var uri  = string.Format(GetUriStringTemplate(type), args);
            var json = await PostAsync(uri, content);

            var    o     = JObject.Parse(json);
            JToken token = null;

            if (!string.IsNullOrEmpty(json) &&
                !o.TryGetValue("data", out token) &&
                o.TryGetValue("message", out _))
            {
                throw new CoolapkMessageException(o);
            }
            else
            {
                return(token);
            }
        }
Exemple #4
0
        /// <summary>
        /// Copies headers from one <see cref="Windows.Web.Http.IHttpContent"/> instance to another.
        /// </summary>
        /// <param name="source">The source <see cref="Windows.Web.Http.IHttpContent"/> to copy from.</param>
        /// <param name="destination">The destination <see cref="Windows.Web.Http.IHttpContent"/> to copy to.</param>
        public static void CopyHeadersTo(this Windows.Web.Http.IHttpContent source, Windows.Web.Http.IHttpContent destination)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            foreach (var header in source.Headers)
            {
                if (destination.Headers.ContainsKey(header.Key))
                {
                    destination.Headers.Remove(header.Key);
                }

                destination.Headers.Add(header.Key, header.Value);
            }
        }
        /// <summary>
        /// Converts the convent from Windows.Web.Http.IHttpContent to System.Net.Http.HttpContent.
        /// </summary>
        /// <param name="content">The Windows.Web.Http.IHttpContent to convert.</param>
        /// <param name="cancellationToken">The operation cancellation token.</param>
        /// <returns>Converted System.Net.Http.HttpContent.</returns>
        private static async Task <HttpContent> ConvertContent(
            Windows.Web.Http.IHttpContent content,
            CancellationToken cancellationToken)
        {
            // If no content to convert
            if (content == null)
            {
                return(null);
            }

            // Convert the content
            var stream = await content.ReadAsInputStreamAsync().AsTask(cancellationToken).ConfigureAwait(false);

            var converted = new StreamContent(stream.AsStreamForRead());

            // Copy content headers
            foreach (var header in content.Headers)
            {
                converted.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            // Return the converted content
            return(converted);
        }
Exemple #6
0
        public virtual async System.Threading.Tasks.Task <IServiceResponse> PostAsyncWindowsWeb(Uri uri, byte[] audioBytes, apiArgs)
        {
            IServiceResponse response = new IServiceResponse(service);

            try
            {
                // Using HttpClient to grab chunked encoding (partial) responses.
                using (Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient())
                {
                    Log.WriteLine("before requestContent");
                    Log.WriteLine("after requestContent");
                    // rate must be specified but doesn't seem to need to be accurate.

                    Windows.Web.Http.IHttpContent requestContent = null;
                    if (Options.options.APIs.preferChunkedEncodedRequests)
                    {
                        // using chunked transfer requests
                        Log.WriteLine("Using chunked encoding");
                        Windows.Storage.Streams.InMemoryRandomAccessStream contentStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                        // TODO: obsolete to use DataWriter? use await Windows.Storage.FileIO.Write..(file);
                        Windows.Storage.Streams.DataWriter dw = new Windows.Storage.Streams.DataWriter(contentStream);
                        dw.WriteBytes(audioBytes);
                        await dw.StoreAsync();

                        // GetInputStreamAt(0) forces chunked transfer (sort of undocumented behavior).
                        requestContent = new Windows.Web.Http.HttpStreamContent(contentStream.GetInputStreamAt(0));
                    }
                    else
                    {
                        requestContent = new Windows.Web.Http.HttpBufferContent(audioBytes.AsBuffer());
                    }
                    requestContent.Headers.Add("Content-Type", "audio/l16; rate=" + sampleRate.ToString()); // must add header AFTER contents are initialized

                    Log.WriteLine("Before Post: Elapsed milliseconds:" + stopWatch.ElapsedMilliseconds);
                    response.RequestElapsedMilliseconds = stopWatch.ElapsedMilliseconds;
                    using (Windows.Web.Http.HttpResponseMessage hrm = await httpClient.PostAsync(uri, requestContent))
                    {
                        response.RequestElapsedMilliseconds = stopWatch.ElapsedMilliseconds - response.RequestElapsedMilliseconds;
                        response.StatusCode = (int)hrm.StatusCode;
                        Log.WriteLine("After Post: StatusCode:" + response.StatusCode + " Total milliseconds:" + stopWatch.ElapsedMilliseconds + " Request milliseconds:" + response.RequestElapsedMilliseconds);
                        if (hrm.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
                        {
                            string responseContents = await hrm.Content.ReadAsStringAsync();

                            string[] responseJsons = responseContents.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                            foreach (string rj in responseJsons)
                            {
                                response.ResponseJson = rj;
                                Newtonsoft.Json.Linq.JToken ResponseBodyToken = Newtonsoft.Json.Linq.JObject.Parse(response.ResponseJson);
                                response.ResponseJsonFormatted = Newtonsoft.Json.JsonConvert.SerializeObject(ResponseBodyToken, new Newtonsoft.Json.JsonSerializerSettings()
                                {
                                    Formatting = Newtonsoft.Json.Formatting.Indented
                                });
                                if (Options.options.debugLevel >= 4)
                                {
                                    Log.WriteLine(response.ResponseJsonFormatted);
                                }
                                Newtonsoft.Json.Linq.JToken tokResult = ProcessResponse(ResponseBodyToken);
                                if (tokResult == null || string.IsNullOrEmpty(tokResult.ToString()))
                                {
                                    response.ResponseResult = Options.options.Services.APIs.SpeechToText.missingResponse;
                                    if (Options.options.debugLevel >= 3)
                                    {
                                        Log.WriteLine("ResponseResult:" + response.ResponseResult);
                                    }
                                }
                                else
                                {
                                    response.ResponseResult = tokResult.ToString();
                                    if (Options.options.debugLevel >= 3)
                                    {
                                        Log.WriteLine("ResponseResult:" + tokResult.Path + ": " + response.ResponseResult);
                                    }
                                }
                            }
                        }
                        else
                        {
                            response.ResponseResult = hrm.ReasonPhrase;
                            Log.WriteLine("PostAsync Failed: StatusCode:" + hrm.ReasonPhrase + "(" + response.StatusCode.ToString() + ")");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine("Exception:" + ex.Message);
                if (ex.InnerException != null)
                {
                    Log.WriteLine("InnerException:" + ex.InnerException);
                }
            }
            return(response);
        }