HttpClientManager.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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(_fileSystem.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. try
  395. {
  396. var bytes = options.RequestContentBytes ??
  397. Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
  398. httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  399. #if NET46
  400. httpWebRequest.ContentLength = bytes.Length;
  401. #endif
  402. (await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
  403. }
  404. catch (Exception ex)
  405. {
  406. throw new HttpException(ex.Message) { IsTimedOut = true };
  407. }
  408. }
  409. if (options.ResourcePool != null)
  410. {
  411. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  412. }
  413. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  414. {
  415. if (options.ResourcePool != null)
  416. {
  417. options.ResourcePool.Release();
  418. }
  419. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  420. }
  421. if (options.LogRequest)
  422. {
  423. _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
  424. }
  425. try
  426. {
  427. options.CancellationToken.ThrowIfCancellationRequested();
  428. if (!options.BufferContent)
  429. {
  430. var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false);
  431. var httpResponse = (HttpWebResponse)response;
  432. EnsureSuccessStatusCode(client, httpResponse, options);
  433. options.CancellationToken.ThrowIfCancellationRequested();
  434. return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse);
  435. }
  436. using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false))
  437. {
  438. var httpResponse = (HttpWebResponse)response;
  439. EnsureSuccessStatusCode(client, httpResponse, options);
  440. options.CancellationToken.ThrowIfCancellationRequested();
  441. using (var stream = httpResponse.GetResponseStream())
  442. {
  443. var memoryStream = _memoryStreamProvider.CreateNew();
  444. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  445. memoryStream.Position = 0;
  446. return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null);
  447. }
  448. }
  449. }
  450. catch (OperationCanceledException ex)
  451. {
  452. throw GetCancellationException(options, client, options.CancellationToken, ex);
  453. }
  454. catch (Exception ex)
  455. {
  456. throw GetException(ex, options, client);
  457. }
  458. finally
  459. {
  460. if (options.ResourcePool != null)
  461. {
  462. options.ResourcePool.Release();
  463. }
  464. }
  465. }
  466. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength, IDisposable disposable)
  467. {
  468. var responseInfo = new HttpResponseInfo(disposable)
  469. {
  470. Content = content,
  471. StatusCode = httpResponse.StatusCode,
  472. ContentType = httpResponse.ContentType,
  473. ContentLength = contentLength,
  474. ResponseUrl = httpResponse.ResponseUri.ToString()
  475. };
  476. if (httpResponse.Headers != null)
  477. {
  478. SetHeaders(httpResponse.Headers, responseInfo);
  479. }
  480. return responseInfo;
  481. }
  482. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
  483. {
  484. var responseInfo = new HttpResponseInfo
  485. {
  486. TempFilePath = tempFile,
  487. StatusCode = httpResponse.StatusCode,
  488. ContentType = httpResponse.ContentType,
  489. ContentLength = contentLength
  490. };
  491. if (httpResponse.Headers != null)
  492. {
  493. SetHeaders(httpResponse.Headers, responseInfo);
  494. }
  495. return responseInfo;
  496. }
  497. private void SetHeaders(WebHeaderCollection headers, HttpResponseInfo responseInfo)
  498. {
  499. foreach (var key in headers.AllKeys)
  500. {
  501. responseInfo.Headers[key] = headers[key];
  502. }
  503. }
  504. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  505. {
  506. return SendAsync(options, "POST");
  507. }
  508. /// <summary>
  509. /// Performs a POST request
  510. /// </summary>
  511. /// <param name="options">The options.</param>
  512. /// <param name="postData">Params to add to the POST data.</param>
  513. /// <returns>stream on success, null on failure</returns>
  514. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  515. {
  516. options.SetPostData(postData);
  517. var response = await Post(options).ConfigureAwait(false);
  518. return response.Content;
  519. }
  520. /// <summary>
  521. /// Performs a POST request
  522. /// </summary>
  523. /// <param name="url">The URL.</param>
  524. /// <param name="postData">Params to add to the POST data.</param>
  525. /// <param name="resourcePool">The resource pool.</param>
  526. /// <param name="cancellationToken">The cancellation token.</param>
  527. /// <returns>stream on success, null on failure</returns>
  528. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  529. {
  530. return Post(new HttpRequestOptions
  531. {
  532. Url = url,
  533. ResourcePool = resourcePool,
  534. CancellationToken = cancellationToken,
  535. BufferContent = resourcePool != null
  536. }, postData);
  537. }
  538. /// <summary>
  539. /// Downloads the contents of a given url into a temporary location
  540. /// </summary>
  541. /// <param name="options">The options.</param>
  542. /// <returns>Task{System.String}.</returns>
  543. public async Task<string> GetTempFile(HttpRequestOptions options)
  544. {
  545. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  546. return response.TempFilePath;
  547. }
  548. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  549. {
  550. ValidateParams(options);
  551. _fileSystem.CreateDirectory(_appPaths.TempDirectory);
  552. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  553. if (options.Progress == null)
  554. {
  555. throw new ArgumentNullException("progress");
  556. }
  557. options.CancellationToken.ThrowIfCancellationRequested();
  558. var httpWebRequest = GetRequest(options, "GET");
  559. if (options.ResourcePool != null)
  560. {
  561. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  562. }
  563. options.Progress.Report(0);
  564. if (options.LogRequest)
  565. {
  566. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  567. }
  568. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  569. try
  570. {
  571. options.CancellationToken.ThrowIfCancellationRequested();
  572. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  573. {
  574. var httpResponse = (HttpWebResponse)response;
  575. EnsureSuccessStatusCode(client, httpResponse, options);
  576. options.CancellationToken.ThrowIfCancellationRequested();
  577. var contentLength = GetContentLength(httpResponse);
  578. if (!contentLength.HasValue)
  579. {
  580. // We're not able to track progress
  581. using (var stream = httpResponse.GetResponseStream())
  582. {
  583. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  584. {
  585. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  586. }
  587. }
  588. }
  589. else
  590. {
  591. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  592. {
  593. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  594. {
  595. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  596. }
  597. }
  598. }
  599. options.Progress.Report(100);
  600. return GetResponseInfo(httpResponse, tempFile, contentLength);
  601. }
  602. }
  603. catch (Exception ex)
  604. {
  605. DeleteTempFile(tempFile);
  606. throw GetException(ex, options, client);
  607. }
  608. finally
  609. {
  610. if (options.ResourcePool != null)
  611. {
  612. options.ResourcePool.Release();
  613. }
  614. }
  615. }
  616. private long? GetContentLength(HttpWebResponse response)
  617. {
  618. var length = response.ContentLength;
  619. if (length == 0)
  620. {
  621. return null;
  622. }
  623. return length;
  624. }
  625. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  626. private Exception GetException(Exception ex, HttpRequestOptions options, HttpClientInfo client)
  627. {
  628. if (ex is HttpException)
  629. {
  630. return ex;
  631. }
  632. var webException = ex as WebException
  633. ?? ex.InnerException as WebException;
  634. if (webException != null)
  635. {
  636. if (options.LogErrors)
  637. {
  638. _logger.ErrorException("Error getting response from " + options.Url, ex);
  639. }
  640. var exception = new HttpException(ex.Message, ex);
  641. var response = webException.Response as HttpWebResponse;
  642. if (response != null)
  643. {
  644. exception.StatusCode = response.StatusCode;
  645. if ((int)response.StatusCode == 429)
  646. {
  647. client.LastTimeout = DateTime.UtcNow;
  648. }
  649. }
  650. return exception;
  651. }
  652. var operationCanceledException = ex as OperationCanceledException
  653. ?? ex.InnerException as OperationCanceledException;
  654. if (operationCanceledException != null)
  655. {
  656. return GetCancellationException(options, client, options.CancellationToken, operationCanceledException);
  657. }
  658. if (options.LogErrors)
  659. {
  660. _logger.ErrorException("Error getting response from " + options.Url, ex);
  661. }
  662. return ex;
  663. }
  664. private void DeleteTempFile(string file)
  665. {
  666. try
  667. {
  668. _fileSystem.DeleteFile(file);
  669. }
  670. catch (IOException)
  671. {
  672. // Might not have been created at all. No need to worry.
  673. }
  674. }
  675. private void ValidateParams(HttpRequestOptions options)
  676. {
  677. if (string.IsNullOrEmpty(options.Url))
  678. {
  679. throw new ArgumentNullException("options");
  680. }
  681. }
  682. /// <summary>
  683. /// Gets the host from URL.
  684. /// </summary>
  685. /// <param name="url">The URL.</param>
  686. /// <returns>System.String.</returns>
  687. private string GetHostFromUrl(string url)
  688. {
  689. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  690. if (index != -1)
  691. {
  692. url = url.Substring(index + 3);
  693. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  694. if (!string.IsNullOrWhiteSpace(host))
  695. {
  696. return host;
  697. }
  698. }
  699. return url;
  700. }
  701. /// <summary>
  702. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  703. /// </summary>
  704. public void Dispose()
  705. {
  706. Dispose(true);
  707. GC.SuppressFinalize(this);
  708. }
  709. /// <summary>
  710. /// Releases unmanaged and - optionally - managed resources.
  711. /// </summary>
  712. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  713. protected virtual void Dispose(bool dispose)
  714. {
  715. if (dispose)
  716. {
  717. _httpClients.Clear();
  718. }
  719. }
  720. /// <summary>
  721. /// Throws the cancellation exception.
  722. /// </summary>
  723. /// <param name="options">The options.</param>
  724. /// <param name="client">The client.</param>
  725. /// <param name="cancellationToken">The cancellation token.</param>
  726. /// <param name="exception">The exception.</param>
  727. /// <returns>Exception.</returns>
  728. private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
  729. {
  730. // If the HttpClient's timeout is reached, it will cancel the Task internally
  731. if (!cancellationToken.IsCancellationRequested)
  732. {
  733. var msg = string.Format("Connection to {0} timed out", options.Url);
  734. if (options.LogErrors)
  735. {
  736. _logger.Error(msg);
  737. }
  738. client.LastTimeout = DateTime.UtcNow;
  739. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  740. return new HttpException(msg, exception)
  741. {
  742. IsTimedOut = true
  743. };
  744. }
  745. return exception;
  746. }
  747. private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options)
  748. {
  749. var statusCode = response.StatusCode;
  750. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  751. if (!isSuccessful)
  752. {
  753. if (options.LogErrorResponseBody)
  754. {
  755. try
  756. {
  757. using (var stream = response.GetResponseStream())
  758. {
  759. if (stream != null)
  760. {
  761. using (var reader = new StreamReader(stream))
  762. {
  763. var msg = reader.ReadToEnd();
  764. _logger.Error(msg);
  765. }
  766. }
  767. }
  768. }
  769. catch
  770. {
  771. }
  772. }
  773. throw new HttpException(response.StatusDescription)
  774. {
  775. StatusCode = response.StatusCode
  776. };
  777. }
  778. }
  779. /// <summary>
  780. /// Posts the specified URL.
  781. /// </summary>
  782. /// <param name="url">The URL.</param>
  783. /// <param name="postData">The post data.</param>
  784. /// <param name="cancellationToken">The cancellation token.</param>
  785. /// <returns>Task{Stream}.</returns>
  786. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  787. {
  788. return Post(url, postData, null, cancellationToken);
  789. }
  790. private Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
  791. {
  792. #if NET46
  793. var taskCompletion = new TaskCompletionSource<WebResponse>();
  794. Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
  795. ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
  796. var callback = new TaskCallback { taskCompletion = taskCompletion };
  797. asyncTask.ContinueWith(callback.OnSuccess, TaskContinuationOptions.NotOnFaulted);
  798. // Handle errors
  799. asyncTask.ContinueWith(callback.OnError, TaskContinuationOptions.OnlyOnFaulted);
  800. return taskCompletion.Task;
  801. #endif
  802. return request.GetResponseAsync();
  803. }
  804. private static void TimeoutCallback(object state, bool timedOut)
  805. {
  806. if (timedOut)
  807. {
  808. WebRequest request = (WebRequest)state;
  809. if (state != null)
  810. {
  811. request.Abort();
  812. }
  813. }
  814. }
  815. private class TaskCallback
  816. {
  817. public TaskCompletionSource<WebResponse> taskCompletion;
  818. public void OnSuccess(Task<WebResponse> task)
  819. {
  820. taskCompletion.TrySetResult(task.Result);
  821. }
  822. public void OnError(Task<WebResponse> task)
  823. {
  824. if (task.Exception != null)
  825. {
  826. taskCompletion.TrySetException(task.Exception);
  827. }
  828. else
  829. {
  830. taskCompletion.TrySetException(new List<Exception>());
  831. }
  832. }
  833. }
  834. }
  835. }