I cookie di accesso di Bidoo (__stattrb, PHPSESSID) sono HttpOnly: nessuno script o copia della pagina li vede, quindi non esiste un modo più semplice degli strumenti per sviluppatori. Lì Chrome ha già «Copia come cURL», che porta cookie e User-Agent in un colpo. Per questo, come deciso da Alberto, il browser del bot se ne va. - Session/SessionPaste riconosce da solo cURL (bash e cmd, -b o -H cookie, -A o -H user-agent), «Copia come PowerShell», intestazioni della richiesta (anche nome e valore su righe diverse), la riga Cookie, righe della tabella dei cookie e il solo valore di __stattrb; rifiuta un testo senza il cookie di accesso. Lo User-Agent del testo vale più di quello del campo. - La pagina Browser diventa «Accesso a Bidoo» (#/accesso, #/browser ci porta): riquadro da incollare, istruzioni per Chrome, stato della sessione. - Via AssistedLogin, i comandi login.* e i messaggi login.frame/login.state; via chromium e fonts-liberation dall'immagine, e prova-immagine.sh controlla che Chromium non ci sia. All'avvio il bot cancella /config/browser, il profilo della 1.x con una copia dei cookie. - Il client CDP e l'avvio di Chromium passano in tools/Mimante.Schermate, che usa Chrome o Edge del PC. - ADR 0017 (supera la 0003; la 0010 resta per la base Debian), README, architettura, guida, docker.md, stato e CHANGELOG aggiornati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
125 lines
5.4 KiB
C#
125 lines
5.4 KiB
C#
using System.Diagnostics;
|
|
using System.Globalization;
|
|
|
|
namespace Mimante.Schermate.Cdp;
|
|
|
|
/// <summary>
|
|
/// 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
|
|
/// <c>DevToolsActivePort</c> (porta scelta dal browser: nessun conflitto).
|
|
/// </summary>
|
|
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;
|
|
|
|
/// <summary>Dove cercare il browser: su Linux il pacchetto della distribuzione, su Windows Chrome o Edge.</summary>
|
|
public static IEnumerable<string> 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<string> 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<ChromiumProcess> 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");
|
|
}
|
|
|
|
/// <summary>Riga 1 la porta, riga 2 il percorso del WebSocket del browser.</summary>
|
|
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();
|
|
}
|
|
}
|