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.8 kB

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