Site: downloads go straight to the file; Android in the stats
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

A phone with the GitHub app asks to open github.com links in it; the server now asks
GitHub where the release file is and sends the browser there (the usual link when
GitHub does not answer). Stats: the Android share in the summary, both builds with the
downloads left out of the counts, readable names of the files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-22 21:00:07 +03:00
parent b05c4988d8
commit ba00887cc2

View file

@ -107,6 +107,8 @@ struct AppState {
db: Mutex<rusqlite::Connection>,
geoip: Vec<maxminddb::Reader<Vec<u8>>>,
http: reqwest::Client,
/// The same without following redirects: to learn where GitHub sends a file.
direct: reqwest::Client,
release: tokio::sync::Mutex<Option<(Instant, Release)>>,
/// The visitor-key salt and the local day it belongs to.
salt: Mutex<(String, u64)>,
@ -183,6 +185,12 @@ async fn main() {
.timeout(Duration::from_secs(15))
.build()
.expect("http client"),
direct: reqwest::Client::builder()
.user_agent("chesspenguin-site")
.timeout(Duration::from_secs(5))
.redirect(reqwest::redirect::Policy::none())
.build()
.expect("http client"),
release: tokio::sync::Mutex::new(None),
salt: Mutex::new((String::new(), 0)),
});
@ -514,7 +522,7 @@ async fn api_release(State(state): State<Shared>) -> Response {
}
}
/// Counts the download and sends the browser to the file on GitHub.
/// Counts the download and sends the browser to the file on GitHub (see [`file_url`]).
async fn download(
State(state): State<Shared>,
Path(platform): Path<String>,
@ -578,7 +586,22 @@ async fn download(
],
);
}
Redirect::to(&asset.url).into_response()
Redirect::to(&file_url(&state, &asset.url).await).into_response()
}
/// Where GitHub keeps the file of a release download link. A phone with the GitHub app
/// opens github.com links in the app (and the browser asks first), so the visitor is
/// sent straight to the file; when GitHub does not answer, to the usual link.
async fn file_url(state: &AppState, url: &str) -> String {
let location = async {
let resp = state.direct.head(url).send().await.ok()?;
if !resp.status().is_redirection() {
return None;
}
let to = resp.headers().get(header::LOCATION)?.to_str().ok()?;
to.starts_with("https://").then(|| to.to_string())
};
location.await.unwrap_or_else(|| url.to_string())
}
fn client_ip(config: &Config, peer: SocketAddr, headers: &HeaderMap) -> IpAddr {
@ -672,6 +695,24 @@ fn esc(s: &str) -> String {
.replace('"', "&quot;")
}
/// The name of a download on the stats page.
fn platform_label(platform: &str) -> &str {
match platform {
"windows" => "Windows",
"macos" => "macOS",
"deb" => "Linux · .deb",
"rpm" => "Linux · .rpm",
"arch" => "Linux · Arch",
"appimage" => "Linux · AppImage",
"flatpak" => "Linux · Flatpak",
"tarball" => "Linux · .tar.gz",
"android" => "Android · Stockfish внутри",
"android-noengine" => "Android · без Stockfish",
"checksums" => "Контрольные суммы",
other => other,
}
}
/// A ranked list with bars.
fn table(title: &str, rows: &[(String, i64)]) -> String {
let max = rows.iter().map(|r| r.1).max().unwrap_or(1).max(1);
@ -724,6 +765,7 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
("Скачали", "посетители, которые после этого что-то скачали", vec![]),
("Конверсия", "скачали / посетители", vec![]),
("Скачивания", "все скачивания людьми, включая прямые ссылки и повторы", vec![]),
("из них Android", "обе сборки APK", vec![]),
];
for (_, cond) in PERIODS {
let visitors = number(
@ -750,6 +792,11 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
rows[1].2.push(converted.to_string());
rows[2].2.push(rate);
rows[3].2.push(downloads.to_string());
let android = number(
&db,
&format!("SELECT COUNT(*) {HUMAN_DL} AND platform LIKE 'android%' AND {cond}"),
);
rows[4].2.push(android.to_string());
}
for (name, hint, cells) in &rows {
summary.push_str(&format!(
@ -824,7 +871,44 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
}
chart.push_str("</div></section>");
let by_platform = pairs(&db, &format!("SELECT platform, COUNT(*) {HUMAN_DL} GROUP BY 1 ORDER BY 2 DESC"));
let by_platform: Vec<(String, i64)> =
pairs(&db, &format!("SELECT platform, COUNT(*) {HUMAN_DL} GROUP BY 1 ORDER BY 2 DESC"))
.into_iter()
.map(|(p, n)| (platform_label(&p).to_string(), n))
.collect();
// Android: both builds, with the downloads left out of the counts (the owner's own
// tests from home show here too).
let mut android = String::from(
"<section class=wide><h2>Android</h2><table><tr><th>Сборка</th><th class=num>Люди</th><th class=num>7 дней</th><th class=num>Все, с отсеянными</th><th>Последнее (UTC)</th></tr>",
);
for platform in ["android", "android-noengine"] {
let count = |cond: &str| {
number(
&db,
&format!("SELECT COUNT(*) {HUMAN_DL} AND platform = '{platform}' AND {cond}"),
)
};
let all = number(
&db,
&format!("SELECT COUNT(*) FROM downloads WHERE platform = '{platform}'"),
);
let last: String = db
.query_row(
"SELECT ts FROM downloads WHERE platform = ?1 ORDER BY id DESC LIMIT 1",
[platform],
|r| r.get(0),
)
.unwrap_or_else(|_| "—".into());
android.push_str(&format!(
"<tr><td>{}</td><td class=\"num big\">{}</td><td class=num>{}</td><td class=num>{all}</td><td>{}</td></tr>",
platform_label(platform),
count("1"),
count(PERIODS[1].1),
esc(&last.replace('T', " ").replace('Z', "")),
));
}
android.push_str("</table></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(
@ -875,7 +959,7 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
recent.push_str(&format!(
"<tr{class}><td>{}</td><td>{}</td><td>{}</td><td>{place}</td><td>{}</td><td>{}</td><td title=\"{}\">{who}</td></tr>",
esc(&row[0].replace('T', " ").replace('Z', "")),
esc(&row[1]),
esc(platform_label(&row[1])),
esc(&row[2]),
esc(&row[6]),
esc(&row[7]),
@ -906,7 +990,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}{chart}
{summary}{excluded}{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>