HttpClientManager.cs 21 KB

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