From df2ee6f528fd1e7cde216ee127fd1e6aed0d45a4 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 24 Oct 2026 14:08:05 +0300 Subject: [PATCH] Installation counter after review: strict input, limits, country only, GitHub outages - /api/update takes a 32-hex id, an x.y.z version and a known platform; at most 5 new installations a day per address are counted (made-up ids do not flood the bot). - A download's notice: once a day per file and visitor; notices name the country only, as the texts promise; Android's text also says the system is sent. - The release cache is not locked while GitHub is asked (one request asks, the others get what is known); after a failure GitHub is asked again in a minute, not on every request. - An unrecognised desktop installation counts as 'other'; the bot logs a wrong token or a second listener; .env.example lists the bot's settings. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- .../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/update.rs | 2 +- website/.env.example | 5 + website/README.md | 15 +-- website/server/src/main.rs | 91 +++++++++++++++---- website/server/src/telegram.rs | 6 ++ 15 files changed, 106 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ef50ba..3b64809 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,8 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https - 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. + installation, the version and the platform. With the check at start turned off, + nothing is sent unless one checks by hand. The site's statistics show installations by day, platform and version. ## [1.0.0] — 2026-10-24 diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index eff82b6..40d2d1c 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 seine Website nach der neuesten Version; die Website zählt laufende Installationen. Gesendet werden nur eine Zufallsnummer dieser Installation und die Version. + Einmal am Tag fragt ChessPenguin seine Website nach der neuesten Version; die Website zählt laufende Installationen. Gesendet werden nur eine Zufallsnummer dieser Installation, die Version und das System. 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 48e5743..eb23455 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 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. + 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, la versión y el sistema. 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 e391a9d..be7f3f2 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 à 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. + 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, la version et le système 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 a25318f..13f5aae 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 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. + 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, la versione e il sistema. 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 c1b94d9..a3fb20d 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 өз сайтынан соңғы нұсқаны сұрайды; сайт жұмыс істеп тұрған орнатуларды санайды. Тек осы орнатудың кездейсоқ нөмірі мен нұсқа жіберіледі. + Күніне бір рет ChessPenguin өз сайтынан соңғы нұсқаны сұрайды; сайт жұмыс істеп тұрған орнатуларды санайды. Тек осы орнатудың кездейсоқ нөмірі, нұсқа және жүйе жіберіледі. Қазір тексеру Тексерілуде… Сізде соңғы нұсқа diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml index 0753d2e..312a82e 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 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. + 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, a versão e o sistema. 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 c98bf9e..a83cf3b 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 спрашивает у своего сайта, какая версия последняя; сайт считает работающие установки. Передаются только случайный номер этой установки и версия. + Раз в день ChessPenguin спрашивает у своего сайта, какая версия последняя; сайт считает работающие установки. Передаются только случайный номер этой установки, версия и система. Проверить сейчас Проверяю… У вас последняя версия diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml index dd774ce..7942466 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 oʻz saytidan eng soʻnggi versiyani soʻraydi; sayt ishlayotgan oʻrnatmalarni sanaydi. Faqat shu oʻrnatmaning tasodifiy raqami va versiya yuboriladi. + ChessPenguin kuniga bir marta oʻz saytidan eng soʻnggi versiyani soʻraydi; sayt ishlayotgan oʻrnatmalarni sanaydi. Faqat shu oʻrnatmaning tasodifiy raqami, versiya va tizim 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 3996393..3343998 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 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. + 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, the version and the system are sent. Check now Checking… You have the latest version diff --git a/apps/desktop/src/update.rs b/apps/desktop/src/update.rs index 47b518c..a728696 100644 --- a/apps/desktop/src/update.rs +++ b/apps/desktop/src/update.rs @@ -242,7 +242,7 @@ impl Install { Install::Arch => "arch", Install::Aur => "aur", Install::Flatpak => "flatpak", - Install::Other => "source", + Install::Other => "other", } } } diff --git a/website/.env.example b/website/.env.example index a4cd142..c0855fe 100644 --- a/website/.env.example +++ b/website/.env.example @@ -15,3 +15,8 @@ STATS_PASSWORD= GITHUB_REPO=vrubelroman/chessPenguin # Take the visitor address from X-Forwarded-For / X-Real-IP (set by nginx). TRUST_PROXY=1 + +# The owner's Telegram bot (downloads, installations, /stat): its token from @BotFather +# and the owner's chat id. Empty: no notices. One server per bot. +TELEGRAM_TOKEN= +TELEGRAM_CHAT= diff --git a/website/README.md b/website/README.md index 7f758bb..46c7f7e 100644 --- a/website/README.md +++ b/website/README.md @@ -73,18 +73,21 @@ The programs (desktop and Android, from 1.0.1) check for updates through `GET /a 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` +program made up (32 hex digits), its version, platform (`windows`, `macos`, `deb`, `rpm`, +`arch`, `aur`, `appimage`, `flatpak`, `tarball`, `other`, `android`, `android-noengine`) and +the country of the address (the address is not kept). The local network is not counted, +nor more than 5 new installations a day from one address. `/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. +GitHub (uncounted); one with the update check at start turned off is counted only when +the user checks by hand. ## Telegram With `TELEGRAM_TOKEN` (the owner's bot) and `TELEGRAM_CHAT` (the owner's chat id) in -`.env`, the site writes to the owner: «⬇️ Скачали …» for a person's download (not -crawlers, the owner or the local network), «🆕 Новая установка №N» for an installation's +`.env`, the site writes to the owner (with the country only): «⬇️ Скачали …» for a +person's download (not crawlers, the owner or the local network; once a day per file and +visitor), «🆕 Новая установка №N» for an installation's first run, «⬆️ Обновилась …» when it runs a new version, «▶️ Запуск …» when it runs on a new day (once a day at most). `/stat` answers with today and all time: downloads, installations that ran and new ones, active in 7 and 30 days, by platform. Only the diff --git a/website/server/src/main.rs b/website/server/src/main.rs index 3e994bc..38bec37 100644 --- a/website/server/src/main.rs +++ b/website/server/src/main.rs @@ -44,8 +44,20 @@ pub const PLATFORMS: &[(&str, &str)] = &[ ("checksums", "SHA256SUMS.txt"), ]; +/// What a program's update check may give as its platform (desktop installations, +/// Android builds). +const LAUNCH_PLATFORMS: &[&str] = &[ + "windows", "macos", "deb", "rpm", "arch", "aur", "appimage", "flatpak", "tarball", "other", + "android", "android-noengine", +]; + +/// New installations counted per address and day. +const NEW_INSTALLS_PER_ADDRESS: u32 = 5; + /// The latest release is asked from GitHub at most this often. const RELEASE_TTL: Duration = Duration::from_secs(600); +/// GitHub did not answer: what is known serves on, and GitHub is asked again after this. +const RELEASE_RETRY: Duration = Duration::from_secs(60); struct Config { port: u16, @@ -113,7 +125,12 @@ struct AppState { http: reqwest::Client, /// The same without following redirects: to learn where GitHub sends a file. direct: reqwest::Client, + /// The latest release and until when it is fresh. release: tokio::sync::Mutex>, + /// Held by the one request that asks GitHub; the others meanwhile get what is known. + asking: tokio::sync::Mutex<()>, + /// New installations counted today per address (a hash of it): a few per address. + new_installs: Mutex<(String, HashMap)>, /// The owner's Telegram bot (notices and `/stat`), when configured. bot: Option>, /// The visitor-key salt and the local day it belongs to. @@ -214,6 +231,8 @@ async fn main() { .build() .expect("http client"), release: tokio::sync::Mutex::new(None), + asking: tokio::sync::Mutex::new(()), + new_installs: Mutex::new((String::new(), HashMap::new())), bot: telegram::Bot::from_env(), salt: Mutex::new((String::new(), 0)), }); @@ -490,12 +509,16 @@ async fn sitemap(State(state): State) -> Response { /// The latest release, from the cache or GitHub; the last good answer is kept when /// GitHub fails. async fn latest(state: &Shared) -> Option { - let mut cache = state.release.lock().await; - if let Some((at, r)) = cache.as_ref() - && at.elapsed() < RELEASE_TTL + let known = || async { state.release.lock().await.as_ref().map(|(_, r)| r.clone()) }; + if let Some((until, r)) = state.release.lock().await.as_ref() + && Instant::now() < *until { return Some(r.clone()); } + // One request asks GitHub (up to 15 s); the others do not wait for it. + let Ok(_asking) = state.asking.try_lock() else { + return known().await; + }; let url = format!( "https://api.github.com/repos/{}/releases/latest", state.config.repo @@ -536,12 +559,18 @@ async fn latest(state: &Shared) -> Option { }) } .await; + let mut cache = state.release.lock().await; match fetched { Some(r) => { - *cache = Some((Instant::now(), r.clone())); + *cache = Some((Instant::now() + RELEASE_TTL, r.clone())); Some(r) } - None => cache.as_ref().map(|(_, r)| r.clone()), + None => { + if let Some((until, _)) = cache.as_mut() { + *until = Instant::now() + RELEASE_RETRY; + } + cache.as_ref().map(|(_, r)| r.clone()) + } } } @@ -581,15 +610,36 @@ async fn api_update( .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 == '-'); + // An id is 32 lowercase hex digits, a version "1.0.1", a platform one of the builds. + let install = token(&q.install, 32, |c| c.is_ascii_digit() || ('a'..='f').contains(&c)) + .filter(|i| i.len() == 32); + let version = token(&q.version, 20, |c| c.is_ascii_digit() || c == '.') + .filter(|v| v.split('.').count() == 3 && v.split('.').all(|p| !p.is_empty())); + let platform = token(&q.platform, 24, |c| c.is_ascii_lowercase() || c == '-') + .filter(|p| LAUNCH_PLATFORMS.contains(&p.as_str())); 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, region, city) = locate(&state, ip); + let (country, _, _) = locate(&state, ip); let day = chrono::Local::now().format("%Y-%m-%d").to_string(); + // A few new installations a day per address (a family, a classroom); more is + // someone making ids up, and is not counted. + let address = visitor_key(&state, ip, ""); let notice = state.db.lock().ok().and_then(|db| { + let known: Option = db + .query_row("SELECT n FROM installs WHERE install = ?1", [&install], |r| r.get(0)) + .ok(); + if known.is_none() { + let mut seen = state.new_installs.lock().unwrap_or_else(|e| e.into_inner()); + if seen.0 != day { + *seen = (day.clone(), HashMap::new()); + } + let count = seen.1.entry(address).or_default(); + if *count >= NEW_INSTALLS_PER_ADDRESS { + return None; + } + *count += 1; + } // What this installation was before: its last version, and whether it // already ran today. let before: Option = db @@ -611,9 +661,6 @@ async fn api_update( VALUES (?1, ?2, ?3, ?4, ?5)", rusqlite::params![day, install, version, platform, country], ); - let known: Option = db - .query_row("SELECT n FROM installs WHERE install = ?1", [&install], |r| r.get(0)) - .ok(); let n = match known { Some(n) => n, None => { @@ -626,7 +673,8 @@ async fn api_update( } }; let label = platform_label(&platform); - let place = telegram::place(country.as_deref(), region.as_deref(), city.as_deref()); + // The country only: what the texts about the update check promise. + let place = telegram::place(country.as_deref(), None, None); let place = if place.is_empty() { String::new() } else { format!("\n{place}") }; match before { _ if known.is_none() => { @@ -723,9 +771,18 @@ async fn download( c.ua ], ); - // People only: not crawlers, not the owner, not the local network. - if kind == "human" && asset.platform != "checksums" { - let place = telegram::place(c.country.as_deref(), c.region.as_deref(), c.city.as_deref()); + // People only: not crawlers, not the owner, not the local network; one notice a + // day per file and visitor (a download started again is not another person). + let again: bool = db + .query_row( + "SELECT COUNT(*) > 1 FROM downloads WHERE visitor = ?1 AND platform = ?2 + AND date(ts, 'localtime') = date('now', 'localtime')", + rusqlite::params![c.visitor, asset.platform], + |r| r.get(0), + ) + .unwrap_or(false); + if kind == "human" && asset.platform != "checksums" && !again { + let place = telegram::place(c.country.as_deref(), None, None); let from = referrer.as_deref().map(|r| format!(" · с {r}")).unwrap_or_default(); let line = [place, from.trim_start_matches(" · ").to_owned()] .into_iter() @@ -861,7 +918,7 @@ fn platform_label(platform: &str) -> &str { "rpm" => "Linux · .rpm", "arch" => "Linux · Arch", "aur" => "Linux · AUR", - "source" => "Собрано из исходников", + "other" => "Другая установка", "appimage" => "Linux · AppImage", "flatpak" => "Linux · Flatpak", "tarball" => "Linux · .tar.gz", diff --git a/website/server/src/telegram.rs b/website/server/src/telegram.rs index 84f1d63..a0e50f4 100644 --- a/website/server/src/telegram.rs +++ b/website/server/src/telegram.rs @@ -60,6 +60,12 @@ impl Bot { .send() .await; let updates: Value = match got { + // 401: a wrong token; 409: another server listens to this bot. + Ok(r) if !r.status().is_success() => { + eprintln!("telegram: getUpdates {}", r.status()); + tokio::time::sleep(Duration::from_secs(60)).await; + continue; + } Ok(r) => r.json().await.unwrap_or(Value::Null), Err(e) => { eprintln!("telegram: {}", e.without_url());