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 let path_variable = std::env::var_os("PATH").unwrap_or_default();
70 installed_in(
71 Platform::detect(),
72 home.as_deref(),
73 &path_variable,
74 &|path| path.is_file(),
75 )
76}
77
78/// The browser Automatic stands for.
79pub fn automatic_browser(installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
80 automatic_in(Platform::detect(), installed)
81}
82
83fn automatic_in(platform: Platform, installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
84 system_default(platform, installed).or(installed.first())
85}
86
87/// The executable to sign in with: the saved choice while it is installed, else Automatic.
88pub(crate) fn chosen_executable(platform: Platform, home: Option<&Path>) -> Option<PathBuf> {
89 if !platform.uses_unix_paths() {
90 return None;
91 }
92 if let SignInBrowser::Program(path) = SignInBrowser::load()
93 && path.is_file()
94 {
95 return Some(path);
96 }
97 let path_variable = std::env::var_os("PATH").unwrap_or_default();
98 let installed = installed_in(platform, home, &path_variable, &|path| path.is_file());
99 automatic_in(platform, &installed).map(|browser| browser.path.clone())
100}
101
102pub(crate) fn installed_in(
103 platform: Platform,
104 home: Option<&Path>,
105 path_variable: &std::ffi::OsStr,
106 exists: &dyn Fn(&Path) -> bool,
107) -> Vec<InstalledBrowser> {
108 let found: Vec<(String, PathBuf)> = match platform {
109 Platform::Macos => MACOS_CHROME_APP_PATHS
110 .iter()
111 .chain(&MACOS_FIREFOX_APP_PATHS)
112 .filter_map(|relative| {
113 let path = application_roots(home)
114 .map(|root| root.join(relative))
115 .find(|path| exists(path))?;
116 let name = relative.split(".app/").next().unwrap_or(relative);
117 Some((name.to_owned(), path))
118 })
119 .collect(),
120 Platform::Linux => LINUX_CHROME_NAMES
121 .iter()
122 .chain(&LINUX_FIREFOX_NAMES)
123 .filter_map(|name| {
124 let path = std::env::split_paths(path_variable)
125 .map(|directory| directory.join(name))
126 .find(|path| exists(path))?;
127 Some(((*name).to_owned(), path))
128 })
129 .collect(),
130 Platform::Windows | Platform::Wsl => Vec::new(),
131 };
132 found
133 .into_iter()
134 .map(|(name, path)| InstalledBrowser {
135 engine: Engine::of_executable(&path),
136 name,
137 path,
138 })
139 .collect()
140}
141
142fn system_default(platform: Platform, installed: &[InstalledBrowser]) -> Option<&InstalledBrowser> {
143 match platform {
144 Platform::Macos => {
145 let wanted = macos_default_bundle_id()?;
146 installed.iter().find(|browser| {
147 bundle_id(&browser.path).is_some_and(|id| id.eq_ignore_ascii_case(&wanted))
148 })
149 }
150 Platform::Linux => {
151 let output = Command::new("xdg-settings")
152 .args(["get", "default-web-browser"])
153 .output()
154 .ok()?;
155 desktop_entry_match(&String::from_utf8_lossy(&output.stdout), installed)
156 }
157 Platform::Windows | Platform::Wsl => None,
158 }
159}
160
161fn plist_json(path: &Path) -> Option<Value> {
162 let output = Command::new("plutil")
163 .args(["-convert", "json", "-o", "-"])
164 .arg(path)
165 .output()
166 .ok()?;
167 serde_json::from_slice(&output.stdout).ok()
168}
169
170fn macos_default_bundle_id() -> Option<String> {
171 let home = directories::BaseDirs::new()?.home_dir().to_path_buf();
172 let handlers = home
173 .join("Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");
174 handler_bundle_id(&plist_json(&handlers)?)
175}
176
177/// The app LaunchServices opens https links with, falling back to http.
178fn handler_bundle_id(handlers: &Value) -> Option<String> {
179 let entries = handlers["LSHandlers"].as_array()?;
180 ["https", "http"].iter().find_map(|scheme| {
181 entries
182 .iter()
183 .find(|entry| entry["LSHandlerURLScheme"] == *scheme)?["LSHandlerRoleAll"]
184 .as_str()
185 .map(str::to_owned)
186 })
187}
188
189/// `CFBundleIdentifier` of the app bundle holding `executable` (`X.app/Contents/MacOS/x`).
190fn bundle_id(executable: &Path) -> Option<String> {
191 let info = executable.parent()?.parent()?.join("Info.plist");
192 plist_json(&info)?["CFBundleIdentifier"]
193 .as_str()
194 .map(str::to_owned)
195}
196
197/// The installed browser named like the desktop entry `xdg-settings` reports, as in `firefox.desktop`.
198fn desktop_entry_match<'a>(
199 entry: &str,
200 installed: &'a [InstalledBrowser],
201) -> Option<&'a InstalledBrowser> {
202 let stem = entry.trim().trim_end_matches(".desktop");
203 installed.iter().find(|browser| browser.name == stem)
204}
205
206#[cfg(test)]
207mod tests {
208 use std::ffi::OsString;
209
210 use serde_json::json;
211
212 use super::*;
213
214 #[test]
215 fn finds_installed_browsers_chromium_first_once_each() {
216 let installed = [
217 "/Applications/Zen.app/Contents/MacOS/zen",
218 "/Users/joe/Applications/Zen.app/Contents/MacOS/zen",
219 "/Users/joe/Applications/Helium.app/Contents/MacOS/Helium",
220 ];
221 let found = installed_in(
222 Platform::Macos,
223 Some(Path::new("/Users/joe")),
224 &OsString::new(),
225 &|path| installed.iter().any(|known| path == Path::new(known)),
226 );
227 let names: Vec<(&str, Engine)> = found
228 .iter()
229 .map(|browser| (browser.name.as_str(), browser.engine))
230 .collect();
231 assert_eq!(
232 names,
233 [("Helium", Engine::Chromium), ("Zen", Engine::Firefox)]
234 );
235 assert_eq!(found[1].path, PathBuf::from(installed[0]));
236 }
237
238 #[test]
239 fn reads_the_https_handler() {
240 let handlers = json!({"LSHandlers": [
241 {"LSHandlerContentType": "public.html", "LSHandlerRoleAll": "com.apple.safari"},
242 {"LSHandlerURLScheme": "http", "LSHandlerRoleAll": "org.mozilla.firefox"},
243 {"LSHandlerURLScheme": "https", "LSHandlerRoleAll": "app.zen-browser.zen"},
244 ]});
245 assert_eq!(
246 handler_bundle_id(&handlers).as_deref(),
247 Some("app.zen-browser.zen")
248 );
249 assert_eq!(handler_bundle_id(&json!({"LSHandlers": []})), None);
250 }
251
252 #[test]
253 fn matches_the_linux_desktop_entry_by_name() {
254 let installed = installed_in(
255 Platform::Linux,
256 None,
257 &std::env::join_paths(["/usr/bin"]).unwrap(),
258 &|path| path == Path::new("/usr/bin/chromium") || path == Path::new("/usr/bin/firefox"),
259 );
260 let found = desktop_entry_match("firefox.desktop\n", &installed).unwrap();
261 assert_eq!(found.engine, Engine::Firefox);
262 assert!(desktop_entry_match("org.gnome.Epiphany.desktop", &installed).is_none());
263 }
264
265 #[test]
266 fn parses_the_saved_choice() {
267 assert_eq!(SignInBrowser::parse(" \n"), SignInBrowser::Automatic);
268 assert_eq!(
269 SignInBrowser::parse("/Applications/Zen.app/Contents/MacOS/zen\n"),
270 SignInBrowser::Program(PathBuf::from("/Applications/Zen.app/Contents/MacOS/zen"))
271 );
272 }
273}