portal.mjs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import dbus from "dbus-next";
  2. const { sessionBus, Variant, MessageType } = dbus;
  3. const REQUEST_IFACE = "org.freedesktop.portal.Request";
  4. const PORTAL_NAME = "org.freedesktop.portal.Desktop";
  5. const PORTAL_PATH = "/org/freedesktop/portal/desktop";
  6. const SOURCE_TYPE_MONITOR = 1;
  7. const CURSOR_MODE_EMBEDDED = 2;
  8. function unwrap(v) {
  9. if (v instanceof Variant) return unwrap(v.value);
  10. return v;
  11. }
  12. function fail(stage, code) {
  13. throw new Error(`${stage} failed with response ${code}`);
  14. }
  15. function summarizeResults(results, verbose) {
  16. if (!results || typeof results !== "object") return String(results);
  17. const keys = Object.keys(results);
  18. const out = { keys };
  19. if (verbose) {
  20. try {
  21. out.dump = JSON.stringify(results, replacer, 2);
  22. } catch (e) {
  23. out.dump = `(could not stringify: ${e.message})`;
  24. }
  25. }
  26. return out;
  27. }
  28. /**
  29. * @param {import('dbus-next').MessageBus} bus
  30. * @param {string} step — label for logs
  31. * @param {() => Promise<string>} callMethod — returns Request `handle` (object path)
  32. * @param {{ trace: boolean; verbose: boolean }} logOpts
  33. */
  34. async function waitPortalResponse(bus, step, callMethod, logOpts) {
  35. const { trace, verbose } = logOpts;
  36. if (trace) console.info(`[portal] ${step}: calling D-Bus method…`);
  37. const handlePath = await callMethod();
  38. if (trace) {
  39. console.info(`[portal] ${step}: method returned request handle:`, handlePath);
  40. }
  41. if (typeof handlePath !== "string" || !handlePath.startsWith("/")) {
  42. throw new Error(
  43. `Portal did not return a request object path (got ${typeof handlePath}: ${String(handlePath)})`,
  44. );
  45. }
  46. const match = `type='signal',interface='${REQUEST_IFACE}',member='Response',path='${handlePath}'`;
  47. if (verbose) {
  48. console.info(`[portal] ${step}: AddMatch rule:`, match);
  49. }
  50. return new Promise((resolve, reject) => {
  51. let settled = false;
  52. const onMsg = (msg) => {
  53. if (msg.type !== MessageType.SIGNAL) return;
  54. if (msg.path !== handlePath) return;
  55. if (msg.interface !== REQUEST_IFACE) return;
  56. if (msg.member !== "Response") return;
  57. if (settled) return;
  58. settled = true;
  59. bus.removeListener("message", onMsg);
  60. bus._removeMatch(match).catch(() => {});
  61. const code = msg.body[0];
  62. const results = msg.body[1] || {};
  63. if (trace) {
  64. console.info(`[portal] ${step}: Response signal received, code=${code}`);
  65. console.info(`[portal] ${step}: results summary:`, summarizeResults(results, verbose));
  66. }
  67. if (verbose) {
  68. console.info(`[portal] ${step}: raw msg.signature=`, msg.signature, "body length=", msg.body?.length);
  69. }
  70. resolve({ code, results });
  71. };
  72. bus.on("message", onMsg);
  73. bus
  74. ._addMatch(match)
  75. .then(() => {
  76. if (trace) {
  77. console.info(`[portal] ${step}: AddMatch registered; waiting for Response on`);
  78. console.info(`[portal] ${step}: ${handlePath}`);
  79. }
  80. })
  81. .catch((err) => {
  82. if (!settled) {
  83. settled = true;
  84. bus.removeListener("message", onMsg);
  85. reject(err);
  86. }
  87. });
  88. });
  89. }
  90. /**
  91. * PipeWire node id from Start results: `streams` is `a(ua{sv})` → [[nodeId, props], ...].
  92. */
  93. function extractNodeId(results, verbose) {
  94. const streamsRaw = results.streams;
  95. if (verbose) {
  96. console.info("[portal] Start: raw results.streams type=", typeof streamsRaw);
  97. try {
  98. console.info(
  99. "[portal] Start: streams (verbose)=",
  100. JSON.stringify(streamsRaw, replacer, 2),
  101. );
  102. } catch (e) {
  103. console.info("[portal] Start: streams not JSON-serializable:", e.message);
  104. }
  105. }
  106. const streams = unwrap(streamsRaw);
  107. if (!Array.isArray(streams) || streams.length === 0) {
  108. return null;
  109. }
  110. const first = streams[0];
  111. if (Array.isArray(first) && first.length > 0) {
  112. const id = unwrap(first[0]);
  113. if (id !== undefined && id !== null) {
  114. if (typeof id === "bigint") return Number(id);
  115. return Number(id);
  116. }
  117. }
  118. return null;
  119. }
  120. /**
  121. * @param {{ verbose?: boolean; trace?: boolean }} [options]
  122. * - trace: step-by-step portal logs (default true unless NEBUCAST_PORTAL_TRACE=0)
  123. * - verbose: extra dumps (default: argv --verbose or NEBUCAST_VERBOSE=1)
  124. */
  125. export async function negotiateScreencastPortal(options = {}) {
  126. const envTrace = process.env.NEBUCAST_PORTAL_TRACE !== "0";
  127. const envVerbose =
  128. process.env.NEBUCAST_VERBOSE === "1" || process.env.DEBUG?.includes("nebucast");
  129. const trace = options.trace !== false && envTrace;
  130. const verbose = Boolean(options.verbose || envVerbose);
  131. const logOpts = { trace, verbose };
  132. if (trace) {
  133. console.info("[portal] connecting session D-Bus (negotiateUnixFd=true)…");
  134. }
  135. const bus = sessionBus({ negotiateUnixFd: true });
  136. await new Promise((resolve, reject) => {
  137. if (bus.name) resolve();
  138. else {
  139. bus.once("connect", resolve);
  140. bus.once("error", reject);
  141. }
  142. });
  143. if (trace) {
  144. console.info("[portal] bus connected, unique name:", bus.name);
  145. }
  146. bus.on("error", (err) => {
  147. console.error("[portal] bus error:", err?.stack || err?.message || err);
  148. });
  149. let n = 0;
  150. const nextToken = () => `sc${++n}`;
  151. if (trace) {
  152. console.info("[portal] introspecting", PORTAL_NAME, PORTAL_PATH);
  153. }
  154. const portal = await bus.getProxyObject(PORTAL_NAME, PORTAL_PATH);
  155. const sc = portal.getInterface("org.freedesktop.portal.ScreenCast");
  156. let t = nextToken();
  157. if (trace) console.info("[portal] CreateSession handle_token=", t);
  158. const r1 = await waitPortalResponse(
  159. bus,
  160. "CreateSession",
  161. () =>
  162. sc.CreateSession({
  163. handle_token: new Variant("s", t),
  164. session_handle_token: new Variant("s", "nebucast_session"),
  165. }),
  166. logOpts,
  167. );
  168. if (r1.code !== 0) fail("CreateSession", r1.code);
  169. const sessionPath = unwrap(r1.results.session_handle);
  170. if (typeof sessionPath !== "string") {
  171. throw new Error("CreateSession: missing session_handle");
  172. }
  173. console.info("[portal] session:", sessionPath);
  174. t = nextToken();
  175. if (trace) console.info("[portal] SelectSources handle_token=", t);
  176. const r2 = await waitPortalResponse(
  177. bus,
  178. "SelectSources",
  179. () =>
  180. sc.SelectSources(sessionPath, {
  181. handle_token: new Variant("s", t),
  182. types: new Variant("u", SOURCE_TYPE_MONITOR),
  183. cursor_mode: new Variant("u", CURSOR_MODE_EMBEDDED),
  184. }),
  185. logOpts,
  186. );
  187. if (r2.code !== 0) fail("SelectSources", r2.code);
  188. console.info("[portal] source selected, starting…");
  189. t = nextToken();
  190. if (trace) console.info("[portal] Start handle_token=", t);
  191. const r3 = await waitPortalResponse(
  192. bus,
  193. "Start",
  194. () =>
  195. sc.Start(sessionPath, "", {
  196. handle_token: new Variant("s", t),
  197. }),
  198. logOpts,
  199. );
  200. if (r3.code !== 0) fail("Start", r3.code);
  201. const nodeIdNum = extractNodeId(r3.results, verbose);
  202. if (nodeIdNum === null || Number.isNaN(nodeIdNum)) {
  203. console.error("[portal] Start results:", JSON.stringify(r3.results, replacer, 2));
  204. throw new Error(
  205. "Start: could not read PipeWire node id from streams (see log above).",
  206. );
  207. }
  208. if (trace) {
  209. console.info("[portal] calling OpenPipeWireRemote for", sessionPath);
  210. }
  211. let fd;
  212. try {
  213. fd = await sc.OpenPipeWireRemote(sessionPath, {});
  214. } catch (e) {
  215. console.error("[portal] OpenPipeWireRemote threw:", e?.stack || e?.message || e);
  216. throw e;
  217. }
  218. if (trace) {
  219. console.info("[portal] OpenPipeWireRemote returned:", fd, `(type ${typeof fd})`);
  220. }
  221. if (typeof fd !== "number" || fd < 0) {
  222. throw new Error(
  223. `OpenPipeWireRemote: expected unix fd number, got ${typeof fd}: ${String(fd)}`,
  224. );
  225. }
  226. console.info("[portal] PipeWire fd=%d node=%d", fd, nodeIdNum);
  227. return { fd, nodeId: nodeIdNum, bus };
  228. }
  229. function replacer(_key, value) {
  230. if (value instanceof Variant) {
  231. return { _variant: value.signature, value: value.value };
  232. }
  233. if (typeof value === "bigint") return value.toString();
  234. return value;
  235. }