Jackett/src/Jackett.Common/Utils/Clients/WebClient.cs

170 lines
6.8 KiB
C#
Raw Normal View History

using AutoMapper;
using Jackett.Models;
using Jackett.Services;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
Feature/netcore preparation (#2035) * Move to use package reference for restoring nuget packages. * Return a task result for this async method. * Update to a supported version of the .NET Framework. This also has the side effect of allowing us to automatically generate our binding redirects on build. * Set the solution to target VS2017 * Update test solution csproj file to support being built through MSBuild 15 * Move to use package reference for restoring nuget packages. * Return a task result for this async method. * Update to a supported version of the .NET Framework. This also has the side effect of allowing us to automatically generate our binding redirects on build. * Set the solution to target VS2017 * Update test solution csproj file to support being built through MSBuild 15 * DateTimeRoutines does not have Nuget packages that support .NET Standard (and therefore .NET Core). We will have to include them for now until we can get rid of this dependency. * Move the interfaces into their own files. This will be useful when we share them between the .NET Core and .NET Framework WebAPI * Stage services that need to point to the new interface namespace. * Update CurlSharp to fix memory leak issue and support better runtime compatibility with OSX and Linux * Start spliting some interfaces into their own files - this will help by allowing us to split them out in the future into a seperate project so the actual implementations can stay within their respective architectures when required
2017-10-29 10:19:09 +00:00
using Jackett.Services.Interfaces;
using Jackett.Models.Config;
namespace Jackett.Utils.Clients
{
public abstract class WebClient
{
protected Logger logger;
protected IConfigurationService configService;
protected readonly ServerConfig serverConfig;
protected IProcessService processService;
2017-03-09 14:04:05 +00:00
protected DateTime lastRequest = DateTime.MinValue;
protected TimeSpan requestDelayTimeSpan;
2017-11-15 18:00:27 +00:00
protected string ClientType;
2017-08-11 14:52:58 +00:00
public bool EmulateBrowser = true;
public double requestDelay
{
get { return requestDelayTimeSpan.TotalSeconds; }
set
{
requestDelayTimeSpan = TimeSpan.FromSeconds(value);
}
2017-03-09 14:04:05 +00:00
}
virtual public void AddTrustedCertificate(string host, string hash)
{
// not implemented by default
}
public WebClient(IProcessService p, Logger l, IConfigurationService c, ServerConfig sc)
{
processService = p;
logger = l;
configService = c;
serverConfig = sc;
2017-11-15 18:00:27 +00:00
ClientType = GetType().Name;
}
2017-10-03 13:32:34 +00:00
async protected Task DelayRequest(WebRequest request)
{
2017-08-11 14:52:58 +00:00
if (request.EmulateBrowser == null)
request.EmulateBrowser = EmulateBrowser;
if (requestDelay != 0)
{
var timeElapsed = DateTime.Now - lastRequest;
if (timeElapsed < requestDelayTimeSpan)
{
var delay = requestDelayTimeSpan - timeElapsed;
2017-11-15 18:00:27 +00:00
logger.Debug(string.Format("WebClient({0}): delaying request for {1} by {2} seconds", ClientType, request.Url, delay.TotalSeconds.ToString()));
await Task.Delay(delay);
}
lastRequest = DateTime.Now;
}
2017-03-09 14:04:05 +00:00
}
virtual protected void PrepareRequest(WebRequest request)
{
// add Accept/Accept-Language header if not set
// some webservers won't accept requests without accept
// e.g. elittracker requieres the Accept-Language header
if (request.Headers == null)
request.Headers = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
var hasAccept = false;
var hasAcceptLanguage = false;
foreach (var header in request.Headers)
{
var key = header.Key.ToLower();
if (key == "accept")
{
hasAccept = true;
}
else if (key == "accept-language")
{
hasAcceptLanguage = true;
}
}
if (!hasAccept)
request.Headers.Add("Accept", "*/*");
if (!hasAcceptLanguage)
request.Headers.Add("Accept-Language", "*");
return;
2017-02-07 16:06:17 +00:00
}
virtual public async Task<WebClientByteResult> GetBytes(WebRequest request)
{
2017-11-15 18:00:27 +00:00
logger.Debug(string.Format("WebClient({0}).GetBytes(Url:{1})", ClientType, request.Url));
PrepareRequest(request);
2017-10-03 13:32:34 +00:00
await DelayRequest(request);
var result = await Run(request);
result.Request = request;
2017-11-15 18:00:27 +00:00
logger.Debug(string.Format("WebClient({0}): Returning {1} => {2} bytes", ClientType, result.Status, (result.IsRedirect ? result.RedirectingTo + " " : "") + (result.Content == null ? "<NULL>" : result.Content.Length.ToString())));
return result;
}
virtual public async Task<WebClientStringResult> GetString(WebRequest request)
{
2017-11-15 18:00:27 +00:00
logger.Debug(string.Format("WebClient({0}).GetString(Url:{1})", ClientType, request.Url));
PrepareRequest(request);
2017-10-03 13:32:34 +00:00
await DelayRequest(request);
var result = await Run(request);
result.Request = request;
WebClientStringResult stringResult = Mapper.Map<WebClientStringResult>(result);
Encoding encoding = null;
if (request.Encoding != null)
{
encoding = request.Encoding;
}
else if (result.Headers.ContainsKey("content-type"))
{
Regex CharsetRegex = new Regex(@"charset=([\w-]+)", RegexOptions.Compiled);
var CharsetRegexMatch = CharsetRegex.Match(result.Headers["content-type"][0]);
if (CharsetRegexMatch.Success)
{
var charset = CharsetRegexMatch.Groups[1].Value;
try
{
encoding = Encoding.GetEncoding(charset);
}
catch (Exception ex)
{
2017-11-15 18:00:27 +00:00
logger.Error(string.Format("WebClient({0}).GetString(Url:{1}): Error loading encoding {2} based on header {3}: {4}", ClientType, request.Url, charset, result.Headers["content-type"][0], ex));
}
}
else
{
2017-11-15 18:00:27 +00:00
logger.Error(string.Format("WebClient({0}).GetString(Url:{1}): Got header without charset: {2}", ClientType, request.Url, result.Headers["content-type"][0]));
}
}
if (encoding == null)
{
2017-11-15 18:00:27 +00:00
logger.Error(string.Format("WebClient({0}).GetString(Url:{1}): No encoding detected, defaulting to UTF-8", ClientType, request.Url));
encoding = Encoding.UTF8;
}
string decodedContent = null;
if (result.Content != null)
decodedContent = encoding.GetString(result.Content);
stringResult.Content = decodedContent;
2017-11-15 18:00:27 +00:00
logger.Debug(string.Format("WebClient({0}): Returning {1} => {2}", ClientType, result.Status, (result.IsRedirect ? result.RedirectingTo + " " : "") + (decodedContent == null ? "<NULL>" : decodedContent)));
string[] server;
if (stringResult.Headers.TryGetValue("server", out server))
{
if (server[0] == "cloudflare-nginx")
stringResult.Content = BrowserUtil.DecodeCloudFlareProtectedEmailFromHTML(stringResult.Content);
}
return stringResult;
}
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
virtual protected async Task<WebClientByteResult> Run(WebRequest webRequest) { throw new NotImplementedException(); }
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
abstract public void Init();
}
}