HttpClientManager.cs 20 KB

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