288 lines
15 KiB
JavaScript
Executable File
288 lines
15 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
||
// 用無頭 Chrome(不開視窗、自己的設定檔)操作 AnyBot 的手機頁面,像手機上的人一樣按、打字、截圖。
|
||
// 只用 Node 內建的 fetch 和 WebSocket(Node 22 以上),走 Chrome DevTools Protocol。
|
||
// 平常從 ctl 叫:`ctl phone <動作> …`(ctl 會帶 --state、--out、網址、憑證)。
|
||
//
|
||
// start --profile <資料夾> --spki <base64> [--home <資料夾>] [--chrome <路徑>] 開無頭 Chrome(只信任這張憑證的公鑰)
|
||
// open <網址> 打開頁面,等載入完
|
||
// wait <css> [秒] 等元素出現(看得見)
|
||
// wait-gone <css> [秒] 等元素消失或看不見
|
||
// wait-text <字> [--in <css>] [秒] 等畫面上出現這些字
|
||
// click <css> [--text <字>] 在元素正中間按一下(有 --text:符合 css 而且含這些字的那一個)
|
||
// long-press <css> [--text <字>] 在元素正中間用手指按住 0.8 秒再放開(手機的長按,例如訊息的選單)
|
||
// type <css> <字> | --file <檔> 點進輸入框、清空、像鍵盤一樣打進去(--file:字從檔案讀,密碼不進指令列)
|
||
// upload <css> <檔> 在檔案選擇欄(input type=file,可以是隱藏的)選這個檔案,等於系統的檔案選擇器選好按「打開」
|
||
// press <鍵> Enter、Escape、Tab、Backspace
|
||
// text [css] 印出看得到的字
|
||
// shot <名稱> 證據:<out>/NN-名稱.png(截圖)、.ax.txt(無障礙樹)、.txt(看得到的字)
|
||
// js <運算式> 只給除錯用(印出結果),證明不要靠它
|
||
// stop 關掉這個 Chrome
|
||
|
||
import { spawn } from "node:child_process";
|
||
import fs from "node:fs";
|
||
import path from "node:path";
|
||
|
||
const argv = process.argv.slice(2);
|
||
const opt = (name) => {
|
||
const i = argv.indexOf(name);
|
||
if (i < 0) return undefined;
|
||
const v = argv[i + 1];
|
||
argv.splice(i, 2);
|
||
return v;
|
||
};
|
||
const STATE = opt("--state");
|
||
const OUT = opt("--out");
|
||
const PROFILE = opt("--profile");
|
||
const SPKI = opt("--spki");
|
||
const CHROME = opt("--chrome") || process.env.ABV_CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
|
||
const IN = opt("--in");
|
||
const TEXT = opt("--text");
|
||
const FILE = opt("--file");
|
||
const HOME = opt("--home");
|
||
const [cmd, ...rest] = argv;
|
||
|
||
const die = (msg) => { console.error(`phone:${msg}`); process.exit(1); };
|
||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||
if (!STATE) die("少了 --state");
|
||
if (typeof WebSocket === "undefined") die("這個 Node 沒有內建 WebSocket(要 Node 22 以上)");
|
||
|
||
async function start() {
|
||
if (!PROFILE || !SPKI) die("start 要 --profile 和 --spki");
|
||
if (!fs.existsSync(CHROME)) die(`找不到 Chrome:${CHROME}(用 --chrome 或 ABV_CHROME 指定)`);
|
||
fs.mkdirSync(PROFILE, { recursive: true });
|
||
const portFile = path.join(PROFILE, "DevToolsActivePort");
|
||
fs.rmSync(portFile, { force: true });
|
||
const log = fs.openSync(path.join(PROFILE, "..", "chrome.log"), "a");
|
||
const args = [
|
||
"--headless=new", `--user-data-dir=${PROFILE}`, "--remote-debugging-port=0",
|
||
// 不碰鑰匙圈、不連 Google 的背景服務、不開第一次使用畫面。
|
||
"--use-mock-keychain", "--no-first-run", "--no-default-browser-check", "--disable-background-networking",
|
||
"--disable-component-update", "--disable-sync", "--disable-default-apps", "--disable-extensions",
|
||
"--disable-domain-reliability", "--metrics-recording-only", "--no-pings", "--disable-breakpad", "--disable-crash-reporter",
|
||
"--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider,AutofillServerCommunication,CertificateTransparencyComponentUpdater",
|
||
// 像一支 iPhone:裝置名稱 AnyBot 從 User-Agent 認成「iPhone」。無頭視窗最窄 500,畫面大小
|
||
// (390×844、2 倍)由每個動作連上時設定(connect)。
|
||
"--window-size=390,844", "--force-device-scale-factor=2",
|
||
"--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 AnyBotVerify",
|
||
// 信任憑證:只信這台 scratch AnyBot 自己做的那一張(它的公鑰),不是關掉所有檢查。
|
||
`--ignore-certificate-errors-spki-list=${SPKI}`,
|
||
"about:blank",
|
||
];
|
||
// HOME 也換成 scratch 的(看 HOME 的東西就落在 scratch)。macOS 上當機回報程式照樣用真的
|
||
// ~/Library/Application Support/Google/Chrome/Crashpad(只碰 settings.dat),SKILL.md 的陷阱有寫。
|
||
const env = HOME ? { ...process.env, HOME } : process.env;
|
||
const child = spawn(CHROME, args, { detached: true, stdio: ["ignore", log, log], env });
|
||
child.unref();
|
||
for (let i = 0; i < 150; i++) {
|
||
if (fs.existsSync(portFile)) {
|
||
const port = Number(fs.readFileSync(portFile, "utf8").split("\n")[0]);
|
||
if (port) {
|
||
fs.writeFileSync(STATE, JSON.stringify({ pid: child.pid, port, profile: PROFILE }));
|
||
console.log(`chrome pid ${child.pid} devtools 127.0.0.1:${port}`);
|
||
return;
|
||
}
|
||
}
|
||
await sleep(100);
|
||
}
|
||
try { process.kill(child.pid, "SIGKILL"); } catch (_) {}
|
||
die("Chrome 15 秒內沒有開好(看 chrome.log)");
|
||
}
|
||
|
||
function state() {
|
||
if (!fs.existsSync(STATE)) die("Chrome 還沒開:先 `ctl phone start`");
|
||
return JSON.parse(fs.readFileSync(STATE, "utf8"));
|
||
}
|
||
|
||
async function connect() {
|
||
const { port } = state();
|
||
let list;
|
||
try { list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); } catch (e) { die(`連不上 Chrome(${e.message}):先 \`ctl phone start\``); }
|
||
let page = list.find((t) => t.type === "page");
|
||
if (!page) page = await (await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" })).json();
|
||
const ws = new WebSocket(page.webSocketDebuggerUrl);
|
||
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = () => rej(new Error("websocket")); });
|
||
let id = 0;
|
||
const pending = new Map();
|
||
const events = [];
|
||
ws.onmessage = (ev) => {
|
||
const m = JSON.parse(ev.data);
|
||
if (m.id && pending.has(m.id)) {
|
||
const { res, rej, timer } = pending.get(m.id);
|
||
clearTimeout(timer);
|
||
pending.delete(m.id);
|
||
m.error ? rej(new Error(m.error.message)) : res(m.result);
|
||
} else events.push(m);
|
||
};
|
||
const send = (method, params = {}) => new Promise((res, rej) => {
|
||
const i = ++id;
|
||
const timer = setTimeout(() => pending.has(i) && (pending.delete(i), rej(new Error(`${method} 逾時`))), 30000);
|
||
pending.set(i, { res, rej, timer });
|
||
ws.send(JSON.stringify({ id: i, method, params }));
|
||
});
|
||
const evaluate = async (expr) => {
|
||
const r = await send("Runtime.evaluate", { expression: expr, returnByValue: true, awaitPromise: true });
|
||
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text);
|
||
return r.result.value;
|
||
};
|
||
// 手機大小(390×844、2 倍):無頭 Chrome 的視窗最窄 500,所以每次連上都設一次(離開時 Chrome 會還原)。
|
||
await send("Emulation.setDeviceMetricsOverride", { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
|
||
await evaluate("new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))").catch(() => {});
|
||
return { send, evaluate, events, close: () => ws.close() };
|
||
}
|
||
|
||
const q = (s) => JSON.stringify(s);
|
||
// The element: the first visible match of css (with TEXT: the first whose text contains it).
|
||
const finder = (css, text) => `(() => {
|
||
const vis = (e) => { const r = e.getBoundingClientRect(); const s = getComputedStyle(e); return r.width > 0 && r.height > 0 && s.visibility !== "hidden" && s.display !== "none"; };
|
||
const all = [...document.querySelectorAll(${q(css)})].filter(vis);
|
||
return ${text ? `all.find((e) => (e.innerText || e.value || e.title || e.getAttribute("aria-label") || "").includes(${q(text)}))` : "all[0]"} || null;
|
||
})()`;
|
||
|
||
async function waitFor(c, expr, secs, what) {
|
||
const until = Date.now() + secs * 1000;
|
||
while (Date.now() < until) {
|
||
if (await c.evaluate(expr).catch(() => false)) return;
|
||
await sleep(200);
|
||
}
|
||
die(`等了 ${secs} 秒還沒有:${what}`);
|
||
}
|
||
|
||
// The middle of the element, once it is there and has stopped moving (sheets and pages slide in):
|
||
// up to 10 seconds, like a person waiting for the screen to settle before tapping.
|
||
async function center(c, css, text) {
|
||
let last = null;
|
||
for (const until = Date.now() + 10000; Date.now() < until; await sleep(120)) {
|
||
const r = await c.evaluate(`(() => { const e = ${finder(css, text)}; if (!e) return null; e.scrollIntoView({block: "center"}); const b = e.getBoundingClientRect(); return {x: b.left + b.width / 2, y: b.top + b.height / 2}; })()`).catch(() => null);
|
||
if (r && last && Math.abs(r.x - last.x) < 0.5 && Math.abs(r.y - last.y) < 0.5) return r;
|
||
last = r;
|
||
}
|
||
die(`10 秒內找不到停住、看得見的 ${css}${text ? `(含「${text}」)` : ""}`);
|
||
}
|
||
|
||
async function mouseClick(c, x, y) {
|
||
await c.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y });
|
||
await c.send("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "left", clickCount: 1 });
|
||
await c.send("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "left", clickCount: 1 });
|
||
}
|
||
|
||
const KEYS = { Enter: [13, "\r"], Escape: [27, ""], Tab: [9, "\t"], Backspace: [8, ""] };
|
||
async function press(c, key) {
|
||
const [code, text] = KEYS[key] || die(`不認得的鍵:${key}(Enter、Escape、Tab、Backspace)`);
|
||
await c.send("Input.dispatchKeyEvent", { type: "keyDown", key, code: key, windowsVirtualKeyCode: code, text: text || undefined });
|
||
await c.send("Input.dispatchKeyEvent", { type: "keyUp", key, code: key, windowsVirtualKeyCode: code });
|
||
}
|
||
|
||
function nextName(name) {
|
||
if (!OUT) die("少了 --out");
|
||
fs.mkdirSync(OUT, { recursive: true });
|
||
const n = fs.readdirSync(OUT).filter((f) => f.endsWith(".png")).length + 1;
|
||
return path.join(OUT, `${String(n).padStart(2, "0")}-${name.replace(/[^\p{L}\p{N}_-]+/gu, "-")}`);
|
||
}
|
||
|
||
async function axText(c) {
|
||
const { nodes } = await c.send("Accessibility.getFullAXTree");
|
||
const byId = new Map(nodes.map((n) => [n.nodeId, n]));
|
||
const lines = [];
|
||
const walk = (n, depth) => {
|
||
if (!n) return;
|
||
const role = n.role?.value || "";
|
||
const name = (n.name?.value || "").replace(/\s+/g, " ").trim();
|
||
const shown = !n.ignored && name && !["none", "generic", "InlineTextBox", "LineBreak"].includes(role);
|
||
if (shown) lines.push(`${" ".repeat(depth)}${role} "${name.slice(0, 160)}"`);
|
||
for (const id of n.childIds || []) walk(byId.get(id), shown ? depth + 1 : depth);
|
||
};
|
||
walk(nodes[0], 0);
|
||
return lines.join("\n") + "\n";
|
||
}
|
||
|
||
async function main() {
|
||
if (cmd === "start") return start();
|
||
if (cmd === "stop") {
|
||
const st = fs.existsSync(STATE) ? JSON.parse(fs.readFileSync(STATE, "utf8")) : null;
|
||
if (!st) return console.log("Chrome 沒有開著");
|
||
try {
|
||
const v = await (await fetch(`http://127.0.0.1:${st.port}/json/version`)).json();
|
||
const ws = new WebSocket(v.webSocketDebuggerUrl);
|
||
await new Promise((res) => { ws.onopen = res; ws.onerror = res; });
|
||
ws.send(JSON.stringify({ id: 1, method: "Browser.close" }));
|
||
} catch (_) {}
|
||
for (let i = 0; i < 50; i++) {
|
||
try { process.kill(st.pid, 0); } catch (_) { fs.rmSync(STATE, { force: true }); return console.log(`Chrome ${st.pid} 已關閉`); }
|
||
await sleep(100);
|
||
}
|
||
try { process.kill(st.pid, "SIGKILL"); } catch (_) {}
|
||
fs.rmSync(STATE, { force: true });
|
||
return console.log(`Chrome ${st.pid} 強制結束`);
|
||
}
|
||
const c = await connect();
|
||
try {
|
||
switch (cmd) {
|
||
case "open": {
|
||
await c.send("Page.enable");
|
||
await c.send("Page.navigate", { url: rest[0] || die("open 要網址") });
|
||
await waitFor(c, `document.readyState === "complete" && location.href !== "about:blank"`, 20, "頁面載入");
|
||
console.log(await c.evaluate("location.href"));
|
||
break;
|
||
}
|
||
case "wait": await waitFor(c, `!!${finder(rest[0] || die("wait 要 css"), TEXT)}`, Number(rest[1] || 20), rest[0]); break;
|
||
case "wait-gone": await waitFor(c, `!${finder(rest[0] || die("wait-gone 要 css"), TEXT)}`, Number(rest[1] || 20), `${rest[0]} 消失`); break;
|
||
case "wait-text": {
|
||
const t = rest[0] || die("wait-text 要字");
|
||
await waitFor(c, `((${IN ? `document.querySelector(${q(IN)})` : "document.body"}) || {innerText: ""}).innerText.includes(${q(t)})`, Number(rest[1] || 30), `「${t}」${IN ? `在 ${IN}` : ""}`);
|
||
break;
|
||
}
|
||
case "click": {
|
||
const { x, y } = await center(c, rest[0] || die("click 要 css"), TEXT);
|
||
await mouseClick(c, x, y);
|
||
break;
|
||
}
|
||
case "long-press": {
|
||
// 手指按住(觸控,不是滑鼠):頁面看 touchstart 之後有沒有放開,按滿 0.8 秒才放。
|
||
const { x, y } = await center(c, rest[0] || die("long-press 要 css"), TEXT);
|
||
await c.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 });
|
||
await c.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] });
|
||
await sleep(800);
|
||
await c.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
|
||
break;
|
||
}
|
||
case "upload": {
|
||
// 系統的檔案選擇器開不了(無頭):直接把檔案放進那個 input,頁面照樣收到 change。
|
||
const file = rest[1] || die("upload 要 css 和檔案");
|
||
if (!fs.existsSync(file)) die(`沒有這個檔案:${file}`);
|
||
const { root } = await c.send("DOM.getDocument", { depth: 0 });
|
||
const { nodeId } = await c.send("DOM.querySelector", { nodeId: root.nodeId, selector: rest[0] });
|
||
if (!nodeId) die(`找不到 ${rest[0]}`);
|
||
await c.send("DOM.setFileInputFiles", { nodeId, files: [path.resolve(file)] });
|
||
break;
|
||
}
|
||
case "type": {
|
||
const css = rest[0];
|
||
const text = FILE ? fs.readFileSync(FILE, "utf8").trim() : rest[1];
|
||
if (!css || text === undefined) die("type 要 css 和字(或 --file)");
|
||
const { x, y } = await center(c, css);
|
||
await mouseClick(c, x, y);
|
||
await c.evaluate(`(() => { const e = document.activeElement; if (e && "value" in e) { e.value = ""; e.dispatchEvent(new Event("input", {bubbles: true})); } })()`);
|
||
await c.send("Input.insertText", { text });
|
||
break;
|
||
}
|
||
case "press": await press(c, rest[0] || die("press 要鍵")); break;
|
||
case "text": console.log(await c.evaluate(`((${rest[0] ? `document.querySelector(${q(rest[0])})` : "document.body"}) || {innerText: ""}).innerText`)); break;
|
||
case "shot": {
|
||
const base = nextName(rest[0] || "shot");
|
||
const { data } = await c.send("Page.captureScreenshot", { format: "png" });
|
||
fs.writeFileSync(`${base}.png`, Buffer.from(data, "base64"));
|
||
fs.writeFileSync(`${base}.ax.txt`, await axText(c));
|
||
fs.writeFileSync(`${base}.txt`, `${await c.evaluate("location.href")}\n\n${await c.evaluate("document.body.innerText")}\n`);
|
||
console.log(`${base}.png`);
|
||
break;
|
||
}
|
||
case "js": console.log(JSON.stringify(await c.evaluate(rest[0] || die("js 要一段運算式")), null, 2)); break;
|
||
default: die(`不認得的動作:${cmd ?? "(空的)"}`);
|
||
}
|
||
} finally {
|
||
c.close();
|
||
}
|
||
}
|
||
|
||
main().then(() => process.exit(0), (e) => die(e.message));
|