misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Lab: KDE, Cinnamon and XFCE copies that test a build, and harnesses for theme and store checks (#164) (#211)
Ahmed Nefzaoui43499f08a2b6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e7e2c3c1..fa1e293a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -319,7 +319,12 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, seepixel by pixel (`shots.sh`, `shot-host.sh`, `pixdiff.py`), HLS and DASH hand-overs from the SnapFirefox and Google Chrome (`streams.mjs`, `streams-chrome.mjs`), the extension's proxy switch(`proxy-optin.mjs`), hand-overs and the Scheduler while minimized, torrents without a network,- and MDM's start-up time (`measure.sh`). Every change is now checked on Linux as on Windows.+ and MDM's start-up time (`measure.sh`). Every change is now checked on Linux as on Windows. The+ machine also has copies on KDE Plasma, Cinnamon and XFCE (`desktop.sh`), which get a build+ copied over instead of making one (`vm.ps1 deploy`); a window harness shoots many windows from+ one running MDM in any language, mode and theme, with real clicks and keys inside the machine+ (`win.sh`, `win-host.sh`); and a store package is checked before it ships (`store-check.mjs`,+ `chrome-menu.mjs`).- **Developers: the engine tests no longer fail on a busy computer**([#136](https://github.com/anefzaoui/misterdownloadmanager/issues/136)). Three end-to-end testsdepended on timing: a refused connection coming back, the learned connection limit, and a deaddiff --git a/ROADMAP.md b/ROADMAP.mdindex a18b3dc1..18a840e2 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -32,6 +32,9 @@ Everything below ships together, in one release, as version 0.3.0.- ✅ A Linux test machine for every change, scripted: an Ubuntu 24.04 desktop that builds eachbranch and drives MDM, Firefox and Chrome there (part of[#164](https://github.com/anefzaoui/misterdownloadmanager/issues/164))+- ✅ The Linux test machine also has KDE Plasma, Cinnamon and XFCE copies, which test a build+ without making it; store packages and theme windows are checked there too (part of+ [#164](https://github.com/anefzaoui/misterdownloadmanager/issues/164))- ✅ Firefox: reading the browser's proxy (#42) is an opt-in, a switch in the extension's popup, sothe extension's update asks for no new permission; Chrome's extension leaves it out for now- ✅ Streams whose address doesn't end in .m3u8 or .mpd, served as plain text, are found too: bydiff --git a/tools/lab/linux-vm/build.sh b/tools/lab/linux-vm/build.shindex f485fb59..a772f471 100644--- a/tools/lab/linux-vm/build.sh+++ b/tools/lab/linux-vm/build.sh@@ -16,7 +16,9 @@ if [ $# -gt 0 ]; thengit fetch -q origin '+refs/heads/*:refs/remotes/origin/*' '+refs/pull/*/head:refs/remotes/origin/pr/*'ref=$(git rev-parse -q --verify "origin/$1^{commit}" || git rev-parse -q --verify "$1^{commit}") || {echo "== no branch, PR or commit named $1"; exit 1; }- git checkout -q --detach "$ref"+ # The lab's checkout is a scratch copy: a Cargo.lock that a test run rewrote must not keep it on+ # the last commit (the build would then carry the wrong label).+ git checkout -q -f --detach "$ref" || { echo "== could not check out $1"; exit 1; }fiprofile=${MDM_PROFILE:-vmtest}label=${2:-$(echo "$ref_name" | tr '/' '-')}diff --git a/tools/lab/linux-vm/chrome-menu.mjs b/tools/lab/linux-vm/chrome-menu.mjsnew file mode 100644index 00000000..b0e5fe65--- /dev/null+++ b/tools/lab/linux-vm/chrome-menu.mjs@@ -0,0 +1,151 @@+// #155 in Google Chrome by the right-click menu, which headless Chrome can't show: a Chrome window+// on the lab's desktop (the DevTools pipe loads the unpacked extension), the lab's HLS player+// page, a real right-click on the player (xdotool), then the menu's own entry by the keyboard+// (Up from the menu's end: Inspect, then the extension's entry above it). Then as streams.mjs:+// MDM's Download video window, the address yt-dlp was given, what the lab saw.+// node chrome-menu.mjs <unpacked extension folder> [lab] [kind:manifest] e.g. hls:/hls/master.m3u8+// MENU_KEYS: the keys after the right-click (default "Up Up Return"); MENU_SHOT: a file to write+// "x y" of the click to and wait 4 s on, so a screenshot of the open menu can be taken from outside.+import fs from "node:fs";+import path from "node:path";+import { spawn, execFileSync } from "node:child_process";++const ext = path.resolve(process.argv[2]);+const LAB = process.argv[3] || "http://127.0.0.1:8097";+const [kind, manifest] = (process.argv[4] || "hls:/hls/master.m3u8").split(":");+const keys = (process.env.MENU_KEYS || "Up Up Return").split(" ");+const NL = String.fromCharCode(10);+const NUL = String.fromCharCode(0);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+async function until(what, ms, f) {+ const end = Date.now() + ms;+ for (;;) {+ const v = await f().catch(() => null);+ if (v) return v;+ if (Date.now() > end) throw new Error(`timed out: ${what}`);+ await sleep(250);+ }+}+const run = (cmd, args) => {+ try {+ return execFileSync(cmd, args, { encoding: "utf8" });+ } catch (e) {+ return e.stdout || "";+ }+};+const windows = () => run("wmctrl", ["-l"]);+const ytdlpPids = () => run("pgrep", ["-f", "^python3 /usr/local/bin/yt-dlp"]).split(NL).filter(Boolean);+const argOf = (pid) => {+ try {+ return fs.readFileSync(`/proc/${pid}/cmdline`, "utf8").split(NUL).filter(Boolean).pop();+ } catch {+ return null;+ }+};+class Pipe {+ constructor(proc) {+ this.out = proc.stdio[3];+ this.next = 1;+ this.waiting = new Map();+ let buf = "";+ proc.stdio[4].on("data", (d) => {+ buf += d.toString("utf8");+ let i;+ while ((i = buf.indexOf(NUL)) >= 0) {+ const m = JSON.parse(buf.slice(0, i));+ buf = buf.slice(i + 1);+ const w = m.id && this.waiting.get(m.id);+ if (!w) continue;+ this.waiting.delete(m.id);+ if (m.error) w.reject(new Error(`${w.method}: ${m.error.message}`));+ else w.resolve(m.result);+ }+ });+ }+ send(method, params = {}, sessionId) {+ const id = this.next++;+ this.out.write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + NUL);+ return new Promise((resolve, reject) => {+ this.waiting.set(id, { resolve, reject, method });+ setTimeout(() => this.waiting.has(id) && (this.waiting.delete(id), reject(new Error(`${method}: no answer in 60 s`))), 60000);+ });+ }+}+const profile = path.join(process.env.HOME, "lab/chrome-menu");+fs.rmSync(profile, { recursive: true, force: true });+const hosts = path.join(profile, "NativeMessagingHosts");+fs.mkdirSync(hosts, { recursive: true });+fs.copyFileSync(path.join(process.env.HOME, ".config/google-chrome/NativeMessagingHosts/com.misterdownloadmanager.host.json"), path.join(hosts, "com.misterdownloadmanager.host.json"));+const proc = spawn(+ "/usr/bin/google-chrome",+ ["--remote-debugging-pipe", "--enable-unsafe-extension-debugging", "--password-store=basic", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", "--window-position=40,60", "--window-size=1100,800", "about:blank"],+ { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"] },+);+const say = (s) => console.log(s);+try {+ const cdp = new Pipe(proc);+ const { product } = await cdp.send("Browser.getVersion");+ const { id } = await cdp.send("Extensions.loadUnpacked", { path: ext });+ say(`${product} (a window on the desktop), extension ${id} from ${ext}`);+ const targets = (await cdp.send("Target.getTargets")).targetInfos;+ const tab = targets.find((t) => t.type === "page");+ const { sessionId } = await cdp.send("Target.attachToTarget", { targetId: tab.targetId, flatten: true });+ await cdp.send("Page.enable", {}, sessionId);+ const evaluate = async (expression) => {+ const r = await cdp.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }, sessionId);+ if (r.exceptionDetails) throw new Error(`evaluate: ${r.exceptionDetails.text}`);+ return r.result.value;+ };+ const cookie = `sid155=chrome-menu-${kind}`;+ await cdp.send("Page.navigate", { url: `${LAB}/cookie?set=${encodeURIComponent(cookie)}` }, sessionId);+ await sleep(1500);+ const page = `${LAB}/page?${kind}=1`;+ await cdp.send("Page.navigate", { url: page }, sessionId);+ const state = await until("the stream player", 20000, () => evaluate("document.body.dataset.stream || ''"));+ say(`${kind}: the page's player: ${state}`);+ // The player's middle on the screen: the window's place plus the toolbar's height.+ const at = await evaluate(`(() => { const r = document.querySelector("#player").getBoundingClientRect();+ return { x: Math.round(window.screenX + r.left + r.width / 2), y: Math.round(window.screenY + (window.outerHeight - window.innerHeight) + r.top + r.height / 2) }; })()`);+ await sleep(1000);+ await fetch(`${LAB}/_log`, { method: "DELETE" });+ const before = new Set(ytdlpPids());+ run("xdotool", ["mousemove", String(at.x), String(at.y), "click", "1"]);+ await sleep(800);+ run("xdotool", ["click", "3"]);+ await sleep(1500);+ if (process.env.MENU_SHOT) {+ fs.writeFileSync(process.env.MENU_SHOT, `${at.x} ${at.y}${NL}`);+ await sleep(4000);+ }+ for (const k of keys) {+ run("xdotool", ["key", k]);+ await sleep(300);+ }+ const t0 = Date.now();+ const secs = () => ((Date.now() - t0) / 1000).toFixed(1);+ let windowAt = null;+ let given = null;+ let pid = null;+ while (Date.now() - t0 < 60000 && !(windowAt && given)) {+ if (!windowAt && windows().includes("Download video from a page")) windowAt = secs();+ if (!given) {+ pid = ytdlpPids().find((x) => !before.has(x));+ if (pid) given = argOf(pid);+ }+ await sleep(200);+ }+ if (pid) await until("yt-dlp's lookup", 90000, async () => !fs.existsSync(`/proc/${pid}`)).catch(() => {});+ const asked = (await (await fetch(`${LAB}/_log`)).json()).filter((e) => e.referer === page || e.path === manifest);+ const seen = asked.map((e) => `${e.path}${e.query ? "?" + e.query : ""} ${e.status}${(e.cookie || "").includes(cookie) ? " +cookie" : ""}${e.referer === page ? " +referrer" : ""}`);+ const ok = windowAt && given && new URL(given).pathname === manifest && asked.some((e) => e.path === manifest);+ say(+ `${ok ? "OK " : "FAIL"} ${kind} right-click menu (keys ${keys.join(" ")}): MDM's window ${windowAt ? `at ${windowAt} s` : "NOT within 60 s"}; ` ++ `yt-dlp given ${given || "nothing"}; the lab saw ${seen.join(", ") || "nothing"}`,+ );+ run("wmctrl", ["-c", "Download video from a page"]);+} catch (e) {+ say(`ERROR ${e.message}`);+} finally {+ proc.kill();+}+process.exit(0);diff --git a/tools/lab/linux-vm/desktop.sh b/tools/lab/linux-vm/desktop.shnew file mode 100644index 00000000..f9d75481--- /dev/null+++ b/tools/lab/linux-vm/desktop.sh@@ -0,0 +1,22 @@+#!/bin/bash+# Another desktop beside GNOME in a lab clone (vm.ps1 clone), GDM kept as the login manager and the+# auto-login session switched to the new desktop, for MDM's checks on KDE Plasma, Cinnamon, XFCE.+# Reboot the clone afterwards. The sudo password comes on stdin (vm.ps1 run passes MDM_SUDO_PASSWORD):+# echo "$MDM_SUDO_PASSWORD" | bash desktop.sh "<packages>" <session>+# e.g. "kde-plasma-desktop xdg-desktop-portal-kde" plasma · cinnamon-core cinnamon ·+# "xfce4 xfce4-goodies xdg-desktop-portal-gtk" xfce+# Plasma: its screen locker is turned off afterwards (kwriteconfig5 --file kscreenlockerrc --group+# Daemon --key Autolock false), as GNOME's is in setup.sh.+read -r PW+S() { echo "$PW" | sudo -S -p '' "$@"; }+pkgs=$1; session=$2+S true || exit 1+# GDM stays the display manager (a desktop's own, sddm or lightdm, would ask).+for dm in gdm3 lightdm sddm; do echo "$dm shared/default-x-display-manager select gdm3" | S debconf-set-selections; done+S env DEBIAN_FRONTEND=noninteractive apt-get update -q >/dev/null+S env DEBIAN_FRONTEND=noninteractive apt-get install -y -q $pkgs 2>&1 | tail -3+ls /usr/share/xsessions/+# AccountsService names the session GDM logs into; XSession for an X11 one.+S sed -i -e "s/^Session=.*/Session=$session/" -e "/^XSession=/d" /var/lib/AccountsService/users/"$USER"+S sed -i "s/^Session=$session/Session=$session\nXSession=$session/" /var/lib/AccountsService/users/"$USER"+S head -3 /var/lib/AccountsService/users/"$USER"diff --git a/tools/lab/linux-vm/store-check.mjs b/tools/lab/linux-vm/store-check.mjsnew file mode 100644index 00000000..41f44428--- /dev/null+++ b/tools/lab/linux-vm/store-check.mjs@@ -0,0 +1,230 @@+// A store package checked on Linux before it ships: installed in a throwaway profile (Firefox: the+// .xpi as a temporary add-on over WebDriver BiDi, as about:debugging loads one, since the Snap+// Firefox wants signed add-ons for a normal install; Google Chrome: the unpacked folder over the+// DevTools pipe), its version read back, its popup captured (PNG beside the output), and an+// ordinary download handed to MDM: the browser asked for a lab file, MDM's Download File Info+// window must open and the browser must not keep the download itself. MDM and the lab server must+// be running.+// node store-check.mjs firefox <file.xpi> [lab] [out folder]+// node store-check.mjs chrome <unpacked folder> [lab] [out folder]+import fs from "node:fs";+import path from "node:path";+import { spawn, execFileSync } from "node:child_process";++const [browser, pkg] = [process.argv[2], path.resolve(process.argv[3])];+const LAB = process.argv[4] || "http://127.0.0.1:8097";+const OUT = path.resolve(process.argv[5] || path.join(process.env.HOME, "lab/store-check"));+const ID = "[email protected]";+const UUID = "5d0c3b8e-7a51-4c1e-9f0a-38e2c4a1d7b6";+const NL = String.fromCharCode(10);+const NUL = String.fromCharCode(0);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+async function until(what, ms, f) {+ const end = Date.now() + ms;+ for (;;) {+ const v = await f().catch(() => null);+ if (v) return v;+ if (Date.now() > end) throw new Error(`timed out: ${what}`);+ await sleep(250);+ }+}+const run = (cmd, args) => {+ try {+ return execFileSync(cmd, args, { encoding: "utf8" });+ } catch (e) {+ return e.stdout || "";+ }+};+const windows = () => run("wmctrl", ["-l"]);+fs.mkdirSync(OUT, { recursive: true });+const say = (s) => console.log(s);++// The ordinary download: a lab file of its own name, MDM's window looked for, then closed.+async function ordinary(navigate, downloadsDir) {+ run("wmctrl", ["-c", "Download File Info"]);+ await sleep(1000);+ const name = `store-${browser}-${Date.now() % 100000}.zip`;+ const t0 = Date.now();+ await navigate(`${LAB}/gen/1M/${name}`).catch(() => {});+ const at = await until("MDM's Download File Info", 30000, async () => windows().includes("Download File Info") && ((Date.now() - t0) / 1000).toFixed(1)).catch(() => null);+ await sleep(2000);+ const kept = downloadsDir && fs.existsSync(downloadsDir) ? fs.readdirSync(downloadsDir).filter((f) => f.startsWith(name.replace(".zip", ""))) : [];+ run("wmctrl", ["-c", "Download File Info"]);+ say(`${at ? "OK " : "FAIL"} ordinary download ${name}: MDM's Download File Info ${at ? `at ${at} s` : "NOT within 30 s"}; ` + `the browser kept ${kept.length ? kept.join(", ") : "nothing"}`);+}++if (browser === "firefox") {+ class Bidi {+ constructor(ws) {+ this.ws = ws;+ this.next = 1;+ this.waiting = new Map();+ ws.addEventListener("message", (e) => {+ const m = JSON.parse(e.data);+ const w = m.id && this.waiting.get(m.id);+ if (!w) return;+ this.waiting.delete(m.id);+ if (m.type === "error") w.reject(new Error(`${w.method}: ${m.error} ${m.message}`));+ else w.resolve(m.result);+ });+ }+ send(method, params = {}) {+ const id = this.next++;+ this.ws.send(JSON.stringify({ id, method, params }));+ return new Promise((resolve, reject) => this.waiting.set(id, { resolve, reject, method }));+ }+ }+ // The Snap Firefox reads profiles under its own ~/snap folder only.+ const profile = path.join(process.env.HOME, "snap/firefox/common/mdm-store-check");+ try {+ execFileSync("pkill", ["-f", "--", `-profile ${profile}`]);+ execFileSync("sleep", ["2"]);+ } catch {}+ fs.rmSync(profile, { recursive: true, force: true });+ const downloads = path.join(profile, "downloads");+ fs.mkdirSync(downloads, { recursive: true });+ const pref = (k, v) => `user_pref(${JSON.stringify(k)}, ${JSON.stringify(v)});`;+ fs.writeFileSync(+ path.join(profile, "user.js"),+ [+ pref("browser.shell.checkDefaultBrowser", false),+ pref("datareporting.policy.dataSubmissionEnabled", false),+ pref("browser.aboutwelcome.enabled", false),+ pref("extensions.webextensions.uuids", JSON.stringify({ [ID]: UUID })),+ pref("browser.download.dir", downloads),+ pref("browser.download.folderList", 2),+ pref("browser.download.useDownloadDir", true),+ ].join(NL),+ );+ const port = 9300 + Math.floor(Math.random() * 500);+ const ff = spawn("/snap/bin/firefox", ["--headless", "-no-remote", "-profile", profile, "--remote-debugging-port", String(port)], {+ env: { ...process.env, MOZ_REMOTE_ALLOW_SYSTEM_ACCESS: "1" },+ stdio: "ignore",+ });+ try {+ const ws = await until("Firefox's remote protocol", 60000, () =>+ new Promise((resolve) => {+ const s = new WebSocket(`ws://127.0.0.1:${port}/session`);+ s.addEventListener("open", () => resolve(s));+ s.addEventListener("error", () => resolve(null));+ }),+ );+ const bidi = new Bidi(ws);+ const { capabilities } = await bidi.send("session.new", { capabilities: {} });+ const { extension } = await bidi.send("webExtension.install", { extensionData: { type: "archivePath", path: pkg } });+ const chrome = async (expression) => {+ const { contexts: w } = await bidi.send("browsingContext.getTree", { "moz:scope": "chrome" });+ const r = await bidi.send("script.evaluate", { expression, target: { context: w[0].context }, awaitPromise: true, "moz:scope": "chrome" });+ if (r.type === "exception") throw new Error(`chrome: ${r.exceptionDetails.text}`);+ return r.result.value;+ };+ const info = await chrome(`(async () => { const { AddonManager } = ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs");+ const a = await AddonManager.getAddonByID(${JSON.stringify(ID)}); return a ? [a.name, a.version, a.isActive, a.temporarilyInstalled, a.signedState].join(" | ") : "not installed"; })()`);+ say(`Firefox ${capabilities.browserVersion} (Snap, headless): installed ${extension}: ${info} (name | version | active | temporary | signed state)`);+ // A tab of its own (the first one can be a privileged page).+ const { context: ctx } = await bidi.send("browsingContext.create", { type: "tab" });+ const evaluate = async (expression) => {+ const r = await bidi.send("script.evaluate", { expression, target: { context: ctx }, awaitPromise: true });+ if (r.type === "exception") throw new Error(`evaluate: ${r.exceptionDetails.text}`);+ return r.result.value;+ };+ const navigate = async (url) => {+ await bidi.send("browsingContext.navigate", { context: ctx, url, wait: "complete" });+ };+ await bidi.send("browsingContext.setViewport", { context: ctx, viewport: { width: 420, height: 640 } });+ await navigate(`moz-extension://${UUID}/popup.html`);+ await sleep(2500);+ const text = await evaluate(`document.body.innerText.replace(/\\s+/g, " ").trim()`);+ // Firefox captures no extension page over BiDi ("privileged scope"): the text only; the+ // headed proxy-optin.mjs shows the popup on the lab's screen.+ say(`popup: "${text.slice(0, 300)}"`);+ await navigate(`${LAB}/`).catch(() => {});+ await ordinary(navigate, downloads);+ } catch (e) {+ say(`ERROR ${e.message}`);+ } finally {+ ff.kill();+ }+} else {+ class Pipe {+ constructor(proc) {+ this.out = proc.stdio[3];+ this.next = 1;+ this.waiting = new Map();+ let buf = "";+ proc.stdio[4].on("data", (d) => {+ buf += d.toString("utf8");+ let i;+ while ((i = buf.indexOf(NUL)) >= 0) {+ const m = JSON.parse(buf.slice(0, i));+ buf = buf.slice(i + 1);+ const w = m.id && this.waiting.get(m.id);+ if (!w) continue;+ this.waiting.delete(m.id);+ if (m.error) w.reject(new Error(`${w.method}: ${m.error.message}`));+ else w.resolve(m.result);+ }+ });+ }+ send(method, params = {}, sessionId) {+ const id = this.next++;+ this.out.write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + NUL);+ return new Promise((resolve, reject) => {+ this.waiting.set(id, { resolve, reject, method });+ setTimeout(() => this.waiting.has(id) && (this.waiting.delete(id), reject(new Error(`${method}: no answer in 60 s`))), 60000);+ });+ }+ }+ const profile = path.join(process.env.HOME, "lab/chrome-store-check");+ fs.rmSync(profile, { recursive: true, force: true });+ const downloads = path.join(profile, "downloads");+ fs.mkdirSync(downloads, { recursive: true });+ // With --user-data-dir, Chrome reads host manifests from <user-data-dir>/NativeMessagingHosts.+ const hosts = path.join(profile, "NativeMessagingHosts");+ fs.mkdirSync(hosts, { recursive: true });+ fs.copyFileSync(path.join(process.env.HOME, ".config/google-chrome/NativeMessagingHosts/com.misterdownloadmanager.host.json"), path.join(hosts, "com.misterdownloadmanager.host.json"));+ const proc = spawn(+ "/usr/bin/google-chrome",+ ["--headless", "--remote-debugging-pipe", "--enable-unsafe-extension-debugging", "--password-store=basic", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", "about:blank"],+ { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"] },+ );+ try {+ const cdp = new Pipe(proc);+ const { product } = await cdp.send("Browser.getVersion");+ const { id } = await cdp.send("Extensions.loadUnpacked", { path: pkg });+ const sw = await until("the extension's service worker", 15000, async () =>+ (await cdp.send("Target.getTargets")).targetInfos.find((t) => t.type === "service_worker" && t.url.includes(id)),+ );+ const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });+ const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });+ await cdp.send("Page.enable", {}, sessionId);+ // DOWNLOAD_BEHAVIOR=allow: the browser's own downloads go to the profile's folder (CDP's+ // setting); by default Chrome's own behaviour is left alone.+ if (process.env.DOWNLOAD_BEHAVIOR) await cdp.send("Browser.setDownloadBehavior", { behavior: process.env.DOWNLOAD_BEHAVIOR, downloadPath: downloads });+ const evaluate = async (expression) => {+ const r = await cdp.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }, sessionId);+ if (r.exceptionDetails) throw new Error(`evaluate: ${r.exceptionDetails.text}`);+ return r.result.value;+ };+ const navigate = async (url) => {+ await cdp.send("Page.navigate", { url }, sessionId);+ await sleep(1500);+ };+ await cdp.send("Emulation.setDeviceMetricsOverride", { width: 420, height: 640, deviceScaleFactor: 1, mobile: false }, sessionId);+ await navigate(`chrome-extension://${id}/popup.html`);+ await sleep(2500);+ const manifest = await evaluate(`(() => { const m = chrome.runtime.getManifest(); return [m.name, m.version, m.manifest_version].join(" | "); })()`);+ say(`${product} (headless): loaded unpacked ${id} from ${pkg}: ${manifest} (name | version | manifest); service worker ${sw ? "running" : "NOT running"}`);+ const text = await evaluate(`document.body.innerText.replace(/\\s+/g, " ").trim()`);+ const shot = await cdp.send("Page.captureScreenshot", { format: "png" }, sessionId);+ fs.writeFileSync(path.join(OUT, "chrome-popup.png"), Buffer.from(shot.data, "base64"));+ say(`popup: "${text.slice(0, 300)}"`);+ await navigate(`${LAB}/`);+ await ordinary(navigate, downloads);+ } catch (e) {+ say(`ERROR ${e.message}`);+ } finally {+ proc.kill();+ }+}+process.exit(0);diff --git a/tools/lab/linux-vm/vm.ps1 b/tools/lab/linux-vm/vm.ps1index 63085e63..a6344f63 100644--- a/tools/lab/linux-vm/vm.ps1+++ b/tools/lab/linux-vm/vm.ps1@@ -14,6 +14,9 @@ and clipboard are never touched; keep the VM's clipboard sharing and drag-and-drtools/lab/linux-vm/vm.ps1 clone <new name> [-Snapshot <name>] [-Cpus 6] [-MemoryMb 10240]# a linked clone of a snapshot of $MDM_VM, its own# hostname; then `start` it with MDM_VM=<name>+ tools/lab/linux-vm/vm.ps1 deploy <to VM> <label> # ~/lab/bin/<label> from $MDM_VM to another VM+ # (through a folder on the host), with the guest+ # scripts: a clone tests a build without making itIn the guest (~/lab, from `setup`):build.sh <ref> [label] a branch, PR (pr/<n>) or commit, built with the lab's vmtest profile@@ -28,6 +31,14 @@ In the guest (~/lab, from `setup`):checked against the lab server's logproxy-optin.mjs, chrome-popup.mjs the extension's popup: the proxy switch and its permissionprompt in Firefox; any check of the popup in Chrome+ win.sh (with win-host.sh on the host) one MDM kept running while several of its windows are+ shot in turn: start with a language, mode and theme, open, close,+ switch theme live, real clicks and keys inside the VM+ store-check.mjs a store package (.xpi, unpacked Chrome zip) installed, its popup, an+ ordinary download handed to MDM+ chrome-menu.mjs an HLS stream from Google Chrome's right-click menu (a real right-click+ in a Chrome window, which headless Chrome can't show)+ desktop.sh KDE Plasma, Cinnamon or XFCE beside GNOME in a clone, auto-login to ithandoff-minimized.sh, queue-minimized.sh hand-overs and the Scheduler while MDM is minimizedtorrent-menu.sh a torrent in the list with no network, for the torrent windowsuse-system-helpers.sh MDM uses the system's yt-dlp, ffmpeg and gallery-dl@@ -41,7 +52,7 @@ mdm-ubuntu, mdm, and the lab's throwaway password). Commands run with the desktoDISPLAY and D-Bus, so GUI programs open on the VM's screen.#>param(- [Parameter(Position = 0, Mandatory)] [ValidateSet('configure', 'start', 'setup', 'run', 'shot', 'get', 'put', 'clone')] [string] $Action,+ [Parameter(Position = 0, Mandatory)] [ValidateSet('configure', 'start', 'setup', 'run', 'shot', 'get', 'put', 'clone', 'deploy')] [string] $Action,[Parameter(Position = 1)] [string] $Arg1,[Parameter(Position = 2)] [string] $Arg2,[string] $Branch = 'main',@@ -56,12 +67,12 @@ $user = if ($env:MDM_VM_USER) { $env:MDM_VM_USER } else { 'mdm' }$pass = if ($env:MDM_VM_PASSWORD) { $env:MDM_VM_PASSWORD } else { 'mdm123456789' }$auth = @('--username', $user, '--password', $pass)-function Invoke-Guest([string] $Command) {+function Invoke-Guest([string] $Command, [string] $On = $vm) {# The desktop session's display and bus, so GUI programs and gsettings reach it.$session = 'export DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/$(id -u) DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus; ' +'export XAUTHORITY=$(ls /run/user/$(id -u)/gdm/Xauthority 2>/dev/null || echo $HOME/.Xauthority); ' +"export MDM_SUDO_PASSWORD='$pass'; [ -f ~/.cargo/env ] && . ~/.cargo/env; "- & $vbox guestcontrol $vm run --exe /bin/bash @auth --wait-stdout --wait-stderr -- -c ($session + $Command)+ & $vbox guestcontrol $On run --exe /bin/bash @auth --wait-stdout --wait-stderr -- -c ($session + $Command)if ($LASTEXITCODE) { throw "guest command failed ($LASTEXITCODE)" }}@@ -134,6 +145,34 @@ switch ($Action) {& $vbox guestcontrol $name run --exe /bin/bash @auth --wait-stdout --wait-stderr -- -c `"echo '$pass' | sudo -S -p '' hostnamectl set-hostname $name && echo '$pass' | sudo -S -p '' sed -i 's/$vm/$name/g' /etc/hosts && hostname"}+ 'deploy' {+ # The programs of one build, from the VM that built them to one that only tests (a clone+ # with another desktop): no toolchain or second build needed there. VirtualBox copies+ # between guest and host only, so through a folder on the host, removed afterwards.+ $to = $Arg1; $label = $Arg2+ if (-not $to -or -not $label) { throw 'deploy: <to VM> <label>' }+ $tmp = Join-Path ([IO.Path]::GetTempPath()) "mdm-lab-deploy-$label"+ Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue+ New-Item -ItemType Directory $tmp | Out-Null+ try {+ & $vbox guestcontrol $vm copyfrom @auth --recursive --target-directory "$tmp\\" "/home/$user/lab/bin/$label"+ if ($LASTEXITCODE) { throw "copy from $vm failed ($LASTEXITCODE)" }+ Invoke-Guest "mkdir -p ~/lab/bin && rm -rf ~/lab/bin/$label" -On $to+ & $vbox guestcontrol $to copyto @auth --recursive --target-directory "/home/$user/lab/bin/" (Join-Path $tmp $label)+ if ($LASTEXITCODE) { throw "copy to $to failed ($LASTEXITCODE)" }+ # The guest scripts too, so the clone runs the same harnesses as the lab: copied beside+ # and renamed into place, since bash reads a running script as it goes (a build.sh+ # overwritten mid-build broke at its next line).+ $files = Get-ChildItem $PSScriptRoot -File | Where-Object { $_.Extension -in '.sh', '.mjs', '.py' -and $_.Name -notlike '*-host.sh' } | ForEach-Object FullName+ Invoke-Guest 'rm -rf ~/lab/.incoming && mkdir -p ~/lab/.incoming' -On $to+ & $vbox guestcontrol $to copyto @auth --target-directory /home/$user/lab/.incoming/ @files+ Invoke-Guest 'mv -f ~/lab/.incoming/* ~/lab/ && rmdir ~/lab/.incoming' -On $to+ # The copy keeps no file modes: the programs made runnable again.+ Invoke-Guest "chmod +x ~/lab/bin/$label/* && ls -l ~/lab/bin/$label" -On $to+ } finally {+ Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue+ }+ }'run' { Invoke-Guest $Arg1 }'shot' { & $vbox controlvm $vm screenshotpng ([IO.Path]::GetFullPath($Arg1)) }'get' { & $vbox guestcontrol $vm copyfrom @auth --target-directory $Arg2 $Arg1 }diff --git a/tools/lab/linux-vm/win-host.sh b/tools/lab/linux-vm/win-host.shnew file mode 100644index 00000000..81e052c0--- /dev/null+++ b/tools/lab/linux-vm/win-host.sh@@ -0,0 +1,33 @@+#!/bin/bash+# Host side (Git Bash on Windows) of win.sh: run one of its steps in the lab VM and, when the step+# printed a frame and an output file is given, crop VirtualBox's screenshot to it.+# win-host.sh <vm> <out.png|-> <win.sh step and its arguments>+# e.g. win-host.sh mdm-ubuntu - start pr-199 ar dark adwaita+# win-host.sh mdm-ubuntu shots/options.png open options+# Environment for the guest: MDM_STATE, MDM_SET, MDM_SETTLE, MDM_NATIVE_ACCENT, MDM_NATIVE_CONTRAST. The guest account+# from MDM_VM_USER (default mdm) and MDM_VM_PASSWORD (required).+V="${VBOXMANAGE:-/c/Program Files/Oracle/VirtualBox/VBoxManage.exe}"+user=${MDM_VM_USER:-mdm}+pass=${MDM_VM_PASSWORD:?set MDM_VM_PASSWORD to the lab account password}+vm=$1; out=$2; shift 2+env="MDM_STATE=${MDM_STATE:-} MDM_SET='${MDM_SET:-}' MDM_SETTLE=${MDM_SETTLE:-} MDM_ON=${MDM_ON:-} MDM_NATIVE_ACCENT=${MDM_NATIVE_ACCENT:-} MDM_NATIVE_CONTRAST=${MDM_NATIVE_CONTRAST:-}"+geo=$(MSYS_NO_PATHCONV=1 "$V" guestcontrol "$vm" run --exe /bin/bash --username "$user" --password "$pass" --timeout 150000 --wait-stdout -- \+ -c "$env bash /home/$user/lab/win.sh $*" 2>/dev/null | tail -1)+[ "$out" = - ] && { echo "$geo"; exit 0; }+case "$geo" in *[0-9]\ *[0-9]\ *[0-9]\ *[0-9]*) ;; *) echo "no frame from win.sh $* ($geo)" >&2; exit 1 ;; esac+mkdir -p "$(dirname "$out")"+full="${out%.png}.full.png"+"$V" controlvm "$vm" screenshotpng "$(cygpath -aw "$full")"+MDM_GROW=${MDM_GROW:-0} python - "$full" "$out" $geo <<'PY'+import os, sys+from PIL import Image+full, out, x, y, w, h = sys.argv[1], sys.argv[2], *map(int, sys.argv[3:7])+im = Image.open(full)+# MDM_GROW: pixels more on every side (a menu that opens past the window's edge).+g = int(os.environ.get("MDM_GROW") or 0); x, y, w, h = x - g, y - g, w + 2 * g, h + 2 * g+# A frame partly off the screen is clipped to it.+box = (max(x, 0), max(y, 0), min(x + w, im.width), min(y + h, im.height))+im.crop(box).save(out, optimize=True)+print(out, *box)+PY+rm -f -- "$full"diff --git a/tools/lab/linux-vm/win.sh b/tools/lab/linux-vm/win.shnew file mode 100644index 00000000..5402b8f3--- /dev/null+++ b/tools/lab/linux-vm/win.sh@@ -0,0 +1,132 @@+#!/bin/bash+# One MDM kept running while the host screenshots several of its windows in turn (faster than+# shots.sh, which restarts MDM for each): start it once with a language, mode and theme, then+# open, shoot and close windows one by one. Each `open` prints the window's frame as "X Y W H"+# for the host to crop VirtualBox's screenshot to (shot-host.sh's way).+#+# win.sh start <label> <lang> <light|dark|system> [theme] MDM restarted with these settings+# (system: Dark Mode support, following the desktop; theme:+# classic, native, high-contrast, metro, adwaita, breeze…)+# win.sh open <main|fileinfo|show name> e.g. options, scheduler, addurl, progress,+# properties, about, menu:3:theme+# win.sh close every MDM window but the main one, closed as a person would+# win.sh theme <id> View → Theme → <id>, live (/show theme:<id>)+# win.sh click|hover|press|release <x> <y> real input at a point of the main window's frame+# (MDM_ON=last: of the window last opened)+# win.sh key <key>... keys to the focused window (xdotool names)+# win.sh stop MDM ended+#+# MDM_STATE: a saved downloads.json put back first (as shots.sh); MDM_SET: more settings, a JSON+# object (e.g. '{"net_adapter":"none0"}'). MDM_NATIVE_ACCENT and+# MDM_NATIVE_CONTRAST pass through to MDM (the Native theme's stand-ins for the system's).+. ~/lab/env.sh+data=$HOME/.local/share/misterdownloadmanager+state=/tmp/mdm-win.state+cmd=$1; shift++frame() { # the window's frame, widened by the window manager's title bar and borders+ local win=$1 l r t b+ read -r l r t b < <(timeout 5 xprop -id "$win" _NET_FRAME_EXTENTS | grep -o '[0-9]\+' | tr '\n' ' ')+ timeout 5 xwininfo -id "$win" | awk -v l="${l:-0}" -v r="${r:-0}" -v t="${t:-0}" -v b="${b:-0}" '/Absolute upper-left X/ {x=$4} /Absolute upper-left Y/ {y=$4} /Width:/ {w=$2} /Height:/ {h=$2}+ END {print x - l, y - t, w + l + r, h + t + b}'+}+mine() { wmctrl -lp | awk -v p="$PID" '$3 == p {print $1}'; }++case "$cmd" in+ start)+ label=$1; lang=$2; mode=$3; theme=${4:-classic}+ app=$HOME/lab/bin/$label/misterdownloadmanager+ # The last MDM gone for good first: a new one started while it still ends hands its command+ # line to it and leaves, and nothing is left running.+ pkill -x misterdownloadm+ for _ in $(seq 20); do pgrep -x misterdownloadm >/dev/null || break; sleep 0.5; done+ pkill -9 -x misterdownloadm; sleep 1+ [ -n "${MDM_STATE:-}" ] && cp "$MDM_STATE" "$data/downloads.json"+ python3 - "$data/downloads.json" "$lang" "$mode" "$theme" <<'PY'+import json, os, sys+p, lang, mode, theme = sys.argv[1:5]+d = json.load(open(p))+s = d.setdefault("settings", {})+s.update(language=lang, language_asked=True, always_dark=(mode == "dark"),+ dark_mode_support=(mode != "light"), theme=theme)+s.update(json.loads(os.environ.get("MDM_SET") or "{}"))+json.dump(d, open(p, "w"))+PY+ # The pointer parked at the screen's right edge, so no hover or tooltip shows in a shot.+ read -r sw sh < <(xdotool getdisplaygeometry); xdotool mousemove $((sw - 2)) $((sh / 2))+ cd ~; setsid -f "$app" >/tmp/mdm-win.log 2>&1 </dev/null+ for _ in $(seq 60); do+ PID=$(pgrep -f "^$app$" | head -1)+ [ -n "$PID" ] && [ -n "$(mine)" ] && break+ sleep 1+ done+ main=$(mine | head -1)+ echo "PID=$PID MAIN=$main APP=$app" > "$state"+ sleep 4+ timeout 5 wmctrl -i -a "$main"; sleep 1+ frame "$main"+ ;;+ open)+ . "$state"+ show=$1+ before=$(mine | tr '\n' ' ')+ case "$show" in+ main) ;;+ fileinfo) timeout 20 "$APP" /d "http://127.0.0.1:8097/gen/1M/shot.zip" ;;+ *) timeout 20 "$APP" /show "$show" ;;+ esac+ win=$MAIN+ for _ in $(seq 40); do+ case "$show" in main|menu:*|theme:*) break ;; esac+ new=$(mine | grep -v -F -x -f <(echo "$before" | tr ' ' '\n' | grep .) | tail -1)+ [ -n "$new" ] && win=$new && break+ sleep 0.5+ done+ sleep 2+ timeout 5 wmctrl -i -a "$win"; sleep 1+ sed -i '/^LAST=/d' "$state"; echo "LAST=$win" >> "$state"+ frame "$win"+ ;;+ close)+ . "$state"+ read -r sw sh < <(xdotool getdisplaygeometry); xdotool mousemove $((sw - 2)) $((sh / 2))+ for w in $(mine); do [ "$w" != "$MAIN" ] && timeout 5 wmctrl -i -c "$w"; done+ sleep 1.5+ # A menu or popup inside the main window: Escape closes it.+ timeout 5 xdotool key --window "$MAIN" Escape 2>/dev/null; sleep 0.5+ ;;+ theme)+ . "$state"+ timeout 20 "$APP" /show "theme:$1"; sleep 2+ frame "$MAIN"+ ;;+ click|hover|press|release)+ # Real input inside the VM: the pointer moved to <x> <y> in the main window's frame (a+ # negative x counts from its right edge, for right-to-left languages), then a click, a button+ # held down or let go, or nothing. Prints the main window's frame. (`/show menu:…` opens the+ # wrong popup on X11, so menus are opened as a person would.)+ . "$state"+ # MDM_ON=last: the point is in the window `open` showed last instead.+ target=$MAIN; [ "${MDM_ON:-}" = last ] && target=${LAST:-$MAIN}+ read -r fx fy fw fh < <(frame "$target")+ x=$1; y=$2; [ "$x" -lt 0 ] && x=$((fw + x))+ xdotool mousemove $((fx + x)) $((fy + y)); sleep 0.4+ case "$cmd" in+ click) xdotool click 1 ;;+ press) xdotool mousedown 1 ;;+ release) xdotool mouseup 1 ;;+ esac+ sleep "${MDM_SETTLE:-1.2}"+ echo "$fx $fy $fw $fh"+ ;;+ key)+ # Keys to the focused window, one by one: e.g. `key Tab Tab space`.+ for k in "$@"; do xdotool key "$k"; sleep 0.3; done+ sleep 0.8+ . "$state"; frame "$MAIN"+ ;;+ stop)+ pkill -x misterdownloadm+ ;;+ *) echo "win.sh start|open|close|theme|click|hover|press|release|key|stop"; exit 2 ;;+esac