You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

HttpMixin.cs 5.7 kB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. //From https://github.com/akavache/Akavache
  2. //Copyright (c) 2012 GitHub
  3. //TODO: Remove once netstandard support is added
  4. #pragma warning disable CS0618
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Net;
  10. using System.Reactive;
  11. using System.Reactive.Linq;
  12. using System.Reactive.Subjects;
  13. using System.Reactive.Threading.Tasks;
  14. using System.Text;
  15. using Akavache;
  16. namespace Discord.Net
  17. {
  18. public class HttpMixin : IAkavacheHttpMixin
  19. {
  20. /// <summary>
  21. /// Download data from an HTTP URL and insert the result into the
  22. /// cache. If the data is already in the cache, this returns
  23. /// a cached value. The URL itself is used as the key.
  24. /// </summary>
  25. /// <param name="url">The URL to download.</param>
  26. /// <param name="headers">
  27. /// An optional Dictionary containing the HTTP
  28. /// request headers.
  29. /// </param>
  30. /// <param name="fetchAlways">Force a web request to always be issued, skipping the cache.</param>
  31. /// <param name="absoluteExpiration">An optional expiration date.</param>
  32. /// <returns>The data downloaded from the URL.</returns>
  33. public IObservable<byte[]> DownloadUrl(IBlobCache This, string url, IDictionary<string, string> headers = null,
  34. bool fetchAlways = false, DateTimeOffset? absoluteExpiration = null) =>
  35. This.DownloadUrl(url, url, headers, fetchAlways, absoluteExpiration);
  36. /// <summary>
  37. /// Download data from an HTTP URL and insert the result into the
  38. /// cache. If the data is already in the cache, this returns
  39. /// a cached value. An explicit key is provided rather than the URL itself.
  40. /// </summary>
  41. /// <param name="key">The key to store with.</param>
  42. /// <param name="url">The URL to download.</param>
  43. /// <param name="headers">
  44. /// An optional Dictionary containing the HTTP
  45. /// request headers.
  46. /// </param>
  47. /// <param name="fetchAlways">Force a web request to always be issued, skipping the cache.</param>
  48. /// <param name="absoluteExpiration">An optional expiration date.</param>
  49. /// <returns>The data downloaded from the URL.</returns>
  50. public IObservable<byte[]> DownloadUrl(IBlobCache This, string key, string url,
  51. IDictionary<string, string> headers = null, bool fetchAlways = false,
  52. DateTimeOffset? absoluteExpiration = null)
  53. {
  54. var doFetch = MakeWebRequest(new Uri(url), headers)
  55. .SelectMany(x => ProcessWebResponse(x, url, absoluteExpiration));
  56. var fetchAndCache = doFetch.SelectMany(x => This.Insert(key, x, absoluteExpiration).Select(_ => x));
  57. var ret = !fetchAlways ? This.Get(key).Catch(fetchAndCache) : fetchAndCache;
  58. var conn = ret.PublishLast();
  59. conn.Connect();
  60. return conn;
  61. }
  62. private IObservable<byte[]> ProcessWebResponse(WebResponse wr, string url, DateTimeOffset? absoluteExpiration)
  63. {
  64. var hwr = (HttpWebResponse)wr;
  65. Debug.Assert(hwr != null, "The Web Response is somehow null but shouldn't be.");
  66. if ((int)hwr.StatusCode >= 400) return Observable.Throw<byte[]>(new WebException(hwr.StatusDescription));
  67. var ms = new MemoryStream();
  68. using (var responseStream = hwr.GetResponseStream())
  69. {
  70. Debug.Assert(responseStream != null, "The response stream is somehow null");
  71. responseStream.CopyTo(ms);
  72. }
  73. var ret = ms.ToArray();
  74. return Observable.Return(ret);
  75. }
  76. private static IObservable<WebResponse> MakeWebRequest(
  77. Uri uri,
  78. IDictionary<string, string> headers = null,
  79. string content = null,
  80. int retries = 3,
  81. TimeSpan? timeout = null)
  82. {
  83. var request = Observable.Defer(() =>
  84. {
  85. var hwr = CreateWebRequest(uri, headers);
  86. if (content == null)
  87. return Observable.FromAsyncPattern(hwr.BeginGetResponse, hwr.EndGetResponse)();
  88. var buf = Encoding.UTF8.GetBytes(content);
  89. // NB: You'd think that BeginGetResponse would never block,
  90. // seeing as how it's asynchronous. You'd be wrong :-/
  91. var ret = new AsyncSubject<WebResponse>();
  92. Observable.Start(() =>
  93. {
  94. Observable.FromAsyncPattern(hwr.BeginGetRequestStream, hwr.EndGetRequestStream)()
  95. .SelectMany(x => WriteAsyncRx(x, buf, 0, buf.Length))
  96. .SelectMany(_ => Observable.FromAsyncPattern(hwr.BeginGetResponse, hwr.EndGetResponse)())
  97. .Multicast(ret).Connect();
  98. }, BlobCache.TaskpoolScheduler);
  99. return ret;
  100. });
  101. return request.Timeout(timeout ?? TimeSpan.FromSeconds(15), BlobCache.TaskpoolScheduler).Retry(retries);
  102. }
  103. private static WebRequest CreateWebRequest(Uri uri, IDictionary<string, string> headers)
  104. {
  105. var hwr = WebRequest.Create(uri);
  106. if (headers == null) return hwr;
  107. foreach (var x in headers)
  108. hwr.Headers[x.Key] = x.Value;
  109. return hwr;
  110. }
  111. private static IObservable<Unit> WriteAsyncRx(Stream stream, byte[] data, int start, int length) =>
  112. stream.WriteAsync(data, start, length).ToObservable();
  113. }
  114. }