HttpClientManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  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. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  43. _fileSystem = fileSystem;
  44. _appPaths = appPaths ?? throw new ArgumentNullException(nameof(appPaths));
  45. _defaultUserAgentFn = defaultUserAgentFn;
  46. }
  47. /// <summary>
  48. /// Gets the correct http client for the given url.
  49. /// </summary>
  50. /// <param name="url">The url.</param>
  51. /// <returns>HttpClient.</returns>
  52. private HttpClient GetHttpClient(string url)
  53. {
  54. var key = GetHostFromUrl(url);
  55. if (!_httpClients.TryGetValue(key, out var client))
  56. {
  57. var httpClientHandler = new HttpClientHandler()
  58. {
  59. ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
  60. {
  61. var success = errors == System.Net.Security.SslPolicyErrors.None;
  62. _logger.LogDebug("Validating certificate {Cert}. Success {1}", cert, success);
  63. return success;
  64. }
  65. };
  66. client = new HttpClient(httpClientHandler)
  67. {
  68. BaseAddress = new Uri(url)
  69. };
  70. _httpClients.TryAdd(key, client);
  71. }
  72. return client;
  73. }
  74. private HttpRequestMessage GetRequestMessage(HttpRequestOptions options, HttpMethod method)
  75. {
  76. string url = options.Url;
  77. var uriAddress = new Uri(url);
  78. string userInfo = uriAddress.UserInfo;
  79. if (!string.IsNullOrWhiteSpace(userInfo))
  80. {
  81. _logger.LogWarning("Found userInfo in url: {0} ... url: {1}", userInfo, url);
  82. url = url.Replace(userInfo + '@', string.Empty);
  83. }
  84. var request = new HttpRequestMessage(method, url);
  85. foreach (var header in options.RequestHeaders)
  86. {
  87. request.Headers.TryAddWithoutValidation(header.Key, header.Value);
  88. }
  89. if (options.EnableDefaultUserAgent
  90. && !request.Headers.TryGetValues(HeaderNames.UserAgent, out _))
  91. {
  92. request.Headers.Add(HeaderNames.UserAgent, _defaultUserAgentFn());
  93. }
  94. switch (options.DecompressionMethod)
  95. {
  96. case CompressionMethod.Deflate | CompressionMethod.Gzip:
  97. request.Headers.Add(HeaderNames.AcceptEncoding, new[] { "gzip", "deflate" });
  98. break;
  99. case CompressionMethod.Deflate:
  100. request.Headers.Add(HeaderNames.AcceptEncoding, "deflate");
  101. break;
  102. case CompressionMethod.Gzip:
  103. request.Headers.Add(HeaderNames.AcceptEncoding, "gzip");
  104. break;
  105. default:
  106. break;
  107. }
  108. if (options.EnableKeepAlive)
  109. {
  110. request.Headers.Add(HeaderNames.Connection, "Keep-Alive");
  111. }
  112. // request.Headers.Add(HeaderNames.CacheControl, "no-cache");
  113. /*
  114. if (!string.IsNullOrWhiteSpace(userInfo))
  115. {
  116. var parts = userInfo.Split(':');
  117. if (parts.Length == 2)
  118. {
  119. request.Headers.Add(HeaderNames., GetCredential(url, parts[0], parts[1]);
  120. }
  121. }
  122. */
  123. return request;
  124. }
  125. /// <summary>
  126. /// Gets the response internal.
  127. /// </summary>
  128. /// <param name="options">The options.</param>
  129. /// <returns>Task{HttpResponseInfo}.</returns>
  130. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  131. => SendAsync(options, HttpMethod.Get);
  132. /// <summary>
  133. /// Performs a GET request and returns the resulting stream
  134. /// </summary>
  135. /// <param name="options">The options.</param>
  136. /// <returns>Task{Stream}.</returns>
  137. public async Task<Stream> Get(HttpRequestOptions options)
  138. {
  139. var response = await GetResponse(options).ConfigureAwait(false);
  140. return response.Content;
  141. }
  142. /// <summary>
  143. /// send as an asynchronous operation.
  144. /// </summary>
  145. /// <param name="options">The options.</param>
  146. /// <param name="httpMethod">The HTTP method.</param>
  147. /// <returns>Task{HttpResponseInfo}.</returns>
  148. public Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  149. => SendAsync(options, new HttpMethod(httpMethod));
  150. /// <summary>
  151. /// send as an asynchronous operation.
  152. /// </summary>
  153. /// <param name="options">The options.</param>
  154. /// <param name="httpMethod">The HTTP method.</param>
  155. /// <returns>Task{HttpResponseInfo}.</returns>
  156. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, HttpMethod httpMethod)
  157. {
  158. if (options.CacheMode == CacheMode.None)
  159. {
  160. return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  161. }
  162. var url = options.Url;
  163. var urlHash = url.ToUpperInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
  164. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  165. var response = GetCachedResponse(responseCachePath, options.CacheLength, url);
  166. if (response != null)
  167. {
  168. return response;
  169. }
  170. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  171. if (response.StatusCode == HttpStatusCode.OK)
  172. {
  173. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  174. }
  175. return response;
  176. }
  177. private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  178. {
  179. if (File.Exists(responseCachePath)
  180. && _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  181. {
  182. var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
  183. return new HttpResponseInfo
  184. {
  185. ResponseUrl = url,
  186. Content = stream,
  187. StatusCode = HttpStatusCode.OK,
  188. ContentLength = stream.Length
  189. };
  190. }
  191. return null;
  192. }
  193. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  194. {
  195. Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  196. using (var fileStream = new FileStream(
  197. responseCachePath,
  198. FileMode.Create,
  199. FileAccess.Write,
  200. FileShare.None,
  201. StreamDefaults.DefaultFileStreamBufferSize,
  202. true))
  203. {
  204. await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
  205. response.Content.Position = 0;
  206. }
  207. }
  208. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, HttpMethod httpMethod)
  209. {
  210. ValidateParams(options);
  211. options.CancellationToken.ThrowIfCancellationRequested();
  212. var client = GetHttpClient(options.Url);
  213. var httpWebRequest = GetRequestMessage(options, httpMethod);
  214. if (options.RequestContentBytes != null
  215. || !string.IsNullOrEmpty(options.RequestContent)
  216. || httpMethod == HttpMethod.Post)
  217. {
  218. if (options.RequestContentBytes != null)
  219. {
  220. httpWebRequest.Content = new ByteArrayContent(options.RequestContentBytes);
  221. }
  222. else if (options.RequestContent != null)
  223. {
  224. httpWebRequest.Content = new StringContent(
  225. options.RequestContent,
  226. null,
  227. options.RequestContentType);
  228. }
  229. else
  230. {
  231. httpWebRequest.Content = new ByteArrayContent(Array.Empty<byte>());
  232. }
  233. }
  234. options.CancellationToken.ThrowIfCancellationRequested();
  235. var response = await client.SendAsync(
  236. httpWebRequest,
  237. options.BufferContent || options.CacheMode == CacheMode.Unconditional ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
  238. options.CancellationToken).ConfigureAwait(false);
  239. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  240. options.CancellationToken.ThrowIfCancellationRequested();
  241. var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  242. return new HttpResponseInfo(response.Headers, response.Content.Headers)
  243. {
  244. Content = stream,
  245. StatusCode = response.StatusCode,
  246. ContentType = response.Content.Headers.ContentType?.MediaType,
  247. ContentLength = response.Content.Headers.ContentLength,
  248. ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
  249. };
  250. }
  251. /// <inheritdoc />
  252. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  253. => SendAsync(options, HttpMethod.Post);
  254. private void ValidateParams(HttpRequestOptions options)
  255. {
  256. if (string.IsNullOrEmpty(options.Url))
  257. {
  258. throw new ArgumentNullException(nameof(options));
  259. }
  260. }
  261. /// <summary>
  262. /// Gets the host from URL.
  263. /// </summary>
  264. /// <param name="url">The URL.</param>
  265. /// <returns>System.String.</returns>
  266. private static string GetHostFromUrl(string url)
  267. {
  268. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  269. if (index != -1)
  270. {
  271. url = url.Substring(index + 3);
  272. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  273. if (!string.IsNullOrWhiteSpace(host))
  274. {
  275. return host;
  276. }
  277. }
  278. return url;
  279. }
  280. private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
  281. {
  282. if (response.IsSuccessStatusCode)
  283. {
  284. return;
  285. }
  286. if (options.LogErrorResponseBody)
  287. {
  288. string msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  289. _logger.LogError("HTTP request failed with message: {Message}", msg);
  290. }
  291. throw new HttpException(response.ReasonPhrase)
  292. {
  293. StatusCode = response.StatusCode
  294. };
  295. }
  296. }
  297. }