BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / support.rs

support.rs

support.rs 16.0 KiB Download Raw
1use std::path::{Path, PathBuf};
2
3use crate::diagnostics;
4use crate::version;
5
6pub const SUPPORT_BUNDLES_DIR: &str = "support-bundles";
7pub const CALL_REPORTS_DIR: &str = "call-reports";
8pub const CALL_DUMPS_DIR: &str = "call-dumps";
9pub const CRASH_LOG_FILE: &str = "crash.log";
10
11/// Upstream tracker — fork mirror has Issues disabled.
12pub const GITHUB_ISSUES_NEW: &str = "https://github.com/danieldaeschle/rusty-teams/issues/new";
13
14/// Runtime facts for Help, `client.md`, clipboard, and issue drafts. English keys only.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct ClientInfo {
17 pub version: String,
18 pub build: String,
19 pub os: String,
20 pub arch: String,
21 pub session: String,
22 pub ui_locale: String,
23 pub timezone: String,
24 pub signed_in: bool,
25 pub call_reports: bool,
26 pub debug_logging: bool,
27 pub audio_input: String,
28 pub audio_output: String,
29 pub camera: String,
30 pub logs_root: String,
31 pub support_bundles_root: String,
32}
33
34impl ClientInfo {
35 pub fn capture(
36 package_version: &str,
37 ui_locale: &str,
38 signed_in: bool,
39 call_reports: bool,
40 audio_input: impl Into<String>,
41 audio_output: impl Into<String>,
42 camera: impl Into<String>,
43 ) -> Self {
44 let logs_root = local_data_dir()
45 .map(|path| home_relative(&path))
46 .unwrap_or_else(|| "unknown".to_owned());
47 let support_bundles_root = support_bundles_dir()
48 .map(|path| home_relative(&path))
49 .unwrap_or_else(|| "unknown".to_owned());
50 ClientInfo {
51 version: package_version.to_owned(),
52 build: version::build_version().to_owned(),
53 os: std::env::consts::OS.to_owned(),
54 arch: std::env::consts::ARCH.to_owned(),
55 session: desktop_session(),
56 ui_locale: ui_locale.to_owned(),
57 timezone: timezone_name(),
58 signed_in,
59 call_reports,
60 debug_logging: diagnostics::is_enabled(),
61 audio_input: audio_input.into(),
62 audio_output: audio_output.into(),
63 camera: camera.into(),
64 logs_root,
65 support_bundles_root,
66 }
67 }
68
69 pub fn markdown(&self) -> String {
70 format!(
71 "### Client\n\
72 - Version: {}\n\
73 - Build: {}\n\
74 - OS: {} ({})\n\
75 - Session: {}\n\
76 - UI language: {}\n\
77 - Timezone: {}\n\
78 - Signed in: {}\n\
79 - Call reports: {}\n\
80 - Debug logging: {}\n\
81 - Audio input: {}\n\
82 - Audio output: {}\n\
83 - Camera: {}\n\
84 - Logs root: {}\n\
85 - Support bundles: {}\n",
86 self.version,
87 self.build,
88 self.os,
89 self.arch,
90 self.session,
91 self.ui_locale,
92 self.timezone,
93 yes_no(self.signed_in),
94 yes_no(self.call_reports),
95 yes_no(self.debug_logging),
96 self.audio_input,
97 self.audio_output,
98 self.camera,
99 self.logs_root,
100 self.support_bundles_root,
101 )
102 }
103
104 pub fn one_line(&self) -> String {
105 format!(
106 "client version={} build={} os={}/{} session={} locale={} tz={} signed_in={} call_reports={} debug_logging={} logs={}",
107 self.version,
108 self.build,
109 self.os,
110 self.arch,
111 self.session,
112 self.ui_locale,
113 self.timezone,
114 yes_no(self.signed_in),
115 yes_no(self.call_reports),
116 yes_no(self.debug_logging),
117 self.logs_root,
118 )
119 }
120}
121
122pub fn home_relative(path: &Path) -> String {
123 let home = directories::BaseDirs::new().map(|base| base.home_dir().to_path_buf());
124 match home.and_then(|home| path.strip_prefix(home).ok().map(Path::to_path_buf)) {
125 Some(relative) => format!("~/{}", relative.display()).replace('\\', "/"),
126 None => path.display().to_string(),
127 }
128}
129
130fn yes_no(value: bool) -> &'static str {
131 if value { "yes" } else { "no" }
132}
133
134pub fn desktop_session() -> String {
135 #[cfg(target_os = "linux")]
136 {
137 std::env::var("XDG_SESSION_TYPE")
138 .ok()
139 .filter(|value| !value.is_empty())
140 .unwrap_or_else(|| "unknown".to_owned())
141 }
142 #[cfg(target_os = "macos")]
143 {
144 "macos".to_owned()
145 }
146 #[cfg(target_os = "windows")]
147 {
148 "windows".to_owned()
149 }
150 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
151 {
152 "unknown".to_owned()
153 }
154}
155
156fn timezone_name() -> String {
157 std::env::var("TZ")
158 .ok()
159 .filter(|value| !value.is_empty())
160 .unwrap_or_else(|| format!("{}", chrono::Local::now().offset()))
161}
162
163/// OS local application data root for `ms-teams-linux` (legacy product directory name).
164pub fn local_data_dir() -> Option<PathBuf> {
165 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
166 .map(|directories| directories.data_local_dir().to_path_buf())
167}
168
169pub fn diagnostics_log_path() -> Option<PathBuf> {
170 local_data_dir().map(|root| root.join(diagnostics::DIAGNOSTICS_FILE))
171}
172
173pub fn crash_log_path() -> Option<PathBuf> {
174 local_data_dir().map(|root| root.join(CRASH_LOG_FILE))
175}
176
177pub fn call_dumps_dir() -> Option<PathBuf> {
178 local_data_dir().map(|root| root.join(CALL_DUMPS_DIR))
179}
180
181pub fn call_reports_dir() -> Option<PathBuf> {
182 local_data_dir().map(|root| root.join(CALL_REPORTS_DIR))
183}
184
185pub fn support_bundles_dir() -> Option<PathBuf> {
186 local_data_dir().map(|root| root.join(SUPPORT_BUNDLES_DIR))
187}
188
189pub fn support_bundles_directory(data_dir: &Path) -> PathBuf {
190 data_dir.join(SUPPORT_BUNDLES_DIR)
191}
192
193pub fn bundle_folder_name(utc: chrono::DateTime<chrono::Utc>) -> String {
194 format!("support-{}", utc.format("%Y%m%dT%H%M%SZ"))
195}
196
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub struct SupportBundleEntry {
199 pub directory: PathBuf,
200 pub name: String,
201}
202
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct BundleFileEntry {
205 pub path: PathBuf,
206 pub name: String,
207 pub size_bytes: u64,
208}
209
210/// Newest-first list of package folders under `support-bundles/`.
211pub fn list_support_bundles(root: &Path) -> std::io::Result<Vec<SupportBundleEntry>> {
212 if !root.is_dir() {
213 return Ok(Vec::new());
214 }
215 let mut entries: Vec<SupportBundleEntry> = std::fs::read_dir(root)?
216 .filter_map(Result::ok)
217 .map(|entry| entry.path())
218 .filter(|path| path.is_dir())
219 .filter_map(|directory| {
220 let name = directory.file_name()?.to_string_lossy().into_owned();
221 Some(SupportBundleEntry { directory, name })
222 })
223 .collect();
224 entries.sort_by(|left, right| right.name.cmp(&left.name));
225 Ok(entries)
226}
227
228pub fn list_bundle_files(bundle: &Path) -> std::io::Result<Vec<BundleFileEntry>> {
229 if !bundle.is_dir() {
230 return Ok(Vec::new());
231 }
232 let mut files: Vec<BundleFileEntry> = std::fs::read_dir(bundle)?
233 .filter_map(Result::ok)
234 .map(|entry| entry.path())
235 .filter(|path| path.is_file())
236 .filter_map(|path| {
237 let name = path.file_name()?.to_string_lossy().into_owned();
238 let size_bytes = std::fs::metadata(&path).ok()?.len();
239 Some(BundleFileEntry {
240 path,
241 name,
242 size_bytes,
243 })
244 })
245 .collect();
246 files.sort_by(|left, right| left.name.cmp(&right.name));
247 Ok(files)
248}
249
250/// Remove one support package directory. Refuses paths outside `parent` when provided.
251pub fn delete_support_bundle(bundle: &Path, parent: Option<&Path>) -> std::io::Result<()> {
252 if let Some(parent) = parent {
253 let canonical_parent = parent
254 .canonicalize()
255 .unwrap_or_else(|_| parent.to_path_buf());
256 let canonical_bundle = bundle
257 .canonicalize()
258 .unwrap_or_else(|_| bundle.to_path_buf());
259 if !canonical_bundle.starts_with(&canonical_parent) {
260 return Err(std::io::Error::new(
261 std::io::ErrorKind::InvalidInput,
262 "bundle path is outside the support-bundles directory",
263 ));
264 }
265 }
266 if bundle.is_dir() {
267 std::fs::remove_dir_all(bundle)?;
268 }
269 Ok(())
270}
271
272pub fn ensure_dir(path: &Path) -> std::io::Result<()> {
273 std::fs::create_dir_all(path)
274}
275
276pub fn format_bytes(size: u64) -> String {
277 const KB: u64 = 1024;
278 const MB: u64 = KB * 1024;
279 if size >= MB {
280 format!(
281 "{} MB",
282 crate::format::decimal_label(size as f64 / MB as f64, 1)
283 )
284 } else if size >= KB {
285 format!(
286 "{} KB",
287 crate::format::decimal_label(size as f64 / KB as f64, 1)
288 )
289 } else {
290 format!("{size} B")
291 }
292}
293
294pub fn issue_title() -> &'static str {
295 "Bug report"
296}
297
298pub fn issue_body(client: &ClientInfo, bundle: &SupportBundlePaths) -> String {
299 format!(
300 "## What happened\n\n\
301 <!-- Describe the bug -->\n\n\
302 ## Expected\n\n\
303 <!-- What should happen -->\n\n\
304 {}\n\
305 Support package folder: `{}`\n\
306 Support package path: `{}`\n\n\
307 Attach the files from that folder (do not paste secrets).\n",
308 client.markdown(),
309 bundle.folder_name,
310 home_relative(&bundle.directory),
311 )
312}
313
314#[derive(Debug, Clone, PartialEq, Eq)]
315pub struct SupportBundlePaths {
316 pub directory: PathBuf,
317 pub folder_name: String,
318}
319
320pub fn issue_url(client: &ClientInfo, bundle: &SupportBundlePaths) -> String {
321 format!(
322 "{GITHUB_ISSUES_NEW}?title={}&body={}",
323 encode_query(issue_title()),
324 encode_query(&issue_body(client, bundle))
325 )
326}
327
328pub fn encode_query(value: &str) -> String {
329 let mut out = String::with_capacity(value.len() * 3);
330 for byte in value.bytes() {
331 match byte {
332 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
333 out.push(byte as char);
334 }
335 b' ' => out.push_str("%20"),
336 _ => out.push_str(&format!("%{byte:02X}")),
337 }
338 }
339 out
340}
341
342/// Append a client snapshot when debug logging is on (after store/locale when possible).
343pub fn record_startup_client_line(
344 package_version: &str,
345 ui_locale: &str,
346 signed_in: bool,
347 call_reports: bool,
348) {
349 if !diagnostics::is_enabled() {
350 return;
351 }
352 let info = ClientInfo::capture(
353 package_version,
354 ui_locale,
355 signed_in,
356 call_reports,
357 "n/a",
358 "n/a",
359 "n/a",
360 );
361 diagnostics::record(info.one_line());
362}
363
364/// Chain a panic hook that also writes a short line into the diagnostics log.
365pub fn install_panic_diagnostics_hook() {
366 let previous = std::panic::take_hook();
367 std::panic::set_hook(Box::new(move |info| {
368 let payload = info.payload();
369 let message = payload
370 .downcast_ref::<&str>()
371 .copied()
372 .map(str::to_owned)
373 .or_else(|| payload.downcast_ref::<String>().cloned())
374 .unwrap_or_else(|| "non-text panic payload".to_owned());
375 let location = info
376 .location()
377 .map(|location| {
378 format!(
379 "{}:{}:{}",
380 location.file(),
381 location.line(),
382 location.column()
383 )
384 })
385 .unwrap_or_else(|| "unknown".to_owned());
386 diagnostics::record(format!("panic at {location}: {message}"));
387 previous(info);
388 }));
389}
390
391pub fn readme_text() -> &'static str {
392 "Attach the files in this folder to a GitHub issue on danieldaeschle/rusty-teams.\n\
393 The app store, cookies, and tokens are not included.\n"
394}
395
396#[cfg(test)]
397mod tests {
398 use super::*;
399
400 fn sample_client() -> ClientInfo {
401 ClientInfo {
402 version: "0.3.0".into(),
403 build: "abc".into(),
404 os: "linux".into(),
405 arch: "x86_64".into(),
406 session: "wayland".into(),
407 ui_locale: "de".into(),
408 timezone: "Europe/Zurich".into(),
409 signed_in: true,
410 call_reports: false,
411 debug_logging: true,
412 audio_input: "Default device".into(),
413 audio_output: "Default device".into(),
414 camera: "none".into(),
415 logs_root: "/tmp/ms-teams-linux".into(),
416 support_bundles_root: "/tmp/ms-teams-linux/support-bundles".into(),
417 }
418 }
419
420 #[test]
421 fn markdown_block_lists_stable_keys_and_paths() {
422 let text = sample_client().markdown();
423 assert!(text.contains("- Version: 0.3.0"));
424 assert!(text.contains("- Build: abc"));
425 assert!(text.contains("- OS: linux (x86_64)"));
426 assert!(text.contains("- Session: wayland"));
427 assert!(text.contains("- Signed in: yes"));
428 assert!(text.contains("- Call reports: no"));
429 assert!(text.contains("- Logs root: /tmp/ms-teams-linux"));
430 assert!(text.contains("- Support bundles: /tmp/ms-teams-linux/support-bundles"));
431 assert!(!text.contains('@'));
432 }
433
434 #[test]
435 fn layout_relative_names_are_stable() {
436 assert_eq!(SUPPORT_BUNDLES_DIR, "support-bundles");
437 assert_eq!(CALL_REPORTS_DIR, "call-reports");
438 assert_eq!(CALL_DUMPS_DIR, "call-dumps");
439 assert_eq!(CRASH_LOG_FILE, "crash.log");
440 assert_eq!(diagnostics::DIAGNOSTICS_FILE, "diagnostics.log");
441 let root = PathBuf::from("/data/ms-teams-linux");
442 assert_eq!(
443 support_bundles_directory(&root),
444 root.join("support-bundles")
445 );
446 }
447
448 #[test]
449 fn issue_url_encodes_spaces_and_newlines() {
450 let info = sample_client();
451 let bundle = SupportBundlePaths {
452 directory: PathBuf::from(
453 "/tmp/ms-teams-linux/support-bundles/support-20260101T000000Z",
454 ),
455 folder_name: "support-20260101T000000Z".into(),
456 };
457 let url = issue_url(&info, &bundle);
458 assert!(url.starts_with(GITHUB_ISSUES_NEW));
459 assert!(url.contains("title=Bug%20report"));
460 assert!(url.contains("body="));
461 assert!(url.contains("support-20260101T000000Z"));
462 assert!(!url.contains(' '));
463 }
464
465 #[test]
466 fn encode_query_percent_encodes_specials() {
467 assert_eq!(encode_query("a b"), "a%20b");
468 assert_eq!(encode_query("a&b"), "a%26b");
469 }
470
471 #[test]
472 fn list_and_delete_support_bundles_in_temp_dir() {
473 let root = tempfile::tempdir().unwrap();
474 let bundles = root.path().join(SUPPORT_BUNDLES_DIR);
475 let older = bundles.join("support-20260101T000000Z");
476 let newer = bundles.join("support-20260102T000000Z");
477 std::fs::create_dir_all(&older).unwrap();
478 std::fs::create_dir_all(&newer).unwrap();
479 std::fs::write(older.join("client.md"), "old").unwrap();
480 std::fs::write(newer.join("client.md"), "new").unwrap();
481 std::fs::write(newer.join("diagnostics.log"), "log").unwrap();
482
483 let listed = list_support_bundles(&bundles).unwrap();
484 assert_eq!(listed.len(), 2);
485 assert_eq!(listed[0].name, "support-20260102T000000Z");
486 assert_eq!(listed[1].name, "support-20260101T000000Z");
487
488 let files = list_bundle_files(&newer).unwrap();
489 assert_eq!(files.len(), 2);
490 assert_eq!(files[0].name, "client.md");
491 assert_eq!(files[1].name, "diagnostics.log");
492
493 delete_support_bundle(&newer, Some(&bundles)).unwrap();
494 let listed = list_support_bundles(&bundles).unwrap();
495 assert_eq!(listed.len(), 1);
496 assert_eq!(listed[0].name, "support-20260101T000000Z");
497 assert!(!newer.exists());
498 }
499
500 #[test]
501 fn delete_refuses_paths_outside_parent() {
502 let root = tempfile::tempdir().unwrap();
503 let bundles = root.path().join(SUPPORT_BUNDLES_DIR);
504 let outside = root.path().join("other");
505 std::fs::create_dir_all(&bundles).unwrap();
506 std::fs::create_dir_all(&outside).unwrap();
507 assert!(delete_support_bundle(&outside, Some(&bundles)).is_err());
508 assert!(outside.exists());
509 }
510}