HttpClientManager.cs 22 KB

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