Something went wrong. Try again.
Local-first knowledge base made for Typst and the Atmosphere. typbase.at
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677//! 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<R: Runtime>(PluginHandle<R>);
/// 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<String>,}
/// 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<PackageManagerInfo>,}
/// 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<R: Runtime>() -> TauriPlugin<R> { 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<R: Runtime>(app: AppHandle<R>) -> Result<UpdateChannelInfo, String> { 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<R: Runtime>(app: &AppHandle<R>, 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<Option<PackageManagerInfo>> = OnceLock::new();
#[cfg(desktop)]fn package_manager() -> Option<PackageManagerInfo> { 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<PackageManagerInfo> { 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<PackageManagerInfo> { 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<String> { // 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<PathBuf> = ["/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<R: Runtime>(app: &AppHandle<R>) -> Result<String, String> { let installer = { let updater = app.state::<AndroidUpdater<R>>(); updater .0 .run_mobile_plugin::<InstallerSource>("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<String>, published_at: Option<String>,}
#[cfg(target_os = "android")]#[derive(Debug, Deserialize)]#[serde(rename_all = "camelCase")]struct AndroidManifest { version: String, #[serde(default)] notes: Option<String>, #[serde(default)] published_at: Option<String>, abis: BTreeMap<String, AndroidAbiEntry>,}
#[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<String>,}
#[cfg(target_os = "android")]#[derive(Debug, Deserialize)]struct AbiList { abis: Vec<String>,}
/// 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<u64> }, Progress { downloaded: u64, total: Option<u64> }, Finished { total: Option<u64> },}
/// 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<R: Runtime>( app: AppHandle<R>,) -> Result<Option<SideloadUpdate>, 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<R: Runtime>( app: &AppHandle<R>,) -> Result<Option<SideloadUpdate>, String> { let abis = { let updater = app.state::<AndroidUpdater<R>>(); updater .0 .run_mobile_plugin::<AbiList>("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<R: Runtime>( app: AppHandle<R>, url: String, sha256: String, on_event: Channel<DownloadEvent>,) -> Result<String, String> { 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<R: Runtime>(app: AppHandle<R>) -> Result<bool, String> { let updater = app.state::<AndroidUpdater<R>>(); updater .0 .run_mobile_plugin::<CanInstallResponse>("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<R: Runtime>( app: AppHandle<R>,) -> Result<(), String> { let updater = app.state::<AndroidUpdater<R>>(); updater .0 .run_mobile_plugin::<serde_json::Value>("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<R: Runtime>( app: AppHandle<R>, path: String,) -> Result<(), String> { let updater = app.state::<AndroidUpdater<R>>(); updater .0 .run_mobile_plugin::<serde_json::Value>("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<R: Runtime>( app: AppHandle<R>,) -> Result<PlayUpdate, String> { let updater = app.state::<AndroidUpdater<R>>(); updater .0 .run_mobile_plugin::<PlayUpdate>("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<R: Runtime>( app: AppHandle<R>,) -> Result<PlayResult, String> { let updater = app.state::<AndroidUpdater<R>>(); updater .0 .run_mobile_plugin::<PlayResult>("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()}