2019-01-06 13:50:43 -07:00
|
|
|
using System;
|
2016-10-28 22:40:15 -07:00
|
|
|
using System.Collections.Concurrent;
|
2019-07-02 12:47:36 -07:00
|
|
|
using System.Globalization;
|
2016-10-28 22:40:15 -07:00
|
|
|
using System.IO;
|
|
|
|
using System.Linq;
|
|
|
|
using System.Net;
|
2019-03-08 12:17:17 -07:00
|
|
|
using System.Net.Http;
|
2016-10-28 22:40:15 -07:00
|
|
|
using System.Threading.Tasks;
|
2017-08-15 23:43:41 -07:00
|
|
|
using MediaBrowser.Common.Configuration;
|
|
|
|
using MediaBrowser.Common.Extensions;
|
|
|
|
using MediaBrowser.Common.Net;
|
2016-10-28 22:40:15 -07:00
|
|
|
using MediaBrowser.Model.IO;
|
2017-08-15 23:43:41 -07:00
|
|
|
using MediaBrowser.Model.Net;
|
2019-01-13 12:20:41 -07:00
|
|
|
using Microsoft.Extensions.Logging;
|
2019-03-05 11:20:28 -07:00
|
|
|
using Microsoft.Net.Http.Headers;
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2017-08-15 23:43:41 -07:00
|
|
|
namespace Emby.Server.Implementations.HttpClientManager
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
|
|
|
/// <summary>
|
2019-07-29 14:47:25 -07:00
|
|
|
/// Class HttpClientManager.
|
2016-10-28 22:40:15 -07:00
|
|
|
/// </summary>
|
|
|
|
public class HttpClientManager : IHttpClient
|
|
|
|
{
|
|
|
|
private readonly ILogger _logger;
|
|
|
|
private readonly IApplicationPaths _appPaths;
|
|
|
|
private readonly IFileSystem _fileSystem;
|
2017-02-08 20:58:04 -07:00
|
|
|
private readonly Func<string> _defaultUserAgentFn;
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-07-01 10:24:42 -07:00
|
|
|
/// <summary>
|
|
|
|
/// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
|
|
|
|
/// DON'T dispose it after use.
|
|
|
|
/// </summary>
|
|
|
|
/// <value>The HTTP clients.</value>
|
|
|
|
private readonly ConcurrentDictionary<string, HttpClient> _httpClients = new ConcurrentDictionary<string, HttpClient>();
|
|
|
|
|
2016-10-28 22:40:15 -07:00
|
|
|
/// <summary>
|
|
|
|
/// Initializes a new instance of the <see cref="HttpClientManager" /> class.
|
|
|
|
/// </summary>
|
2019-01-17 15:55:05 -07:00
|
|
|
public HttpClientManager(
|
|
|
|
IApplicationPaths appPaths,
|
2019-06-14 07:32:37 -07:00
|
|
|
ILogger<HttpClientManager> logger,
|
2019-01-17 15:55:05 -07:00
|
|
|
IFileSystem fileSystem,
|
|
|
|
Func<string> defaultUserAgentFn)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
2019-07-29 14:47:25 -07:00
|
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
2016-10-28 22:40:15 -07:00
|
|
|
_fileSystem = fileSystem;
|
2019-07-29 14:47:25 -07:00
|
|
|
_appPaths = appPaths ?? throw new ArgumentNullException(nameof(appPaths));
|
2017-02-08 20:58:04 -07:00
|
|
|
_defaultUserAgentFn = defaultUserAgentFn;
|
2016-10-28 22:40:15 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2019-07-01 10:24:42 -07:00
|
|
|
/// Gets the correct http client for the given url.
|
2016-10-28 22:40:15 -07:00
|
|
|
/// </summary>
|
2019-07-01 10:24:42 -07:00
|
|
|
/// <param name="url">The url.</param>
|
2016-10-28 22:40:15 -07:00
|
|
|
/// <returns>HttpClient.</returns>
|
2019-06-14 07:32:37 -07:00
|
|
|
private HttpClient GetHttpClient(string url)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
2019-06-14 07:32:37 -07:00
|
|
|
var key = GetHostFromUrl(url);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-01-13 13:46:33 -07:00
|
|
|
if (!_httpClients.TryGetValue(key, out var client))
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
2019-03-08 12:17:17 -07:00
|
|
|
client = new HttpClient()
|
|
|
|
{
|
|
|
|
BaseAddress = new Uri(url)
|
|
|
|
};
|
2016-10-28 22:40:15 -07:00
|
|
|
|
|
|
|
_httpClients.TryAdd(key, client);
|
|
|
|
}
|
|
|
|
|
|
|
|
return client;
|
|
|
|
}
|
|
|
|
|
2019-03-08 12:17:17 -07:00
|
|
|
private HttpRequestMessage GetRequestMessage(HttpRequestOptions options, HttpMethod method)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
2018-12-30 05:01:52 -07:00
|
|
|
string url = options.Url;
|
2019-01-13 13:37:13 -07:00
|
|
|
var uriAddress = new Uri(url);
|
2018-12-30 05:01:52 -07:00
|
|
|
string userInfo = uriAddress.UserInfo;
|
2016-10-28 22:40:15 -07:00
|
|
|
if (!string.IsNullOrWhiteSpace(userInfo))
|
|
|
|
{
|
2019-03-08 12:17:17 -07:00
|
|
|
_logger.LogWarning("Found userInfo in url: {0} ... url: {1}", userInfo, url);
|
2019-06-14 07:32:37 -07:00
|
|
|
url = url.Replace(userInfo + '@', string.Empty);
|
2016-10-28 22:40:15 -07:00
|
|
|
}
|
|
|
|
|
2019-03-08 12:17:17 -07:00
|
|
|
var request = new HttpRequestMessage(method, url);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-09-08 12:07:29 -07:00
|
|
|
foreach (var header in options.RequestHeaders)
|
|
|
|
{
|
|
|
|
request.Headers.TryAddWithoutValidation(header.Key, header.Value);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (options.EnableDefaultUserAgent
|
|
|
|
&& !request.Headers.TryGetValues(HeaderNames.UserAgent, out _))
|
|
|
|
{
|
|
|
|
request.Headers.Add(HeaderNames.UserAgent, _defaultUserAgentFn());
|
|
|
|
}
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-06-14 07:32:37 -07:00
|
|
|
switch (options.DecompressionMethod)
|
2019-03-08 12:17:17 -07:00
|
|
|
{
|
2019-06-14 07:32:37 -07:00
|
|
|
case CompressionMethod.Deflate | CompressionMethod.Gzip:
|
2019-03-08 12:17:17 -07:00
|
|
|
request.Headers.Add(HeaderNames.AcceptEncoding, new[] { "gzip", "deflate" });
|
2019-06-14 07:32:37 -07:00
|
|
|
break;
|
|
|
|
case CompressionMethod.Deflate:
|
2019-03-08 12:17:17 -07:00
|
|
|
request.Headers.Add(HeaderNames.AcceptEncoding, "deflate");
|
2019-06-14 07:32:37 -07:00
|
|
|
break;
|
|
|
|
case CompressionMethod.Gzip:
|
|
|
|
request.Headers.Add(HeaderNames.AcceptEncoding, "gzip");
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
break;
|
2019-03-08 12:17:17 -07:00
|
|
|
}
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-03-08 12:17:17 -07:00
|
|
|
if (options.EnableKeepAlive)
|
|
|
|
{
|
|
|
|
request.Headers.Add(HeaderNames.Connection, "Keep-Alive");
|
|
|
|
}
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-07-29 14:47:25 -07:00
|
|
|
// request.Headers.Add(HeaderNames.CacheControl, "no-cache");
|
2018-12-25 17:16:02 -07:00
|
|
|
|
2019-03-08 12:17:17 -07:00
|
|
|
/*
|
2016-10-28 22:40:15 -07:00
|
|
|
if (!string.IsNullOrWhiteSpace(userInfo))
|
|
|
|
{
|
|
|
|
var parts = userInfo.Split(':');
|
|
|
|
if (parts.Length == 2)
|
|
|
|
{
|
2019-03-08 12:17:17 -07:00
|
|
|
request.Headers.Add(HeaderNames., GetCredential(url, parts[0], parts[1]);
|
2016-10-28 22:40:15 -07:00
|
|
|
}
|
|
|
|
}
|
2019-03-08 12:17:17 -07:00
|
|
|
*/
|
2016-10-28 22:40:15 -07:00
|
|
|
|
|
|
|
return request;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Gets the response internal.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="options">The options.</param>
|
|
|
|
/// <returns>Task{HttpResponseInfo}.</returns>
|
|
|
|
public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
|
2019-06-14 07:32:37 -07:00
|
|
|
=> SendAsync(options, HttpMethod.Get);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Performs a GET request and returns the resulting stream
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="options">The options.</param>
|
|
|
|
/// <returns>Task{Stream}.</returns>
|
|
|
|
public async Task<Stream> Get(HttpRequestOptions options)
|
|
|
|
{
|
|
|
|
var response = await GetResponse(options).ConfigureAwait(false);
|
|
|
|
return response.Content;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// send as an asynchronous operation.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="options">The options.</param>
|
|
|
|
/// <param name="httpMethod">The HTTP method.</param>
|
|
|
|
/// <returns>Task{HttpResponseInfo}.</returns>
|
2019-03-08 12:17:17 -07:00
|
|
|
public Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
|
2019-07-07 09:26:01 -07:00
|
|
|
=> SendAsync(options, new HttpMethod(httpMethod));
|
2019-03-08 12:17:17 -07:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// send as an asynchronous operation.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="options">The options.</param>
|
|
|
|
/// <param name="httpMethod">The HTTP method.</param>
|
|
|
|
/// <returns>Task{HttpResponseInfo}.</returns>
|
|
|
|
public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, HttpMethod httpMethod)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
|
|
|
if (options.CacheMode == CacheMode.None)
|
|
|
|
{
|
|
|
|
return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
var url = options.Url;
|
2019-07-29 14:47:25 -07:00
|
|
|
var urlHash = url.ToUpperInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
|
|
|
var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
|
|
|
|
|
2019-01-18 12:40:08 -07:00
|
|
|
var response = GetCachedResponse(responseCachePath, options.CacheLength, url);
|
2016-10-28 22:40:15 -07:00
|
|
|
if (response != null)
|
|
|
|
{
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
|
|
|
response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
|
|
|
|
|
|
|
|
if (response.StatusCode == HttpStatusCode.OK)
|
|
|
|
{
|
|
|
|
await CacheResponse(response, responseCachePath).ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
2019-01-18 12:40:08 -07:00
|
|
|
private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
2019-01-27 09:00:17 -07:00
|
|
|
if (File.Exists(responseCachePath)
|
|
|
|
&& _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
2019-01-27 09:00:17 -07:00
|
|
|
var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-01-27 09:00:17 -07:00
|
|
|
return new HttpResponseInfo
|
|
|
|
{
|
|
|
|
ResponseUrl = url,
|
|
|
|
Content = stream,
|
|
|
|
StatusCode = HttpStatusCode.OK,
|
|
|
|
ContentLength = stream.Length
|
|
|
|
};
|
2016-10-28 22:40:15 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
|
|
|
|
{
|
2019-01-26 14:08:04 -07:00
|
|
|
Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-07-29 14:47:25 -07:00
|
|
|
using (var fileStream = new FileStream(
|
|
|
|
responseCachePath,
|
|
|
|
FileMode.Create,
|
|
|
|
FileAccess.Write,
|
|
|
|
FileShare.None,
|
|
|
|
StreamDefaults.DefaultFileStreamBufferSize,
|
|
|
|
true))
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
2019-01-18 12:40:08 -07:00
|
|
|
await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-01-18 12:40:08 -07:00
|
|
|
response.Content.Position = 0;
|
2016-10-28 22:40:15 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-08 12:17:17 -07:00
|
|
|
private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, HttpMethod httpMethod)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
|
|
|
ValidateParams(options);
|
|
|
|
|
|
|
|
options.CancellationToken.ThrowIfCancellationRequested();
|
|
|
|
|
2019-06-14 07:32:37 -07:00
|
|
|
var client = GetHttpClient(options.Url);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-03-08 12:17:17 -07:00
|
|
|
var httpWebRequest = GetRequestMessage(options, httpMethod);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-06-14 07:32:37 -07:00
|
|
|
if (options.RequestContentBytes != null
|
|
|
|
|| !string.IsNullOrEmpty(options.RequestContent)
|
|
|
|
|| httpMethod == HttpMethod.Post)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
2019-06-14 08:31:56 -07:00
|
|
|
if (options.RequestContentBytes != null)
|
|
|
|
{
|
|
|
|
httpWebRequest.Content = new ByteArrayContent(options.RequestContentBytes);
|
|
|
|
}
|
|
|
|
else if (options.RequestContent != null)
|
|
|
|
{
|
2019-07-07 09:04:06 -07:00
|
|
|
httpWebRequest.Content = new StringContent(
|
|
|
|
options.RequestContent,
|
|
|
|
null,
|
|
|
|
options.RequestContentType);
|
2017-02-09 16:25:10 -07:00
|
|
|
}
|
2019-06-14 08:31:56 -07:00
|
|
|
else
|
|
|
|
{
|
|
|
|
httpWebRequest.Content = new ByteArrayContent(Array.Empty<byte>());
|
|
|
|
}
|
2016-10-28 22:40:15 -07:00
|
|
|
}
|
|
|
|
|
2019-06-14 08:31:56 -07:00
|
|
|
options.CancellationToken.ThrowIfCancellationRequested();
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-07-24 14:46:58 -07:00
|
|
|
var response = await client.SendAsync(
|
|
|
|
httpWebRequest,
|
2019-07-29 14:47:25 -07:00
|
|
|
options.BufferContent || options.CacheMode == CacheMode.Unconditional ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
|
2019-07-24 14:46:58 -07:00
|
|
|
options.CancellationToken).ConfigureAwait(false);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-07-24 14:46:58 -07:00
|
|
|
await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-07-24 14:46:58 -07:00
|
|
|
options.CancellationToken.ThrowIfCancellationRequested();
|
2016-10-28 22:40:15 -07:00
|
|
|
|
2019-07-24 14:46:58 -07:00
|
|
|
var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
|
|
|
|
return new HttpResponseInfo(response.Headers, response.Content.Headers)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
2019-07-24 14:46:58 -07:00
|
|
|
Content = stream,
|
|
|
|
StatusCode = response.StatusCode,
|
|
|
|
ContentType = response.Content.Headers.ContentType?.MediaType,
|
|
|
|
ContentLength = response.Content.Headers.ContentLength,
|
|
|
|
ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
|
|
|
|
};
|
2016-10-28 22:40:15 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
public Task<HttpResponseInfo> Post(HttpRequestOptions options)
|
2019-06-14 07:32:37 -07:00
|
|
|
=> SendAsync(options, HttpMethod.Post);
|
2016-10-28 22:40:15 -07:00
|
|
|
|
|
|
|
private void ValidateParams(HttpRequestOptions options)
|
|
|
|
{
|
|
|
|
if (string.IsNullOrEmpty(options.Url))
|
|
|
|
{
|
2019-01-06 13:50:43 -07:00
|
|
|
throw new ArgumentNullException(nameof(options));
|
2016-10-28 22:40:15 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Gets the host from URL.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="url">The URL.</param>
|
|
|
|
/// <returns>System.String.</returns>
|
2019-01-06 13:50:43 -07:00
|
|
|
private static string GetHostFromUrl(string url)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
|
|
|
var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
|
|
|
|
|
|
|
|
if (index != -1)
|
|
|
|
{
|
|
|
|
url = url.Substring(index + 3);
|
|
|
|
var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
|
|
|
|
|
|
|
|
if (!string.IsNullOrWhiteSpace(host))
|
|
|
|
{
|
|
|
|
return host;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return url;
|
|
|
|
}
|
|
|
|
|
2019-03-08 12:17:17 -07:00
|
|
|
private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
|
2016-10-28 22:40:15 -07:00
|
|
|
{
|
2019-03-08 12:17:17 -07:00
|
|
|
if (response.IsSuccessStatusCode)
|
2018-12-25 17:16:02 -07:00
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-07-29 14:47:25 -07:00
|
|
|
if (options.LogErrorResponseBody)
|
|
|
|
{
|
|
|
|
var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
|
|
|
_logger.LogError("HTTP request failed with message: {Message}", msg);
|
|
|
|
}
|
2018-12-25 17:16:02 -07:00
|
|
|
|
2019-03-08 12:17:17 -07:00
|
|
|
throw new HttpException(response.ReasonPhrase)
|
2018-12-25 17:16:02 -07:00
|
|
|
{
|
|
|
|
StatusCode = response.StatusCode
|
|
|
|
};
|
2016-10-28 22:40:15 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|