HttpClientManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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;
  13. using System.Net.Cache;
  14. using System.Net.Http;
  15. using System.Reflection;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Common.Implementations.HttpClientManager
  20. {
  21. /// <summary>
  22. /// Class HttpClientManager
  23. /// </summary>
  24. public class HttpClientManager : IHttpClient
  25. {
  26. /// <summary>
  27. /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
  28. /// </summary>
  29. private const int TimeoutSeconds = 30;
  30. /// <summary>
  31. /// The _logger
  32. /// </summary>
  33. private readonly ILogger _logger;
  34. /// <summary>
  35. /// The _app paths
  36. /// </summary>
  37. private readonly IApplicationPaths _appPaths;
  38. private readonly IFileSystem _fileSystem;
  39. /// <summary>
  40. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  41. /// </summary>
  42. /// <param name="appPaths">The app paths.</param>
  43. /// <param name="logger">The logger.</param>
  44. /// <param name="fileSystem">The file system.</param>
  45. /// <exception cref="System.ArgumentNullException">appPaths
  46. /// or
  47. /// logger</exception>
  48. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
  49. {
  50. if (appPaths == null)
  51. {
  52. throw new ArgumentNullException("appPaths");
  53. }
  54. if (logger == null)
  55. {
  56. throw new ArgumentNullException("logger");
  57. }
  58. _logger = logger;
  59. _fileSystem = fileSystem;
  60. _appPaths = appPaths;
  61. }
  62. /// <summary>
  63. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  64. /// DON'T dispose it after use.
  65. /// </summary>
  66. /// <value>The HTTP clients.</value>
  67. private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  68. /// <summary>
  69. /// Gets
  70. /// </summary>
  71. /// <param name="host">The host.</param>
  72. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  73. /// <returns>HttpClient.</returns>
  74. /// <exception cref="System.ArgumentNullException">host</exception>
  75. private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  76. {
  77. if (string.IsNullOrEmpty(host))
  78. {
  79. throw new ArgumentNullException("host");
  80. }
  81. HttpClientInfo client;
  82. var key = host + enableHttpCompression;
  83. if (!_httpClients.TryGetValue(key, out client))
  84. {
  85. client = new HttpClientInfo();
  86. _httpClients.TryAdd(key, client);
  87. }
  88. return client;
  89. }
  90. private PropertyInfo _httpBehaviorPropertyInfo;
  91. private HttpWebRequest GetRequest(HttpRequestOptions options, string method, bool enableHttpCompression)
  92. {
  93. var request = HttpWebRequest.CreateHttp(options.Url);
  94. if (!string.IsNullOrEmpty(options.AcceptHeader))
  95. {
  96. request.Accept = options.AcceptHeader;
  97. }
  98. request.AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None;
  99. request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate);
  100. request.ConnectionGroupName = GetHostFromUrl(options.Url);
  101. request.KeepAlive = true;
  102. request.Method = method;
  103. request.Pipelined = true;
  104. request.Timeout = 20000;
  105. if (!string.IsNullOrEmpty(options.UserAgent))
  106. {
  107. request.UserAgent = options.UserAgent;
  108. }
  109. // This is a hack to prevent KeepAlive from getting disabled internally by the HttpWebRequest
  110. // May need to remove this for mono
  111. var sp = request.ServicePoint;
  112. if (_httpBehaviorPropertyInfo == null)
  113. {
  114. _httpBehaviorPropertyInfo = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
  115. }
  116. _httpBehaviorPropertyInfo.SetValue(sp, (byte)0, null);
  117. return request;
  118. }
  119. /// <summary>
  120. /// Gets the response internal.
  121. /// </summary>
  122. /// <param name="options">The options.</param>
  123. /// <returns>Task{HttpResponseInfo}.</returns>
  124. /// <exception cref="HttpException">
  125. /// </exception>
  126. public async Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  127. {
  128. ValidateParams(options.Url, options.CancellationToken);
  129. options.CancellationToken.ThrowIfCancellationRequested();
  130. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  131. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  132. {
  133. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url)) { IsTimedOut = true };
  134. }
  135. var httpWebRequest = GetRequest(options, "GET", options.EnableHttpCompression);
  136. if (options.ResourcePool != null)
  137. {
  138. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  139. }
  140. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  141. {
  142. if (options.ResourcePool != null)
  143. {
  144. options.ResourcePool.Release();
  145. }
  146. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  147. }
  148. _logger.Info("HttpClientManager.GET url: {0}", options.Url);
  149. try
  150. {
  151. options.CancellationToken.ThrowIfCancellationRequested();
  152. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  153. {
  154. var httpResponse = (HttpWebResponse)response;
  155. EnsureSuccessStatusCode(httpResponse);
  156. options.CancellationToken.ThrowIfCancellationRequested();
  157. using (var stream = httpResponse.GetResponseStream())
  158. {
  159. var memoryStream = new MemoryStream();
  160. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  161. memoryStream.Position = 0;
  162. return new HttpResponseInfo
  163. {
  164. Content = memoryStream,
  165. StatusCode = httpResponse.StatusCode,
  166. ContentType = httpResponse.ContentType
  167. };
  168. }
  169. }
  170. }
  171. catch (OperationCanceledException ex)
  172. {
  173. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  174. var httpException = exception as HttpException;
  175. if (httpException != null && httpException.IsTimedOut)
  176. {
  177. client.LastTimeout = DateTime.UtcNow;
  178. }
  179. throw exception;
  180. }
  181. catch (HttpRequestException ex)
  182. {
  183. _logger.ErrorException("Error getting response from " + options.Url, ex);
  184. throw new HttpException(ex.Message, ex);
  185. }
  186. catch (WebException ex)
  187. {
  188. _logger.ErrorException("Error getting response from " + options.Url, ex);
  189. throw new HttpException(ex.Message, ex);
  190. }
  191. catch (Exception ex)
  192. {
  193. _logger.ErrorException("Error getting response from " + options.Url, ex);
  194. throw;
  195. }
  196. finally
  197. {
  198. if (options.ResourcePool != null)
  199. {
  200. options.ResourcePool.Release();
  201. }
  202. }
  203. }
  204. /// <summary>
  205. /// Performs a GET request and returns the resulting stream
  206. /// </summary>
  207. /// <param name="options">The options.</param>
  208. /// <returns>Task{Stream}.</returns>
  209. /// <exception cref="HttpException"></exception>
  210. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  211. public async Task<Stream> Get(HttpRequestOptions options)
  212. {
  213. var response = await GetResponse(options).ConfigureAwait(false);
  214. return response.Content;
  215. }
  216. /// <summary>
  217. /// Performs a GET request and returns the resulting stream
  218. /// </summary>
  219. /// <param name="url">The URL.</param>
  220. /// <param name="resourcePool">The resource pool.</param>
  221. /// <param name="cancellationToken">The cancellation token.</param>
  222. /// <returns>Task{Stream}.</returns>
  223. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  224. {
  225. return Get(new HttpRequestOptions
  226. {
  227. Url = url,
  228. ResourcePool = resourcePool,
  229. CancellationToken = cancellationToken,
  230. });
  231. }
  232. /// <summary>
  233. /// Gets the specified URL.
  234. /// </summary>
  235. /// <param name="url">The URL.</param>
  236. /// <param name="cancellationToken">The cancellation token.</param>
  237. /// <returns>Task{Stream}.</returns>
  238. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  239. {
  240. return Get(url, null, cancellationToken);
  241. }
  242. /// <summary>
  243. /// Performs a POST request
  244. /// </summary>
  245. /// <param name="options">The options.</param>
  246. /// <param name="postData">Params to add to the POST data.</param>
  247. /// <returns>stream on success, null on failure</returns>
  248. /// <exception cref="HttpException">
  249. /// </exception>
  250. /// <exception cref="System.ArgumentNullException">postData</exception>
  251. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  252. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  253. {
  254. ValidateParams(options.Url, options.CancellationToken);
  255. options.CancellationToken.ThrowIfCancellationRequested();
  256. var httpWebRequest = GetRequest(options, "POST", options.EnableHttpCompression);
  257. var strings = postData.Keys.Select(key => string.Format("{0}={1}", key, postData[key]));
  258. var postContent = string.Join("&", strings.ToArray());
  259. var bytes = Encoding.UTF8.GetBytes(postContent);
  260. httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  261. httpWebRequest.ContentLength = bytes.Length;
  262. httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
  263. if (options.ResourcePool != null)
  264. {
  265. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  266. }
  267. _logger.Info("HttpClientManager.POST url: {0}", options.Url);
  268. try
  269. {
  270. options.CancellationToken.ThrowIfCancellationRequested();
  271. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  272. {
  273. var httpResponse = (HttpWebResponse)response;
  274. EnsureSuccessStatusCode(httpResponse);
  275. options.CancellationToken.ThrowIfCancellationRequested();
  276. using (var stream = httpResponse.GetResponseStream())
  277. {
  278. var memoryStream = new MemoryStream();
  279. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  280. memoryStream.Position = 0;
  281. return memoryStream;
  282. }
  283. }
  284. }
  285. catch (OperationCanceledException ex)
  286. {
  287. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  288. throw exception;
  289. }
  290. catch (HttpRequestException ex)
  291. {
  292. _logger.ErrorException("Error getting response from " + options.Url, ex);
  293. throw new HttpException(ex.Message, ex);
  294. }
  295. catch (WebException ex)
  296. {
  297. _logger.ErrorException("Error getting response from " + options.Url, ex);
  298. throw new HttpException(ex.Message, ex);
  299. }
  300. catch (Exception ex)
  301. {
  302. _logger.ErrorException("Error getting response from " + options.Url, ex);
  303. throw;
  304. }
  305. finally
  306. {
  307. if (options.ResourcePool != null)
  308. {
  309. options.ResourcePool.Release();
  310. }
  311. }
  312. }
  313. /// <summary>
  314. /// Performs a POST request
  315. /// </summary>
  316. /// <param name="url">The URL.</param>
  317. /// <param name="postData">Params to add to the POST data.</param>
  318. /// <param name="resourcePool">The resource pool.</param>
  319. /// <param name="cancellationToken">The cancellation token.</param>
  320. /// <returns>stream on success, null on failure</returns>
  321. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  322. {
  323. return Post(new HttpRequestOptions
  324. {
  325. Url = url,
  326. ResourcePool = resourcePool,
  327. CancellationToken = cancellationToken
  328. }, postData);
  329. }
  330. /// <summary>
  331. /// Downloads the contents of a given url into a temporary location
  332. /// </summary>
  333. /// <param name="options">The options.</param>
  334. /// <returns>Task{System.String}.</returns>
  335. /// <exception cref="System.ArgumentNullException">progress</exception>
  336. /// <exception cref="HttpException"></exception>
  337. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  338. public async Task<string> GetTempFile(HttpRequestOptions options)
  339. {
  340. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  341. return response.TempFilePath;
  342. }
  343. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  344. {
  345. ValidateParams(options.Url, options.CancellationToken);
  346. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  347. if (options.Progress == null)
  348. {
  349. throw new ArgumentNullException("progress");
  350. }
  351. options.CancellationToken.ThrowIfCancellationRequested();
  352. var httpWebRequest = GetRequest(options, "GET", options.EnableHttpCompression);
  353. if (options.ResourcePool != null)
  354. {
  355. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  356. }
  357. options.Progress.Report(0);
  358. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  359. try
  360. {
  361. options.CancellationToken.ThrowIfCancellationRequested();
  362. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  363. {
  364. var httpResponse = (HttpWebResponse)response;
  365. EnsureSuccessStatusCode(httpResponse);
  366. options.CancellationToken.ThrowIfCancellationRequested();
  367. var contentLength = GetContentLength(httpResponse);
  368. if (!contentLength.HasValue)
  369. {
  370. // We're not able to track progress
  371. using (var stream = httpResponse.GetResponseStream())
  372. {
  373. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  374. {
  375. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  376. }
  377. }
  378. }
  379. else
  380. {
  381. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  382. {
  383. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  384. {
  385. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  386. }
  387. }
  388. }
  389. options.Progress.Report(100);
  390. return new HttpResponseInfo
  391. {
  392. TempFilePath = tempFile,
  393. StatusCode = httpResponse.StatusCode,
  394. ContentType = httpResponse.ContentType
  395. };
  396. }
  397. }
  398. catch (OperationCanceledException ex)
  399. {
  400. throw GetTempFileException(ex, options, tempFile);
  401. }
  402. catch (HttpRequestException ex)
  403. {
  404. throw GetTempFileException(ex, options, tempFile);
  405. }
  406. catch (WebException ex)
  407. {
  408. throw GetTempFileException(ex, options, tempFile);
  409. }
  410. catch (Exception ex)
  411. {
  412. throw GetTempFileException(ex, options, tempFile);
  413. }
  414. finally
  415. {
  416. if (options.ResourcePool != null)
  417. {
  418. options.ResourcePool.Release();
  419. }
  420. }
  421. }
  422. private long? GetContentLength(HttpWebResponse response)
  423. {
  424. var length = response.ContentLength;
  425. if (length == 0)
  426. {
  427. return null;
  428. }
  429. return length;
  430. }
  431. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  432. /// <summary>
  433. /// Handles the temp file exception.
  434. /// </summary>
  435. /// <param name="ex">The ex.</param>
  436. /// <param name="options">The options.</param>
  437. /// <param name="tempFile">The temp file.</param>
  438. /// <returns>Task.</returns>
  439. /// <exception cref="HttpException"></exception>
  440. private Exception GetTempFileException(Exception ex, HttpRequestOptions options, string tempFile)
  441. {
  442. var operationCanceledException = ex as OperationCanceledException;
  443. if (operationCanceledException != null)
  444. {
  445. // Cleanup
  446. DeleteTempFile(tempFile);
  447. return GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  448. }
  449. _logger.ErrorException("Error getting response from " + options.Url, ex);
  450. // Cleanup
  451. DeleteTempFile(tempFile);
  452. var httpRequestException = ex as HttpRequestException;
  453. if (httpRequestException != null)
  454. {
  455. return new HttpException(ex.Message, ex);
  456. }
  457. var webException = ex as WebException;
  458. if (webException != null)
  459. {
  460. return new HttpException(ex.Message, ex);
  461. }
  462. return ex;
  463. }
  464. private void DeleteTempFile(string file)
  465. {
  466. try
  467. {
  468. File.Delete(file);
  469. }
  470. catch (IOException)
  471. {
  472. // Might not have been created at all. No need to worry.
  473. }
  474. }
  475. /// <summary>
  476. /// Validates the params.
  477. /// </summary>
  478. /// <param name="url">The URL.</param>
  479. /// <param name="cancellationToken">The cancellation token.</param>
  480. /// <exception cref="System.ArgumentNullException">url</exception>
  481. private void ValidateParams(string url, CancellationToken cancellationToken)
  482. {
  483. if (string.IsNullOrEmpty(url))
  484. {
  485. throw new ArgumentNullException("url");
  486. }
  487. }
  488. /// <summary>
  489. /// Gets the host from URL.
  490. /// </summary>
  491. /// <param name="url">The URL.</param>
  492. /// <returns>System.String.</returns>
  493. private string GetHostFromUrl(string url)
  494. {
  495. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  496. var len = url.IndexOf('/', start) - start;
  497. return url.Substring(start, len);
  498. }
  499. /// <summary>
  500. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  501. /// </summary>
  502. public void Dispose()
  503. {
  504. Dispose(true);
  505. GC.SuppressFinalize(this);
  506. }
  507. /// <summary>
  508. /// Releases unmanaged and - optionally - managed resources.
  509. /// </summary>
  510. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  511. protected virtual void Dispose(bool dispose)
  512. {
  513. if (dispose)
  514. {
  515. _httpClients.Clear();
  516. }
  517. }
  518. /// <summary>
  519. /// Throws the cancellation exception.
  520. /// </summary>
  521. /// <param name="url">The URL.</param>
  522. /// <param name="cancellationToken">The cancellation token.</param>
  523. /// <param name="exception">The exception.</param>
  524. /// <returns>Exception.</returns>
  525. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  526. {
  527. // If the HttpClient's timeout is reached, it will cancel the Task internally
  528. if (!cancellationToken.IsCancellationRequested)
  529. {
  530. var msg = string.Format("Connection to {0} timed out", url);
  531. _logger.Error(msg);
  532. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  533. return new HttpException(msg, exception) { IsTimedOut = true };
  534. }
  535. return exception;
  536. }
  537. private void EnsureSuccessStatusCode(HttpWebResponse response)
  538. {
  539. var statusCode = response.StatusCode;
  540. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  541. if (!isSuccessful)
  542. {
  543. throw new HttpException(response.StatusDescription) { StatusCode = response.StatusCode };
  544. }
  545. }
  546. /// <summary>
  547. /// Posts the specified URL.
  548. /// </summary>
  549. /// <param name="url">The URL.</param>
  550. /// <param name="postData">The post data.</param>
  551. /// <param name="cancellationToken">The cancellation token.</param>
  552. /// <returns>Task{Stream}.</returns>
  553. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  554. {
  555. return Post(url, postData, null, cancellationToken);
  556. }
  557. }
  558. }