HttpClientManager.cs 20 KB

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