Skip to main content

tauri_plugin_update_gate/
lib.rs

1//! `tauri-plugin-update-gate`: reads a JSON document over HTTP and tells an
2//! app whether the installed copy is too old to run.
3
4mod decide;
5mod source;
6
7use tauri::plugin::{Builder, TauriPlugin};
8use tauri::{AppHandle, Manager, Runtime, State as Managed};
9
10use source::Source;
11
12pub use decide::{Gate, State};
13pub use source::Config;
14
15/// This build's OS, in the vocabulary `decide::Document::url` keys are
16/// written in. A target this list doesn't know about still compiles; the
17/// document simply won't carry a URL for it.
18const PLATFORM: &str = if cfg!(target_os = "ios") {
19    "ios"
20} else if cfg!(target_os = "android") {
21    "android"
22} else if cfg!(target_os = "macos") {
23    "macos"
24} else if cfg!(target_os = "windows") {
25    "windows"
26} else if cfg!(target_os = "linux") {
27    "linux"
28} else {
29    "unknown"
30};
31
32/// Registers the `check` command, backed by a `Source` built from `config`
33/// and held as managed state so the cache in `Source::gate` survives across
34/// calls.
35#[must_use]
36pub fn init<R: Runtime>(config: Config) -> TauriPlugin<R> {
37    Builder::new("update-gate")
38        .invoke_handler(tauri::generate_handler![check])
39        .setup(|app, _api| {
40            app.manage(Source::new(config));
41            Ok(())
42        })
43        .build()
44}
45
46/// Asks the managed `Source` whether the running copy may still play, in
47/// `lang` — the app's own language choice, e.g. one the player picked in
48/// its own Settings, independent of the OS — falling back through
49/// `resolve_language` to the OS environment and then `"en"` when `lang` is
50/// absent or unusable. The version comes from Tauri's own `PackageInfo`,
51/// never from the caller, so a webview can't lie about which build it is.
52///
53/// Returns `Result` only because Tauri requires it of an async command that
54/// borrows `State`; the gate itself fails open, so this never returns `Err`.
55#[tauri::command]
56async fn check<R: Runtime>(
57    app: AppHandle<R>,
58    source: Managed<'_, Source>,
59    lang: Option<String>,
60) -> Result<Gate, String> {
61    let running = app.package_info().version.to_string();
62    let lang = resolve_language(
63        lang.as_deref(),
64        env_language(|key| std::env::var(key).ok()).as_deref(),
65    );
66    Ok(source.gate(&running, &lang, PLATFORM).await)
67}
68
69/// Resolves the language to check the gate against: the caller's own
70/// choice first, then the OS environment, then `"en"` if neither yields a
71/// usable two-letter code. Kept pure and separate from where each side
72/// comes from so the fallback order is unit-testable without touching the
73/// environment.
74fn resolve_language(caller: Option<&str>, env: Option<&str>) -> String {
75    caller
76        .and_then(parse_language)
77        .or_else(|| env.and_then(parse_language))
78        .unwrap_or_else(|| "en".to_string())
79}
80
81/// Reads the OS's language hint, unparsed, from the POSIX locale variables
82/// through `var`, in the order POSIX gives them for messages: `LC_ALL`
83/// overrides everything, `LANG` is only the default. An empty variable
84/// counts as unset, as POSIX says. Desktop only: mobile targets typically
85/// leave these unset.
86fn env_language(var: impl Fn(&str) -> Option<String>) -> Option<String> {
87    ["LC_ALL", "LC_MESSAGES", "LANG"]
88        .into_iter()
89        .find_map(|key| var(key).filter(|v| !v.is_empty()))
90}
91
92/// Pulls a lowercase two-letter language code out of a locale-ish string —
93/// a bare code like `"vi"`, or a POSIX locale like `"vi_VN.UTF-8"` or
94/// `"en-US"` — by taking the substring before the first `_`, `.`, or `-`.
95/// Returns `None` for anything that doesn't reduce to exactly two ASCII
96/// letters, including `""`, `"C"`, and `"POSIX"`, none of which name a
97/// language.
98fn parse_language(raw: &str) -> Option<String> {
99    raw.split(['_', '.', '-'])
100        .next()
101        .map(str::to_lowercase)
102        .filter(|code| code.len() == 2 && code.bytes().all(|b| b.is_ascii_lowercase()))
103}
104
105#[cfg(test)]
106mod tests {
107    use super::{env_language, resolve_language};
108
109    /// An environment holding only `vars`, so the lookup order can be tested
110    /// without touching the real one.
111    fn env<'a>(vars: &'a [(&str, &str)]) -> impl Fn(&str) -> Option<String> + 'a {
112        move |key| {
113            vars.iter()
114                .find(|(k, _)| *k == key)
115                .map(|(_, v)| (*v).to_string())
116        }
117    }
118
119    #[test]
120    fn the_environment_is_read_in_posix_order() {
121        let all = [
122            ("LANG", "en_US"),
123            ("LC_MESSAGES", "fr_FR"),
124            ("LC_ALL", "vi_VN"),
125        ];
126        assert_eq!(env_language(env(&all)).as_deref(), Some("vi_VN"));
127        let no_all = [("LANG", "en_US"), ("LC_MESSAGES", "fr_FR")];
128        assert_eq!(env_language(env(&no_all)).as_deref(), Some("fr_FR"));
129        assert_eq!(
130            env_language(env(&[("LANG", "en_US")])).as_deref(),
131            Some("en_US")
132        );
133        assert_eq!(env_language(env(&[])), None);
134    }
135
136    #[test]
137    fn an_empty_variable_counts_as_unset() {
138        let vars = [("LANG", "en_US"), ("LC_ALL", "")];
139        assert_eq!(env_language(env(&vars)).as_deref(), Some("en_US"));
140    }
141
142    #[test]
143    fn the_callers_language_wins_over_the_environment() {
144        assert_eq!(resolve_language(Some("vi"), Some("en_US.UTF-8")), "vi");
145    }
146
147    #[test]
148    fn the_callers_language_is_parsed_the_same_way_as_the_environment() {
149        assert_eq!(resolve_language(Some("vi-VN"), None), "vi");
150    }
151
152    #[test]
153    fn an_absent_or_unusable_caller_falls_back_to_the_environment() {
154        assert_eq!(resolve_language(None, Some("fr.UTF-8")), "fr");
155        assert_eq!(resolve_language(Some(""), Some("fr.UTF-8")), "fr");
156        assert_eq!(resolve_language(Some("123"), Some("fr.UTF-8")), "fr");
157    }
158
159    #[test]
160    fn neither_side_usable_falls_back_to_english() {
161        assert_eq!(resolve_language(None, None), "en");
162        assert_eq!(resolve_language(Some("C"), Some("POSIX")), "en");
163    }
164}