using System.Diagnostics;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
///
/// Screenshots through the DevTools protocol of the Edge or Chrome already installed (ADR 0007). The protocol sets the
/// exact width: a headless window cannot be narrower than about 500 pixels, too wide for the 390-pixel phone.
///
internal sealed class Shots : IDisposable
{
private readonly Process _browser;
private readonly ClientWebSocket _socket = new();
private readonly string _profile;
private int _id;
private Shots(Process browser, string profile)
{
_browser = browser;
_profile = profile;
}
public static Shots Start(string browserPath)
{
var profile = Path.Combine(Path.GetTempPath(), "anubis-shots-" + Guid.NewGuid().ToString("N"));
var info = new ProcessStartInfo(browserPath)
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach (var argument in new[] { "--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check",
"--remote-debugging-port=0", "--user-data-dir=" + profile, "about:blank" })
{
info.ArgumentList.Add(argument);
}
var process = Process.Start(info)!;
process.OutputDataReceived += (_, _) => { };
process.ErrorDataReceived += (_, _) => { };
process.BeginOutputReadLine();
process.BeginErrorReadLine();
var shots = new Shots(process, profile);
try
{
shots.Connect();
return shots;
}
catch
{
shots.Dispose();
throw;
}
}
// The browser writes its port into DevToolsActivePort; the page target is found through /json/list.
private void Connect()
{
var portFile = Path.Combine(_profile, "DevToolsActivePort");
for (var i = 0; i < 60 && !File.Exists(portFile); i++)
{
Thread.Sleep(250);
}
var port = File.ReadAllLines(portFile)[0].Trim();
using var http = new HttpClient();
string? target = null;
for (var i = 0; i < 40 && target is null; i++)
{
var list = JsonNode.Parse(http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list")).GetAwaiter().GetResult())!.AsArray();
target = list.FirstOrDefault(t => (string?)t!["type"] == "page")?["webSocketDebuggerUrl"]?.GetValue();
if (target is null)
{
Thread.Sleep(250);
}
}
_socket.ConnectAsync(new Uri(target ?? throw new InvalidOperationException("Nessuna pagina nel browser.")), CancellationToken.None).GetAwaiter().GetResult();
Send("Page.enable", new JsonObject());
}
/// Opens at the given size and theme and saves the visible part as PNG.
public void Take(string url, int width, int height, bool dark, string file)
{
Send("Emulation.setDeviceMetricsOverride", new JsonObject
{
["width"] = width,
["height"] = height,
["deviceScaleFactor"] = 2,
["mobile"] = width < 768,
});
Send("Emulation.setEmulatedMedia", new JsonObject
{
["features"] = new JsonArray(new JsonObject { ["name"] = "prefers-color-scheme", ["value"] = dark ? "dark" : "light" }),
});
Send("Page.navigate", new JsonObject { ["url"] = url }, waitForEvent: "Page.loadEventFired");
Thread.Sleep(500);
// The whole page, not just the first screen: a page taller than the window grows the window to fit.
var metrics = Send("Page.getLayoutMetrics", new JsonObject());
var full = (int)Math.Ceiling(metrics["cssContentSize"]?["height"]?.GetValue() ?? height);
if (full > height)
{
Send("Emulation.setDeviceMetricsOverride", new JsonObject
{
["width"] = width,
["height"] = full,
["deviceScaleFactor"] = 2,
["mobile"] = width < 768,
});
Thread.Sleep(300);
}
var result = Send("Page.captureScreenshot", new JsonObject { ["format"] = "png" });
File.WriteAllBytes(file, Convert.FromBase64String(result["data"]!.GetValue()));
}
// Sends one command and waits for its answer (and, if asked, for an event), skipping everything else.
private JsonNode Send(string method, JsonObject parameters, string? waitForEvent = null)
{
var id = ++_id;
var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters };
_socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, true, CancellationToken.None).GetAwaiter().GetResult();
JsonNode? answer = null;
var eventSeen = waitForEvent is null;
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
while (answer is null || !eventSeen)
{
var received = Receive(limit.Token);
if ((int?)received["id"] == id)
{
if (received["error"] is { } error)
{
throw new InvalidOperationException(method + ": " + error.ToJsonString());
}
answer = received["result"] ?? new JsonObject();
}
else if ((string?)received["method"] == waitForEvent)
{
eventSeen = true;
}
}
return answer;
}
private JsonNode Receive(CancellationToken cancellationToken)
{
var buffer = new byte[64 * 1024];
using var all = new MemoryStream();
WebSocketReceiveResult result;
do
{
result = _socket.ReceiveAsync(buffer, cancellationToken).GetAwaiter().GetResult();
all.Write(buffer, 0, result.Count);
}
while (!result.EndOfMessage);
return JsonNode.Parse(all.ToArray(), documentOptions: new JsonDocumentOptions { MaxDepth = 64 })!;
}
public void Dispose()
{
_socket.Dispose();
try
{
_browser.Kill(entireProcessTree: true);
_browser.WaitForExit(5000);
}
catch (InvalidOperationException)
{
}
_browser.Dispose();
for (var i = 0; i < 10 && Directory.Exists(_profile); i++)
{
try
{
Directory.Delete(_profile, recursive: true);
}
catch (IOException)
{
Thread.Sleep(300);
}
catch (UnauthorizedAccessException)
{
Thread.Sleep(300);
}
}
}
}