| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285 |
- import dbus from "dbus-next";
- const { sessionBus, Variant, MessageType } = dbus;
- const REQUEST_IFACE = "org.freedesktop.portal.Request";
- const PORTAL_NAME = "org.freedesktop.portal.Desktop";
- const PORTAL_PATH = "/org/freedesktop/portal/desktop";
- const SOURCE_TYPE_MONITOR = 1;
- const CURSOR_MODE_EMBEDDED = 2;
- function unwrap(v) {
- if (v instanceof Variant) return unwrap(v.value);
- return v;
- }
- function fail(stage, code) {
- throw new Error(`${stage} failed with response ${code}`);
- }
- function summarizeResults(results, verbose) {
- if (!results || typeof results !== "object") return String(results);
- const keys = Object.keys(results);
- const out = { keys };
- if (verbose) {
- try {
- out.dump = JSON.stringify(results, replacer, 2);
- } catch (e) {
- out.dump = `(could not stringify: ${e.message})`;
- }
- }
- return out;
- }
- /**
- * @param {import('dbus-next').MessageBus} bus
- * @param {string} step — label for logs
- * @param {() => Promise<string>} callMethod — returns Request `handle` (object path)
- * @param {{ trace: boolean; verbose: boolean }} logOpts
- */
- async function waitPortalResponse(bus, step, callMethod, logOpts) {
- const { trace, verbose } = logOpts;
- if (trace) console.info(`[portal] ${step}: calling D-Bus method…`);
- const handlePath = await callMethod();
- if (trace) {
- console.info(`[portal] ${step}: method returned request handle:`, handlePath);
- }
- if (typeof handlePath !== "string" || !handlePath.startsWith("/")) {
- throw new Error(
- `Portal did not return a request object path (got ${typeof handlePath}: ${String(handlePath)})`,
- );
- }
- const match = `type='signal',interface='${REQUEST_IFACE}',member='Response',path='${handlePath}'`;
- if (verbose) {
- console.info(`[portal] ${step}: AddMatch rule:`, match);
- }
- return new Promise((resolve, reject) => {
- let settled = false;
- const onMsg = (msg) => {
- if (msg.type !== MessageType.SIGNAL) return;
- if (msg.path !== handlePath) return;
- if (msg.interface !== REQUEST_IFACE) return;
- if (msg.member !== "Response") return;
- if (settled) return;
- settled = true;
- bus.removeListener("message", onMsg);
- bus._removeMatch(match).catch(() => {});
- const code = msg.body[0];
- const results = msg.body[1] || {};
- if (trace) {
- console.info(`[portal] ${step}: Response signal received, code=${code}`);
- console.info(`[portal] ${step}: results summary:`, summarizeResults(results, verbose));
- }
- if (verbose) {
- console.info(`[portal] ${step}: raw msg.signature=`, msg.signature, "body length=", msg.body?.length);
- }
- resolve({ code, results });
- };
- bus.on("message", onMsg);
- bus
- ._addMatch(match)
- .then(() => {
- if (trace) {
- console.info(`[portal] ${step}: AddMatch registered; waiting for Response on`);
- console.info(`[portal] ${step}: ${handlePath}`);
- }
- })
- .catch((err) => {
- if (!settled) {
- settled = true;
- bus.removeListener("message", onMsg);
- reject(err);
- }
- });
- });
- }
- /**
- * PipeWire node id from Start results: `streams` is `a(ua{sv})` → [[nodeId, props], ...].
- */
- function extractNodeId(results, verbose) {
- const streamsRaw = results.streams;
- if (verbose) {
- console.info("[portal] Start: raw results.streams type=", typeof streamsRaw);
- try {
- console.info(
- "[portal] Start: streams (verbose)=",
- JSON.stringify(streamsRaw, replacer, 2),
- );
- } catch (e) {
- console.info("[portal] Start: streams not JSON-serializable:", e.message);
- }
- }
- const streams = unwrap(streamsRaw);
- if (!Array.isArray(streams) || streams.length === 0) {
- return null;
- }
- const first = streams[0];
- if (Array.isArray(first) && first.length > 0) {
- const id = unwrap(first[0]);
- if (id !== undefined && id !== null) {
- if (typeof id === "bigint") return Number(id);
- return Number(id);
- }
- }
- return null;
- }
- /**
- * @param {{ verbose?: boolean; trace?: boolean }} [options]
- * - trace: step-by-step portal logs (default true unless NEBUCAST_PORTAL_TRACE=0)
- * - verbose: extra dumps (default: argv --verbose or NEBUCAST_VERBOSE=1)
- */
- export async function negotiateScreencastPortal(options = {}) {
- const envTrace = process.env.NEBUCAST_PORTAL_TRACE !== "0";
- const envVerbose =
- process.env.NEBUCAST_VERBOSE === "1" || process.env.DEBUG?.includes("nebucast");
- const trace = options.trace !== false && envTrace;
- const verbose = Boolean(options.verbose || envVerbose);
- const logOpts = { trace, verbose };
- if (trace) {
- console.info("[portal] connecting session D-Bus (negotiateUnixFd=true)…");
- }
- const bus = sessionBus({ negotiateUnixFd: true });
- await new Promise((resolve, reject) => {
- if (bus.name) resolve();
- else {
- bus.once("connect", resolve);
- bus.once("error", reject);
- }
- });
- if (trace) {
- console.info("[portal] bus connected, unique name:", bus.name);
- }
- bus.on("error", (err) => {
- console.error("[portal] bus error:", err?.stack || err?.message || err);
- });
- let n = 0;
- const nextToken = () => `sc${++n}`;
- if (trace) {
- console.info("[portal] introspecting", PORTAL_NAME, PORTAL_PATH);
- }
- const portal = await bus.getProxyObject(PORTAL_NAME, PORTAL_PATH);
- const sc = portal.getInterface("org.freedesktop.portal.ScreenCast");
- let t = nextToken();
- if (trace) console.info("[portal] CreateSession handle_token=", t);
- const r1 = await waitPortalResponse(
- bus,
- "CreateSession",
- () =>
- sc.CreateSession({
- handle_token: new Variant("s", t),
- session_handle_token: new Variant("s", "nebucast_session"),
- }),
- logOpts,
- );
- if (r1.code !== 0) fail("CreateSession", r1.code);
- const sessionPath = unwrap(r1.results.session_handle);
- if (typeof sessionPath !== "string") {
- throw new Error("CreateSession: missing session_handle");
- }
- console.info("[portal] session:", sessionPath);
- t = nextToken();
- if (trace) console.info("[portal] SelectSources handle_token=", t);
- const r2 = await waitPortalResponse(
- bus,
- "SelectSources",
- () =>
- sc.SelectSources(sessionPath, {
- handle_token: new Variant("s", t),
- types: new Variant("u", SOURCE_TYPE_MONITOR),
- cursor_mode: new Variant("u", CURSOR_MODE_EMBEDDED),
- }),
- logOpts,
- );
- if (r2.code !== 0) fail("SelectSources", r2.code);
- console.info("[portal] source selected, starting…");
- t = nextToken();
- if (trace) console.info("[portal] Start handle_token=", t);
- const r3 = await waitPortalResponse(
- bus,
- "Start",
- () =>
- sc.Start(sessionPath, "", {
- handle_token: new Variant("s", t),
- }),
- logOpts,
- );
- if (r3.code !== 0) fail("Start", r3.code);
- const nodeIdNum = extractNodeId(r3.results, verbose);
- if (nodeIdNum === null || Number.isNaN(nodeIdNum)) {
- console.error("[portal] Start results:", JSON.stringify(r3.results, replacer, 2));
- throw new Error(
- "Start: could not read PipeWire node id from streams (see log above).",
- );
- }
- if (trace) {
- console.info("[portal] calling OpenPipeWireRemote for", sessionPath);
- }
- let fd;
- try {
- fd = await sc.OpenPipeWireRemote(sessionPath, {});
- } catch (e) {
- console.error("[portal] OpenPipeWireRemote threw:", e?.stack || e?.message || e);
- throw e;
- }
- if (trace) {
- console.info("[portal] OpenPipeWireRemote returned:", fd, `(type ${typeof fd})`);
- }
- if (typeof fd !== "number" || fd < 0) {
- throw new Error(
- `OpenPipeWireRemote: expected unix fd number, got ${typeof fd}: ${String(fd)}`,
- );
- }
- console.info("[portal] PipeWire fd=%d node=%d", fd, nodeIdNum);
- return { fd, nodeId: nodeIdNum, bus };
- }
- function replacer(_key, value) {
- if (value instanceof Variant) {
- return { _variant: value.signature, value: value.value };
- }
- if (typeof value === "bigint") return value.toString();
- return value;
- }
|