using System.Diagnostics;
using System.Globalization;
namespace Mimante.Schermate.Cdp;
///
/// Chromium senza finestra per le schermate. Il bot non ha più un browser (ADR 0017): Chrome, Edge o
/// Chromium sono quelli del PC o del lavoro della CI. L'indirizzo del protocollo si legge da
/// DevToolsActivePort (porta scelta dal browser: nessun conflitto).
///
public sealed class ChromiumProcess : IAsyncDisposable
{
private readonly Process _process;
public Uri Endpoint { get; }
private ChromiumProcess(Process process, Uri endpoint)
{
_process = process;
Endpoint = endpoint;
}
public bool HasExited => _process.HasExited;
/// Dove cercare il browser: su Linux il pacchetto della distribuzione, su Windows Chrome o Edge.
public static IEnumerable Candidates()
{
yield return "/usr/bin/chromium";
yield return "/usr/bin/chromium-browser";
yield return "/usr/bin/google-chrome";
yield return "/usr/bin/google-chrome-stable";
if (OperatingSystem.IsWindows())
{
foreach (var root in new[] { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) })
{
if (string.IsNullOrEmpty(root)) continue;
yield return Path.Combine(root, "Google", "Chrome", "Application", "chrome.exe");
yield return Path.Combine(root, "Chromium", "Application", "chrome.exe");
yield return Path.Combine(root, "Microsoft", "Edge", "Application", "msedge.exe");
}
}
if (OperatingSystem.IsMacOS()) yield return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
}
public static string? FindExecutable() => Candidates().FirstOrDefault(File.Exists);
public static IReadOnlyList Arguments(string profileDir) => new[]
{
"--headless=new", "--remote-debugging-port=0", $"--user-data-dir={profileDir}", "--no-sandbox", "--disable-gpu",
"--window-size=1280,900", "--lang=it-IT", "--no-first-run", "--no-default-browser-check", "--disable-dev-shm-usage",
"--disable-background-networking", "--disable-sync", "--mute-audio", "about:blank"
};
public static async Task StartAsync(string profileDir, CancellationToken ct)
{
var exe = FindExecutable() ?? throw new InvalidOperationException("Chrome, Edge o Chromium non trovato su questo computer");
Directory.CreateDirectory(profileDir);
var portFile = Path.Combine(profileDir, "DevToolsActivePort");
try { if (File.Exists(portFile)) File.Delete(portFile); } catch (IOException) { }
// Un blocco lasciato da un Chromium ucciso impedisce di riaprire il profilo.
foreach (var lockName in new[] { "SingletonLock", "SingletonSocket", "SingletonCookie" })
{
try { var p = Path.Combine(profileDir, lockName); if (File.Exists(p) || Directory.Exists(p)) File.Delete(p); } catch { }
}
var psi = new ProcessStartInfo(exe)
{
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true
};
foreach (var a in Arguments(profileDir)) psi.ArgumentList.Add(a);
var process = Process.Start(psi) ?? throw new InvalidOperationException("Chromium non si è avviato");
process.ErrorDataReceived += (_, _) => { };
process.OutputDataReceived += (_, _) => { };
process.BeginErrorReadLine();
process.BeginOutputReadLine();
var deadline = DateTime.UtcNow.AddSeconds(20);
while (DateTime.UtcNow < deadline)
{
ct.ThrowIfCancellationRequested();
if (process.HasExited) throw new InvalidOperationException($"Chromium si è chiuso subito (codice {process.ExitCode})");
if (TryReadPort(portFile) is { } endpoint) return new ChromiumProcess(process, endpoint);
await Task.Delay(100, ct).ConfigureAwait(false);
}
try { process.Kill(entireProcessTree: true); } catch { }
throw new InvalidOperationException("Chromium non ha aperto il protocollo di controllo in 20 secondi");
}
/// Riga 1 la porta, riga 2 il percorso del WebSocket del browser.
internal static Uri? TryReadPort(string file)
{
try
{
if (!File.Exists(file)) return null;
var lines = File.ReadAllLines(file);
if (lines.Length < 2 || !int.TryParse(lines[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var port) || port <= 0) return null;
return new Uri($"ws://127.0.0.1:{port}{lines[1].Trim()}");
}
catch (IOException)
{
return null;
}
}
public async ValueTask DisposeAsync()
{
try
{
if (!_process.HasExited)
{
await _process.WaitForExitAsync(new CancellationTokenSource(TimeSpan.FromSeconds(3)).Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { }
try { if (!_process.HasExited) _process.Kill(entireProcessTree: true); } catch { }
_process.Dispose();
}
}