BlueGit

ict rusty-teams

Files

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

sign_in_choice.rs

sign_in_choice.rs 9.3 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 => LINUX_CHROME_NAMES
124 .iter()
125 .chain(&LINUX_FIREFOX_NAMES)
126 .filter_map(|name| {
127 let path = std::env::split_paths(path_variable)
128 .map(|directory| directory.join(name))
129 .find(|path| exists(path))?;
130 Some(((*name).to_owned(), path))
131 })
132 .collect(),
133 Platform::Windows | Platform::Wsl => Vec::new(),
134 };
135 found
136 .into_iter()
137 .map(|(name, path)| InstalledBrowser {
138 engine: Engine::of_executable(&path),
139 name,
140 path,
141 })
142 .collect()
143}
144
145fn system_default(platform: Platform, installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
146 match platform {
147 Platform::Macos => {
148 let wanted = macos_default_bundle_id()?;
149 installed.iter().find(|browser| {
150 bundle_id(&browser.path).is_some_and(|id| id.eq_ignore_ascii_case(&wanted))
151 })
152 }
153 Platform::Linux => {
154 let output = crate::host::command("xdg-settings")
155 .args(["get", "default-web-browser"])
156 .output()
157 .ok()?;
158 desktop_entry_match(&String::from_utf8_lossy(&output.stdout), installed)
159 }
160 Platform::Windows | Platform::Wsl => None,
161 }
162}
163
164fn plist_json(path: &Path) -> Option<Value> {
165 let output = Command::new("plutil")
166 .args(["-convert", "json", "-o", "-"])
167 .arg(path)
168 .output()
169 .ok()?;
170 serde_json::from_slice(&output.stdout).ok()
171}
172
173fn macos_default_bundle_id() -> Option<String> {
174 let home = directories::BaseDirs::new()?.home_dir().to_path_buf();
175 let handlers = home
176 .join("Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");
177 handler_bundle_id(&plist_json(&handlers)?)
178}
179
180/// The app LaunchServices opens https links with, falling back to http.
181fn handler_bundle_id(handlers: &Value) -> Option<String> {
182 let entries = handlers["LSHandlers"].as_array()?;
183 ["https", "http"].iter().find_map(|scheme| {
184 entries
185 .iter()
186 .find(|entry| entry["LSHandlerURLScheme"] == *scheme)?["LSHandlerRoleAll"]
187 .as_str()
188 .map(str::to_owned)
189 })
190}
191
192/// `CFBundleIdentifier` of the app bundle holding `executable` (`X.app/Contents/MacOS/x`).
193fn bundle_id(executable: &Path) -> Option<String> {
194 let info = executable.parent()?.parent()?.join("Info.plist");
195 plist_json(&info)?["CFBundleIdentifier"]
196 .as_str()
197 .map(str::to_owned)
198}
199
200/// The installed browser named like the desktop entry `xdg-settings` reports, as in `firefox.desktop`.
201fn desktop_entry_match<'a>(
202 entry: &str,
203 installed: &'a [InstalledBrowser],
204) -> Option<&'a InstalledBrowser> {
205 let stem = entry.trim().trim_end_matches(".desktop");
206 installed.iter().find(|browser| browser.name == stem)
207}
208
209#[cfg(test)]
210mod tests {
211 use std::ffi::OsString;
212
213 use serde_json::json;
214
215 use super::*;
216
217 #[test]
218 fn finds_installed_browsers_chromium_first_once_each() {
219 let installed = [
220 "/Applications/Zen.app/Contents/MacOS/zen",
221 "/Users/joe/Applications/Zen.app/Contents/MacOS/zen",
222 "/Users/joe/Applications/Helium.app/Contents/MacOS/Helium",
223 ];
224 let found = installed_in(
225 Platform::Macos,
226 Some(Path::new("/Users/joe")),
227 &OsString::new(),
228 &|path| installed.iter().any(|known| path == Path::new(known)),
229 );
230 let names: Vec<(&str, Engine)> = found
231 .iter()
232 .map(|browser| (browser.name.as_str(), browser.engine))
233 .collect();
234 assert_eq!(
235 names,
236 [("Helium", Engine::Chromium), ("Zen", Engine::Firefox)]
237 );
238 assert_eq!(found[1].path, PathBuf::from(installed[0]));
239 }
240
241 #[test]
242 fn reads_the_https_handler() {
243 let handlers = json!({"LSHandlers": [
244 {"LSHandlerContentType": "public.html", "LSHandlerRoleAll": "com.apple.safari"},
245 {"LSHandlerURLScheme": "http", "LSHandlerRoleAll": "org.mozilla.firefox"},
246 {"LSHandlerURLScheme": "https", "LSHandlerRoleAll": "app.zen-browser.zen"},
247 ]});
248 assert_eq!(
249 handler_bundle_id(&handlers).as_deref(),
250 Some("app.zen-browser.zen")
251 );
252 assert_eq!(handler_bundle_id(&json!({"LSHandlers": []})), None);
253 }
254
255 #[test]
256 fn matches_the_linux_desktop_entry_by_name() {
257 let installed = installed_in(
258 Platform::Linux,
259 None,
260 &std::env::join_paths(["/usr/bin"]).unwrap(),
261 &|path| path == Path::new("/usr/bin/chromium") || path == Path::new("/usr/bin/firefox"),
262 );
263 let found = desktop_entry_match("firefox.desktop\n", &installed).unwrap();
264 assert_eq!(found.engine, Engine::Firefox);
265 assert!(desktop_entry_match("org.gnome.Epiphany.desktop", &installed).is_none());
266 }
267
268 #[test]
269 fn parses_the_saved_choice() {
270 assert_eq!(SignInBrowser::parse(" \n"), SignInBrowser::Automatic);
271 assert_eq!(
272 SignInBrowser::parse("/Applications/Zen.app/Contents/MacOS/zen\n"),
273 SignInBrowser::Program(PathBuf::from("/Applications/Zen.app/Contents/MacOS/zen"))
274 );
275 }
276}