Tranga/Tranga/MangaConnectors/DownloadClient.cs

45 lines
1.7 KiB
C#
Raw Normal View History

2023-07-30 17:04:43 +02:00
using System.Net;
using HtmlAgilityPack;
2023-07-30 17:04:43 +02:00
2023-08-01 18:22:24 +02:00
namespace Tranga.MangaConnectors;
2023-07-30 17:04:43 +02:00
internal abstract class DownloadClient : GlobalBase
{
private readonly Dictionary<RequestType, DateTime> _lastExecutedRateLimit;
2023-07-30 17:04:43 +02:00
protected DownloadClient(GlobalBase clone) : base(clone)
{
this._lastExecutedRateLimit = new();
2024-01-31 18:30:44 +01:00
}
public RequestResult MakeRequest(string url, RequestType requestType, string? referrer = null, string? clickButton = null)
{
if (!settings.requestLimits.ContainsKey(requestType))
2023-07-30 17:04:43 +02:00
{
Log("RequestType not configured for rate-limit.");
return new RequestResult(HttpStatusCode.NotAcceptable, null, Stream.Null);
2023-07-30 17:04:43 +02:00
}
int rateLimit = settings.userAgent == TrangaSettings.DefaultUserAgent
? TrangaSettings.DefaultRequestLimits[requestType]
: settings.requestLimits[requestType];
TimeSpan timeBetweenRequests = TimeSpan.FromMinutes(1).Divide(rateLimit);
_lastExecutedRateLimit.TryAdd(requestType, DateTime.Now.Subtract(timeBetweenRequests));
TimeSpan rateLimitTimeout = timeBetweenRequests.Subtract(DateTime.Now.Subtract(_lastExecutedRateLimit[requestType]));
2023-07-30 17:04:43 +02:00
if (rateLimitTimeout > TimeSpan.Zero)
{
Log($"Waiting {rateLimitTimeout.TotalSeconds} seconds");
Thread.Sleep(rateLimitTimeout);
}
2023-07-30 17:04:43 +02:00
RequestResult result = MakeRequestInternal(url, referrer, clickButton);
_lastExecutedRateLimit[requestType] = DateTime.Now;
return result;
}
2023-07-30 17:04:43 +02:00
protected abstract RequestResult MakeRequestInternal(string url, string? referrer = null, string? clickButton = null);
public abstract void Close();
}