HttpClientManager.cs 32 KB

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