Files
Mimante/tools/Mimante.Schermate/Program.cs
T
Alby96andClaude Opus 5.5 ef30e5563e Tre proposte grafiche da scegliere (#28)
Prima di toccare l'interfaccia, Alberto sceglie da immagini: Aste, Impostazioni
e Puntate gratis nello stile di Febe, di Khaemhat e di Anubis, in chiaro e in
scuro, con lo stesso contenuto (docs/mockup/redesign). Mimante.Schermate ha la
modalità --mockup che le fotografa e compone il foglio di confronto. I caratteri
(Archivo, Instrument Sans) sono copiati in locale con le loro licenze OFL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:57:46 +01:00

210 lines
10 KiB
C#

using System.Text.Json;
using Mimante.Session.Cdp;
// Uso: dotnet run --project tools/Mimante.Schermate -- <indirizzo> <password dell'interfaccia> <cartella>
// Esempio: dotnet run --project tools/Mimante.Schermate -- http://localhost:8080 dev docs/schermate
// Il bot deve girare sul simulatore (--simulatore) per avere aste da fotografare.
// Esce con 1 se una pagina ha errori JavaScript.
//
// Proposte grafiche: dotnet run --project tools/Mimante.Schermate -- --mockup [cartella]
// (predefinita docs/mockup/redesign): fotografa ogni <variante>/<pagina>.html in chiaro e in scuro
// in <cartella>/immagini, poi il foglio di confronto (confronto.html) se c'è.
var mockup = args.Length >= 1 && args[0] == "--mockup";
if (!mockup && args.Length < 3)
{
Console.Error.WriteLine("Uso: Mimante.Schermate <indirizzo> <password> <cartella> | --mockup [cartella]");
return 2;
}
var baseUrl = mockup ? "" : args[0].TrimEnd('/');
var password = mockup ? "" : args[1];
// Un percorso relativo vale dalla radice del repository: `dotnet run` parte nella cartella del progetto.
var dirArg = mockup ? (args.Length > 1 ? args[1] : "docs/mockup/redesign") : args[2];
var outDir = Path.IsPathRooted(dirArg) ? dirArg : Path.GetFullPath(Path.Combine(RepoRoot(), dirArg));
Directory.CreateDirectory(outDir);
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
var ct = cts.Token;
var profile = Path.Combine(Path.GetTempPath(), $"mimante-schermate-{Environment.ProcessId}");
await using var chromium = await ChromiumProcess.StartAsync(profile, ct);
await using var cdp = await CdpClient.ConnectAsync(chromium.Endpoint, ct);
var errors = new List<string>();
var loaded = new SemaphoreSlim(0);
string? session = null;
cdp.Event += (method, p, s) =>
{
if (s != session) return;
switch (method)
{
case "Page.loadEventFired":
loaded.Release();
break;
case "Runtime.exceptionThrown":
var d = p.GetProperty("exceptionDetails");
errors.Add("eccezione: " + (d.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var desc) ? desc.GetString() : d.GetProperty("text").GetString()));
break;
case "Runtime.consoleAPICalled" when p.GetProperty("type").GetString() == "error":
errors.Add("console: " + string.Join(" ", p.GetProperty("args").EnumerateArray().Select(a => a.TryGetProperty("value", out var v) ? v.ToString() : a.TryGetProperty("description", out var dd) ? dd.GetString() : "?")));
break;
case "Log.entryAdded":
var e = p.GetProperty("entry");
var text = e.GetProperty("text").GetString() ?? "";
if (e.GetProperty("level").GetString() == "error" && !text.Contains("favicon", StringComparison.OrdinalIgnoreCase))
errors.Add("browser: " + text + (e.TryGetProperty("url", out var u) ? " " + u.GetString() : ""));
break;
}
};
var target = await cdp.SendAsync("Target.createTarget", new { url = "about:blank" }, ct: ct);
var attached = await cdp.SendAsync("Target.attachToTarget", new { targetId = target.GetProperty("targetId").GetString(), flatten = true }, ct: ct);
session = attached.GetProperty("sessionId").GetString();
foreach (var domain in new[] { "Page.enable", "Runtime.enable", "Log.enable" }) await cdp.SendAsync(domain, sessionId: session, ct: ct);
async Task Viewport(int w, int h) =>
await cdp.SendAsync("Emulation.setDeviceMetricsOverride", new { width = w, height = h, deviceScaleFactor = 1, mobile = false }, session, ct);
async Task Navigate(string url)
{
while (loaded.CurrentCount > 0) await loaded.WaitAsync(ct);
await cdp.SendAsync("Page.navigate", new { url }, session, ct);
await loaded.WaitAsync(TimeSpan.FromSeconds(20), ct);
}
async Task<JsonElement> Eval(string js)
{
var r = await cdp.SendAsync("Runtime.evaluate", new { expression = js, awaitPromise = true, returnByValue = true }, session, ct);
return r.TryGetProperty("result", out var v) && v.TryGetProperty("value", out var val) ? val : default;
}
async Task Shot(string name, string hash, string? script = null, int waitMs = 2500)
{
var before = errors.Count;
await Eval($"location.hash = '{hash}'");
await Task.Delay(waitMs, ct);
if (script != null)
{
await Eval(script);
await Task.Delay(1500, ct);
}
await Capture(Path.Combine(outDir, name + ".png"));
Console.WriteLine($"{name}.png{(errors.Count > before ? $" ({errors.Count - before} errori)" : "")}");
}
async Task Capture(string file)
{
var png = await cdp.SendAsync("Page.captureScreenshot", new { format = "png" }, session, ct);
await File.WriteAllBytesAsync(file, Convert.FromBase64String(png.GetProperty("data").GetString()!), ct);
}
if (mockup)
{
var images = Path.Combine(outDir, "immagini");
Directory.CreateDirectory(images);
await Viewport(1600, 1000);
foreach (var variant in Directory.GetDirectories(outDir).Where(d => File.Exists(Path.Combine(d, "stile.css"))).Order())
{
foreach (var page in new[] { "aste", "impostazioni", "puntate-gratis" })
{
foreach (var (theme, label) in new[] { ("light", "chiaro"), ("dark", "scuro") })
{
var before = errors.Count;
await Navigate(new Uri(Path.Combine(variant, page + ".html")).AbsoluteUri + "?tema=" + theme);
await Eval("document.fonts.ready.then(() => true)");
await Task.Delay(300, ct);
var name = $"{Path.GetFileName(variant)}-{page}-{label}.png";
await Capture(Path.Combine(images, name));
Console.WriteLine($"{name}{(errors.Count > before ? $" ({errors.Count - before} errori)" : "")}");
}
}
}
var sheet = Path.Combine(outDir, "confronto.html");
if (File.Exists(sheet))
{
await Navigate(new Uri(sheet).AbsoluteUri);
await Eval("Promise.all([...document.images].map(i => i.decode().catch(() => null))).then(() => true)");
var height = (await Eval("document.documentElement.scrollHeight")).GetInt32();
await Viewport(1600, height);
await Task.Delay(300, ct);
await Capture(Path.Combine(images, "confronto.png"));
Console.WriteLine("confronto.png");
}
}
else
{
await Viewport(1600, 1000);
await Navigate(baseUrl + "/accesso");
await Shot("00-accesso-interfaccia", "", null, 500);
await Eval($"document.querySelector('input[type=password]').value = {JsonSerializer.Serialize(password)}; document.querySelector('form').submit();");
await loaded.WaitAsync(TimeSpan.FromSeconds(20), ct);
await Task.Delay(1500, ct);
const string clickFirst = "document.querySelector('.split tbody tr[data-id]')?.click()";
await Shot("01-aste", "#/aste", clickFirst, 4000);
await Shot("12-aste-registro", "#/aste", "document.querySelector('.panel .panel-mode button[data-mode=registro]')?.click()", 500);
await Shot("14-aste-puntate", "#/aste", "document.querySelector('.panel .tabs button[data-tab=puntate]')?.click()", 500);
await Eval("document.querySelector('.panel .tabs button[data-tab=auto]')?.click()");
await Shot("02-apprendimento", "#/apprendimento", null, 3500);
await Shot("03-browser", "#/browser");
if (args.Contains("--accesso-assistito"))
{
// Apre il browser del bot (Chromium dentro il bot) e aspetta il primo fotogramma.
await Eval("document.querySelector('.browser .idle button')?.click()");
var frame = false;
for (var i = 0; i < 40 && !frame; i++)
{
await Task.Delay(500, ct);
frame = (await Eval("!document.querySelector('.browser canvas').hidden")).ValueKind == JsonValueKind.True;
}
await Task.Delay(2500, ct);
await Shot("03-browser", "#/browser", null, 200);
Console.WriteLine(frame ? "Browser del bot: fotogrammi ricevuti" : "Browser del bot: nessun fotogramma");
if (!frame) errors.Add("accesso assistito: nessun fotogramma dal browser del bot");
await Eval("document.querySelector('.browser .url button[title^=\"Chiudi\"]')?.click()");
}
if (args.Contains("--messaggio"))
{
// Il messaggio a schermo per un'informazione importante: senza token Telegram il
// messaggio di prova risponde che manca la configurazione.
await Shot("11-messaggio", "#/impostazioni", "[...document.querySelectorAll('.section button')].find(b => b.textContent.startsWith('Invia messaggio'))?.click()");
if ((await Eval("!!document.querySelector('.modal .notice')")).ValueKind != JsonValueKind.True)
errors.Add("messaggio a schermo: nessun avviso dopo «Invia messaggio di prova»");
await Eval("document.querySelector('.modal footer .btn')?.click()");
}
await Shot("04-prodotti", "#/prodotti", clickFirst);
await Shot("13-prodotti-statistiche", "#/prodotti", "[...document.querySelectorAll('.panel .tabs button')].find(b => b.textContent === 'Statistiche')?.click()", 500);
await Eval("[...document.querySelectorAll('.panel .tabs button')].find(b => b.textContent === 'Paletti e valore')?.click()");
await Shot("05-impostazioni", "#/impostazioni");
await Shot("06-storico", "#/storico", clickFirst);
await Shot("09-cerca", "#/cerca", null, 4000);
await Shot("10-registro", "#/registro");
await Eval("document.documentElement.dataset.theme = 'light'");
await Shot("07-aste-tema-chiaro", "#/aste", clickFirst, 2500);
await Eval("document.documentElement.dataset.theme = 'dark'");
// Una finestra di portatile comune: la colonna Azioni deve restare in vista.
await Viewport(1366, 768);
await Shot("15-aste-1366", "#/aste", clickFirst, 2000);
await Viewport(1000, 900);
await Shot("08-aste-finestra-stretta", "#/aste", clickFirst, 2000);
await Eval("localStorage.removeItem('mimante.theme')");
}
try { await cdp.SendAsync("Browser.close", timeout: TimeSpan.FromSeconds(3)); } catch { }
if (errors.Count == 0)
{
Console.WriteLine($"Nessun errore JavaScript. Schermate in {outDir}");
return 0;
}
Console.WriteLine("Errori dell'interfaccia:");
foreach (var e in errors.Distinct()) Console.WriteLine(" " + e);
return 1;
static string RepoRoot()
{
for (var d = new DirectoryInfo(Environment.CurrentDirectory); d != null; d = d.Parent)
if (File.Exists(Path.Combine(d.FullName, "Mimante.slnx"))) return d.FullName;
return Environment.CurrentDirectory;
}