HttpClientManager.cs 19 KB

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