HttpClientManager.cs 23 KB

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