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 <noreply@anthropic.com>
This commit is contained in:
parent
04bd7c08a1
commit
1edbbda368
30 changed files with 284 additions and 44 deletions
|
|
@ -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=<id>&version=<v>&platform=<p>`
|
||||
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
|
||||
|
|
|
|||
|
|
@ -99,6 +99,9 @@ pub struct Release {
|
|||
pub version: String,
|
||||
pub published: String,
|
||||
pub assets: Vec<Asset>,
|
||||
/// 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<Release> {
|
|||
.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<Release> {
|
|||
version,
|
||||
published,
|
||||
assets,
|
||||
page,
|
||||
})
|
||||
}
|
||||
.await;
|
||||
|
|
@ -522,6 +538,60 @@ async fn api_release(State(state): State<Shared>) -> Response {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Launch {
|
||||
install: Option<String>,
|
||||
version: Option<String>,
|
||||
platform: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<Shared>,
|
||||
Query(q): Query<Launch>,
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let token = |s: &Option<String>, 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::<Vec<_>>(),
|
||||
}))
|
||||
.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<Shared>,
|
||||
|
|
@ -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<Shared>, headers: HeaderMap) -> Response {
|
|||
));
|
||||
}
|
||||
android.push_str("</table></section>");
|
||||
|
||||
// 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!(
|
||||
"<section class=wide><h2>Установки — запускались (проверка обновлений)</h2><table><tr><th>Платформа</th><th class=num>Сегодня</th><th class=num>7 дней</th><th class=num>30 дней</th><th class=num>Всего</th><th class=num>Новые за 7 дней</th></tr>"
|
||||
);
|
||||
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!("<td class=\"num{}\">{n}</td>", if strong { " big" } else { "" }))
|
||||
.concat();
|
||||
launches.push_str(&format!("<tr><td>{}</td>{cells}</tr>", esc(label)));
|
||||
};
|
||||
row("Все платформы", None, true);
|
||||
for (p, _) in &platforms {
|
||||
row(platform_label(p), Some(p), false);
|
||||
}
|
||||
launches.push_str("</table>");
|
||||
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("<p class=muted>Версии за 7 дней: ");
|
||||
launches.push_str(
|
||||
&versions
|
||||
.iter()
|
||||
.map(|(v, n)| format!("{} — {n}", esc(v)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" · "),
|
||||
);
|
||||
launches.push_str("</p>");
|
||||
}
|
||||
launches.push_str("<p class=muted>Каждая установка — случайный номер, который программа придумала сама; её считают раз в день, когда она проверяет обновления (кто выключил проверку, не учитывается). Локальная сеть не считается.</p></section>");
|
||||
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)}}</style></head><body><main>
|
||||
<h1>ChessPenguin · статистика</h1>
|
||||
{summary}{excluded}{android}{chart}
|
||||
{summary}{excluded}{launches}{android}{chart}
|
||||
<div class=grid>{}{}{}{}{}{}{}</div>{recent}
|
||||
<p class=muted>Считаются только люди: боты, ваши визиты (браузер, открывший эту страницу) и локальная сеть отсеиваются. Посетители считаются по странице, выполнившей JavaScript. IP не хранится.
|
||||
<a href="/stats.csv">Скачивания в CSV</a> · <a href="/stats.csv?t=visits">Просмотры в CSV</a> · Геолокация по IP: <a href="https://db-ip.com">DB-IP</a></p>
|
||||
|
|
|
|||
|
|
@ -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.",
|
||||
|
|
|
|||
|
|
@ -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.",
|
||||
|
|
|
|||
|
|
@ -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í.",
|
||||
|
|
|
|||
|
|
@ -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.",
|
||||
|
|
|
|||
|
|
@ -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.",
|
||||
|
|
|
|||
|
|
@ -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": "Сіз іздеген бет немесе файл бұл жерде жоқ.",
|
||||
|
|
|
|||
|
|
@ -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.",
|
||||
|
|
|
|||
|
|
@ -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": "Страницы или файла, который вы искали, здесь нет.",
|
||||
|
|
|
|||
|
|
@ -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.",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue