using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Browser.Hosting;
namespace Febe.Schermate;
///
/// One screenshot of Febe's own interface through the DevTools protocol of a Chromium without window: exact viewport at
/// scale 1.25 (like the mockups), console errors printed, an optional step (a script evaluated in the page and awaited;
/// when it returns { hover: [x, y] } the pointer is moved there, so :hover styles show). A fresh profile every
/// time, deleted at the end. Only addresses on this computer ().
///
internal sealed class Screenshotter : IAsyncDisposable
{
/// The scale of the mockups.
public const double Scale = 1.25;
private static readonly TimeSpan StartPatience = TimeSpan.FromSeconds(20);
private readonly Process _process;
private readonly string _profile;
private readonly ClientWebSocket _socket;
private readonly ConcurrentDictionary> _pending = new();
private readonly CancellationTokenSource _stop = new();
private readonly Task _receiving;
private readonly TextWriter _log;
private int _id;
private Screenshotter(Process process, string profile, ClientWebSocket socket, TextWriter log)
{
_process = process;
_profile = profile;
_socket = socket;
_log = log;
_receiving = Task.Run(ReceiveAsync);
}
/// Chromium: FEBE_CHROMIUM, then PATH and the usual places (Debian's «chromium», Edge on Windows).
public static string? FindChromium() => ChromiumCommandLine.FindExecutable();
/// The command line of the screenshot browser: no window, a private profile, the debug port only on 127.0.0.1.
internal static List Arguments(string profile, int width, int height, bool noSandbox)
{
// Port 0: Chromium picks a free port and writes it in DevToolsActivePort, so no other process can take it.
List arguments =
[
"--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check",
"--disable-extensions", "--disable-background-networking", "--disable-component-update", "--no-proxy-server",
"--mute-audio", string.Create(CultureInfo.InvariantCulture, $"--window-size={width},{height}"),
$"--user-data-dir={profile}", "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1",
];
if (noSandbox)
{
arguments.Add("--no-sandbox");
}
arguments.Add("about:blank");
return arguments;
}
public static async Task StartAsync(string chromium, int width, int height, TextWriter log, CancellationToken ct)
{
var profile = Path.Combine(Path.GetTempPath(), "febe-schermata-" + Guid.NewGuid().ToString("N"));
var info = new ProcessStartInfo(chromium) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var argument in Arguments(profile, width, height, OperatingSystem.IsLinux() && Environment.UserName == "root"))
{
info.ArgumentList.Add(argument);
}
var process = Process.Start(info) ?? throw new InvalidOperationException("Chromium non parte.");
process.OutputDataReceived += (_, _) => { };
process.ErrorDataReceived += (_, _) => { };
process.BeginOutputReadLine();
process.BeginErrorReadLine();
try
{
using var http = new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(5) };
var watch = Stopwatch.StartNew();
string? debugger = null;
while (debugger is null)
{
if (process.HasExited)
{
throw new InvalidOperationException($"Chromium si è chiuso all'avvio (codice {process.ExitCode}).");
}
if (watch.Elapsed > StartPatience)
{
throw new TimeoutException("Chromium non risponde sulla porta di debug.");
}
if (ActivePort(profile) is > 0 and var port)
{
try
{
debugger = PageDebugger(await http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list"), ct));
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException)
{
// Chromium is still starting.
}
}
if (debugger is null)
{
await Task.Delay(100, ct);
}
}
var socket = new ClientWebSocket();
socket.Options.Proxy = null;
await socket.ConnectAsync(new Uri(debugger), ct);
return new Screenshotter(process, profile, socket, log);
}
catch
{
Kill(process);
TryDelete(profile);
throw;
}
}
/// Navigates, waits, runs the step, and returns the PNG.
public async Task TakeAsync(Uri address, int width, int height, TimeSpan wait, string? stepCode, CancellationToken ct)
{
if (!Shots.IsOnThisComputer(address))
{
throw new ArgumentException("Solo l'interfaccia di Febe su questo computer (127.0.0.1, localhost o [::1]).", nameof(address));
}
await SendAsync("Runtime.enable", null, ct);
await SendAsync("Log.enable", null, ct);
await SendAsync("Page.enable", null, ct);
await SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject
{
["width"] = width, ["height"] = height, ["deviceScaleFactor"] = Scale, ["mobile"] = false,
}, ct);
await SendAsync("Page.navigate", new JsonObject { ["url"] = address.AbsoluteUri }, ct);
await Task.Delay(wait, ct);
if (stepCode is not null)
{
var evaluated = await SendAsync("Runtime.evaluate", new JsonObject
{
["expression"] = $"(async () => {{ {stepCode}\n}})()", ["awaitPromise"] = true, ["returnByValue"] = true,
}, ct);
if (evaluated.TryGetProperty("exceptionDetails", out var failure))
{
_log.WriteLine($"errore nel passo: {Description(failure)}");
}
else if (evaluated.TryGetProperty("result", out var result) && result.TryGetProperty("value", out var value))
{
_log.WriteLine($"passo: {value.GetRawText()}");
if (HoverPoint(value) is { } point)
{
await SendAsync("Input.dispatchMouseEvent", new JsonObject
{
["type"] = "mouseMoved", ["x"] = point.X, ["y"] = point.Y,
}, ct);
}
}
await Task.Delay(800, ct);
}
var shot = await SendAsync("Page.captureScreenshot", new JsonObject { ["format"] = "png" }, ct);
return Convert.FromBase64String(shot.GetProperty("data").GetString() ?? string.Empty);
}
/// The point of { hover: [x, y] }, or null.
internal static (double X, double Y)? HoverPoint(JsonElement value) =>
value.ValueKind == JsonValueKind.Object
&& value.TryGetProperty("hover", out var hover)
&& hover.ValueKind == JsonValueKind.Array
&& hover.GetArrayLength() == 2
&& hover[0].ValueKind == JsonValueKind.Number
&& hover[1].ValueKind == JsonValueKind.Number
? (hover[0].GetDouble(), hover[1].GetDouble())
: null;
/// The debugger address of the first page target of /json/list, or null.
internal static string? PageDebugger(string list)
{
using var document = JsonDocument.Parse(list);
foreach (var target in document.RootElement.EnumerateArray())
{
if (target.TryGetProperty("type", out var type) && type.GetString() == "page"
&& target.TryGetProperty("webSocketDebuggerUrl", out var url) && url.GetString() is { } address
&& Uri.TryCreate(address, UriKind.Absolute, out var parsed) && parsed.Host == "127.0.0.1")
{
return address;
}
}
return null;
}
public async ValueTask DisposeAsync()
{
await _stop.CancelAsync();
try
{
await _receiving;
}
catch (OperationCanceledException)
{
// Stopped on purpose.
}
_socket.Dispose();
Kill(_process);
_process.Dispose();
_stop.Dispose();
TryDelete(_profile);
}
private async Task SendAsync(string method, JsonObject? parameters, CancellationToken ct)
{
var id = Interlocked.Increment(ref _id);
var answer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_pending[id] = answer;
var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters ?? new JsonObject() };
await _socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, endOfMessage: true, ct);
using var registration = ct.Register(() => answer.TrySetCanceled(ct));
return await answer.Task;
}
private async Task ReceiveAsync()
{
var buffer = new byte[64 * 1024];
using var message = new MemoryStream();
while (!_stop.IsCancellationRequested && _socket.State == WebSocketState.Open)
{
ValueWebSocketReceiveResult result;
try
{
result = await _socket.ReceiveAsync(buffer.AsMemory(), _stop.Token);
}
catch (WebSocketException)
{
break;
}
if (result.MessageType == WebSocketMessageType.Close)
{
break;
}
message.Write(buffer, 0, result.Count);
if (!result.EndOfMessage)
{
continue;
}
Dispatch(message.GetBuffer().AsSpan(0, (int)message.Length));
message.SetLength(0);
}
foreach (var pending in _pending.Values)
{
pending.TrySetException(new InvalidOperationException("Chromium ha chiuso il collegamento."));
}
}
private void Dispatch(ReadOnlySpan text)
{
var reader = new Utf8JsonReader(text);
using var document = JsonDocument.ParseValue(ref reader);
var root = document.RootElement;
if (root.TryGetProperty("id", out var id) && _pending.TryRemove(id.GetInt32(), out var answer))
{
if (root.TryGetProperty("error", out var error))
{
answer.TrySetException(new InvalidOperationException($"DevTools: {error.GetRawText()}"));
}
else
{
answer.TrySetResult(root.GetProperty("result").Clone());
}
return;
}
if (!root.TryGetProperty("method", out var method) || !root.TryGetProperty("params", out var parameters))
{
return;
}
// Only Febe's own pages: what they print in their console is Febe's own interface talking.
switch (method.GetString())
{
case "Runtime.consoleAPICalled" when parameters.GetProperty("type").GetString() is "error" or "warning":
var words = new List();
foreach (var argument in parameters.GetProperty("args").EnumerateArray())
{
words.Add(argument.TryGetProperty("value", out var value) ? value.ToString() : Description(argument));
}
_log.WriteLine($"console.{parameters.GetProperty("type").GetString()}: {string.Join(' ', words)}");
break;
case "Runtime.exceptionThrown":
_log.WriteLine($"eccezione: {Description(parameters.GetProperty("exceptionDetails"))}");
break;
case "Log.entryAdded" when parameters.GetProperty("entry").GetProperty("level").GetString() == "error":
var entry = parameters.GetProperty("entry");
_log.WriteLine($"errore: {entry.GetProperty("text").GetString()} {(entry.TryGetProperty("url", out var url) ? url.GetString() : string.Empty)}");
break;
}
}
private static string Description(JsonElement element)
{
if (element.TryGetProperty("exception", out var exception) && exception.TryGetProperty("description", out var described))
{
return described.GetString() ?? string.Empty;
}
if (element.TryGetProperty("description", out var description))
{
return description.GetString() ?? string.Empty;
}
return element.TryGetProperty("text", out var text) ? text.GetString() ?? string.Empty : string.Empty;
}
/// The port Chromium wrote in DevToolsActivePort (first line), or 0 while it has not.
private static int ActivePort(string profile)
{
try
{
using var reader = new StreamReader(Path.Combine(profile, "DevToolsActivePort"));
return int.TryParse(reader.ReadLine(), NumberStyles.None, CultureInfo.InvariantCulture, out var port) ? port : 0;
}
catch (IOException)
{
return 0;
}
catch (UnauthorizedAccessException)
{
return 0;
}
}
private static void Kill(Process process)
{
try
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
process.WaitForExit(5000);
}
}
catch (InvalidOperationException)
{
// Already gone.
}
}
private static void TryDelete(string profile)
{
// Chromium may hold its files for a moment after it exits.
for (var attempt = 0; attempt < 10; attempt++)
{
try
{
if (Directory.Exists(profile))
{
Directory.Delete(profile, recursive: true);
}
return;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Thread.Sleep(200);
}
}
}
}