HttpClientManager.cs 34 KB

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