chessbaseLinux/website/server/src/main.rs

1677 lines
64 KiB
Rust
Raw Normal View History

//! The ChessPenguin website: serves the static page, answers "which release is the
//! latest" from the GitHub API (cached), counts downloads and redirects them to the
//! release files on GitHub (the visitor stays on the site), counts page views, and
//! shows the statistics behind a password.
//!
//! Nothing personal is stored: a row keeps its time, the country/region/city looked up
//! from the IP (DB-IP Lite), the browser language and user agent, and a visitor key —
//! a hash of IP and user agent with a random salt that lives only in memory and changes
//! every day, so visitors can be told apart within a day but the IP cannot be recovered.
//! Each row is classified: `human`, `bot`, `owner` (the browser that opened /stats) or
//! `local` (the local network); the statistics count only `human`.
mod site;
mod telegram;
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use axum::extract::{ConnectInfo, Path, Query, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{Html, IntoResponse, Redirect, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use base64::Engine as _;
use serde::Serialize;
use tower_http::services::ServeDir;
/// Downloadable files, by the platform names used in `/download/<platform>`.
pub const PLATFORMS: &[(&str, &str)] = &[
("windows", "-windows-x86_64.zip"),
("macos", "-macos-arm64.dmg"),
("deb", "_amd64.deb"),
("rpm", ".x86_64.rpm"),
("arch", ".pkg.tar.zst"),
("appimage", ".AppImage"),
("flatpak", ".flatpak"),
("tarball", "-linux-x86_64.tar.gz"),
// Android: Stockfish built in, and Stockfish downloaded in the app.
("android", "-android.apk"),
("android-noengine", "-android-noengine.apk"),
("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,
static_dir: PathBuf,
site_dir: PathBuf,
/// Public address of the site (canonical links, sitemap, Open Graph).
site_url: String,
db_path: PathBuf,
/// Geolocation databases (MaxMind DB format): DB-IP Lite City, either the official
/// file or the IPv4/IPv6 pair of ip-location-db; comma-separated.
geoip_paths: Vec<PathBuf>,
/// The network owner (ASN) database: DB-IP Lite ASN, to tell the big clouds apart.
asn_path: PathBuf,
repo: String,
stats_user: String,
stats_password: String,
/// Take the client address from `X-Forwarded-For` / `X-Real-IP` (behind nginx).
trust_proxy: bool,
}
impl Config {
fn from_env() -> Config {
let var = |k: &str, d: &str| std::env::var(k).unwrap_or_else(|_| d.to_string());
Config {
port: var("PORT", "8080").parse().unwrap_or(8080),
static_dir: var("STATIC_DIR", "static").into(),
site_dir: var("SITE_DIR", "site").into(),
site_url: var("SITE_URL", "http://localhost:8080"),
db_path: var("DB_PATH", "data/downloads.sqlite").into(),
asn_path: var("ASN_DB", "data/dbip-asn.mmdb").into(),
geoip_paths: var(
"GEOIP_DB",
"data/dbip-city-ipv4.mmdb,data/dbip-city-ipv6.mmdb",
)
.split(',')
.map(|s| PathBuf::from(s.trim()))
.filter(|p| !p.as_os_str().is_empty())
.collect(),
repo: var("GITHUB_REPO", "vrubelroman/chessPenguin"),
stats_user: var("STATS_USER", "admin"),
stats_password: var("STATS_PASSWORD", ""),
trust_proxy: var("TRUST_PROXY", "1") != "0",
}
}
}
#[derive(Clone, Serialize)]
pub struct Asset {
pub platform: &'static str,
pub name: String,
pub size: u64,
#[serde(skip)]
url: String,
}
#[derive(Clone, Serialize)]
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 {
config: Config,
site: site::Site,
db: Mutex<rusqlite::Connection>,
geoip: Vec<maxminddb::Reader<Vec<u8>>>,
asn: Option<maxminddb::Reader<Vec<u8>>>,
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<Option<(Instant, Release)>>,
/// 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<String, u32>)>,
/// The owner's Telegram bot (notices and `/stat`), when configured.
bot: Option<Arc<telegram::Bot>>,
/// The visitor-key salt and the local day it belongs to.
salt: Mutex<(String, u64)>,
}
type Shared = Arc<AppState>;
#[tokio::main]
async fn main() {
let config = Config::from_env();
if let Some(dir) = config.db_path.parent() {
let _ = std::fs::create_dir_all(dir);
}
let db = rusqlite::Connection::open(&config.db_path).expect("open the database");
db.execute_batch(
"PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS downloads (
id INTEGER PRIMARY KEY,
ts TEXT NOT NULL, -- UTC, RFC 3339
platform TEXT NOT NULL,
version TEXT NOT NULL,
asset TEXT NOT NULL,
country TEXT, -- ISO 3166-1 alpha-2
region TEXT,
city TEXT,
lang TEXT, -- first browser language
referrer TEXT -- host of the referring page
);
CREATE INDEX IF NOT EXISTS downloads_ts ON downloads (ts);
CREATE TABLE IF NOT EXISTS pageviews (
id INTEGER PRIMARY KEY,
ts TEXT NOT NULL, -- UTC, RFC 3339
page TEXT NOT NULL, -- page language
country TEXT,
region TEXT,
city TEXT,
lang TEXT,
referrer TEXT, -- host of the page the visitor came from
visitor TEXT NOT NULL,
kind TEXT NOT NULL,
ua TEXT
);
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)
);
-- Installations in the order they first ran: their number (\"installation 12\").
CREATE TABLE IF NOT EXISTS installs (
n INTEGER PRIMARY KEY AUTOINCREMENT,
install TEXT NOT NULL UNIQUE,
first TEXT NOT NULL -- UTC, RFC 3339
);",
)
.expect("create the tables");
migrate(&db);
mark_repeats(&db);
let geoip: Vec<_> = config
.geoip_paths
.iter()
.filter_map(|p| match maxminddb::Reader::open_readfile(p) {
Ok(r) => Some(r),
Err(e) => {
eprintln!("geolocation database {} not used: {e}", p.display());
None
}
})
.collect();
if geoip.is_empty() {
eprintln!("geolocation off: downloads are stored without a country");
}
let asn = match maxminddb::Reader::open_readfile(&config.asn_path) {
Ok(r) => Some(r),
Err(e) => {
eprintln!(
"network database {} not used: {e}; clouds are not told apart",
config.asn_path.display()
);
None
}
};
if config.stats_password.is_empty() {
eprintln!("STATS_PASSWORD is empty: /stats is disabled");
}
let port = config.port;
let static_dir = config.static_dir.clone();
let site = site::Site::load(&config.site_dir, config.site_url.clone());
let state: Shared = Arc::new(AppState {
site,
config,
db: Mutex::new(db),
geoip,
asn,
http: reqwest::Client::builder()
.user_agent("chesspenguin-site")
.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),
asking: tokio::sync::Mutex::new(()),
new_installs: Mutex::new((String::new(), HashMap::new())),
bot: telegram::Bot::from_env(),
salt: Mutex::new((String::new(), 0)),
});
if let Some(bot) = state.bot.clone() {
let st = state.clone();
tokio::spawn(bot.listen(move |command| match command {
"/stat" => Some(stat_text(&st)),
"/start" | "/help" => Some(
"Здесь появляются скачивания с сайта и запуски программ.\n/stat — статистика за сегодня и за всё время."
.to_owned(),
),
_ => None,
}));
}
let mut app = Router::new()
.route("/", get(home))
.route("/robots.txt", get(robots))
.route("/sitemap.xml", get(sitemap));
for (code, _, _) in site::LANGS.iter().skip(1) {
let code: &'static str = code;
app = app
.route(
&format!("/{code}/"),
get(move |s: State<Shared>| async move { page(s, code).await }),
)
.route(
&format!("/{code}"),
get(move || async move { Redirect::permanent(&format!("/{code}/")) }),
);
}
let not_found = {
let state = state.clone();
move || async move { (StatusCode::NOT_FOUND, Html(state.site.not_found("en"))) }
};
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))
.route("/stats.csv", get(stats_csv))
.route("/healthz", get(|| async { "ok" }))
.fallback_service(
// Precompressed copies (`.br`, `.gz`) next to a file go to the browsers that
// take them: the web version's program (/app/) is 23 MB, 6 MB in Brotli.
ServeDir::new(static_dir)
.precompressed_br()
.precompressed_gzip()
.fallback(get(not_found)),
)
.with_state(state);
let listener = tokio::net::TcpListener::bind(("0.0.0.0", port))
.await
.expect("bind");
println!("listening on :{port}");
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await
.expect("serve");
}
/// Adds the visitor key and class columns to a database from before them and
/// classifies those old downloads after the fact: no browser language → bot; three or
/// more files in the same minute from the same place → bot; from the local network →
/// local.
fn migrate(db: &rusqlite::Connection) {
if db.prepare("SELECT kind FROM downloads LIMIT 0").is_ok() {
return;
}
if let Err(e) = db.execute_batch(
"BEGIN;
ALTER TABLE downloads ADD COLUMN visitor TEXT;
ALTER TABLE downloads ADD COLUMN kind TEXT NOT NULL DEFAULT 'human';
ALTER TABLE downloads ADD COLUMN ua TEXT;
UPDATE downloads SET kind = 'local'
WHERE referrer LIKE '192.168.%' OR referrer LIKE '10.%' OR referrer LIKE 'localhost%';
UPDATE downloads SET kind = 'bot' WHERE kind = 'human' AND COALESCE(lang, '') = '';
UPDATE downloads SET kind = 'bot' WHERE kind = 'human' AND substr(ts, 1, 16) || COALESCE(city, '') IN (
SELECT substr(ts, 1, 16) || COALESCE(city, '') FROM downloads
GROUP BY 1 HAVING COUNT(DISTINCT platform) >= 3);
COMMIT;",
) {
eprintln!("database migration failed: {e}");
}
}
/// A file downloaded again the same day by the same visitor (a download manager or
/// browser asking again, a button pressed twice) is one download: the later rows are
/// `repeat`, out of the counts, as they are out of the notices. Runs at every start, for
/// the rows from before this rule (15 requests for one APK in a minute, 2026-10-29).
fn mark_repeats(db: &rusqlite::Connection) {
if let Err(e) = db.execute(
"UPDATE downloads SET kind = 'repeat'
WHERE kind = 'human' AND visitor IS NOT NULL AND id NOT IN (
SELECT MIN(id) FROM downloads WHERE kind = 'human' AND visitor IS NOT NULL
GROUP BY visitor, platform, date(ts, 'localtime'))",
[],
) {
eprintln!("marking repeated downloads failed: {e}");
}
}
/// What is known about the visitor of a request.
struct Client {
country: Option<String>,
region: Option<String>,
city: Option<String>,
lang: Option<String>,
ua: String,
visitor: String,
kind: &'static str,
}
/// User agents of crawlers, link previews, scanners and scripts (lowercase).
const BOT_MARKS: &[&str] = &[
"bot",
"crawl",
"spider",
"slurp",
"preview",
"fetch",
"scan",
"curl",
"wget",
"python",
"go-http",
"java/",
"okhttp",
"libwww",
"httpclient",
"headless",
"phantom",
"selenium",
"puppeteer",
"playwright",
"facebookexternalhit",
"whatsapp",
"telegram",
"discord",
"slack",
"embedly",
"axios",
"aiohttp",
"httpx",
"postman",
"monitor",
"lighthouse",
"pingdom",
"uptime",
"validator",
"archive",
];
fn is_local(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => v4.is_private() || v4.is_loopback() || v4.is_link_local(),
IpAddr::V6(v6) => {
v6.is_loopback()
|| (v6.segments()[0] & 0xfe00) == 0xfc00
|| (v6.segments()[0] & 0xffc0) == 0xfe80
|| v6
.to_ipv4_mapped()
.is_some_and(|v4| is_local(IpAddr::V4(v4)))
}
}
}
/// Real browsers send `Mozilla/5.0 …` and a language; crawlers often do not.
fn looks_like_bot(ua: &str, lang: Option<&str>) -> bool {
let lower = ua.to_lowercase();
lang.is_none() || !lower.starts_with("mozilla/") || BOT_MARKS.iter().any(|m| lower.contains(m))
}
fn client(state: &AppState, peer: SocketAddr, headers: &HeaderMap) -> Client {
let ip = client_ip(&state.config, peer, headers);
let (country, region, city) = locate(state, ip);
let text = |h| {
headers
.get(h)
.and_then(|v: &HeaderValue| v.to_str().ok())
.unwrap_or("")
};
let lang = text(header::ACCEPT_LANGUAGE)
.split([',', ';'])
.next()
.map(|s| s.trim().chars().take(16).collect::<String>())
.filter(|s| !s.is_empty());
let ua: String = text(header::USER_AGENT).chars().take(200).collect();
let owner = text(header::COOKIE)
.split(';')
.any(|c| c.trim() == "cp_owner=1");
let kind = if owner {
"owner"
} else if is_local(ip) {
"local"
} else if looks_like_bot(&ua, lang.as_deref()) || in_cloud(state, ip) {
"bot"
} else {
"human"
};
Client {
country,
region,
city,
lang,
visitor: visitor_key(state, ip, &ua),
ua,
kind,
}
}
/// A key that is the same for one IP and browser during one local day.
fn visitor_key(state: &AppState, ip: IpAddr, ua: &str) -> String {
use std::hash::{Hash, Hasher};
let today = chrono::Local::now().format("%Y-%m-%d").to_string();
let salt = {
let mut s = state.salt.lock().unwrap_or_else(|e| e.into_inner());
if s.0 != today {
*s = (today, random_u64());
}
s.1
};
let mut h = std::collections::hash_map::DefaultHasher::new();
salt.hash(&mut h);
ip.hash(&mut h);
ua.hash(&mut h);
format!("{:016x}", h.finish())
}
fn random_u64() -> u64 {
use std::io::Read;
let mut b = [0u8; 8];
match std::fs::File::open("/dev/urandom").and_then(|mut f| f.read_exact(&mut b)) {
Ok(()) => u64::from_le_bytes(b),
// Not expected on Linux; still differs between runs.
Err(_) => std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos() as u64,
}
}
fn now_utc() -> String {
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
fn ago_utc(minutes: i64) -> String {
(chrono::Utc::now() - chrono::Duration::minutes(minutes))
.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
/// `POST /hit`: the page reports that it was shown. site.js sends it, so only visitors
/// that run JavaScript are counted: nearly all people and few crawlers.
async fn hit(
State(state): State<Shared>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
body: String,
) -> StatusCode {
let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
let page = v["p"].as_str().unwrap_or("/").trim_matches('/');
let page = if page.is_empty() { "en" } else { page };
if !state.site.has_lang(page) {
return StatusCode::NO_CONTENT;
}
// Where the visitor came from; moving between our own pages is not a source.
let own = state.site.url.split('/').nth(2).unwrap_or("");
let host = headers
.get(header::HOST)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let referrer = v["r"]
.as_str()
.and_then(|r| r.split('/').nth(2))
.filter(|h| !h.is_empty() && *h != own && *h != host)
.map(|h| h.chars().take(64).collect::<String>());
let c = client(&state, peer, &headers);
if let Ok(db) = state.db.lock() {
let _ = db.execute(
"INSERT INTO pageviews (ts, page, country, region, city, lang, referrer, visitor, kind, ua)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
rusqlite::params![
now_utc(),
page,
c.country,
c.region,
c.city,
c.lang,
referrer,
c.visitor,
c.kind,
c.ua
],
);
}
StatusCode::NO_CONTENT
}
/// `/`: English, or `?lang=xx` → `/xx/`.
async fn home(state: State<Shared>, Query(q): Query<HashMap<String, String>>) -> Response {
if let Some(lang) = q.get("lang")
&& lang != "en"
&& state.site.has_lang(lang)
{
return Redirect::permanent(&format!("/{lang}/")).into_response();
}
page(state, "en").await
}
async fn page(State(state): State<Shared>, lang: &'static str) -> Response {
let release = latest(&state).await;
let mut resp = Html(state.site.page(lang, release.as_ref())).into_response();
resp.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=300"),
);
resp
}
async fn robots(State(state): State<Shared>) -> String {
format!(
"User-agent: *\nDisallow: /stats\nDisallow: /download/\nSitemap: {}/sitemap.xml\n",
state.site.url
)
}
async fn sitemap(State(state): State<Shared>) -> Response {
(
[(header::CONTENT_TYPE, "application/xml; charset=utf-8")],
state.site.sitemap(),
)
.into_response()
}
/// The latest release, from the cache or GitHub; the last good answer is kept when
/// GitHub fails.
async fn latest(state: &Shared) -> Option<Release> {
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
);
let fetched = async {
let v: serde_json::Value = state
.http
.get(&url)
.header("Accept", "application/vnd.github+json")
.send()
.await
.ok()?
.error_for_status()
.ok()?
.json()
.await
.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("");
if let Some((platform, _)) = PLATFORMS.iter().find(|(_, end)| name.ends_with(end)) {
assets.push(Asset {
platform,
name: name.to_string(),
size: a["size"].as_u64().unwrap_or(0),
url: a["browser_download_url"].as_str()?.to_string(),
});
}
}
Some(Release {
version,
published,
assets,
page,
})
}
.await;
let mut cache = state.release.lock().await;
match fetched {
Some(r) => {
*cache = Some((Instant::now() + RELEASE_TTL, r.clone()));
Some(r)
}
None => {
if let Some((until, _)) = cache.as_mut() {
*until = Instant::now() + RELEASE_RETRY;
}
cache.as_ref().map(|(_, r)| r.clone())
}
}
}
async fn api_release(State(state): State<Shared>) -> Response {
match latest(&state).await {
Some(r) => {
let mut resp = Json(r).into_response();
resp.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=300"),
);
resp
}
None => (
StatusCode::SERVICE_UNAVAILABLE,
"release information unavailable",
)
.into_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)
};
// 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);
// Neither the local network nor a cloud: a program a scanner runs is no user.
if !is_local(ip) && !in_cloud(&state, ip) {
let (country, region, city) = 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<i64> = 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<String> = db
.query_row(
"SELECT version FROM launches WHERE install = ?1 ORDER BY day DESC LIMIT 1",
[&install],
|r| r.get(0),
)
.ok();
let today: bool = db
.query_row(
"SELECT 1 FROM launches WHERE day = ?1 AND install = ?2",
[&day, &install],
|_| Ok(true),
)
.unwrap_or(false);
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],
);
let n = match known {
Some(n) => n,
None => {
db.execute(
"INSERT INTO installs (install, first) VALUES (?1, ?2)",
[&install, &now_utc()],
)
.ok()?;
db.last_insert_rowid()
}
};
let label = platform_label(&platform);
// The city is not kept (the table has the country), only shown here.
let place = telegram::place(country.as_deref(), region.as_deref(), city.as_deref());
let place = if place.is_empty() {
String::new()
} else {
format!("\n{place}")
};
match before {
_ if known.is_none() => Some(format!(
"🆕 Новая установка №{n}\n{label} · {version}{place}"
)),
Some(old) if old != version => Some(format!(
"⬆️ Обновилась установка №{n}\n{label} · {old} → {version}{place}"
)),
_ if !today => Some(format!(
"▶️ Запуск · установка №{n}\n{label} · {version}{place}"
)),
_ => None,
}
});
if let (Some(bot), Some(text)) = (&state.bot, notice) {
bot.send(text);
}
}
}
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>,
Path(platform): Path<String>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
) -> Response {
if !PLATFORMS.iter().any(|(p, _)| *p == platform) {
return (StatusCode::NOT_FOUND, Html(state.site.not_found("en"))).into_response();
}
// Without the release data the visitor still gets the files, from GitHub's page.
let fallback = format!("https://github.com/{}/releases/latest", state.config.repo);
let Some(release) = latest(&state).await else {
return Redirect::to(&fallback).into_response();
};
let Some(asset) = release.assets.iter().find(|a| a.platform == platform) else {
return Redirect::to(&fallback).into_response();
};
let c = client(&state, peer, &headers);
let referrer = headers
.get(header::REFERER)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.split('/').nth(2))
.map(|s| s.chars().take(64).collect::<String>());
let mut notice = None;
if let Ok(db) = state.db.lock() {
let mut kind = c.kind;
// A crawler following every download link: three or more different files from
// one visitor within ten minutes. Its earlier downloads are reclassified too.
if kind == "human" && asset.platform != "checksums" {
let others: i64 = db
.query_row(
"SELECT COUNT(DISTINCT platform) FROM downloads
WHERE visitor = ?1 AND platform NOT IN ('checksums', ?2) AND ts >= ?3",
rusqlite::params![c.visitor, asset.platform, ago_utc(10)],
|r| r.get(0),
)
.unwrap_or(0);
if others >= 2 {
kind = "bot";
let _ = db.execute(
"UPDATE downloads SET kind = 'bot' WHERE visitor = ?1 AND ts >= ?2 AND kind = 'human'",
rusqlite::params![c.visitor, ago_utc(10)],
);
}
}
// The same file again today from the same visitor: counted once (see `mark_repeats`).
let again: bool = db
.query_row(
"SELECT COUNT(*) > 0 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" && again {
kind = "repeat";
}
let _ = db.execute(
"INSERT INTO downloads (ts, platform, version, asset, country, region, city, lang, referrer, visitor, kind, ua)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
rusqlite::params![
now_utc(),
asset.platform,
release.version,
asset.name,
c.country,
c.region,
c.city,
c.lang,
referrer,
c.visitor,
kind,
c.ua
],
);
// 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).
if kind == "human" && asset.platform != "checksums" {
let place =
telegram::place(c.country.as_deref(), c.region.as_deref(), c.city.as_deref());
let from = referrer
.as_deref()
.map(|r| format!(" · с {r}"))
.unwrap_or_default();
let line = [place, from.trim_start_matches(" · ").to_owned()]
.into_iter()
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join(" · ");
let line = if line.is_empty() {
String::new()
} else {
format!("\n{line}")
};
notice = Some(format!(
"⬇️ Скачали {} · {}{line}",
platform_label(asset.platform),
release.version
));
}
}
if let (Some(bot), Some(text)) = (&state.bot, notice) {
bot.send(text);
}
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 {
if config.trust_proxy {
let forwarded = headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.split(',').next())
.or_else(|| headers.get("x-real-ip").and_then(|v| v.to_str().ok()))
.and_then(|s| s.trim().parse().ok());
if let Some(ip) = forwarded {
return ip;
}
}
peer.ip()
}
/// Country code, region and city of an address (all `None` without a database). Reads
/// both the GeoIP2-style records of the official DB-IP file (`country.iso_code`,
/// `subdivisions[0].names.en`, `city.names.en`) and the flat ones of ip-location-db
/// (`country_code`, `state1`, `city`).
/// The big clouds (their networks, ASN): an address in them is a machine — a security
/// scanner running a new program (Microsoft's, in Cheyenne), a crawler — not a person.
/// Small hostings are not here: people's VPNs run on them.
const CLOUDS: &[u32] = &[
8075, 8068, 8069, 8070, 8071, 8072, 8073, 8074, 12076, // Microsoft (Azure)
16509, 14618, 8987, // Amazon (AWS)
15169, 396982, 19527, 36040, 36492, 43515, // Google (Cloud)
31898, 792, // Oracle
45102, 37963, 24429, // Alibaba
132203, 45090, // Tencent
36351, // IBM (SoftLayer)
];
/// The address is in a big cloud (see [`CLOUDS`]).
fn in_cloud(state: &AppState, ip: IpAddr) -> bool {
let Some(reader) = &state.asn else {
return false;
};
reader
.lookup(ip)
.ok()
.and_then(|r| r.decode::<serde_json::Value>().ok().flatten())
.and_then(|r| r["autonomous_system_number"].as_u64())
.is_some_and(|n| CLOUDS.contains(&(n as u32)))
}
fn locate(state: &AppState, ip: IpAddr) -> (Option<String>, Option<String>, Option<String>) {
let record = state.geoip.iter().find_map(|reader| {
reader
.lookup(ip)
.ok()?
.decode::<serde_json::Value>()
.ok()
.flatten()
});
let Some(r) = record else {
return (None, None, None);
};
let text = |v: &serde_json::Value| v.as_str().filter(|s| !s.is_empty()).map(str::to_string);
let country = text(&r["country_code"]).or_else(|| text(&r["country"]["iso_code"]));
let region = text(&r["state1"]).or_else(|| text(&r["subdivisions"][0]["names"]["en"]));
let city = text(&r["city"]).or_else(|| text(&r["city"]["names"]["en"]));
(country, region, city)
}
/// Basic authentication against STATS_USER / STATS_PASSWORD.
fn authorized(config: &Config, headers: &HeaderMap) -> bool {
if config.stats_password.is_empty() {
return false;
}
let Some(value) = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Basic "))
else {
return false;
};
let expected = format!("{}:{}", config.stats_user, config.stats_password);
base64::engine::general_purpose::STANDARD
.decode(value.trim())
.is_ok_and(|d| d == expected.as_bytes())
}
fn ask_password() -> Response {
(
StatusCode::UNAUTHORIZED,
[(
header::WWW_AUTHENTICATE,
"Basic realm=\"ChessPenguin stats\"",
)],
"Password required",
)
.into_response()
}
/// Rows of `SELECT label, count` as pairs.
fn pairs(db: &rusqlite::Connection, sql: &str) -> Vec<(String, i64)> {
let Ok(mut stmt) = db.prepare(sql) else {
return Vec::new();
};
stmt.query_map([], |r| {
Ok((
r.get::<_, Option<String>>(0)?.unwrap_or_else(|| "—".into()),
r.get::<_, i64>(1)?,
))
})
.map(|rows| rows.flatten().collect())
.unwrap_or_default()
}
fn number(db: &rusqlite::Connection, sql: &str) -> i64 {
db.query_row(sql, [], |r| r.get(0)).unwrap_or(0)
}
fn esc(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.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",
"aur" => "Linux · AUR",
"other" => "Другая установка",
"appimage" => "Linux · AppImage",
"flatpak" => "Linux · Flatpak",
"tarball" => "Linux · .tar.gz",
"android" => "Android · Stockfish внутри",
"android-noengine" => "Android · без Stockfish",
"checksums" => "Контрольные суммы",
other => other,
}
}
/// The answer to `/stat`: today and all time, in a few lines.
fn stat_text(state: &AppState) -> String {
let Ok(db) = state.db.lock() else {
return "База статистики недоступна".to_owned();
};
let today_dl = "AND date(ts, 'localtime') = date('now', 'localtime')";
let day = |back: i64| {
(chrono::Local::now() - chrono::Duration::days(back))
.format("%Y-%m-%d")
.to_string()
};
let (d0, d6, d29) = (day(0), day(6), day(29));
let n = |sql: &str| number(&db, sql);
let dl_today = n(&format!("SELECT COUNT(*) {HUMAN_DL} {today_dl}"));
let dl_all = n(&format!("SELECT COUNT(*) {HUMAN_DL}"));
let ran_today = n(&format!("SELECT COUNT(*) FROM launches WHERE day = '{d0}'"));
let new_today = n(
"SELECT COUNT(*) FROM installs WHERE date(first, 'localtime') = date('now', 'localtime')",
);
let installs = n("SELECT COUNT(*) FROM installs");
let week = n(&format!(
"SELECT COUNT(DISTINCT install) FROM launches WHERE day >= '{d6}'"
));
let month = n(&format!(
"SELECT COUNT(DISTINCT install) FROM launches WHERE day >= '{d29}'"
));
let mut out = format!(
"📊 ChessPenguin · {}\n\n\
Сегодня\n\
⬇️ скачали: {dl_today}\n\
▶️ запускались: {ran_today} (новых {new_today})\n\n\
За всё время\n\
⬇️ скачали: {dl_all}\n\
💻 установок: {installs}\n\
активны за 7 дней: {week}, за 30 дней: {month}",
chrono::Local::now().format("%d.%m.%Y"),
);
let rows = |sql: &str| {
let mut stmt = db.prepare(sql).ok()?;
let rows = stmt
.query_map([], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, i64>(1)?,
r.get::<_, i64>(2)?,
))
})
.ok()?
.flatten()
.collect::<Vec<_>>();
Some(rows)
};
if let Some(list) = rows(&format!(
"SELECT platform, COUNT(DISTINCT install), COUNT(DISTINCT CASE WHEN day >= '{d6}' THEN install END)
FROM launches GROUP BY 1 ORDER BY 2 DESC"
))
.filter(|l| !l.is_empty())
{
out.push_str("\n\nУстановки: всего · за 7 дней");
for (p, all, week) in list {
out.push_str(&format!("\n{} — {all} · {week}", platform_label(&p)));
}
}
if let Some(list) = rows(&format!(
"SELECT platform, COUNT(*), SUM(date(ts, 'localtime') = date('now', 'localtime')) {HUMAN_DL} GROUP BY 1 ORDER BY 2 DESC"
))
.filter(|l| !l.is_empty())
{
out.push_str("\n\nСкачивания: всего · сегодня");
for (p, all, today) in list {
out.push_str(&format!("\n{} — {all} · {today}", platform_label(&p)));
}
}
out
}
/// 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);
let mut out = format!("<section><h2>{}</h2><table>", esc(title));
if rows.is_empty() {
out.push_str("<tr><td class=muted>Пока пусто</td></tr>");
}
for (label, n) in rows {
let w = (*n as f64 / max as f64 * 100.0).round();
out.push_str(&format!(
"<tr><td>{}</td><td class=num>{n}</td><td class=bar><span style=\"width:{w}%\"></span></td></tr>",
esc(label)
));
}
out.push_str("</table></section>");
out
}
/// Human downloads of the program (the checksum file is not a download).
const HUMAN_DL: &str = "FROM downloads WHERE kind = 'human' AND platform <> 'checksums'";
const HUMAN_PV: &str = "FROM pageviews WHERE kind = 'human'";
/// A platform's family on the statistics page (its variants are shown under it).
fn family(platform: &str) -> &'static str {
match platform {
"windows" => "Windows",
"macos" => "macOS",
"android" | "android-noengine" => "Android",
"other" => "Другие установки",
_ => "Linux",
}
}
const FAMILIES: [&str; 5] = ["Windows", "macOS", "Linux", "Android", "Другие установки"];
/// `/stats`: people only (crawlers, the owner and the local network are left out), from
/// the main numbers down to the latest events.
async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
if !authorized(&state.config, &headers) {
return ask_password();
}
let Ok(db) = state.db.lock() else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let zone = match std::env::var("TZ").as_deref() {
Ok("Europe/Moscow") => "МСК".to_owned(),
Ok(z) if !z.is_empty() => z.to_owned(),
_ => "UTC".to_owned(),
};
let day = |back: i64| {
(chrono::Local::now() - chrono::Duration::days(back))
.format("%Y-%m-%d")
.to_string()
};
// The periods: their first local day (None: all time). Downloads and visits keep a
// UTC time; installations a local day.
let periods: [(&str, Option<String>); 4] = [
("Сегодня", Some(day(0))),
("7 дней", Some(day(6))),
("30 дней", Some(day(29))),
("Всё время", None),
];
let since_ts = |from: &Option<String>| match from {
Some(d) => format!("date(ts, 'localtime') >= '{d}'"),
None => "1".to_owned(),
};
let since_day = |from: &Option<String>| match from {
Some(d) => format!("day >= '{d}'"),
None => "1".to_owned(),
};
let since_first = |from: &Option<String>| match from {
Some(d) => format!("date(first, 'localtime') >= '{d}'"),
None => "1".to_owned(),
};
// 1. The main numbers.
let mut main_rows: Vec<(&str, &str, Vec<i64>)> = vec![
(
"Посетители сайта",
"открыли страницу; один браузер за день — один посетитель",
vec![],
),
(
"Скачивания",
"файлы программы, скачанные людьми с сайта",
vec![],
),
(
"Новые установки",
"программа запущена впервые (считается с версии 1.0.1)",
vec![],
),
(
"Работающие установки",
"разные установки, запускавшиеся за период",
vec![],
),
];
for (_, from) in &periods {
main_rows[0].2.push(number(
&db,
&format!(
"SELECT COUNT(DISTINCT substr(ts, 1, 10) || visitor) {HUMAN_PV} AND {}",
since_ts(from)
),
));
main_rows[1].2.push(number(
&db,
&format!("SELECT COUNT(*) {HUMAN_DL} AND {}", since_ts(from)),
));
main_rows[2].2.push(number(
&db,
&format!("SELECT COUNT(*) FROM installs WHERE {}", since_first(from)),
));
main_rows[3].2.push(number(
&db,
&format!(
"SELECT COUNT(DISTINCT install) FROM launches WHERE {}",
since_day(from)
),
));
}
let mut main = String::from("<section><table class=summary><tr><th></th>");
for (name, _) in &periods {
main.push_str(&format!("<th class=num>{name}</th>"));
}
main.push_str("</tr>");
for (name, hint, cells) in &main_rows {
main.push_str(&format!(
"<tr><td><b>{name}</b><br><small class=muted>{hint}</small></td>"
));
for n in cells {
main.push_str(&format!("<td class=\"num big\">{n}</td>"));
}
main.push_str("</tr>");
}
main.push_str("</table></section>");
// 2. Thirty days: the site, the programs.
let days: Vec<String> = (0..30).rev().map(day).collect();
let by_day = |sql: String| -> HashMap<String, i64> { pairs(&db, &sql).into_iter().collect() };
let first = &days[0];
let visits = by_day(format!(
"SELECT date(ts, 'localtime'), COUNT(DISTINCT visitor) {HUMAN_PV} AND date(ts, 'localtime') >= '{first}' GROUP BY 1"
));
let downloads = by_day(format!(
"SELECT date(ts, 'localtime'), COUNT(*) {HUMAN_DL} AND date(ts, 'localtime') >= '{first}' GROUP BY 1"
));
let running = by_day(format!(
"SELECT day, COUNT(*) FROM launches WHERE day >= '{first}' GROUP BY 1"
));
let fresh = by_day(format!(
"SELECT date(first, 'localtime'), COUNT(*) FROM installs WHERE date(first, 'localtime') >= '{first}' GROUP BY 1"
));
let chart = |title: &str,
(a, a_name): (&HashMap<String, i64>, &str),
(b, b_name): (&HashMap<String, i64>, &str)| {
let get = |m: &HashMap<String, i64>, d: &str| m.get(d).copied().unwrap_or(0);
let max = days
.iter()
.map(|d| get(a, d).max(get(b, d)))
.max()
.unwrap_or(0)
.max(1);
let (sa, sb) = (
days.iter().map(|d| get(a, d)).sum::<i64>(),
days.iter().map(|d| get(b, d)).sum::<i64>(),
);
let mut out = format!(
"<section><h2>{title} · 30 дней <span class=legend><i class=v></i>{a_name} <i class=d></i>{b_name}</span></h2><div class=chart>"
);
for (i, d) in days.iter().enumerate() {
let (x, y) = (get(a, d), get(b, d));
// A day number under every fifth bar and the last: they fit a phone.
let label = if i % 5 == 0 || i + 1 == days.len() {
&d[8..]
} else {
""
};
let h = |n: i64| (n as f64 / max as f64 * 100.0).round();
out.push_str(&format!(
"<div title=\"{d}: {a_name} {x}, {b_name} {y}\"><p><span class=v style=\"height:{}%\"></span><span class=d style=\"height:{}%\"></span></p><small>{}</small></div>",
h(x),
h(y),
label
));
}
out.push_str(&format!(
"</div><p class=muted>За 30 дней: {a_name} {sa}, {b_name} {sb}. Наведите на столбик — число за день.</p></section>"
));
out
};
let charts = format!(
"<div class=pair>{}{}</div>",
chart("Сайт", (&visits, "посетители"), (&downloads, "скачивания")),
chart(
"Программы",
(&running, "работали"),
(&fresh, "новые установки")
),
);
// 3. Platforms: one row per family, its variants under it.
let d30 = day(29);
let dl_all: HashMap<String, i64> = pairs(
&db,
&format!("SELECT platform, COUNT(*) {HUMAN_DL} GROUP BY 1"),
)
.into_iter()
.collect();
let dl_30: HashMap<String, i64> = pairs(
&db,
&format!(
"SELECT platform, COUNT(*) {HUMAN_DL} AND date(ts, 'localtime') >= '{d30}' GROUP BY 1"
),
)
.into_iter()
.collect();
// An installation's platform: the latest it reported.
let inst_all: HashMap<String, i64> = pairs(
&db,
"SELECT platform, COUNT(*) FROM (SELECT install, platform FROM launches l
WHERE day = (SELECT MAX(day) FROM launches WHERE install = l.install)) GROUP BY 1",
)
.into_iter()
.collect();
let inst_30: HashMap<String, i64> = pairs(
&db,
&format!(
"SELECT platform, COUNT(DISTINCT install) FROM launches WHERE day >= '{d30}' GROUP BY 1"
),
)
.into_iter()
.collect();
let mut platforms: Vec<String> = dl_all.keys().chain(inst_all.keys()).cloned().collect();
platforms.sort();
platforms.dedup();
let mut plat = String::from(
"<section><h2>Платформы</h2><table><tr><th></th><th class=num>Скачивания<br><small>30 дней</small></th><th class=num>Скачивания<br><small>всего</small></th><th class=num>Работали<br><small>30 дней</small></th><th class=num>Установок<br><small>всего</small></th></tr>",
);
let sum = |m: &HashMap<String, i64>, ps: &[&String]| {
ps.iter()
.map(|p| m.get(*p).copied().unwrap_or(0))
.sum::<i64>()
};
for fam in FAMILIES {
let members: Vec<&String> = platforms.iter().filter(|p| family(p) == fam).collect();
if members.is_empty() {
continue;
}
plat.push_str(&format!(
"<tr><td><b>{fam}</b></td><td class=\"num big\">{}</td><td class=num>{}</td><td class=\"num big\">{}</td><td class=num>{}</td></tr>",
sum(&dl_30, &members),
sum(&dl_all, &members),
sum(&inst_30, &members),
sum(&inst_all, &members),
));
if members.len() > 1 || fam == "Linux" || fam == "Android" {
let parts: Vec<String> = members
.iter()
.map(|p| {
let label = platform_label(p);
let short = label.split(" · ").last().unwrap_or(label);
format!(
"{} — {} / {}",
esc(short),
dl_all.get(*p).copied().unwrap_or(0),
inst_all.get(*p).copied().unwrap_or(0)
)
})
.collect();
plat.push_str(&format!(
"<tr class=sub><td colspan=5>{} <span class=muted>(скачиваний / установок, всего)</span></td></tr>",
parts.join(" · ")
));
}
}
plat.push_str("</table></section>");
// 4. Versions that run (30 days), installations of each.
let versions = pairs(
&db,
&format!(
"SELECT version, COUNT(DISTINCT install) FROM launches WHERE day >= '{d30}' GROUP BY 1 ORDER BY 2 DESC LIMIT 10"
),
);
// 5. Where people are and where they came from.
let countries = pairs(
&db,
"SELECT COALESCE(country, '—'), COUNT(*) FROM (
SELECT country FROM downloads WHERE kind = 'human' AND platform <> 'checksums'
UNION ALL SELECT country FROM installs i JOIN launches l ON l.install = i.install
AND l.day = (SELECT MIN(day) FROM launches WHERE install = i.install)
) GROUP BY 1 ORDER BY 2 DESC LIMIT 20",
);
let cities = pairs(
&db,
&format!(
"SELECT COALESCE(country, '—') || COALESCE(' · ' || city, ''), COUNT(*) {HUMAN_DL} GROUP BY 1 ORDER BY 2 DESC LIMIT 20"
),
);
let referrers = pairs(
&db,
&format!(
"SELECT COALESCE(referrer, 'напрямую'), COUNT(DISTINCT substr(ts, 1, 10) || visitor) {HUMAN_PV} GROUP BY 1 ORDER BY 2 DESC LIMIT 15"
),
);
let languages = pairs(
&db,
&format!(
"SELECT page, COUNT(DISTINCT substr(ts, 1, 10) || visitor) {HUMAN_PV} GROUP BY 1 ORDER BY 2 DESC"
),
);
// 6. The latest events: downloads by people and new installations.
let mut events: Vec<(String, String)> = Vec::new();
if let Ok(mut stmt) = db.prepare(&format!(
"SELECT datetime(ts, 'localtime'), platform, version, country, city, referrer {HUMAN_DL} ORDER BY id DESC LIMIT 40"
)) {
let rows = stmt.query_map([], |r| {
(0..6)
.map(|i| r.get::<_, Option<String>>(i).map(|v| v.unwrap_or_default()))
.collect::<Result<Vec<_>, _>>()
});
for r in rows.into_iter().flatten().flatten() {
let place = telegram::place(Some(&r[3]).filter(|s| !s.is_empty()).map(String::as_str), None, Some(&r[4]).filter(|s| !s.is_empty()).map(String::as_str));
let from = if r[5].is_empty() { String::new() } else { format!(" · с {}", esc(&r[5])) };
events.push((
r[0].clone(),
format!("⬇️ Скачали <b>{}</b> {}<span class=muted> · {}{from}</span>", esc(platform_label(&r[1])), esc(&r[2]), esc(&place)),
));
}
}
if let Ok(mut stmt) = db.prepare(
"SELECT datetime(i.first, 'localtime'), i.n, l.platform, l.version, l.country FROM installs i
JOIN launches l ON l.install = i.install AND l.day = (SELECT MIN(day) FROM launches WHERE install = i.install)
ORDER BY i.n DESC LIMIT 40",
) {
let rows = stmt.query_map([], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, i64>(1)?,
r.get::<_, String>(2)?,
r.get::<_, String>(3)?,
r.get::<_, Option<String>>(4)?,
))
});
for (ts, n, p, v, c) in rows.into_iter().flatten().flatten() {
events.push((
ts,
format!(
"🆕 Новая установка №{n} · <b>{}</b> {}<span class=muted> · {}</span>",
esc(platform_label(&p)),
esc(&v),
esc(&telegram::place(c.as_deref(), None, None))
),
));
}
}
events.sort_by(|a, b| b.0.cmp(&a.0));
events.truncate(40);
let mut recent = format!("<section><h2>Последние события ({zone})</h2><table class=recent>");
if events.is_empty() {
recent.push_str("<tr><td class=muted>Пока пусто</td></tr>");
}
for (ts, text) in &events {
recent.push_str(&format!(
"<tr><td class=time>{}</td><td class=wrap>{text}</td></tr>",
esc(&ts[..16.min(ts.len())])
));
}
recent.push_str("</table></section>");
let now = chrono::Local::now().format("%d.%m.%Y %H:%M");
let page = format!(
r#"<!doctype html><html lang=ru><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1">
<meta name=robots content=noindex><title>ChessPenguin · статистика</title><style>
:root{{color-scheme:light dark;--bg:#f6f7f9;--fg:#1b1f24;--muted:#6b7280;--card:#fff;--line:#e5e7eb;--accent:#1f6fa8;--soft:#a9c8e2}}
@media(prefers-color-scheme:dark){{:root{{--bg:#16181b;--fg:#e6e8eb;--muted:#9aa1ab;--card:#1f2226;--line:#2c3036;--accent:#4a9be0;--soft:#2f4b63}}}}
body{{margin:0;font:15px/1.45 system-ui,sans-serif;background:var(--bg);color:var(--fg)}}
main{{max-width:1100px;margin:0 auto;padding:24px 16px}} h1{{font-size:22px;margin:0}} .when{{color:var(--muted);margin:2px 0 16px}}
.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(320px,100%),1fr));gap:16px;margin-top:16px}}
.pair{{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(420px,100%),1fr));gap:16px;margin-top:16px}}
section{{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px;overflow-x:auto}}
main>section{{margin-top:16px}} h2{{font-size:15px;margin:0 0 10px}}
table{{border-collapse:collapse;width:100%}} td,th{{padding:4px 6px;border-bottom:1px solid var(--line);text-align:left;white-space:nowrap}}
th{{font-weight:600}} th small{{font-weight:400;color:var(--muted)}}
.summary td{{padding:10px 8px}} .summary td:first-child{{white-space:normal}} .big{{font-size:22px;font-weight:600}}
tr.sub td{{border-bottom:1px solid var(--line);padding:0 6px 8px 20px;font-size:13px;white-space:normal}}
.grid td:first-child{{max-width:230px;overflow:hidden;text-overflow:ellipsis}} .num{{text-align:right;width:80px}} .bar{{width:40%}} .bar span{{display:block;height:8px;border-radius:4px;background:var(--accent)}}
.recent td.wrap{{white-space:normal;overflow-wrap:anywhere}} .recent td.time{{color:var(--muted);width:130px}}
.muted{{color:var(--muted)}} .chart{{display:flex;gap:3px;height:150px}}
.chart div{{flex:1;min-width:0;display:flex;flex-direction:column;text-align:center}}
.chart p{{flex:1;margin:0;display:flex;align-items:flex-end;justify-content:center;gap:1px}}
.chart p span{{flex:1;max-width:10px;border-radius:2px 2px 0 0;min-height:1px}}
.v{{background:var(--soft)}} .d{{background:var(--accent)}} .chart small{{color:var(--muted);font-size:10px}}
.legend{{font-weight:400;color:var(--muted);margin-left:8px}} .legend i{{display:inline-block;width:10px;height:10px;border-radius:2px;margin:0 4px 0 10px;vertical-align:-1px}}
section p.muted{{margin:8px 0 0;font-size:13px}}
a{{color:var(--accent)}}</style></head><body><main>
<h1>ChessPenguin · статистика</h1><p class=when>{now} {zone} · только живые люди: боты, вы и локальная сеть не считаются</p>
{main}{charts}{plat}
<div class=grid>{}{}{}{}{}</div>{recent}
<p class=muted>Установка — случайный номер, который программа придумала сама; она считается, когда при запуске проверяет обновления (с версии 1.0.1). Посетители — по странице, выполнившей 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>
</main></body></html>"#,
table("Версии в работе (30 дней, установок)", &versions),
table("Страны (скачивания и новые установки)", &countries),
table("Города (скачивания)", &cities),
table("Откуда пришли на сайт", &referrers),
table("Язык страницы сайта", &languages),
);
// Marks this browser as the owner's, so its own visits are left out of the counts.
(
[(
header::SET_COOKIE,
"cp_owner=1; Max-Age=31536000; Path=/; HttpOnly; SameSite=Lax",
)],
Html(page),
)
.into_response()
}
/// `/stats.csv`: every download; `/stats.csv?t=visits`: every page view.
async fn stats_csv(
State(state): State<Shared>,
Query(q): Query<HashMap<String, String>>,
headers: HeaderMap,
) -> Response {
if !authorized(&state.config, &headers) {
return ask_password();
}
let Ok(db) = state.db.lock() else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let (head, sql, name) = if q.get("t").map(String::as_str) == Some("visits") {
(
"time_utc,page,country,region,city,language,referrer,visitor,kind,user_agent",
"SELECT ts, page, country, region, city, lang, referrer, visitor, kind, ua FROM pageviews ORDER BY id",
"chesspenguin-visits.csv",
)
} else {
(
"time_utc,platform,version,asset,country,region,city,language,referrer,visitor,kind,user_agent",
"SELECT ts, platform, version, asset, country, region, city, lang, referrer, visitor, kind, ua FROM downloads ORDER BY id",
"chesspenguin-downloads.csv",
)
};
let columns = head.split(',').count();
let mut out = format!("{head}\n");
if let Ok(mut stmt) = db.prepare(sql) {
let rows = stmt.query_map([], |r| {
(0..columns)
.map(|i| r.get::<_, Option<String>>(i).map(|v| v.unwrap_or_default()))
.collect::<Result<Vec<_>, _>>()
});
for row in rows.into_iter().flatten().flatten() {
let cells: Vec<String> = row
.iter()
.map(|c| format!("\"{}\"", c.replace('"', "\"\"")))
.collect();
out.push_str(&cells.join(","));
out.push('\n');
}
}
(
[
(header::CONTENT_TYPE, "text/csv; charset=utf-8".to_string()),
(
header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{name}\""),
),
],
out,
)
.into_response()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bots_and_local_addresses() {
let chrome = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0 Safari/537.36";
assert!(!looks_like_bot(chrome, Some("ru-RU")));
assert!(looks_like_bot(chrome, None));
assert!(looks_like_bot("curl/8.10", Some("en")));
assert!(looks_like_bot(
"Mozilla/5.0 (compatible; Googlebot/2.1)",
Some("en")
));
assert!(looks_like_bot(
"Mozilla/5.0 HeadlessChrome/141.0",
Some("en")
));
assert!(looks_like_bot("TelegramBot (like TwitterBot)", Some("en")));
for local in [
"192.168.8.20",
"10.0.0.1",
"127.0.0.1",
"::1",
"fd00::1",
"::ffff:192.168.1.2",
] {
assert!(is_local(local.parse().unwrap()), "{local}");
}
for public in ["8.8.8.8", "77.88.8.8", "2a00:1450:4001:830::200e"] {
assert!(!is_local(public.parse().unwrap()), "{public}");
}
}
}