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
|
|
@ -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>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue