BlueGit

ict rusty-teams

test(calls): live meeting matrix

- `live_matrix` example: Meet now organizer driven by stdin commands, JSON event lines (roster, levels, frames per person, captions, recording, options, chat), `--recap <thread>` reads and deletes recordings.
- `scripts/live-matrix.mjs`: runs the example in its own Teams tab, drives anonymous Teams web guests over CDP, reads their WebRTC stats.
- ROADMAP: call rows verified live move to Done, gaps named.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 6 weeks ago

Hash
92c23844594cd281aea9f460814787204bec43d7
Parent
c2d4ff75
3 files changed +852 −12
ROADMAP.md +12 −12
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 80 %** (84 done, 28 partial, 10 missing of 122). Partial counts half.
5 **Parity: 84 %** (93 done, 19 partial, 10 missing of 122). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18 18 | [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
19 19 | [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20 20 | [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21 | [Calls and meetings](#calls-and-meetings) | 50 % | 6 | 27 | 6 |
21 | [Calls and meetings](#calls-and-meetings) | 62 % | 15 | 18 | 6 |
22 22
23 23 ## Next
24 24
@@ -167,25 +167,25 @@ Feature parity with the Microsoft Teams desktop client.
167 167 | Call test report | Done | After every call a pseudonymized JSON and Markdown report lands in the app data folder `call-reports` (newest 30): timeline, SDP summary, stats every 2 s as min / max / last, features used with result, notices, end reason. People, e-mails, phone numbers, ids, URL queries, IPs, ICE credentials, fingerprints and chat text never reach the file. Toast "Test report saved" with Open folder; Settings > Devices switch, default on. Demo calls write one too |
168 168 | Incoming call: ring, accept, decline | Partial | Ring toast, ring tone, missed call in Activity, registrar endpoint, attach + accept. Built from the Teams code, not yet rung by a second person |
169 169 | 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
170 | Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
171 | Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person |
172 | Meeting extras | Partial | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Checked with synthetic sources and the demo only; not yet live in a meeting or with a second person |
173 | Organizer controls | Partial | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Request bodies built from the Teams code and unit tested; demo checked, not yet live with a second person |
174 | People panel, roles, lock, invite | Partial | People button before chat opens a 320 px panel (closes the chat): "People (N)" with Invite and "...", lobby with Admit / Deny / Admit all, raised hands in queue order, groups Organizers / Presenters / Attendees (flat "In this call" in 1:1 and group calls), row "..." with Pin, Spotlight, Mute, Disable / Allow mic and camera, Make presenter / attendee, Remove. "..." menu: Mute all, Lock / Unlock meeting ("Locked" chip, banner for organizers), mic and camera off for attendees, Add people (1:1). Invite adds a person to the running meeting or group call; in a 1:1 call it creates a group chat and escalates. Request bodies from the Teams code and unit tested; demo checked, nothing sent to the live service |
175 | Meeting options | Partial | Organizer "..." > Meeting options: lobby bypass, who can present, attendee mic and camera, meeting chat (On / In-meeting only / Off), reactions, record automatically. Reads and writes the `meetings/v1/options` service from the captured shapes, one request per changed option, errors inline. Not yet read or written live |
176 | Live captions | Partial | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. "Captions settings": spoken language (`setLanguage`), size S/M/L, position bottom/top (size and position remembered). "Show transcript": 320 px side panel with the whole call (speaker, mm:ss, text), search, Jump to latest. Message framing and parsing from the Teams code; `setLanguage` body from capture, not sent live; not yet seen with real speech |
170 | Join a meeting from a chat | Done | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Live at engine level with up to 9 anonymous guests: roster, lobby, audio both ways, End meeting. The chat Join button itself not driven live |
171 | Video and screen sharing | Done | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Live with guests: camera and screen received (screen 1280x720), own camera and screen decoded by a guest |
172 | Meeting extras | Done | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Live with guests: hands raised and lowered (one and all), reactions both ways, meeting chat both ways. "Include computer sound" not checked live |
173 | Organizer controls | Done | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Live with guests: admit, deny, Admit all (admits each waiting person; the service's admitAll leaves anonymous guests waiting), spotlight on and off, mute, Mute all (`specified` scope; `all` mutes nobody), lower hand, remove |
174 | People panel, roles, lock, invite | Done | People button before chat opens a 320 px panel (closes the chat): "People (N)" with Invite and "...", lobby with Admit / Deny / Admit all, raised hands in queue order, groups Organizers / Presenters / Attendees (flat "In this call" in 1:1 and group calls), row "..." with Pin, Spotlight, Mute, Disable / Allow mic and camera, Make presenter / attendee, Remove. "..." menu: Mute all, Lock / Unlock meeting ("Locked" chip, banner for organizers), mic and camera off for attendees, Add people (1:1). Invite adds a person to the running meeting or group call; in a 1:1 call it creates a group chat and escalates. Live with guests: make attendee, lock (a new guest sees "This meeting is locked") and unlock, block and allow mic and camera per attendee, mic and camera off for all attendees with a per-person release. Invite not run live (nobody real may be invited) |
175 | Meeting options | Done | Organizer "..." > Meeting options: lobby bypass, who can present, attendee mic and camera, meeting chat (On / In-meeting only / Off), reactions, record automatically. Reads and writes the `meetings/v1/options` service from the captured shapes, one request per changed option, errors inline. Read, written and restored live in a Meet now meeting |
176 | Live captions | Done | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. "Captions settings": spoken language (`setLanguage`), size S/M/L, position bottom/top (size and position remembered). "Show transcript": 320 px side panel with the whole call (speaker, mm:ss, text), search, Jump to latest. Message framing and parsing from the Teams code; Live with speech from guests: captions with speaker names, `setLanguage` switches recognition. Overlay and panel not checked live |
177 177 | Backgrounds | Partial | Camera menu Background: None / Blur / Microsoft's default images / "Add image..." (remembered). The image list and thumbnails are fetched at runtime into the app data folder, nothing of Microsoft's ships with the app; the picture is cover-scaled behind the same segmentation mask (checked with a synthetic mask, demo with generated pictures, the CDN download only through `meet_now --background`). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |
178 178 | Camera effects | Partial | Camera menu "Effects" and Settings > Devices: Mirror my video (self view and camera test only, default on), Auto framing, Adjust brightness, Soft focus (Low / Medium / High in Settings). Framing, brightness and soft focus run on the send path, so others see them; one segmentation mask per frame is shared with the background. Crop planner, gamma and blend are unit tested; not yet checked on a real camera |
179 179 | Video calls (1:1 and incoming) | Partial | Camera button in 1:1 calls renegotiates a video line on the same peer connection (modalities Audio and Video), incoming video ring toast with Decline / Audio / Video, accept with video answers the video line sending, accept with audio receive-only. Offer and answer built from the Teams code and unit tested at SDP level; needs a second person |
180 | Recording | Partial | Organizer "..." > Record and transcribe: Start recording, Record audio only, Start transcription only; Stop recording / Stop transcription / Stop both (confirm) through the recorder bot; header chip red "Recording" / "Recording audio" or blue "Transcribing" for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; video start and stop run live through `meet_now --record` (audio only, transcription only and the stop variants are from capture, not run live), consent needs a tenant with the policy on and a second person |
181 | Meeting recap tab | Partial | Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; the Graph and SharePoint calls are not yet run against a real recording |
180 | Recording | Done | Organizer "..." > Record and transcribe: Start recording, Record audio only, Start transcription only; Stop recording / Stop transcription / Stop both (confirm) through the recorder bot; header chip red "Recording" / "Recording audio" or blue "Transcribing" for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; video, audio only, transcription only and every stop variant run live; a stop sent while the recorder still settles is retried. Consent needs a tenant with the policy on |
181 | Meeting recap tab | Partial | Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; occurrences, details and delete run live against real recordings. Gaps: an audio-only file carries a 1920x1080 slate, so "Audio only" never shows; a transcription-only file is listed as a recording |
182 182 | Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |
183 183 | Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto (device track with WebRTC echo cancellation, AGC, NS) or Off, Music mode keeps echo cancellation only. No Low/High, the APM has on/off flags only. Off and Music mode run a cpal mic through our own APM; checked with synthetic sources only, not with a real mic in a call |
184 184 | Push to talk | Partial | Hold Ctrl+Space while muted to talk, release to mute; main window focused, not inside text fields; hint chip on the stage. Unit tested, not tried on the Windows build |
185 185 | Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |
186 186 | Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |
187 187 | View and layout | Partial | "View" button between share and "...": Gallery (up to 3x3 of 16:9 tiles, "+N" tile with a pin list; visible tiles only swap after 2 s of speech, one swap per 5 s), Speaker (stage plus filmstrip of up to 6), Focus on content (only while someone shares), Hide people without video with a count chip, Hide me / Show me, Chat bubbles, Full screen (F11, controls hide after 3 s). Choice, Hide people without video and Chat bubbles are remembered. Checked with the demo gallery scene only; not yet in a large live meeting |
188 | Gallery video slots | Partial | Meetings offer 9 receive lines (mids 2-10, share on 11), so a 3x3 gallery shows up to 9 live videos. The mixer accepts the offer (self-only Meet now, live). Only visible tiles get a slot: "+N" people and people hidden by "Hide people without video" are not requested. Speaker stage asks for 3600 macroblocks (max-fs), filmstrip, strip and big-gallery tiles for 920. 1:1 calls unchanged. Slot plan and offer layout unit tested; not yet seen with nine people on a live mixer |
188 | Gallery video slots | Done | Meetings offer 9 receive lines (mids 2-10, share on 11), so a 3x3 gallery shows up to 9 live videos. The mixer accepts the offer (self-only Meet now, live). Only visible tiles get a slot: "+N" people and people hidden by "Hide people without video" are not requested. Speaker stage asks for 3600 macroblocks (max-fs), filmstrip, strip and big-gallery tiles for 920. 1:1 calls unchanged. Live with nine guests: all nine slots decode; a stage request lifts the sender to 1280x720 |
189 189 | Sharing tools | Partial | Received share: Ctrl+wheel zoom 1x-4x around the pointer, drag to pan, Alt+Shift+Plus / Minus / 0, "250%" chip resets; draggable divider (strip 160-400 px, remembered); "Pop out" opens the content in its own window, closing it returns it. Share menu: "Optimize for motion" (maintain framerate, 30 fps; off = maintain resolution, 15 fps) and "Show me over my content" (camera cut-out bottom right, 22 % wide, rounded; skipped without a mask). Linux: red border windows ignore the mouse on X11. Checked in the demo and unit tests; not yet live with a second person |
190 190 | Whiteboard | Partial | Stage shows "<name> is sharing a whiteboard" with Open in browser, "..." > Whiteboard opens the meeting's board. State parsing unit tested; the share callback link is registered on join but not yet seen live |
191 191 | Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 80 %** (84 done, 28 partial, 10 missing of 122). Partial counts half.
5**Parity: 84 %** (93 done, 19 partial, 10 missing of 122). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
18| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
20| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21| [Calls and meetings](#calls-and-meetings) | 50 % | 6 | 27 | 6 |
21| [Calls and meetings](#calls-and-meetings) | 62 % | 15 | 18 | 6 |
22
22
23## Next
23## Next
24
24
@@ -167,25 +167,25 @@ Feature parity with the Microsoft Teams desktop client.
167| Call test report | Done | After every call a pseudonymized JSON and Markdown report lands in the app data folder `call-reports` (newest 30): timeline, SDP summary, stats every 2 s as min / max / last, features used with result, notices, end reason. People, e-mails, phone numbers, ids, URL queries, IPs, ICE credentials, fingerprints and chat text never reach the file. Toast "Test report saved" with Open folder; Settings > Devices switch, default on. Demo calls write one too |
167| Call test report | Done | After every call a pseudonymized JSON and Markdown report lands in the app data folder `call-reports` (newest 30): timeline, SDP summary, stats every 2 s as min / max / last, features used with result, notices, end reason. People, e-mails, phone numbers, ids, URL queries, IPs, ICE credentials, fingerprints and chat text never reach the file. Toast "Test report saved" with Open folder; Settings > Devices switch, default on. Demo calls write one too |
168| Incoming call: ring, accept, decline | Partial | Ring toast, ring tone, missed call in Activity, registrar endpoint, attach + accept. Built from the Teams code, not yet rung by a second person |
168| Incoming call: ring, accept, decline | Partial | Ring toast, ring tone, missed call in Activity, registrar endpoint, attach + accept. Built from the Teams code, not yet rung by a second person |
169| 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
169| 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
170| Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
170| Join a meeting from a chat | Done | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Live at engine level with up to 9 anonymous guests: roster, lobby, audio both ways, End meeting. The chat Join button itself not driven live |
171| Video and screen sharing | Partial | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Sent frames acknowledged by the mixer; receive only checked by a local loopback, not with a second person |
171| Video and screen sharing | Done | Send and receive over libwebrtc H264, source requests through `applyChannelParameters`, stage, strip, self view, share banner. Live with guests: camera and screen received (screen 1280x720), own camera and screen decoded by a guest |
172| Meeting extras | Partial | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Checked with synthetic sources and the demo only; not yet live in a meeting or with a second person |
172| Meeting extras | Done | Share menu switch "Include computer sound" (remembered, mixed into the one audio track with the mic, own playback excluded on Windows 10 build 20348+), raise hand with queue badge, lower hand and Lower all hands for organizers, reactions on the sender's tile for 3 s, meeting chat in a 320 px side panel with unread badge. Live with guests: hands raised and lowered (one and all), reactions both ways, meeting chat both ways. "Include computer sound" not checked live |
173| Organizer controls | Partial | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Request bodies built from the Teams code and unit tested; demo checked, not yet live with a second person |
173| Organizer controls | Done | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Live with guests: admit, deny, Admit all (admits each waiting person; the service's admitAll leaves anonymous guests waiting), spotlight on and off, mute, Mute all (`specified` scope; `all` mutes nobody), lower hand, remove |
174| People panel, roles, lock, invite | Partial | People button before chat opens a 320 px panel (closes the chat): "People (N)" with Invite and "...", lobby with Admit / Deny / Admit all, raised hands in queue order, groups Organizers / Presenters / Attendees (flat "In this call" in 1:1 and group calls), row "..." with Pin, Spotlight, Mute, Disable / Allow mic and camera, Make presenter / attendee, Remove. "..." menu: Mute all, Lock / Unlock meeting ("Locked" chip, banner for organizers), mic and camera off for attendees, Add people (1:1). Invite adds a person to the running meeting or group call; in a 1:1 call it creates a group chat and escalates. Request bodies from the Teams code and unit tested; demo checked, nothing sent to the live service |
174| People panel, roles, lock, invite | Done | People button before chat opens a 320 px panel (closes the chat): "People (N)" with Invite and "...", lobby with Admit / Deny / Admit all, raised hands in queue order, groups Organizers / Presenters / Attendees (flat "In this call" in 1:1 and group calls), row "..." with Pin, Spotlight, Mute, Disable / Allow mic and camera, Make presenter / attendee, Remove. "..." menu: Mute all, Lock / Unlock meeting ("Locked" chip, banner for organizers), mic and camera off for attendees, Add people (1:1). Invite adds a person to the running meeting or group call; in a 1:1 call it creates a group chat and escalates. Live with guests: make attendee, lock (a new guest sees "This meeting is locked") and unlock, block and allow mic and camera per attendee, mic and camera off for all attendees with a per-person release. Invite not run live (nobody real may be invited) |
175| Meeting options | Partial | Organizer "..." > Meeting options: lobby bypass, who can present, attendee mic and camera, meeting chat (On / In-meeting only / Off), reactions, record automatically. Reads and writes the `meetings/v1/options` service from the captured shapes, one request per changed option, errors inline. Not yet read or written live |
175| Meeting options | Done | Organizer "..." > Meeting options: lobby bypass, who can present, attendee mic and camera, meeting chat (On / In-meeting only / Off), reactions, record automatically. Reads and writes the `meetings/v1/options` service from the captured shapes, one request per changed option, errors inline. Read, written and restored live in a Meet now meeting |
176| Live captions | Partial | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. "Captions settings": spoken language (`setLanguage`), size S/M/L, position bottom/top (size and position remembered). "Show transcript": 320 px side panel with the whole call (speaker, mm:ss, text), search, Jump to latest. Message framing and parsing from the Teams code; `setLanguage` body from capture, not sent live; not yet seen with real speech |
176| Live captions | Done | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. "Captions settings": spoken language (`setLanguage`), size S/M/L, position bottom/top (size and position remembered). "Show transcript": 320 px side panel with the whole call (speaker, mm:ss, text), search, Jump to latest. Message framing and parsing from the Teams code; Live with speech from guests: captions with speaker names, `setLanguage` switches recognition. Overlay and panel not checked live |
177| Backgrounds | Partial | Camera menu Background: None / Blur / Microsoft's default images / "Add image..." (remembered). The image list and thumbnails are fetched at runtime into the app data folder, nothing of Microsoft's ships with the app; the picture is cover-scaled behind the same segmentation mask (checked with a synthetic mask, demo with generated pictures, the CDN download only through `meet_now --background`). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |
177| Backgrounds | Partial | Camera menu Background: None / Blur / Microsoft's default images / "Add image..." (remembered). The image list and thumbnails are fetched at runtime into the app data folder, nothing of Microsoft's ships with the app; the picture is cover-scaled behind the same segmentation mask (checked with a synthetic mask, demo with generated pictures, the CDN download only through `meet_now --background`). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |
178| Camera effects | Partial | Camera menu "Effects" and Settings > Devices: Mirror my video (self view and camera test only, default on), Auto framing, Adjust brightness, Soft focus (Low / Medium / High in Settings). Framing, brightness and soft focus run on the send path, so others see them; one segmentation mask per frame is shared with the background. Crop planner, gamma and blend are unit tested; not yet checked on a real camera |
178| Camera effects | Partial | Camera menu "Effects" and Settings > Devices: Mirror my video (self view and camera test only, default on), Auto framing, Adjust brightness, Soft focus (Low / Medium / High in Settings). Framing, brightness and soft focus run on the send path, so others see them; one segmentation mask per frame is shared with the background. Crop planner, gamma and blend are unit tested; not yet checked on a real camera |
179| Video calls (1:1 and incoming) | Partial | Camera button in 1:1 calls renegotiates a video line on the same peer connection (modalities Audio and Video), incoming video ring toast with Decline / Audio / Video, accept with video answers the video line sending, accept with audio receive-only. Offer and answer built from the Teams code and unit tested at SDP level; needs a second person |
179| Video calls (1:1 and incoming) | Partial | Camera button in 1:1 calls renegotiates a video line on the same peer connection (modalities Audio and Video), incoming video ring toast with Decline / Audio / Video, accept with video answers the video line sending, accept with audio receive-only. Offer and answer built from the Teams code and unit tested at SDP level; needs a second person |
180| Recording | Partial | Organizer "..." > Record and transcribe: Start recording, Record audio only, Start transcription only; Stop recording / Stop transcription / Stop both (confirm) through the recorder bot; header chip red "Recording" / "Recording audio" or blue "Transcribing" for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; video start and stop run live through `meet_now --record` (audio only, transcription only and the stop variants are from capture, not run live), consent needs a tenant with the policy on and a second person |
180| Recording | Done | Organizer "..." > Record and transcribe: Start recording, Record audio only, Start transcription only; Stop recording / Stop transcription / Stop both (confirm) through the recorder bot; header chip red "Recording" / "Recording audio" or blue "Transcribing" for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; video, audio only, transcription only and every stop variant run live; a stop sent while the recorder still settles is retried. Consent needs a tenant with the policy on |
181| Meeting recap tab | Partial | Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; the Graph and SharePoint calls are not yet run against a real recording |
181| Meeting recap tab | Partial | Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; occurrences, details and delete run live against real recordings. Gaps: an audio-only file carries a 1920x1080 slate, so "Audio only" never shows; a transcription-only file is listed as a recording |
182| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |
182| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |
183| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto (device track with WebRTC echo cancellation, AGC, NS) or Off, Music mode keeps echo cancellation only. No Low/High, the APM has on/off flags only. Off and Music mode run a cpal mic through our own APM; checked with synthetic sources only, not with a real mic in a call |
183| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto (device track with WebRTC echo cancellation, AGC, NS) or Off, Music mode keeps echo cancellation only. No Low/High, the APM has on/off flags only. Off and Music mode run a cpal mic through our own APM; checked with synthetic sources only, not with a real mic in a call |
184| Push to talk | Partial | Hold Ctrl+Space while muted to talk, release to mute; main window focused, not inside text fields; hint chip on the stage. Unit tested, not tried on the Windows build |
184| Push to talk | Partial | Hold Ctrl+Space while muted to talk, release to mute; main window focused, not inside text fields; hint chip on the stage. Unit tested, not tried on the Windows build |
185| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |
185| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |
186| Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |
186| Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |
187| View and layout | Partial | "View" button between share and "...": Gallery (up to 3x3 of 16:9 tiles, "+N" tile with a pin list; visible tiles only swap after 2 s of speech, one swap per 5 s), Speaker (stage plus filmstrip of up to 6), Focus on content (only while someone shares), Hide people without video with a count chip, Hide me / Show me, Chat bubbles, Full screen (F11, controls hide after 3 s). Choice, Hide people without video and Chat bubbles are remembered. Checked with the demo gallery scene only; not yet in a large live meeting |
187| View and layout | Partial | "View" button between share and "...": Gallery (up to 3x3 of 16:9 tiles, "+N" tile with a pin list; visible tiles only swap after 2 s of speech, one swap per 5 s), Speaker (stage plus filmstrip of up to 6), Focus on content (only while someone shares), Hide people without video with a count chip, Hide me / Show me, Chat bubbles, Full screen (F11, controls hide after 3 s). Choice, Hide people without video and Chat bubbles are remembered. Checked with the demo gallery scene only; not yet in a large live meeting |
188| Gallery video slots | Partial | Meetings offer 9 receive lines (mids 2-10, share on 11), so a 3x3 gallery shows up to 9 live videos. The mixer accepts the offer (self-only Meet now, live). Only visible tiles get a slot: "+N" people and people hidden by "Hide people without video" are not requested. Speaker stage asks for 3600 macroblocks (max-fs), filmstrip, strip and big-gallery tiles for 920. 1:1 calls unchanged. Slot plan and offer layout unit tested; not yet seen with nine people on a live mixer |
188| Gallery video slots | Done | Meetings offer 9 receive lines (mids 2-10, share on 11), so a 3x3 gallery shows up to 9 live videos. The mixer accepts the offer (self-only Meet now, live). Only visible tiles get a slot: "+N" people and people hidden by "Hide people without video" are not requested. Speaker stage asks for 3600 macroblocks (max-fs), filmstrip, strip and big-gallery tiles for 920. 1:1 calls unchanged. Live with nine guests: all nine slots decode; a stage request lifts the sender to 1280x720 |
189| Sharing tools | Partial | Received share: Ctrl+wheel zoom 1x-4x around the pointer, drag to pan, Alt+Shift+Plus / Minus / 0, "250%" chip resets; draggable divider (strip 160-400 px, remembered); "Pop out" opens the content in its own window, closing it returns it. Share menu: "Optimize for motion" (maintain framerate, 30 fps; off = maintain resolution, 15 fps) and "Show me over my content" (camera cut-out bottom right, 22 % wide, rounded; skipped without a mask). Linux: red border windows ignore the mouse on X11. Checked in the demo and unit tests; not yet live with a second person |
189| Sharing tools | Partial | Received share: Ctrl+wheel zoom 1x-4x around the pointer, drag to pan, Alt+Shift+Plus / Minus / 0, "250%" chip resets; draggable divider (strip 160-400 px, remembered); "Pop out" opens the content in its own window, closing it returns it. Share menu: "Optimize for motion" (maintain framerate, 30 fps; off = maintain resolution, 15 fps) and "Show me over my content" (camera cut-out bottom right, 22 % wide, rounded; skipped without a mask). Linux: red border windows ignore the mouse on X11. Checked in the demo and unit tests; not yet live with a second person |
190| Whiteboard | Partial | Stage shows "<name> is sharing a whiteboard" with Open in browser, "..." > Whiteboard opens the meeting's board. State parsing unit tested; the share callback link is registered on join but not yet seen live |
190| Whiteboard | Partial | Stage shows "<name> is sharing a whiteboard" with Open in browser, "..." > Whiteboard opens the meeting's board. State parsing unit tested; the share callback link is registered on join but not yet seen live |
191| Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |
191| Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |
crates/calling/examples/live_matrix.rs added +550 −0
@@ -0,0 +1,550 @@
1 use std::collections::HashMap;
2 use std::path::PathBuf;
3 use std::time::{Duration, Instant};
4
5 use calling::meeting::fetch_live_meeting;
6 use calling::relay::ic3_scope;
7 use calling::signaling::{CHATSVC_REGION, fetch_self};
8 use calling::{
9 CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingOptions, MeetingRole, MeetingTarget, Modality,
10 MuteCommand, Reaction, RecordingKind, RosterEntry, ShareKind, ShareSource, StopScope, TileDetail, VideoKey, VideoWant,
11 };
12 use chatsvc::InstanceNames;
13 use chatsvc::recap::Recap;
14 use serde_json::{Value, json};
15 use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};
16
17 const CREATE_URL: &str =
18 "https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create";
19 const SUBJECT: &str = "Native client test";
20 const REPORT_EVERY: Duration = Duration::from_secs(2);
21 const THREAD_PROPERTY_RETRIES: usize = 8;
22 const GONE_LIMIT: Duration = Duration::from_secs(90);
23 const GRAPH_CHATS: &str = "https://graph.microsoft.com/v1.0/chats";
24
25 struct Arguments {
26 link_out: Option<PathBuf>,
27 thread_out: Option<PathBuf>,
28 recap_thread: Option<String>,
29 }
30
31 fn arguments() -> Arguments {
32 let mut parsed = Arguments { link_out: None, thread_out: None, recap_thread: None };
33 let mut input = std::env::args().skip(1);
34 while let Some(flag) = input.next() {
35 match flag.as_str() {
36 "--link-out" => parsed.link_out = input.next().map(PathBuf::from),
37 "--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
38 "--recap" => parsed.recap_thread = input.next(),
39 _ => {}
40 }
41 }
42 parsed
43 }
44
45 fn emit(value: Value) {
46 println!("@{value}");
47 }
48
49 fn main() {
50 for (name, value) in [("CALLING_AUDIO", "tone"), ("CALLING_VIDEO", "pattern")] {
51 if std::env::var_os(name).is_none() {
52 // SAFETY: nothing else runs yet; the runtime below starts after this.
53 unsafe { std::env::set_var(name, value) };
54 }
55 }
56 tokio::runtime::Runtime::new().expect("runtime").block_on(run());
57 }
58
59 fn as_object(value: &Value) -> Option<Value> {
60 match value {
61 Value::String(text) => serde_json::from_str(text).ok(),
62 Value::Object(_) => Some(value.clone()),
63 _ => None,
64 }
65 }
66
67 fn encoded(value: &str) -> String {
68 value
69 .bytes()
70 .map(|byte| match byte {
71 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (byte as char).to_string(),
72 other => format!("%{other:02X}"),
73 })
74 .collect()
75 }
76
77 async fn tenant_and_organizer(session: &Session, thread_id: &str) -> (Option<String>, Option<String>) {
78 let url = format!(
79 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
80 encoded(thread_id)
81 );
82 let Ok(response) = session.send(Request::get(url), &ic3_scope()).await else {
83 return (None, None);
84 };
85 let properties = &response.body["properties"];
86 let meeting = as_object(&properties["meeting"]);
87 let text = |value: &Value| value.as_str().filter(|text| !text.is_empty()).map(str::to_owned);
88 let tenant = meeting
89 .as_ref()
90 .and_then(|meeting| text(&meeting["tenantId"]))
91 .or_else(|| text(&properties["addedByTenantId"]));
92 (tenant, meeting.as_ref().and_then(|meeting| text(&meeting["organizerId"])))
93 }
94
95 fn find_text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
96 match value {
97 Value::Object(map) => map.iter().find_map(|(key, inner)| {
98 let direct = keys.iter().any(|wanted| key.eq_ignore_ascii_case(wanted)).then(|| inner.as_str().filter(|text| !text.is_empty())).flatten();
99 direct.or_else(|| find_text(inner, keys))
100 }),
101 Value::Array(items) => items.iter().find_map(|item| find_text(item, keys)),
102 _ => None,
103 }
104 }
105
106 fn roster_json(entries: &[RosterEntry], own_mri: Option<&str>) -> Value {
107 Value::Array(
108 entries
109 .iter()
110 .map(|entry| {
111 json!({
112 "name": if Some(entry.mri.as_str()) == own_mri { "(me)" } else { entry.display_name.as_str() },
113 "muted": entry.muted,
114 "lobby": entry.in_lobby,
115 "video": entry.has_video,
116 "sharing": entry.sharing,
117 "hand": entry.hand.is_some(),
118 "spotlight": entry.spotlight.is_some(),
119 "organizer": entry.organizer,
120 "role": entry.role.map(|role| format!("{role:?}")),
121 "mic_blocked": entry.limits.mic_blocked.is_some(),
122 "camera_blocked": entry.limits.camera_blocked.is_some(),
123 "mic_released": entry.limits.mic_released.is_some(),
124 "camera_released": entry.limits.camera_released.is_some(),
125 })
126 })
127 .collect(),
128 )
129 }
130
131 fn options_json(options: &MeetingOptions) -> Value {
132 json!({
133 "bypass_lobby": options.bypass_lobby,
134 "presenters": options.presenters,
135 "attendee_mic": options.attendee_mic,
136 "attendee_camera": options.attendee_camera,
137 "meeting_chat": options.meeting_chat,
138 "reactions": options.reactions,
139 "record_automatically": options.record_automatically,
140 })
141 }
142
143 fn reaction_named(name: &str) -> Option<Reaction> {
144 Reaction::ALL.into_iter().find(|reaction| format!("{reaction:?}").eq_ignore_ascii_case(name))
145 }
146
147 #[derive(Default)]
148 struct Window {
149 local_level: f32,
150 remote_level: f32,
151 frames: HashMap<VideoKey, (usize, u32, u32)>,
152 }
153
154 struct Matrix {
155 session: Session,
156 thread_id: String,
157 own_mri: Option<String>,
158 roster: Vec<RosterEntry>,
159 options: Option<MeetingOptions>,
160 original_options: Option<MeetingOptions>,
161 }
162
163 impl Matrix {
164 fn mri_of(&self, name: &str) -> Option<String> {
165 self.roster
166 .iter()
167 .find(|entry| entry.display_name.eq_ignore_ascii_case(name))
168 .or_else(|| self.roster.iter().find(|entry| entry.display_name.to_lowercase().contains(&name.to_lowercase())))
169 .map(|entry| entry.mri.clone())
170 }
171
172 fn name_of(&self, key: &VideoKey) -> String {
173 match key {
174 VideoKey::Person(mri) => self
175 .roster
176 .iter()
177 .find(|entry| &entry.mri == mri)
178 .map_or_else(|| "unknown".to_owned(), |entry| entry.display_name.clone()),
179 other => format!("{other:?}"),
180 }
181 }
182
183 async fn command(&mut self, line: &str) -> Vec<CallCommand> {
184 let line = line.trim();
185 let (verb, rest) = line.split_once(' ').unwrap_or((line, ""));
186 let rest = rest.trim();
187 let person = |matrix: &Matrix, name: &str| {
188 let found = matrix.mri_of(name);
189 if found.is_none() {
190 emit(json!({"event": "error", "command": verb, "reason": "no such person in the roster"}));
191 }
192 found
193 };
194 let on = |text: &str| matches!(text, "on" | "true" | "yes");
195 let split_last = |text: &str| text.rsplit_once(' ').map(|(head, tail)| (head.trim().to_owned(), tail.trim().to_owned()));
196 match verb {
197 "admit" => person(self, rest).map(|mri| vec![CallCommand::Admit { mri }]).unwrap_or_default(),
198 "deny" => person(self, rest).map(|mri| vec![CallCommand::Deny { mri }]).unwrap_or_default(),
199 "admit-all" => vec![CallCommand::AdmitAll],
200 "mute" => person(self, rest).map(|mri| vec![CallCommand::MuteParticipant { mri }]).unwrap_or_default(),
201 "mute-all" => vec![CallCommand::MuteAll],
202 "spotlight" => person(self, rest).map(|mri| vec![CallCommand::Spotlight { mri }]).unwrap_or_default(),
203 "unspotlight" => person(self, rest).map(|mri| vec![CallCommand::StopSpotlight { mri }]).unwrap_or_default(),
204 "remove" => person(self, rest).map(|mri| vec![CallCommand::RemoveParticipant { mri }]).unwrap_or_default(),
205 "lower" => person(self, rest).map(|mri| vec![CallCommand::LowerHand { mri }]).unwrap_or_default(),
206 "lower-all" => vec![CallCommand::LowerAllHands],
207 "role" => {
208 let Some((name, role)) = split_last(rest) else { return Vec::new() };
209 let role = if role == "presenter" { MeetingRole::Presenter } else { MeetingRole::Attendee };
210 person(self, &name).map(|mri| vec![CallCommand::SetRole { mri, role }]).unwrap_or_default()
211 }
212 "allow-mic" | "allow-camera" | "block-mic" | "block-camera" => {
213 let modality = if verb.ends_with("mic") { Modality::Mic } else { Modality::Camera };
214 let allowed = verb.starts_with("allow");
215 person(self, rest).map(|mri| vec![CallCommand::SetAttendeeModality { mri, modality, allowed }]).unwrap_or_default()
216 }
217 "restrict" => {
218 let mic_off = rest.contains("mic");
219 let camera_off = rest.contains("camera");
220 vec![CallCommand::SetAttendeeRestrictions { mic_off, camera_off }]
221 }
222 "lock" => vec![CallCommand::SetLock(on(rest))],
223 "options" => vec![CallCommand::LoadMeetingOptions],
224 "option" => {
225 let (Some(current), Some((name, value))) = (self.options.clone(), split_last(rest)) else {
226 emit(json!({"event": "error", "command": verb, "reason": "load options first"}));
227 return Vec::new();
228 };
229 let mut edited = current.clone();
230 match name.as_str() {
231 "reactions" => edited.reactions = on(&value),
232 "chat" => edited.meeting_chat = value,
233 "lobby" => edited.bypass_lobby = value,
234 "presenters" => edited.presenters = value,
235 "attendee_mic" => edited.attendee_mic = on(&value),
236 "attendee_camera" => edited.attendee_camera = on(&value),
237 _ => {}
238 }
239 vec![CallCommand::SaveMeetingOptions(current.changes(&edited))]
240 }
241 "options-restore" => match (&self.options, &self.original_options) {
242 (Some(current), Some(original)) => vec![CallCommand::SaveMeetingOptions(current.changes(original))],
243 _ => Vec::new(),
244 },
245 "captions" => vec![CallCommand::SetCaptions(on(rest))],
246 "language" => vec![CallCommand::SetCaptionLanguage(rest.to_owned())],
247 "record" => {
248 let kind = match rest {
249 "audio" => RecordingKind::AudioOnly,
250 "transcript" => RecordingKind::TranscriptOnly,
251 _ => RecordingKind::Video,
252 };
253 vec![CallCommand::StartRecording { kind, title: SUBJECT.to_owned() }]
254 }
255 "stop" => {
256 let scope = match rest {
257 "recording" => StopScope::RecordingOnly,
258 "transcription" => StopScope::TranscriptionOnly,
259 _ => StopScope::Both,
260 };
261 vec![CallCommand::StopRecording { scope }]
262 }
263 "camera" => vec![CallCommand::SetCamera(on(rest))],
264 "share" if on(rest) => vec![CallCommand::StartShare(ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() })],
265 "share" => vec![CallCommand::StopShare],
266 "self-mute" => vec![CallCommand::Mute(if on(rest) { MuteCommand::Mute } else { MuteCommand::Unmute })],
267 "hand" => vec![CallCommand::SetHand(on(rest))],
268 "react" => reaction_named(rest).map(|reaction| vec![CallCommand::SendReaction(reaction)]).unwrap_or_default(),
269 "incoming" => vec![CallCommand::SetIncomingVideo(on(rest))],
270 "wants" => {
271 let wants = rest
272 .split(',')
273 .filter_map(|item| {
274 let (detail, name) = item.trim().split_once(':')?;
275 let detail = if detail == "stage" { TileDetail::Stage } else { TileDetail::Small };
276 Some(VideoWant { mri: self.mri_of(name)?, detail })
277 })
278 .collect();
279 vec![CallCommand::SetVideoWants(wants)]
280 }
281 "chat" => {
282 self.send_chat(rest).await;
283 Vec::new()
284 }
285 "chat-read" => {
286 self.read_chat().await;
287 Vec::new()
288 }
289 "end" => vec![CallCommand::EndMeeting],
290 "hangup" => vec![CallCommand::Hangup],
291 _ => {
292 emit(json!({"event": "error", "command": verb, "reason": "unknown command"}));
293 Vec::new()
294 }
295 }
296 }
297
298 async fn send_chat(&self, text: &str) {
299 let url = format!("{GRAPH_CHATS}/{}/messages", encoded(&self.thread_id));
300 let body = json!({"body": {"contentType": "text", "content": text}});
301 let outcome = self.session.request(Method::Post, &url, &Scope::graph("Chat.ReadWrite"), Some(body)).await;
302 emit(json!({"event": "chat_sent", "status": outcome.as_ref().map(|answer| answer.status).ok(), "error": outcome.err().map(|error| error.to_string().chars().take(160).collect::<String>())}));
303 }
304
305 async fn read_chat(&self) {
306 let url = format!("{GRAPH_CHATS}/{}/messages?$top=20", encoded(&self.thread_id));
307 match self.session.request(Method::Get, &url, &Scope::graph("Chat.ReadWrite"), None).await {
308 Ok(answer) => {
309 let messages: Vec<Value> = answer.body["value"]
310 .as_array()
311 .into_iter()
312 .flatten()
313 .filter(|message| message["messageType"].as_str() == Some("message"))
314 .map(|message| {
315 let sender = message.pointer("/from/user/displayName").and_then(Value::as_str).unwrap_or("?");
316 let own = message.pointer("/from/user/id").and_then(Value::as_str).is_some_and(|id| self.own_mri.as_deref().is_some_and(|mri| mri.ends_with(id)));
317 json!({"from": if own { "(me)" } else { sender }, "text": message.pointer("/body/content").and_then(Value::as_str).unwrap_or_default().chars().take(120).collect::<String>()})
318 })
319 .collect();
320 emit(json!({"event": "chat_read", "status": answer.status, "messages": messages}));
321 }
322 Err(error) => emit(json!({"event": "chat_read", "error": error.to_string().chars().take(160).collect::<String>()})),
323 }
324 }
325 }
326
327 async fn recap(session: &Session, thread_id: &str) {
328 let recap = Recap::new(session);
329 let occurrences = match recap.occurrences(thread_id).await {
330 Ok(occurrences) => occurrences,
331 Err(error) => {
332 emit(json!({"event": "recap", "error": format!("{error:?}")}));
333 return;
334 }
335 };
336 emit(json!({"event": "recap_occurrences", "count": occurrences.len()}));
337 for occurrence in &occurrences {
338 match recap.details(occurrence).await {
339 Ok(details) => {
340 emit(json!({
341 "event": "recap_recording",
342 "audio_only": details.audio_only,
343 "duration_seconds": details.duration_seconds,
344 "expires_set": details.expires_at.is_some(),
345 "transcript": details.transcript_id.is_some(),
346 }));
347 let deleted = recap.delete_recording(&details).await;
348 emit(json!({"event": "recap_deleted", "ok": deleted.is_ok(), "error": deleted.err().map(|error| format!("{error:?}"))}));
349 }
350 Err(error) => emit(json!({"event": "recap_recording", "error": format!("{error:?}")})),
351 }
352 }
353 }
354
355 async fn run() {
356 let arguments = arguments();
357 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
358 let session = Session::connect(&endpoint).await.expect("browser");
359 if let Some(thread_id) = &arguments.recap_thread {
360 recap(&session, thread_id).await;
361 return;
362 }
363 let poll_session = Session::connect(&endpoint).await.expect("browser");
364 let me = fetch_self(&session).await.expect("own identity");
365 let started = Instant::now();
366
367 let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});
368 let created = session
369 .request(Method::Post, CREATE_URL, &Scope::new(SPACES, "user_impersonation"), Some(body))
370 .await
371 .expect("create meeting");
372 let thread_id = created.body.pointer("/value/groupContext/threadId").and_then(Value::as_str).expect("meeting thread").to_owned();
373 emit(json!({"event": "created", "status": created.status}));
374 if let Some(path) = &arguments.thread_out {
375 std::fs::write(path, &thread_id).expect("thread file");
376 }
377
378 let (mut tenant_id, mut organizer_id) = tenant_and_organizer(&session, &thread_id).await;
379 for _ in 0..THREAD_PROPERTY_RETRIES {
380 if tenant_id.is_some() {
381 break;
382 }
383 tokio::time::sleep(REPORT_EVERY).await;
384 (tenant_id, organizer_id) = tenant_and_organizer(&session, &thread_id).await;
385 }
386 let target = MeetingTarget {
387 thread_id: thread_id.clone(),
388 tenant_id: tenant_id.expect("tenant id"),
389 organizer_id: organizer_id.unwrap_or_else(|| me.object_id.clone()),
390 meeting_data: None,
391 };
392 let join_link = find_text(&created.body, &["joinUrl", "meetingJoinUrl", "joinWebUrl"]).map_or_else(
393 || {
394 let context = json!({"Tid": target.tenant_id, "Oid": target.organizer_id}).to_string();
395 format!("https://teams.microsoft.com/l/meetup-join/{}/0?context={}", encoded(&thread_id), encoded(&context))
396 },
397 str::to_owned,
398 );
399 if let Some(path) = &arguments.link_out {
400 std::fs::write(path, &join_link).expect("link file");
401 }
402 let config = EngineConfig {
403 ringable: false,
404 trace: std::env::var_os("LIVE_TRACE").is_some(),
405 instance: InstanceNames {
406 global: "__liveMatrixTrouter".into(),
407 binding: "__liveMatrixRealtime".into(),
408 endpoint_storage_key: "__liveMatrixEpid".into(),
409 },
410 ..EngineConfig::default()
411 };
412 let (engine, _events) = CallEngine::start(session.clone(), poll_session, config).await.expect("engine");
413 let mut handle = engine.start_call(CallSpec::Meeting(target));
414 emit(json!({"event": "joining", "after_ms": started.elapsed().as_millis()}));
415
416 let (line_sender, mut lines) = tokio::sync::mpsc::unbounded_channel::<String>();
417 std::thread::spawn(move || {
418 for line in std::io::stdin().lines().map_while(Result::ok) {
419 if line_sender.send(line).is_err() {
420 break;
421 }
422 }
423 });
424
425 let mut matrix = Matrix { session: session.clone(), thread_id: thread_id.clone(), own_mri: None, roster: Vec::new(), options: None, original_options: None };
426 let mut window = Window::default();
427 let mut last_roster = Value::Null;
428 let mut last_health = Value::Null;
429 let mut packets = (0u64, 0u64);
430 let mut ended = None;
431 let mut tick = tokio::time::interval(REPORT_EVERY);
432 while ended.is_none() {
433 tokio::select! {
434 update = handle.updates.recv() => match update {
435 Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(format!("{reason:?}")),
436 Some(CallUpdate::State(state)) => emit(json!({"event": "state", "state": format!("{state:?}").split([' ', '{', '(']).next().unwrap_or_default()})),
437 Some(CallUpdate::OwnIdentity { mri }) => matrix.own_mri = Some(mri),
438 Some(CallUpdate::Roster(entries)) => {
439 let summary = roster_json(&entries, matrix.own_mri.as_deref());
440 if summary != last_roster {
441 emit(json!({"event": "roster", "entries": summary}));
442 last_roster = summary;
443 }
444 matrix.roster = entries;
445 }
446 Some(CallUpdate::Lobby(waiting)) => emit(json!({"event": "lobby_self", "waiting": waiting})),
447 Some(CallUpdate::Levels { local, remote }) => {
448 window.local_level = window.local_level.max(local);
449 window.remote_level = window.remote_level.max(remote);
450 }
451 Some(CallUpdate::Stats { inbound_packets, outbound_packets }) => packets = (inbound_packets, outbound_packets),
452 Some(CallUpdate::VideoReady) => {
453 for (key, picture) in handle.video.drain() {
454 let slot = window.frames.entry(key).or_insert((0, 0, 0));
455 slot.0 += 1;
456 slot.1 = picture.width;
457 slot.2 = picture.height;
458 }
459 }
460 Some(CallUpdate::Speakers(speakers)) => {
461 let names: Vec<String> = speakers.iter().map(|mri| matrix.name_of(&VideoKey::Person(mri.clone()))).collect();
462 emit(json!({"event": "speakers", "names": names}));
463 }
464 Some(CallUpdate::ScreenShare(sharer)) => emit(json!({"event": "screen_share", "sharer": sharer.map(|mri| matrix.name_of(&VideoKey::Person(mri)))})),
465 Some(CallUpdate::LocalShare(label)) => emit(json!({"event": "local_share", "on": label.is_some()})),
466 Some(CallUpdate::Camera(on)) => emit(json!({"event": "camera", "on": on})),
467 Some(CallUpdate::Muted(muted)) => emit(json!({"event": "muted", "muted": muted})),
468 Some(CallUpdate::OwnHand(hand)) => emit(json!({"event": "own_hand", "raised": hand.is_some()})),
469 Some(CallUpdate::Reaction { mri, reaction }) => emit(json!({"event": "reaction", "from": matrix.name_of(&VideoKey::Person(mri)), "reaction": format!("{reaction:?}")})),
470 Some(CallUpdate::Captions(state)) => emit(json!({"event": "captions", "state": match state {
471 CaptionState::Off => "off".to_owned(),
472 CaptionState::Starting => "starting".to_owned(),
473 CaptionState::On => "on".to_owned(),
474 CaptionState::Failed(reason) => format!("failed: {reason}"),
475 }})),
476 Some(CallUpdate::Caption(entry)) => {
477 if entry.is_final {
478 emit(json!({"event": "caption", "speaker": entry.display_name, "text": entry.text}));
479 }
480 }
481 Some(CallUpdate::Recording(on)) => emit(json!({"event": "recording", "on": on})),
482 Some(CallUpdate::RecordingAudioOnly(on)) => emit(json!({"event": "recording_audio_only", "on": on})),
483 Some(CallUpdate::Transcribing(on)) => emit(json!({"event": "transcribing", "on": on})),
484 Some(CallUpdate::ConsentRequired(on)) => emit(json!({"event": "consent_required", "on": on})),
485 Some(CallUpdate::Capability(capability)) => emit(json!({"event": "capability", "locked": capability.locked, "attendee_mic_off": capability.attendee_mic_off, "attendee_camera_off": capability.attendee_camera_off})),
486 Some(CallUpdate::MeetingOptions(result) | CallUpdate::MeetingOptionsSaved(result)) => match result {
487 Ok(options) => {
488 emit(json!({"event": "options", "options": options_json(&options)}));
489 if matrix.original_options.is_none() {
490 matrix.original_options = Some(options.clone());
491 }
492 matrix.options = Some(options);
493 }
494 Err(reason) => emit(json!({"event": "options", "error": reason.chars().take(200).collect::<String>()})),
495 },
496 Some(CallUpdate::Organizer { action, outcome }) => emit(json!({"event": "organizer", "action": action, "status": outcome.as_ref().ok(), "error": outcome.err().map(|reason| reason.chars().take(200).collect::<String>())})),
497 Some(CallUpdate::Whiteboard(share)) => emit(json!({"event": "whiteboard", "active": share.is_some()})),
498 Some(CallUpdate::BreakoutMove(_)) => emit(json!({"event": "breakout_move"})),
499 Some(CallUpdate::BreakoutRoom { .. }) => emit(json!({"event": "breakout_room"})),
500 Some(CallUpdate::MeetingChat(thread)) => emit(json!({"event": "meeting_chat", "same_thread": thread == thread_id})),
501 Some(CallUpdate::Health(health)) => {
502 let summary = json!({"event": "health", "level": format!("{:?}", health.level), "path": format!("{:?}", health.path)});
503 if summary != last_health {
504 emit(summary.clone());
505 last_health = summary;
506 }
507 }
508 Some(CallUpdate::Notice(text)) => emit(json!({"event": "notice", "text": text})),
509 Some(_) => {}
510 None => break,
511 },
512 line = lines.recv() => {
513 let Some(line) = line else { continue };
514 emit(json!({"event": "command", "line": line}));
515 for command in matrix.command(&line).await {
516 let _ = handle.commands.send(command);
517 }
518 }
519 _ = tick.tick() => {
520 let frames: serde_json::Map<String, Value> = window
521 .frames
522 .iter()
523 .map(|(key, (count, width, height))| (matrix.name_of(key), json!({"frames": count, "size": format!("{width}x{height}")})))
524 .collect();
525 emit(json!({
526 "event": "stats",
527 "t": started.elapsed().as_secs(),
528 "local_level": (window.local_level * 1000.0).round() / 1000.0,
529 "remote_level": (window.remote_level * 1000.0).round() / 1000.0,
530 "inbound": packets.0,
531 "outbound": packets.1,
532 "video": frames,
533 }));
534 window = Window::default();
535 }
536 }
537 }
538 emit(json!({"event": "ended", "reason": ended}));
539 let gone_started = Instant::now();
540 let mut gone = false;
541 while gone_started.elapsed() < GONE_LIMIT {
542 if matches!(fetch_live_meeting(&session, &thread_id).await, Ok(None)) {
543 gone = true;
544 break;
545 }
546 tokio::time::sleep(REPORT_EVERY).await;
547 }
548 emit(json!({"event": "live_state_gone", "gone": gone, "after_s": gone_started.elapsed().as_secs()}));
549 engine.stop().await;
550 }
@@ -0,0 +1,550 @@
1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::time::{Duration, Instant};
4
5use calling::meeting::fetch_live_meeting;
6use calling::relay::ic3_scope;
7use calling::signaling::{CHATSVC_REGION, fetch_self};
8use calling::{
9 CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingOptions, MeetingRole, MeetingTarget, Modality,
10 MuteCommand, Reaction, RecordingKind, RosterEntry, ShareKind, ShareSource, StopScope, TileDetail, VideoKey, VideoWant,
11};
12use chatsvc::InstanceNames;
13use chatsvc::recap::Recap;
14use serde_json::{Value, json};
15use session::{DEFAULT_ENDPOINT, Method, Request, Scope, Session, SPACES};
16
17const CREATE_URL: &str =
18 "https://teams.cloud.microsoft/api/mt/emea/beta/me/calendarEvents/privateMeeting/schedulingService/create";
19const SUBJECT: &str = "Native client test";
20const REPORT_EVERY: Duration = Duration::from_secs(2);
21const THREAD_PROPERTY_RETRIES: usize = 8;
22const GONE_LIMIT: Duration = Duration::from_secs(90);
23const GRAPH_CHATS: &str = "https://graph.microsoft.com/v1.0/chats";
24
25struct Arguments {
26 link_out: Option<PathBuf>,
27 thread_out: Option<PathBuf>,
28 recap_thread: Option<String>,
29}
30
31fn arguments() -> Arguments {
32 let mut parsed = Arguments { link_out: None, thread_out: None, recap_thread: None };
33 let mut input = std::env::args().skip(1);
34 while let Some(flag) = input.next() {
35 match flag.as_str() {
36 "--link-out" => parsed.link_out = input.next().map(PathBuf::from),
37 "--thread-out" => parsed.thread_out = input.next().map(PathBuf::from),
38 "--recap" => parsed.recap_thread = input.next(),
39 _ => {}
40 }
41 }
42 parsed
43}
44
45fn emit(value: Value) {
46 println!("@{value}");
47}
48
49fn main() {
50 for (name, value) in [("CALLING_AUDIO", "tone"), ("CALLING_VIDEO", "pattern")] {
51 if std::env::var_os(name).is_none() {
52 // SAFETY: nothing else runs yet; the runtime below starts after this.
53 unsafe { std::env::set_var(name, value) };
54 }
55 }
56 tokio::runtime::Runtime::new().expect("runtime").block_on(run());
57}
58
59fn as_object(value: &Value) -> Option<Value> {
60 match value {
61 Value::String(text) => serde_json::from_str(text).ok(),
62 Value::Object(_) => Some(value.clone()),
63 _ => None,
64 }
65}
66
67fn encoded(value: &str) -> String {
68 value
69 .bytes()
70 .map(|byte| match byte {
71 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (byte as char).to_string(),
72 other => format!("%{other:02X}"),
73 })
74 .collect()
75}
76
77async fn tenant_and_organizer(session: &Session, thread_id: &str) -> (Option<String>, Option<String>) {
78 let url = format!(
79 "https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
80 encoded(thread_id)
81 );
82 let Ok(response) = session.send(Request::get(url), &ic3_scope()).await else {
83 return (None, None);
84 };
85 let properties = &response.body["properties"];
86 let meeting = as_object(&properties["meeting"]);
87 let text = |value: &Value| value.as_str().filter(|text| !text.is_empty()).map(str::to_owned);
88 let tenant = meeting
89 .as_ref()
90 .and_then(|meeting| text(&meeting["tenantId"]))
91 .or_else(|| text(&properties["addedByTenantId"]));
92 (tenant, meeting.as_ref().and_then(|meeting| text(&meeting["organizerId"])))
93}
94
95fn find_text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
96 match value {
97 Value::Object(map) => map.iter().find_map(|(key, inner)| {
98 let direct = keys.iter().any(|wanted| key.eq_ignore_ascii_case(wanted)).then(|| inner.as_str().filter(|text| !text.is_empty())).flatten();
99 direct.or_else(|| find_text(inner, keys))
100 }),
101 Value::Array(items) => items.iter().find_map(|item| find_text(item, keys)),
102 _ => None,
103 }
104}
105
106fn roster_json(entries: &[RosterEntry], own_mri: Option<&str>) -> Value {
107 Value::Array(
108 entries
109 .iter()
110 .map(|entry| {
111 json!({
112 "name": if Some(entry.mri.as_str()) == own_mri { "(me)" } else { entry.display_name.as_str() },
113 "muted": entry.muted,
114 "lobby": entry.in_lobby,
115 "video": entry.has_video,
116 "sharing": entry.sharing,
117 "hand": entry.hand.is_some(),
118 "spotlight": entry.spotlight.is_some(),
119 "organizer": entry.organizer,
120 "role": entry.role.map(|role| format!("{role:?}")),
121 "mic_blocked": entry.limits.mic_blocked.is_some(),
122 "camera_blocked": entry.limits.camera_blocked.is_some(),
123 "mic_released": entry.limits.mic_released.is_some(),
124 "camera_released": entry.limits.camera_released.is_some(),
125 })
126 })
127 .collect(),
128 )
129}
130
131fn options_json(options: &MeetingOptions) -> Value {
132 json!({
133 "bypass_lobby": options.bypass_lobby,
134 "presenters": options.presenters,
135 "attendee_mic": options.attendee_mic,
136 "attendee_camera": options.attendee_camera,
137 "meeting_chat": options.meeting_chat,
138 "reactions": options.reactions,
139 "record_automatically": options.record_automatically,
140 })
141}
142
143fn reaction_named(name: &str) -> Option<Reaction> {
144 Reaction::ALL.into_iter().find(|reaction| format!("{reaction:?}").eq_ignore_ascii_case(name))
145}
146
147#[derive(Default)]
148struct Window {
149 local_level: f32,
150 remote_level: f32,
151 frames: HashMap<VideoKey, (usize, u32, u32)>,
152}
153
154struct Matrix {
155 session: Session,
156 thread_id: String,
157 own_mri: Option<String>,
158 roster: Vec<RosterEntry>,
159 options: Option<MeetingOptions>,
160 original_options: Option<MeetingOptions>,
161}
162
163impl Matrix {
164 fn mri_of(&self, name: &str) -> Option<String> {
165 self.roster
166 .iter()
167 .find(|entry| entry.display_name.eq_ignore_ascii_case(name))
168 .or_else(|| self.roster.iter().find(|entry| entry.display_name.to_lowercase().contains(&name.to_lowercase())))
169 .map(|entry| entry.mri.clone())
170 }
171
172 fn name_of(&self, key: &VideoKey) -> String {
173 match key {
174 VideoKey::Person(mri) => self
175 .roster
176 .iter()
177 .find(|entry| &entry.mri == mri)
178 .map_or_else(|| "unknown".to_owned(), |entry| entry.display_name.clone()),
179 other => format!("{other:?}"),
180 }
181 }
182
183 async fn command(&mut self, line: &str) -> Vec<CallCommand> {
184 let line = line.trim();
185 let (verb, rest) = line.split_once(' ').unwrap_or((line, ""));
186 let rest = rest.trim();
187 let person = |matrix: &Matrix, name: &str| {
188 let found = matrix.mri_of(name);
189 if found.is_none() {
190 emit(json!({"event": "error", "command": verb, "reason": "no such person in the roster"}));
191 }
192 found
193 };
194 let on = |text: &str| matches!(text, "on" | "true" | "yes");
195 let split_last = |text: &str| text.rsplit_once(' ').map(|(head, tail)| (head.trim().to_owned(), tail.trim().to_owned()));
196 match verb {
197 "admit" => person(self, rest).map(|mri| vec![CallCommand::Admit { mri }]).unwrap_or_default(),
198 "deny" => person(self, rest).map(|mri| vec![CallCommand::Deny { mri }]).unwrap_or_default(),
199 "admit-all" => vec![CallCommand::AdmitAll],
200 "mute" => person(self, rest).map(|mri| vec![CallCommand::MuteParticipant { mri }]).unwrap_or_default(),
201 "mute-all" => vec![CallCommand::MuteAll],
202 "spotlight" => person(self, rest).map(|mri| vec![CallCommand::Spotlight { mri }]).unwrap_or_default(),
203 "unspotlight" => person(self, rest).map(|mri| vec![CallCommand::StopSpotlight { mri }]).unwrap_or_default(),
204 "remove" => person(self, rest).map(|mri| vec![CallCommand::RemoveParticipant { mri }]).unwrap_or_default(),
205 "lower" => person(self, rest).map(|mri| vec![CallCommand::LowerHand { mri }]).unwrap_or_default(),
206 "lower-all" => vec![CallCommand::LowerAllHands],
207 "role" => {
208 let Some((name, role)) = split_last(rest) else { return Vec::new() };
209 let role = if role == "presenter" { MeetingRole::Presenter } else { MeetingRole::Attendee };
210 person(self, &name).map(|mri| vec![CallCommand::SetRole { mri, role }]).unwrap_or_default()
211 }
212 "allow-mic" | "allow-camera" | "block-mic" | "block-camera" => {
213 let modality = if verb.ends_with("mic") { Modality::Mic } else { Modality::Camera };
214 let allowed = verb.starts_with("allow");
215 person(self, rest).map(|mri| vec![CallCommand::SetAttendeeModality { mri, modality, allowed }]).unwrap_or_default()
216 }
217 "restrict" => {
218 let mic_off = rest.contains("mic");
219 let camera_off = rest.contains("camera");
220 vec![CallCommand::SetAttendeeRestrictions { mic_off, camera_off }]
221 }
222 "lock" => vec![CallCommand::SetLock(on(rest))],
223 "options" => vec![CallCommand::LoadMeetingOptions],
224 "option" => {
225 let (Some(current), Some((name, value))) = (self.options.clone(), split_last(rest)) else {
226 emit(json!({"event": "error", "command": verb, "reason": "load options first"}));
227 return Vec::new();
228 };
229 let mut edited = current.clone();
230 match name.as_str() {
231 "reactions" => edited.reactions = on(&value),
232 "chat" => edited.meeting_chat = value,
233 "lobby" => edited.bypass_lobby = value,
234 "presenters" => edited.presenters = value,
235 "attendee_mic" => edited.attendee_mic = on(&value),
236 "attendee_camera" => edited.attendee_camera = on(&value),
237 _ => {}
238 }
239 vec![CallCommand::SaveMeetingOptions(current.changes(&edited))]
240 }
241 "options-restore" => match (&self.options, &self.original_options) {
242 (Some(current), Some(original)) => vec![CallCommand::SaveMeetingOptions(current.changes(original))],
243 _ => Vec::new(),
244 },
245 "captions" => vec![CallCommand::SetCaptions(on(rest))],
246 "language" => vec![CallCommand::SetCaptionLanguage(rest.to_owned())],
247 "record" => {
248 let kind = match rest {
249 "audio" => RecordingKind::AudioOnly,
250 "transcript" => RecordingKind::TranscriptOnly,
251 _ => RecordingKind::Video,
252 };
253 vec![CallCommand::StartRecording { kind, title: SUBJECT.to_owned() }]
254 }
255 "stop" => {
256 let scope = match rest {
257 "recording" => StopScope::RecordingOnly,
258 "transcription" => StopScope::TranscriptionOnly,
259 _ => StopScope::Both,
260 };
261 vec![CallCommand::StopRecording { scope }]
262 }
263 "camera" => vec![CallCommand::SetCamera(on(rest))],
264 "share" if on(rest) => vec![CallCommand::StartShare(ShareSource { id: 0, kind: ShareKind::Screen, title: String::new() })],
265 "share" => vec![CallCommand::StopShare],
266 "self-mute" => vec![CallCommand::Mute(if on(rest) { MuteCommand::Mute } else { MuteCommand::Unmute })],
267 "hand" => vec![CallCommand::SetHand(on(rest))],
268 "react" => reaction_named(rest).map(|reaction| vec![CallCommand::SendReaction(reaction)]).unwrap_or_default(),
269 "incoming" => vec![CallCommand::SetIncomingVideo(on(rest))],
270 "wants" => {
271 let wants = rest
272 .split(',')
273 .filter_map(|item| {
274 let (detail, name) = item.trim().split_once(':')?;
275 let detail = if detail == "stage" { TileDetail::Stage } else { TileDetail::Small };
276 Some(VideoWant { mri: self.mri_of(name)?, detail })
277 })
278 .collect();
279 vec![CallCommand::SetVideoWants(wants)]
280 }
281 "chat" => {
282 self.send_chat(rest).await;
283 Vec::new()
284 }
285 "chat-read" => {
286 self.read_chat().await;
287 Vec::new()
288 }
289 "end" => vec![CallCommand::EndMeeting],
290 "hangup" => vec![CallCommand::Hangup],
291 _ => {
292 emit(json!({"event": "error", "command": verb, "reason": "unknown command"}));
293 Vec::new()
294 }
295 }
296 }
297
298 async fn send_chat(&self, text: &str) {
299 let url = format!("{GRAPH_CHATS}/{}/messages", encoded(&self.thread_id));
300 let body = json!({"body": {"contentType": "text", "content": text}});
301 let outcome = self.session.request(Method::Post, &url, &Scope::graph("Chat.ReadWrite"), Some(body)).await;
302 emit(json!({"event": "chat_sent", "status": outcome.as_ref().map(|answer| answer.status).ok(), "error": outcome.err().map(|error| error.to_string().chars().take(160).collect::<String>())}));
303 }
304
305 async fn read_chat(&self) {
306 let url = format!("{GRAPH_CHATS}/{}/messages?$top=20", encoded(&self.thread_id));
307 match self.session.request(Method::Get, &url, &Scope::graph("Chat.ReadWrite"), None).await {
308 Ok(answer) => {
309 let messages: Vec<Value> = answer.body["value"]
310 .as_array()
311 .into_iter()
312 .flatten()
313 .filter(|message| message["messageType"].as_str() == Some("message"))
314 .map(|message| {
315 let sender = message.pointer("/from/user/displayName").and_then(Value::as_str).unwrap_or("?");
316 let own = message.pointer("/from/user/id").and_then(Value::as_str).is_some_and(|id| self.own_mri.as_deref().is_some_and(|mri| mri.ends_with(id)));
317 json!({"from": if own { "(me)" } else { sender }, "text": message.pointer("/body/content").and_then(Value::as_str).unwrap_or_default().chars().take(120).collect::<String>()})
318 })
319 .collect();
320 emit(json!({"event": "chat_read", "status": answer.status, "messages": messages}));
321 }
322 Err(error) => emit(json!({"event": "chat_read", "error": error.to_string().chars().take(160).collect::<String>()})),
323 }
324 }
325}
326
327async fn recap(session: &Session, thread_id: &str) {
328 let recap = Recap::new(session);
329 let occurrences = match recap.occurrences(thread_id).await {
330 Ok(occurrences) => occurrences,
331 Err(error) => {
332 emit(json!({"event": "recap", "error": format!("{error:?}")}));
333 return;
334 }
335 };
336 emit(json!({"event": "recap_occurrences", "count": occurrences.len()}));
337 for occurrence in &occurrences {
338 match recap.details(occurrence).await {
339 Ok(details) => {
340 emit(json!({
341 "event": "recap_recording",
342 "audio_only": details.audio_only,
343 "duration_seconds": details.duration_seconds,
344 "expires_set": details.expires_at.is_some(),
345 "transcript": details.transcript_id.is_some(),
346 }));
347 let deleted = recap.delete_recording(&details).await;
348 emit(json!({"event": "recap_deleted", "ok": deleted.is_ok(), "error": deleted.err().map(|error| format!("{error:?}"))}));
349 }
350 Err(error) => emit(json!({"event": "recap_recording", "error": format!("{error:?}")})),
351 }
352 }
353}
354
355async fn run() {
356 let arguments = arguments();
357 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
358 let session = Session::connect(&endpoint).await.expect("browser");
359 if let Some(thread_id) = &arguments.recap_thread {
360 recap(&session, thread_id).await;
361 return;
362 }
363 let poll_session = Session::connect(&endpoint).await.expect("browser");
364 let me = fetch_self(&session).await.expect("own identity");
365 let started = Instant::now();
366
367 let body = json!({"meetingType": "MeetNow", "isStreamEnabled": false, "subject": SUBJECT, "unhideChatThread": true});
368 let created = session
369 .request(Method::Post, CREATE_URL, &Scope::new(SPACES, "user_impersonation"), Some(body))
370 .await
371 .expect("create meeting");
372 let thread_id = created.body.pointer("/value/groupContext/threadId").and_then(Value::as_str).expect("meeting thread").to_owned();
373 emit(json!({"event": "created", "status": created.status}));
374 if let Some(path) = &arguments.thread_out {
375 std::fs::write(path, &thread_id).expect("thread file");
376 }
377
378 let (mut tenant_id, mut organizer_id) = tenant_and_organizer(&session, &thread_id).await;
379 for _ in 0..THREAD_PROPERTY_RETRIES {
380 if tenant_id.is_some() {
381 break;
382 }
383 tokio::time::sleep(REPORT_EVERY).await;
384 (tenant_id, organizer_id) = tenant_and_organizer(&session, &thread_id).await;
385 }
386 let target = MeetingTarget {
387 thread_id: thread_id.clone(),
388 tenant_id: tenant_id.expect("tenant id"),
389 organizer_id: organizer_id.unwrap_or_else(|| me.object_id.clone()),
390 meeting_data: None,
391 };
392 let join_link = find_text(&created.body, &["joinUrl", "meetingJoinUrl", "joinWebUrl"]).map_or_else(
393 || {
394 let context = json!({"Tid": target.tenant_id, "Oid": target.organizer_id}).to_string();
395 format!("https://teams.microsoft.com/l/meetup-join/{}/0?context={}", encoded(&thread_id), encoded(&context))
396 },
397 str::to_owned,
398 );
399 if let Some(path) = &arguments.link_out {
400 std::fs::write(path, &join_link).expect("link file");
401 }
402 let config = EngineConfig {
403 ringable: false,
404 trace: std::env::var_os("LIVE_TRACE").is_some(),
405 instance: InstanceNames {
406 global: "__liveMatrixTrouter".into(),
407 binding: "__liveMatrixRealtime".into(),
408 endpoint_storage_key: "__liveMatrixEpid".into(),
409 },
410 ..EngineConfig::default()
411 };
412 let (engine, _events) = CallEngine::start(session.clone(), poll_session, config).await.expect("engine");
413 let mut handle = engine.start_call(CallSpec::Meeting(target));
414 emit(json!({"event": "joining", "after_ms": started.elapsed().as_millis()}));
415
416 let (line_sender, mut lines) = tokio::sync::mpsc::unbounded_channel::<String>();
417 std::thread::spawn(move || {
418 for line in std::io::stdin().lines().map_while(Result::ok) {
419 if line_sender.send(line).is_err() {
420 break;
421 }
422 }
423 });
424
425 let mut matrix = Matrix { session: session.clone(), thread_id: thread_id.clone(), own_mri: None, roster: Vec::new(), options: None, original_options: None };
426 let mut window = Window::default();
427 let mut last_roster = Value::Null;
428 let mut last_health = Value::Null;
429 let mut packets = (0u64, 0u64);
430 let mut ended = None;
431 let mut tick = tokio::time::interval(REPORT_EVERY);
432 while ended.is_none() {
433 tokio::select! {
434 update = handle.updates.recv() => match update {
435 Some(CallUpdate::State(CallState::Ended { reason })) => ended = Some(format!("{reason:?}")),
436 Some(CallUpdate::State(state)) => emit(json!({"event": "state", "state": format!("{state:?}").split([' ', '{', '(']).next().unwrap_or_default()})),
437 Some(CallUpdate::OwnIdentity { mri }) => matrix.own_mri = Some(mri),
438 Some(CallUpdate::Roster(entries)) => {
439 let summary = roster_json(&entries, matrix.own_mri.as_deref());
440 if summary != last_roster {
441 emit(json!({"event": "roster", "entries": summary}));
442 last_roster = summary;
443 }
444 matrix.roster = entries;
445 }
446 Some(CallUpdate::Lobby(waiting)) => emit(json!({"event": "lobby_self", "waiting": waiting})),
447 Some(CallUpdate::Levels { local, remote }) => {
448 window.local_level = window.local_level.max(local);
449 window.remote_level = window.remote_level.max(remote);
450 }
451 Some(CallUpdate::Stats { inbound_packets, outbound_packets }) => packets = (inbound_packets, outbound_packets),
452 Some(CallUpdate::VideoReady) => {
453 for (key, picture) in handle.video.drain() {
454 let slot = window.frames.entry(key).or_insert((0, 0, 0));
455 slot.0 += 1;
456 slot.1 = picture.width;
457 slot.2 = picture.height;
458 }
459 }
460 Some(CallUpdate::Speakers(speakers)) => {
461 let names: Vec<String> = speakers.iter().map(|mri| matrix.name_of(&VideoKey::Person(mri.clone()))).collect();
462 emit(json!({"event": "speakers", "names": names}));
463 }
464 Some(CallUpdate::ScreenShare(sharer)) => emit(json!({"event": "screen_share", "sharer": sharer.map(|mri| matrix.name_of(&VideoKey::Person(mri)))})),
465 Some(CallUpdate::LocalShare(label)) => emit(json!({"event": "local_share", "on": label.is_some()})),
466 Some(CallUpdate::Camera(on)) => emit(json!({"event": "camera", "on": on})),
467 Some(CallUpdate::Muted(muted)) => emit(json!({"event": "muted", "muted": muted})),
468 Some(CallUpdate::OwnHand(hand)) => emit(json!({"event": "own_hand", "raised": hand.is_some()})),
469 Some(CallUpdate::Reaction { mri, reaction }) => emit(json!({"event": "reaction", "from": matrix.name_of(&VideoKey::Person(mri)), "reaction": format!("{reaction:?}")})),
470 Some(CallUpdate::Captions(state)) => emit(json!({"event": "captions", "state": match state {
471 CaptionState::Off => "off".to_owned(),
472 CaptionState::Starting => "starting".to_owned(),
473 CaptionState::On => "on".to_owned(),
474 CaptionState::Failed(reason) => format!("failed: {reason}"),
475 }})),
476 Some(CallUpdate::Caption(entry)) => {
477 if entry.is_final {
478 emit(json!({"event": "caption", "speaker": entry.display_name, "text": entry.text}));
479 }
480 }
481 Some(CallUpdate::Recording(on)) => emit(json!({"event": "recording", "on": on})),
482 Some(CallUpdate::RecordingAudioOnly(on)) => emit(json!({"event": "recording_audio_only", "on": on})),
483 Some(CallUpdate::Transcribing(on)) => emit(json!({"event": "transcribing", "on": on})),
484 Some(CallUpdate::ConsentRequired(on)) => emit(json!({"event": "consent_required", "on": on})),
485 Some(CallUpdate::Capability(capability)) => emit(json!({"event": "capability", "locked": capability.locked, "attendee_mic_off": capability.attendee_mic_off, "attendee_camera_off": capability.attendee_camera_off})),
486 Some(CallUpdate::MeetingOptions(result) | CallUpdate::MeetingOptionsSaved(result)) => match result {
487 Ok(options) => {
488 emit(json!({"event": "options", "options": options_json(&options)}));
489 if matrix.original_options.is_none() {
490 matrix.original_options = Some(options.clone());
491 }
492 matrix.options = Some(options);
493 }
494 Err(reason) => emit(json!({"event": "options", "error": reason.chars().take(200).collect::<String>()})),
495 },
496 Some(CallUpdate::Organizer { action, outcome }) => emit(json!({"event": "organizer", "action": action, "status": outcome.as_ref().ok(), "error": outcome.err().map(|reason| reason.chars().take(200).collect::<String>())})),
497 Some(CallUpdate::Whiteboard(share)) => emit(json!({"event": "whiteboard", "active": share.is_some()})),
498 Some(CallUpdate::BreakoutMove(_)) => emit(json!({"event": "breakout_move"})),
499 Some(CallUpdate::BreakoutRoom { .. }) => emit(json!({"event": "breakout_room"})),
500 Some(CallUpdate::MeetingChat(thread)) => emit(json!({"event": "meeting_chat", "same_thread": thread == thread_id})),
501 Some(CallUpdate::Health(health)) => {
502 let summary = json!({"event": "health", "level": format!("{:?}", health.level), "path": format!("{:?}", health.path)});
503 if summary != last_health {
504 emit(summary.clone());
505 last_health = summary;
506 }
507 }
508 Some(CallUpdate::Notice(text)) => emit(json!({"event": "notice", "text": text})),
509 Some(_) => {}
510 None => break,
511 },
512 line = lines.recv() => {
513 let Some(line) = line else { continue };
514 emit(json!({"event": "command", "line": line}));
515 for command in matrix.command(&line).await {
516 let _ = handle.commands.send(command);
517 }
518 }
519 _ = tick.tick() => {
520 let frames: serde_json::Map<String, Value> = window
521 .frames
522 .iter()
523 .map(|(key, (count, width, height))| (matrix.name_of(key), json!({"frames": count, "size": format!("{width}x{height}")})))
524 .collect();
525 emit(json!({
526 "event": "stats",
527 "t": started.elapsed().as_secs(),
528 "local_level": (window.local_level * 1000.0).round() / 1000.0,
529 "remote_level": (window.remote_level * 1000.0).round() / 1000.0,
530 "inbound": packets.0,
531 "outbound": packets.1,
532 "video": frames,
533 }));
534 window = Window::default();
535 }
536 }
537 }
538 emit(json!({"event": "ended", "reason": ended}));
539 let gone_started = Instant::now();
540 let mut gone = false;
541 while gone_started.elapsed() < GONE_LIMIT {
542 if matches!(fetch_live_meeting(&session, &thread_id).await, Ok(None)) {
543 gone = true;
544 break;
545 }
546 tokio::time::sleep(REPORT_EVERY).await;
547 }
548 emit(json!({"event": "live_state_gone", "gone": gone, "after_s": gone_started.elapsed().as_secs()}));
549 engine.stop().await;
550}
scripts/live-matrix.mjs added +290 −0
@@ -0,0 +1,290 @@
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);
@@ -0,0 +1,290 @@
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).
3import { spawn } from 'node:child_process';
4import { createServer } from 'node:http';
5import { readFileSync, writeFileSync, existsSync } from 'node:fs';
6
7const [binary, workDir] = process.argv.slice(2);
8const GUEST_ENDPOINT = process.env.GUEST_CDP ?? 'http://127.0.0.1:9471';
9const OWN_ENDPOINT = process.env.OWN_CDP ?? 'http://127.0.0.1:9222';
10const PORT = Number(process.env.MATRIX_PORT ?? 9472);
11
12const 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.
24const 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
62const 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
76class 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
98const guests = new Map();
99const events = [];
100let child;
101let guestBrowser;
102let ownBrowser;
103
104// Shared Chrome: other clients reload or close the first Teams tab, which took our Trouter with it.
105const TAB_PROXY_PORT = PORT + 1;
106let organizerTabId;
107
108async 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
117createServer(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
127async 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
151async 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
157const 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
169async 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
189async 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
198async 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
205async 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
212async 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
221async 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
234const trouterFrames = [];
235async 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
249const 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
269guestBrowser = await new Browser(GUEST_ENDPOINT).connect();
270ownBrowser = await new Browser(OWN_ENDPOINT).connect();
271if (!existsSync(workDir)) throw new Error('work dir missing');
272
273createServer(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');
290console.log('live matrix driver on ' + PORT);