Android: the app updates itself; one release check for the desktop and the phone
Some checks are pending
CI / macos-build (push) Waiting to run
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run

- crates/releases: the latest release on GitHub, its files and SHA-256 sums, shared by
  the desktop updater and the phone (desktop update.rs keeps its installers).
- mobile-api check_release: a newer release with its APKs and sums; a desktop-only
  release is no update, one without the light APK's sum cannot be checked.
- Android (android-ui.md §25): a check at start and on return once a day (switch and
  «Check now» in About), a card over the databases, a sheet through the install
  permission, the download (DownloadManager), the SHA-256, the full build keeping its
  engine network, and PackageInstaller; the state survives restarts, the update's
  snackbar waits for a screen. Network state permission for both builds (the full one
  crashed without it). Debug builds may ask a test server (CP_UPDATE_API).
- Release notes on GitHub come from this version's CHANGELOG section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-23 18:42:27 +03:00
parent 136f5320a8
commit 7f23bca320
35 changed files with 2502 additions and 138 deletions

View file

@ -26,6 +26,7 @@ chess-core.workspace = true
chess-import.workspace = true
game-review.workspace = true
online-games.workspace = true
releases.workspace = true
shakmaty.workspace = true
thiserror.workspace = true
uci.workspace = true

View file

@ -14,6 +14,7 @@ use shakmaty::Position;
mod engine;
mod online;
mod review;
mod update;
pub use engine::{Analysis, Analyzer, EngineFailure, EngineLine, LineStep};
pub use online::{
@ -21,6 +22,7 @@ pub use online::{
OnlineProblem, OnlineTarget, Site,
};
pub use review::{GameReview, MoveJudgement, ReviewMove, ReviewPoint, ReviewState, SideReview};
pub use update::{ApkFile, AppRelease, ReleaseCheck};
uniffi::setup_scaffolding!();

View file

@ -0,0 +1,153 @@
//! A newer release for the Android app: the `releases` crate (the same check as the
//! desktop's) with the two APKs of the release and their SHA-256. The app downloads and
//! installs the file itself (Android's download service and package installer).
//!
//! The check talks to GitHub (or to a test server in a debug build) and blocks: call it
//! off the main thread.
use releases::{Release, VERSION, fetch_latest, fetch_sums, sum_in};
/// GitHub's answer for the latest release (a debug build may ask a test server).
#[uniffi::export]
pub fn release_api() -> String {
releases::API.to_owned()
}
/// An APK of a release.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ApkFile {
pub name: String,
pub url: String,
pub size: u64,
/// From the release's `SHA256SUMS.txt`, lowercase hex.
pub sha256: String,
}
/// A release newer than this app.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct AppRelease {
pub version: String,
/// Its page: what is new in it.
pub page: String,
/// The build without the engine's network (the network already in the app stays).
pub light: Option<ApkFile>,
/// The build with the network inside.
pub full: Option<ApkFile>,
}
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
pub enum ReleaseCheck {
/// This app is the latest release (or newer: a build from the sources), or the newer
/// release has nothing for Android (a desktop-only one).
UpToDate {
latest: String,
},
Newer {
release: AppRelease,
},
/// A newer release whose light APK cannot be checked: no `SHA256SUMS.txt`, or no sum
/// for the file in it.
Unverifiable {
release: AppRelease,
},
/// No answer: `detail` for the log.
Failed {
detail: String,
},
}
const LIGHT: &str = "-android-noengine.apk";
const FULL: &str = "-android.apk";
/// Asks `api` for the latest release; a newer one comes with its APKs.
#[uniffi::export]
pub fn check_release(api: String) -> ReleaseCheck {
let client = format!("ChessPenguin/{VERSION} (Android)");
let release = match fetch_latest(&api, &client) {
Ok(r) => r,
Err(detail) => return ReleaseCheck::Failed { detail },
};
if !release.newer() || release.asset_ending(LIGHT).is_none() {
return ReleaseCheck::UpToDate {
latest: release.version,
};
}
let sums = if release.sums().is_some() {
match fetch_sums(&release, &client) {
Ok(s) => s,
Err(detail) => return ReleaseCheck::Failed { detail },
}
} else {
String::new()
};
let found = app_release(&release, &sums);
if found.light.as_ref().is_some_and(|a| !a.sha256.is_empty()) {
ReleaseCheck::Newer { release: found }
} else {
ReleaseCheck::Unverifiable { release: found }
}
}
/// The release's APKs with their sums ("" when `sums` has none for a file).
fn app_release(release: &Release, sums: &str) -> AppRelease {
let apk = |suffix: &str| {
let a = release.asset_ending(suffix)?;
Some(ApkFile {
name: a.name.clone(),
url: a.url.clone(),
size: a.size,
sha256: sum_in(sums, &a.name).unwrap_or_default(),
})
};
AppRelease {
version: release.version.clone(),
page: release.page.clone(),
light: apk(LIGHT),
full: apk(FULL),
}
}
#[cfg(test)]
mod tests {
use super::*;
use releases::Asset;
fn release(names: &[&str]) -> Release {
Release {
version: "9.9.9".into(),
page: "https://example.org/v9.9.9".into(),
assets: names
.iter()
.map(|n| Asset {
name: (*n).into(),
url: format!("https://example.org/{n}"),
size: 7,
})
.collect(),
}
}
#[test]
fn both_apks_with_their_sums() {
let r = release(&[
"ChessPenguin-9.9.9-android.apk",
"ChessPenguin-9.9.9-android-noengine.apk",
"SHA256SUMS.txt",
]);
let sums =
"aa ChessPenguin-9.9.9-android.apk\nbb ChessPenguin-9.9.9-android-noengine.apk\n";
let a = app_release(&r, sums);
let light = a.light.unwrap();
assert_eq!(light.name, "ChessPenguin-9.9.9-android-noengine.apk");
assert_eq!(light.sha256, "bb");
assert_eq!(a.full.unwrap().sha256, "aa");
}
#[test]
fn an_apk_without_its_sum_has_none() {
let r = release(&["ChessPenguin-9.9.9-android-noengine.apk", "SHA256SUMS.txt"]);
assert_eq!(app_release(&r, "").light.unwrap().sha256, "");
let r = release(&["ChessPenguin-9.9.9-windows-x86_64.zip"]);
assert!(app_release(&r, "").light.is_none());
}
}

