//! Update channel reporting and the Android sideload updater. //! //! Desktop installs check through `tauri-plugin-updater` from the frontend. This //! module only reports which update path an install should use. Sideloaded //! Android builds cannot use that plugin (it is desktop-only), so the manifest //! fetch, APK download, checksum, and installer handoff live here behind app //! commands. Play-installed builds delegate to Play Core through the same //! Kotlin plugin. //! //! The app commands are registered on the main builder, not as plugin commands, //! so they need no capability entry (same pattern as `storage.rs`). #[cfg(target_os = "android")] use std::collections::BTreeMap; #[cfg(target_os = "linux")] use std::path::{Path, PathBuf}; #[cfg(target_os = "linux")] use std::process::Command; #[cfg(desktop)] use std::sync::OnceLock; #[cfg(target_os = "android")] use futures_util::StreamExt; #[cfg(target_os = "android")] use serde::Deserialize; use serde::Serialize; #[cfg(target_os = "android")] use sha2::{Digest, Sha256}; #[cfg(target_os = "android")] use tauri::Manager; #[cfg(target_os = "android")] use tauri::ipc::Channel; #[cfg(target_os = "android")] use tauri::plugin::{Builder as PluginBuilder, PluginHandle, TauriPlugin}; use tauri::{AppHandle, Runtime}; #[cfg(target_os = "android")] use tokio::io::AsyncWriteExt; /// Release manifest attached to every GitHub release as `android.json`. #[cfg(target_os = "android")] const ANDROID_MANIFEST_URL: &str = "https://github.com/lemueldls/typbase/releases/latest/download/android.json"; #[cfg(target_os = "android")] const GOOGLE_PLAY_INSTALLER: &str = "com.android.vending"; /// The Kotlin plugin handle. Registered in [`init`] and read by the commands. #[cfg(target_os = "android")] pub struct AndroidUpdater(PluginHandle); /// Update paths reported to the frontend. #[cfg(target_os = "android")] pub const CHANNEL_ANDROID_PLAY: &str = "android-play"; #[cfg(target_os = "android")] pub const CHANNEL_ANDROID_SIDELOAD: &str = "android-sideload"; #[cfg(desktop)] const CHANNEL_DESKTOP: &str = "desktop"; #[cfg(desktop)] const CHANNEL_DESKTOP_PACKAGE_MANAGED: &str = "desktop-package-managed"; #[cfg(not(any(target_os = "android", desktop)))] const CHANNEL_UNSUPPORTED: &str = "unsupported"; /// The package manager that installed this app, when it can be found from /// the executable's path. `command` is a copyable hint, not something the app /// runs itself. #[derive(Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PackageManagerInfo { id: String, #[serde(skip_serializing_if = "Option::is_none")] command: Option, } /// The channel and the data the update UI needs without a second round trip. #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct UpdateChannelInfo { channel: String, current_version: String, #[serde(skip_serializing_if = "Option::is_none")] manager: Option, } /// Registers the Kotlin `UpdaterPlugin` that handles the installer intent, the /// install-unknown-apps settings flow, and the Play Core update. Android only. /// There is no Kotlin half on other targets. #[cfg(target_os = "android")] pub fn init() -> TauriPlugin { PluginBuilder::new("update") .setup(|app, api| { let handle = api.register_android_plugin("at.typbase.app", "UpdaterPlugin")?; app.manage(AndroidUpdater(handle)); Ok(()) }) .build() } /// Which updater the running install should use. #[tauri::command] pub async fn update_channel(app: AppHandle) -> Result { let current_version = app.package_info().version.to_string(); #[cfg(target_os = "android")] { return Ok(UpdateChannelInfo { channel: android_channel(&app)?, current_version, manager: None, }); } #[cfg(desktop)] { let manager = package_manager(); Ok(UpdateChannelInfo { channel: desktop_channel(&app, manager.is_some()), current_version, manager, }) } #[cfg(not(any(target_os = "android", desktop)))] { let _ = app; Ok(UpdateChannelInfo { channel: CHANNEL_UNSUPPORTED.into(), current_version, manager: None, }) } } /// A distro build can blank the updater endpoints, but release `.deb` and /// `.rpm` files also get repackaged by distro maintainers. Probe the package /// database for the installed package too, and treat anything it reports as /// package-managed even when the bundled updater has endpoints. #[cfg(desktop)] fn desktop_channel(app: &AppHandle, owned: bool) -> String { let has_endpoints = app .config() .plugins .0 .get("updater") .and_then(|value| value.get("endpoints")) .and_then(|value| value.as_array()) .is_some_and(|endpoints| !endpoints.is_empty()); if has_endpoints && !owned { CHANNEL_DESKTOP.into() } else { CHANNEL_DESKTOP_PACKAGE_MANAGED.into() } } #[cfg(desktop)] static PACKAGE_MANAGER: OnceLock> = OnceLock::new(); #[cfg(desktop)] fn package_manager() -> Option { PACKAGE_MANAGER.get_or_init(detect_package_manager).clone() } /// Checks the executable against the package databases that ship a query tool. /// A source build outside those paths reports no owner and keeps the bundled /// updater. Nix store paths and sandboxed package layouts are recognized /// without running a command because their paths are already distinctive. #[cfg(desktop)] fn detect_package_manager() -> Option { if std::env::var_os("APPIMAGE").is_some() { return None; } if let Some(id) = std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()) { return Some(PackageManagerInfo { id: "flatpak".into(), command: Some(format!("flatpak update {id}")), }); } if std::env::var_os("SNAP").is_some() { let package = std::env::var("SNAP_NAME").unwrap_or_else(|_| "typbase".into()); return Some(PackageManagerInfo { id: "snap".into(), command: Some(format!("sudo snap refresh {package}")), }); } let exe = std::env::current_exe().ok()?; let canonical = std::fs::canonicalize(&exe).unwrap_or_else(|_| exe.clone()); let path = exe.to_string_lossy(); let canonical_path = canonical.to_string_lossy(); if path.starts_with("/nix/store/") || canonical_path.starts_with("/nix/store/") { return Some(PackageManagerInfo { id: "nix".into(), command: None, }); } if cfg!(target_os = "macos") && (path.contains("/Caskroom/") || canonical_path.contains("/Caskroom/") || [ "/opt/homebrew/Caskroom/typbase", "/usr/local/Caskroom/typbase", ] .iter() .any(|cask| std::path::Path::new(cask).exists())) { return Some(PackageManagerInfo { id: "homebrew".into(), command: Some("brew upgrade --cask typbase".into()), }); } #[cfg(target_os = "linux")] { for candidate in [path.as_ref(), canonical_path.as_ref()] { if let Some(manager) = linux_package_owner(candidate) { return Some(manager); } } } None } /// The owner query order follows the common layouts. A missing tool just /// returns `None`, so the next database gets a chance. #[cfg(target_os = "linux")] fn linux_package_owner(path: &str) -> Option { if let Some(package) = command_output("pacman", &["-Qoq", path]) { let official = command_output("pacman", &["-Si", package.as_str()]).is_some(); let helper = if official { None } else if command_exists("shelly") { Some("shelly") } else { ["yay", "paru"] .into_iter() .find(|helper| command_exists(helper)) }; let (id, command) = match (official, helper) { (true, _) => ("pacman", Some(format!("sudo pacman -Syu {package}"))), (false, Some("shelly")) => ("shelly", Some(format!("shelly update aur {package}"))), (false, Some(helper)) => (helper, Some(format!("{helper} -Syu {package}"))), (false, None) => ("pacman", None), }; return Some(PackageManagerInfo { id: id.into(), command, }); } if let Some(owner) = command_output("dpkg-query", &["-S", path]) { let package = owner .split(':') .next() .and_then(|names| names.split(',').next()) .map(str::trim) .filter(|name| !name.is_empty()); let command = match package { Some(package) => { format!("sudo apt update && sudo apt install --only-upgrade {package}") } None => "sudo apt update && sudo apt upgrade".into(), }; return Some(PackageManagerInfo { id: "apt".into(), command: Some(command), }); } if let Some(package) = command_output("rpm", &["-qf", "--qf", "%{NAME}", path]) { let (id, command) = if Path::new("/usr/bin/dnf").exists() { ("dnf", Some(format!("sudo dnf upgrade {package}"))) } else if Path::new("/usr/bin/zypper").exists() { ("zypper", Some(format!("sudo zypper update {package}"))) } else if Path::new("/usr/bin/rpm-ostree").exists() { ("rpm-ostree", Some("sudo rpm-ostree upgrade".into())) } else { ("rpm", None) }; return Some(PackageManagerInfo { id: id.into(), command, }); } if command_output("xbps-query", &["-o", path]).is_some() { return Some(PackageManagerInfo { id: "xbps".into(), command: Some("sudo xbps-install -Su".into()), }); } if command_output("apk", &["info", "--who-owns", path]).is_some() { return Some(PackageManagerInfo { id: "apk".into(), command: Some("sudo apk upgrade".into()), }); } None } #[cfg(target_os = "linux")] fn command_exists(program: &str) -> bool { if ["/usr/bin", "/bin", "/usr/sbin", "/sbin"] .iter() .any(|directory| Path::new(directory).join(program).is_file()) { return true; } std::env::var_os("PATH").is_some_and(|path| { std::env::split_paths(&path).any(|directory| directory.join(program).is_file()) }) } #[cfg(target_os = "linux")] fn command_output(program: &str, args: &[&str]) -> Option { // A desktop session can have a shorter PATH than a login shell, and Alpine // keeps apk in /sbin. Try the standard bin directories before PATH lookup. let mut candidates: Vec = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"] .iter() .map(|directory| Path::new(directory).join(program)) .filter(|path| path.exists()) .collect(); candidates.push(PathBuf::from(program)); for candidate in candidates { let Ok(output) = Command::new(&candidate).args(args).output() else { continue; }; if !output.status.success() { continue; } let text = String::from_utf8_lossy(&output.stdout).trim().to_string(); if text.is_empty() { continue; } return Some(text.lines().next().unwrap_or_default().to_string()); } None } /// Installs from Google Play get Play Core updates. Everything else (direct APK, /// sideload managers like Obtainium) gets the updater that reads the release manifest. #[cfg(target_os = "android")] fn android_channel(app: &AppHandle) -> Result { let installer = { let updater = app.state::>(); updater .0 .run_mobile_plugin::("installerSource", ()) .map_err(plugin_error)? .installer }; Ok(if installer.as_deref() == Some(GOOGLE_PLAY_INSTALLER) { CHANNEL_ANDROID_PLAY.into() } else { CHANNEL_ANDROID_SIDELOAD.into() }) } /// The sideload manifest entry for the device's best ABI, if it is newer than /// the installed version. #[cfg(target_os = "android")] #[derive(Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct SideloadUpdate { current_version: String, version: String, abi: String, url: String, sha256: String, size: u64, notes: Option, published_at: Option, } #[cfg(target_os = "android")] #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct AndroidManifest { version: String, #[serde(default)] notes: Option, #[serde(default)] published_at: Option, abis: BTreeMap, } #[cfg(target_os = "android")] #[derive(Debug, Deserialize)] struct AndroidAbiEntry { url: String, sha256: String, size: u64, } #[cfg(target_os = "android")] #[derive(Debug, Deserialize)] struct InstallerSource { installer: Option, } #[cfg(target_os = "android")] #[derive(Debug, Deserialize)] struct AbiList { abis: Vec, } /// Registers the download progress reported over the command channel. #[cfg(target_os = "android")] #[derive(Clone, Serialize)] #[serde(tag = "event", content = "data", rename_all = "camelCase")] pub enum DownloadEvent { Started { total: Option }, Progress { downloaded: u64, total: Option }, Finished { total: Option }, } /// Fetches the release manifest and returns the entry for this device, or /// `None` when the installed version is current or no ABI matches. #[tauri::command] #[cfg(target_os = "android")] pub async fn android_update_check( app: AppHandle, ) -> Result, String> { let result = check_sideload_update(&app).await; if let Err(cause) = &result { eprintln!("[update] check failed: {cause}"); } result } #[cfg(target_os = "android")] async fn check_sideload_update( app: &AppHandle, ) -> Result, String> { let abis = { let updater = app.state::>(); updater .0 .run_mobile_plugin::("abi", ()) .map_err(plugin_error)? .abis }; let manifest: AndroidManifest = crate::http::client()? .get(ANDROID_MANIFEST_URL) .timeout(std::time::Duration::from_secs(30)) .send() .await .map_err(|cause| format!("update check failed: {cause}"))? .error_for_status() .map_err(|cause| format!("update check failed: {cause}"))? .json() .await .map_err(|cause| format!("update manifest is not readable: {cause}"))?; let current = app.package_info().version.clone(); let latest = semver::Version::parse(manifest.version.trim().trim_start_matches('v')) .map_err(|cause| format!("update manifest version is not semver: {cause}"))?; if latest <= current { return Ok(None); } let Some(abi) = abis .into_iter() .find(|candidate| manifest.abis.contains_key(candidate)) else { return Ok(None); }; let entry = manifest .abis .get(&abi) .expect("abi picked from the manifest keys"); Ok(Some(SideloadUpdate { current_version: current.to_string(), version: manifest.version, abi, url: entry.url.clone(), sha256: entry.sha256.clone(), size: entry.size, notes: manifest.notes, published_at: manifest.published_at, })) } /// Streams the APK into the app cache and verifies its SHA-256 before handing /// the path back. The file lands inside the existing `${applicationId}.fileprovider` /// `cache-path` root, so the installer intent can share it. #[tauri::command] #[cfg(target_os = "android")] pub async fn android_update_download( app: AppHandle, url: String, sha256: String, on_event: Channel, ) -> Result { let directory = app .path() .app_cache_dir() .map_err(|cause| format!("no cache directory: {cause}"))?; tokio::fs::create_dir_all(&directory) .await .map_err(|cause| format!("could not create the cache directory: {cause}"))?; let path = directory.join("typbase-update.apk"); let response = crate::http::client()? .get(&url) .timeout(std::time::Duration::from_secs(900)) .send() .await .map_err(|cause| format!("download failed: {cause}"))? .error_for_status() .map_err(|cause| format!("download failed: {cause}"))?; let total = response.content_length(); let _ = on_event.send(DownloadEvent::Started { total }); let mut file = tokio::fs::File::create(&path) .await .map_err(|cause| format!("could not write the update: {cause}"))?; let mut hasher = Sha256::new(); let mut downloaded: u64 = 0; let mut stream = response.bytes_stream(); while let Some(chunk) = stream.next().await { let chunk = chunk.map_err(|cause| format!("download failed: {cause}"))?; hasher.update(&chunk); downloaded += chunk.len() as u64; file.write_all(&chunk) .await .map_err(|cause| format!("could not write the update: {cause}"))?; let _ = on_event.send(DownloadEvent::Progress { downloaded, total }); } file.flush() .await .map_err(|cause| format!("could not write the update: {cause}"))?; drop(file); let digest = hex::encode(hasher.finalize()); if !digest.eq_ignore_ascii_case(sha256.trim()) { let _ = tokio::fs::remove_file(&path).await; return Err("the downloaded update failed its checksum".into()); } let _ = on_event.send(DownloadEvent::Finished { total }); Ok(path.to_string_lossy().into_owned()) } /// Whether "install unknown apps" is granted. Android 8+ gates it per app. #[tauri::command] #[cfg(target_os = "android")] pub async fn android_update_can_install(app: AppHandle) -> Result { let updater = app.state::>(); updater .0 .run_mobile_plugin::("canInstall", ()) .map_err(plugin_error) .map(|response| response.can_install) } /// Opens the "install unknown apps" settings screen for Typbase. Resolves when /// the user comes back, so re-check `android_update_can_install` after it. #[tauri::command] #[cfg(target_os = "android")] pub async fn android_update_request_permission( app: AppHandle, ) -> Result<(), String> { let updater = app.state::>(); updater .0 .run_mobile_plugin::("requestInstallPermission", ()) .map_err(plugin_error)?; Ok(()) } /// Hands the cached APK to the system installer. The process is replaced once /// the user confirms, so this may never resolve on success. #[tauri::command] #[cfg(target_os = "android")] pub async fn android_update_install( app: AppHandle, path: String, ) -> Result<(), String> { let updater = app.state::>(); updater .0 .run_mobile_plugin::("install", InstallArgs { path }) .map_err(plugin_error)?; Ok(()) } /// Whether Play has an update for a Play-installed build. #[tauri::command] #[cfg(target_os = "android")] pub async fn android_play_update_check( app: AppHandle, ) -> Result { let updater = app.state::>(); updater .0 .run_mobile_plugin::("playCheck", ()) .map_err(plugin_error) } /// Starts Play's update flow. Immediate updates replace the screen with Play's /// own UI, and the result reports whether the user completed it. #[tauri::command] #[cfg(target_os = "android")] pub async fn android_play_update_start( app: AppHandle, ) -> Result { let updater = app.state::>(); updater .0 .run_mobile_plugin::("playStart", ()) .map_err(plugin_error) } #[cfg(target_os = "android")] #[derive(Debug, Deserialize)] struct CanInstallResponse { #[serde(rename = "canInstall")] can_install: bool, } #[cfg(target_os = "android")] #[derive(Debug, Serialize, Deserialize)] struct InstallArgs { path: String, } #[cfg(target_os = "android")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PlayUpdate { available: bool, #[serde(default)] version_code: i64, #[serde(default)] priority: i32, } #[cfg(target_os = "android")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PlayResult { status: String, #[serde(default)] code: i32, } #[cfg(target_os = "android")] fn plugin_error(cause: tauri::plugin::mobile::PluginInvokeError) -> String { cause.to_string() }