| 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 | |
| 7 | const [binary, workDir] = process.argv.slice(2); |
| 8 | const GUEST_ENDPOINT = process.env.GUEST_CDP ?? 'http://127.0.0.1:9471'; |
| 9 | const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222'; |
| 10 | const PORT = Number(process.env.MATRIX_PORT ?? 9472); |
| 11 | |
| 12 | const PEER_HOOK = `(() => { |
| 13 | const Original = window.RTCPeerConnection; |
| 14 | if (!Original || Original.__matrix) return; |
| 15 | window.__pcs = []; |
| 16 | const Wrapped = function (...args) { const peer = new Original(...args); window.__pcs.push(peer); return peer; }; |
| 17 | Wrapped.prototype = Original.prototype; |
| 18 | Object.setPrototypeOf(Wrapped, Original); |
| 19 | Wrapped.__matrix = true; |
| 20 | window.RTCPeerConnection = Wrapped; |
| 21 | })();`; |
| 22 | |
| 23 | // Signed-in Chrome has no fake devices: camera = moving canvas, mic = looped speech file, screen = canvas. |
| 24 | const FAKE_MEDIA = (speechUrl) => `(() => { |
| 25 | if (!navigator.mediaDevices || navigator.mediaDevices.__matrix) return; |
| 26 | const canvasTrack = (label, width, height) => { |
| 27 | const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; |
| 28 | const context = canvas.getContext('2d'); let frame = 0; |
| 29 | setInterval(() => { frame++; context.fillStyle = 'hsl(' + (frame * 3 % 360) + ',70%,40%)'; context.fillRect(0, 0, width, height); |
| 30 | context.fillStyle = '#fff'; context.font = '48px sans-serif'; context.fillText(label + ' ' + frame, 40, height / 2); }, 66); |
| 31 | return canvas.captureStream(15).getVideoTracks()[0]; |
| 32 | }; |
| 33 | let audioContext; |
| 34 | const speechTrack = async () => { |
| 35 | audioContext = audioContext || new AudioContext(); |
| 36 | const destination = audioContext.createMediaStreamDestination(); |
| 37 | try { |
| 38 | const data = await (await fetch('${speechUrl}')).arrayBuffer(); |
| 39 | const buffer = await audioContext.decodeAudioData(data); |
| 40 | const source = audioContext.createBufferSource(); source.buffer = buffer; source.loop = true; source.connect(destination); source.start(); |
| 41 | } catch (error) { |
| 42 | const oscillator = audioContext.createOscillator(); oscillator.frequency.value = 440; oscillator.connect(destination); oscillator.start(); |
| 43 | } |
| 44 | return destination.stream.getAudioTracks()[0]; |
| 45 | }; |
| 46 | const devices = [ |
| 47 | { deviceId: 'matrix-mic', kind: 'audioinput', label: 'Matrix mic', groupId: 'matrix' }, |
| 48 | { deviceId: 'matrix-cam', kind: 'videoinput', label: 'Matrix camera', groupId: 'matrix' }, |
| 49 | { deviceId: 'matrix-speaker', kind: 'audiooutput', label: 'Matrix speaker', groupId: 'matrix' }, |
| 50 | ].map((device) => ({ ...device, toJSON() { return device; } })); |
| 51 | navigator.mediaDevices.enumerateDevices = async () => devices; |
| 52 | navigator.mediaDevices.getUserMedia = async (constraints) => { |
| 53 | const tracks = []; |
| 54 | if (constraints && constraints.audio) tracks.push(await speechTrack()); |
| 55 | if (constraints && constraints.video) tracks.push(canvasTrack('camera', 640, 360)); |
| 56 | return new MediaStream(tracks); |
| 57 | }; |
| 58 | navigator.mediaDevices.getDisplayMedia = async () => new MediaStream([canvasTrack('screen', 1280, 720)]); |
| 59 | navigator.mediaDevices.__matrix = true; |
| 60 | })();`; |
| 61 | |
| 62 | const PEER_STATS = `(async () => { |
| 63 | const report = { peers: 0, audioIn: [], videoIn: [], audioOut: [], videoOut: [] }; |
| 64 | for (const peer of window.__pcs || []) { |
| 65 | if (peer.connectionState === 'closed') continue; |
| 66 | report.peers++; |
| 67 | (await peer.getStats()).forEach((entry) => { |
| 68 | if (entry.type === 'inbound-rtp' && entry.kind === 'audio') report.audioIn.push({ energy: entry.totalAudioEnergy, level: entry.audioLevel, packets: entry.packetsReceived }); |
| 69 | if (entry.type === 'inbound-rtp' && entry.kind === 'video') report.videoIn.push({ mid: entry.mid, decoded: entry.framesDecoded || 0, width: entry.frameWidth, height: entry.frameHeight }); |
| 70 | if (entry.type === 'outbound-rtp') report[entry.kind + 'Out'].push({ mid: entry.mid, packets: entry.packetsSent, frames: entry.framesEncoded, width: entry.frameWidth, height: entry.frameHeight }); |
| 71 | }); |
| 72 | } |
| 73 | return report; |
| 74 | })()`; |
| 75 | |
| 76 | class Browser { |
| 77 | constructor(endpoint) { this.endpoint = endpoint; this.nextId = 1; this.pending = new Map(); this.listeners = []; } |
| 78 | async connect() { |
| 79 | const version = await (await fetch(this.endpoint + '/json/version')).json(); |
| 80 | this.socket = new WebSocket(version.webSocketDebuggerUrl); |
| 81 | await new Promise((resolve, reject) => { this.socket.onopen = resolve; this.socket.onerror = reject; }); |
| 82 | this.socket.onmessage = (message) => { |
| 83 | const data = JSON.parse(message.data); |
| 84 | if (data.id && this.pending.has(data.id)) { |
| 85 | const { resolve, reject } = this.pending.get(data.id); this.pending.delete(data.id); |
| 86 | data.error ? reject(new Error(data.error.message)) : resolve(data.result); |
| 87 | } else if (data.method) this.listeners.forEach((listener) => listener(data)); |
| 88 | }; |
| 89 | return this; |
| 90 | } |
| 91 | send(method, params = {}, sessionId) { |
| 92 | const id = this.nextId++; |
| 93 | this.socket.send(JSON.stringify({ id, method, params, sessionId })); |
| 94 | return new Promise((resolve, reject) => { this.pending.set(id, { resolve, reject }); setTimeout(() => { if (this.pending.delete(id)) reject(new Error(method + ' timed out')); }, 60000); }); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | const guests = new Map(); |
| 99 | const events = []; |
| 100 | let child; |
| 101 | let guestBrowser; |
| 102 | let ownBrowser; |
| 103 | |
| 104 | // Shared Chrome: other clients reload or close the first Teams tab, which took our Trouter with it. |
| 105 | const TAB_PROXY_PORT = PORT + 1; |
| 106 | let organizerTabId; |
| 107 | |
| 108 | async function openOrganizerTab() { |
| 109 | if (!organizerTabId) { |
| 110 | organizerTabId = (await ownBrowser.send('Target.createTarget', { url: 'https://teams.cloud.microsoft/robots.txt' })).targetId; |
| 111 | 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')); |
| 112 | if (others[0]) await ownBrowser.send('Target.activateTarget', { targetId: others[0].id }).catch(() => {}); |
| 113 | } |
| 114 | return organizerTabId; |
| 115 | } |
| 116 | |
| 117 | createServer(async (request, response) => { |
| 118 | const upstream = await fetch(OWN_ENDPOINT + request.url); |
| 119 | let body = await upstream.text(); |
| 120 | if (request.url.startsWith('/json/list') || request.url === '/json') { |
| 121 | const targets = JSON.parse(body); |
| 122 | body = JSON.stringify(targets.filter((target) => target.id === organizerTabId || !target.url.startsWith('https://teams.'))); |
| 123 | } |
| 124 | response.writeHead(upstream.status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) }).end(body); |
| 125 | }).listen(TAB_PROXY_PORT, '127.0.0.1'); |
| 126 | |
| 127 | async function startOrganizer() { |
| 128 | await openOrganizerTab(); |
| 129 | child = spawn(binary, ['--link-out', workDir + '/link.txt', '--thread-out', workDir + '/thread.txt'], { |
| 130 | stdio: ['pipe', 'pipe', 'pipe'], |
| 131 | env: { ...process.env, CDP_ENDPOINT: `http://127.0.0.1:${TAB_PROXY_PORT}` }, |
| 132 | }); |
| 133 | let buffer = ''; |
| 134 | child.stdout.on('data', (chunk) => { |
| 135 | buffer += chunk; |
| 136 | let index; |
| 137 | while ((index = buffer.indexOf('\n')) >= 0) { |
| 138 | const line = buffer.slice(0, index); buffer = buffer.slice(index + 1); |
| 139 | if (line.startsWith('@')) { try { events.push({ at: Date.now(), ...JSON.parse(line.slice(1)) }); } catch { /* partial line */ } } |
| 140 | } |
| 141 | }); |
| 142 | child.stderr.on('data', (chunk) => writeFileSync(workDir + '/organizer.stderr', chunk, { flag: 'a' })); |
| 143 | child.on('exit', (code) => { |
| 144 | events.push({ at: Date.now(), event: 'organizer_exit', code }); |
| 145 | ownBrowser.send('Target.closeTarget', { targetId: organizerTabId }).catch(() => {}); |
| 146 | organizerTabId = undefined; |
| 147 | }); |
| 148 | child.stdout.on('data', (chunk) => writeFileSync(workDir + '/organizer.stdout', chunk, { flag: 'a' })); |
| 149 | } |
| 150 | |
| 151 | async function evaluate(guest, expression) { |
| 152 | const result = await guest.browser.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, guest.sessionId); |
| 153 | if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? 'evaluate failed'); |
| 154 | return result.result.value; |
| 155 | } |
| 156 | |
| 157 | const CLICK = (text) => `(() => { |
| 158 | const wanted = ${JSON.stringify(text)}.toLowerCase(); |
| 159 | const nodes = [...document.querySelectorAll('button, [role=button], [role=menuitem], [role=menuitemcheckbox], [role=tab], a, [role=option]')]; |
| 160 | const label = (node) => ((node.getAttribute('aria-label') || '') + ' ' + (node.innerText || '') + ' ' + (node.getAttribute('title') || '')).trim().toLowerCase(); |
| 161 | const visible = nodes.filter((node) => node.offsetParent !== null || node.getClientRects().length); |
| 162 | const exact = visible.find((node) => (node.innerText || '').trim().toLowerCase() === wanted || (node.getAttribute('aria-label') || '').trim().toLowerCase() === wanted); |
| 163 | const target = exact || visible.find((node) => label(node).includes(wanted)); |
| 164 | if (!target) return { clicked: false, candidates: visible.map(label).filter(Boolean).slice(0, 60) }; |
| 165 | target.scrollIntoView({ block: 'center' }); target.click(); |
| 166 | return { clicked: true, label: label(target).slice(0, 80) }; |
| 167 | })()`; |
| 168 | |
| 169 | async function openGuest({ name, own = false, url }) { |
| 170 | const browser = own ? ownBrowser : guestBrowser; |
| 171 | let browserContextId; |
| 172 | if (!own) browserContextId = (await browser.send('Target.createBrowserContext', { disposeOnDetach: false })).browserContextId; |
| 173 | const { targetId } = await browser.send('Target.createTarget', { url: 'about:blank', ...(browserContextId ? { browserContextId } : {}) }); |
| 174 | const { sessionId } = await browser.send('Target.attachToTarget', { targetId, flatten: true }); |
| 175 | const guest = { name, own, browser, browserContextId, targetId, sessionId }; |
| 176 | await browser.send('Page.enable', {}, sessionId); |
| 177 | await browser.send('Runtime.enable', {}, sessionId); |
| 178 | await browser.send('Page.addScriptToEvaluateOnNewDocument', { source: PEER_HOOK }, sessionId); |
| 179 | if (own) { |
| 180 | await browser.send('Page.addScriptToEvaluateOnNewDocument', { source: FAKE_MEDIA(`http://127.0.0.1:${PORT}/speech.wav`) }, sessionId); |
| 181 | await browser.send('Browser.grantPermissions', { permissions: ['audioCapture', 'videoCapture', 'displayCapture'], origin: 'https://teams.cloud.microsoft' }).catch(() => {}); |
| 182 | } |
| 183 | await browser.send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId).catch(() => {}); |
| 184 | await browser.send('Page.navigate', { url: url ?? readFileSync(workDir + '/link.txt', 'utf8').trim() }, sessionId); |
| 185 | guests.set(name, guest); |
| 186 | return { opened: name }; |
| 187 | } |
| 188 | |
| 189 | async function closeGuest(name) { |
| 190 | const guest = guests.get(name); |
| 191 | if (!guest) return { closed: false }; |
| 192 | await guest.browser.send('Target.closeTarget', { targetId: guest.targetId }).catch(() => {}); |
| 193 | if (guest.browserContextId) await guest.browser.send('Target.disposeBrowserContext', { browserContextId: guest.browserContextId }).catch(() => {}); |
| 194 | guests.delete(name); |
| 195 | return { closed: true }; |
| 196 | } |
| 197 | |
| 198 | async function screenshot(name, path) { |
| 199 | const guest = guests.get(name); |
| 200 | const { data } = await guest.browser.send('Page.captureScreenshot', { format: 'png' }, guest.sessionId); |
| 201 | writeFileSync(path, Buffer.from(data, 'base64')); |
| 202 | return { path }; |
| 203 | } |
| 204 | |
| 205 | async function typeText(name, selector, text) { |
| 206 | const guest = guests.get(name); |
| 207 | const focused = await evaluate(guest, `(() => { const node = document.querySelector(${JSON.stringify(selector)}); if (!node) return false; node.focus(); node.select && node.select(); return true; })()`); |
| 208 | if (focused) await guest.browser.send('Input.insertText', { text }, guest.sessionId); |
| 209 | return { typed: focused }; |
| 210 | } |
| 211 | |
| 212 | async function pressKey(name, key, modifiers = 0) { |
| 213 | const guest = guests.get(name); |
| 214 | const codes = { Enter: 13, Escape: 27, Space: 32 }; |
| 215 | for (const type of ['keyDown', 'keyUp']) { |
| 216 | await guest.browser.send('Input.dispatchKeyEvent', { type, key, code: key, windowsVirtualKeyCode: codes[key] ?? key.toUpperCase().charCodeAt(0), modifiers }, guest.sessionId); |
| 217 | } |
| 218 | return { pressed: key }; |
| 219 | } |
| 220 | |
| 221 | async function capture(name) { |
| 222 | const guest = guests.get(name); |
| 223 | guest.requests = []; |
| 224 | guest.browser.listeners.push((message) => { |
| 225 | if (message.sessionId === guest.sessionId && message.method === 'Network.requestWillBeSent') { |
| 226 | const { url, method, postData } = message.params.request; |
| 227 | guest.requests.push({ url, method, postData }); |
| 228 | } |
| 229 | }); |
| 230 | await guest.browser.send('Network.enable', {}, guest.sessionId); |
| 231 | return { capturing: name }; |
| 232 | } |
| 233 | |
| 234 | const trouterFrames = []; |
| 235 | async function watchTrouter() { |
| 236 | const { sessionId } = await ownBrowser.send('Target.attachToTarget', { targetId: organizerTabId, flatten: true }); |
| 237 | ownBrowser.listeners.push((message) => { |
| 238 | if (message.sessionId !== sessionId || message.method !== 'Network.webSocketFrameReceived') return; |
| 239 | const payload = message.params.response.payloadData || ''; |
| 240 | const path = /callAgent\/[^"]*?\/(call|conversation)\/([A-Za-z]+)/.exec(payload); |
| 241 | if (!path) return; |
| 242 | const sequence = /sequenceNumber\\?":(\d+)/.exec(payload); |
| 243 | 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 }); |
| 244 | }); |
| 245 | await ownBrowser.send('Network.enable', {}, sessionId); |
| 246 | return { watching: true }; |
| 247 | } |
| 248 | |
| 249 | const ROUTES = { |
| 250 | 'POST /organizer/watch-trouter': async () => watchTrouter(), |
| 251 | 'GET /organizer/trouter-frames': async () => trouterFrames, |
| 252 | 'POST /guest/capture': async (body) => capture(body.name), |
| 253 | 'POST /guest/requests': async (body) => (guests.get(body.name).requests ?? []).filter((request) => request.url.includes(body.match ?? '')), |
| 254 | 'POST /organizer/start': async () => { await startOrganizer(); return { started: true }; }, |
| 255 | 'POST /organizer/send': async (body) => { child.stdin.write(body.line + '\n'); return { sent: body.line }; }, |
| 256 | 'GET /events': async (_, query) => events.filter((event) => event.at > Number(query.get('since') ?? 0) && (!query.get('type') || event.event === query.get('type'))), |
| 257 | 'POST /guest/open': async (body) => openGuest(body), |
| 258 | 'POST /guest/close': async (body) => closeGuest(body.name), |
| 259 | 'POST /guest/eval': async (body) => evaluate(guests.get(body.name), body.expression), |
| 260 | 'POST /guest/click': async (body) => evaluate(guests.get(body.name), CLICK(body.text)), |
| 261 | 'POST /guest/type': async (body) => typeText(body.name, body.selector, body.text), |
| 262 | 'POST /guest/key': async (body) => pressKey(body.name, body.key, body.modifiers), |
| 263 | 'POST /guest/shot': async (body) => screenshot(body.name, body.path), |
| 264 | 'POST /guest/stats': async (body) => evaluate(guests.get(body.name), PEER_STATS), |
| 265 | 'POST /guest/text': async (body) => evaluate(guests.get(body.name), `document.body.innerText.slice(0, ${body.limit ?? 3000})`), |
| 266 | 'GET /guests': async () => [...guests.keys()], |
| 267 | }; |
| 268 | |
| 269 | guestBrowser = await new Browser(GUEST_ENDPOINT).connect(); |
| 270 | ownBrowser = await new Browser(OWN_ENDPOINT).connect(); |
| 271 | if (!existsSync(workDir)) throw new Error('work dir missing'); |
| 272 | |
| 273 | createServer(async (request, response) => { |
| 274 | const url = new URL(request.url, 'http://localhost'); |
| 275 | if (url.pathname === '/speech.wav') { |
| 276 | response.writeHead(200, { 'content-type': 'audio/wav', 'access-control-allow-origin': '*', 'access-control-allow-private-network': 'true' }).end(readFileSync(workDir + '/speech.wav')); |
| 277 | return; |
| 278 | } |
| 279 | const route = ROUTES[request.method + ' ' + url.pathname]; |
| 280 | let raw = ''; |
| 281 | for await (const chunk of request) raw += chunk; |
| 282 | try { |
| 283 | if (!route) throw new Error('no route'); |
| 284 | const result = await route(raw ? JSON.parse(raw) : {}, url.searchParams); |
| 285 | response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(result ?? null)); |
| 286 | } catch (error) { |
| 287 | response.writeHead(500, { 'content-type': 'application/json' }).end(JSON.stringify({ error: String(error.message ?? error) })); |
| 288 | } |
| 289 | }).listen(PORT, '127.0.0.1'); |
| 290 | console.log('live matrix driver on ' + PORT); |