HttpClientManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. _logger.Info("HttpClientManager.Get url: {0}", options.Url);
  118. try
  119. {
  120. options.CancellationToken.ThrowIfCancellationRequested();
  121. var response = await client.HttpClient.SendAsync(message, HttpCompletionOption.ResponseContentRead, options.CancellationToken).ConfigureAwait(false);
  122. EnsureSuccessStatusCode(response);
  123. options.CancellationToken.ThrowIfCancellationRequested();
  124. return await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  125. }
  126. catch (OperationCanceledException ex)
  127. {
  128. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  129. var httpException = exception as HttpException;
  130. if (httpException != null && httpException.IsTimedOut)
  131. {
  132. client.LastTimeout = DateTime.UtcNow;
  133. }
  134. throw exception;
  135. }
  136. catch (HttpRequestException ex)
  137. {
  138. _logger.ErrorException("Error getting response from " + options.Url, ex);
  139. throw new HttpException(ex.Message, ex);
  140. }
  141. catch (Exception ex)
  142. {
  143. _logger.ErrorException("Error getting response from " + options.Url, ex);
  144. throw;
  145. }
  146. finally
  147. {
  148. if (options.ResourcePool != null)
  149. {
  150. options.ResourcePool.Release();
  151. }
  152. }
  153. }
  154. }
  155. /// <summary>
  156. /// Performs a GET request and returns the resulting stream
  157. /// </summary>
  158. /// <param name="url">The URL.</param>
  159. /// <param name="resourcePool">The resource pool.</param>
  160. /// <param name="cancellationToken">The cancellation token.</param>
  161. /// <returns>Task{Stream}.</returns>
  162. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  163. {
  164. return Get(new HttpRequestOptions
  165. {
  166. Url = url,
  167. ResourcePool = resourcePool,
  168. CancellationToken = cancellationToken,
  169. });
  170. }
  171. /// <summary>
  172. /// Gets the specified URL.
  173. /// </summary>
  174. /// <param name="url">The URL.</param>
  175. /// <param name="cancellationToken">The cancellation token.</param>
  176. /// <returns>Task{Stream}.</returns>
  177. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  178. {
  179. return Get(url, null, cancellationToken);
  180. }
  181. /// <summary>
  182. /// Performs a POST request
  183. /// </summary>
  184. /// <param name="url">The URL.</param>
  185. /// <param name="postData">Params to add to the POST data.</param>
  186. /// <param name="resourcePool">The resource pool.</param>
  187. /// <param name="cancellationToken">The cancellation token.</param>
  188. /// <returns>stream on success, null on failure</returns>
  189. /// <exception cref="System.ArgumentNullException">postData</exception>
  190. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  191. public async Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  192. {
  193. ValidateParams(url, cancellationToken);
  194. if (postData == null)
  195. {
  196. throw new ArgumentNullException("postData");
  197. }
  198. cancellationToken.ThrowIfCancellationRequested();
  199. var strings = postData.Keys.Select(key => string.Format("{0}={1}", key, postData[key]));
  200. var postContent = string.Join("&", strings.ToArray());
  201. var content = new StringContent(postContent, Encoding.UTF8, "application/x-www-form-urlencoded");
  202. if (resourcePool != null)
  203. {
  204. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  205. }
  206. _logger.Info("HttpClientManager.Post url: {0}", url);
  207. try
  208. {
  209. cancellationToken.ThrowIfCancellationRequested();
  210. var msg = await GetHttpClient(GetHostFromUrl(url), false).HttpClient.PostAsync(url, content, cancellationToken).ConfigureAwait(false);
  211. EnsureSuccessStatusCode(msg);
  212. return await msg.Content.ReadAsStreamAsync().ConfigureAwait(false);
  213. }
  214. catch (OperationCanceledException ex)
  215. {
  216. throw GetCancellationException(url, cancellationToken, ex);
  217. }
  218. catch (HttpRequestException ex)
  219. {
  220. _logger.ErrorException("Error getting response from " + url, ex);
  221. throw new HttpException(ex.Message, ex);
  222. }
  223. finally
  224. {
  225. if (resourcePool != null)
  226. {
  227. resourcePool.Release();
  228. }
  229. }
  230. }
  231. /// <summary>
  232. /// Downloads the contents of a given url into a temporary location
  233. /// </summary>
  234. /// <param name="options">The options.</param>
  235. /// <returns>Task{System.String}.</returns>
  236. /// <exception cref="System.ArgumentNullException">progress</exception>
  237. /// <exception cref="HttpException"></exception>
  238. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  239. public async Task<string> GetTempFile(HttpRequestOptions options)
  240. {
  241. ValidateParams(options.Url, options.CancellationToken);
  242. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  243. if (options.Progress == null)
  244. {
  245. throw new ArgumentNullException("progress");
  246. }
  247. options.CancellationToken.ThrowIfCancellationRequested();
  248. if (options.ResourcePool != null)
  249. {
  250. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  251. }
  252. options.Progress.Report(0);
  253. _logger.Info("HttpClientManager.GetTempFile url: {0}, temp file: {1}", options.Url, tempFile);
  254. try
  255. {
  256. options.CancellationToken.ThrowIfCancellationRequested();
  257. using (var message = GetHttpRequestMessage(options))
  258. {
  259. using (var response = await GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression).HttpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, options.CancellationToken).ConfigureAwait(false))
  260. {
  261. EnsureSuccessStatusCode(response);
  262. options.CancellationToken.ThrowIfCancellationRequested();
  263. var contentLength = GetContentLength(response);
  264. if (!contentLength.HasValue)
  265. {
  266. // We're not able to track progress
  267. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  268. {
  269. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  270. {
  271. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  272. }
  273. }
  274. }
  275. else
  276. {
  277. using (var stream = ProgressStream.CreateReadProgressStream(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), options.Progress.Report, contentLength.Value))
  278. {
  279. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  280. {
  281. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  282. }
  283. }
  284. }
  285. options.Progress.Report(100);
  286. options.CancellationToken.ThrowIfCancellationRequested();
  287. }
  288. }
  289. }
  290. catch (Exception ex)
  291. {
  292. HandleTempFileException(ex, options, tempFile);
  293. }
  294. finally
  295. {
  296. if (options.ResourcePool != null)
  297. {
  298. options.ResourcePool.Release();
  299. }
  300. }
  301. return tempFile;
  302. }
  303. /// <summary>
  304. /// Gets the message.
  305. /// </summary>
  306. /// <param name="options">The options.</param>
  307. /// <returns>HttpResponseMessage.</returns>
  308. private HttpRequestMessage GetHttpRequestMessage(HttpRequestOptions options)
  309. {
  310. var message = new HttpRequestMessage(HttpMethod.Get, options.Url);
  311. if (!string.IsNullOrEmpty(options.UserAgent))
  312. {
  313. message.Headers.Add("User-Agent", options.UserAgent);
  314. }
  315. if (!string.IsNullOrEmpty(options.AcceptHeader))
  316. {
  317. message.Headers.Add("Accept", options.AcceptHeader);
  318. }
  319. return message;
  320. }
  321. /// <summary>
  322. /// Gets the length of the content.
  323. /// </summary>
  324. /// <param name="response">The response.</param>
  325. /// <returns>System.Nullable{System.Int64}.</returns>
  326. private long? GetContentLength(HttpResponseMessage response)
  327. {
  328. IEnumerable<string> lengthValues;
  329. if (!response.Headers.TryGetValues("content-length", out lengthValues) && !response.Content.Headers.TryGetValues("content-length", out lengthValues))
  330. {
  331. return null;
  332. }
  333. return long.Parse(string.Join(string.Empty, lengthValues.ToArray()), UsCulture);
  334. }
  335. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  336. /// <summary>
  337. /// Handles the temp file exception.
  338. /// </summary>
  339. /// <param name="ex">The ex.</param>
  340. /// <param name="options">The options.</param>
  341. /// <param name="tempFile">The temp file.</param>
  342. /// <returns>Task.</returns>
  343. /// <exception cref="HttpException"></exception>
  344. private void HandleTempFileException(Exception ex, HttpRequestOptions options, string tempFile)
  345. {
  346. var operationCanceledException = ex as OperationCanceledException;
  347. if (operationCanceledException != null)
  348. {
  349. // Cleanup
  350. if (File.Exists(tempFile))
  351. {
  352. File.Delete(tempFile);
  353. }
  354. throw GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  355. }
  356. _logger.ErrorException("Error getting response from " + options.Url, ex);
  357. var httpRequestException = ex as HttpRequestException;
  358. // Cleanup
  359. if (File.Exists(tempFile))
  360. {
  361. File.Delete(tempFile);
  362. }
  363. if (httpRequestException != null)
  364. {
  365. throw new HttpException(ex.Message, ex);
  366. }
  367. throw ex;
  368. }
  369. /// <summary>
  370. /// Validates the params.
  371. /// </summary>
  372. /// <param name="url">The URL.</param>
  373. /// <param name="cancellationToken">The cancellation token.</param>
  374. /// <exception cref="System.ArgumentNullException">url</exception>
  375. private void ValidateParams(string url, CancellationToken cancellationToken)
  376. {
  377. if (string.IsNullOrEmpty(url))
  378. {
  379. throw new ArgumentNullException("url");
  380. }
  381. if (cancellationToken == null)
  382. {
  383. throw new ArgumentNullException("cancellationToken");
  384. }
  385. }
  386. /// <summary>
  387. /// Gets the host from URL.
  388. /// </summary>
  389. /// <param name="url">The URL.</param>
  390. /// <returns>System.String.</returns>
  391. private string GetHostFromUrl(string url)
  392. {
  393. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  394. var len = url.IndexOf('/', start) - start;
  395. return url.Substring(start, len);
  396. }
  397. /// <summary>
  398. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  399. /// </summary>
  400. public void Dispose()
  401. {
  402. Dispose(true);
  403. GC.SuppressFinalize(this);
  404. }
  405. /// <summary>
  406. /// Releases unmanaged and - optionally - managed resources.
  407. /// </summary>
  408. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  409. protected virtual void Dispose(bool dispose)
  410. {
  411. if (dispose)
  412. {
  413. foreach (var client in _httpClients.Values.ToList())
  414. {
  415. client.HttpClient.Dispose();
  416. }
  417. _httpClients.Clear();
  418. }
  419. }
  420. /// <summary>
  421. /// Throws the cancellation exception.
  422. /// </summary>
  423. /// <param name="url">The URL.</param>
  424. /// <param name="cancellationToken">The cancellation token.</param>
  425. /// <param name="exception">The exception.</param>
  426. /// <returns>Exception.</returns>
  427. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  428. {
  429. // If the HttpClient's timeout is reached, it will cancel the Task internally
  430. if (!cancellationToken.IsCancellationRequested)
  431. {
  432. var msg = string.Format("Connection to {0} timed out", url);
  433. _logger.Error(msg);
  434. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  435. return new HttpException(msg, exception) { IsTimedOut = true };
  436. }
  437. return exception;
  438. }
  439. /// <summary>
  440. /// Ensures the success status code.
  441. /// </summary>
  442. /// <param name="response">The response.</param>
  443. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  444. private void EnsureSuccessStatusCode(HttpResponseMessage response)
  445. {
  446. if (!response.IsSuccessStatusCode)
  447. {
  448. throw new HttpException(response.ReasonPhrase) { StatusCode = response.StatusCode };
  449. }
  450. }
  451. /// <summary>
  452. /// Posts the specified URL.
  453. /// </summary>
  454. /// <param name="url">The URL.</param>
  455. /// <param name="postData">The post data.</param>
  456. /// <param name="cancellationToken">The cancellation token.</param>
  457. /// <returns>Task{Stream}.</returns>
  458. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  459. {
  460. return Post(url, postData, null, cancellationToken);
  461. }
  462. }
  463. }