BlueGit

ict rusty-teams

Files

rusty-teams / scripts / teams-web-cdp.mjs

teams-web-cdp.mjs

teams-web-cdp.mjs 6.3 KiB Download Raw
1// Teams web over the Chrome DevTools Protocol: peer connection hook, fake media, stats and click helpers.
2
3export const PEER_HOOK = `(() => {
4 const Original = window.RTCPeerConnection;
5 if (!Original || Original.__matrix) return;
6 window.__pcs = [];
7 const Wrapped = function (...args) { const peer = new Original(...args); window.__pcs.push(peer); return peer; };
8 Wrapped.prototype = Original.prototype;
9 Object.setPrototypeOf(Wrapped, Original);
10 Wrapped.__matrix = true;
11 window.RTCPeerConnection = Wrapped;
12})();`;
13
14// Signed-in Chrome has no fake devices: camera = moving canvas, mic = looped speech file, screen = canvas.
15export const FAKE_MEDIA = (speechUrl) => `(() => {
16 if (!navigator.mediaDevices || navigator.mediaDevices.__matrix) return;
17 const canvasTrack = (label, width, height) => {
18 const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height;
19 const context = canvas.getContext('2d'); let frame = 0;
20 setInterval(() => { frame++; context.fillStyle = 'hsl(' + (frame * 3 % 360) + ',70%,40%)'; context.fillRect(0, 0, width, height);
21 context.fillStyle = '#fff'; context.font = '48px sans-serif'; context.fillText(label + ' ' + frame, 40, height / 2); }, 66);
22 return canvas.captureStream(15).getVideoTracks()[0];
23 };
24 let audioContext;
25 const speechTrack = async () => {
26 audioContext = audioContext || new AudioContext();
27 addEventListener('pointerdown', () => audioContext.resume(), true);
28 audioContext.resume().catch(() => {});
29 const destination = audioContext.createMediaStreamDestination();
30 try {
31 const data = await (await fetch('${speechUrl}')).arrayBuffer();
32 const buffer = await audioContext.decodeAudioData(data);
33 const source = audioContext.createBufferSource(); source.buffer = buffer; source.loop = true; source.connect(destination); source.start();
34 } catch (error) {
35 const oscillator = audioContext.createOscillator(); oscillator.frequency.value = 440; oscillator.connect(destination); oscillator.start();
36 }
37 return destination.stream.getAudioTracks()[0];
38 };
39 const devices = [
40 { deviceId: 'matrix-mic', kind: 'audioinput', label: 'Matrix mic', groupId: 'matrix' },
41 { deviceId: 'matrix-cam', kind: 'videoinput', label: 'Matrix camera', groupId: 'matrix' },
42 { deviceId: 'matrix-speaker', kind: 'audiooutput', label: 'Matrix speaker', groupId: 'matrix' },
43 ].map((device) => ({ ...device, toJSON() { return device; } }));
44 navigator.mediaDevices.enumerateDevices = async () => devices;
45 navigator.mediaDevices.getUserMedia = async (constraints) => {
46 const tracks = [];
47 if (constraints && constraints.audio) tracks.push(await speechTrack());
48 if (constraints && constraints.video) tracks.push(canvasTrack('camera', 640, 360));
49 return new MediaStream(tracks);
50 };
51 navigator.mediaDevices.getDisplayMedia = async () => new MediaStream([canvasTrack('screen', 1280, 720)]);
52 const query = navigator.permissions.query.bind(navigator.permissions);
53 navigator.permissions.query = (descriptor) => ['microphone', 'camera'].includes(descriptor && descriptor.name)
54 ? Promise.resolve({ state: 'granted', name: descriptor.name, onchange: null, addEventListener() {}, removeEventListener() {} })
55 : query(descriptor);
56 navigator.mediaDevices.__matrix = true;
57})();`;
58
59export const PEER_STATS = `(async () => {
60 const report = { peers: 0, audioIn: [], videoIn: [], audioOut: [], videoOut: [] };
61 for (const peer of window.__pcs || []) {
62 if (peer.connectionState === 'closed') continue;
63 report.peers++;
64 (await peer.getStats()).forEach((entry) => {
65 if (entry.type === 'inbound-rtp' && entry.kind === 'audio') report.audioIn.push({ energy: entry.totalAudioEnergy, level: entry.audioLevel, packets: entry.packetsReceived });
66 if (entry.type === 'inbound-rtp' && entry.kind === 'video') report.videoIn.push({ mid: entry.mid, decoded: entry.framesDecoded || 0, width: entry.frameWidth, height: entry.frameHeight });
67 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 });
68 });
69 }
70 return report;
71})()`;
72
73export const CLICK = (text) => `(() => {
74 const wanted = ${JSON.stringify(text)}.toLowerCase();
75 const nodes = [...document.querySelectorAll('button, [role=button], [role=menuitem], [role=menuitemcheckbox], [role=tab], a, [role=option]')];
76 const label = (node) => ((node.getAttribute('aria-label') || '') + ' ' + (node.innerText || '') + ' ' + (node.getAttribute('title') || '')).trim().toLowerCase();
77 const visible = nodes.filter((node) => node.offsetParent !== null || node.getClientRects().length);
78 const exact = visible.find((node) => (node.innerText || '').trim().toLowerCase() === wanted || (node.getAttribute('aria-label') || '').trim().toLowerCase() === wanted);
79 const target = exact || visible.find((node) => label(node).includes(wanted));
80 if (!target) return { clicked: false, candidates: visible.map(label).filter(Boolean).slice(0, 60) };
81 target.scrollIntoView({ block: 'center' }); target.click();
82 return { clicked: true, label: label(target).slice(0, 80) };
83})()`;
84
85export class Browser {
86 constructor(endpoint) { this.endpoint = endpoint; this.nextId = 1; this.pending = new Map(); this.listeners = []; }
87 async connect() {
88 const version = await (await fetch(this.endpoint + '/json/version')).json();
89 this.socket = new WebSocket(version.webSocketDebuggerUrl);
90 await new Promise((resolve, reject) => { this.socket.onopen = resolve; this.socket.onerror = reject; });
91 this.socket.onmessage = (message) => {
92 const data = JSON.parse(message.data);
93 if (data.id && this.pending.has(data.id)) {
94 const { resolve, reject } = this.pending.get(data.id); this.pending.delete(data.id);
95 data.error ? reject(new Error(data.error.message)) : resolve(data.result);
96 } else if (data.method) this.listeners.forEach((listener) => listener(data));
97 };
98 return this;
99 }
100 send(method, params = {}, sessionId) {
101 const id = this.nextId++;
102 this.socket.send(JSON.stringify({ id, method, params, sessionId }));
103 return new Promise((resolve, reject) => { this.pending.set(id, { resolve, reject }); setTimeout(() => { if (this.pending.delete(id)) reject(new Error(method + ' timed out')); }, 60000); });
104 }
105}