BlueGit

ict rusty-teams

Files

rusty-teams / crates / browser / src / sign_in_choice.rs

sign_in_choice.rs

sign_in_choice.rs 12.0 KiB Download Raw
1//! Which browser the app signs in with. The user picks one in Settings; Automatic takes the
2//! system's default browser when it is Chromium- or Firefox-based, else the first one installed.
3//! The choice lives in a file beside the browser profiles, since every org shares them.
4
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use serde_json::Value;
9
10use crate::config::{
11 Engine, LINUX_CHROME_NAMES, LINUX_FIREFOX_NAMES, MACOS_CHROME_APP_PATHS,
12 MACOS_FIREFOX_APP_PATHS, Platform, application_roots,
13};
14
15const CHOICE_FILE: &str = "rusty-teams-sign-in-browser";
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum SignInBrowser {
19 Automatic,
20 Program(PathBuf),
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct InstalledBrowser {
25 pub name: String,
26 pub path: PathBuf,
27 pub engine: Engine,
28}
29
30fn choice_path() -> Option<PathBuf> {
31 directories::BaseDirs::new().map(|dirs| dirs.data_dir().join(CHOICE_FILE))
32}
33
34impl SignInBrowser {
35 pub fn load() -> SignInBrowser {
36 choice_path()
37 .and_then(|path| std::fs::read_to_string(path).ok())
38 .map(|text| SignInBrowser::parse(&text))
39 .unwrap_or(SignInBrowser::Automatic)
40 }
41
42 pub fn save(&self) -> std::io::Result<()> {
43 let path = choice_path().ok_or_else(|| std::io::Error::other("no data directory"))?;
44 match self {
45 SignInBrowser::Automatic => match std::fs::remove_file(&path) {
46 Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
47 _ => Ok(()),
48 },
49 SignInBrowser::Program(program) => {
50 if let Some(parent) = path.parent() {
51 std::fs::create_dir_all(parent)?;
52 }
53 std::fs::write(&path, program.to_string_lossy().as_bytes())
54 }
55 }
56 }
57
58 fn parse(text: &str) -> SignInBrowser {
59 match text.trim() {
60 "" => SignInBrowser::Automatic,
61 path => SignInBrowser::Program(PathBuf::from(path)),
62 }
63 }
64}
65
66/// Chromium and Firefox browsers on this machine, Chromium first.
67pub fn installed_browsers() -> Vec<InstalledBrowser> {
68 let home = directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_path_buf());
69 installed_in(
70 Platform::detect(),
71 home.as_deref(),
72 &crate::host::path_variable(),
73 &crate::host::is_file,
74 )
75}
76
77/// The browser Automatic stands for.
78pub fn automatic_browser(installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
79 automatic_in(Platform::detect(), installed)
80}
81
82fn automatic_in(platform: Platform, installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
83 system_default(platform, installed).or(installed.first())
84}
85
86/// The executable to sign in with: the saved choice while it is installed, else Automatic.
87pub(crate) fn chosen_executable(platform: Platform, home: Option<&Path>) -> Option<PathBuf> {
88 if !platform.uses_unix_paths() {
89 return None;
90 }
91 if let SignInBrowser::Program(path) = SignInBrowser::load()
92 && crate::host::is_file(&path)
93 {
94 return Some(path);
95 }
96 let installed = installed_in(
97 platform,
98 home,
99 &crate::host::path_variable(),
100 &crate::host::is_file,
101 );
102 automatic_in(platform, &installed).map(|browser| browser.path.clone())
103}
104
105pub(crate) fn installed_in(
106 platform: Platform,
107 home: Option<&Path>,
108 path_variable: &std::ffi::OsStr,
109 exists: &dyn Fn(&Path) -> bool,
110) -> Vec<InstalledBrowser> {
111 let found: Vec<(String, PathBuf)> = match platform {
112 Platform::Macos => MACOS_CHROME_APP_PATHS
113 .iter()
114 .chain(&MACOS_FIREFOX_APP_PATHS)
115 .filter_map(|relative| {
116 let path = application_roots(home)
117 .map(|root| root.join(relative))
118 .find(|path| exists(path))?;
119 let name = relative.split(".app/").next().unwrap_or(relative);
120 Some((name.to_owned(), path))
121 })
122 .collect(),
123 Platform::Linux => {
124 let mut found = Vec::new();
125 let mut seen = Vec::new();
126 for name in LINUX_CHROME_NAMES.iter().chain(LINUX_FIREFOX_NAMES.iter()) {
127 let Some(path) = std::env::split_paths(path_variable)
128 .map(|directory| directory.join(name))
129 .find(|path| exists(path))
130 else {
131 continue;
132 };
133 let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
134 if seen.contains(&key) {
135 continue;
136 }
137 seen.push(key);
138 found.push(((*name).to_owned(), path));
139 }
140 found
141 }
142 Platform::Windows | Platform::Wsl => Vec::new(),
143 };
144 found
145 .into_iter()
146 .map(|(name, path)| InstalledBrowser {
147 engine: Engine::of_executable(&path),
148 name,
149 path,
150 })
151 .collect()
152}
153
154fn system_default(platform: Platform, installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
155 match platform {
156 Platform::Macos => {
157 let wanted = macos_default_bundle_id()?;
158 installed.iter().find(|browser| {
159 bundle_id(&browser.path).is_some_and(|id| id.eq_ignore_ascii_case(&wanted))
160 })
161 }
162 Platform::Linux => {
163 let output = crate::host::command("xdg-settings")
164 .args(["get", "default-web-browser"])
165 .output()
166 .ok()?;
167 desktop_entry_match(&String::from_utf8_lossy(&output.stdout), installed)
168 }
169 Platform::Windows | Platform::Wsl => None,
170 }
171}
172
173fn plist_json(path: &Path) -> Option<Value> {
174 let output = Command::new("plutil")
175 .args(["-convert", "json", "-o", "-"])
176 .arg(path)
177 .output()
178 .ok()?;
179 serde_json::from_slice(&output.stdout).ok()
180}
181
182fn macos_default_bundle_id() -> Option<String> {
183 let home = directories::BaseDirs::new()?.home_dir().to_path_buf();
184 let handlers = home
185 .join("Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");
186 handler_bundle_id(&plist_json(&handlers)?)
187}
188
189/// The app LaunchServices opens https links with, falling back to http.
190fn handler_bundle_id(handlers: &Value) -> Option<String> {
191 let entries = handlers["LSHandlers"].as_array()?;
192 ["https", "http"].iter().find_map(|scheme| {
193 entries
194 .iter()
195 .find(|entry| entry["LSHandlerURLScheme"] == *scheme)?["LSHandlerRoleAll"]
196 .as_str()
197 .map(str::to_owned)
198 })
199}
200
201/// `CFBundleIdentifier` of the app bundle holding `executable` (`X.app/Contents/MacOS/x`).
202fn bundle_id(executable: &Path) -> Option<String> {
203 let info = executable.parent()?.parent()?.join("Info.plist");
204 plist_json(&info)?["CFBundleIdentifier"]
205 .as_str()
206 .map(str::to_owned)
207}
208
209/// The installed browser named like the desktop entry `xdg-settings` reports, as in `firefox.desktop`.
210/// Edge Stable's desktop file is `microsoft-edge.desktop` while the executable is
211/// `microsoft-edge-stable`. Brave's desktop file is `brave-browser.desktop` while the
212/// executable on some distributions is `brave`.
213fn desktop_entry_match<'a>(
214 entry: &str,
215 installed: &'a [InstalledBrowser],
216) -> Option<&'a InstalledBrowser> {
217 let stem = entry.trim().trim_end_matches(".desktop");
218 let names: &[&str] = match stem {
219 "microsoft-edge" => &["microsoft-edge", "microsoft-edge-stable"],
220 "brave-browser" => &["brave", "brave-browser", "brave-browser-stable"],
221 other => return installed.iter().find(|browser| browser.name == other),
222 };
223 names
224 .iter()
225 .find_map(|name| installed.iter().find(|browser| browser.name == *name))
226}
227
228#[cfg(test)]
229mod tests {
230 use std::ffi::OsString;
231
232 use serde_json::json;
233
234 use super::*;
235
236 #[test]
237 fn finds_installed_browsers_chromium_first_once_each() {
238 let installed = [
239 "/Applications/Zen.app/Contents/MacOS/zen",
240 "/Users/joe/Applications/Zen.app/Contents/MacOS/zen",
241 "/Users/joe/Applications/Helium.app/Contents/MacOS/Helium",
242 ];
243 let found = installed_in(
244 Platform::Macos,
245 Some(Path::new("/Users/joe")),
246 &OsString::new(),
247 &|path| installed.iter().any(|known| path == Path::new(known)),
248 );
249 let names: Vec<(&str, Engine)> = found
250 .iter()
251 .map(|browser| (browser.name.as_str(), browser.engine))
252 .collect();
253 assert_eq!(
254 names,
255 [("Helium", Engine::Chromium), ("Zen", Engine::Firefox)]
256 );
257 assert_eq!(found[1].path, PathBuf::from(installed[0]));
258 }
259
260 #[test]
261 fn reads_the_https_handler() {
262 let handlers = json!({"LSHandlers": [
263 {"LSHandlerContentType": "public.html", "LSHandlerRoleAll": "com.apple.safari"},
264 {"LSHandlerURLScheme": "http", "LSHandlerRoleAll": "org.mozilla.firefox"},
265 {"LSHandlerURLScheme": "https", "LSHandlerRoleAll": "app.zen-browser.zen"},
266 ]});
267 assert_eq!(
268 handler_bundle_id(&handlers).as_deref(),
269 Some("app.zen-browser.zen")
270 );
271 assert_eq!(handler_bundle_id(&json!({"LSHandlers": []})), None);
272 }
273
274 #[test]
275 fn matches_the_linux_desktop_entry_by_name() {
276 let installed = installed_in(
277 Platform::Linux,
278 None,
279 &std::env::join_paths(["/usr/bin"]).unwrap(),
280 &|path| path == Path::new("/usr/bin/chromium") || path == Path::new("/usr/bin/firefox"),
281 );
282 let found = desktop_entry_match("firefox.desktop\n", &installed).unwrap();
283 assert_eq!(found.engine, Engine::Firefox);
284 assert!(desktop_entry_match("org.gnome.Epiphany.desktop", &installed).is_none());
285 }
286
287 #[test]
288 fn lists_edge_and_brave_and_matches_their_desktop_files() {
289 let root = Path::new("/usr/bin");
290 let installed = installed_in(
291 Platform::Linux,
292 None,
293 &std::env::join_paths([root]).unwrap(),
294 &|path| {
295 path == root.join("microsoft-edge-stable")
296 || path == root.join("brave")
297 || path == root.join("firefox")
298 },
299 );
300 let names: Vec<&str> = installed
301 .iter()
302 .map(|browser| browser.name.as_str())
303 .collect();
304 assert_eq!(names, ["microsoft-edge-stable", "brave", "firefox"]);
305 assert_eq!(
306 desktop_entry_match("microsoft-edge.desktop\n", &installed)
307 .map(|browser| browser.name.as_str()),
308 Some("microsoft-edge-stable")
309 );
310 assert_eq!(
311 desktop_entry_match("brave-browser.desktop", &installed)
312 .map(|browser| browser.name.as_str()),
313 Some("brave")
314 );
315 assert_eq!(installed[0].engine, Engine::Chromium);
316 assert_eq!(installed[1].engine, Engine::Chromium);
317
318 let channels = installed_in(
319 Platform::Linux,
320 None,
321 &std::env::join_paths([root]).unwrap(),
322 &|path| {
323 path == root.join("microsoft-edge-beta")
324 || path == root.join("brave-browser-nightly")
325 },
326 );
327 assert!(desktop_entry_match("microsoft-edge.desktop", &channels).is_none());
328 assert!(desktop_entry_match("brave-browser.desktop", &channels).is_none());
329 assert_eq!(
330 desktop_entry_match("microsoft-edge-beta.desktop", &channels)
331 .map(|browser| browser.name.as_str()),
332 Some("microsoft-edge-beta")
333 );
334 }
335
336 #[test]
337 fn parses_the_saved_choice() {
338 assert_eq!(SignInBrowser::parse(" \n"), SignInBrowser::Automatic);
339 assert_eq!(
340 SignInBrowser::parse("/Applications/Zen.app/Contents/MacOS/zen\n"),
341 SignInBrowser::Program(PathBuf::from("/Applications/Zen.app/Contents/MacOS/zen"))
342 );
343 }
344}