HttpClientManager.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. using System.Net.Sockets;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Collections.Specialized;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using Emby.Common.Implementations.HttpClientManager;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Common;
  22. namespace Emby.Common.Implementations.HttpClientManager
  23. {
  24. /// <summary>
  25. /// Class HttpClientManager
  26. /// </summary>
  27. public class HttpClientManager : IHttpClient
  28. {
  29. /// <summary>
  30. /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
  31. /// </summary>
  32. private const int TimeoutSeconds = 30;
  33. /// <summary>
  34. /// The _logger
  35. /// </summary>
  36. private readonly ILogger _logger;
  37. /// <summary>
  38. /// The _app paths
  39. /// </summary>
  40. private readonly IApplicationPaths _appPaths;
  41. private readonly IFileSystem _fileSystem;
  42. private readonly IMemoryStreamFactory _memoryStreamProvider;
  43. private readonly Func<string> _defaultUserAgentFn;
  44. /// <summary>
  45. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  46. /// </summary>
  47. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem, IMemoryStreamFactory memoryStreamProvider, Func<string> defaultUserAgentFn)
  48. {
  49. if (appPaths == null)
  50. {
  51. throw new ArgumentNullException("appPaths");
  52. }
  53. if (logger == null)
  54. {
  55. throw new ArgumentNullException("logger");
  56. }
  57. _logger = logger;
  58. _fileSystem = fileSystem;
  59. _memoryStreamProvider = memoryStreamProvider;
  60. _appPaths = appPaths;
  61. _defaultUserAgentFn = defaultUserAgentFn;
  62. #if NET46
  63. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  64. ServicePointManager.Expect100Continue = false;
  65. // Trakt requests sometimes fail without this
  66. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
  67. #endif
  68. }
  69. /// <summary>
  70. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  71. /// DON'T dispose it after use.
  72. /// </summary>
  73. /// <value>The HTTP clients.</value>
  74. private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  75. /// <summary>
  76. /// Gets
  77. /// </summary>
  78. /// <param name="host">The host.</param>
  79. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  80. /// <returns>HttpClient.</returns>
  81. /// <exception cref="System.ArgumentNullException">host</exception>
  82. private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  83. {
  84. if (string.IsNullOrEmpty(host))
  85. {
  86. throw new ArgumentNullException("host");
  87. }
  88. HttpClientInfo client;
  89. var key = host + enableHttpCompression;
  90. if (!_httpClients.TryGetValue(key, out client))
  91. {
  92. client = new HttpClientInfo();
  93. _httpClients.TryAdd(key, client);
  94. }
  95. return client;
  96. }
  97. private WebRequest CreateWebRequest(string url)
  98. {
  99. try
  100. {
  101. return WebRequest.Create(url);
  102. }
  103. catch (NotSupportedException)
  104. {
  105. //Webrequest creation does fail on MONO randomly when using WebRequest.Create
  106. //the issue occurs in the GetCreator method here: http://www.oschina.net/code/explore/mono-2.8.1/mcs/class/System/System.Net/WebRequest.cs
  107. var type = Type.GetType("System.Net.HttpRequestCreator, System, Version=4.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089");
  108. var creator = Activator.CreateInstance(type, nonPublic: true) as IWebRequestCreate;
  109. return creator.Create(new Uri(url)) as HttpWebRequest;
  110. }
  111. }
  112. private void AddIpv4Option(HttpWebRequest request, HttpRequestOptions options)
  113. {
  114. #if NET46
  115. request.ServicePoint.BindIPEndPointDelegate = (servicePount, remoteEndPoint, retryCount) =>
  116. {
  117. if (remoteEndPoint.AddressFamily == AddressFamily.InterNetwork)
  118. {
  119. return new IPEndPoint(IPAddress.Any, 0);
  120. }
  121. throw new InvalidOperationException("no IPv4 address");
  122. };
  123. #endif
  124. }
  125. private WebRequest GetRequest(HttpRequestOptions options, string method)
  126. {
  127. var url = options.Url;
  128. var uriAddress = new Uri(url);
  129. var userInfo = uriAddress.UserInfo;
  130. if (!string.IsNullOrWhiteSpace(userInfo))
  131. {
  132. _logger.Info("Found userInfo in url: {0} ... url: {1}", userInfo, url);
  133. url = url.Replace(userInfo + "@", string.Empty);
  134. }
  135. var request = CreateWebRequest(url);
  136. var httpWebRequest = request as HttpWebRequest;
  137. if (httpWebRequest != null)
  138. {
  139. if (options.PreferIpv4)
  140. {
  141. AddIpv4Option(httpWebRequest, options);
  142. }
  143. AddRequestHeaders(httpWebRequest, options);
  144. #if NET46
  145. if (options.EnableHttpCompression)
  146. {
  147. if (options.DecompressionMethod.HasValue)
  148. {
  149. httpWebRequest.AutomaticDecompression = options.DecompressionMethod.Value == CompressionMethod.Gzip
  150. ? DecompressionMethods.GZip
  151. : DecompressionMethods.Deflate;
  152. }
  153. else
  154. {
  155. httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate;
  156. }
  157. }
  158. else
  159. {
  160. httpWebRequest.AutomaticDecompression = DecompressionMethods.None;
  161. }
  162. #endif
  163. }
  164. #if NET46
  165. request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
  166. #endif
  167. if (httpWebRequest != null)
  168. {
  169. if (options.EnableKeepAlive)
  170. {
  171. #if NET46
  172. httpWebRequest.KeepAlive = true;
  173. #endif
  174. }
  175. }
  176. request.Method = method;
  177. #if NET46
  178. request.Timeout = options.TimeoutMs;
  179. #endif
  180. if (httpWebRequest != null)
  181. {
  182. if (!string.IsNullOrEmpty(options.Host))
  183. {
  184. #if NET46
  185. httpWebRequest.Host = options.Host;
  186. #elif NETSTANDARD1_6
  187. httpWebRequest.Headers["Host"] = options.Host;
  188. #endif
  189. }
  190. if (!string.IsNullOrEmpty(options.Referer))
  191. {
  192. #if NET46
  193. httpWebRequest.Referer = options.Referer;
  194. #elif NETSTANDARD1_6
  195. httpWebRequest.Headers["Referer"] = options.Referer;
  196. #endif
  197. }
  198. }
  199. if (!string.IsNullOrWhiteSpace(userInfo))
  200. {
  201. var parts = userInfo.Split(':');
  202. if (parts.Length == 2)
  203. {
  204. request.Credentials = GetCredential(url, parts[0], parts[1]);
  205. // TODO: .net core ??
  206. #if NET46
  207. request.PreAuthenticate = true;
  208. #endif
  209. }
  210. }
  211. return request;
  212. }
  213. private CredentialCache GetCredential(string url, string username, string password)
  214. {
  215. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
  216. CredentialCache credentialCache = new CredentialCache();
  217. credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
  218. return credentialCache;
  219. }
  220. private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
  221. {
  222. var hasUserAgent = false;
  223. foreach (var header in options.RequestHeaders.ToList())
  224. {
  225. if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
  226. {
  227. request.Accept = header.Value;
  228. }
  229. else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
  230. {
  231. SetUserAgent(request, header.Value);
  232. hasUserAgent = true;
  233. }
  234. else
  235. {
  236. #if NET46
  237. request.Headers.Set(header.Key, header.Value);
  238. #elif NETSTANDARD1_6
  239. request.Headers[header.Key] = header.Value;
  240. #endif
  241. }
  242. }
  243. if (!hasUserAgent && options.EnableDefaultUserAgent)
  244. {
  245. SetUserAgent(request, _defaultUserAgentFn());
  246. }
  247. }
  248. private void SetUserAgent(HttpWebRequest request, string userAgent)
  249. {
  250. #if NET46
  251. request.UserAgent = userAgent;
  252. #elif NETSTANDARD1_6
  253. request.Headers["User-Agent"] = userAgent;
  254. #endif
  255. }
  256. /// <summary>
  257. /// Gets the response internal.
  258. /// </summary>
  259. /// <param name="options">The options.</param>
  260. /// <returns>Task{HttpResponseInfo}.</returns>
  261. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  262. {
  263. return SendAsync(options, "GET");
  264. }
  265. /// <summary>
  266. /// Performs a GET request and returns the resulting stream
  267. /// </summary>
  268. /// <param name="options">The options.</param>
  269. /// <returns>Task{Stream}.</returns>
  270. public async Task<Stream> Get(HttpRequestOptions options)
  271. {
  272. var response = await GetResponse(options).ConfigureAwait(false);
  273. return response.Content;
  274. }
  275. /// <summary>
  276. /// Performs a GET request and returns the resulting stream
  277. /// </summary>
  278. /// <param name="url">The URL.</param>
  279. /// <param name="resourcePool">The resource pool.</param>
  280. /// <param name="cancellationToken">The cancellation token.</param>
  281. /// <returns>Task{Stream}.</returns>
  282. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  283. {
  284. return Get(new HttpRequestOptions
  285. {
  286. Url = url,
  287. ResourcePool = resourcePool,
  288. CancellationToken = cancellationToken,
  289. BufferContent = resourcePool != null
  290. });
  291. }
  292. /// <summary>
  293. /// Gets the specified URL.
  294. /// </summary>
  295. /// <param name="url">The URL.</param>
  296. /// <param name="cancellationToken">The cancellation token.</param>
  297. /// <returns>Task{Stream}.</returns>
  298. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  299. {
  300. return Get(url, null, cancellationToken);
  301. }
  302. /// <summary>
  303. /// send as an asynchronous operation.
  304. /// </summary>
  305. /// <param name="options">The options.</param>
  306. /// <param name="httpMethod">The HTTP method.</param>
  307. /// <returns>Task{HttpResponseInfo}.</returns>
  308. /// <exception cref="HttpException">
  309. /// </exception>
  310. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  311. {
  312. if (options.CacheMode == CacheMode.None)
  313. {
  314. return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  315. }
  316. var url = options.Url;
  317. var urlHash = url.ToLower().GetMD5().ToString("N");
  318. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  319. var response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
  320. if (response != null)
  321. {
  322. return response;
  323. }
  324. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  325. if (response.StatusCode == HttpStatusCode.OK)
  326. {
  327. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  328. }
  329. return response;
  330. }
  331. private async Task<HttpResponseInfo> GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  332. {
  333. _logger.Info("Checking for cache file {0}", responseCachePath);
  334. try
  335. {
  336. if (_fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  337. {
  338. using (var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true))
  339. {
  340. var memoryStream = _memoryStreamProvider.CreateNew();
  341. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  342. memoryStream.Position = 0;
  343. return new HttpResponseInfo
  344. {
  345. ResponseUrl = url,
  346. Content = memoryStream,
  347. StatusCode = HttpStatusCode.OK,
  348. ContentLength = memoryStream.Length
  349. };
  350. }
  351. }
  352. }
  353. catch (FileNotFoundException)
  354. {
  355. }
  356. catch (DirectoryNotFoundException)
  357. {
  358. }
  359. return null;
  360. }
  361. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  362. {
  363. _fileSystem.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  364. using (var responseStream = response.Content)
  365. {
  366. var memoryStream = _memoryStreamProvider.CreateNew();
  367. await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  368. memoryStream.Position = 0;
  369. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
  370. {
  371. await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
  372. memoryStream.Position = 0;
  373. response.Content = memoryStream;
  374. }
  375. }
  376. }
  377. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod)
  378. {
  379. ValidateParams(options);
  380. options.CancellationToken.ThrowIfCancellationRequested();
  381. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  382. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  383. {
  384. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url))
  385. {
  386. IsTimedOut = true
  387. };
  388. }
  389. var httpWebRequest = GetRequest(options, httpMethod);
  390. if (options.RequestContentBytes != null ||
  391. !string.IsNullOrEmpty(options.RequestContent) ||
  392. string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
  393. {
  394. var bytes = options.RequestContentBytes ??
  395. Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
  396. httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  397. #if NET46
  398. httpWebRequest.ContentLength = bytes.Length;
  399. #endif
  400. (await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
  401. }
  402. if (options.ResourcePool != null)
  403. {
  404. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  405. }
  406. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  407. {
  408. if (options.ResourcePool != null)
  409. {
  410. options.ResourcePool.Release();
  411. }
  412. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  413. }
  414. if (options.LogRequest)
  415. {
  416. _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
  417. }
  418. try
  419. {
  420. options.CancellationToken.ThrowIfCancellationRequested();
  421. if (!options.BufferContent)
  422. {
  423. var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false);
  424. var httpResponse = (HttpWebResponse)response;
  425. EnsureSuccessStatusCode(client, httpResponse, options);
  426. options.CancellationToken.ThrowIfCancellationRequested();
  427. return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse);
  428. }
  429. using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false))
  430. {
  431. var httpResponse = (HttpWebResponse)response;
  432. EnsureSuccessStatusCode(client, httpResponse, options);
  433. options.CancellationToken.ThrowIfCancellationRequested();
  434. using (var stream = httpResponse.GetResponseStream())
  435. {
  436. var memoryStream = _memoryStreamProvider.CreateNew();
  437. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  438. memoryStream.Position = 0;
  439. return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null);
  440. }
  441. }
  442. }
  443. catch (OperationCanceledException ex)
  444. {
  445. throw GetCancellationException(options, client, options.CancellationToken, ex);
  446. }
  447. catch (Exception ex)
  448. {
  449. throw GetException(ex, options, client);
  450. }
  451. finally
  452. {
  453. if (options.ResourcePool != null)
  454. {
  455. options.ResourcePool.Release();
  456. }
  457. }
  458. }
  459. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength, IDisposable disposable)
  460. {
  461. var responseInfo = new HttpResponseInfo(disposable)
  462. {
  463. Content = content,
  464. StatusCode = httpResponse.StatusCode,
  465. ContentType = httpResponse.ContentType,
  466. ContentLength = contentLength,
  467. ResponseUrl = httpResponse.ResponseUri.ToString()
  468. };
  469. if (httpResponse.Headers != null)
  470. {
  471. SetHeaders(httpResponse.Headers, responseInfo);
  472. }
  473. return responseInfo;
  474. }
  475. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
  476. {
  477. var responseInfo = new HttpResponseInfo
  478. {
  479. TempFilePath = tempFile,
  480. StatusCode = httpResponse.StatusCode,
  481. ContentType = httpResponse.ContentType,
  482. ContentLength = contentLength
  483. };
  484. if (httpResponse.Headers != null)
  485. {
  486. SetHeaders(httpResponse.Headers, responseInfo);
  487. }
  488. return responseInfo;
  489. }
  490. private void SetHeaders(WebHeaderCollection headers, HttpResponseInfo responseInfo)
  491. {
  492. foreach (var key in headers.AllKeys)
  493. {
  494. responseInfo.Headers[key] = headers[key];
  495. }
  496. }
  497. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  498. {
  499. return SendAsync(options, "POST");
  500. }
  501. /// <summary>
  502. /// Performs a POST request
  503. /// </summary>
  504. /// <param name="options">The options.</param>
  505. /// <param name="postData">Params to add to the POST data.</param>
  506. /// <returns>stream on success, null on failure</returns>
  507. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  508. {
  509. options.SetPostData(postData);
  510. var response = await Post(options).ConfigureAwait(false);
  511. return response.Content;
  512. }
  513. /// <summary>
  514. /// Performs a POST request
  515. /// </summary>
  516. /// <param name="url">The URL.</param>
  517. /// <param name="postData">Params to add to the POST data.</param>
  518. /// <param name="resourcePool">The resource pool.</param>
  519. /// <param name="cancellationToken">The cancellation token.</param>
  520. /// <returns>stream on success, null on failure</returns>
  521. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  522. {
  523. return Post(new HttpRequestOptions
  524. {
  525. Url = url,
  526. ResourcePool = resourcePool,
  527. CancellationToken = cancellationToken,
  528. BufferContent = resourcePool != null
  529. }, postData);
  530. }
  531. /// <summary>
  532. /// Downloads the contents of a given url into a temporary location
  533. /// </summary>
  534. /// <param name="options">The options.</param>
  535. /// <returns>Task{System.String}.</returns>
  536. public async Task<string> GetTempFile(HttpRequestOptions options)
  537. {
  538. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  539. return response.TempFilePath;
  540. }
  541. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  542. {
  543. ValidateParams(options);
  544. _fileSystem.CreateDirectory(_appPaths.TempDirectory);
  545. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  546. if (options.Progress == null)
  547. {
  548. throw new ArgumentNullException("progress");
  549. }
  550. options.CancellationToken.ThrowIfCancellationRequested();
  551. var httpWebRequest = GetRequest(options, "GET");
  552. if (options.ResourcePool != null)
  553. {
  554. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  555. }
  556. options.Progress.Report(0);
  557. if (options.LogRequest)
  558. {
  559. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  560. }
  561. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  562. try
  563. {
  564. options.CancellationToken.ThrowIfCancellationRequested();
  565. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  566. {
  567. var httpResponse = (HttpWebResponse)response;
  568. EnsureSuccessStatusCode(client, httpResponse, options);
  569. options.CancellationToken.ThrowIfCancellationRequested();
  570. var contentLength = GetContentLength(httpResponse);
  571. if (!contentLength.HasValue)
  572. {
  573. // We're not able to track progress
  574. using (var stream = httpResponse.GetResponseStream())
  575. {
  576. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  577. {
  578. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  579. }
  580. }
  581. }
  582. else
  583. {
  584. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  585. {
  586. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  587. {
  588. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  589. }
  590. }
  591. }
  592. options.Progress.Report(100);
  593. return GetResponseInfo(httpResponse, tempFile, contentLength);
  594. }
  595. }
  596. catch (Exception ex)
  597. {
  598. DeleteTempFile(tempFile);
  599. throw GetException(ex, options, client);
  600. }
  601. finally
  602. {
  603. if (options.ResourcePool != null)
  604. {
  605. options.ResourcePool.Release();
  606. }
  607. }
  608. }
  609. private long? GetContentLength(HttpWebResponse response)
  610. {
  611. var length = response.ContentLength;
  612. if (length == 0)
  613. {
  614. return null;
  615. }
  616. return length;
  617. }
  618. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  619. private Exception GetException(Exception ex, HttpRequestOptions options, HttpClientInfo client)
  620. {
  621. if (ex is HttpException)
  622. {
  623. return ex;
  624. }
  625. var webException = ex as WebException
  626. ?? ex.InnerException as WebException;
  627. if (webException != null)
  628. {
  629. if (options.LogErrors)
  630. {
  631. _logger.ErrorException("Error getting response from " + options.Url, ex);
  632. }
  633. var exception = new HttpException(ex.Message, ex);
  634. var response = webException.Response as HttpWebResponse;
  635. if (response != null)
  636. {
  637. exception.StatusCode = response.StatusCode;
  638. if ((int)response.StatusCode == 429)
  639. {
  640. client.LastTimeout = DateTime.UtcNow;
  641. }
  642. }
  643. return exception;
  644. }
  645. var operationCanceledException = ex as OperationCanceledException
  646. ?? ex.InnerException as OperationCanceledException;
  647. if (operationCanceledException != null)
  648. {
  649. return GetCancellationException(options, client, options.CancellationToken, operationCanceledException);
  650. }
  651. if (options.LogErrors)
  652. {
  653. _logger.ErrorException("Error getting response from " + options.Url, ex);
  654. }
  655. return ex;
  656. }
  657. private void DeleteTempFile(string file)
  658. {
  659. try
  660. {
  661. _fileSystem.DeleteFile(file);
  662. }
  663. catch (IOException)
  664. {
  665. // Might not have been created at all. No need to worry.
  666. }
  667. }
  668. private void ValidateParams(HttpRequestOptions options)
  669. {
  670. if (string.IsNullOrEmpty(options.Url))
  671. {
  672. throw new ArgumentNullException("options");
  673. }
  674. }
  675. /// <summary>
  676. /// Gets the host from URL.
  677. /// </summary>
  678. /// <param name="url">The URL.</param>
  679. /// <returns>System.String.</returns>
  680. private string GetHostFromUrl(string url)
  681. {
  682. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  683. if (index != -1)
  684. {
  685. url = url.Substring(index + 3);
  686. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  687. if (!string.IsNullOrWhiteSpace(host))
  688. {
  689. return host;
  690. }
  691. }
  692. return url;
  693. }
  694. /// <summary>
  695. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  696. /// </summary>
  697. public void Dispose()
  698. {
  699. Dispose(true);
  700. GC.SuppressFinalize(this);
  701. }
  702. /// <summary>
  703. /// Releases unmanaged and - optionally - managed resources.
  704. /// </summary>
  705. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  706. protected virtual void Dispose(bool dispose)
  707. {
  708. if (dispose)
  709. {
  710. _httpClients.Clear();
  711. }
  712. }
  713. /// <summary>
  714. /// Throws the cancellation exception.
  715. /// </summary>
  716. /// <param name="options">The options.</param>
  717. /// <param name="client">The client.</param>
  718. /// <param name="cancellationToken">The cancellation token.</param>
  719. /// <param name="exception">The exception.</param>
  720. /// <returns>Exception.</returns>
  721. private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
  722. {
  723. // If the HttpClient's timeout is reached, it will cancel the Task internally
  724. if (!cancellationToken.IsCancellationRequested)
  725. {
  726. var msg = string.Format("Connection to {0} timed out", options.Url);
  727. if (options.LogErrors)
  728. {
  729. _logger.Error(msg);
  730. }
  731. client.LastTimeout = DateTime.UtcNow;
  732. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  733. return new HttpException(msg, exception)
  734. {
  735. IsTimedOut = true
  736. };
  737. }
  738. return exception;
  739. }
  740. private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options)
  741. {
  742. var statusCode = response.StatusCode;
  743. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  744. if (!isSuccessful)
  745. {
  746. if (options.LogErrorResponseBody)
  747. {
  748. try
  749. {
  750. using (var stream = response.GetResponseStream())
  751. {
  752. if (stream != null)
  753. {
  754. using (var reader = new StreamReader(stream))
  755. {
  756. var msg = reader.ReadToEnd();
  757. _logger.Error(msg);
  758. }
  759. }
  760. }
  761. }
  762. catch
  763. {
  764. }
  765. }
  766. throw new HttpException(response.StatusDescription)
  767. {
  768. StatusCode = response.StatusCode
  769. };
  770. }
  771. }
  772. /// <summary>
  773. /// Posts the specified URL.
  774. /// </summary>
  775. /// <param name="url">The URL.</param>
  776. /// <param name="postData">The post data.</param>
  777. /// <param name="cancellationToken">The cancellation token.</param>
  778. /// <returns>Task{Stream}.</returns>
  779. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  780. {
  781. return Post(url, postData, null, cancellationToken);
  782. }
  783. private Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
  784. {
  785. #if NET46
  786. var taskCompletion = new TaskCompletionSource<WebResponse>();
  787. Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
  788. ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
  789. var callback = new TaskCallback { taskCompletion = taskCompletion };
  790. asyncTask.ContinueWith(callback.OnSuccess, TaskContinuationOptions.NotOnFaulted);
  791. // Handle errors
  792. asyncTask.ContinueWith(callback.OnError, TaskContinuationOptions.OnlyOnFaulted);
  793. return taskCompletion.Task;
  794. #endif
  795. return request.GetResponseAsync();
  796. }
  797. private static void TimeoutCallback(object state, bool timedOut)
  798. {
  799. if (timedOut)
  800. {
  801. WebRequest request = (WebRequest)state;
  802. if (state != null)
  803. {
  804. request.Abort();
  805. }
  806. }
  807. }
  808. private class TaskCallback
  809. {
  810. public TaskCompletionSource<WebResponse> taskCompletion;
  811. public void OnSuccess(Task<WebResponse> task)
  812. {
  813. taskCompletion.TrySetResult(task.Result);
  814. }
  815. public void OnError(Task<WebResponse> task)
  816. {
  817. if (task.Exception != null)
  818. {
  819. taskCompletion.TrySetException(task.Exception);
  820. }
  821. else
  822. {
  823. taskCompletion.TrySetException(new List<Exception>());
  824. }
  825. }
  826. }
  827. }
  828. }