Skip to content

Commit

Permalink
Add Puppeteer Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
C9Glax committed Dec 12, 2024
1 parent 463f360 commit 747df0b
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions Tranga/MangaConnectors/ChromiumDownloadClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using Microsoft.Extensions.Logging;
using PuppeteerSharp;

namespace Tranga.MangaConnectors;

internal class ChromiumDownloadClient : DownloadClient
{
private static readonly IBrowser Browser = StartBrowser().Result;
private static IBrowser? _browser;
private const int StartTimeoutMs = 10000;
private readonly HttpDownloadClient _httpDownloadClient;

private static async Task<IBrowser> StartBrowser()
private static async Task<IBrowser> StartBrowser(Logging.Logger? logger = null)
{
logger?.WriteLine("Starting ChromiumDownloadClient Puppeteer");
return await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true,
Expand All @@ -23,12 +25,37 @@ private static async Task<IBrowser> StartBrowser()
"--disable-setuid-sandbox",
"--no-sandbox"},
Timeout = StartTimeoutMs
});
}, new LoggerFactory([new LogProvider(logger)]));
}

private class LogProvider : GlobalBase, ILoggerProvider
{
public LogProvider(Logging.Logger? logger) : base(logger) { }

public void Dispose() { }

public ILogger CreateLogger(string categoryName) => new Logger(logger);
}

private class Logger : GlobalBase, ILogger
{
public Logger(Logging.Logger? logger) : base(logger) { }

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
logger?.WriteLine("Puppeteer", formatter.Invoke(state, exception));
}

public bool IsEnabled(LogLevel logLevel) => true;

public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
}

public ChromiumDownloadClient(GlobalBase clone) : base(clone)
{
_httpDownloadClient = new(this);
if(_browser is null)
_browser = StartBrowser(this.logger).Result;
}

private readonly Regex _imageUrlRex = new(@"https?:\/\/.*\.(?:p?jpe?g|gif|a?png|bmp|avif|webp)(\?.*)?");
Expand All @@ -41,7 +68,7 @@ internal override RequestResult MakeRequestInternal(string url, string? referrer

private RequestResult MakeRequestBrowser(string url, string? referrer = null, string? clickButton = null)
{
IPage page = Browser.NewPageAsync().Result;
IPage page = _browser.NewPageAsync().Result;
page.DefaultTimeout = 10000;
IResponse response;
try
Expand Down

0 comments on commit 747df0b

Please sign in to comment.