Il monitor coordina i motori delle aste, incorpora le risposte di data.php, chiede il verdetto alla strategia, spara la puntata sul thread del cecchino e chiude le aste alimentando storico, rischio, statistiche dei prodotti e apprendimento. Il bot vive in un "mondo": il sito vero con la sessione salvata o il simulatore interno quando la sessione manca, con dati del simulatore tenuti separati (auctions.type = 'sim', modello ml-sim/). Aggiunti: archivio della sessione cifrato AES-256-GCM, verifica periodica del conto, accesso assistito via CDP scritto a mano con screencast, sorveglianza dei prodotti seguiti, notifiche e comandi Telegram, manutenzione notturna (partizioni, tetto dati, registri, backup), esportazioni CSV per la revisione, riscaldamento del motore, hub WebSocket a 10 Hz con righe a delta e le letture /api delle pagine. Test del monitor end-to-end sul simulatore. 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 BidooBidBot.Session.Cdp;
|
|
|
|
/// <summary>
|
|
/// Chromium senza finestra per l'accesso assistito (specifica §6.5). Il profilo sta in
|
|
/// <c>/config/browser</c> e resta fra un accesso e l'altro; 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: l'immagine Docker ha <c>/usr/bin/chromium</c>; in sviluppo 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("Chromium non trovato nell'immagine: usa «incolla i cookie»");
|
|
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();
|
|
}
|
|
}
|