HttpClientManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. using System.Globalization;
  2. using System.Net.Http.Headers;
  3. using MediaBrowser.Common.Configuration;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  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(30);
  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="options">The options.</param>
  179. /// <returns>Task{System.String}.</returns>
  180. /// <exception cref="System.ArgumentNullException">progress</exception>
  181. /// <exception cref="HttpException"></exception>
  182. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  183. public Task<string> GetTempFile(HttpRequestOptions options)
  184. {
  185. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  186. return GetTempFile(options, tempFile, 0);
  187. }
  188. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  189. /// <summary>
  190. /// Gets the temp file.
  191. /// </summary>
  192. /// <param name="options">The options.</param>
  193. /// <param name="tempFile">The temp file.</param>
  194. /// <param name="resumeCount">The resume count.</param>
  195. /// <returns>Task{System.String}.</returns>
  196. /// <exception cref="System.ArgumentNullException">progress</exception>
  197. /// <exception cref="HttpException"></exception>
  198. private async Task<string> GetTempFile(HttpRequestOptions options, string tempFile, int resumeCount)
  199. {
  200. ValidateParams(options.Url, options.CancellationToken);
  201. if (options.Progress == null)
  202. {
  203. throw new ArgumentNullException("progress");
  204. }
  205. options.CancellationToken.ThrowIfCancellationRequested();
  206. var message = new HttpRequestMessage(HttpMethod.Get, options.Url);
  207. if (!string.IsNullOrEmpty(options.UserAgent))
  208. {
  209. message.Headers.Add("User-Agent", options.UserAgent);
  210. }
  211. if (options.ResourcePool != null)
  212. {
  213. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  214. }
  215. options.Progress.Report(0);
  216. _logger.Info("HttpClientManager.GetTempFile url: {0}, temp file: {1}", options.Url, tempFile);
  217. try
  218. {
  219. options.CancellationToken.ThrowIfCancellationRequested();
  220. using (var response = await GetHttpClient(GetHostFromUrl(options.Url)).SendAsync(message, HttpCompletionOption.ResponseHeadersRead, options.CancellationToken).ConfigureAwait(false))
  221. {
  222. EnsureSuccessStatusCode(response);
  223. options.CancellationToken.ThrowIfCancellationRequested();
  224. IEnumerable<string> lengthValues;
  225. if (!response.Headers.TryGetValues("content-length", out lengthValues) &&
  226. !response.Content.Headers.TryGetValues("content-length", out lengthValues))
  227. {
  228. // We're not able to track progress
  229. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  230. {
  231. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  232. {
  233. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  234. }
  235. }
  236. }
  237. else
  238. {
  239. var length = long.Parse(string.Join(string.Empty, lengthValues.ToArray()), UsCulture);
  240. using (var stream = ProgressStream.CreateReadProgressStream(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), options.Progress.Report, length))
  241. {
  242. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  243. {
  244. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  245. }
  246. }
  247. }
  248. options.Progress.Report(100);
  249. options.CancellationToken.ThrowIfCancellationRequested();
  250. }
  251. }
  252. catch (Exception ex)
  253. {
  254. HandleTempFileException(ex, options, tempFile);
  255. }
  256. finally
  257. {
  258. if (options.ResourcePool != null)
  259. {
  260. options.ResourcePool.Release();
  261. }
  262. }
  263. return tempFile;
  264. }
  265. /// <summary>
  266. /// Handles the temp file exception.
  267. /// </summary>
  268. /// <param name="ex">The ex.</param>
  269. /// <param name="options">The options.</param>
  270. /// <param name="tempFile">The temp file.</param>
  271. /// <returns>Task.</returns>
  272. /// <exception cref="HttpException"></exception>
  273. private void HandleTempFileException(Exception ex, HttpRequestOptions options, string tempFile)
  274. {
  275. var operationCanceledException = ex as OperationCanceledException;
  276. if (operationCanceledException != null)
  277. {
  278. // Cleanup
  279. if (File.Exists(tempFile))
  280. {
  281. File.Delete(tempFile);
  282. }
  283. throw GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  284. }
  285. _logger.ErrorException("Error getting response from " + options.Url, ex);
  286. var httpRequestException = ex as HttpRequestException;
  287. // Cleanup
  288. if (File.Exists(tempFile))
  289. {
  290. File.Delete(tempFile);
  291. }
  292. if (httpRequestException != null)
  293. {
  294. throw new HttpException(ex.Message, ex);
  295. }
  296. throw ex;
  297. }
  298. /// <summary>
  299. /// Downloads the contents of a given url into a MemoryStream
  300. /// </summary>
  301. /// <param name="url">The URL.</param>
  302. /// <param name="resourcePool">The resource pool.</param>
  303. /// <param name="cancellationToken">The cancellation token.</param>
  304. /// <returns>Task{MemoryStream}.</returns>
  305. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  306. public async Task<MemoryStream> GetMemoryStream(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  307. {
  308. ValidateParams(url, cancellationToken);
  309. cancellationToken.ThrowIfCancellationRequested();
  310. var message = new HttpRequestMessage(HttpMethod.Get, url);
  311. if (resourcePool != null)
  312. {
  313. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  314. }
  315. var ms = new MemoryStream();
  316. _logger.Info("HttpClientManager.GetMemoryStream url: {0}", url);
  317. try
  318. {
  319. cancellationToken.ThrowIfCancellationRequested();
  320. using (var response = await GetHttpClient(GetHostFromUrl(url)).SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false))
  321. {
  322. EnsureSuccessStatusCode(response);
  323. cancellationToken.ThrowIfCancellationRequested();
  324. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  325. {
  326. await stream.CopyToAsync(ms, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  327. }
  328. cancellationToken.ThrowIfCancellationRequested();
  329. }
  330. ms.Position = 0;
  331. return ms;
  332. }
  333. catch (OperationCanceledException ex)
  334. {
  335. ms.Dispose();
  336. throw GetCancellationException(url, cancellationToken, ex);
  337. }
  338. catch (HttpRequestException ex)
  339. {
  340. _logger.ErrorException("Error getting response from " + url, ex);
  341. ms.Dispose();
  342. throw new HttpException(ex.Message, ex);
  343. }
  344. catch (Exception ex)
  345. {
  346. _logger.ErrorException("Error getting response from " + url, ex);
  347. ms.Dispose();
  348. throw;
  349. }
  350. finally
  351. {
  352. if (resourcePool != null)
  353. {
  354. resourcePool.Release();
  355. }
  356. }
  357. }
  358. /// <summary>
  359. /// Validates the params.
  360. /// </summary>
  361. /// <param name="url">The URL.</param>
  362. /// <param name="cancellationToken">The cancellation token.</param>
  363. /// <exception cref="System.ArgumentNullException">url</exception>
  364. private void ValidateParams(string url, CancellationToken cancellationToken)
  365. {
  366. if (string.IsNullOrEmpty(url))
  367. {
  368. throw new ArgumentNullException("url");
  369. }
  370. if (cancellationToken == null)
  371. {
  372. throw new ArgumentNullException("cancellationToken");
  373. }
  374. }
  375. /// <summary>
  376. /// Gets the host from URL.
  377. /// </summary>
  378. /// <param name="url">The URL.</param>
  379. /// <returns>System.String.</returns>
  380. private string GetHostFromUrl(string url)
  381. {
  382. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  383. var len = url.IndexOf('/', start) - start;
  384. return url.Substring(start, len);
  385. }
  386. /// <summary>
  387. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  388. /// </summary>
  389. public void Dispose()
  390. {
  391. Dispose(true);
  392. GC.SuppressFinalize(this);
  393. }
  394. /// <summary>
  395. /// Releases unmanaged and - optionally - managed resources.
  396. /// </summary>
  397. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  398. protected virtual void Dispose(bool dispose)
  399. {
  400. if (dispose)
  401. {
  402. foreach (var client in _httpClients.Values.ToList())
  403. {
  404. client.Dispose();
  405. }
  406. _httpClients.Clear();
  407. }
  408. }
  409. /// <summary>
  410. /// Throws the cancellation exception.
  411. /// </summary>
  412. /// <param name="url">The URL.</param>
  413. /// <param name="cancellationToken">The cancellation token.</param>
  414. /// <param name="exception">The exception.</param>
  415. /// <returns>Exception.</returns>
  416. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  417. {
  418. // If the HttpClient's timeout is reached, it will cancel the Task internally
  419. if (!cancellationToken.IsCancellationRequested)
  420. {
  421. var msg = string.Format("Connection to {0} timed out", url);
  422. _logger.Error(msg);
  423. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  424. return new HttpException(msg, exception) { IsTimedOut = true };
  425. }
  426. return exception;
  427. }
  428. /// <summary>
  429. /// Ensures the success status code.
  430. /// </summary>
  431. /// <param name="response">The response.</param>
  432. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  433. private void EnsureSuccessStatusCode(HttpResponseMessage response)
  434. {
  435. if (!response.IsSuccessStatusCode)
  436. {
  437. throw new HttpException(response.ReasonPhrase) { StatusCode = response.StatusCode };
  438. }
  439. }
  440. /// <summary>
  441. /// Gets the specified URL.
  442. /// </summary>
  443. /// <param name="url">The URL.</param>
  444. /// <param name="cancellationToken">The cancellation token.</param>
  445. /// <returns>Task{Stream}.</returns>
  446. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  447. {
  448. return Get(url, null, cancellationToken);
  449. }
  450. /// <summary>
  451. /// Posts the specified URL.
  452. /// </summary>
  453. /// <param name="url">The URL.</param>
  454. /// <param name="postData">The post data.</param>
  455. /// <param name="cancellationToken">The cancellation token.</param>
  456. /// <returns>Task{Stream}.</returns>
  457. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  458. {
  459. return Post(url, postData, null, cancellationToken);
  460. }
  461. /// <summary>
  462. /// Gets the memory stream.
  463. /// </summary>
  464. /// <param name="url">The URL.</param>
  465. /// <param name="cancellationToken">The cancellation token.</param>
  466. /// <returns>Task{MemoryStream}.</returns>
  467. public Task<MemoryStream> GetMemoryStream(string url, CancellationToken cancellationToken)
  468. {
  469. return GetMemoryStream(url, null, cancellationToken);
  470. }
  471. }
  472. }