using System.Text.Json; using BidooBidBot.Session.Cdp; // Uso: dotnet run --project tools/Screenshots -- // Esempio: dotnet run --project tools/Screenshots -- http://localhost:8080 dev docs/screenshot // Il bot deve girare sul simulatore (--simulatore) per avere aste da fotografare. // Esce con 1 se una pagina ha errori JavaScript. if (args.Length < 3) { Console.Error.WriteLine("Uso: Screenshots "); return 2; } var baseUrl = args[0].TrimEnd('/'); var password = args[1]; // Un percorso relativo vale dalla radice del repository: `dotnet run` parte nella cartella del progetto. var outDir = Path.IsPathRooted(args[2]) ? args[2] : Path.GetFullPath(Path.Combine(RepoRoot(), args[2])); Directory.CreateDirectory(outDir); using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)); var ct = cts.Token; var profile = Path.Combine(Path.GetTempPath(), $"bidbot-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(); 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 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); } var png = await cdp.SendAsync("Page.captureScreenshot", new { format = "png" }, session, ct); var file = Path.Combine(outDir, name + ".png"); await File.WriteAllBytesAsync(file, Convert.FromBase64String(png.GetProperty("data").GetString()!), ct); Console.WriteLine($"{name}.png{(errors.Count > before ? $" ({errors.Count - before} errori)" : "")}"); } 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('bidbot.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, "BidooBidBot.sln"))) return d.FullName; return Environment.CurrentDirectory; }