2
0

HttpClientManager.cs 24 KB

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