From 1edbbda36850d63dc61957db70fcf2a4e6b015cb Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 24 Oct 2026 13:45:15 +0300 Subject: [PATCH] Count installations that run: the update check goes through the site The programs (desktop, Android) ask https://chess.vrubel.xyz/api/update for the latest release instead of GitHub, with a random id of the installation (made once, kept in the settings), the version and the platform; the site passes GitHub's answer on and keeps one row per installation and day (no IP; the country of the address). Without the site the programs ask GitHub, uncounted; with the update check off nothing is sent. /stats shows installations that ran today, in 7 and 30 days, in all and new ones, by platform and version. The texts about the update check and the site's privacy line say so. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + .../chesspenguin/data/AppUpdates.kt | 17 ++- .../app/src/main/res/values-de/strings.xml | 2 +- .../app/src/main/res/values-es/strings.xml | 2 +- .../app/src/main/res/values-fr/strings.xml | 2 +- .../app/src/main/res/values-it/strings.xml | 2 +- .../app/src/main/res/values-kk/strings.xml | 2 +- .../app/src/main/res/values-pt/strings.xml | 2 +- .../app/src/main/res/values-ru/strings.xml | 2 +- .../app/src/main/res/values-uz/strings.xml | 2 +- .../app/src/main/res/values/strings.xml | 2 +- apps/desktop/src/app.rs | 4 + apps/desktop/src/i18n.rs | 18 +-- apps/desktop/src/settings.rs | 4 + apps/desktop/src/settings_ui.rs | 2 +- apps/desktop/src/update.rs | 52 ++++++- crates/mobile-api/src/update.rs | 21 ++- crates/releases/src/lib.rs | 14 ++ docs/dev/desktop.md | 2 +- website/README.md | 13 ++ website/server/src/main.rs | 138 +++++++++++++++++- website/site/i18n/de.json | 2 +- website/site/i18n/en.json | 2 +- website/site/i18n/es.json | 2 +- website/site/i18n/fr.json | 2 +- website/site/i18n/it.json | 2 +- website/site/i18n/kk.json | 2 +- website/site/i18n/pt.json | 2 +- website/site/i18n/ru.json | 2 +- website/site/i18n/uz.json | 2 +- 30 files changed, 284 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb94b69..5ef50ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- The update check goes through the ChessPenguin site (GitHub when the site does not + answer), which counts installations that run: once a day, only a random number of the + installation, the version and the platform. With the check turned off, nothing is + sent. The site's statistics show installations by day, platform and version. + ## [1.0.0] — 2026-10-24 - Three more interface languages on the desktop, on Android and on the website: Brazilian diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/AppUpdates.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/AppUpdates.kt index 7f6a944..062c2b3 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/AppUpdates.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/AppUpdates.kt @@ -28,7 +28,7 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import uniffi.mobile_api.ReleaseCheck import uniffi.mobile_api.checkRelease -import uniffi.mobile_api.releaseApi +import uniffi.mobile_api.checkReleaseCounted import java.io.File import java.io.IOException import java.security.MessageDigest @@ -95,7 +95,14 @@ class AppUpdates(private val context: Context, private val scope: CoroutineScope private val downloads get() = context.getSystemService(DownloadManager::class.java) private val dir get() = context.getExternalFilesDir("updates") private val json = Json { ignoreUnknownKeys = true } - private val api = BuildConfig.UPDATE_API.ifEmpty { releaseApi() } + /// A test server (debug builds); otherwise the site, which counts this installation. + private val testApi = BuildConfig.UPDATE_API + + /// A random id of this installation, made once; the site counts installations that + /// run by it (nothing else about the user is sent). + private fun installId(): String = prefs.getString(INSTALL_ID, null) ?: java.util.UUID.randomUUID().toString().replace("-", "").also { + prefs.edit().putString(INSTALL_ID, it).apply() + } private val _state = MutableStateFlow(null) /// The known newer release and where its update is; null when there is none. @@ -214,7 +221,10 @@ class AppUpdates(private val context: Context, private val scope: CoroutineScope _check.value = if (manual) CheckState.Offline else CheckState.Idle return } - val result = withContext(Dispatchers.IO) { checkRelease(api) } + val platform = if (BuildConfig.FLAVOR == "full") "android" else "android-noengine" + val result = withContext(Dispatchers.IO) { + if (testApi.isNotEmpty()) checkRelease(testApi) else checkReleaseCounted(installId(), platform) + } when (result) { is ReleaseCheck.Newer -> { val light = result.release.light ?: return @@ -599,6 +609,7 @@ class AppUpdates(private val context: Context, private val scope: CoroutineScope const val AUTO = "autoCheck" const val LAST_OK = "lastCheckOk" const val LAST_ATTEMPT = "lastAttempt" + const val INSTALL_ID = "installId" const val LATEST = "latest" const val HIDDEN = "hiddenVersion" const val DOWNLOAD = "downloadId" diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index aaa7533..eff82b6 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -376,7 +376,7 @@ Kopieren Updates Beim Start nach Updates suchen - Einmal am Tag fragt ChessPenguin bei GitHub nach der neuesten Version; über Sie wird nichts gesendet. + Einmal am Tag fragt ChessPenguin seine Website nach der neuesten Version; die Website zählt laufende Installationen. Gesendet werden nur eine Zufallsnummer dieser Installation und die Version. Jetzt prüfen Wird geprüft… Sie haben die neueste Version diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index 500a1b1..48e5743 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -382,7 +382,7 @@ Copiar Actualizaciones Buscar actualizaciones al iniciar - Una vez al día ChessPenguin pregunta a GitHub cuál es la última versión; no se envía nada sobre ti. + Una vez al día ChessPenguin pregunta a su sitio cuál es la última versión; el sitio cuenta las instalaciones en uso. Solo se envían un número aleatorio de esta instalación y la versión. Comprobar ahora Comprobando… Tienes la última versión diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index 48574f3..e391a9d 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -382,7 +382,7 @@ Copier Mises à jour Rechercher les mises à jour au démarrage - Une fois par jour, ChessPenguin demande à GitHub quelle est la dernière version ; rien sur vous n’est envoyé. + Une fois par jour, ChessPenguin demande à son site quelle est la dernière version ; le site compte les installations actives. Seuls un numéro aléatoire de cette installation et la version sont envoyés. Vérifier maintenant Vérification… Vous avez la dernière version diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index 34beb4f..a25318f 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -382,7 +382,7 @@ Copia Aggiornamenti Cerca aggiornamenti all’avvio - Una volta al giorno ChessPenguin chiede a GitHub qual è l’ultima versione; nulla su di te viene inviato. + Una volta al giorno ChessPenguin chiede al suo sito qual è l’ultima versione; il sito conta le installazioni in uso. Vengono inviati solo un numero casuale di questa installazione e la versione. Controlla ora Controllo in corso… Hai l’ultima versione diff --git a/androidApp/app/src/main/res/values-kk/strings.xml b/androidApp/app/src/main/res/values-kk/strings.xml index 822fdca..c1b94d9 100644 --- a/androidApp/app/src/main/res/values-kk/strings.xml +++ b/androidApp/app/src/main/res/values-kk/strings.xml @@ -375,7 +375,7 @@ Көшіру Жаңартулар Іске қосқанда жаңартуларды тексеру - Күніне бір рет ChessPenguin GitHub-тан қай нұсқа соңғы екенін сұрайды; сіз туралы ештеңе жіберілмейді. + Күніне бір рет ChessPenguin өз сайтынан соңғы нұсқаны сұрайды; сайт жұмыс істеп тұрған орнатуларды санайды. Тек осы орнатудың кездейсоқ нөмірі мен нұсқа жіберіледі. Қазір тексеру Тексерілуде… Сізде соңғы нұсқа diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml index c16b5d4..0753d2e 100644 --- a/androidApp/app/src/main/res/values-pt/strings.xml +++ b/androidApp/app/src/main/res/values-pt/strings.xml @@ -381,7 +381,7 @@ Copiar Atualizações Verificar atualizações ao iniciar - Uma vez por dia o ChessPenguin pergunta ao GitHub qual é a versão mais recente; nada sobre você é enviado. + Uma vez por dia o ChessPenguin pergunta ao seu site qual é a versão mais recente; o site conta as instalações em uso. São enviados apenas um número aleatório desta instalação e a versão. Verificar agora Verificando… Você tem a versão mais recente diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index a6f6578..c98bf9e 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -388,7 +388,7 @@ Копировать Обновления Проверять обновления при запуске - Раз в день ChessPenguin спрашивает у GitHub, какая версия последняя; ничего о вас не отправляется. + Раз в день ChessPenguin спрашивает у своего сайта, какая версия последняя; сайт считает работающие установки. Передаются только случайный номер этой установки и версия. Проверить сейчас Проверяю… У вас последняя версия diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml index f09cbac..dd774ce 100644 --- a/androidApp/app/src/main/res/values-uz/strings.xml +++ b/androidApp/app/src/main/res/values-uz/strings.xml @@ -374,7 +374,7 @@ Nusxalash Yangilanishlar Ishga tushganda yangilanishlarni tekshirish - ChessPenguin kuniga bir marta GitHubdan eng soʻnggi versiyani soʻraydi; siz haqingizda hech narsa yuborilmaydi. + ChessPenguin kuniga bir marta oʻz saytidan eng soʻnggi versiyani soʻraydi; sayt ishlayotgan oʻrnatmalarni sanaydi. Faqat shu oʻrnatmaning tasodifiy raqami va versiya yuboriladi. Hozir tekshirish Tekshirilmoqda… Sizda eng soʻnggi versiya diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index c14b1a3..3996393 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -378,7 +378,7 @@ Copy Updates Check for updates at start - Once a day ChessPenguin asks GitHub which version is the latest; nothing about you is sent. + Once a day ChessPenguin asks its site which version is the latest; the site counts installations that run. Only a random number of this installation and the version are sent. Check now Checking… You have the latest version diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 6af87f2..321b814 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -167,6 +167,10 @@ impl App { .last_version .clone() .filter(|v| crate::update::parse_version(v) < crate::update::parse_version(current)); + if settings.install_id.is_empty() { + settings.install_id = crate::update::new_install_id(); + } + crate::update::set_install_id(&settings.install_id); if settings.last_version.as_deref() != Some(current) { settings.last_version = Some(current.to_owned()); let _ = settings.save(); diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index ea1850e..a79e572 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -5661,15 +5661,15 @@ const ROWS: &[[&str; 9]] = &[ "Іске қосқанда жаңа нұсқаны тексеру", ], [ - "ChessPenguin asks GitHub which version is the latest; nothing about you is sent", - "ChessPenguin спрашивает у GitHub, какая версия последняя; ничего о вас не отправляется", - "ChessPenguin demande à GitHub quelle est la dernière version ; rien sur vous n'est envoyé", - "ChessPenguin fragt GitHub nach der neuesten Version; nichts über Sie wird gesendet", - "ChessPenguin pregunta a GitHub cuál es la última versión; no se envía nada sobre ti", - "ChessPenguin chiede a GitHub qual è l'ultima versione; nulla su di te viene inviato", - "O ChessPenguin pergunta ao GitHub qual é a versão mais recente; nada sobre você é enviado", - "ChessPenguin GitHubdan eng so‘nggi versiyani so‘raydi; siz haqingizda hech narsa yuborilmaydi", - "ChessPenguin GitHub-тан қай нұсқа соңғы екенін сұрайды; сіз туралы ештеңе жіберілмейді", + "ChessPenguin asks its site which version is the latest; the site counts installations that run: only a random number of this installation, the version and the system are sent", + "ChessPenguin спрашивает у своего сайта, какая версия последняя; сайт считает работающие установки: передаются только случайный номер этой установки, версия и система", + "ChessPenguin demande à son site quelle est la dernière version ; le site compte les installations actives : seuls un numéro aléatoire de cette installation, la version et le système sont envoyés", + "ChessPenguin fragt seine Website nach der neuesten Version; die Website zählt laufende Installationen: Gesendet werden nur eine Zufallsnummer dieser Installation, die Version und das System", + "ChessPenguin pregunta a su sitio cuál es la última versión; el sitio cuenta las instalaciones en uso: solo se envían un número aleatorio de esta instalación, la versión y el sistema", + "ChessPenguin chiede al suo sito qual è l'ultima versione; il sito conta le installazioni in uso: vengono inviati solo un numero casuale di questa installazione, la versione e il sistema", + "O ChessPenguin pergunta ao seu site qual é a versão mais recente; o site conta as instalações em uso: são enviados apenas um número aleatório desta instalação, a versão e o sistema", + "ChessPenguin o‘z saytidan eng so‘nggi versiyani so‘raydi; sayt ishlayotgan o‘rnatmalarni sanaydi: faqat shu o‘rnatmaning tasodifiy raqami, versiya va tizim yuboriladi", + "ChessPenguin өз сайтынан соңғы нұсқаны сұрайды; сайт жұмыс істеп тұрған орнатуларды санайды: тек осы орнатудың кездейсоқ нөмірі, нұсқа және жүйе жіберіледі", ], [ "Check now", diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index cd1070d..c55babb 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -128,6 +128,9 @@ pub struct Settings { pub skipped_version: Option, /// The version that ran last (to say "updated to …" once). pub last_version: Option, + /// A random id of this installation, sent with the update check (the site counts + /// installations that run; nothing else identifies the user). + pub install_id: String, /// The database of the reference tab (`None`: the largest one on the shelf). pub reference_db: Option, } @@ -189,6 +192,7 @@ impl Default for Settings { check_updates: true, skipped_version: None, last_version: None, + install_id: String::new(), reference_db: None, } } diff --git a/apps/desktop/src/settings_ui.rs b/apps/desktop/src/settings_ui.rs index 4e830f7..db8f1ab 100644 --- a/apps/desktop/src/settings_ui.rs +++ b/apps/desktop/src/settings_ui.rs @@ -123,7 +123,7 @@ impl SettingsWindow { changed |= ui .checkbox(&mut s.check_updates, tr("Check for updates at start")) .on_hover_text(tr( - "ChessPenguin asks GitHub which version is the latest; nothing about you is sent", + "ChessPenguin asks its site which version is the latest; the site counts installations that run: only a random number of this installation, the version and the system are sent", )) .changed(); }); diff --git a/apps/desktop/src/update.rs b/apps/desktop/src/update.rs index 80d8fe9..47b518c 100644 --- a/apps/desktop/src/update.rs +++ b/apps/desktop/src/update.rs @@ -1,6 +1,7 @@ -//! Updates: at start the program asks GitHub for the latest release (once, in the -//! background; can be turned off in Settings → About). When it is newer, a button next -//! to Settings offers it. What "update" does depends on how ChessPenguin was installed: +//! Updates: at start the program asks its site (else GitHub) for the latest release +//! (once, in the background; can be turned off in Settings → About; the site counts the +//! installation, see `releases::check_latest`). When it is newer, a button next to +//! Settings offers it. What "update" does depends on how ChessPenguin was installed: //! //! - the Windows zip, the AppImage and the Linux tarball: the new file is downloaded, //! checked against `SHA256SUMS.txt` and put in place of the running one; the program @@ -206,12 +207,48 @@ fn source_dir() -> Option { std::env::var_os("CP_UPDATE_SOURCE").map(PathBuf::from) } -/// Who asks GitHub. +/// Who asks the site and GitHub. fn client() -> String { format!("ChessPenguin/{}", env!("CARGO_PKG_VERSION")) } -/// Asks for the latest release. `Err` with a short reason when there is no answer. +static INSTALL_ID: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// This installation's id for the update check (`Settings::install_id`). +pub fn set_install_id(id: &str) { + let _ = INSTALL_ID.set(id.to_owned()); +} + +/// A new random installation id: 32 hex digits. +pub fn new_install_id() -> String { + let mut b = [0u8; 16]; + if getrandom::fill(&mut b).is_err() { + // No randomness: no id; the check then goes to GitHub, uncounted. + return String::new(); + } + b.iter().map(|x| format!("{x:02x}")).collect() +} + +impl Install { + /// The platform the site counts this installation under. + fn platform(&self) -> &'static str { + match self { + Install::Windows(_) => "windows", + Install::Mac => "macos", + Install::AppImage(_) => "appimage", + Install::Tarball(_) => "tarball", + Install::Deb => "deb", + Install::Rpm => "rpm", + Install::Arch => "arch", + Install::Aur => "aur", + Install::Flatpak => "flatpak", + Install::Other => "source", + } + } +} + +/// Asks for the latest release (through the site, which counts this installation; see +/// `releases::check_latest`). `Err` with a short reason when there is no answer. pub fn latest() -> Result { match source_dir() { Some(dir) => { @@ -220,7 +257,10 @@ pub fn latest() -> Result { let v: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; releases::parse_release(&v).ok_or_else(|| "unexpected answer".to_owned()) } - None => releases::fetch_latest(releases::API, &client()), + None => match INSTALL_ID.get().filter(|id| !id.is_empty()) { + Some(id) => releases::check_latest(id, detect().platform(), &client()), + None => releases::fetch_latest(releases::API, &client()), + }, } } diff --git a/crates/mobile-api/src/update.rs b/crates/mobile-api/src/update.rs index b5d841c..a749dd1 100644 --- a/crates/mobile-api/src/update.rs +++ b/crates/mobile-api/src/update.rs @@ -5,7 +5,7 @@ //! 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}; +use releases::{Release, VERSION, check_latest, fetch_latest, fetch_sums, sum_in}; /// GitHub's answer for the latest release (a debug build may ask a test server). #[uniffi::export] @@ -59,11 +59,24 @@ pub enum ReleaseCheck { const LIGHT: &str = "-android-noengine.apk"; const FULL: &str = "-android.apk"; -/// Asks `api` for the latest release; a newer one comes with its APKs. +/// Asks `api` (a test server) 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) { + checked(fetch_latest(&api, &client), &client) +} + +/// Asks the site for the latest release, counting this installation for the day (its +/// random `install` id and `platform`: "android" or "android-noengine"); without the +/// site, GitHub. A newer release comes with its APKs. +#[uniffi::export] +pub fn check_release_counted(install: String, platform: String) -> ReleaseCheck { + let client = format!("ChessPenguin/{VERSION} (Android)"); + checked(check_latest(&install, &platform, &client), &client) +} + +fn checked(found: Result, client: &str) -> ReleaseCheck { + let release = match found { Ok(r) => r, Err(detail) => return ReleaseCheck::Failed { detail }, }; @@ -73,7 +86,7 @@ pub fn check_release(api: String) -> ReleaseCheck { }; } let sums = if release.sums().is_some() { - match fetch_sums(&release, &client) { + match fetch_sums(&release, client) { Ok(s) => s, Err(detail) => return ReleaseCheck::Failed { detail }, } diff --git a/crates/releases/src/lib.rs b/crates/releases/src/lib.rs index b31b237..538ded1 100644 --- a/crates/releases/src/lib.rs +++ b/crates/releases/src/lib.rs @@ -10,6 +10,10 @@ use serde_json::Value; /// GitHub's answer for the latest release. pub const API: &str = "https://api.github.com/repos/vrubelroman/chessPenguin/releases/latest"; +/// The site's update check: GitHub's answer passed on, and this installation counted for +/// the day (website/README.md, "Installations"). +pub const CHECK: &str = "https://chess.vrubel.xyz/api/update"; + /// Where people download ChessPenguin. pub const DOWNLOAD_PAGE: &str = "https://chess.vrubel.xyz/"; @@ -130,6 +134,16 @@ pub fn fetch_latest(api: &str, client: &str) -> Result { parse_release(&v).ok_or_else(|| "unexpected answer".to_owned()) } +/// Asks the site for the latest release, counting this installation once a day: only its +/// random id (`install`, made up by the program), this version and `platform` ("windows", +/// "deb", "android"…) are sent. Without an answer from the site, GitHub is asked. +pub fn check_latest(install: &str, platform: &str, client: &str) -> Result { + // `CP_UPDATE_CHECK`: another site (a local one, to try it). + let site = std::env::var("CP_UPDATE_CHECK").unwrap_or_else(|_| CHECK.to_owned()); + let url = format!("{site}?install={install}&version={VERSION}&platform={platform}"); + fetch_latest(&url, client).or_else(|_| fetch_latest(API, client)) +} + /// Opens a file of the release for reading; a whole download has half an hour. pub fn open(asset: &Asset, client: &str) -> Result, String> { let resp = agent(client, Duration::from_secs(1800)) diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index af33404..595674c 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -50,7 +50,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe ``` `CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, -`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды), `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). +`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды), `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). ## Языки diff --git a/website/README.md b/website/README.md index ea0b711..c30044c 100644 --- a/website/README.md +++ b/website/README.md @@ -67,6 +67,19 @@ not run JavaScript never appear as visitors. Every row is classified: No IP is stored: visitors are told apart by a hash of IP and user agent with a salt that lives only in memory and changes every day. +## Installations + +The programs (desktop and Android, from 1.0.1) check for updates through `GET /api/update?install=&version=&platform=

