HttpClientManager.cs 24 KB

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