View file

@ -0,0 +1,13 @@
[package]
name = "releases"
description = "The latest ChessPenguin release on GitHub: its version, files and SHA-256 sums (the desktop and Android apps share it)"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
publish = false
[dependencies]
serde_json.workspace = true
ureq = "3.4"

206
crates/releases/src/lib.rs Normal file
View file

@ -0,0 +1,206 @@
//! The latest ChessPenguin release on GitHub: its version, its files and their SHA-256
//! from the release's `SHA256SUMS.txt`. The desktop app updates itself with it, the
//! Android app offers its new APK; both are one release with one version (Cargo.toml).
use std::io::Read;
use std::time::Duration;
use serde_json::Value;
/// GitHub's answer for the latest release.
pub const API: &str = "https://api.github.com/repos/vrubelroman/chessPenguin/releases/latest";
/// Where people download ChessPenguin.
pub const DOWNLOAD_PAGE: &str = "https://chess.vrubel.xyz/";
/// The version of this build (the workspace's: the desktop and the phone are one release).
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// The file of the release with every file's SHA-256.
pub const SUMS: &str = "SHA256SUMS.txt";
/// "0.7.1" / "v0.7.1" → (0, 7, 1).
pub fn parse_version(v: &str) -> Option<(u32, u32, u32)> {
let mut it = v.trim().trim_start_matches('v').split('.');
let n = |s: Option<&str>| -> Option<u32> {
s?.chars()
.take_while(|c| c.is_ascii_digit())
.collect::<String>()
.parse()
.ok()
};
Some((n(it.next())?, n(it.next())?, n(it.next()).unwrap_or(0)))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Asset {
pub name: String,
pub url: String,
pub size: u64,
}
/// The latest release.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Release {
pub version: String,
/// Its page (what is new in it).
pub page: String,
pub assets: Vec<Asset>,
}
impl Release {
/// Newer than this build.
pub fn newer(&self) -> bool {
self.newer_than(VERSION)
}
pub fn newer_than(&self, current: &str) -> bool {
match (parse_version(&self.version), parse_version(current)) {
(Some(v), Some(c)) => v > c,
_ => false,
}
}
/// The file whose name ends with `suffix` ("-android-noengine.apk").
pub fn asset_ending(&self, suffix: &str) -> Option<&Asset> {
self.assets.iter().find(|a| a.name.ends_with(suffix))
}
pub fn sums(&self) -> Option<&Asset> {
self.assets.iter().find(|a| a.name == SUMS)
}
}
/// GitHub's answer for a release, as a [`Release`].
pub fn parse_release(v: &Value) -> Option<Release> {
let tag = v["tag_name"].as_str()?;
let assets = v["assets"]
.as_array()?
.iter()
.filter_map(|a| {
Some(Asset {
name: a["name"].as_str()?.to_owned(),
url: a["browser_download_url"].as_str()?.to_owned(),
size: a["size"].as_u64().unwrap_or(0),
})
})
.collect();
Some(Release {
version: tag.trim_start_matches('v').to_owned(),
page: v["html_url"].as_str().unwrap_or(DOWNLOAD_PAGE).to_owned(),
assets,
})
}
/// The SHA-256 of `name` in the text of a `SHA256SUMS.txt` (`<hash> <name>` lines, as
/// `sha256sum` writes them; a `*` before the name marks binary mode).
pub fn sum_in(sums: &str, name: &str) -> Option<String> {
sums.lines().find_map(|l| {
let (hash, file) = l.split_once(char::is_whitespace)?;
(file.trim().trim_start_matches('*') == name).then(|| hash.to_lowercase())
})
}
/// An HTTP client that says who asks (`client`: "ChessPenguin/0.15.0 (Android)").
/// `body` bounds the time to read an answer's body: a stalled connection ends then.
fn agent(client: &str, body: Duration) -> ureq::Agent {
let config = ureq::Agent::config_builder()
.user_agent(format!("{client} (+{DOWNLOAD_PAGE})"))
.timeout_connect(Some(Duration::from_secs(10)))
.timeout_recv_response(Some(Duration::from_secs(30)))
.timeout_recv_body(Some(body))
.build();
ureq::Agent::new_with_config(config)
}
/// Asks `api` (GitHub's [`API`], or a test server with the same answer) for the latest
/// release. `Err` with a short reason when there is no answer.
pub fn fetch_latest(api: &str, client: &str) -> Result<Release, String> {
let text = agent(client, Duration::from_secs(30))
.get(api)
.header("Accept", "application/vnd.github+json")
.call()
.map_err(|e| e.to_string())?
.body_mut()
.with_config()
.limit(4 << 20)
.read_to_string()
.map_err(|e| e.to_string())?;
let v: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
parse_release(&v).ok_or_else(|| "unexpected answer".to_owned())
}
/// Opens a file of the release for reading; a whole download has half an hour.
pub fn open(asset: &Asset, client: &str) -> Result<Box<dyn Read + Send>, String> {
let resp = agent(client, Duration::from_secs(1800))
.get(&asset.url)
.call()
.map_err(|e| e.to_string())?;
Ok(Box::new(resp.into_body().into_reader()))
}
/// The text of the release's `SHA256SUMS.txt`.
pub fn fetch_sums(release: &Release, client: &str) -> Result<String, String> {
let sums = release.sums().ok_or("the release has no SHA256SUMS.txt")?;
let mut text = String::new();
open(sums, client)?
.take(1 << 20)
.read_to_string(&mut text)
.map_err(|e| e.to_string())?;
Ok(text)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn versions() {
assert_eq!(parse_version("v0.7.1"), Some((0, 7, 1)));
assert_eq!(parse_version("0.10"), Some((0, 10, 0)));
assert_eq!(parse_version("1.2.3-rc1"), Some((1, 2, 3)));
assert_eq!(parse_version("x"), None);
let r = |v: &str| Release {
version: v.into(),
page: String::new(),
assets: Vec::new(),
};
assert!(r("0.10.0").newer_than("0.9.9"));
assert!(!r("0.14.0").newer_than("0.14.0"));
assert!(!r("0.13.9").newer_than("0.14.0"));
assert!(!r("garbage").newer_than("0.14.0"));
}
#[test]
fn github_answer() {
let v: Value = serde_json::from_str(
r#"{"tag_name":"v0.7.1","html_url":"https://github.com/x/releases/tag/v0.7.1",
"assets":[{"name":"SHA256SUMS.txt","browser_download_url":"https://x/s","size":10},
{"name":"ChessPenguin-0.7.1-android-noengine.apk","browser_download_url":"https://x/a","size":9}]}"#,
)
.unwrap();
let r = parse_release(&v).unwrap();
assert_eq!(r.version, "0.7.1");
assert_eq!(r.page, "https://github.com/x/releases/tag/v0.7.1");
assert_eq!(r.sums().map(|a| a.url.as_str()), Some("https://x/s"));
assert_eq!(
r.asset_ending("-android-noengine.apk").map(|a| a.size),
Some(9)
);
assert!(r.asset_ending("-android.apk").is_none());
}
#[test]
fn sums() {
let text = "AB12 ChessPenguin-1-android.apk\ncd34 *ChessPenguin-1-android-noengine.apk\n";
assert_eq!(
sum_in(text, "ChessPenguin-1-android.apk").as_deref(),
Some("ab12")
);
assert_eq!(
sum_in(text, "ChessPenguin-1-android-noengine.apk").as_deref(),
Some("cd34")
);
assert_eq!(sum_in(text, "other"), None);
}
}