BlueGit

ict rusty-teams

Merge branch 'fix/recap-live' into integrate/calls-10

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 7 weeks ago

Hash
fac848749d4c601c33aebbf36220f3c9b6d3037e
6 files changed +327 −7
crates/calling/examples/meet_now.rs +11 −2
@@ -5,7 +5,7 @@ use calling::meeting::fetch_live_meeting;
5 5 use calling::relay::ic3_scope;
6 6 use calling::signaling::{CHATSVC_REGION, fetch_self};
7 7 use calling::{
8 BackgroundCache, BackgroundChoice, CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingTarget, Reaction, RecordingKind, ShareKind,
8 BackgroundCache, BackgroundChoice, CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingTarget, MuteCommand, Reaction, RecordingKind, ShareKind,
9 9 ShareSource, StopScope,
10 10 };
11 11 use chatsvc::InstanceNames;
@@ -40,6 +40,8 @@ struct Arguments {
40 40 mute_all: bool,
41 41 blur: bool,
42 42 record: bool,
43 record_for: Duration,
44 unmute: bool,
43 45 whiteboard_state: bool,
44 46 background: bool,
45 47 stop_media_after: Option<Duration>,
@@ -59,6 +61,8 @@ fn arguments() -> Arguments {
59 61 mute_all: false,
60 62 blur: false,
61 63 record: false,
64 record_for: RECORD_HOLD,
65 unmute: false,
62 66 whiteboard_state: false,
63 67 background: false,
64 68 stop_media_after: None,
@@ -80,6 +84,8 @@ fn arguments() -> Arguments {
80 84 parsed.camera = true;
81 85 }
82 86 "--record" => parsed.record = true,
87 "--record-for" => parsed.record_for = input.next().and_then(|value| value.parse().ok()).map_or(RECORD_HOLD, Duration::from_secs),
88 "--unmute" => parsed.unmute = true,
83 89 "--whiteboard-state" => parsed.whiteboard_state = true,
84 90 "--resolve-by-id" => parsed.resolve_by_id = true,
85 91 "--background" => {
@@ -282,7 +288,7 @@ async fn run() {
282 288 println!("# recording state: {}", if on { "on" } else { "off" });
283 289 if on {
284 290 features.recording_seen_on = true;
285 features.recording_stop_due = Some(Instant::now() + RECORD_HOLD);
291 features.recording_stop_due = Some(Instant::now() + arguments.record_for);
286 292 } else if features.recording_seen_on {
287 293 features.recording_seen_off = true;
288 294 features.recording_done = true;
@@ -398,6 +404,9 @@ async fn run() {
398 404 if arguments.camera {
399 405 let _ = handle.commands.send(CallCommand::SetCamera(true));
400 406 }
407 if arguments.unmute {
408 let _ = handle.commands.send(CallCommand::Mute(MuteCommand::Unmute));
409 }
401 410 if arguments.extras {
402 411 let _ = handle.commands.send(CallCommand::SetHand(true));
403 412 for reaction in Reaction::ALL {
@@ -5,7 +5,7 @@ use calling::meeting::fetch_live_meeting;
5use calling::relay::ic3_scope;
5use calling::relay::ic3_scope;
6use calling::signaling::{CHATSVC_REGION, fetch_self};
6use calling::signaling::{CHATSVC_REGION, fetch_self};
7use calling::{
7use calling::{
8 BackgroundCache, BackgroundChoice, CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingTarget, Reaction, RecordingKind, ShareKind,
8 BackgroundCache, BackgroundChoice, CallCommand, CallEngine, CallSpec, CallState, CallUpdate, CaptionState, EngineConfig, MeetingTarget, MuteCommand, Reaction, RecordingKind, ShareKind,
9 ShareSource, StopScope,
9 ShareSource, StopScope,
10};
10};
11use chatsvc::InstanceNames;
11use chatsvc::InstanceNames;
@@ -40,6 +40,8 @@ struct Arguments {
40 mute_all: bool,
40 mute_all: bool,
41 blur: bool,
41 blur: bool,
42 record: bool,
42 record: bool,
43 record_for: Duration,
44 unmute: bool,
43 whiteboard_state: bool,
45 whiteboard_state: bool,
44 background: bool,
46 background: bool,
45 stop_media_after: Option<Duration>,
47 stop_media_after: Option<Duration>,
@@ -59,6 +61,8 @@ fn arguments() -> Arguments {
59 mute_all: false,
61 mute_all: false,
60 blur: false,
62 blur: false,
61 record: false,
63 record: false,
64 record_for: RECORD_HOLD,
65 unmute: false,
62 whiteboard_state: false,
66 whiteboard_state: false,
63 background: false,
67 background: false,
64 stop_media_after: None,
68 stop_media_after: None,
@@ -80,6 +84,8 @@ fn arguments() -> Arguments {
80 parsed.camera = true;
84 parsed.camera = true;
81 }
85 }
82 "--record" => parsed.record = true,
86 "--record" => parsed.record = true,
87 "--record-for" => parsed.record_for = input.next().and_then(|value| value.parse().ok()).map_or(RECORD_HOLD, Duration::from_secs),
88 "--unmute" => parsed.unmute = true,
83 "--whiteboard-state" => parsed.whiteboard_state = true,
89 "--whiteboard-state" => parsed.whiteboard_state = true,
84 "--resolve-by-id" => parsed.resolve_by_id = true,
90 "--resolve-by-id" => parsed.resolve_by_id = true,
85 "--background" => {
91 "--background" => {
@@ -282,7 +288,7 @@ async fn run() {
282 println!("# recording state: {}", if on { "on" } else { "off" });
288 println!("# recording state: {}", if on { "on" } else { "off" });
283 if on {
289 if on {
284 features.recording_seen_on = true;
290 features.recording_seen_on = true;
285 features.recording_stop_due = Some(Instant::now() + RECORD_HOLD);
291 features.recording_stop_due = Some(Instant::now() + arguments.record_for);
286 } else if features.recording_seen_on {
292 } else if features.recording_seen_on {
287 features.recording_seen_off = true;
293 features.recording_seen_off = true;
288 features.recording_done = true;
294 features.recording_done = true;
@@ -398,6 +404,9 @@ async fn run() {
398 if arguments.camera {
404 if arguments.camera {
399 let _ = handle.commands.send(CallCommand::SetCamera(true));
405 let _ = handle.commands.send(CallCommand::SetCamera(true));
400 }
406 }
407 if arguments.unmute {
408 let _ = handle.commands.send(CallCommand::Mute(MuteCommand::Unmute));
409 }
401 if arguments.extras {
410 if arguments.extras {
402 let _ = handle.commands.send(CallCommand::SetHand(true));
411 let _ = handle.commands.send(CallCommand::SetHand(true));
403 for reaction in Reaction::ALL {
412 for reaction in Reaction::ALL {
crates/calling/src/audio.rs +59 −0
@@ -32,6 +32,53 @@ impl SineGenerator {
32 32 }
33 33 }
34 34
35 pub struct ClipGenerator {
36 samples: Vec<i16>,
37 position: usize,
38 }
39
40 impl ClipGenerator {
41 pub fn from_wav(bytes: &[u8]) -> Option<Self> {
42 let mut format = None;
43 let mut offset = 12;
44 if bytes.get(0..4)? != b"RIFF" || bytes.get(8..12)? != b"WAVE" {
45 return None;
46 }
47 while offset + 8 <= bytes.len() {
48 let chunk_id = &bytes[offset..offset + 4];
49 let chunk_size = u32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().ok()?) as usize;
50 let body = bytes.get(offset + 8..(offset + 8 + chunk_size).min(bytes.len()))?;
51 match chunk_id {
52 b"fmt " => format = Some(body.get(0..16)?.to_vec()),
53 b"data" => {
54 let format = format?;
55 let channels = u16::from_le_bytes([format[2], format[3]]);
56 let rate = u32::from_le_bytes(format[4..8].try_into().ok()?);
57 let bits = u16::from_le_bytes([format[14], format[15]]);
58 if u16::from_le_bytes([format[0], format[1]]) != 1 || channels != 1 || rate != SAMPLE_RATE || bits != 16 {
59 return None;
60 }
61 let samples: Vec<i16> = body.as_chunks::<2>().0.iter().map(|pair| i16::from_le_bytes(*pair)).collect();
62 return (!samples.is_empty()).then_some(ClipGenerator { samples, position: 0 });
63 }
64 _ => {}
65 }
66 offset += 8 + chunk_size + chunk_size % 2;
67 }
68 None
69 }
70
71 pub fn next_frame(&mut self) -> Vec<i16> {
72 (0..FRAME_SAMPLES)
73 .map(|_| {
74 let sample = self.samples[self.position];
75 self.position = (self.position + 1) % self.samples.len();
76 sample
77 })
78 .collect()
79 }
80 }
81
35 82 pub fn rms(samples: &[i16]) -> f32 {
36 83 if samples.is_empty() {
37 84 return 0.0;
@@ -96,4 +143,16 @@ mod tests {
96 143 assert!((rms(&samples) - 0.3 / 2f32.sqrt()).abs() < 0.01);
97 144 assert_eq!(tone_ratio(&vec![0; 4800], 440.0), 0.0);
98 145 }
146
147 #[test]
148 fn clip_generator_loops_a_mono_wav() {
149 let path = std::env::temp_dir().join(format!("clip-generator-{}.wav", std::process::id()));
150 write_wav(&path, &[1, 2, 3]).unwrap();
151 let bytes = std::fs::read(&path).unwrap();
152 std::fs::remove_file(&path).unwrap();
153 let frame = ClipGenerator::from_wav(&bytes).unwrap().next_frame();
154 assert_eq!(frame.len(), FRAME_SAMPLES);
155 assert_eq!(&frame[..5], &[1, 2, 3, 1, 2]);
156 assert!(ClipGenerator::from_wav(b"RIFF\0\0\0\0WAVE").is_none());
157 }
99 158 }
@@ -32,6 +32,53 @@ impl SineGenerator {
32 }
32 }
33}
33}
34
34
35pub struct ClipGenerator {
36 samples: Vec<i16>,
37 position: usize,
38}
39
40impl ClipGenerator {
41 pub fn from_wav(bytes: &[u8]) -> Option<Self> {
42 let mut format = None;
43 let mut offset = 12;
44 if bytes.get(0..4)? != b"RIFF" || bytes.get(8..12)? != b"WAVE" {
45 return None;
46 }
47 while offset + 8 <= bytes.len() {
48 let chunk_id = &bytes[offset..offset + 4];
49 let chunk_size = u32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().ok()?) as usize;
50 let body = bytes.get(offset + 8..(offset + 8 + chunk_size).min(bytes.len()))?;
51 match chunk_id {
52 b"fmt " => format = Some(body.get(0..16)?.to_vec()),
53 b"data" => {
54 let format = format?;
55 let channels = u16::from_le_bytes([format[2], format[3]]);
56 let rate = u32::from_le_bytes(format[4..8].try_into().ok()?);
57 let bits = u16::from_le_bytes([format[14], format[15]]);
58 if u16::from_le_bytes([format[0], format[1]]) != 1 || channels != 1 || rate != SAMPLE_RATE || bits != 16 {
59 return None;
60 }
61 let samples: Vec<i16> = body.as_chunks::<2>().0.iter().map(|pair| i16::from_le_bytes(*pair)).collect();
62 return (!samples.is_empty()).then_some(ClipGenerator { samples, position: 0 });
63 }
64 _ => {}
65 }
66 offset += 8 + chunk_size + chunk_size % 2;
67 }
68 None
69 }
70
71 pub fn next_frame(&mut self) -> Vec<i16> {
72 (0..FRAME_SAMPLES)
73 .map(|_| {
74 let sample = self.samples[self.position];
75 self.position = (self.position + 1) % self.samples.len();
76 sample
77 })
78 .collect()
79 }
80}
81
35pub fn rms(samples: &[i16]) -> f32 {
82pub fn rms(samples: &[i16]) -> f32 {
36 if samples.is_empty() {
83 if samples.is_empty() {
37 return 0.0;
84 return 0.0;
@@ -96,4 +143,16 @@ mod tests {
96 assert!((rms(&samples) - 0.3 / 2f32.sqrt()).abs() < 0.01);
143 assert!((rms(&samples) - 0.3 / 2f32.sqrt()).abs() < 0.01);
97 assert_eq!(tone_ratio(&vec![0; 4800], 440.0), 0.0);
144 assert_eq!(tone_ratio(&vec![0; 4800], 440.0), 0.0);
98 }
145 }
146
147 #[test]
148 fn clip_generator_loops_a_mono_wav() {
149 let path = std::env::temp_dir().join(format!("clip-generator-{}.wav", std::process::id()));
150 write_wav(&path, &[1, 2, 3]).unwrap();
151 let bytes = std::fs::read(&path).unwrap();
152 std::fs::remove_file(&path).unwrap();
153 let frame = ClipGenerator::from_wav(&bytes).unwrap().next_frame();
154 assert_eq!(frame.len(), FRAME_SAMPLES);
155 assert_eq!(&frame[..5], &[1, 2, 3, 1, 2]);
156 assert!(ClipGenerator::from_wav(b"RIFF\0\0\0\0WAVE").is_none());
157 }
99}
158}
crates/calling/src/audio_io.rs +29 −4
@@ -8,13 +8,14 @@ use libwebrtc::prelude::*;
8 8 use tokio::task::JoinHandle;
9 9 use tokio::time::interval;
10 10
11 use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
11 use crate::audio::{ClipGenerator, FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
12 12 use crate::devices::{self, DeviceChoice};
13 13
14 14 const TONE_AMPLITUDE: f32 = 0.3;
15 15 const SOURCE_QUEUE_MS: u32 = 100;
16 16 const FRAME_PERIOD: Duration = Duration::from_millis(10);
17 17 pub const AUDIO_MODE_ENV: &str = "CALLING_AUDIO";
18 pub const AUDIO_FILE_ENV: &str = "CALLING_AUDIO_FILE";
18 19
19 20 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20 21 pub enum AudioMode {
@@ -22,6 +23,7 @@ pub enum AudioMode {
22 23 Platform,
23 24 Tone,
24 25 Silence,
26 File,
25 27 }
26 28
27 29 impl AudioMode {
@@ -33,6 +35,7 @@ impl AudioMode {
33 35 match value.map(str::to_ascii_lowercase).as_deref() {
34 36 Some("tone") => AudioMode::Tone,
35 37 Some("silence") => AudioMode::Silence,
38 Some("file") => AudioMode::File,
36 39 _ => AudioMode::Platform,
37 40 }
38 41 }
@@ -93,11 +96,18 @@ impl AudioSetup {
93 96 feeder: None,
94 97 };
95 98 }
96 let amplitude = if mode == AudioMode::Tone { TONE_AMPLITUDE } else { 0.0 };
99 let generator = match mode {
100 AudioMode::File => std::env::var_os(AUDIO_FILE_ENV)
101 .and_then(|path| std::fs::read(path).ok())
102 .and_then(|bytes| ClipGenerator::from_wav(&bytes))
103 .map_or(FrameGenerator::Sine(SineGenerator::new(tone_hz, 0.0)), FrameGenerator::Clip),
104 AudioMode::Tone => FrameGenerator::Sine(SineGenerator::new(tone_hz, TONE_AMPLITUDE)),
105 AudioMode::Platform | AudioMode::Silence => FrameGenerator::Sine(SineGenerator::new(tone_hz, 0.0)),
106 };
97 107 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
98 108 let track = factory.create_audio_track("microphone", source.clone());
99 109 let running = Arc::new(AtomicBool::new(true));
100 let task = tokio::spawn(feed_frames(source, SineGenerator::new(tone_hz, amplitude), running.clone()));
110 let task = tokio::spawn(feed_frames(source, generator, running.clone()));
101 111 AudioSetup {
102 112 factory: factory.clone(),
103 113 track,
@@ -125,7 +135,21 @@ impl AudioSetup {
125 135 }
126 136 }
127 137
128 async fn feed_frames(source: NativeAudioSource, mut generator: SineGenerator, running: Arc<AtomicBool>) {
138 enum FrameGenerator {
139 Sine(SineGenerator),
140 Clip(ClipGenerator),
141 }
142
143 impl FrameGenerator {
144 fn next_frame(&mut self) -> Vec<i16> {
145 match self {
146 FrameGenerator::Sine(generator) => generator.next_frame(),
147 FrameGenerator::Clip(generator) => generator.next_frame(),
148 }
149 }
150 }
151
152 async fn feed_frames(source: NativeAudioSource, mut generator: FrameGenerator, running: Arc<AtomicBool>) {
129 153 let mut tick = interval(FRAME_PERIOD);
130 154 while running.load(Ordering::SeqCst) {
131 155 tick.tick().await;
@@ -150,6 +174,7 @@ mod tests {
150 174 assert_eq!(AudioMode::parse(None), AudioMode::Platform);
151 175 assert_eq!(AudioMode::parse(Some("tone")), AudioMode::Tone);
152 176 assert_eq!(AudioMode::parse(Some("SILENCE")), AudioMode::Silence);
177 assert_eq!(AudioMode::parse(Some("file")), AudioMode::File);
153 178 assert_eq!(AudioMode::parse(Some("whatever")), AudioMode::Platform);
154 179 }
155 180 }
@@ -8,13 +8,14 @@ use libwebrtc::prelude::*;
8use tokio::task::JoinHandle;
8use tokio::task::JoinHandle;
9use tokio::time::interval;
9use tokio::time::interval;
10
10
11use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
11use crate::audio::{ClipGenerator, FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
12use crate::devices::{self, DeviceChoice};
12use crate::devices::{self, DeviceChoice};
13
13
14const TONE_AMPLITUDE: f32 = 0.3;
14const TONE_AMPLITUDE: f32 = 0.3;
15const SOURCE_QUEUE_MS: u32 = 100;
15const SOURCE_QUEUE_MS: u32 = 100;
16const FRAME_PERIOD: Duration = Duration::from_millis(10);
16const FRAME_PERIOD: Duration = Duration::from_millis(10);
17pub const AUDIO_MODE_ENV: &str = "CALLING_AUDIO";
17pub const AUDIO_MODE_ENV: &str = "CALLING_AUDIO";
18pub const AUDIO_FILE_ENV: &str = "CALLING_AUDIO_FILE";
18
19
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20pub enum AudioMode {
21pub enum AudioMode {
@@ -22,6 +23,7 @@ pub enum AudioMode {
22 Platform,
23 Platform,
23 Tone,
24 Tone,
24 Silence,
25 Silence,
26 File,
25}
27}
26
28
27impl AudioMode {
29impl AudioMode {
@@ -33,6 +35,7 @@ impl AudioMode {
33 match value.map(str::to_ascii_lowercase).as_deref() {
35 match value.map(str::to_ascii_lowercase).as_deref() {
34 Some("tone") => AudioMode::Tone,
36 Some("tone") => AudioMode::Tone,
35 Some("silence") => AudioMode::Silence,
37 Some("silence") => AudioMode::Silence,
38 Some("file") => AudioMode::File,
36 _ => AudioMode::Platform,
39 _ => AudioMode::Platform,
37 }
40 }
38 }
41 }
@@ -93,11 +96,18 @@ impl AudioSetup {
93 feeder: None,
96 feeder: None,
94 };
97 };
95 }
98 }
96 let amplitude = if mode == AudioMode::Tone { TONE_AMPLITUDE } else { 0.0 };
99 let generator = match mode {
100 AudioMode::File => std::env::var_os(AUDIO_FILE_ENV)
101 .and_then(|path| std::fs::read(path).ok())
102 .and_then(|bytes| ClipGenerator::from_wav(&bytes))
103 .map_or(FrameGenerator::Sine(SineGenerator::new(tone_hz, 0.0)), FrameGenerator::Clip),
104 AudioMode::Tone => FrameGenerator::Sine(SineGenerator::new(tone_hz, TONE_AMPLITUDE)),
105 AudioMode::Platform | AudioMode::Silence => FrameGenerator::Sine(SineGenerator::new(tone_hz, 0.0)),
106 };
97 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
107 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
98 let track = factory.create_audio_track("microphone", source.clone());
108 let track = factory.create_audio_track("microphone", source.clone());
99 let running = Arc::new(AtomicBool::new(true));
109 let running = Arc::new(AtomicBool::new(true));
100 let task = tokio::spawn(feed_frames(source, SineGenerator::new(tone_hz, amplitude), running.clone()));
110 let task = tokio::spawn(feed_frames(source, generator, running.clone()));
101 AudioSetup {
111 AudioSetup {
102 factory: factory.clone(),
112 factory: factory.clone(),
103 track,
113 track,
@@ -125,7 +135,21 @@ impl AudioSetup {
125 }
135 }
126}
136}
127
137
128async fn feed_frames(source: NativeAudioSource, mut generator: SineGenerator, running: Arc<AtomicBool>) {
138enum FrameGenerator {
139 Sine(SineGenerator),
140 Clip(ClipGenerator),
141}
142
143impl FrameGenerator {
144 fn next_frame(&mut self) -> Vec<i16> {
145 match self {
146 FrameGenerator::Sine(generator) => generator.next_frame(),
147 FrameGenerator::Clip(generator) => generator.next_frame(),
148 }
149 }
150}
151
152async fn feed_frames(source: NativeAudioSource, mut generator: FrameGenerator, running: Arc<AtomicBool>) {
129 let mut tick = interval(FRAME_PERIOD);
153 let mut tick = interval(FRAME_PERIOD);
130 while running.load(Ordering::SeqCst) {
154 while running.load(Ordering::SeqCst) {
131 tick.tick().await;
155 tick.tick().await;
@@ -150,6 +174,7 @@ mod tests {
150 assert_eq!(AudioMode::parse(None), AudioMode::Platform);
174 assert_eq!(AudioMode::parse(None), AudioMode::Platform);
151 assert_eq!(AudioMode::parse(Some("tone")), AudioMode::Tone);
175 assert_eq!(AudioMode::parse(Some("tone")), AudioMode::Tone);
152 assert_eq!(AudioMode::parse(Some("SILENCE")), AudioMode::Silence);
176 assert_eq!(AudioMode::parse(Some("SILENCE")), AudioMode::Silence);
177 assert_eq!(AudioMode::parse(Some("file")), AudioMode::File);
153 assert_eq!(AudioMode::parse(Some("whatever")), AudioMode::Platform);
178 assert_eq!(AudioMode::parse(Some("whatever")), AudioMode::Platform);
154 }
179 }
155}
180}
crates/chatsvc/examples/recap_probe.rs added +152 −0
@@ -0,0 +1,152 @@
1 use chatsvc::{Attendance, Recap, TranscriptError, TranscriptFormat};
2 use chrono::Utc;
3 use session::{DEFAULT_ENDPOINT, Session};
4
5 fn usage() -> ! {
6 eprintln!("usage: recap_probe <thread-id-file> [--delete]");
7 std::process::exit(2)
8 }
9
10 fn host_and_path_shape(url: &str) -> String {
11 let without_scheme = url.split("://").nth(1).unwrap_or(url);
12 let mut parts = without_scheme.split('?');
13 let path = parts.next().unwrap_or_default();
14 let segments: Vec<&str> = path.split('/').skip(1).collect();
15 let shape: Vec<&str> = segments
16 .iter()
17 .map(|segment| match *segment {
18 "_api" | "v2.1" | "drives" | "items" | "personal" | ":v:" | "g" => segment,
19 _ => "*",
20 })
21 .collect();
22 let host_kind = without_scheme
23 .split('/')
24 .next()
25 .map_or("?", |host| if host.ends_with("-my.sharepoint.com") { "<tenant>-my.sharepoint.com" } else { "other" });
26 format!("{host_kind}/{}", shape.join("/"))
27 }
28
29 fn error_shape(error: &TranscriptError) -> String {
30 match error {
31 TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(
32 "HTTP {status} code {}",
33 body.pointer("/error/code").and_then(serde_json::Value::as_str).unwrap_or("-")
34 ),
35 TranscriptError::Request(other) => format!("request {}", other.to_string().chars().take(60).collect::<String>()),
36 other => format!("{other:?}"),
37 }
38 }
39
40 fn magic(bytes: &[u8]) -> String {
41 let start = bytes.strip_prefix(b"\xEF\xBB\xBF".as_slice()).unwrap_or(bytes);
42 if start.starts_with(b"WEBVTT") {
43 format!("WEBVTT (bom {})", start.len() != bytes.len())
44 } else if bytes.starts_with(b"PK\x03\x04") {
45 "zip PK".to_owned()
46 } else {
47 format!("unknown {:02x?}", &bytes[..bytes.len().min(4)])
48 }
49 }
50
51 #[tokio::main]
52 async fn main() {
53 let mut arguments = std::env::args().skip(1);
54 let Some(thread_file) = arguments.next() else { usage() };
55 let delete = arguments.any(|argument| argument == "--delete");
56 let thread_id = std::fs::read_to_string(&thread_file).expect("thread file").trim().to_owned();
57 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
58 let session = Session::connect(&endpoint).await.expect("browser");
59 let recap = Recap::new(&session);
60
61 let occurrences = match recap.occurrences(&thread_id).await {
62 Ok(occurrences) => occurrences,
63 Err(error) => {
64 println!("# occurrences: error {}", error_shape(&error));
65 return;
66 }
67 };
68 println!("# occurrences: {}", occurrences.len());
69 for occurrence in &occurrences {
70 println!(
71 "# started {}, name {}, duration {:?}, organizer {}, url {}",
72 occurrence.started_at.is_some(),
73 occurrence.recording_name.is_some(),
74 occurrence.duration_seconds,
75 occurrence.organizer_id.is_some(),
76 host_and_path_shape(&occurrence.recording_url)
77 );
78 }
79 let Some(occurrence) = occurrences.first() else { return };
80
81 let details = match recap.details(occurrence).await {
82 Ok(details) => details,
83 Err(error) => {
84 println!("# details: error {}", error_shape(&error));
85 return;
86 }
87 };
88 println!(
89 "# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",
90 details.audio_only,
91 details.duration_seconds,
92 details.expires_at.map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
93 details.transcript_id.is_some(),
94 host_and_path_shape(&details.item_url)
95 );
96
97 match recap.transcript(&details).await {
98 Ok(turns) => println!(
99 "# transcript: {} turns, {} with speaker, {} words, spans {:?}",
100 turns.len(),
101 turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),
102 turns.iter().map(|turn| turn.text.split_whitespace().count()).sum::<usize>(),
103 turns.iter().map(|turn| (turn.start_seconds.round(), turn.end_seconds.round())).collect::<Vec<_>>()
104 ),
105 Err(error) => println!("# transcript: error {}", error_shape(&error)),
106 }
107
108 let directory = std::env::temp_dir().join(format!("recap-probe-{}", std::process::id()));
109 std::fs::create_dir_all(&directory).expect("temp dir");
110 for format in [TranscriptFormat::Vtt, TranscriptFormat::Docx] {
111 match recap.transcript_file(&details, format).await {
112 Ok(bytes) => {
113 let path = directory.join(format!("transcript.{}", format.query()));
114 std::fs::write(&path, &bytes).expect("write transcript");
115 let text = String::from_utf8_lossy(&bytes);
116 println!(
117 "# transcript file {}: {} bytes, magic {}, cues {}, voice tags {}, word document part {}",
118 format.query(),
119 bytes.len(),
120 magic(&bytes),
121 text.matches("-->").count(),
122 text.matches("<v ").count(),
123 text.contains("word/document.xml")
124 );
125 }
126 Err(error) => println!("# transcript file {}: error {}", format.query(), error_shape(&error)),
127 }
128 }
129 let _ = std::fs::remove_dir_all(&directory);
130
131 match recap.attendance(&thread_id).await {
132 Ok(Attendance::TurnedOff) => println!("# attendance: turned off"),
133 Ok(Attendance::Report(records)) => println!("# attendance: {} records", records.len()),
134 Err(error) => println!("# attendance: error {}", error_shape(&error)),
135 }
136
137 if !delete {
138 return;
139 }
140 match recap.delete_recording(&details).await {
141 Ok(()) => println!("# delete: ok"),
142 Err(error) => println!("# delete: error {}", error_shape(&error)),
143 }
144 match recap.occurrences(&thread_id).await {
145 Ok(after) => println!("# occurrences after delete: {}", after.len()),
146 Err(error) => println!("# occurrences after delete: error {}", error_shape(&error)),
147 }
148 match recap.details(occurrence).await {
149 Ok(_) => println!("# details after delete: still found"),
150 Err(error) => println!("# details after delete: {}", error_shape(&error)),
151 }
152 }
@@ -0,0 +1,152 @@
1use chatsvc::{Attendance, Recap, TranscriptError, TranscriptFormat};
2use chrono::Utc;
3use session::{DEFAULT_ENDPOINT, Session};
4
5fn usage() -> ! {
6 eprintln!("usage: recap_probe <thread-id-file> [--delete]");
7 std::process::exit(2)
8}
9
10fn host_and_path_shape(url: &str) -> String {
11 let without_scheme = url.split("://").nth(1).unwrap_or(url);
12 let mut parts = without_scheme.split('?');
13 let path = parts.next().unwrap_or_default();
14 let segments: Vec<&str> = path.split('/').skip(1).collect();
15 let shape: Vec<&str> = segments
16 .iter()
17 .map(|segment| match *segment {
18 "_api" | "v2.1" | "drives" | "items" | "personal" | ":v:" | "g" => segment,
19 _ => "*",
20 })
21 .collect();
22 let host_kind = without_scheme
23 .split('/')
24 .next()
25 .map_or("?", |host| if host.ends_with("-my.sharepoint.com") { "<tenant>-my.sharepoint.com" } else { "other" });
26 format!("{host_kind}/{}", shape.join("/"))
27}
28
29fn error_shape(error: &TranscriptError) -> String {
30 match error {
31 TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(
32 "HTTP {status} code {}",
33 body.pointer("/error/code").and_then(serde_json::Value::as_str).unwrap_or("-")
34 ),
35 TranscriptError::Request(other) => format!("request {}", other.to_string().chars().take(60).collect::<String>()),
36 other => format!("{other:?}"),
37 }
38}
39
40fn magic(bytes: &[u8]) -> String {
41 let start = bytes.strip_prefix(b"\xEF\xBB\xBF".as_slice()).unwrap_or(bytes);
42 if start.starts_with(b"WEBVTT") {
43 format!("WEBVTT (bom {})", start.len() != bytes.len())
44 } else if bytes.starts_with(b"PK\x03\x04") {
45 "zip PK".to_owned()
46 } else {
47 format!("unknown {:02x?}", &bytes[..bytes.len().min(4)])
48 }
49}
50
51#[tokio::main]
52async fn main() {
53 let mut arguments = std::env::args().skip(1);
54 let Some(thread_file) = arguments.next() else { usage() };
55 let delete = arguments.any(|argument| argument == "--delete");
56 let thread_id = std::fs::read_to_string(&thread_file).expect("thread file").trim().to_owned();
57 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
58 let session = Session::connect(&endpoint).await.expect("browser");
59 let recap = Recap::new(&session);
60
61 let occurrences = match recap.occurrences(&thread_id).await {
62 Ok(occurrences) => occurrences,
63 Err(error) => {
64 println!("# occurrences: error {}", error_shape(&error));
65 return;
66 }
67 };
68 println!("# occurrences: {}", occurrences.len());
69 for occurrence in &occurrences {
70 println!(
71 "# started {}, name {}, duration {:?}, organizer {}, url {}",
72 occurrence.started_at.is_some(),
73 occurrence.recording_name.is_some(),
74 occurrence.duration_seconds,
75 occurrence.organizer_id.is_some(),
76 host_and_path_shape(&occurrence.recording_url)
77 );
78 }
79 let Some(occurrence) = occurrences.first() else { return };
80
81 let details = match recap.details(occurrence).await {
82 Ok(details) => details,
83 Err(error) => {
84 println!("# details: error {}", error_shape(&error));
85 return;
86 }
87 };
88 println!(
89 "# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",
90 details.audio_only,
91 details.duration_seconds,
92 details.expires_at.map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
93 details.transcript_id.is_some(),
94 host_and_path_shape(&details.item_url)
95 );
96
97 match recap.transcript(&details).await {
98 Ok(turns) => println!(
99 "# transcript: {} turns, {} with speaker, {} words, spans {:?}",
100 turns.len(),
101 turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),
102 turns.iter().map(|turn| turn.text.split_whitespace().count()).sum::<usize>(),
103 turns.iter().map(|turn| (turn.start_seconds.round(), turn.end_seconds.round())).collect::<Vec<_>>()
104 ),
105 Err(error) => println!("# transcript: error {}", error_shape(&error)),
106 }
107
108 let directory = std::env::temp_dir().join(format!("recap-probe-{}", std::process::id()));
109 std::fs::create_dir_all(&directory).expect("temp dir");
110 for format in [TranscriptFormat::Vtt, TranscriptFormat::Docx] {
111 match recap.transcript_file(&details, format).await {
112 Ok(bytes) => {
113 let path = directory.join(format!("transcript.{}", format.query()));
114 std::fs::write(&path, &bytes).expect("write transcript");
115 let text = String::from_utf8_lossy(&bytes);
116 println!(
117 "# transcript file {}: {} bytes, magic {}, cues {}, voice tags {}, word document part {}",
118 format.query(),
119 bytes.len(),
120 magic(&bytes),
121 text.matches("-->").count(),
122 text.matches("<v ").count(),
123 text.contains("word/document.xml")
124 );
125 }
126 Err(error) => println!("# transcript file {}: error {}", format.query(), error_shape(&error)),
127 }
128 }
129 let _ = std::fs::remove_dir_all(&directory);
130
131 match recap.attendance(&thread_id).await {
132 Ok(Attendance::TurnedOff) => println!("# attendance: turned off"),
133 Ok(Attendance::Report(records)) => println!("# attendance: {} records", records.len()),
134 Err(error) => println!("# attendance: error {}", error_shape(&error)),
135 }
136
137 if !delete {
138 return;
139 }
140 match recap.delete_recording(&details).await {
141 Ok(()) => println!("# delete: ok"),
142 Err(error) => println!("# delete: error {}", error_shape(&error)),
143 }
144 match recap.occurrences(&thread_id).await {
145 Ok(after) => println!("# occurrences after delete: {}", after.len()),
146 Err(error) => println!("# occurrences after delete: error {}", error_shape(&error)),
147 }
148 match recap.details(occurrence).await {
149 Ok(_) => println!("# details after delete: still found"),
150 Err(error) => println!("# details after delete: {}", error_shape(&error)),
151 }
152}
crates/chatsvc/src/recap.rs +70 −1
@@ -1,3 +1,5 @@
1 use std::collections::{BTreeSet, HashSet};
2
1 3 use base64::Engine as _;
2 4 use base64::engine::general_purpose::STANDARD;
3 5 use chrono::{DateTime, Utc};
@@ -97,7 +99,47 @@ impl<'a> Recap<'a> {
97 99 None => break,
98 100 }
99 101 }
100 Ok(sorted_occurrences(found))
102 let occurrences = sorted_occurrences(found);
103 let deleted = self.deleted_recordings(&occurrences).await;
104 Ok(without_deleted(occurrences, &deleted))
105 }
106
107 async fn deleted_recordings(&self, occurrences: &[Occurrence]) -> HashSet<String> {
108 let mut deleted = HashSet::new();
109 let sites: BTreeSet<String> = occurrences
110 .iter()
111 .map(|occurrence| site_origin(&occurrence.recording_url))
112 .collect();
113 for site in sites {
114 let urls: Vec<&str> = occurrences
115 .iter()
116 .map(|occurrence| occurrence.recording_url.as_str())
117 .filter(|url| site_origin(url) == site)
118 .collect();
119 let requests: Vec<Request> = urls
120 .iter()
121 .map(|url| {
122 Request::get(format!(
123 "{site}/_api/v2.1/shares/{}/driveItem?$select=id",
124 share_id(url)
125 ))
126 })
127 .collect();
128 let Ok(answers) = self
129 .session
130 .batch(&requests, &Scope::new(site.clone(), SITE_SCOPE))
131 .await
132 else {
133 continue;
134 };
135 deleted.extend(
136 urls.iter()
137 .zip(answers)
138 .filter(|(_, answer)| answer.status == 404)
139 .map(|(url, _)| (*url).to_owned()),
140 );
141 }
142 deleted
101 143 }
102 144
103 145 pub async fn details(
@@ -364,6 +406,13 @@ pub fn sorted_occurrences(mut occurrences: Vec<Occurrence>) -> Vec<Occurrence> {
364 406 occurrences
365 407 }
366 408
409 pub fn without_deleted(occurrences: Vec<Occurrence>, deleted: &HashSet<String>) -> Vec<Occurrence> {
410 occurrences
411 .into_iter()
412 .filter(|occurrence| !deleted.contains(&occurrence.recording_url))
413 .collect()
414 }
415
367 416 pub fn parse_iso_duration(text: &str) -> Option<u64> {
368 417 let time = text.strip_prefix("PT")?;
369 418 let mut total = 0.0;
@@ -480,6 +529,15 @@ mod tests {
480 529 assert_eq!(occurrences[1].duration_seconds, None);
481 530 }
482 531
532 #[test]
533 fn deleted_recordings_drop_out_of_the_occurrences() {
534 let occurrences = sorted_occurrences(parse_occurrences(&fixture("messages.json")));
535 let deleted: HashSet<String> = [occurrences[0].recording_url.clone()].into();
536 let remaining = without_deleted(occurrences, &deleted);
537 assert_eq!(remaining.len(), 1);
538 assert_eq!(remaining[0].message_id, "2001");
539 }
540
483 541 #[test]
484 542 fn iso_durations_parse_to_seconds() {
485 543 assert_eq!(parse_iso_duration("PT1H2M3S"), Some(3723));
@@ -519,6 +577,17 @@ mod tests {
519 577 );
520 578 }
521 579
580 #[test]
581 fn recording_item_gives_url_duration_and_video() {
582 let item = fixture("drive_item.json");
583 assert_eq!(
584 item_url("https://contoso-my.sharepoint.com", &item).as_deref(),
585 Some("https://contoso-my.sharepoint.com/_api/v2.1/drives/drive-1/items/item-1")
586 );
587 assert!(!is_audio_only(&item));
588 assert_eq!(item_duration_seconds(&item), Some(53));
589 }
590
522 591 #[test]
523 592 fn transcript_urls_request_the_wanted_format() {
524 593 assert_eq!(
@@ -1,3 +1,5 @@
1use std::collections::{BTreeSet, HashSet};
2
1use base64::Engine as _;
3use base64::Engine as _;
2use base64::engine::general_purpose::STANDARD;
4use base64::engine::general_purpose::STANDARD;
3use chrono::{DateTime, Utc};
5use chrono::{DateTime, Utc};
@@ -97,7 +99,47 @@ impl<'a> Recap<'a> {
97 None => break,
99 None => break,
98 }
100 }
99 }
101 }
100 Ok(sorted_occurrences(found))
102 let occurrences = sorted_occurrences(found);
103 let deleted = self.deleted_recordings(&occurrences).await;
104 Ok(without_deleted(occurrences, &deleted))
105 }
106
107 async fn deleted_recordings(&self, occurrences: &[Occurrence]) -> HashSet<String> {
108 let mut deleted = HashSet::new();
109 let sites: BTreeSet<String> = occurrences
110 .iter()
111 .map(|occurrence| site_origin(&occurrence.recording_url))
112 .collect();
113 for site in sites {
114 let urls: Vec<&str> = occurrences
115 .iter()
116 .map(|occurrence| occurrence.recording_url.as_str())
117 .filter(|url| site_origin(url) == site)
118 .collect();
119 let requests: Vec<Request> = urls
120 .iter()
121 .map(|url| {
122 Request::get(format!(
123 "{site}/_api/v2.1/shares/{}/driveItem?$select=id",
124 share_id(url)
125 ))
126 })
127 .collect();
128 let Ok(answers) = self
129 .session
130 .batch(&requests, &Scope::new(site.clone(), SITE_SCOPE))
131 .await
132 else {
133 continue;
134 };
135 deleted.extend(
136 urls.iter()
137 .zip(answers)
138 .filter(|(_, answer)| answer.status == 404)
139 .map(|(url, _)| (*url).to_owned()),
140 );
141 }
142 deleted
101 }
143 }
102
144
103 pub async fn details(
145 pub async fn details(
@@ -364,6 +406,13 @@ pub fn sorted_occurrences(mut occurrences: Vec<Occurrence>) -> Vec<Occurrence> {
364 occurrences
406 occurrences
365}
407}
366
408
409pub fn without_deleted(occurrences: Vec<Occurrence>, deleted: &HashSet<String>) -> Vec<Occurrence> {
410 occurrences
411 .into_iter()
412 .filter(|occurrence| !deleted.contains(&occurrence.recording_url))
413 .collect()
414}
415
367pub fn parse_iso_duration(text: &str) -> Option<u64> {
416pub fn parse_iso_duration(text: &str) -> Option<u64> {
368 let time = text.strip_prefix("PT")?;
417 let time = text.strip_prefix("PT")?;
369 let mut total = 0.0;
418 let mut total = 0.0;
@@ -480,6 +529,15 @@ mod tests {
480 assert_eq!(occurrences[1].duration_seconds, None);
529 assert_eq!(occurrences[1].duration_seconds, None);
481 }
530 }
482
531
532 #[test]
533 fn deleted_recordings_drop_out_of_the_occurrences() {
534 let occurrences = sorted_occurrences(parse_occurrences(&fixture("messages.json")));
535 let deleted: HashSet<String> = [occurrences[0].recording_url.clone()].into();
536 let remaining = without_deleted(occurrences, &deleted);
537 assert_eq!(remaining.len(), 1);
538 assert_eq!(remaining[0].message_id, "2001");
539 }
540
483 #[test]
541 #[test]
484 fn iso_durations_parse_to_seconds() {
542 fn iso_durations_parse_to_seconds() {
485 assert_eq!(parse_iso_duration("PT1H2M3S"), Some(3723));
543 assert_eq!(parse_iso_duration("PT1H2M3S"), Some(3723));
@@ -519,6 +577,17 @@ mod tests {
519 );
577 );
520 }
578 }
521
579
580 #[test]
581 fn recording_item_gives_url_duration_and_video() {
582 let item = fixture("drive_item.json");
583 assert_eq!(
584 item_url("https://contoso-my.sharepoint.com", &item).as_deref(),
585 Some("https://contoso-my.sharepoint.com/_api/v2.1/drives/drive-1/items/item-1")
586 );
587 assert!(!is_audio_only(&item));
588 assert_eq!(item_duration_seconds(&item), Some(53));
589 }
590
522 #[test]
591 #[test]
523 fn transcript_urls_request_the_wanted_format() {
592 fn transcript_urls_request_the_wanted_format() {
524 assert_eq!(
593 assert_eq!(
crates/chatsvc/tests/fixtures/recap/drive_item.json added +6 −0
@@ -0,0 +1,6 @@
1 {
2 "id": "item-1",
3 "parentReference": {"driveId": "drive-1"},
4 "video": {"duration": 53120, "width": 1920, "height": 1080},
5 "file": {"mimeType": "video/mp4"}
6 }
@@ -0,0 +1,6 @@
1{
2 "id": "item-1",
3 "parentReference": {"driveId": "drive-1"},
4 "video": {"duration": 53120, "width": 1920, "height": 1080},
5 "file": {"mimeType": "video/mp4"}
6}