Skip to main content

smriti/services/
update_checker.rs

1//! GitHub Releases API client — "is a newer Smriti out?"
2//!
3//! This module owns the HTTP call, JSON parsing, semver comparison,
4//! and all the error cases that come with talking to a remote API.
5//! The Tauri command handler just turns the result into a DTO.
6//!
7//! Everything here is opt-in — the call only runs when the user has
8//! enabled "Automatically check for updates" in Settings or explicitly
9//! clicks "Check for updates now". See PRIVACY.md.
10
11use semver::Version;
12use serde::Deserialize;
13use std::time::Duration;
14
15/// Where GitHub's API lives. Overridable via `SMRITI_GITHUB_API_URL`
16/// (legacy `PHOTOVAULT_GITHUB_API_URL` still honoured) for integration
17/// tests without hitting the real API.
18const DEFAULT_API_URL: &str =
19    "https://api.github.com/repos/ChivukulaVirinchi/photovault/releases/latest";
20
21/// Timeout for the single API call. Short enough that a hung network
22/// doesn't block app startup, long enough to survive normal jitter.
23const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
24
25/// A release asset attached to a GitHub release (MSI, AppImage,
26/// .dmg, SHA256SUMS, etc.). `self_replace` consumes these.
27#[derive(Debug, Clone, Deserialize)]
28pub struct ReleaseAsset {
29    pub name: String,
30    pub browser_download_url: String,
31    #[serde(rename = "size")]
32    pub size_bytes: u64,
33}
34
35/// Raw shape of the GitHub `/releases/latest` JSON payload — just
36/// the fields we actually use.
37#[derive(Debug, Deserialize)]
38struct GithubRelease {
39    tag_name: String,
40    html_url: String,
41    #[serde(default)]
42    body: String,
43    #[serde(default)]
44    assets: Vec<ReleaseAsset>,
45}
46
47/// Normalized latest-release descriptor the rest of the app talks to.
48#[derive(Debug, Clone)]
49pub struct LatestRelease {
50    pub version: Version,
51    pub tag_name: String,
52    pub html_url: String,
53    pub body: String,
54    pub assets: Vec<ReleaseAsset>,
55}
56
57/// Result of a single update check: the running version, the latest
58/// published one, and whether an upgrade is available.
59#[derive(Debug, Clone)]
60pub struct UpdateStatus {
61    pub current: Version,
62    pub latest: LatestRelease,
63    pub newer_available: bool,
64}
65
66pub fn current_version() -> Version {
67    Version::parse(env!("CARGO_PKG_VERSION"))
68        .expect("CARGO_PKG_VERSION must be a valid semantic version")
69}
70
71/// Typed errors the UI/handler needs to distinguish so the user sees
72/// a useful message instead of a raw `reqwest` string.
73#[derive(Debug, thiserror::Error)]
74pub enum UpdateCheckError {
75    #[error("failed to reach GitHub's release API: {0}")]
76    Network(String),
77
78    #[error("GitHub returned HTTP {status} from {url}")]
79    HttpStatus { status: u16, url: String },
80
81    #[error("failed to parse GitHub's release JSON: {0}")]
82    Parse(String),
83
84    #[error("couldn't parse the release's tag as a semver: {0}")]
85    InvalidTag(String),
86
87    #[error("couldn't parse Smriti's own version as a semver: {0}")]
88    InvalidSelfVersion(String),
89}
90
91/// Check whether a newer release is available.
92///
93/// Hits `api.github.com/repos/ChivukulaVirinchi/photovault/releases/latest`
94/// by default. Set `SMRITI_GITHUB_API_URL` (or the legacy
95/// `PHOTOVAULT_GITHUB_API_URL`) to override — used by integration
96/// tests to point at a local mock.
97pub async fn check_for_updates() -> Result<UpdateStatus, UpdateCheckError> {
98    let url = std::env::var("SMRITI_GITHUB_API_URL")
99        .or_else(|_| std::env::var("PHOTOVAULT_GITHUB_API_URL"))
100        .unwrap_or_else(|_| DEFAULT_API_URL.to_string());
101
102    let client = reqwest::Client::builder()
103        .timeout(REQUEST_TIMEOUT)
104        .user_agent(format!("smriti/{}", env!("CARGO_PKG_VERSION")))
105        .build()
106        .map_err(|e| UpdateCheckError::Network(e.to_string()))?;
107
108    let response = client
109        .get(&url)
110        .header("Accept", "application/vnd.github+json")
111        .header("X-GitHub-Api-Version", "2022-11-28")
112        .send()
113        .await
114        .map_err(|e| UpdateCheckError::Network(e.to_string()))?;
115
116    let status = response.status();
117    if !status.is_success() {
118        return Err(UpdateCheckError::HttpStatus {
119            status: status.as_u16(),
120            url,
121        });
122    }
123
124    let payload: GithubRelease = response
125        .json()
126        .await
127        .map_err(|e| UpdateCheckError::Parse(e.to_string()))?;
128
129    let latest_version = parse_tag_as_version(&payload.tag_name)?;
130    let current_version = current_version();
131
132    let newer_available = latest_version > current_version;
133
134    Ok(UpdateStatus {
135        current: current_version,
136        newer_available,
137        latest: LatestRelease {
138            version: latest_version,
139            tag_name: payload.tag_name,
140            html_url: payload.html_url,
141            body: payload.body,
142            assets: payload.assets,
143        },
144    })
145}
146
147/// Parse a GitHub tag name into a `semver::Version`. Handles the
148/// common `v1.2.3` form by stripping the leading `v` before parsing.
149fn parse_tag_as_version(tag: &str) -> Result<Version, UpdateCheckError> {
150    let trimmed = tag.trim().trim_start_matches('v').trim_start_matches('V');
151    Version::parse(trimmed).map_err(|e| UpdateCheckError::InvalidTag(e.to_string()))
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[test]
159    fn tag_parses_with_v_prefix() {
160        assert_eq!(
161            parse_tag_as_version("v1.2.3").unwrap(),
162            Version::parse("1.2.3").unwrap()
163        );
164    }
165
166    #[test]
167    fn tag_parses_without_v_prefix() {
168        assert_eq!(
169            parse_tag_as_version("1.2.3").unwrap(),
170            Version::parse("1.2.3").unwrap()
171        );
172    }
173
174    #[test]
175    fn tag_parses_prerelease() {
176        let v = parse_tag_as_version("v1.0.0-beta.1").unwrap();
177        assert_eq!(v, Version::parse("1.0.0-beta.1").unwrap());
178        assert!(!v.pre.is_empty(), "prerelease segment should be present");
179    }
180
181    #[test]
182    fn tag_parses_uppercase_v() {
183        assert_eq!(
184            parse_tag_as_version("V2.0.0").unwrap(),
185            Version::parse("2.0.0").unwrap()
186        );
187    }
188
189    #[test]
190    fn tag_rejects_nonsemver() {
191        assert!(matches!(
192            parse_tag_as_version("banana"),
193            Err(UpdateCheckError::InvalidTag(_))
194        ));
195    }
196
197    #[test]
198    fn tag_rejects_empty() {
199        assert!(matches!(
200            parse_tag_as_version(""),
201            Err(UpdateCheckError::InvalidTag(_))
202        ));
203    }
204
205    #[test]
206    fn current_version_matches_package_version() {
207        assert_eq!(current_version().to_string(), env!("CARGO_PKG_VERSION"));
208    }
209}