HttpClientManager.cs 20 KB

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