256 lines
13 KiB
JavaScript
256 lines
13 KiB
JavaScript
#!/usr/bin/env node
|
|
// Steuert die Client-Oberfläche über das Debug-Port - ohne Koordinaten.
|
|
//
|
|
// node cdp.mjs --text # sichtbare Texte auflisten
|
|
// node cdp.mjs --click "Join" # Element über seinen Text klicken
|
|
// node cdp.mjs --eval "<js>" # beliebigen Ausdruck auswerten
|
|
//
|
|
// Die Seite wird über ihren Zieldaten ermittelt; geklickt wird der kleinste
|
|
// passende Knoten, damit nicht ein umschliessender Container getroffen wird.
|
|
|
|
// Dieselbe Regel wie client/umgebung.cdp_port: CDP_PORT, sonst der Klon (9402). Den Client (9333)
|
|
// erreicht es nur mit ausdruecklichem Port - der Betriebssatz (umgebung.betrieb_am_client) setzt ihn.
|
|
// Bis 6.11. nahm es ohne Angabe den Client (archiv/mitschrieb/VORFAELLE.md).
|
|
const PORT = process.env.CDP_PORT || 9402;
|
|
const args = process.argv.slice(2);
|
|
|
|
function flag(name) {
|
|
const i = args.indexOf(name);
|
|
return i < 0 ? null : (args[i + 1] ?? true);
|
|
}
|
|
|
|
async function seite() {
|
|
const liste = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();
|
|
return liste.find((t) => t.type === "page" && (t.url || "").includes("lobby"))
|
|
|| liste.find((t) => t.type === "page");
|
|
}
|
|
|
|
// Ein Klick, drei Wege (hand/eingabe.py): mit EINGABE=maus nur die Bildschirmlage ("MAUS {x,y}")
|
|
// - den Klick macht Python; sonst ein ECHTER Klick über CDP `Input.dispatchMouseEvent` ("CDP {x,y}",
|
|
// isTrusted:true wie eine Hand); mit EINGABE=js die alten synthetischen DOM-Ereignisse als Rueckfall.
|
|
// Alle Klicks dieser Datei und mcp/lobby_adapter.KLICK_ZEILE gehen hierüber.
|
|
const MAUS = process.env.EINGABE === "maus";
|
|
const JS_KLICK = process.env.EINGABE === "js";
|
|
const VORSPANN = `window.__pfMaus = ${MAUS}; window.__pfJs = ${JS_KLICK};
|
|
window.__pfKlick = (ziel) => {
|
|
// Was nicht im Bild steht, trifft kein Mausklick: der Reiterstreifen scrollt waagerecht
|
|
// ("horizontal-scroll-container", overflow auto), die hinteren Reiter liegen ausserhalb des
|
|
// Fensters (31.10.: "Practice Games" bei x=1344 in einem 1280 breiten Fenster - der Punkt
|
|
// lag nicht im Fenster, der Klick wurde verweigert). Darum erst ins Bild holen, dann messen.
|
|
// behavior "instant" ist Pflicht: der Streifen hat scroll-behavior smooth, sonst wird sofort
|
|
// die ALTE Lage gemessen (gemessen).
|
|
try { ziel.scrollIntoView({block: "nearest", inline: "center", behavior: "instant"}); } catch (e) { /* egal */ }
|
|
const r = ziel.getBoundingClientRect();
|
|
if (window.__pfMaus) {
|
|
const kopf = window.outerHeight - window.innerHeight;
|
|
return "MAUS " + JSON.stringify({x: window.screenX + r.x + r.width / 2,
|
|
y: window.screenY + kopf + r.y + r.height / 2,
|
|
text: (ziel.innerText || "").trim().replace(/\\s+/g, " ").slice(0, 50)});
|
|
}
|
|
const mitte = { x: r.x + r.width / 2, y: r.y + r.height / 2,
|
|
text: (ziel.innerText || "").trim().replace(/\\s+/g, " ").slice(0, 50) };
|
|
// Nur echt klicken, wenn der Punkt auch trifft: liegt etwas davor, faellt es auf JS zurueck.
|
|
const oben = document.elementFromPoint(mitte.x, mitte.y);
|
|
const trifft = oben && (oben === ziel || ziel.contains(oben) || oben.contains(ziel));
|
|
if (!window.__pfJs && trifft) {
|
|
// Kein Sprung: der Zeiger faehrt hin (Hover wie eine Hand), erst dann faellt der Klick.
|
|
const ziel_ = { x: r.x + r.width * (0.2 + 0.6 * Math.random()),
|
|
y: r.y + r.height * (0.2 + 0.6 * Math.random()) };
|
|
const von = window.__pfZeiger || { x: ziel_.x - 40, y: ziel_.y + 60 };
|
|
const n = 3 + Math.floor(Math.random() * 4);
|
|
const pfad = [];
|
|
for (let i = 1; i <= n; i++) {
|
|
const t = i / n;
|
|
pfad.push([von.x + (ziel_.x - von.x) * t + (Math.random() - 0.5) * 6,
|
|
von.y + (ziel_.y - von.y) * t + (Math.random() - 0.5) * 6]);
|
|
}
|
|
window.__pfZeiger = { x: ziel_.x, y: ziel_.y };
|
|
return "CDP " + JSON.stringify({ pfad: pfad, text: mitte.text,
|
|
steh: Math.round(60 + Math.random() * 140) });
|
|
}
|
|
const opt = { bubbles: true, cancelable: true, composed: true, button: 0,
|
|
clientX: mitte.x, clientY: mitte.y };
|
|
for (const art of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
|
|
ziel.dispatchEvent(art.startsWith("pointer") ? new PointerEvent(art, opt) : new MouseEvent(art, opt));
|
|
}
|
|
return null;
|
|
};`;
|
|
|
|
const HOVER = `(() => {
|
|
const knoepfe = [...document.querySelectorAll('button, [role="button"]')]
|
|
.filter((n) => n.offsetParent !== null && n.innerText.trim());
|
|
if (!knoepfe.length) return "kein Knopf zum Zeigen";
|
|
const z = knoepfe[Math.floor(Math.random() * knoepfe.length)];
|
|
z.scrollIntoView({block: "nearest", inline: "center", behavior: "instant"});
|
|
const r = z.getBoundingClientRect();
|
|
const ziel_ = { x: r.x + r.width * (0.2 + 0.6 * Math.random()), y: r.y + r.height * (0.2 + 0.6 * Math.random()) };
|
|
const von = window.__pfZeiger || { x: ziel_.x - 60, y: ziel_.y + 80 };
|
|
const n = 4 + Math.floor(Math.random() * 4), pfad = [];
|
|
for (let i = 1; i <= n; i++) {
|
|
const t = i / n;
|
|
pfad.push([von.x + (ziel_.x - von.x) * t + (Math.random() - 0.5) * 8,
|
|
von.y + (ziel_.y - von.y) * t + (Math.random() - 0.5) * 8]);
|
|
}
|
|
window.__pfZeiger = ziel_;
|
|
return "CDP " + JSON.stringify({ pfad: pfad, text: (z.innerText || "").trim().slice(0, 40) });
|
|
})()`;
|
|
|
|
const SICHTBAR = `n.offsetParent !== null && (n.innerText || "").trim().length > 0`;
|
|
|
|
const KLICK = (text) => `(() => {
|
|
const wollen = ${JSON.stringify(text)}.trim().toLowerCase();
|
|
const alle = [...document.querySelectorAll('button, a, [role="button"], span, div, li')]
|
|
.filter((n) => ${SICHTBAR});
|
|
const genau = alle.filter((n) => (n.innerText || "").trim().toLowerCase() === wollen)
|
|
.sort((a, b) => {
|
|
const istKnopf = (n) => (n.tagName === 'BUTTON' ||
|
|
n.getAttribute('role') === 'button') ? 0 : 1;
|
|
if (istKnopf(a) !== istKnopf(b)) return istKnopf(a) - istKnopf(b);
|
|
const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect();
|
|
return ra.width * ra.height - rb.width * rb.height;
|
|
});
|
|
const teil = alle.filter((n) => (n.innerText || "").trim().toLowerCase().startsWith(wollen))
|
|
.sort((a, b) => {
|
|
const istKnopf = (n) => (n.tagName === 'BUTTON' ||
|
|
n.getAttribute('role') === 'button') ? 0 : 1;
|
|
if (istKnopf(a) !== istKnopf(b)) return istKnopf(a) - istKnopf(b);
|
|
const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect();
|
|
return ra.width * ra.height - rb.width * rb.height;
|
|
});
|
|
const ziel = genau[0] || teil[0];
|
|
if (!ziel) return "nichts gefunden fuer: " + wollen;
|
|
const r = ziel.getBoundingClientRect();
|
|
{ const maus = window.__pfKlick(ziel); if (maus) return maus; }
|
|
return "geklickt: " + (ziel.innerText || "").trim().replace(/\\s+/g, " ").slice(0, 50)
|
|
+ " [" + Math.round(r.width) + "x" + Math.round(r.height) + "]";
|
|
})()`;
|
|
|
|
const TEXTE = `(() => {
|
|
const knoten = [...document.querySelectorAll('button, a, [role="button"], span, div, th, td')]
|
|
.filter((n) => ${SICHTBAR} && n.children.length === 0);
|
|
const gesehen = new Set(); const aus = [];
|
|
for (const n of knoten) {
|
|
const t = (n.innerText || "").trim().replace(/\\s+/g, " ");
|
|
if (!t || t.length > 40 || gesehen.has(t)) continue;
|
|
gesehen.add(t); aus.push(t);
|
|
}
|
|
return aus.join(" | ");
|
|
})()`;
|
|
|
|
// Wie KLICK, aber der n-te Treffer (0-basiert, in Reihenfolge der Seite).
|
|
const KLICK_NTH = (text, n) => `(() => {
|
|
const wollen = ${JSON.stringify(text)}.trim().toLowerCase();
|
|
const treffer = [...document.querySelectorAll('button, a, [role="button"], span, div')]
|
|
.filter((k) => k.offsetParent !== null &&
|
|
(k.innerText || "").trim().toLowerCase() === wollen);
|
|
if (!treffer.length) return "nichts gefunden: " + wollen;
|
|
const ziel = treffer[Math.min(${Number(n) || 0}, treffer.length - 1)];
|
|
const r = ziel.getBoundingClientRect();
|
|
{ const maus = window.__pfKlick(ziel); if (maus) return maus; }
|
|
const zeile = (ziel.closest("tr, li, [class*=row], [class*=Row]") || ziel).innerText || "";
|
|
return "geklickt #" + ${Number(n) || 0} + " von " + treffer.length + ": "
|
|
+ zeile.replace(/\\s+/g, " ").slice(0, 60);
|
|
})()`;
|
|
|
|
// Klickt einen Knopf INNERHALB der Zeile, die einen Text enthält.
|
|
const KLICK_IN = (zeilenText, knopfText) => `(() => {
|
|
const zeile = ${JSON.stringify(zeilenText)}.trim().toLowerCase();
|
|
const knopf = ${JSON.stringify(knopfText)}.trim().toLowerCase();
|
|
const sichtbar = (n) => n.offsetParent !== null;
|
|
const flaeche = (n) => { const r = n.getBoundingClientRect(); return r.width * r.height; };
|
|
const treffer = [...document.querySelectorAll("*")]
|
|
.filter((n) => sichtbar(n) && (n.innerText || "").toLowerCase().includes(zeile))
|
|
.sort((a, b) => flaeche(a) - flaeche(b));
|
|
for (const z of treffer) {
|
|
const knoepfe = [...z.querySelectorAll('button, a, [role="button"], span, div')]
|
|
.filter((n) => sichtbar(n) && (n.innerText || "").trim().toLowerCase() === knopf)
|
|
.sort((a, b) => {
|
|
const istKnopf = (n) => (n.tagName === 'BUTTON' ||
|
|
n.getAttribute('role') === 'button') ? 0 : 1;
|
|
if (istKnopf(a) !== istKnopf(b)) return istKnopf(a) - istKnopf(b);
|
|
return flaeche(a) - flaeche(b);
|
|
});
|
|
if (!knoepfe.length) continue;
|
|
const ziel = knoepfe[0];
|
|
const r = ziel.getBoundingClientRect();
|
|
{ const maus = window.__pfKlick(ziel); if (maus) return maus; }
|
|
return "geklickt in Zeile '" + ${JSON.stringify(zeilenText)} + "': "
|
|
+ (ziel.innerText || "").trim().slice(0, 30);
|
|
}
|
|
return "kein Knopf '" + knopf + "' in der Zeile gefunden";
|
|
})()`;
|
|
|
|
async function main() {
|
|
const t = await seite();
|
|
if (!t) { console.log("keine Seite am Debug-Port"); process.exit(1); }
|
|
const ws = new WebSocket(t.webSocketDebuggerUrl);
|
|
await new Promise((ok, bad) => { ws.onopen = ok; ws.onerror = bad; });
|
|
let nr = 0; const wartend = new Map();
|
|
ws.onmessage = (e) => {
|
|
const m = JSON.parse(e.data);
|
|
if (m.id && wartend.has(m.id)) { wartend.get(m.id)(m); wartend.delete(m.id); }
|
|
};
|
|
const senden = (method, params = {}) => new Promise((res) => {
|
|
const i = ++nr; wartend.set(i, res); ws.send(JSON.stringify({ id: i, method, params }));
|
|
});
|
|
await senden("Runtime.enable");
|
|
const werten = async (expr, klicken = true) => {
|
|
const r = await senden("Runtime.evaluate",
|
|
{ expression: VORSPANN + "\n" + expr, returnByValue: true, awaitPromise: true });
|
|
if (r.result?.exceptionDetails) return "Fehler: " + JSON.stringify(r.result.exceptionDetails).slice(0, 300);
|
|
const wert = r.result?.result?.value;
|
|
if (typeof wert === "string" && wert.startsWith("CDP ")) { // echter Klick, wie eine Hand
|
|
const p = JSON.parse(wert.slice(4));
|
|
const [zx, zy] = p.pfad[p.pfad.length - 1];
|
|
for (const [x, y] of p.pfad) { // hinfahren, Stueck fuer Stueck
|
|
await senden("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "none" });
|
|
await new Promise((ok) => setTimeout(ok, 6 + Math.floor(Math.random() * 9)));
|
|
}
|
|
if (!klicken) return "gezeigt: " + p.text;
|
|
await new Promise((ok) => setTimeout(ok, p.steh)); // kurz stehen, dann druecken
|
|
await senden("Input.dispatchMouseEvent",
|
|
{ type: "mousePressed", x: zx, y: zy, button: "left", clickCount: 1 });
|
|
await new Promise((ok) => setTimeout(ok, 45 + Math.floor(Math.random() * 120)));
|
|
await senden("Input.dispatchMouseEvent",
|
|
{ type: "mouseReleased", x: zx, y: zy, button: "left", clickCount: 1 });
|
|
return "geklickt (echt): " + p.text;
|
|
}
|
|
return wert;
|
|
};
|
|
|
|
if (args.includes("--hover")) { // nur hinsehen: Zeiger auf einen Knopf
|
|
const wert = await werten(HOVER, false);
|
|
if (typeof wert === "string" && wert.startsWith("CDP ")) {
|
|
const p = JSON.parse(wert.slice(4));
|
|
for (const [x, y] of p.pfad) {
|
|
await senden("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "none" });
|
|
await new Promise((ok) => setTimeout(ok, 6 + Math.floor(Math.random() * 9)));
|
|
}
|
|
console.log("gezeigt: " + p.text);
|
|
} else console.log(wert);
|
|
ws.close(); return;
|
|
}
|
|
const klick = flag("--click");
|
|
if (klick) { console.log(await werten(KLICK(klick))); ws.close(); return; }
|
|
if (args.includes("--click-in")) {
|
|
const i = args.indexOf("--click-in");
|
|
console.log(await werten(KLICK_IN(args[i + 1], args[i + 2] || "Join")));
|
|
ws.close();
|
|
return;
|
|
}
|
|
if (args.includes("--click-nth")) {
|
|
const i = args.indexOf("--click-nth");
|
|
console.log(await werten(KLICK_NTH(args[i + 1], args[i + 2])));
|
|
ws.close();
|
|
return;
|
|
}
|
|
const js = args.includes("--eval") ? args[args.indexOf("--eval") + 1] : null;
|
|
if (js) { console.log(await werten(js)); ws.close(); return; }
|
|
console.log("Titel:", await werten("document.title"));
|
|
console.log("Adresse:", await werten("location.href"));
|
|
console.log("Texte:", await werten(TEXTE));
|
|
ws.close();
|
|
}
|
|
|
|
main().catch((e) => { console.error("Fehler:", e.message); process.exit(1); });
|