BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / examples / recap_probe.rs

recap_probe.rs

recap_probe.rs 6.2 KiB Download Raw
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}