HttpClientManager.cs 20 KB

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