HttpClientManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Net.Http.Headers;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Common.Extensions;
  13. using MediaBrowser.Common.Net;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.Net;
  16. using Microsoft.Extensions.Logging;
  17. using Microsoft.Net.Http.Headers;
  18. namespace Emby.Server.Implementations.HttpClientManager
  19. {
  20. /// <summary>
  21. /// Class HttpClientManager
  22. /// </summary>
  23. public class HttpClientManager : IHttpClient
  24. {
  25. /// <summary>
  26. /// The _logger
  27. /// </summary>
  28. private readonly ILogger _logger;
  29. /// <summary>
  30. /// The _app paths
  31. /// </summary>
  32. private readonly IApplicationPaths _appPaths;
  33. private readonly IFileSystem _fileSystem;
  34. private readonly Func<string> _defaultUserAgentFn;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  37. /// </summary>
  38. public HttpClientManager(
  39. IApplicationPaths appPaths,
  40. ILogger<HttpClientManager> logger,
  41. IFileSystem fileSystem,
  42. Func<string> defaultUserAgentFn)
  43. {
  44. if (appPaths == null)
  45. {
  46. throw new ArgumentNullException(nameof(appPaths));
  47. }
  48. if (logger == null)
  49. {
  50. throw new ArgumentNullException(nameof(logger));
  51. }
  52. _logger = logger;
  53. _fileSystem = fileSystem;
  54. _appPaths = appPaths;
  55. _defaultUserAgentFn = defaultUserAgentFn;
  56. }
  57. /// <summary>
  58. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  59. /// DON'T dispose it after use.
  60. /// </summary>
  61. /// <value>The HTTP clients.</value>
  62. private readonly ConcurrentDictionary<string, HttpClient> _httpClients = new ConcurrentDictionary<string, HttpClient>();
  63. /// <summary>
  64. /// Gets
  65. /// </summary>
  66. /// <param name="url">The host.</param>
  67. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  68. /// <returns>HttpClient.</returns>
  69. /// <exception cref="ArgumentNullException">host</exception>
  70. private HttpClient GetHttpClient(string url)
  71. {
  72. var key = GetHostFromUrl(url);
  73. if (!_httpClients.TryGetValue(key, out var client))
  74. {
  75. client = new HttpClient()
  76. {
  77. BaseAddress = new Uri(url)
  78. };
  79. _httpClients.TryAdd(key, client);
  80. }
  81. return client;
  82. }
  83. private HttpRequestMessage GetRequestMessage(HttpRequestOptions options, HttpMethod method)
  84. {
  85. string url = options.Url;
  86. var uriAddress = new Uri(url);
  87. string userInfo = uriAddress.UserInfo;
  88. if (!string.IsNullOrWhiteSpace(userInfo))
  89. {
  90. _logger.LogWarning("Found userInfo in url: {0} ... url: {1}", userInfo, url);
  91. url = url.Replace(userInfo + '@', string.Empty);
  92. }
  93. var request = new HttpRequestMessage(method, url);
  94. AddRequestHeaders(request, options);
  95. switch (options.DecompressionMethod)
  96. {
  97. case CompressionMethod.Deflate | CompressionMethod.Gzip:
  98. request.Headers.Add(HeaderNames.AcceptEncoding, new[] { "gzip", "deflate" });
  99. break;
  100. case CompressionMethod.Deflate:
  101. request.Headers.Add(HeaderNames.AcceptEncoding, "deflate");
  102. break;
  103. case CompressionMethod.Gzip:
  104. request.Headers.Add(HeaderNames.AcceptEncoding, "gzip");
  105. break;
  106. case 0:
  107. default:
  108. break;
  109. }
  110. if (options.EnableKeepAlive)
  111. {
  112. request.Headers.Add(HeaderNames.Connection, "Keep-Alive");
  113. }
  114. //request.Headers.Add(HeaderNames.CacheControl, "no-cache");
  115. /*
  116. if (!string.IsNullOrWhiteSpace(userInfo))
  117. {
  118. var parts = userInfo.Split(':');
  119. if (parts.Length == 2)
  120. {
  121. request.Headers.Add(HeaderNames., GetCredential(url, parts[0], parts[1]);
  122. }
  123. }
  124. */
  125. return request;
  126. }
  127. private void AddRequestHeaders(HttpRequestMessage request, HttpRequestOptions options)
  128. {
  129. var hasUserAgent = false;
  130. foreach (var header in options.RequestHeaders)
  131. {
  132. if (string.Equals(header.Key, HeaderNames.UserAgent, StringComparison.OrdinalIgnoreCase))
  133. {
  134. hasUserAgent = true;
  135. }
  136. request.Headers.Add(header.Key, header.Value);
  137. }
  138. if (!hasUserAgent && options.EnableDefaultUserAgent)
  139. {
  140. request.Headers.Add(HeaderNames.UserAgent, _defaultUserAgentFn());
  141. }
  142. }
  143. /// <summary>
  144. /// Gets the response internal.
  145. /// </summary>
  146. /// <param name="options">The options.</param>
  147. /// <returns>Task{HttpResponseInfo}.</returns>
  148. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  149. => SendAsync(options, HttpMethod.Get);
  150. /// <summary>
  151. /// Performs a GET request and returns the resulting stream
  152. /// </summary>
  153. /// <param name="options">The options.</param>
  154. /// <returns>Task{Stream}.</returns>
  155. public async Task<Stream> Get(HttpRequestOptions options)
  156. {
  157. var response = await GetResponse(options).ConfigureAwait(false);
  158. return response.Content;
  159. }
  160. /// <summary>
  161. /// send as an asynchronous operation.
  162. /// </summary>
  163. /// <param name="options">The options.</param>
  164. /// <param name="httpMethod">The HTTP method.</param>
  165. /// <returns>Task{HttpResponseInfo}.</returns>
  166. /// <exception cref="HttpException">
  167. /// </exception>
  168. public Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  169. {
  170. var httpMethod2 = GetHttpMethod(httpMethod);
  171. return SendAsync(options, httpMethod2);
  172. }
  173. /// <summary>
  174. /// send as an asynchronous operation.
  175. /// </summary>
  176. /// <param name="options">The options.</param>
  177. /// <param name="httpMethod">The HTTP method.</param>
  178. /// <returns>Task{HttpResponseInfo}.</returns>
  179. /// <exception cref="HttpException">
  180. /// </exception>
  181. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, HttpMethod httpMethod)
  182. {
  183. if (options.CacheMode == CacheMode.None)
  184. {
  185. return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  186. }
  187. var url = options.Url;
  188. var urlHash = url.ToLowerInvariant().GetMD5().ToString("N");
  189. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  190. var response = GetCachedResponse(responseCachePath, options.CacheLength, url);
  191. if (response != null)
  192. {
  193. return response;
  194. }
  195. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  196. if (response.StatusCode == HttpStatusCode.OK)
  197. {
  198. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  199. }
  200. return response;
  201. }
  202. private HttpMethod GetHttpMethod(string httpMethod)
  203. {
  204. if (httpMethod.Equals("DELETE", StringComparison.OrdinalIgnoreCase))
  205. {
  206. return HttpMethod.Delete;
  207. }
  208. else if (httpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
  209. {
  210. return HttpMethod.Get;
  211. }
  212. else if (httpMethod.Equals("HEAD", StringComparison.OrdinalIgnoreCase))
  213. {
  214. return HttpMethod.Head;
  215. }
  216. else if (httpMethod.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase))
  217. {
  218. return HttpMethod.Options;
  219. }
  220. else if (httpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
  221. {
  222. return HttpMethod.Post;
  223. }
  224. else if (httpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase))
  225. {
  226. return HttpMethod.Put;
  227. }
  228. else if (httpMethod.Equals("TRACE", StringComparison.OrdinalIgnoreCase))
  229. {
  230. return HttpMethod.Trace;
  231. }
  232. throw new ArgumentException("Invalid HTTP method", nameof(httpMethod));
  233. }
  234. private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  235. {
  236. if (File.Exists(responseCachePath)
  237. && _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  238. {
  239. var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
  240. return new HttpResponseInfo
  241. {
  242. ResponseUrl = url,
  243. Content = stream,
  244. StatusCode = HttpStatusCode.OK,
  245. ContentLength = stream.Length
  246. };
  247. }
  248. return null;
  249. }
  250. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  251. {
  252. Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  253. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
  254. {
  255. await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
  256. response.Content.Position = 0;
  257. }
  258. }
  259. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, HttpMethod httpMethod)
  260. {
  261. ValidateParams(options);
  262. options.CancellationToken.ThrowIfCancellationRequested();
  263. var client = GetHttpClient(options.Url);
  264. var httpWebRequest = GetRequestMessage(options, httpMethod);
  265. if (options.RequestContentBytes != null
  266. || !string.IsNullOrEmpty(options.RequestContent)
  267. || httpMethod == HttpMethod.Post)
  268. {
  269. try
  270. {
  271. if (options.RequestContentBytes != null)
  272. {
  273. httpWebRequest.Content = new ByteArrayContent(options.RequestContentBytes);
  274. }
  275. else if (options.RequestContent != null)
  276. {
  277. httpWebRequest.Content = new StringContent(options.RequestContent);
  278. }
  279. else
  280. {
  281. httpWebRequest.Content = new ByteArrayContent(Array.Empty<byte>());
  282. }
  283. /*
  284. var contentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  285. if (options.AppendCharsetToMimeType)
  286. {
  287. contentType = contentType.TrimEnd(';') + "; charset=\"utf-8\"";
  288. }
  289. httpWebRequest.Headers.Add(HeaderNames.ContentType, contentType);*/
  290. using (var response = await client.SendAsync(httpWebRequest).ConfigureAwait(false))
  291. {
  292. return await HandleResponseAsync(response, options).ConfigureAwait(false);
  293. }
  294. }
  295. catch (Exception ex)
  296. {
  297. throw new HttpException(ex.Message) { IsTimedOut = true };
  298. }
  299. }
  300. if (options.LogRequest)
  301. {
  302. _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToString(), options.Url);
  303. }
  304. try
  305. {
  306. options.CancellationToken.ThrowIfCancellationRequested();
  307. /*if (!options.BufferContent)
  308. {
  309. var response = await client.HttpClient.SendAsync(httpWebRequest).ConfigureAwait(false);
  310. await EnsureSuccessStatusCode(client, response, options).ConfigureAwait(false);
  311. options.CancellationToken.ThrowIfCancellationRequested();
  312. return GetResponseInfo(response, await response.Content.ReadAsStreamAsync().ConfigureAwait(false), response.Content.Headers.ContentLength, response);
  313. }*/
  314. using (var response = await client.SendAsync(httpWebRequest).ConfigureAwait(false))
  315. {
  316. return await HandleResponseAsync(response, options).ConfigureAwait(false);
  317. }
  318. }
  319. catch (OperationCanceledException ex)
  320. {
  321. throw GetCancellationException(options, options.CancellationToken, ex);
  322. }
  323. }
  324. private async Task<HttpResponseInfo> HandleResponseAsync(HttpResponseMessage response, HttpRequestOptions options)
  325. {
  326. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  327. options.CancellationToken.ThrowIfCancellationRequested();
  328. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  329. {
  330. var memoryStream = new MemoryStream();
  331. await stream.CopyToAsync(memoryStream, 81920, options.CancellationToken).ConfigureAwait(false);
  332. memoryStream.Position = 0;
  333. return GetResponseInfo(response, memoryStream, memoryStream.Length);
  334. }
  335. }
  336. private HttpResponseInfo GetResponseInfo(HttpResponseMessage httpResponse, Stream content, long? contentLength)
  337. {
  338. var responseInfo = new HttpResponseInfo()
  339. {
  340. Content = content,
  341. StatusCode = httpResponse.StatusCode,
  342. ContentType = httpResponse.Content.Headers.ContentType?.MediaType,
  343. ContentLength = contentLength,
  344. ResponseUrl = httpResponse.Content.Headers.ContentLocation?.ToString()
  345. };
  346. if (httpResponse.Headers != null)
  347. {
  348. SetHeaders(httpResponse.Content.Headers, responseInfo);
  349. }
  350. return responseInfo;
  351. }
  352. private HttpResponseInfo GetResponseInfo(HttpResponseMessage httpResponse, string tempFile, long? contentLength)
  353. {
  354. var responseInfo = new HttpResponseInfo
  355. {
  356. TempFilePath = tempFile,
  357. StatusCode = httpResponse.StatusCode,
  358. ContentType = httpResponse.Content.Headers.ContentType?.MediaType,
  359. ContentLength = contentLength
  360. };
  361. if (httpResponse.Headers != null)
  362. {
  363. SetHeaders(httpResponse.Content.Headers, responseInfo);
  364. }
  365. return responseInfo;
  366. }
  367. private static void SetHeaders(HttpContentHeaders headers, HttpResponseInfo responseInfo)
  368. {
  369. foreach (var header in headers)
  370. {
  371. responseInfo.Headers[header.Key] = string.Join(", ", header.Value);
  372. }
  373. }
  374. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  375. => SendAsync(options, HttpMethod.Post);
  376. /// <summary>
  377. /// Downloads the contents of a given url into a temporary location
  378. /// </summary>
  379. /// <param name="options">The options.</param>
  380. /// <returns>Task{System.String}.</returns>
  381. public async Task<string> GetTempFile(HttpRequestOptions options)
  382. {
  383. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  384. return response.TempFilePath;
  385. }
  386. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  387. {
  388. ValidateParams(options);
  389. Directory.CreateDirectory(_appPaths.TempDirectory);
  390. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  391. if (options.Progress == null)
  392. {
  393. throw new ArgumentException("Options did not have a Progress value.", nameof(options));
  394. }
  395. options.CancellationToken.ThrowIfCancellationRequested();
  396. var httpWebRequest = GetRequestMessage(options, HttpMethod.Get);
  397. options.Progress.Report(0);
  398. if (options.LogRequest)
  399. {
  400. _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  401. }
  402. var client = GetHttpClient(options.Url);
  403. try
  404. {
  405. options.CancellationToken.ThrowIfCancellationRequested();
  406. using (var response = (await client.SendAsync(httpWebRequest, options.CancellationToken).ConfigureAwait(false)))
  407. {
  408. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  409. options.CancellationToken.ThrowIfCancellationRequested();
  410. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  411. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  412. {
  413. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  414. }
  415. options.Progress.Report(100);
  416. var contentLength = response.Content.Headers.ContentLength;
  417. return GetResponseInfo(response, tempFile, contentLength);
  418. }
  419. }
  420. catch (Exception ex)
  421. {
  422. if (File.Exists(tempFile))
  423. {
  424. File.Delete(tempFile);
  425. }
  426. throw GetException(ex, options);
  427. }
  428. }
  429. private Exception GetException(Exception ex, HttpRequestOptions options)
  430. {
  431. if (ex is HttpException)
  432. {
  433. return ex;
  434. }
  435. var webException = ex as WebException
  436. ?? ex.InnerException as WebException;
  437. if (webException != null)
  438. {
  439. if (options.LogErrors)
  440. {
  441. _logger.LogError(webException, "Error {Status} getting response from {Url}", webException.Status, options.Url);
  442. }
  443. var exception = new HttpException(webException.Message, webException);
  444. using (var response = webException.Response as HttpWebResponse)
  445. {
  446. if (response != null)
  447. {
  448. exception.StatusCode = response.StatusCode;
  449. }
  450. }
  451. if (!exception.StatusCode.HasValue)
  452. {
  453. if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
  454. webException.Status == WebExceptionStatus.ConnectFailure)
  455. {
  456. exception.IsTimedOut = true;
  457. }
  458. }
  459. return exception;
  460. }
  461. var operationCanceledException = ex as OperationCanceledException
  462. ?? ex.InnerException as OperationCanceledException;
  463. if (operationCanceledException != null)
  464. {
  465. return GetCancellationException(options, options.CancellationToken, operationCanceledException);
  466. }
  467. if (options.LogErrors)
  468. {
  469. _logger.LogError(ex, "Error getting response from {Url}", options.Url);
  470. }
  471. return ex;
  472. }
  473. private void ValidateParams(HttpRequestOptions options)
  474. {
  475. if (string.IsNullOrEmpty(options.Url))
  476. {
  477. throw new ArgumentNullException(nameof(options));
  478. }
  479. }
  480. /// <summary>
  481. /// Gets the host from URL.
  482. /// </summary>
  483. /// <param name="url">The URL.</param>
  484. /// <returns>System.String.</returns>
  485. private static string GetHostFromUrl(string url)
  486. {
  487. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  488. if (index != -1)
  489. {
  490. url = url.Substring(index + 3);
  491. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  492. if (!string.IsNullOrWhiteSpace(host))
  493. {
  494. return host;
  495. }
  496. }
  497. return url;
  498. }
  499. /// <summary>
  500. /// Throws the cancellation exception.
  501. /// </summary>
  502. /// <param name="options">The options.</param>
  503. /// <param name="cancellationToken">The cancellation token.</param>
  504. /// <param name="exception">The exception.</param>
  505. /// <returns>Exception.</returns>
  506. private Exception GetCancellationException(HttpRequestOptions options, CancellationToken cancellationToken, OperationCanceledException exception)
  507. {
  508. // If the HttpClient's timeout is reached, it will cancel the Task internally
  509. if (!cancellationToken.IsCancellationRequested)
  510. {
  511. var msg = string.Format("Connection to {0} timed out", options.Url);
  512. if (options.LogErrors)
  513. {
  514. _logger.LogError(msg);
  515. }
  516. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  517. return new HttpException(msg, exception)
  518. {
  519. IsTimedOut = true
  520. };
  521. }
  522. return exception;
  523. }
  524. private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
  525. {
  526. if (response.IsSuccessStatusCode)
  527. {
  528. return;
  529. }
  530. var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  531. _logger.LogError(msg);
  532. throw new HttpException(response.ReasonPhrase)
  533. {
  534. StatusCode = response.StatusCode
  535. };
  536. }
  537. }
  538. }