HttpClientManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Net;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Net.Cache;
  15. using System.Net.Http;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Common.Implementations.HttpClientManager
  20. {
  21. /// <summary>
  22. /// Class HttpClientManager
  23. /// </summary>
  24. public class HttpClientManager : IHttpClient
  25. {
  26. /// <summary>
  27. /// The _logger
  28. /// </summary>
  29. private readonly ILogger _logger;
  30. /// <summary>
  31. /// The _app paths
  32. /// </summary>
  33. private readonly IApplicationPaths _appPaths;
  34. private readonly IJsonSerializer _jsonSerializer;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  37. /// </summary>
  38. /// <param name="appPaths">The kernel.</param>
  39. /// <param name="logger">The logger.</param>
  40. /// <param name="jsonSerializer">The json serializer.</param>
  41. /// <exception cref="System.ArgumentNullException">
  42. /// appPaths
  43. /// or
  44. /// logger
  45. /// </exception>
  46. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IJsonSerializer jsonSerializer)
  47. {
  48. if (appPaths == null)
  49. {
  50. throw new ArgumentNullException("appPaths");
  51. }
  52. if (logger == null)
  53. {
  54. throw new ArgumentNullException("logger");
  55. }
  56. _logger = logger;
  57. _jsonSerializer = jsonSerializer;
  58. _appPaths = appPaths;
  59. }
  60. /// <summary>
  61. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  62. /// DON'T dispose it after use.
  63. /// </summary>
  64. /// <value>The HTTP clients.</value>
  65. private readonly ConcurrentDictionary<string, HttpClient> _httpClients = new ConcurrentDictionary<string, HttpClient>();
  66. /// <summary>
  67. /// Gets
  68. /// </summary>
  69. /// <param name="host">The host.</param>
  70. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  71. /// <returns>HttpClient.</returns>
  72. /// <exception cref="System.ArgumentNullException">host</exception>
  73. private HttpClient GetHttpClient(string host, bool enableHttpCompression)
  74. {
  75. if (string.IsNullOrEmpty(host))
  76. {
  77. throw new ArgumentNullException("host");
  78. }
  79. HttpClient client;
  80. var key = host + enableHttpCompression;
  81. if (!_httpClients.TryGetValue(key, out client))
  82. {
  83. var handler = new WebRequestHandler
  84. {
  85. CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache),
  86. AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None
  87. };
  88. client = new HttpClient(handler);
  89. client.Timeout = TimeSpan.FromSeconds(20);
  90. _httpClients.TryAdd(key, client);
  91. }
  92. return client;
  93. }
  94. /// <summary>
  95. /// Performs a GET request and returns the resulting stream
  96. /// </summary>
  97. /// <param name="options">The options.</param>
  98. /// <returns>Task{Stream}.</returns>
  99. /// <exception cref="HttpException"></exception>
  100. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  101. public async Task<Stream> Get(HttpRequestOptions options)
  102. {
  103. ValidateParams(options.Url, options.CancellationToken);
  104. options.CancellationToken.ThrowIfCancellationRequested();
  105. using (var message = GetHttpRequestMessage(options))
  106. {
  107. if (options.ResourcePool != null)
  108. {
  109. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  110. }
  111. _logger.Info("HttpClientManager.Get url: {0}", options.Url);
  112. try
  113. {
  114. options.CancellationToken.ThrowIfCancellationRequested();
  115. var response = await GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression).SendAsync(message, HttpCompletionOption.ResponseContentRead, options.CancellationToken).ConfigureAwait(false);
  116. EnsureSuccessStatusCode(response);
  117. options.CancellationToken.ThrowIfCancellationRequested();
  118. return await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  119. }
  120. catch (OperationCanceledException ex)
  121. {
  122. throw GetCancellationException(options.Url, options.CancellationToken, ex);
  123. }
  124. catch (HttpRequestException ex)
  125. {
  126. _logger.ErrorException("Error getting response from " + options.Url, ex);
  127. throw new HttpException(ex.Message, ex);
  128. }
  129. catch (Exception ex)
  130. {
  131. _logger.ErrorException("Error getting response from " + options.Url, ex);
  132. throw;
  133. }
  134. finally
  135. {
  136. if (options.ResourcePool != null)
  137. {
  138. options.ResourcePool.Release();
  139. }
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// Performs a GET request and returns the resulting stream
  145. /// </summary>
  146. /// <param name="url">The URL.</param>
  147. /// <param name="resourcePool">The resource pool.</param>
  148. /// <param name="cancellationToken">The cancellation token.</param>
  149. /// <returns>Task{Stream}.</returns>
  150. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  151. {
  152. return Get(new HttpRequestOptions
  153. {
  154. Url = url,
  155. ResourcePool = resourcePool,
  156. CancellationToken = cancellationToken,
  157. });
  158. }
  159. /// <summary>
  160. /// Gets the specified URL.
  161. /// </summary>
  162. /// <param name="url">The URL.</param>
  163. /// <param name="cancellationToken">The cancellation token.</param>
  164. /// <returns>Task{Stream}.</returns>
  165. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  166. {
  167. return Get(url, null, cancellationToken);
  168. }
  169. /// <summary>
  170. /// Gets the cached response.
  171. /// </summary>
  172. /// <param name="responsePath">The response path.</param>
  173. /// <returns>Stream.</returns>
  174. private Stream GetCachedResponse(string responsePath)
  175. {
  176. return File.OpenRead(responsePath);
  177. }
  178. /// <summary>
  179. /// Updates the cache.
  180. /// </summary>
  181. /// <param name="cachedInfo">The cached info.</param>
  182. /// <param name="url">The URL.</param>
  183. /// <param name="path">The path.</param>
  184. /// <param name="response">The response.</param>
  185. private HttpResponseInfo UpdateInfoCache(HttpResponseInfo cachedInfo, string url, string path, HttpResponseMessage response)
  186. {
  187. var fileExists = true;
  188. if (cachedInfo == null)
  189. {
  190. cachedInfo = new HttpResponseInfo();
  191. fileExists = false;
  192. }
  193. cachedInfo.Url = url;
  194. cachedInfo.RequestDate = DateTime.UtcNow;
  195. var etag = response.Headers.ETag;
  196. if (etag != null)
  197. {
  198. cachedInfo.Etag = etag.Tag;
  199. }
  200. var modified = response.Content.Headers.LastModified;
  201. if (modified.HasValue)
  202. {
  203. cachedInfo.LastModified = modified.Value.UtcDateTime;
  204. }
  205. else if (response.Headers.Age.HasValue)
  206. {
  207. cachedInfo.LastModified = DateTime.UtcNow.Subtract(response.Headers.Age.Value);
  208. }
  209. var expires = response.Content.Headers.Expires;
  210. if (expires.HasValue)
  211. {
  212. cachedInfo.Expires = expires.Value.UtcDateTime;
  213. }
  214. else
  215. {
  216. var cacheControl = response.Headers.CacheControl;
  217. if (cacheControl != null)
  218. {
  219. if (cacheControl.MaxAge.HasValue)
  220. {
  221. var baseline = cachedInfo.LastModified ?? DateTime.UtcNow;
  222. cachedInfo.Expires = baseline.Add(cacheControl.MaxAge.Value);
  223. }
  224. cachedInfo.MustRevalidate = cacheControl.MustRevalidate;
  225. }
  226. }
  227. if (string.IsNullOrEmpty(cachedInfo.Etag) && !cachedInfo.Expires.HasValue && !cachedInfo.LastModified.HasValue)
  228. {
  229. // Nothing to cache
  230. if (fileExists)
  231. {
  232. File.Delete(path);
  233. }
  234. }
  235. else
  236. {
  237. _jsonSerializer.SerializeToFile(cachedInfo, path);
  238. }
  239. return cachedInfo;
  240. }
  241. /// <summary>
  242. /// Updates the response cache.
  243. /// </summary>
  244. /// <param name="response">The response.</param>
  245. /// <param name="path">The path.</param>
  246. /// <returns>Task.</returns>
  247. private async Task UpdateResponseCache(HttpResponseMessage response, string path)
  248. {
  249. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  250. {
  251. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  252. {
  253. await stream.CopyToAsync(fs).ConfigureAwait(false);
  254. }
  255. }
  256. }
  257. /// <summary>
  258. /// Performs a POST request
  259. /// </summary>
  260. /// <param name="url">The URL.</param>
  261. /// <param name="postData">Params to add to the POST data.</param>
  262. /// <param name="resourcePool">The resource pool.</param>
  263. /// <param name="cancellationToken">The cancellation token.</param>
  264. /// <returns>stream on success, null on failure</returns>
  265. /// <exception cref="System.ArgumentNullException">postData</exception>
  266. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  267. public async Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  268. {
  269. ValidateParams(url, cancellationToken);
  270. if (postData == null)
  271. {
  272. throw new ArgumentNullException("postData");
  273. }
  274. cancellationToken.ThrowIfCancellationRequested();
  275. var strings = postData.Keys.Select(key => string.Format("{0}={1}", key, postData[key]));
  276. var postContent = string.Join("&", strings.ToArray());
  277. var content = new StringContent(postContent, Encoding.UTF8, "application/x-www-form-urlencoded");
  278. if (resourcePool != null)
  279. {
  280. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  281. }
  282. _logger.Info("HttpClientManager.Post url: {0}", url);
  283. try
  284. {
  285. cancellationToken.ThrowIfCancellationRequested();
  286. var msg = await GetHttpClient(GetHostFromUrl(url), false).PostAsync(url, content, cancellationToken).ConfigureAwait(false);
  287. EnsureSuccessStatusCode(msg);
  288. return await msg.Content.ReadAsStreamAsync().ConfigureAwait(false);
  289. }
  290. catch (OperationCanceledException ex)
  291. {
  292. throw GetCancellationException(url, cancellationToken, ex);
  293. }
  294. catch (HttpRequestException ex)
  295. {
  296. _logger.ErrorException("Error getting response from " + url, ex);
  297. throw new HttpException(ex.Message, ex);
  298. }
  299. finally
  300. {
  301. if (resourcePool != null)
  302. {
  303. resourcePool.Release();
  304. }
  305. }
  306. }
  307. /// <summary>
  308. /// Downloads the contents of a given url into a temporary location
  309. /// </summary>
  310. /// <param name="options">The options.</param>
  311. /// <returns>Task{System.String}.</returns>
  312. /// <exception cref="System.ArgumentNullException">progress</exception>
  313. /// <exception cref="HttpException"></exception>
  314. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  315. public async Task<string> GetTempFile(HttpRequestOptions options)
  316. {
  317. ValidateParams(options.Url, options.CancellationToken);
  318. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  319. if (options.Progress == null)
  320. {
  321. throw new ArgumentNullException("progress");
  322. }
  323. options.CancellationToken.ThrowIfCancellationRequested();
  324. if (options.ResourcePool != null)
  325. {
  326. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  327. }
  328. options.Progress.Report(0);
  329. _logger.Info("HttpClientManager.GetTempFile url: {0}, temp file: {1}", options.Url, tempFile);
  330. try
  331. {
  332. options.CancellationToken.ThrowIfCancellationRequested();
  333. using (var message = GetHttpRequestMessage(options))
  334. {
  335. using (var response = await GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression).SendAsync(message, HttpCompletionOption.ResponseHeadersRead, options.CancellationToken).ConfigureAwait(false))
  336. {
  337. EnsureSuccessStatusCode(response);
  338. options.CancellationToken.ThrowIfCancellationRequested();
  339. var contentLength = GetContentLength(response);
  340. if (!contentLength.HasValue)
  341. {
  342. // We're not able to track progress
  343. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  344. {
  345. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  346. {
  347. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  348. }
  349. }
  350. }
  351. else
  352. {
  353. using (var stream = ProgressStream.CreateReadProgressStream(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), options.Progress.Report, contentLength.Value))
  354. {
  355. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  356. {
  357. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  358. }
  359. }
  360. }
  361. options.Progress.Report(100);
  362. options.CancellationToken.ThrowIfCancellationRequested();
  363. }
  364. }
  365. }
  366. catch (Exception ex)
  367. {
  368. HandleTempFileException(ex, options, tempFile);
  369. }
  370. finally
  371. {
  372. if (options.ResourcePool != null)
  373. {
  374. options.ResourcePool.Release();
  375. }
  376. }
  377. return tempFile;
  378. }
  379. /// <summary>
  380. /// Gets the message.
  381. /// </summary>
  382. /// <param name="options">The options.</param>
  383. /// <returns>HttpResponseMessage.</returns>
  384. private HttpRequestMessage GetHttpRequestMessage(HttpRequestOptions options)
  385. {
  386. var message = new HttpRequestMessage(HttpMethod.Get, options.Url);
  387. if (!string.IsNullOrEmpty(options.UserAgent))
  388. {
  389. message.Headers.Add("User-Agent", options.UserAgent);
  390. }
  391. if (!string.IsNullOrEmpty(options.AcceptHeader))
  392. {
  393. message.Headers.Add("Accept", options.AcceptHeader);
  394. }
  395. return message;
  396. }
  397. /// <summary>
  398. /// Gets the length of the content.
  399. /// </summary>
  400. /// <param name="response">The response.</param>
  401. /// <returns>System.Nullable{System.Int64}.</returns>
  402. private long? GetContentLength(HttpResponseMessage response)
  403. {
  404. IEnumerable<string> lengthValues;
  405. if (!response.Headers.TryGetValues("content-length", out lengthValues) && !response.Content.Headers.TryGetValues("content-length", out lengthValues))
  406. {
  407. return null;
  408. }
  409. return long.Parse(string.Join(string.Empty, lengthValues.ToArray()), UsCulture);
  410. }
  411. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  412. /// <summary>
  413. /// Handles the temp file exception.
  414. /// </summary>
  415. /// <param name="ex">The ex.</param>
  416. /// <param name="options">The options.</param>
  417. /// <param name="tempFile">The temp file.</param>
  418. /// <returns>Task.</returns>
  419. /// <exception cref="HttpException"></exception>
  420. private void HandleTempFileException(Exception ex, HttpRequestOptions options, string tempFile)
  421. {
  422. var operationCanceledException = ex as OperationCanceledException;
  423. if (operationCanceledException != null)
  424. {
  425. // Cleanup
  426. if (File.Exists(tempFile))
  427. {
  428. File.Delete(tempFile);
  429. }
  430. throw GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  431. }
  432. _logger.ErrorException("Error getting response from " + options.Url, ex);
  433. var httpRequestException = ex as HttpRequestException;
  434. // Cleanup
  435. if (File.Exists(tempFile))
  436. {
  437. File.Delete(tempFile);
  438. }
  439. if (httpRequestException != null)
  440. {
  441. throw new HttpException(ex.Message, ex);
  442. }
  443. throw ex;
  444. }
  445. /// <summary>
  446. /// Validates the params.
  447. /// </summary>
  448. /// <param name="url">The URL.</param>
  449. /// <param name="cancellationToken">The cancellation token.</param>
  450. /// <exception cref="System.ArgumentNullException">url</exception>
  451. private void ValidateParams(string url, CancellationToken cancellationToken)
  452. {
  453. if (string.IsNullOrEmpty(url))
  454. {
  455. throw new ArgumentNullException("url");
  456. }
  457. if (cancellationToken == null)
  458. {
  459. throw new ArgumentNullException("cancellationToken");
  460. }
  461. }
  462. /// <summary>
  463. /// Gets the host from URL.
  464. /// </summary>
  465. /// <param name="url">The URL.</param>
  466. /// <returns>System.String.</returns>
  467. private string GetHostFromUrl(string url)
  468. {
  469. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  470. var len = url.IndexOf('/', start) - start;
  471. return url.Substring(start, len);
  472. }
  473. /// <summary>
  474. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  475. /// </summary>
  476. public void Dispose()
  477. {
  478. Dispose(true);
  479. GC.SuppressFinalize(this);
  480. }
  481. /// <summary>
  482. /// Releases unmanaged and - optionally - managed resources.
  483. /// </summary>
  484. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  485. protected virtual void Dispose(bool dispose)
  486. {
  487. if (dispose)
  488. {
  489. foreach (var client in _httpClients.Values.ToList())
  490. {
  491. client.Dispose();
  492. }
  493. _httpClients.Clear();
  494. }
  495. }
  496. /// <summary>
  497. /// Throws the cancellation exception.
  498. /// </summary>
  499. /// <param name="url">The URL.</param>
  500. /// <param name="cancellationToken">The cancellation token.</param>
  501. /// <param name="exception">The exception.</param>
  502. /// <returns>Exception.</returns>
  503. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  504. {
  505. // If the HttpClient's timeout is reached, it will cancel the Task internally
  506. if (!cancellationToken.IsCancellationRequested)
  507. {
  508. var msg = string.Format("Connection to {0} timed out", url);
  509. _logger.Error(msg);
  510. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  511. return new HttpException(msg, exception) { IsTimedOut = true };
  512. }
  513. return exception;
  514. }
  515. /// <summary>
  516. /// Ensures the success status code.
  517. /// </summary>
  518. /// <param name="response">The response.</param>
  519. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  520. private void EnsureSuccessStatusCode(HttpResponseMessage response)
  521. {
  522. if (!response.IsSuccessStatusCode)
  523. {
  524. throw new HttpException(response.ReasonPhrase) { StatusCode = response.StatusCode };
  525. }
  526. }
  527. /// <summary>
  528. /// Posts the specified URL.
  529. /// </summary>
  530. /// <param name="url">The URL.</param>
  531. /// <param name="postData">The post data.</param>
  532. /// <param name="cancellationToken">The cancellation token.</param>
  533. /// <returns>Task{Stream}.</returns>
  534. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  535. {
  536. return Post(url, postData, null, cancellationToken);
  537. }
  538. }
  539. }