HttpClientManager.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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 HttpClient GetHttpClientHandler(bool enableHttpCompression);
  32. private readonly GetHttpClientHandler _getHttpClientHandler;
  33. private readonly IFileSystem _fileSystem;
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="HttpClientManager"/> class.
  36. /// </summary>
  37. /// <param name="appPaths">The app paths.</param>
  38. /// <param name="logger">The logger.</param>
  39. /// <param name="getHttpClientHandler">The get HTTP client handler.</param>
  40. /// <exception cref="System.ArgumentNullException">
  41. /// appPaths
  42. /// or
  43. /// logger
  44. /// </exception>
  45. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, GetHttpClientHandler getHttpClientHandler, IFileSystem fileSystem)
  46. {
  47. if (appPaths == null)
  48. {
  49. throw new ArgumentNullException("appPaths");
  50. }
  51. if (logger == null)
  52. {
  53. throw new ArgumentNullException("logger");
  54. }
  55. _logger = logger;
  56. _getHttpClientHandler = getHttpClientHandler;
  57. _fileSystem = fileSystem;
  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, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  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 HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  74. {
  75. if (string.IsNullOrEmpty(host))
  76. {
  77. throw new ArgumentNullException("host");
  78. }
  79. HttpClientInfo client;
  80. var key = host + enableHttpCompression;
  81. if (!_httpClients.TryGetValue(key, out client))
  82. {
  83. client = new HttpClientInfo
  84. {
  85. HttpClient = _getHttpClientHandler(enableHttpCompression)
  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 = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  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 = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  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.ToList())
  391. {
  392. if (!message.Headers.TryAddWithoutValidation(pair.Key, pair.Value))
  393. {
  394. _logger.Error("Unable to add request header {0} with value {1}", pair.Key, pair.Value);
  395. }
  396. }
  397. return message;
  398. }
  399. /// <summary>
  400. /// Gets the length of the content.
  401. /// </summary>
  402. /// <param name="response">The response.</param>
  403. /// <returns>System.Nullable{System.Int64}.</returns>
  404. private long? GetContentLength(HttpResponseMessage response)
  405. {
  406. IEnumerable<string> lengthValues = null;
  407. // Seeing some InvalidOperationException here under mono
  408. try
  409. {
  410. response.Headers.TryGetValues("content-length", out lengthValues);
  411. }
  412. catch (InvalidOperationException ex)
  413. {
  414. _logger.ErrorException("Error accessing response.Headers.TryGetValues Content-Length", ex);
  415. }
  416. if (lengthValues == null)
  417. {
  418. try
  419. {
  420. response.Content.Headers.TryGetValues("content-length", out lengthValues);
  421. }
  422. catch (InvalidOperationException ex)
  423. {
  424. _logger.ErrorException("Error accessing response.Content.Headers.TryGetValues Content-Length", ex);
  425. }
  426. }
  427. if (lengthValues == null)
  428. {
  429. return null;
  430. }
  431. return long.Parse(string.Join(string.Empty, lengthValues.ToArray()), UsCulture);
  432. }
  433. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  434. /// <summary>
  435. /// Handles the temp file exception.
  436. /// </summary>
  437. /// <param name="ex">The ex.</param>
  438. /// <param name="options">The options.</param>
  439. /// <param name="tempFile">The temp file.</param>
  440. /// <returns>Task.</returns>
  441. /// <exception cref="HttpException"></exception>
  442. private Exception GetTempFileException(Exception ex, HttpRequestOptions options, string tempFile)
  443. {
  444. var operationCanceledException = ex as OperationCanceledException;
  445. if (operationCanceledException != null)
  446. {
  447. // Cleanup
  448. DeleteTempFile(tempFile);
  449. return GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  450. }
  451. _logger.ErrorException("Error getting response from " + options.Url, ex);
  452. var httpRequestException = ex as HttpRequestException;
  453. // Cleanup
  454. DeleteTempFile(tempFile);
  455. if (httpRequestException != null)
  456. {
  457. return new HttpException(ex.Message, ex);
  458. }
  459. return ex;
  460. }
  461. private void DeleteTempFile(string file)
  462. {
  463. try
  464. {
  465. File.Delete(file);
  466. }
  467. catch (IOException)
  468. {
  469. // Might not have been created at all. No need to worry.
  470. }
  471. }
  472. /// <summary>
  473. /// Validates the params.
  474. /// </summary>
  475. /// <param name="url">The URL.</param>
  476. /// <param name="cancellationToken">The cancellation token.</param>
  477. /// <exception cref="System.ArgumentNullException">url</exception>
  478. private void ValidateParams(string url, CancellationToken cancellationToken)
  479. {
  480. if (string.IsNullOrEmpty(url))
  481. {
  482. throw new ArgumentNullException("url");
  483. }
  484. }
  485. /// <summary>
  486. /// Gets the host from URL.
  487. /// </summary>
  488. /// <param name="url">The URL.</param>
  489. /// <returns>System.String.</returns>
  490. private string GetHostFromUrl(string url)
  491. {
  492. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  493. var len = url.IndexOf('/', start) - start;
  494. return url.Substring(start, len);
  495. }
  496. /// <summary>
  497. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  498. /// </summary>
  499. public void Dispose()
  500. {
  501. Dispose(true);
  502. GC.SuppressFinalize(this);
  503. }
  504. /// <summary>
  505. /// Releases unmanaged and - optionally - managed resources.
  506. /// </summary>
  507. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  508. protected virtual void Dispose(bool dispose)
  509. {
  510. if (dispose)
  511. {
  512. foreach (var client in _httpClients.Values.ToList())
  513. {
  514. client.HttpClient.Dispose();
  515. }
  516. _httpClients.Clear();
  517. }
  518. }
  519. /// <summary>
  520. /// Throws the cancellation exception.
  521. /// </summary>
  522. /// <param name="url">The URL.</param>
  523. /// <param name="cancellationToken">The cancellation token.</param>
  524. /// <param name="exception">The exception.</param>
  525. /// <returns>Exception.</returns>
  526. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  527. {
  528. // If the HttpClient's timeout is reached, it will cancel the Task internally
  529. if (!cancellationToken.IsCancellationRequested)
  530. {
  531. var msg = string.Format("Connection to {0} timed out", url);
  532. _logger.Error(msg);
  533. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  534. return new HttpException(msg, exception) { IsTimedOut = true };
  535. }
  536. return exception;
  537. }
  538. /// <summary>
  539. /// Ensures the success status code.
  540. /// </summary>
  541. /// <param name="response">The response.</param>
  542. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  543. private void EnsureSuccessStatusCode(HttpResponseMessage response)
  544. {
  545. if (!response.IsSuccessStatusCode)
  546. {
  547. throw new HttpException(response.ReasonPhrase) { StatusCode = response.StatusCode };
  548. }
  549. }
  550. /// <summary>
  551. /// Posts the specified URL.
  552. /// </summary>
  553. /// <param name="url">The URL.</param>
  554. /// <param name="postData">The post data.</param>
  555. /// <param name="cancellationToken">The cancellation token.</param>
  556. /// <returns>Task{Stream}.</returns>
  557. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  558. {
  559. return Post(url, postData, null, cancellationToken);
  560. }
  561. }
  562. }