HttpClientManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  316. return response.TempFilePath;
  317. }
  318. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  319. {
  320. ValidateParams(options.Url, options.CancellationToken);
  321. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  322. if (options.Progress == null)
  323. {
  324. throw new ArgumentNullException("progress");
  325. }
  326. options.CancellationToken.ThrowIfCancellationRequested();
  327. if (options.ResourcePool != null)
  328. {
  329. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  330. }
  331. options.Progress.Report(0);
  332. _logger.Info("HttpClientManager.GetTempFile url: {0}, temp file: {1}", options.Url, tempFile);
  333. try
  334. {
  335. options.CancellationToken.ThrowIfCancellationRequested();
  336. using (var message = GetHttpRequestMessage(options))
  337. {
  338. using (var response = await GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression).HttpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, options.CancellationToken).ConfigureAwait(false))
  339. {
  340. EnsureSuccessStatusCode(response);
  341. options.CancellationToken.ThrowIfCancellationRequested();
  342. var contentLength = GetContentLength(response);
  343. if (!contentLength.HasValue)
  344. {
  345. // We're not able to track progress
  346. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  347. {
  348. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  349. {
  350. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  351. }
  352. }
  353. }
  354. else
  355. {
  356. using (var stream = ProgressStream.CreateReadProgressStream(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), options.Progress.Report, contentLength.Value))
  357. {
  358. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  359. {
  360. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  361. }
  362. }
  363. }
  364. options.Progress.Report(100);
  365. return new HttpResponseInfo
  366. {
  367. TempFilePath = tempFile,
  368. StatusCode = response.StatusCode,
  369. ContentType = response.Content.Headers.ContentType.MediaType
  370. };
  371. }
  372. }
  373. }
  374. catch (Exception ex)
  375. {
  376. throw GetTempFileException(ex, options, tempFile);
  377. }
  378. finally
  379. {
  380. if (options.ResourcePool != null)
  381. {
  382. options.ResourcePool.Release();
  383. }
  384. }
  385. }
  386. /// <summary>
  387. /// Gets the message.
  388. /// </summary>
  389. /// <param name="options">The options.</param>
  390. /// <returns>HttpResponseMessage.</returns>
  391. private HttpRequestMessage GetHttpRequestMessage(HttpRequestOptions options)
  392. {
  393. var message = new HttpRequestMessage(HttpMethod.Get, options.Url);
  394. if (!string.IsNullOrEmpty(options.UserAgent))
  395. {
  396. message.Headers.Add("User-Agent", options.UserAgent);
  397. }
  398. if (!string.IsNullOrEmpty(options.AcceptHeader))
  399. {
  400. message.Headers.Add("Accept", options.AcceptHeader);
  401. }
  402. return message;
  403. }
  404. /// <summary>
  405. /// Gets the length of the content.
  406. /// </summary>
  407. /// <param name="response">The response.</param>
  408. /// <returns>System.Nullable{System.Int64}.</returns>
  409. private long? GetContentLength(HttpResponseMessage response)
  410. {
  411. IEnumerable<string> lengthValues;
  412. if (!response.Headers.TryGetValues("content-length", out lengthValues) && !response.Content.Headers.TryGetValues("content-length", out lengthValues))
  413. {
  414. return null;
  415. }
  416. return long.Parse(string.Join(string.Empty, lengthValues.ToArray()), UsCulture);
  417. }
  418. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  419. /// <summary>
  420. /// Handles the temp file exception.
  421. /// </summary>
  422. /// <param name="ex">The ex.</param>
  423. /// <param name="options">The options.</param>
  424. /// <param name="tempFile">The temp file.</param>
  425. /// <returns>Task.</returns>
  426. /// <exception cref="HttpException"></exception>
  427. private Exception GetTempFileException(Exception ex, HttpRequestOptions options, string tempFile)
  428. {
  429. var operationCanceledException = ex as OperationCanceledException;
  430. if (operationCanceledException != null)
  431. {
  432. // Cleanup
  433. if (File.Exists(tempFile))
  434. {
  435. File.Delete(tempFile);
  436. }
  437. return GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  438. }
  439. _logger.ErrorException("Error getting response from " + options.Url, ex);
  440. var httpRequestException = ex as HttpRequestException;
  441. // Cleanup
  442. if (File.Exists(tempFile))
  443. {
  444. File.Delete(tempFile);
  445. }
  446. if (httpRequestException != null)
  447. {
  448. return new HttpException(ex.Message, ex);
  449. }
  450. return ex;
  451. }
  452. /// <summary>
  453. /// Validates the params.
  454. /// </summary>
  455. /// <param name="url">The URL.</param>
  456. /// <param name="cancellationToken">The cancellation token.</param>
  457. /// <exception cref="System.ArgumentNullException">url</exception>
  458. private void ValidateParams(string url, CancellationToken cancellationToken)
  459. {
  460. if (string.IsNullOrEmpty(url))
  461. {
  462. throw new ArgumentNullException("url");
  463. }
  464. if (cancellationToken == null)
  465. {
  466. throw new ArgumentNullException("cancellationToken");
  467. }
  468. }
  469. /// <summary>
  470. /// Gets the host from URL.
  471. /// </summary>
  472. /// <param name="url">The URL.</param>
  473. /// <returns>System.String.</returns>
  474. private string GetHostFromUrl(string url)
  475. {
  476. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  477. var len = url.IndexOf('/', start) - start;
  478. return url.Substring(start, len);
  479. }
  480. /// <summary>
  481. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  482. /// </summary>
  483. public void Dispose()
  484. {
  485. Dispose(true);
  486. GC.SuppressFinalize(this);
  487. }
  488. /// <summary>
  489. /// Releases unmanaged and - optionally - managed resources.
  490. /// </summary>
  491. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  492. protected virtual void Dispose(bool dispose)
  493. {
  494. if (dispose)
  495. {
  496. foreach (var client in _httpClients.Values.ToList())
  497. {
  498. client.HttpClient.Dispose();
  499. }
  500. _httpClients.Clear();
  501. }
  502. }
  503. /// <summary>
  504. /// Throws the cancellation exception.
  505. /// </summary>
  506. /// <param name="url">The URL.</param>
  507. /// <param name="cancellationToken">The cancellation token.</param>
  508. /// <param name="exception">The exception.</param>
  509. /// <returns>Exception.</returns>
  510. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  511. {
  512. // If the HttpClient's timeout is reached, it will cancel the Task internally
  513. if (!cancellationToken.IsCancellationRequested)
  514. {
  515. var msg = string.Format("Connection to {0} timed out", url);
  516. _logger.Error(msg);
  517. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  518. return new HttpException(msg, exception) { IsTimedOut = true };
  519. }
  520. return exception;
  521. }
  522. /// <summary>
  523. /// Ensures the success status code.
  524. /// </summary>
  525. /// <param name="response">The response.</param>
  526. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  527. private void EnsureSuccessStatusCode(HttpResponseMessage response)
  528. {
  529. if (!response.IsSuccessStatusCode)
  530. {
  531. throw new HttpException(response.ReasonPhrase) { StatusCode = response.StatusCode };
  532. }
  533. }
  534. /// <summary>
  535. /// Posts the specified URL.
  536. /// </summary>
  537. /// <param name="url">The URL.</param>
  538. /// <param name="postData">The post data.</param>
  539. /// <param name="cancellationToken">The cancellation token.</param>
  540. /// <returns>Task{Stream}.</returns>
  541. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  542. {
  543. return Post(url, postData, null, cancellationToken);
  544. }
  545. }
  546. }