diff --git a/Cargo.lock b/Cargo.lock index 952216c..ea72b9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2889,6 +2889,7 @@ dependencies = [ "tauri-build", "tauri-plugin-deep-link", "tauri-plugin-dialog", + "tauri-plugin-notification", "tauri-plugin-opener", "tauri-plugin-single-instance", "tokio", @@ -3100,6 +3101,20 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "mac-notification-sys" +version = "0.6.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca" +dependencies = [ + "cc", + "log", + "objc2", + "objc2-foundation", + "time", + "uuid", +] + [[package]] name = "markup5ever" version = "0.39.0" @@ -3306,6 +3321,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "notify-rust" +version = "4.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57da5b5d3b7809bf71858da5a2818c3404ca4688c02c8abecdda0fcdec235df3" +dependencies = [ + "futures-lite", + "log", + "mac-notification-sys", + "serde", + "tauri-winrt-notification", + "zbus 6.5.0", +] + [[package]] name = "notify-types" version = "2.3.1" @@ -5782,6 +5811,26 @@ dependencies = [ "url", ] +[[package]] +name = "tauri-plugin-notification" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14a226bfb8189ec4ab2c1936e66330ad06c44d9f6c54a674338208491dee177f" +dependencies = [ + "log", + "notify-rust", + "rand 0.10.4", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", + "time", + "url", + "zbus 5.19.0", +] + [[package]] name = "tauri-plugin-opener" version = "2.7.3" @@ -5920,6 +5969,17 @@ dependencies = [ "toml 1.2.3+spec-1.1.0", ] +[[package]] +name = "tauri-winrt-notification" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36" +dependencies = [ + "thiserror 2.0.21", + "windows", + "windows-version", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -7366,6 +7426,33 @@ dependencies = [ "zvariant 5.15.1", ] +[[package]] +name = "zbus" +version = "6.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7f9f5dd97fa527c1202ba1cb35d48e07f77d4de8542317c854f7aef22b0668" +dependencies = [ + "async-trait", + "bitflags 2.13.2", + "endi", + "futures-core", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "socket2", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.5", + "zbus_macros 6.5.0", + "zbus_utils", + "zcheapstr", + "zruntime", +] + [[package]] name = "zbus_macros" version = "4.4.0" @@ -7394,6 +7481,18 @@ dependencies = [ "zvariant_utils 4.2.0", ] +[[package]] +name = "zbus_macros" +version = "6.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f5aa7f2c4ea81b7ccfb26bafefdb4d1a44dd9d4f82c8426173a3727311743e4" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "zbus_utils", +] + [[package]] name = "zbus_names" version = "3.0.0" @@ -7416,6 +7515,19 @@ dependencies = [ "zvariant 5.15.1", ] +[[package]] +name = "zbus_utils" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.10", + "winnow 1.0.5", +] + [[package]] name = "zcheapstr" version = "1.4.0" @@ -7531,6 +7643,19 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zruntime" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac67096b97c00742108c4674db6bb6178adb78c4b66a506b0e4a7a9593aa5d9e" +dependencies = [ + "futures-core", + "futures-io", + "rustix", + "socket2", + "windows-sys 0.61.2", +] + [[package]] name = "zstd" version = "0.14.5" diff --git a/crates/knock-core/src/lib.rs b/crates/knock-core/src/lib.rs index 9df6c07..bc12483 100644 --- a/crates/knock-core/src/lib.rs +++ b/crates/knock-core/src/lib.rs @@ -10,6 +10,7 @@ pub mod prepare; pub mod run; pub mod runner; pub mod secrets; +pub mod update; pub mod vars; pub mod ws; diff --git a/crates/knock-core/src/update.rs b/crates/knock-core/src/update.rs new file mode 100644 index 0000000..d9a96a0 --- /dev/null +++ b/crates/knock-core/src/update.rs @@ -0,0 +1,90 @@ +//! Asks GitHub for the latest release. Only runs when the user opted in; +//! the request carries nothing but the version in the User-Agent. + +use anyhow::{anyhow, Result}; +use serde::Serialize; + +pub const RELEASES_API: &str = "https://api.github.com/repos/JoshiCodes/knock/releases/latest"; + +#[derive(Debug, Clone, Serialize)] +pub struct Release { + pub version: String, + pub url: String, + pub notes: String, + pub published_at: String, + pub newer: bool, +} + +/// Parses `1.2.3` or `v1.2.3-rc1`; pre-releases sort before their release. +fn parse(v: &str) -> Option<(u64, u64, u64, Option)> { + let v = v.trim().trim_start_matches('v'); + let (core, pre) = match v.split_once('-') { + Some((c, p)) => (c, Some(p.to_string())), + None => (v, None), + }; + let mut it = core.split('.').map(|x| x.parse::().ok()); + Some((it.next()??, it.next().flatten().unwrap_or(0), it.next().flatten().unwrap_or(0), pre)) +} + +pub fn is_newer(latest: &str, current: &str) -> bool { + match (parse(latest), parse(current)) { + (Some(l), Some(c)) => { + let (lk, ck) = ((l.0, l.1, l.2), (c.0, c.1, c.2)); + if lk != ck { + return lk > ck; + } + match (&l.3, &c.3) { + (None, Some(_)) => true, + (Some(a), Some(b)) => a > b, + _ => false, + } + } + _ => false, + } +} + +pub async fn latest(current: &str) -> Result { + let client = reqwest::Client::builder() + .user_agent(format!("knock/{current}")) + .timeout(std::time::Duration::from_secs(10)) + .build()?; + let resp = client + .get(RELEASES_API) + .header("Accept", "application/vnd.github+json") + .send() + .await + .map_err(|e| anyhow!("could not reach GitHub: {e}"))?; + match resp.status().as_u16() { + 200 => {} + 404 => return Err(anyhow!("no published release found (the repository may be private or have no releases yet)")), + 403 | 429 => return Err(anyhow!("GitHub rate limit reached; try again later")), + s => return Err(anyhow!("GitHub answered HTTP {s}")), + } + let v: serde_json::Value = serde_json::from_slice(&resp.bytes().await?)?; + let tag = v.get("tag_name").and_then(|t| t.as_str()).unwrap_or_default().to_string(); + let version = tag.trim_start_matches('v').to_string(); + Ok(Release { + newer: is_newer(&version, current), + url: v.get("html_url").and_then(|t| t.as_str()).unwrap_or_default().to_string(), + notes: v.get("body").and_then(|t| t.as_str()).unwrap_or_default().to_string(), + published_at: v.get("published_at").and_then(|t| t.as_str()).unwrap_or_default().to_string(), + version, + }) +} + +#[cfg(test)] +mod tests { + use super::is_newer; + + #[test] + fn compares_versions() { + assert!(is_newer("0.2.0", "0.1.0")); + assert!(is_newer("v1.0.0", "0.9.9")); + assert!(is_newer("0.2.0", "0.2.0-rc1")); + assert!(is_newer("0.2.0-rc2", "0.2.0-rc1")); + assert!(!is_newer("0.1.0", "0.1.0")); + assert!(!is_newer("0.2.0-rc1", "0.2.0")); + assert!(!is_newer("0.1.9", "0.2.0")); + assert!(!is_newer("garbage", "0.1.0")); + } +} diff --git a/package-lock.json b/package-lock.json index 51bfe53..3b5d982 100644 --- a/package-lock.json +++ b/package-lock.json @@ -27,6 +27,7 @@ "@tauri-apps/api": "^2.12.5", "@tauri-apps/plugin-deep-link": "^2.6.3", "@tauri-apps/plugin-dialog": "^2.8.4", + "@tauri-apps/plugin-notification": "^2.8.1", "@tauri-apps/plugin-opener": "^2.7.3", "cm6-graphql": "^1.0.0", "graphql": "^17.1.0", @@ -1345,6 +1346,15 @@ "@tauri-apps/api": "^2.12.0" } }, + "node_modules/@tauri-apps/plugin-notification": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-notification/-/plugin-notification-2.8.1.tgz", + "integrity": "sha512-B+OCJv17XCFQxAhe2+fn2bHqQ1fz/hGnYHeT++yv8+q0daOH5o1ghX7MmxWgoGFp7POaNn4UMONclHeZn65mJA==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.12.0" + } + }, "node_modules/@tauri-apps/plugin-opener": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-opener/-/plugin-opener-2.7.3.tgz", diff --git a/package.json b/package.json index 3121f88..565ea52 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "@tauri-apps/api": "^2.12.5", "@tauri-apps/plugin-deep-link": "^2.6.3", "@tauri-apps/plugin-dialog": "^2.8.4", + "@tauri-apps/plugin-notification": "^2.8.1", "@tauri-apps/plugin-opener": "^2.7.3", "cm6-graphql": "^1.0.0", "graphql": "^17.1.0", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 4e123f4..26c97ad 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -29,6 +29,7 @@ tracing.workspace = true tauri = { version = "2", features = [] } tauri-plugin-dialog = "2" tauri-plugin-opener = "2" +tauri-plugin-notification = "2" tauri-plugin-single-instance = { version = "2", features = ["deep-link"] } tauri-plugin-deep-link = "2" rusqlite = { version = "0.37", features = ["bundled"] } diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 194142e..bbbf787 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -18,6 +18,7 @@ "opener:default", "deep-link:default", "core:webview:allow-create-webview-window", - "core:window:allow-set-title" + "core:window:allow-set-title", + "notification:default" ] } diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 2dc661f..faa7995 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -794,3 +794,9 @@ pub async fn code_snippet(app: AppHandle, args: ScopeArgs, lang: knock_core::exp }; Ok(knock_core::export::snippet(&p, lang)) } + +/// Latest release on GitHub. Only called when the user opted in. +#[tauri::command] +pub async fn update_check() -> Res { + knock_core::update::latest(env!("CARGO_PKG_VERSION")).await.map_err(errx) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5dc1474..f95db52 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -19,6 +19,7 @@ pub fn run() { .plugin(tauri_plugin_deep_link::init()) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_opener::init()) + .plugin(tauri_plugin_notification::init()) .setup(|app| { let dir = app.path().app_data_dir()?; app.manage(state::AppState::new(dir)?); @@ -70,6 +71,7 @@ pub fn run() { commands::path_params, commands::app_version, commands::write_text_file, + commands::update_check, commands::runner_run, commands::import_curl, commands::import_detect, diff --git a/src/App.svelte b/src/App.svelte index 78ae5cb..b3429a5 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -20,11 +20,14 @@ import type { TreeNode } from '$lib/types'; import { onDeepLink } from '$lib/deeplink'; import { openDocs } from '$lib/help'; + import UpdateNotice from '$lib/views/UpdateNotice.svelte'; + import { updates } from '$lib/state/updates.svelte'; let ready = $state(false); onMount(() => { ws.restore().finally(() => (ready = true)); + updates.start(); const un = listen<{ collection: string; paths: string[] }>('collection-changed', (e) => { ws.onDiskChange(e.payload.collection, e.payload.paths); }); @@ -201,6 +204,7 @@ {/if} + diff --git a/src/lib/state/updates.svelte.ts b/src/lib/state/updates.svelte.ts new file mode 100644 index 0000000..2ec929c --- /dev/null +++ b/src/lib/state/updates.svelte.ts @@ -0,0 +1,97 @@ +import { invoke } from '@tauri-apps/api/core'; +import { isPermissionGranted, requestPermission, sendNotification } from '@tauri-apps/plugin-notification'; +import { errorText } from '$lib/api'; + +export interface Release { + version: string; + url: string; + notes: string; + published_at: string; + newer: boolean; +} + +const DAY = 24 * 60 * 60 * 1000; + +function get(key: string): string | null { + try { + return localStorage.getItem(key); + } catch { + return null; + } +} +function set(key: string, value: string) { + try { + localStorage.setItem(key, value); + } catch { + /* storage blocked */ + } +} + +/** + * Update notices. Off until the user says yes (no update pings without + * opt-in); then at most one request to GitHub per day. + */ +class Updates { + /** 'on', 'off', or null while the user has not been asked. */ + mode = $state(get('knock.updates')); + available = $state(null); + checking = $state(false); + lastError = $state(null); + askNow = $state(false); + + start() { + if (this.mode === null) { + // Ask once, a moment after start, not in the user's face. + setTimeout(() => (this.askNow = true), 6000); + return; + } + if (this.mode === 'on' && Date.now() - Number(get('knock.updates.last') ?? 0) > DAY) this.check(false); + } + + choose(on: boolean) { + this.mode = on ? 'on' : 'off'; + set('knock.updates', this.mode); + this.askNow = false; + if (on) this.check(false); + } + + async check(manual: boolean): Promise { + this.checking = true; + this.lastError = null; + try { + const r = await invoke('update_check'); + set('knock.updates.last', String(Date.now())); + const skipped = get('knock.updates.skip'); + if (r.newer && (manual || skipped !== r.version)) { + this.available = r; + if (!manual) await this.notify(r); + } + return r; + } catch (e) { + this.lastError = errorText(e); + return null; + } finally { + this.checking = false; + } + } + + skip() { + if (this.available) set('knock.updates.skip', this.available.version); + this.available = null; + } + + /** One desktop notification per version. */ + private async notify(r: Release) { + if (get('knock.updates.notified') === r.version) return; + try { + let ok = await isPermissionGranted(); + if (!ok) ok = (await requestPermission()) === 'granted'; + if (ok) sendNotification({ title: `knock ${r.version} is available`, body: 'Open knock for the download and what changed.' }); + set('knock.updates.notified', r.version); + } catch { + /* notifications unavailable; the in-app notice is enough */ + } + } +} + +export const updates = new Updates(); diff --git a/src/lib/views/UpdateNotice.svelte b/src/lib/views/UpdateNotice.svelte new file mode 100644 index 0000000..0098836 --- /dev/null +++ b/src/lib/views/UpdateNotice.svelte @@ -0,0 +1,25 @@ + + +{#if updates.available} + {@const r = updates.available} +
+ knock {r.version} is available. + Your version keeps working; updates come through your package manager or the download page. + + + + +
+{:else if updates.askNow} +
+ Tell you when a new knock is out? + Once a day knock asks GitHub for the latest release. Nothing about you or your requests is sent. + + + +
+{/if} diff --git a/src/lib/views/settings/AppSettings.svelte b/src/lib/views/settings/AppSettings.svelte index cedc679..4587b1f 100644 --- a/src/lib/views/settings/AppSettings.svelte +++ b/src/lib/views/settings/AppSettings.svelte @@ -5,6 +5,14 @@ import { ws } from '$lib/state/workspace.svelte'; import type { KeyValue } from '$lib/types'; import Mark from '$lib/ui/Mark.svelte'; + import { updates } from '$lib/state/updates.svelte'; + + let checkResult = $state(''); + async function checkNow() { + checkResult = ''; + const r = await updates.check(true); + if (r) checkResult = r.newer ? `knock ${r.version} is available.` : `You have the latest version (${r.version || version}).`; + } let globals = $state([]); let version = $state(''); @@ -74,6 +82,24 @@ +
+

Updates

+
+
+
Tell me about new versions
+
Once a day knock asks GitHub for the latest release. Nothing else is sent. knock never updates itself; use your package manager or the download page.
+
+ updates.choose(v)} aria-label="Check for updates" /> +
+
+ + {#if checkResult}{checkResult}{/if} + {#if updates.lastError}{updates.lastError}{/if} +
+
+

Global variables

Available in every collection, stored on this machine only. Anything defined in a collection wins.

@@ -83,7 +109,7 @@
knock {version} - MIT licensed. No telemetry, no account, no update checks. + MIT licensed. No telemetry, no account; update checks only if you turn them on.