BlueGit

ict rusty-teams

Files

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

recap_probe.rs

8a314dbb History
recap_probe.rs 6.5 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.split('/').next().map_or("?", |host| {
23 if host.ends_with("-my.sharepoint.com") {
24 "<tenant>-my.sharepoint.com"
25 } else {
26 "other"
27 }
28 });
29 format!("{host_kind}/{}", shape.join("/"))
30}
31
32fn error_shape(error: &TranscriptError) -> String {
33 match error {
34 TranscriptError::Request(session::Error::Api { status, body, .. }) => format!(
35 "HTTP {status} code {}",
36 body.pointer("/error/code")
37 .and_then(serde_json::Value::as_str)
38 .unwrap_or("-")
39 ),
40 TranscriptError::Request(other) => format!(
41 "request {}",
42 other.to_string().chars().take(60).collect::<String>()
43 ),
44 other => format!("{other:?}"),
45 }
46}
47
48fn magic(bytes: &[u8]) -> String {
49 let start = bytes
50 .strip_prefix(b"\xEF\xBB\xBF".as_slice())
51 .unwrap_or(bytes);
52 if start.starts_with(b"WEBVTT") {
53 format!("WEBVTT (bom {})", start.len() != bytes.len())
54 } else if bytes.starts_with(b"PK\x03\x04") {
55 "zip PK".to_owned()
56 } else {
57 format!("unknown {:02x?}", &bytes[..bytes.len().min(4)])
58 }
59}
60
61#[tokio::main]
62async fn main() {
63 let mut arguments = std::env::args().skip(1);
64 let Some(thread_file) = arguments.next() else {
65 usage()
66 };
67 let delete = arguments.any(|argument| argument == "--delete");
68 let thread_id = std::fs::read_to_string(&thread_file)
69 .expect("thread file")
70 .trim()
71 .to_owned();
72 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
73 let session = Session::connect(&endpoint).await.expect("browser");
74 let recap = Recap::new(&session);
75
76 let occurrences = match recap.occurrences(&thread_id).await {
77 Ok(occurrences) => occurrences,
78 Err(error) => {
79 println!("# occurrences: error {}", error_shape(&error));
80 return;
81 }
82 };
83 println!("# occurrences: {}", occurrences.len());
84 for occurrence in &occurrences {
85 println!(
86 "# started {}, name {}, duration {:?}, organizer {}, url {}",
87 occurrence.started_at.is_some(),
88 occurrence.recording_name.is_some(),
89 occurrence.duration_seconds,
90 occurrence.organizer_id.is_some(),
91 host_and_path_shape(&occurrence.recording_url)
92 );
93 }
94 let Some(occurrence) = occurrences.first() else {
95 return;
96 };
97
98 let details = match recap.details(occurrence).await {
99 Ok(details) => details,
100 Err(error) => {
101 println!("# details: error {}", error_shape(&error));
102 return;
103 }
104 };
105 println!(
106 "# details: audio only {}, duration {:?}, expires in days {:?}, transcript {}, item {}",
107 details.audio_only,
108 details.duration_seconds,
109 details
110 .expires_at
111 .map(|expires_at| chatsvc::recap::days_until_expiry(expires_at, Utc::now())),
112 details.transcript_id.is_some(),
113 host_and_path_shape(&details.item_url)
114 );
115
116 match recap.transcript(&details).await {
117 Ok(turns) => println!(
118 "# transcript: {} turns, {} with speaker, {} words, spans {:?}",
119 turns.len(),
120 turns.iter().filter(|turn| !turn.speaker.is_empty()).count(),
121 turns
122 .iter()
123 .map(|turn| turn.text.split_whitespace().count())
124 .sum::<usize>(),
125 turns
126 .iter()
127 .map(|turn| (turn.start_seconds.round(), turn.end_seconds.round()))
128 .collect::<Vec<_>>()
129 ),
130 Err(error) => println!("# transcript: error {}", error_shape(&error)),
131 }
132
133 let directory = std::env::temp_dir().join(format!("recap-probe-{}", std::process::id()));
134 std::fs::create_dir_all(&directory).expect("temp dir");
135 for format in [TranscriptFormat::Vtt, TranscriptFormat::Docx] {
136 match recap.transcript_file(&details, format).await {
137 Ok(bytes) => {
138 let path = directory.join(format!("transcript.{}", format.query()));
139 std::fs::write(&path, &bytes).expect("write transcript");
140 let text = String::from_utf8_lossy(&bytes);
141 println!(
142 "# transcript file {}: {} bytes, magic {}, cues {}, voice tags {}, word document part {}",
143 format.query(),
144 bytes.len(),
145 magic(&bytes),
146 text.matches("-->").count(),
147 text.matches("<v ").count(),
148 text.contains("word/document.xml")
149 );
150 }
151 Err(error) => println!(
152 "# transcript file {}: error {}",
153 format.query(),
154 error_shape(&error)
155 ),
156 }
157 }
158 let _ = std::fs::remove_dir_all(&directory);
159
160 match recap.attendance(&thread_id).await {
161 Ok(Attendance::TurnedOff) => println!("# attendance: turned off"),
162 Ok(Attendance::Report(records)) => println!("# attendance: {} records", records.len()),
163 Err(error) => println!("# attendance: error {}", error_shape(&error)),
164 }
165
166 if !delete {
167 return;
168 }
169 match recap.delete_recording(&details).await {
170 Ok(()) => println!("# delete: ok"),
171 Err(error) => println!("# delete: error {}", error_shape(&error)),
172 }
173 match recap.occurrences(&thread_id).await {
174 Ok(after) => println!("# occurrences after delete: {}", after.len()),
175 Err(error) => println!("# occurrences after delete: error {}", error_shape(&error)),
176 }
177 match recap.details(occurrence).await {
178 Ok(_) => println!("# details after delete: still found"),
179 Err(error) => println!("# details after delete: {}", error_shape(&error)),
180 }
181}