HttpManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Kernel;
  3. using MediaBrowser.Model.Logging;
  4. using MediaBrowser.Model.Net;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Cache;
  12. using System.Net.Http;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Common.Net
  17. {
  18. /// <summary>
  19. /// Class HttpManager
  20. /// </summary>
  21. public class HttpManager : BaseManager<IKernel>
  22. {
  23. /// <summary>
  24. /// The _logger
  25. /// </summary>
  26. private readonly ILogger _logger;
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="HttpManager" /> class.
  29. /// </summary>
  30. /// <param name="kernel">The kernel.</param>
  31. /// <param name="logger">The logger.</param>
  32. public HttpManager(IKernel kernel, ILogger logger)
  33. : base(kernel)
  34. {
  35. _logger = logger;
  36. }
  37. /// <summary>
  38. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  39. /// DON'T dispose it after use.
  40. /// </summary>
  41. /// <value>The HTTP clients.</value>
  42. private readonly ConcurrentDictionary<string, HttpClient> _httpClients = new ConcurrentDictionary<string, HttpClient>();
  43. /// <summary>
  44. /// Gets
  45. /// </summary>
  46. /// <param name="host">The host.</param>
  47. /// <returns>HttpClient.</returns>
  48. /// <exception cref="System.ArgumentNullException">host</exception>
  49. private HttpClient GetHttpClient(string host)
  50. {
  51. if (string.IsNullOrEmpty(host))
  52. {
  53. throw new ArgumentNullException("host");
  54. }
  55. HttpClient client;
  56. if (!_httpClients.TryGetValue(host, out client))
  57. {
  58. var handler = new WebRequestHandler
  59. {
  60. AutomaticDecompression = DecompressionMethods.Deflate,
  61. CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate)
  62. };
  63. client = new HttpClient(handler);
  64. client.DefaultRequestHeaders.Add("Accept", "application/json,image/*");
  65. client.Timeout = TimeSpan.FromSeconds(15);
  66. _httpClients.TryAdd(host, client);
  67. }
  68. return client;
  69. }
  70. /// <summary>
  71. /// Performs a GET request and returns the resulting stream
  72. /// </summary>
  73. /// <param name="url">The URL.</param>
  74. /// <param name="resourcePool">The resource pool.</param>
  75. /// <param name="cancellationToken">The cancellation token.</param>
  76. /// <returns>Task{Stream}.</returns>
  77. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  78. public async Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  79. {
  80. ValidateParams(url, resourcePool, cancellationToken);
  81. cancellationToken.ThrowIfCancellationRequested();
  82. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  83. _logger.Info("HttpManager.Get url: {0}", url);
  84. try
  85. {
  86. cancellationToken.ThrowIfCancellationRequested();
  87. var msg = await GetHttpClient(GetHostFromUrl(url)).GetAsync(url, cancellationToken).ConfigureAwait(false);
  88. EnsureSuccessStatusCode(msg);
  89. return await msg.Content.ReadAsStreamAsync().ConfigureAwait(false);
  90. }
  91. catch (OperationCanceledException ex)
  92. {
  93. throw GetCancellationException(url, cancellationToken, ex);
  94. }
  95. catch (HttpRequestException ex)
  96. {
  97. _logger.ErrorException("Error getting response from " + url, ex);
  98. throw new HttpException(ex.Message, ex);
  99. }
  100. finally
  101. {
  102. resourcePool.Release();
  103. }
  104. }
  105. /// <summary>
  106. /// Performs a POST request
  107. /// </summary>
  108. /// <param name="url">The URL.</param>
  109. /// <param name="postData">Params to add to the POST data.</param>
  110. /// <param name="resourcePool">The resource pool.</param>
  111. /// <param name="cancellationToken">The cancellation token.</param>
  112. /// <returns>stream on success, null on failure</returns>
  113. /// <exception cref="System.ArgumentNullException">postData</exception>
  114. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  115. public async Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  116. {
  117. ValidateParams(url, resourcePool, cancellationToken);
  118. if (postData == null)
  119. {
  120. throw new ArgumentNullException("postData");
  121. }
  122. cancellationToken.ThrowIfCancellationRequested();
  123. var strings = postData.Keys.Select(key => string.Format("{0}={1}", key, postData[key]));
  124. var postContent = string.Join("&", strings.ToArray());
  125. var content = new StringContent(postContent, Encoding.UTF8, "application/x-www-form-urlencoded");
  126. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  127. _logger.Info("HttpManager.Post url: {0}", url);
  128. try
  129. {
  130. cancellationToken.ThrowIfCancellationRequested();
  131. var msg = await GetHttpClient(GetHostFromUrl(url)).PostAsync(url, content, cancellationToken).ConfigureAwait(false);
  132. EnsureSuccessStatusCode(msg);
  133. return await msg.Content.ReadAsStreamAsync().ConfigureAwait(false);
  134. }
  135. catch (OperationCanceledException ex)
  136. {
  137. throw GetCancellationException(url, cancellationToken, ex);
  138. }
  139. catch (HttpRequestException ex)
  140. {
  141. _logger.ErrorException("Error getting response from " + url, ex);
  142. throw new HttpException(ex.Message, ex);
  143. }
  144. finally
  145. {
  146. resourcePool.Release();
  147. }
  148. }
  149. /// <summary>
  150. /// Downloads the contents of a given url into a temporary location
  151. /// </summary>
  152. /// <param name="url">The URL.</param>
  153. /// <param name="resourcePool">The resource pool.</param>
  154. /// <param name="cancellationToken">The cancellation token.</param>
  155. /// <param name="progress">The progress.</param>
  156. /// <param name="userAgent">The user agent.</param>
  157. /// <returns>Task{System.String}.</returns>
  158. /// <exception cref="System.ArgumentNullException">progress</exception>
  159. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  160. public async Task<string> FetchToTempFile(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken, IProgress<double> progress, string userAgent = null)
  161. {
  162. ValidateParams(url, resourcePool, cancellationToken);
  163. if (progress == null)
  164. {
  165. throw new ArgumentNullException("progress");
  166. }
  167. cancellationToken.ThrowIfCancellationRequested();
  168. var tempFile = Path.Combine(Kernel.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  169. var message = new HttpRequestMessage(HttpMethod.Get, url);
  170. if (!string.IsNullOrEmpty(userAgent))
  171. {
  172. message.Headers.Add("User-Agent", userAgent);
  173. }
  174. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  175. _logger.Info("HttpManager.FetchToTempFile url: {0}, temp file: {1}", url, tempFile);
  176. try
  177. {
  178. cancellationToken.ThrowIfCancellationRequested();
  179. using (var response = await GetHttpClient(GetHostFromUrl(url)).SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
  180. {
  181. EnsureSuccessStatusCode(response);
  182. cancellationToken.ThrowIfCancellationRequested();
  183. IEnumerable<string> lengthValues;
  184. if (!response.Headers.TryGetValues("content-length", out lengthValues) &&
  185. !response.Content.Headers.TryGetValues("content-length", out lengthValues))
  186. {
  187. // We're not able to track progress
  188. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  189. {
  190. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  191. {
  192. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  193. }
  194. }
  195. }
  196. else
  197. {
  198. var length = long.Parse(string.Join(string.Empty, lengthValues.ToArray()));
  199. using (var stream = ProgressStream.CreateReadProgressStream(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), progress.Report, length))
  200. {
  201. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  202. {
  203. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  204. }
  205. }
  206. }
  207. progress.Report(100);
  208. cancellationToken.ThrowIfCancellationRequested();
  209. }
  210. return tempFile;
  211. }
  212. catch (OperationCanceledException ex)
  213. {
  214. // Cleanup
  215. if (File.Exists(tempFile))
  216. {
  217. File.Delete(tempFile);
  218. }
  219. throw GetCancellationException(url, cancellationToken, ex);
  220. }
  221. catch (HttpRequestException ex)
  222. {
  223. _logger.ErrorException("Error getting response from " + url, ex);
  224. // Cleanup
  225. if (File.Exists(tempFile))
  226. {
  227. File.Delete(tempFile);
  228. }
  229. throw new HttpException(ex.Message, ex);
  230. }
  231. catch (Exception ex)
  232. {
  233. _logger.ErrorException("Error getting response from " + url, ex);
  234. // Cleanup
  235. if (File.Exists(tempFile))
  236. {
  237. File.Delete(tempFile);
  238. }
  239. throw;
  240. }
  241. finally
  242. {
  243. resourcePool.Release();
  244. }
  245. }
  246. /// <summary>
  247. /// Downloads the contents of a given url into a MemoryStream
  248. /// </summary>
  249. /// <param name="url">The URL.</param>
  250. /// <param name="resourcePool">The resource pool.</param>
  251. /// <param name="cancellationToken">The cancellation token.</param>
  252. /// <returns>Task{MemoryStream}.</returns>
  253. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  254. public async Task<MemoryStream> FetchToMemoryStream(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  255. {
  256. ValidateParams(url, resourcePool, cancellationToken);
  257. cancellationToken.ThrowIfCancellationRequested();
  258. var message = new HttpRequestMessage(HttpMethod.Get, url);
  259. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  260. var ms = new MemoryStream();
  261. _logger.Info("HttpManager.FetchToMemoryStream url: {0}", url);
  262. try
  263. {
  264. cancellationToken.ThrowIfCancellationRequested();
  265. using (var response = await GetHttpClient(GetHostFromUrl(url)).SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
  266. {
  267. EnsureSuccessStatusCode(response);
  268. cancellationToken.ThrowIfCancellationRequested();
  269. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  270. {
  271. await stream.CopyToAsync(ms, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  272. }
  273. cancellationToken.ThrowIfCancellationRequested();
  274. }
  275. ms.Position = 0;
  276. return ms;
  277. }
  278. catch (OperationCanceledException ex)
  279. {
  280. ms.Dispose();
  281. throw GetCancellationException(url, cancellationToken, ex);
  282. }
  283. catch (HttpRequestException ex)
  284. {
  285. _logger.ErrorException("Error getting response from " + url, ex);
  286. ms.Dispose();
  287. throw new HttpException(ex.Message, ex);
  288. }
  289. catch (Exception ex)
  290. {
  291. _logger.ErrorException("Error getting response from " + url, ex);
  292. ms.Dispose();
  293. throw;
  294. }
  295. finally
  296. {
  297. resourcePool.Release();
  298. }
  299. }
  300. /// <summary>
  301. /// Validates the params.
  302. /// </summary>
  303. /// <param name="url">The URL.</param>
  304. /// <param name="resourcePool">The resource pool.</param>
  305. /// <param name="cancellationToken">The cancellation token.</param>
  306. /// <exception cref="System.ArgumentNullException">url</exception>
  307. private void ValidateParams(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  308. {
  309. if (string.IsNullOrEmpty(url))
  310. {
  311. throw new ArgumentNullException("url");
  312. }
  313. if (resourcePool == null)
  314. {
  315. throw new ArgumentNullException("resourcePool");
  316. }
  317. if (cancellationToken == null)
  318. {
  319. throw new ArgumentNullException("cancellationToken");
  320. }
  321. }
  322. /// <summary>
  323. /// Gets the host from URL.
  324. /// </summary>
  325. /// <param name="url">The URL.</param>
  326. /// <returns>System.String.</returns>
  327. private string GetHostFromUrl(string url)
  328. {
  329. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  330. var len = url.IndexOf('/', start) - start;
  331. return url.Substring(start, len);
  332. }
  333. /// <summary>
  334. /// Releases unmanaged and - optionally - managed resources.
  335. /// </summary>
  336. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  337. protected override void Dispose(bool dispose)
  338. {
  339. if (dispose)
  340. {
  341. foreach (var client in _httpClients.Values.ToList())
  342. {
  343. client.Dispose();
  344. }
  345. _httpClients.Clear();
  346. }
  347. base.Dispose(dispose);
  348. }
  349. /// <summary>
  350. /// Throws the cancellation exception.
  351. /// </summary>
  352. /// <param name="url">The URL.</param>
  353. /// <param name="cancellationToken">The cancellation token.</param>
  354. /// <param name="exception">The exception.</param>
  355. /// <returns>Exception.</returns>
  356. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  357. {
  358. // If the HttpClient's timeout is reached, it will cancel the Task internally
  359. if (!cancellationToken.IsCancellationRequested)
  360. {
  361. var msg = string.Format("Connection to {0} timed out", url);
  362. _logger.Error(msg);
  363. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  364. return new HttpException(msg, exception) { IsTimedOut = true };
  365. }
  366. return exception;
  367. }
  368. /// <summary>
  369. /// Ensures the success status code.
  370. /// </summary>
  371. /// <param name="response">The response.</param>
  372. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  373. private void EnsureSuccessStatusCode(HttpResponseMessage response)
  374. {
  375. if (!response.IsSuccessStatusCode)
  376. {
  377. throw new HttpException(response.ReasonPhrase) { StatusCode = response.StatusCode };
  378. }
  379. }
  380. }
  381. }