` +instead of GitHub: the answer is GitHub's latest release (the fields the programs read: +`tag_name`, `html_url`, `assets[].name/browser_download_url/size`), and the call is counted +in the `launches` table — one row per installation and local day: the random id the +program made up, its version, platform (`windows`, `macos`, `deb`, `rpm`, `arch`, `aur`, +`appimage`, `flatpak`, `tarball`, `source`, `android`, `android-noengine`) and the country +of the address (the address is not kept). The local network is not counted. `/stats` +shows installations that ran today, in 7 and 30 days, in all, and new ones in 7 days, by +platform, and the versions of the last 7 days. A program that cannot reach the site asks +GitHub (uncounted); one with the update check turned off is not counted. + ## Development ```sh diff --git a/website/server/src/main.rs b/website/server/src/main.rs index d91b8c4..a036c75 100644 --- a/website/server/src/main.rs +++ b/website/server/src/main.rs @@ -99,6 +99,9 @@ pub struct Release { pub version: String, pub published: String, pub assets: Vec, + /// The release's page on GitHub (what is new in it). + #[serde(skip)] + page: String, } struct AppState { @@ -151,7 +154,17 @@ async fn main() { kind TEXT NOT NULL, ua TEXT ); - CREATE INDEX IF NOT EXISTS pageviews_ts ON pageviews (ts);", + CREATE INDEX IF NOT EXISTS pageviews_ts ON pageviews (ts); + -- The programs' update checks: one row per installation and local day. An + -- installation is a random id the program made up; no IP is kept. + CREATE TABLE IF NOT EXISTS launches ( + day TEXT NOT NULL, -- local day (TZ), YYYY-MM-DD + install TEXT NOT NULL, + version TEXT NOT NULL, + platform TEXT NOT NULL, -- windows, macos, deb, …, android, android-noengine + country TEXT, + PRIMARY KEY (day, install) + );", ) .expect("create the tables"); migrate(&db); @@ -216,6 +229,7 @@ async fn main() { }; let app = app .route("/api/release", get(api_release)) + .route("/api/update", get(api_update)) .route("/download/{platform}", get(download)) .route("/hit", post(hit)) .route("/stats", get(stats)) @@ -480,6 +494,7 @@ async fn latest(state: &Shared) -> Option { .ok()?; let version = v["tag_name"].as_str()?.trim_start_matches('v').to_string(); let published = v["published_at"].as_str().unwrap_or("").to_string(); + let page = v["html_url"].as_str().unwrap_or("").to_string(); let mut assets = Vec::new(); for a in v["assets"].as_array()? { let name = a["name"].as_str().unwrap_or(""); @@ -496,6 +511,7 @@ async fn latest(state: &Shared) -> Option { version, published, assets, + page, }) } .await; @@ -522,6 +538,60 @@ async fn api_release(State(state): State) -> Response { } } +#[derive(serde::Deserialize)] +struct Launch { + install: Option, + version: Option, + platform: Option, +} + +/// The programs' update check (desktop and Android): the latest release as GitHub gives +/// it (the fields the programs read), and the installation counted for the day. Only +/// what the program sends is kept: its random id, version, platform, and the country of +/// the address (the address itself is not). The local network is not counted. +async fn api_update( + State(state): State, + Query(q): Query, + ConnectInfo(peer): ConnectInfo, + headers: HeaderMap, +) -> Response { + let token = |s: &Option, max: usize, ok: fn(char) -> bool| { + s.as_deref() + .filter(|v| !v.is_empty() && v.len() <= max && v.chars().all(ok)) + .map(str::to_owned) + }; + let install = token(&q.install, 64, |c| c.is_ascii_hexdigit() || c == '-'); + let version = token(&q.version, 20, |c| c.is_ascii_digit() || c == '.'); + let platform = token(&q.platform, 24, |c| c.is_ascii_lowercase() || c == '-'); + if let (Some(install), Some(version), Some(platform)) = (install, version, platform) { + let ip = client_ip(&state.config, peer, &headers); + if !is_local(ip) { + let (country, _, _) = locate(&state, ip); + let day = chrono::Local::now().format("%Y-%m-%d").to_string(); + if let Ok(db) = state.db.lock() { + let _ = db.execute( + "INSERT OR REPLACE INTO launches (day, install, version, platform, country) + VALUES (?1, ?2, ?3, ?4, ?5)", + rusqlite::params![day, install, version, platform, country], + ); + } + } + } + match latest(&state).await { + Some(r) => Json(serde_json::json!({ + "tag_name": format!("v{}", r.version), + "html_url": r.page, + "assets": r.assets.iter().map(|a| serde_json::json!({ + "name": a.name, + "browser_download_url": a.url, + "size": a.size, + })).collect::>(), + })) + .into_response(), + None => (StatusCode::SERVICE_UNAVAILABLE, "release information unavailable").into_response(), + } +} + /// Counts the download and sends the browser to the file on GitHub (see [`file_url`]). async fn download( State(state): State, @@ -703,6 +773,8 @@ fn platform_label(platform: &str) -> &str { "deb" => "Linux · .deb", "rpm" => "Linux · .rpm", "arch" => "Linux · Arch", + "aur" => "Linux · AUR", + "source" => "Собрано из исходников", "appimage" => "Linux · AppImage", "flatpak" => "Linux · Flatpak", "tarball" => "Linux · .tar.gz", @@ -915,6 +987,68 @@ async fn stats(State(state): State, headers: HeaderMap) -> Response { )); } android.push_str(""); + + // Installations that ran (their update check): distinct ids per period and platform. + let since = |days: i64| { + (chrono::Local::now() - chrono::Duration::days(days - 1)) + .format("%Y-%m-%d") + .to_string() + }; + let (d1, d7, d30) = (since(1), since(7), since(30)); + let active = |platform: Option<&str>, from: Option<&str>| { + let mut sql = String::from("SELECT COUNT(DISTINCT install) FROM launches WHERE 1"); + if let Some(p) = platform { + sql.push_str(&format!(" AND platform = '{}'", p.replace('\'', ""))); + } + if let Some(f) = from { + sql.push_str(&format!(" AND day >= '{f}'")); + } + number(&db, &sql) + }; + let mut launches = format!( + "

Установки — запускались (проверка обновлений)

" + ); + let platforms = pairs(&db, "SELECT platform, COUNT(DISTINCT install) FROM launches GROUP BY 1 ORDER BY 2 DESC"); + let new_since = |platform: Option<&str>| { + let cond = platform.map_or(String::new(), |p| format!(" AND platform = '{}'", p.replace('\'', ""))); + number( + &db, + &format!("SELECT COUNT(*) FROM (SELECT install, MIN(day) AS first FROM launches WHERE 1{cond} GROUP BY install) WHERE first >= '{d7}'"), + ) + }; + let mut row = |label: &str, p: Option<&str>, strong: bool| { + let cells = [ + active(p, Some(&d1)), + active(p, Some(&d7)), + active(p, Some(&d30)), + active(p, None), + new_since(p), + ] + .map(|n| format!("", if strong { " big" } else { "" })) + .concat(); + launches.push_str(&format!("{cells}", esc(label))); + }; + row("Все платформы", None, true); + for (p, _) in &platforms { + row(platform_label(p), Some(p), false); + } + launches.push_str("
ПлатформаСегодня7 дней30 днейВсегоНовые за 7 дней
{n}
{}
"); + let versions = pairs( + &db, + &format!("SELECT version, COUNT(DISTINCT install) FROM launches WHERE day >= '{d7}' GROUP BY 1 ORDER BY 2 DESC LIMIT 10"), + ); + if !versions.is_empty() { + launches.push_str("

Версии за 7 дней: "); + launches.push_str( + &versions + .iter() + .map(|(v, n)| format!("{} — {n}", esc(v))) + .collect::>() + .join(" · "), + ); + launches.push_str("

"); + } + launches.push_str("

Каждая установка — случайный номер, который программа придумала сама; её считают раз в день, когда она проверяет обновления (кто выключил проверку, не учитывается). Локальная сеть не считается.

"); let by_version = pairs(&db, &format!("SELECT version, COUNT(*) {HUMAN_DL} GROUP BY 1 ORDER BY 2 DESC LIMIT 15")); let by_country = pairs(&db, &format!("SELECT country, COUNT(*) {HUMAN_DL} GROUP BY 1 ORDER BY 2 DESC LIMIT 30")); let by_region = pairs( @@ -996,7 +1130,7 @@ table{{border-collapse:collapse;width:100%}} td,th{{padding:4px 6px;border-botto .legend{{font-weight:400;color:var(--muted);margin-left:12px}} .legend i{{display:inline-block;width:10px;height:10px;border-radius:2px;margin:0 4px 0 10px;vertical-align:-1px}} a{{color:var(--accent)}}

ChessPenguin · статистика

-{summary}{excluded}{android}{chart} +{summary}{excluded}{launches}{android}{chart}
{}{}{}{}{}{}{}
{recent}

Считаются только люди: боты, ваши визиты (браузер, открывший эту страницу) и локальная сеть отсеиваются. Посетители считаются по странице, выполнившей JavaScript. IP не хранится. Скачивания в CSV · Просмотры в CSV · Геолокация по IP: DB-IP

diff --git a/website/site/i18n/de.json b/website/site/i18n/de.json index 867959d..50d911b 100644 --- a/website/site/i18n/de.json +++ b/website/site/i18n/de.json @@ -123,7 +123,7 @@ "support_issues": "Sie können auch ein Issue auf GitHub eröffnen:", "support_hint": "Geben Sie bei einem Problem bitte Ihre ChessPenguin-Version und Ihr System an und hängen Sie die PGN-Datei an, wenn es um eine Partie geht.", "footer_license": "Freie Software unter GPL-3.0-or-later", - "footer_privacy": "Keine Cookies, keine Tracker. Besuche, Downloads und Länder werden nur auf dem Server gezählt, ohne IP-Adressen zu speichern.", + "footer_privacy": "Keine Cookies, keine Tracker. Besuche, Downloads und Länder werden nur auf dem Server gezählt, ohne IP-Adressen zu speichern. Die Update-Prüfung des Programms wird ebenso gezählt, über eine Zufallsnummer der Installation.", "footer_geo": "IP-Geolokalisierung von", "nf_title": "Seite nicht gefunden", "nf_text": "Die gesuchte Seite oder Datei gibt es hier nicht.", diff --git a/website/site/i18n/en.json b/website/site/i18n/en.json index c41a849..d21c92d 100644 --- a/website/site/i18n/en.json +++ b/website/site/i18n/en.json @@ -123,7 +123,7 @@ "support_issues": "You can also open an issue on GitHub:", "support_hint": "When reporting a problem, please mention your ChessPenguin version and system, and attach the PGN file if the problem is with a game.", "footer_license": "Free software under GPL-3.0-or-later", - "footer_privacy": "No cookies, no trackers. Visits, downloads and countries are counted on the server only, without storing IP addresses.", + "footer_privacy": "No cookies, no trackers. Visits, downloads and countries are counted on the server only, without storing IP addresses. The program's update check is counted the same way, by a random number of the installation.", "footer_geo": "IP geolocation by", "nf_title": "Page not found", "nf_text": "The page or file you were looking for isn't here.", diff --git a/website/site/i18n/es.json b/website/site/i18n/es.json index 66ae759..2f192e0 100644 --- a/website/site/i18n/es.json +++ b/website/site/i18n/es.json @@ -123,7 +123,7 @@ "support_issues": "También puedes abrir una incidencia en GitHub:", "support_hint": "Al informar de un problema, indica tu versión de ChessPenguin y tu sistema, y adjunta el archivo PGN si el problema es con una partida.", "footer_license": "Software libre bajo GPL-3.0-or-later", - "footer_privacy": "Sin cookies ni rastreadores. Las visitas, descargas y países se cuentan solo en el servidor, sin guardar direcciones IP.", + "footer_privacy": "Sin cookies ni rastreadores. Las visitas, descargas y países se cuentan solo en el servidor, sin guardar direcciones IP. La comprobación de actualizaciones del programa se cuenta igual, mediante un número aleatorio de la instalación.", "footer_geo": "Geolocalización IP por", "nf_title": "Página no encontrada", "nf_text": "La página o el archivo que buscabas no está aquí.", diff --git a/website/site/i18n/fr.json b/website/site/i18n/fr.json index 30ceaa7..4b4f1de 100644 --- a/website/site/i18n/fr.json +++ b/website/site/i18n/fr.json @@ -123,7 +123,7 @@ "support_issues": "Vous pouvez aussi ouvrir un ticket sur GitHub :", "support_hint": "Pour signaler un problème, indiquez votre version de ChessPenguin et votre système, et joignez le fichier PGN si le problème concerne une partie.", "footer_license": "Logiciel libre sous GPL-3.0-or-later", - "footer_privacy": "Sans cookies ni traceurs. Les visites, téléchargements et pays sont comptés uniquement sur le serveur, sans conserver les adresses IP.", + "footer_privacy": "Sans cookies ni traceurs. Les visites, téléchargements et pays sont comptés uniquement sur le serveur, sans conserver les adresses IP. La vérification des mises à jour du programme est comptée de la même façon, par un numéro aléatoire de l’installation.", "footer_geo": "Géolocalisation IP par", "nf_title": "Page introuvable", "nf_text": "La page ou le fichier que vous cherchiez n'est pas ici.", diff --git a/website/site/i18n/it.json b/website/site/i18n/it.json index 635e67a..97872fb 100644 --- a/website/site/i18n/it.json +++ b/website/site/i18n/it.json @@ -123,7 +123,7 @@ "support_issues": "Puoi anche aprire una segnalazione su GitHub:", "support_hint": "Quando segnali un problema, indica la versione di ChessPenguin e il sistema, e allega il file PGN se il problema riguarda una partita.", "footer_license": "Software libero sotto GPL-3.0-or-later", - "footer_privacy": "Niente cookie né tracker. Visite, download e paesi sono contati solo sul server, senza conservare gli indirizzi IP.", + "footer_privacy": "Niente cookie né tracker. Visite, download e paesi sono contati solo sul server, senza conservare gli indirizzi IP. Il controllo degli aggiornamenti del programma è contato allo stesso modo, con un numero casuale dell’installazione.", "footer_geo": "Geolocalizzazione IP di", "nf_title": "Pagina non trovata", "nf_text": "La pagina o il file che cercavi non è qui.", diff --git a/website/site/i18n/kk.json b/website/site/i18n/kk.json index 7d08094..f2d82e0 100644 --- a/website/site/i18n/kk.json +++ b/website/site/i18n/kk.json @@ -123,7 +123,7 @@ "support_issues": "Сондай-ақ GitHub-та issue ашуға болады:", "support_hint": "Мәселе туралы хабарлағанда ChessPenguin нұсқасы мен жүйеңізді көрсетіңіз, ал мәселе партияға қатысты болса, PGN файлын тіркеңіз.", "footer_license": "GPL-3.0-or-later лицензиясымен таратылатын еркін бағдарлама", - "footer_privacy": "Cookie де, трекер де жоқ. Кірулер, жүктеулер мен елдер тек серверде, IP мекенжайлары сақталмай есептеледі.", + "footer_privacy": "Cookie де, трекер де жоқ. Кірулер, жүктеулер мен елдер тек серверде, IP мекенжайлары сақталмай есептеледі. Бағдарламадағы жаңартуларды тексеру де солай — орнатудың кездейсоқ нөмірі бойынша саналады.", "footer_geo": "IP геолокациясын ұсынған:", "nf_title": "Бет табылмады", "nf_text": "Сіз іздеген бет немесе файл бұл жерде жоқ.", diff --git a/website/site/i18n/pt.json b/website/site/i18n/pt.json index 68c6a65..a21f449 100644 --- a/website/site/i18n/pt.json +++ b/website/site/i18n/pt.json @@ -123,7 +123,7 @@ "support_issues": "Você também pode abrir uma issue no GitHub:", "support_hint": "Ao relatar um problema, informe sua versão do ChessPenguin e seu sistema, e anexe o arquivo PGN se o problema for com uma partida.", "footer_license": "Software livre sob GPL-3.0-or-later", - "footer_privacy": "Sem cookies, sem rastreadores. Visitas, downloads e países são contados apenas no servidor, sem guardar endereços IP.", + "footer_privacy": "Sem cookies, sem rastreadores. Visitas, downloads e países são contados apenas no servidor, sem guardar endereços IP. A verificação de atualizações do programa é contada da mesma forma, por um número aleatório da instalação.", "footer_geo": "Geolocalização de IP por", "nf_title": "Página não encontrada", "nf_text": "A página ou o arquivo que você procurava não está aqui.", diff --git a/website/site/i18n/ru.json b/website/site/i18n/ru.json index c2bd29a..1c2dabe 100644 --- a/website/site/i18n/ru.json +++ b/website/site/i18n/ru.json @@ -123,7 +123,7 @@ "support_issues": "Можно также открыть задачу на GitHub:", "support_hint": "Сообщая о проблеме, укажите версию ChessPenguin и систему, а если проблема с партией — приложите файл PGN.", "footer_license": "Свободная программа под GPL-3.0-or-later", - "footer_privacy": "Без cookie и трекеров. Посещения, загрузки и страны считаются только на сервере, IP-адреса не хранятся.", + "footer_privacy": "Без cookie и трекеров. Посещения, загрузки и страны считаются только на сервере, IP-адреса не хранятся. Проверка обновлений в программе считается так же — по случайному номеру установки.", "footer_geo": "Геолокация по IP —", "nf_title": "Страница не найдена", "nf_text": "Страницы или файла, который вы искали, здесь нет.", diff --git a/website/site/i18n/uz.json b/website/site/i18n/uz.json index bc8b5b8..85895b0 100644 --- a/website/site/i18n/uz.json +++ b/website/site/i18n/uz.json @@ -123,7 +123,7 @@ "support_issues": "GitHubda issue ochishingiz ham mumkin:", "support_hint": "Muammo haqida xabar berganda ChessPenguin versiyasi va tizimingizni yozing, muammo partiya bilan boʻlsa, PGN faylni ilova qiling.", "footer_license": "GPL-3.0-or-later litsenziyasidagi erkin dastur", - "footer_privacy": "Cookie ham, kuzatuvchilar ham yoʻq. Tashriflar, yuklab olishlar va mamlakatlar faqat serverda, IP manzillarni saqlamasdan hisoblanadi.", + "footer_privacy": "Cookie ham, kuzatuvchilar ham yoʻq. Tashriflar, yuklab olishlar va mamlakatlar faqat serverda, IP manzillarni saqlamasdan hisoblanadi. Dasturdagi yangilanishlarni tekshirish ham xuddi shunday — oʻrnatmaning tasodifiy raqami boʻyicha sanaladi.", "footer_geo": "IP geolokatsiyasi:", "nf_title": "Sahifa topilmadi", "nf_text": "Siz qidirgan sahifa yoki fayl bu yerda yoʻq.",