HttpClientManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Kernel;
  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.IO;
  10. using System.Linq;
  11. using System.Net;
  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(15);
  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, resourcePool, cancellationToken);
  94. cancellationToken.ThrowIfCancellationRequested();
  95. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  96. _logger.Info("HttpClientManager.Get url: {0}", url);
  97. try
  98. {
  99. cancellationToken.ThrowIfCancellationRequested();
  100. var msg = await GetHttpClient(GetHostFromUrl(url)).GetAsync(url, cancellationToken).ConfigureAwait(false);
  101. EnsureSuccessStatusCode(msg);
  102. return await msg.Content.ReadAsStreamAsync().ConfigureAwait(false);
  103. }
  104. catch (OperationCanceledException ex)
  105. {
  106. throw GetCancellationException(url, cancellationToken, ex);
  107. }
  108. catch (HttpRequestException ex)
  109. {
  110. _logger.ErrorException("Error getting response from " + url, ex);
  111. throw new HttpException(ex.Message, ex);
  112. }
  113. finally
  114. {
  115. resourcePool.Release();
  116. }
  117. }
  118. /// <summary>
  119. /// Performs a POST request
  120. /// </summary>
  121. /// <param name="url">The URL.</param>
  122. /// <param name="postData">Params to add to the POST data.</param>
  123. /// <param name="resourcePool">The resource pool.</param>
  124. /// <param name="cancellationToken">The cancellation token.</param>
  125. /// <returns>stream on success, null on failure</returns>
  126. /// <exception cref="System.ArgumentNullException">postData</exception>
  127. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  128. public async Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  129. {
  130. ValidateParams(url, resourcePool, cancellationToken);
  131. if (postData == null)
  132. {
  133. throw new ArgumentNullException("postData");
  134. }
  135. cancellationToken.ThrowIfCancellationRequested();
  136. var strings = postData.Keys.Select(key => string.Format("{0}={1}", key, postData[key]));
  137. var postContent = string.Join("&", strings.ToArray());
  138. var content = new StringContent(postContent, Encoding.UTF8, "application/x-www-form-urlencoded");
  139. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  140. _logger.Info("HttpClientManager.Post url: {0}", url);
  141. try
  142. {
  143. cancellationToken.ThrowIfCancellationRequested();
  144. var msg = await GetHttpClient(GetHostFromUrl(url)).PostAsync(url, content, cancellationToken).ConfigureAwait(false);
  145. EnsureSuccessStatusCode(msg);
  146. return await msg.Content.ReadAsStreamAsync().ConfigureAwait(false);
  147. }
  148. catch (OperationCanceledException ex)
  149. {
  150. throw GetCancellationException(url, cancellationToken, ex);
  151. }
  152. catch (HttpRequestException ex)
  153. {
  154. _logger.ErrorException("Error getting response from " + url, ex);
  155. throw new HttpException(ex.Message, ex);
  156. }
  157. finally
  158. {
  159. resourcePool.Release();
  160. }
  161. }
  162. /// <summary>
  163. /// Downloads the contents of a given url into a temporary location
  164. /// </summary>
  165. /// <param name="url">The URL.</param>
  166. /// <param name="resourcePool">The resource pool.</param>
  167. /// <param name="cancellationToken">The cancellation token.</param>
  168. /// <param name="progress">The progress.</param>
  169. /// <param name="userAgent">The user agent.</param>
  170. /// <returns>Task{System.String}.</returns>
  171. /// <exception cref="System.ArgumentNullException">progress</exception>
  172. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  173. public async Task<string> GetTempFile(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken, IProgress<double> progress, string userAgent = null)
  174. {
  175. ValidateParams(url, resourcePool, cancellationToken);
  176. if (progress == null)
  177. {
  178. throw new ArgumentNullException("progress");
  179. }
  180. cancellationToken.ThrowIfCancellationRequested();
  181. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  182. var message = new HttpRequestMessage(HttpMethod.Get, url);
  183. if (!string.IsNullOrEmpty(userAgent))
  184. {
  185. message.Headers.Add("User-Agent", userAgent);
  186. }
  187. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  188. _logger.Info("HttpClientManager.GetTempFile url: {0}, temp file: {1}", url, tempFile);
  189. try
  190. {
  191. cancellationToken.ThrowIfCancellationRequested();
  192. using (var response = await GetHttpClient(GetHostFromUrl(url)).SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
  193. {
  194. EnsureSuccessStatusCode(response);
  195. cancellationToken.ThrowIfCancellationRequested();
  196. IEnumerable<string> lengthValues;
  197. if (!response.Headers.TryGetValues("content-length", out lengthValues) &&
  198. !response.Content.Headers.TryGetValues("content-length", out lengthValues))
  199. {
  200. // We're not able to track progress
  201. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  202. {
  203. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  204. {
  205. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  206. }
  207. }
  208. }
  209. else
  210. {
  211. var length = long.Parse(string.Join(string.Empty, lengthValues.ToArray()));
  212. using (var stream = ProgressStream.CreateReadProgressStream(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), progress.Report, length))
  213. {
  214. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  215. {
  216. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  217. }
  218. }
  219. }
  220. progress.Report(100);
  221. cancellationToken.ThrowIfCancellationRequested();
  222. }
  223. return tempFile;
  224. }
  225. catch (OperationCanceledException ex)
  226. {
  227. // Cleanup
  228. if (File.Exists(tempFile))
  229. {
  230. File.Delete(tempFile);
  231. }
  232. throw GetCancellationException(url, cancellationToken, ex);
  233. }
  234. catch (HttpRequestException ex)
  235. {
  236. _logger.ErrorException("Error getting response from " + url, ex);
  237. // Cleanup
  238. if (File.Exists(tempFile))
  239. {
  240. File.Delete(tempFile);
  241. }
  242. throw new HttpException(ex.Message, ex);
  243. }
  244. catch (Exception ex)
  245. {
  246. _logger.ErrorException("Error getting response from " + url, ex);
  247. // Cleanup
  248. if (File.Exists(tempFile))
  249. {
  250. File.Delete(tempFile);
  251. }
  252. throw;
  253. }
  254. finally
  255. {
  256. resourcePool.Release();
  257. }
  258. }
  259. /// <summary>
  260. /// Downloads the contents of a given url into a MemoryStream
  261. /// </summary>
  262. /// <param name="url">The URL.</param>
  263. /// <param name="resourcePool">The resource pool.</param>
  264. /// <param name="cancellationToken">The cancellation token.</param>
  265. /// <returns>Task{MemoryStream}.</returns>
  266. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  267. public async Task<MemoryStream> GetMemoryStream(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  268. {
  269. ValidateParams(url, resourcePool, cancellationToken);
  270. cancellationToken.ThrowIfCancellationRequested();
  271. var message = new HttpRequestMessage(HttpMethod.Get, url);
  272. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  273. var ms = new MemoryStream();
  274. _logger.Info("HttpClientManager.GetMemoryStream url: {0}", url);
  275. try
  276. {
  277. cancellationToken.ThrowIfCancellationRequested();
  278. using (var response = await GetHttpClient(GetHostFromUrl(url)).SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
  279. {
  280. EnsureSuccessStatusCode(response);
  281. cancellationToken.ThrowIfCancellationRequested();
  282. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  283. {
  284. await stream.CopyToAsync(ms, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  285. }
  286. cancellationToken.ThrowIfCancellationRequested();
  287. }
  288. ms.Position = 0;
  289. return ms;
  290. }
  291. catch (OperationCanceledException ex)
  292. {
  293. ms.Dispose();
  294. throw GetCancellationException(url, cancellationToken, ex);
  295. }
  296. catch (HttpRequestException ex)
  297. {
  298. _logger.ErrorException("Error getting response from " + url, ex);
  299. ms.Dispose();
  300. throw new HttpException(ex.Message, ex);
  301. }
  302. catch (Exception ex)
  303. {
  304. _logger.ErrorException("Error getting response from " + url, ex);
  305. ms.Dispose();
  306. throw;
  307. }
  308. finally
  309. {
  310. resourcePool.Release();
  311. }
  312. }
  313. /// <summary>
  314. /// Validates the params.
  315. /// </summary>
  316. /// <param name="url">The URL.</param>
  317. /// <param name="resourcePool">The resource pool.</param>
  318. /// <param name="cancellationToken">The cancellation token.</param>
  319. /// <exception cref="System.ArgumentNullException">url</exception>
  320. private void ValidateParams(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  321. {
  322. if (string.IsNullOrEmpty(url))
  323. {
  324. throw new ArgumentNullException("url");
  325. }
  326. if (resourcePool == null)
  327. {
  328. throw new ArgumentNullException("resourcePool");
  329. }
  330. if (cancellationToken == null)
  331. {
  332. throw new ArgumentNullException("cancellationToken");
  333. }
  334. }
  335. /// <summary>
  336. /// Gets the host from URL.
  337. /// </summary>
  338. /// <param name="url">The URL.</param>
  339. /// <returns>System.String.</returns>
  340. private string GetHostFromUrl(string url)
  341. {
  342. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  343. var len = url.IndexOf('/', start) - start;
  344. return url.Substring(start, len);
  345. }
  346. /// <summary>
  347. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  348. /// </summary>
  349. public void Dispose()
  350. {
  351. Dispose(true);
  352. GC.SuppressFinalize(this);
  353. }
  354. /// <summary>
  355. /// Releases unmanaged and - optionally - managed resources.
  356. /// </summary>
  357. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  358. protected virtual void Dispose(bool dispose)
  359. {
  360. if (dispose)
  361. {
  362. foreach (var client in _httpClients.Values.ToList())
  363. {
  364. client.Dispose();
  365. }
  366. _httpClients.Clear();
  367. }
  368. }
  369. /// <summary>
  370. /// Throws the cancellation exception.
  371. /// </summary>
  372. /// <param name="url">The URL.</param>
  373. /// <param name="cancellationToken">The cancellation token.</param>
  374. /// <param name="exception">The exception.</param>
  375. /// <returns>Exception.</returns>
  376. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  377. {
  378. // If the HttpClient's timeout is reached, it will cancel the Task internally
  379. if (!cancellationToken.IsCancellationRequested)
  380. {
  381. var msg = string.Format("Connection to {0} timed out", url);
  382. _logger.Error(msg);
  383. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  384. return new HttpException(msg, exception) { IsTimedOut = true };
  385. }
  386. return exception;
  387. }
  388. /// <summary>
  389. /// Ensures the success status code.
  390. /// </summary>
  391. /// <param name="response">The response.</param>
  392. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  393. private void EnsureSuccessStatusCode(HttpResponseMessage response)
  394. {
  395. if (!response.IsSuccessStatusCode)
  396. {
  397. throw new HttpException(response.ReasonPhrase) { StatusCode = response.StatusCode };
  398. }
  399. }
  400. }
  401. }