using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Common.Net
{
///
/// User agent delegating handler.
/// Adds User-Agent header to all requests.
///
public class UserAgentDelegatingHandler : DelegatingHandler
{
private readonly ProductInfoHeaderValue[] _userAgentValues;
///
/// Initializes a new instance of the class.
///
/// Instance of the interface.
public UserAgentDelegatingHandler(IApplicationHost applicationHost)
{
_userAgentValues = new[]
{
new ProductInfoHeaderValue(applicationHost.Name.Replace(' ', '-'), applicationHost.ApplicationVersionString),
new ProductInfoHeaderValue($"({Environment.OSVersion}; {applicationHost.ApplicationUserAgentAddress})")
};
}
///
/// Send request message.
///
/// The request message.
/// The cancellation token.
/// A containing the .
protected override Task SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request.Headers.UserAgent.Count == 0)
{
for (var i = 0; i < _userAgentValues.Length; i++)
{
request.Headers.UserAgent.Add(_userAgentValues[i]);
}
}
return base.SendAsync(request, cancellationToken);
}
}
}