HttpClientManager.cs 24 KB

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