2
0

HttpClientManager.cs 25 KB

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