private async Task WriteCompressedContentToStream(Stream outputStream) { Stream compressedStream = null; if (String.Compare(encodingType, "gzip", true) == 0) { compressedStream = new GZipStream(outputStream, CompressionMode.Compress, leaveOpen: true); } else if (String.Compare(encodingType, "deflate", true) == 0) { compressedStream = new DeflateStream(outputStream, CompressionMode.Compress, leaveOpen: true); } using (var stream = await originalContent.ReadAsInputStreamAsync().AsTask().ConfigureAwait(false)) { using (var sourceStream = stream.AsStreamForRead()) { try { sourceStream.CopyTo(compressedStream); } finally { compressedStream?.Dispose(); } } } }
public static async Task <string> ReadAsStringAsync(this IHttpContent content, Encoding encoding) { using (TextReader reader = new StreamReader((await content.ReadAsInputStreamAsync()).AsStreamForRead(), encoding)) { return(reader.ReadToEnd()); } }
public async Task <MessageOfTheDay> GetNewMessage() { try { // Make the request. IHttpContent webResult = await m_baconMan.NetworkMan.MakeGetRequest(c_motdUrl); // Get the input stream and json reader. // NOTE!! We are really careful not to use a string here so we don't have to allocate a huge string. IInputStream inputStream = await webResult.ReadAsInputStreamAsync(); using (StreamReader reader = new StreamReader(inputStream.AsStreamForRead())) using (JsonReader jsonReader = new JsonTextReader(reader)) { // Parse the Json as an object JsonSerializer serializer = new JsonSerializer(); return(await Task.Run(() => serializer.Deserialize <MessageOfTheDay>(jsonReader))); } } catch (Exception e) { m_baconMan.MessageMan.DebugDia("failed to get motd", e); m_baconMan.TelemetryMan.ReportUnExpectedEvent(this, "FailedToGetMotd", e); } return(null); }
private static async Task CompressOriginalContentStream(IHttpContent originalContent, System.IO.MemoryStream ms) { using (var compressingStream = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { using (var originalContentStream = await originalContent.ReadAsInputStreamAsync().AsTask().ConfigureAwait(false)) { originalContentStream.AsStreamForRead().CopyTo(compressingStream); } compressingStream.Flush(); } }
/// <summary> /// Deserializes an object from IHttpContent without using strings. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="content"></param> /// <returns></returns> public async Task <T> DeseralizeObject <T>(IHttpContent content) { // NOTE!! We are really careful not to use a string here so we don't have to allocate a huge string. IInputStream inputStream = await content.ReadAsInputStreamAsync(); using (StreamReader reader = new StreamReader(inputStream.AsStreamForRead())) using (JsonReader jsonReader = new JsonTextReader(reader)) { // Parse the Json as an object JsonSerializer serializer = new JsonSerializer(); T jsonObject = await Task.Run(() => serializer.Deserialize <T>(jsonReader)); return(jsonObject); } }
#pragma warning restore /// <summary> /// Uses GfyCat to convert a normal .gif into a video /// </summary> /// <param name="apiUrl"></param> /// <returns></returns> private async Task <string> ConvertGifUsingGfycat(string gifUrl) { // Return if we have nothing. if (gifUrl.Equals(String.Empty)) { return(String.Empty); } try { // Make the call IHttpContent webResult = await App.BaconMan.NetworkMan.MakeGetRequest("https://upload.gfycat.com/transcode?fetchUrl=" + gifUrl); // Get the input stream and json reader. // NOTE!! We are really careful not to use a string here so we don't have to allocate a huge string. IInputStream inputStream = await webResult.ReadAsInputStreamAsync(); using (StreamReader reader = new StreamReader(inputStream.AsStreamForRead())) using (JsonReader jsonReader = new JsonTextReader(reader)) { // Parse the Json as an object JsonSerializer serializer = new JsonSerializer(); GfyCatConversionData gfyData = await Task.Run(() => serializer.Deserialize <GfyCatConversionData>(jsonReader)); // Validate the response string mp4Url = gfyData.Mp4Url; if (String.IsNullOrWhiteSpace(mp4Url)) { throw new Exception("Gfycat failed to convert"); } // Return the url return(mp4Url); } } catch (Exception e) { App.BaconMan.MessageMan.DebugDia("failed to convert gif via gfycat", e); App.BaconMan.TelemetryMan.ReportUnExpectedEvent(this, "GfyCatConvertFailed", e); } return(String.Empty); }
#pragma warning restore /// <summary> /// Gets a video url from gfycat /// </summary> /// <param name="apiUrl"></param> /// <returns></returns> private async Task <string> GetGfyCatGifUrl(string apiUrl) { // Return if we have nothing. if (apiUrl.Equals(String.Empty)) { return(String.Empty); } try { // Make the call IHttpContent webResult = await App.BaconMan.NetworkMan.MakeGetRequest(apiUrl); // Get the input stream and json reader. // NOTE!! We are really careful not to use a string here so we don't have to allocate a huge string. IInputStream inputStream = await webResult.ReadAsInputStreamAsync(); using (StreamReader reader = new StreamReader(inputStream.AsStreamForRead())) using (JsonReader jsonReader = new JsonTextReader(reader)) { // Parse the Json as an object JsonSerializer serializer = new JsonSerializer(); GfyCatDataContainer gfyData = await Task.Run(() => serializer.Deserialize <GfyCatDataContainer>(jsonReader)); // Validate the response string mp4Url = gfyData.item.Mp4Url; if (String.IsNullOrWhiteSpace(mp4Url)) { throw new Exception("Gfycat response failed to parse"); } // Return the url return(mp4Url); } } catch (Exception e) { App.BaconMan.MessageMan.DebugDia("failed to get image from gfycat", e); App.BaconMan.TelemetryMan.ReportUnExpectedEvent(this, "FaileGfyCatApiCall", e); } return(String.Empty); }
//prepared private public static async Task <string> CookiedGetUrl(string url, string referrer) { HttpResponseMessage response = null; try { HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, new Uri(url)); req.Headers.Referer = new Uri(referrer); response = await client.SendRequestAsync(req); req.Dispose(); } catch (COMException e) { if ((uint)e.HResult == 0x80072f76) { await ShowMessageDialog("可能是被验证码阻挡。", "错误代码:" + String.Format("{0:x8}", e.HResult) + "\n错误类型:" + e.GetType() + "\n错误信息:" + e.Message + "\n" + "如果是验证码问题,请不要立即点确定。请先打开浏览器,输入验证码。"); await ShowMessageDialog("提示", "如果已经输入验证码,可以确认继续;\n如果发现Cookie已失效,继续并稍后以重新设置Cookie"); } try { HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, new Uri(url)); req.Headers.Referer = new Uri(referrer); response = await client.SendRequestAsync(req); req.Dispose(); } catch (COMException e2) { if ((uint)e2.HResult == 0x80072f76) { await ShowMessageDialog("错误未解决。", "错误类型:" + e2.GetType() + "\n错误信息:" + e2.Message + "\n持续网络故障。为避免故障扩大,程序将结束。可检查网络/jingyan.baidu.com,稍后再启动。"); Application.Current.Exit(); } if ((uint)e2.HResult == 0x80072efd) { await ShowMessageDialog("错误未解决。80072efd,系统网络故障", "错误类型:" + e2.GetType() + "\n错误信息:" + e2.Message + "\n请百度80072efd寻找解决办法。该故障和系统网络设置有关。可能是被国产安全软件乱优化造成。\n持续网络故障。为避免故障扩大,程序将结束。可检查网络,稍后再启动。"); Application.Current.Exit(); } client.Dispose(); await ShowMessageDialog("未知故障。可能是网络问题", "错误类型:" + e2.GetType() + "\n错误信息:" + e2.Message); throw new COMException(e2.Message); } } if (response == null) { return("RESPONSE NULL"); } if (response.StatusCode != HttpStatusCode.Ok) { return(response.StatusCode.ToString()); } IHttpContent icont = response.Content; IInputStream istream = await icont.ReadAsInputStreamAsync(); StreamReader reader = new StreamReader(istream.AsStreamForRead(), Encoding.UTF8); string content = reader.ReadToEnd(); reader.Dispose(); istream.Dispose(); icont.Dispose(); response.Dispose(); return(content); }
/// <summary> /// Returns a range of elements from the source, if the elements are not local it will fetch them from the interwebs /// This can take multiple web calls to get the list, so this can be slow. If there aren't enough elements remaining /// we will return as many as we can get. /// THIS IS NOT THREAD SAFE /// </summary> /// <param name="bottom">The bottom range, inclusive</param> /// <param name="top">The top of the range, exclusive</param> /// <returns></returns> public async Task <List <Element <T> > > FetchElements(int bottom, int top) { if (top <= bottom) { throw new Exception("top can't be larger than bottom!"); } int sanityCheckCount = 0; while (true) { // See if we now have what they asked for, OR the list has elements but we don't have an after. // (this is the case when we have hit the end of the list) // #bug!?!? At some point I changed the children count in the after check to sanityCheckCount == 0, but I can't remember why // and it breaks lists that have ends. There is some bug where something doesn't try to refresh or something... if (m_currentElementList.Children.Count >= top || (m_currentElementList.Children.Count != 0 && m_currentElementList.After == null) || (sanityCheckCount > 25)) { // Return what they asked for capped at the list size int length = top - bottom; int listLength = m_currentElementList.Children.Count - bottom; length = Math.Min(length, listLength); // Set what the top was we returned. m_lastTopGet = bottom + length; return(m_currentElementList.Children.GetRange(bottom, length)); } // Figure out how many we need still. int numberNeeded = top - m_currentElementList.Children.Count; // Make the request. IHttpContent webResult = await MakeRequest(numberNeeded, m_currentElementList.After); // This will hold the root RootElement <T> root = null; // Get the input stream and json reader. // NOTE!! We are really careful not to use a string here so we don't have to allocate a huge string. IInputStream inputStream = await webResult.ReadAsInputStreamAsync(); using (StreamReader reader = new StreamReader(inputStream.AsStreamForRead())) using (JsonReader jsonReader = new JsonTextReader(reader)) { // Check if we have an array root or a object root if (m_isArrayRoot) { // Parse the Json as an object JsonSerializer serializer = new JsonSerializer(); List <RootElement <T> > arrayRoot = await Task.Run(() => serializer.Deserialize <List <RootElement <T> > >(jsonReader)); // Use which ever list element we want. if (m_takeFirstArrayRoot) { root = arrayRoot[0]; } else { root = arrayRoot[1]; } } else { // Parse the Json as an object JsonSerializer serializer = new JsonSerializer(); root = await Task.Run(() => serializer.Deserialize <RootElement <T> >(jsonReader)); } } // Copy the new contents into the current cache m_currentElementList.Children.AddRange(root.Data.Children); // Update the before and after m_currentElementList.After = root.Data.After; m_currentElementList.Before = root.Data.Before; sanityCheckCount++; } }