HttpClientManager.cs 33 KB

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