HttpClientManager.cs 19 KB

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