2
0

HttpClientManager.cs 32 KB

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