HttpClientManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. client = new HttpClient()
  58. {
  59. BaseAddress = new Uri(url)
  60. };
  61. _httpClients.TryAdd(key, client);
  62. }
  63. return client;
  64. }
  65. private HttpRequestMessage GetRequestMessage(HttpRequestOptions options, HttpMethod method)
  66. {
  67. string url = options.Url;
  68. var uriAddress = new Uri(url);
  69. string userInfo = uriAddress.UserInfo;
  70. if (!string.IsNullOrWhiteSpace(userInfo))
  71. {
  72. _logger.LogWarning("Found userInfo in url: {0} ... url: {1}", userInfo, url);
  73. url = url.Replace(userInfo + '@', string.Empty);
  74. }
  75. var request = new HttpRequestMessage(method, url);
  76. foreach (var header in options.RequestHeaders)
  77. {
  78. request.Headers.TryAddWithoutValidation(header.Key, header.Value);
  79. }
  80. if (options.EnableDefaultUserAgent
  81. && !request.Headers.TryGetValues(HeaderNames.UserAgent, out _))
  82. {
  83. request.Headers.Add(HeaderNames.UserAgent, _defaultUserAgentFn());
  84. }
  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. /// <summary>
  117. /// Gets the response internal.
  118. /// </summary>
  119. /// <param name="options">The options.</param>
  120. /// <returns>Task{HttpResponseInfo}.</returns>
  121. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  122. => SendAsync(options, HttpMethod.Get);
  123. /// <summary>
  124. /// Performs a GET request and returns the resulting stream
  125. /// </summary>
  126. /// <param name="options">The options.</param>
  127. /// <returns>Task{Stream}.</returns>
  128. public async Task<Stream> Get(HttpRequestOptions options)
  129. {
  130. var response = await GetResponse(options).ConfigureAwait(false);
  131. return response.Content;
  132. }
  133. /// <summary>
  134. /// send as an asynchronous operation.
  135. /// </summary>
  136. /// <param name="options">The options.</param>
  137. /// <param name="httpMethod">The HTTP method.</param>
  138. /// <returns>Task{HttpResponseInfo}.</returns>
  139. public Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  140. => SendAsync(options, new HttpMethod(httpMethod));
  141. /// <summary>
  142. /// send as an asynchronous operation.
  143. /// </summary>
  144. /// <param name="options">The options.</param>
  145. /// <param name="httpMethod">The HTTP method.</param>
  146. /// <returns>Task{HttpResponseInfo}.</returns>
  147. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, HttpMethod httpMethod)
  148. {
  149. if (options.CacheMode == CacheMode.None)
  150. {
  151. return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  152. }
  153. var url = options.Url;
  154. var urlHash = url.ToUpperInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
  155. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  156. var response = GetCachedResponse(responseCachePath, options.CacheLength, url);
  157. if (response != null)
  158. {
  159. return response;
  160. }
  161. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  162. if (response.StatusCode == HttpStatusCode.OK)
  163. {
  164. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  165. }
  166. return response;
  167. }
  168. private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  169. {
  170. if (File.Exists(responseCachePath)
  171. && _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  172. {
  173. var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
  174. return new HttpResponseInfo
  175. {
  176. ResponseUrl = url,
  177. Content = stream,
  178. StatusCode = HttpStatusCode.OK,
  179. ContentLength = stream.Length
  180. };
  181. }
  182. return null;
  183. }
  184. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  185. {
  186. Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  187. using (var fileStream = new FileStream(
  188. responseCachePath,
  189. FileMode.Create,
  190. FileAccess.Write,
  191. FileShare.None,
  192. StreamDefaults.DefaultFileStreamBufferSize,
  193. true))
  194. {
  195. await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
  196. response.Content.Position = 0;
  197. }
  198. }
  199. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, HttpMethod httpMethod)
  200. {
  201. ValidateParams(options);
  202. options.CancellationToken.ThrowIfCancellationRequested();
  203. var client = GetHttpClient(options.Url);
  204. var httpWebRequest = GetRequestMessage(options, httpMethod);
  205. if (options.RequestContentBytes != null
  206. || !string.IsNullOrEmpty(options.RequestContent)
  207. || httpMethod == HttpMethod.Post)
  208. {
  209. if (options.RequestContentBytes != null)
  210. {
  211. httpWebRequest.Content = new ByteArrayContent(options.RequestContentBytes);
  212. }
  213. else if (options.RequestContent != null)
  214. {
  215. httpWebRequest.Content = new StringContent(
  216. options.RequestContent,
  217. null,
  218. options.RequestContentType);
  219. }
  220. else
  221. {
  222. httpWebRequest.Content = new ByteArrayContent(Array.Empty<byte>());
  223. }
  224. }
  225. options.CancellationToken.ThrowIfCancellationRequested();
  226. var response = await client.SendAsync(
  227. httpWebRequest,
  228. options.BufferContent || options.CacheMode == CacheMode.Unconditional ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
  229. options.CancellationToken).ConfigureAwait(false);
  230. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  231. options.CancellationToken.ThrowIfCancellationRequested();
  232. var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  233. return new HttpResponseInfo(response.Headers, response.Content.Headers)
  234. {
  235. Content = stream,
  236. StatusCode = response.StatusCode,
  237. ContentType = response.Content.Headers.ContentType?.MediaType,
  238. ContentLength = response.Content.Headers.ContentLength,
  239. ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
  240. };
  241. }
  242. /// <inheritdoc />
  243. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  244. => SendAsync(options, HttpMethod.Post);
  245. private void ValidateParams(HttpRequestOptions options)
  246. {
  247. if (string.IsNullOrEmpty(options.Url))
  248. {
  249. throw new ArgumentNullException(nameof(options));
  250. }
  251. }
  252. /// <summary>
  253. /// Gets the host from URL.
  254. /// </summary>
  255. /// <param name="url">The URL.</param>
  256. /// <returns>System.String.</returns>
  257. private static string GetHostFromUrl(string url)
  258. {
  259. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  260. if (index != -1)
  261. {
  262. url = url.Substring(index + 3);
  263. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  264. if (!string.IsNullOrWhiteSpace(host))
  265. {
  266. return host;
  267. }
  268. }
  269. return url;
  270. }
  271. private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
  272. {
  273. if (response.IsSuccessStatusCode)
  274. {
  275. return;
  276. }
  277. if (options.LogErrorResponseBody)
  278. {
  279. string msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  280. _logger.LogError("HTTP request failed with message: {Message}", msg);
  281. }
  282. throw new HttpException(response.ReasonPhrase)
  283. {
  284. StatusCode = response.StatusCode
  285. };
  286. }
  287. }
  288. }