HttpClientManager.cs 20 KB

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