2
0

HttpClientManager.cs 25 KB

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