| 1 | // Live meeting matrix driver: runs the `live_matrix` example as organizer and drives Teams web guests over CDP. |
| 2 | // Usage: node scripts/live-matrix.mjs <live_matrix binary> <work dir>; then talk to http://127.0.0.1:9472 (see ROUTES). |
| 3 | import { spawn } from 'node:child_process'; |
| 4 | import { createServer } from 'node:http'; |
| 5 | import { readFileSync, writeFileSync, existsSync } from 'node:fs'; |
| 6 | import { Browser, CLICK, FAKE_MEDIA, PEER_HOOK, PEER_STATS } from './teams-web-cdp.mjs'; |
| 7 | |
| 8 | const [binary, workDir] = process.argv.slice(2); |
| 9 | const GUEST_ENDPOINT = process.env.GUEST_CDP ?? 'http://127.0.0.1:9471'; |
| 10 | const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222'; |
| 11 | const PORT = Number(process.env.MATRIX_PORT ?? 9472); |
| 12 | |
| 13 | const guests = new Map(); |
| 14 | const events = []; |
| 15 | let child; |
| 16 | let guestBrowser; |
| 17 | let ownBrowser; |
| 18 | |
| 19 | // Shared Chrome: other clients reload or close the first Teams tab, which took our Trouter with it. |
| 20 | const TAB_PROXY_PORT = PORT + 1; |
| 21 | let organizerTabId; |
| 22 | |
| 23 | async function openOrganizerTab() { |
| 24 | if (!organizerTabId) { |
| 25 | organizerTabId = (await ownBrowser.send('Target.createTarget', { url: 'https://teams.cloud.microsoft/robots.txt' })).targetId; |
| 26 | const others = (await (await fetch(OWN_ENDPOINT + '/json/list')).json()).filter((target) => target.type === 'page' && target.id !== organizerTabId && target.url.startsWith('https://teams.cloud.microsoft')); |
| 27 | if (others[0]) await ownBrowser.send('Target.activateTarget', { targetId: others[0].id }).catch(() => {}); |
| 28 | } |
| 29 | return organizerTabId; |
| 30 | } |
| 31 | |
| 32 | createServer(async (request, response) => { |
| 33 | const upstream = await fetch(OWN_ENDPOINT + request.url); |
| 34 | let body = await upstream.text(); |
| 35 | if (request.url.startsWith('/json/list') || request.url === '/json') { |
| 36 | const targets = JSON.parse(body); |
| 37 | body = JSON.stringify(targets.filter((target) => target.id === organizerTabId || !target.url.startsWith('https://teams.'))); |
| 38 | } |
| 39 | response.writeHead(upstream.status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) }).end(body); |
| 40 | }).listen(TAB_PROXY_PORT, '127.0.0.1'); |
| 41 | |
| 42 | async function startOrganizer() { |
| 43 | await openOrganizerTab(); |
| 44 | child = spawn(binary, ['--link-out', workDir + '/link.txt', '--thread-out', workDir + '/thread.txt'], { |
| 45 | stdio: ['pipe', 'pipe', 'pipe'], |
| 46 | env: { ...process.env, CDP_ENDPOINT: `http://127.0.0.1:${TAB_PROXY_PORT}` }, |
| 47 | }); |
| 48 | let buffer = ''; |
| 49 | child.stdout.on('data', (chunk) => { |
| 50 | buffer += chunk; |
| 51 | let index; |
| 52 | while ((index = buffer.indexOf('\n')) >= 0) { |
| 53 | const line = buffer.slice(0, index); buffer = buffer.slice(index + 1); |
| 54 | if (line.startsWith('@')) { try { events.push({ at: Date.now(), ...JSON.parse(line.slice(1)) }); } catch { /* partial line */ } } |
| 55 | } |
| 56 | }); |
| 57 | child.stderr.on('data', (chunk) => writeFileSync(workDir + '/organizer.stderr', chunk, { flag: 'a' })); |
| 58 | child.on('exit', (code) => { |
| 59 | events.push({ at: Date.now(), event: 'organizer_exit', code }); |
| 60 | ownBrowser.send('Target.closeTarget', { targetId: organizerTabId }).catch(() => {}); |
| 61 | organizerTabId = undefined; |
| 62 | }); |
| 63 | child.stdout.on('data', (chunk) => writeFileSync(workDir + '/organizer.stdout', chunk, { flag: 'a' })); |
| 64 | } |
| 65 | |
| 66 | async function evaluate(guest, expression) { |
| 67 | const result = await guest.browser.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, guest.sessionId); |
| 68 | if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? 'evaluate failed'); |
| 69 | return result.result.value; |
| 70 | } |
| 71 | |
| 72 | async function openGuest({ name, own = false, url }) { |
| 73 | const browser = own ? ownBrowser : guestBrowser; |
| 74 | let browserContextId; |
| 75 | if (!own) browserContextId = (await browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId; |
| 76 | const { targetId } = await browser.send('Target.createTarget', { url: 'about:blank', ...(browserContextId ? { browserContextId } : {}) }); |
| 77 | const { sessionId } = await browser.send('Target.attachToTarget', { targetId, flatten: true }); |
| 78 | const guest = { name, own, browser, browserContextId, targetId, sessionId }; |
| 79 | await browser.send('Page.enable', {}, sessionId); |
| 80 | await browser.send('Runtime.enable', {}, sessionId); |
| 81 | await browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId); |
| 82 | if (own) { |
| 83 | await browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(`http://127.0.0.1:${PORT}/speech.wav`) }, sessionId); |
| 84 | await browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture', 'displayCapture'], origin: 'https://teams.cloud.microsoft' }).catch(() => {}); |
| 85 | } |
| 86 | await browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {}); |
| 87 | await browser.send('Page.navigate', { url: url ?? readFileSync(workDir + '/link.txt', 'utf8').trim() }, sessionId); |
| 88 | guests.set(name, guest); |
| 89 | return { opened: name }; |
| 90 | } |
| 91 | |
| 92 | async function closeGuest(name) { |
| 93 | const guest = guests.get(name); |
| 94 | if (!guest) return { closed: false }; |
| 95 | await guest.browser.send('Target.closeTarget', { targetId: guest.targetId }).catch(() => {}); |
| 96 | if (guest.browserContextId) await guest.browser.send('Target.disposeBrowserContext', { browserContextId: guest.browserContextId }).catch(() => {}); |
| 97 | guests.delete(name); |
| 98 | return { closed: true }; |
| 99 | } |
| 100 | |
| 101 | async function screenshot(name, path) { |
| 102 | const guest = guests.get(name); |
| 103 | const { data } = await guest.browser.send('Page.captureScreenshot', { format: 'png' }, guest.sessionId); |
| 104 | writeFileSync(path, Buffer.from(data, 'base64')); |
| 105 | return { path }; |
| 106 | } |
| 107 | |
| 108 | async function typeText(name, selector, text) { |
| 109 | const guest = guests.get(name); |
| 110 | const focused = await evaluate(guest, `(() => { const node = document.querySelector(${JSON.stringify(selector)}); if (!node) return false; node.focus(); node.select && node.select(); return true; })()`); |
| 111 | if (focused) await guest.browser.send('Input.insertText', { text }, guest.sessionId); |
| 112 | return { typed: focused }; |
| 113 | } |
| 114 | |
| 115 | async function pressKey(name, key, modifiers = 0) { |
| 116 | const guest = guests.get(name); |
| 117 | const codes = { Enter: 13, Escape: 27, Space: 32 }; |
| 118 | for (const type of ['keyDown', 'keyUp']) { |
| 119 | await guest.browser.send('Input.dispatchKeyEvent', { type, key, code: key, windowsVirtualKeyCode: codes[key] ?? key.toUpperCase().charCodeAt(0), modifiers }, guest.sessionId); |
| 120 | } |
| 121 | return { pressed: key }; |
| 122 | } |
| 123 | |
| 124 | async function capture(name) { |
| 125 | const guest = guests.get(name); |
| 126 | guest.requests = []; |
| 127 | guest.browser.listeners.push((message) => { |
| 128 | if (message.sessionId === guest.sessionId && message.method === 'Network.requestWillBeSent') { |
| 129 | const { url, method, postData } = message.params.request; |
| 130 | guest.requests.push({ url, method, postData }); |
| 131 | } |
| 132 | }); |
| 133 | await guest.browser.send('Network.enable', {}, guest.sessionId); |
| 134 | return { capturing: name }; |
| 135 | } |
| 136 | |
| 137 | const trouterFrames = []; |
| 138 | async function watchTrouter() { |
| 139 | const { sessionId } = await ownBrowser.send('Target.attachToTarget', { targetId: organizerTabId, flatten: true }); |
| 140 | ownBrowser.listeners.push((message) => { |
| 141 | if (message.sessionId !== sessionId || message.method !== 'Network.webSocketFrameReceived') return; |
| 142 | const payload = message.params.response.payloadData || ''; |
| 143 | const path = /callAgent\/[^"]*?\/(call|conversation)\/([A-Za-z]+)/.exec(payload); |
| 144 | if (!path) return; |
| 145 | const sequence = /sequenceNumber\\?":(\d+)/.exec(payload); |
| 146 | trouterFrames.push({ at: Date.now(), event: path[2], url: /\\?"url\\?":\\?"([^"\\]{0,60})/.exec(payload)?.[1], head: payload.slice(0, 12), sequence: sequence ? Number(sequence[1]) : null, bytes: payload.length }); |
| 147 | }); |
| 148 | await ownBrowser.send('Network.enable', {}, sessionId); |
| 149 | return { watching: true }; |
| 150 | } |
| 151 | |
| 152 | const ROUTES = { |
| 153 | 'POST /organizer/watch-trouter': async () => watchTrouter(), |
| 154 | 'GET /organizer/trouter-frames': async () => trouterFrames, |
| 155 | 'POST /guest/capture': async (body) => capture(body.name), |
| 156 | 'POST /guest/requests': async (body) => (guests.get(body.name).requests ?? []).filter((request) => request.url.includes(body.match ?? '')), |
| 157 | 'POST /organizer/start': async () => { await startOrganizer(); return { started: true }; }, |
| 158 | 'POST /organizer/send': async (body) => { child.stdin.write(body.line + '\n'); return { sent: body.line }; }, |
| 159 | 'GET /events': async (_, query) => events.filter((event) => event.at > Number(query.get('since') ?? 0) && (!query.get('type') || event.event === query.get('type'))), |
| 160 | 'POST /guest/open': async (body) => openGuest(body), |
| 161 | 'POST /guest/close': async (body) => closeGuest(body.name), |
| 162 | 'POST /guest/eval': async (body) => evaluate(guests.get(body.name), body.expression), |
| 163 | 'POST /guest/click': async (body) => evaluate(guests.get(body.name), CLICK(body.text)), |
| 164 | 'POST /guest/type': async (body) => typeText(body.name, body.selector, body.text), |
| 165 | 'POST /guest/key': async (body) => pressKey(body.name, body.key, body.modifiers), |
| 166 | 'POST /guest/shot': async (body) => screenshot(body.name, body.path), |
| 167 | 'POST /guest/stats': async (body) => evaluate(guests.get(body.name), PEER_STATS), |
| 168 | 'POST /guest/text': async (body) => evaluate(guests.get(body.name), `document.body.innerText.slice(0, ${body.limit ?? 3000})`), |
| 169 | 'GET /guests': async () => [...guests.keys()], |
| 170 | }; |
| 171 | |
| 172 | guestBrowser = await new Browser(GUEST_ENDPOINT).connect(); |
| 173 | ownBrowser = await new Browser(OWN_ENDPOINT).connect(); |
| 174 | if (!existsSync(workDir)) throw new Error('work dir missing'); |
| 175 | |
| 176 | createServer(async (request, response) => { |
| 177 | const url = new URL(request.url, 'http://localhost'); |
| 178 | if (url.pathname === '/speech.wav') { |
| 179 | response.writeHead(200, { 'content-type': 'audio/wav', 'access-control-allow-origin': '*', 'access-control-allow-private-network': 'true' }).end(readFileSync(workDir + '/speech.wav')); |
| 180 | return; |
| 181 | } |
| 182 | const route = ROUTES[request.method + ' ' + url.pathname]; |
| 183 | let raw = ''; |
| 184 | for await (const chunk of request) raw += chunk; |
| 185 | try { |
| 186 | if (!route) throw new Error('no route'); |
| 187 | const result = await route(raw ? JSON.parse(raw) : {}, url.searchParams); |
| 188 | response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(result ?? null)); |
| 189 | } catch (error) { |
| 190 | response.writeHead(500, { 'content-type': 'application/json' }).end(JSON.stringify({ error: String(error.message ?? error) })); |
| 191 | } |
| 192 | }).listen(PORT, '127.0.0.1'); |
| 193 | console.log('live matrix driver on ' + PORT); |