2
0

HttpClientManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Model.IO;
  14. using MediaBrowser.Model.Net;
  15. using Microsoft.Extensions.Logging;
  16. using Microsoft.Net.Http.Headers;
  17. namespace Emby.Server.Implementations.HttpClientManager
  18. {
  19. /// <summary>
  20. /// Class HttpClientManager.
  21. /// </summary>
  22. public class HttpClientManager : IHttpClient
  23. {
  24. private readonly ILogger<HttpClientManager> _logger;
  25. private readonly IApplicationPaths _appPaths;
  26. private readonly IFileSystem _fileSystem;
  27. private readonly IApplicationHost _appHost;
  28. /// <summary>
  29. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  30. /// DON'T dispose it after use.
  31. /// </summary>
  32. /// <value>The HTTP clients.</value>
  33. private readonly ConcurrentDictionary<string, HttpClient> _httpClients = new ConcurrentDictionary<string, HttpClient>();
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  36. /// </summary>
  37. public HttpClientManager(
  38. IApplicationPaths appPaths,
  39. ILogger<HttpClientManager> logger,
  40. IFileSystem fileSystem,
  41. IApplicationHost appHost)
  42. {
  43. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  44. _fileSystem = fileSystem;
  45. _appPaths = appPaths ?? throw new ArgumentNullException(nameof(appPaths));
  46. _appHost = appHost;
  47. }
  48. /// <summary>
  49. /// Gets the correct http client for the given url.
  50. /// </summary>
  51. /// <param name="url">The url.</param>
  52. /// <returns>HttpClient.</returns>
  53. private HttpClient GetHttpClient(string url)
  54. {
  55. var key = GetHostFromUrl(url);
  56. if (!_httpClients.TryGetValue(key, out var client))
  57. {
  58. client = new HttpClient()
  59. {
  60. BaseAddress = new Uri(url)
  61. };
  62. _httpClients.TryAdd(key, client);
  63. }
  64. return client;
  65. }
  66. private HttpRequestMessage GetRequestMessage(HttpRequestOptions options, HttpMethod method)
  67. {
  68. string url = options.Url;
  69. var uriAddress = new Uri(url);
  70. string userInfo = uriAddress.UserInfo;
  71. if (!string.IsNullOrWhiteSpace(userInfo))
  72. {
  73. _logger.LogWarning("Found userInfo in url: {0} ... url: {1}", userInfo, url);
  74. url = url.Replace(userInfo + '@', string.Empty, StringComparison.Ordinal);
  75. }
  76. var request = new HttpRequestMessage(method, url);
  77. foreach (var header in options.RequestHeaders)
  78. {
  79. request.Headers.TryAddWithoutValidation(header.Key, header.Value);
  80. }
  81. if (options.EnableDefaultUserAgent
  82. && !request.Headers.TryGetValues(HeaderNames.UserAgent, out _))
  83. {
  84. request.Headers.Add(HeaderNames.UserAgent, _appHost.ApplicationUserAgent);
  85. }
  86. switch (options.DecompressionMethod)
  87. {
  88. case CompressionMethods.Deflate | CompressionMethods.Gzip:
  89. request.Headers.Add(HeaderNames.AcceptEncoding, new[] { "gzip", "deflate" });
  90. break;
  91. case CompressionMethods.Deflate:
  92. request.Headers.Add(HeaderNames.AcceptEncoding, "deflate");
  93. break;
  94. case CompressionMethods.Gzip:
  95. request.Headers.Add(HeaderNames.AcceptEncoding, "gzip");
  96. break;
  97. default:
  98. break;
  99. }
  100. if (options.EnableKeepAlive)
  101. {
  102. request.Headers.Add(HeaderNames.Connection, "Keep-Alive");
  103. }
  104. // request.Headers.Add(HeaderNames.CacheControl, "no-cache");
  105. /*
  106. if (!string.IsNullOrWhiteSpace(userInfo))
  107. {
  108. var parts = userInfo.Split(':');
  109. if (parts.Length == 2)
  110. {
  111. request.Headers.Add(HeaderNames., GetCredential(url, parts[0], parts[1]);
  112. }
  113. }
  114. */
  115. return request;
  116. }
  117. /// <summary>
  118. /// Gets the response internal.
  119. /// </summary>
  120. /// <param name="options">The options.</param>
  121. /// <returns>Task{HttpResponseInfo}.</returns>
  122. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  123. => SendAsync(options, HttpMethod.Get);
  124. /// <summary>
  125. /// Performs a GET request and returns the resulting stream.
  126. /// </summary>
  127. /// <param name="options">The options.</param>
  128. /// <returns>Task{Stream}.</returns>
  129. public async Task<Stream> Get(HttpRequestOptions options)
  130. {
  131. var response = await GetResponse(options).ConfigureAwait(false);
  132. return response.Content;
  133. }
  134. /// <summary>
  135. /// send as an asynchronous operation.
  136. /// </summary>
  137. /// <param name="options">The options.</param>
  138. /// <param name="httpMethod">The HTTP method.</param>
  139. /// <returns>Task{HttpResponseInfo}.</returns>
  140. public Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  141. => SendAsync(options, new HttpMethod(httpMethod));
  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 async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, HttpMethod httpMethod)
  149. {
  150. if (options.CacheMode == CacheMode.None)
  151. {
  152. return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  153. }
  154. var url = options.Url;
  155. var urlHash = url.ToUpperInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
  156. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  157. var response = GetCachedResponse(responseCachePath, options.CacheLength, url);
  158. if (response != null)
  159. {
  160. return response;
  161. }
  162. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  163. if (response.StatusCode == HttpStatusCode.OK)
  164. {
  165. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  166. }
  167. return response;
  168. }
  169. private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  170. {
  171. if (File.Exists(responseCachePath)
  172. && _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  173. {
  174. var stream = new FileStream(responseCachePath, FileMode.Open, FileAccess.Read, FileShare.Read, IODefaults.FileStreamBufferSize, true);
  175. return new HttpResponseInfo
  176. {
  177. ResponseUrl = url,
  178. Content = stream,
  179. StatusCode = HttpStatusCode.OK,
  180. ContentLength = stream.Length
  181. };
  182. }
  183. return null;
  184. }
  185. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  186. {
  187. Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  188. using (var fileStream = new FileStream(
  189. responseCachePath,
  190. FileMode.Create,
  191. FileAccess.Write,
  192. FileShare.None,
  193. IODefaults.FileStreamBufferSize,
  194. true))
  195. {
  196. await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
  197. response.Content.Position = 0;
  198. }
  199. }
  200. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, HttpMethod httpMethod)
  201. {
  202. ValidateParams(options);
  203. options.CancellationToken.ThrowIfCancellationRequested();
  204. var client = GetHttpClient(options.Url);
  205. var httpWebRequest = GetRequestMessage(options, httpMethod);
  206. if (!string.IsNullOrEmpty(options.RequestContent)
  207. || httpMethod == HttpMethod.Post)
  208. {
  209. if (options.RequestContent != null)
  210. {
  211. httpWebRequest.Content = new StringContent(
  212. options.RequestContent,
  213. null,
  214. options.RequestContentType);
  215. }
  216. else
  217. {
  218. httpWebRequest.Content = new ByteArrayContent(Array.Empty<byte>());
  219. }
  220. }
  221. options.CancellationToken.ThrowIfCancellationRequested();
  222. var response = await client.SendAsync(
  223. httpWebRequest,
  224. options.BufferContent || options.CacheMode == CacheMode.Unconditional ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
  225. options.CancellationToken).ConfigureAwait(false);
  226. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  227. options.CancellationToken.ThrowIfCancellationRequested();
  228. var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  229. return new HttpResponseInfo(response.Headers, response.Content.Headers)
  230. {
  231. Content = stream,
  232. StatusCode = response.StatusCode,
  233. ContentType = response.Content.Headers.ContentType?.MediaType,
  234. ContentLength = response.Content.Headers.ContentLength,
  235. ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
  236. };
  237. }
  238. /// <inheritdoc />
  239. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  240. => SendAsync(options, HttpMethod.Post);
  241. private void ValidateParams(HttpRequestOptions options)
  242. {
  243. if (string.IsNullOrEmpty(options.Url))
  244. {
  245. throw new ArgumentNullException(nameof(options));
  246. }
  247. }
  248. /// <summary>
  249. /// Gets the host from URL.
  250. /// </summary>
  251. /// <param name="url">The URL.</param>
  252. /// <returns>System.String.</returns>
  253. private static string GetHostFromUrl(string url)
  254. {
  255. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  256. if (index != -1)
  257. {
  258. url = url.Substring(index + 3);
  259. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  260. if (!string.IsNullOrWhiteSpace(host))
  261. {
  262. return host;
  263. }
  264. }
  265. return url;
  266. }
  267. private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
  268. {
  269. if (response.IsSuccessStatusCode)
  270. {
  271. return;
  272. }
  273. if (options.LogErrorResponseBody)
  274. {
  275. string msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  276. _logger.LogError("HTTP request failed with message: {Message}", msg);
  277. }
  278. throw new HttpException(response.ReasonPhrase)
  279. {
  280. StatusCode = response.StatusCode
  281. };
  282. }
  283. }
  284. }