HttpClientManager.cs 23 KB

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