HttpClientManager.cs 25 KB

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