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