2026-10-19 11:00:10 +03:00
//! 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
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
//! release files on GitHub (the visitor stays on the site), counts page views, and
//! shows the statistics behind a password.
2026-10-19 11:00:10 +03:00
//!
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
//! 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`.
2026-10-19 11:00:10 +03:00
mod site ;
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 } ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
use axum ::routing ::{ get , post } ;
2026-10-19 11:00:10 +03:00
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: design review fixes, icon, signed releases, the site's Android downloads
- The design review (docs/design/android-ui.md §17): the move buttons in the
bottom bar (snackbars above them), ripple on press, larger ◀ ▶, coordinates
over the pieces, readable NAG colors in the light theme, 16 dp edges, the
⋮ menu (game details, copy PGN/FEN, share), "Deeper" next to ▾, TalkBack
states, no "*" for unfinished games, "Found N of M", texts.
- The penguin as the adaptive icon and on the splash screen; dark window.
- Release builds: R8, signing from the environment, androidApp/scripts/release.sh
(two APKs, apksigner and 16 KB alignment checks); the release workflow builds
them from the repository secrets.
- Website: the Android tab with both APKs, "Download for Android" on phones.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 01:57:03 +03:00
// Android: Stockfish built in, and Stockfish downloaded in the app.
( " android " , " -android.apk " ) ,
( " android-noengine " , " -android-noengine.apk " ) ,
2026-10-19 11:00:10 +03:00
( " checksums " , " SHA256SUMS.txt " ) ,
] ;
/// The latest release is asked from GitHub at most this often.
const RELEASE_TTL : Duration = Duration ::from_secs ( 600 ) ;
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 > ,
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 ( ) ,
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 > ,
}
struct AppState {
config : Config ,
site : site ::Site ,
db : Mutex < rusqlite ::Connection > ,
geoip : Vec < maxminddb ::Reader < Vec < u8 > > > ,
http : reqwest ::Client ,
2026-10-22 21:00:07 +03:00
/// The same without following redirects: to learn where GitHub sends a file.
direct : reqwest ::Client ,
2026-10-19 11:00:10 +03:00
release : tokio ::sync ::Mutex < Option < ( Instant , Release ) > > ,
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
/// The visitor-key salt and the local day it belongs to.
salt : Mutex < ( String , u64 ) > ,
2026-10-19 11:00:10 +03:00
}
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
) ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
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 ) ; " ,
2026-10-19 11:00:10 +03:00
)
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
. expect ( " create the tables " ) ;
migrate ( & db ) ;
2026-10-19 11:00:10 +03:00
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 " ) ;
}
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 ,
http : reqwest ::Client ::builder ( )
. user_agent ( " chesspenguin-site " )
. timeout ( Duration ::from_secs ( 15 ) )
. build ( )
. expect ( " http client " ) ,
2026-10-22 21:00:07 +03:00
direct : reqwest ::Client ::builder ( )
. user_agent ( " chesspenguin-site " )
. timeout ( Duration ::from_secs ( 5 ) )
. redirect ( reqwest ::redirect ::Policy ::none ( ) )
. build ( )
. expect ( " http client " ) ,
2026-10-19 11:00:10 +03:00
release : tokio ::sync ::Mutex ::new ( None ) ,
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
salt : Mutex ::new ( ( String ::new ( ) , 0 ) ) ,
2026-10-19 11:00:10 +03:00
} ) ;
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 ( " /download/{platform} " , get ( download ) )
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
. route ( " /hit " , post ( hit ) )
2026-10-19 11:00:10 +03:00
. route ( " /stats " , get ( stats ) )
. route ( " /stats.csv " , get ( stats_csv ) )
. route ( " /healthz " , get ( | | async { " ok " } ) )
. fallback_service ( ServeDir ::new ( static_dir ) . 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 " ) ;
}
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
/// 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.16 8. % ' 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} " ) ;
}
}
/// 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 ( ) ) {
" 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 = [ 0 u8 ; 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
}
2026-10-19 11:00:10 +03:00
/// `/`: 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: * \n Disallow: /stats \n Disallow: /download/ \n Sitemap: {}/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 mut cache = state . release . lock ( ) . await ;
if let Some ( ( at , r ) ) = cache . as_ref ( )
& & at . elapsed ( ) < RELEASE_TTL
{
return Some ( r . clone ( ) ) ;
}
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 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 ,
} )
}
. await ;
match fetched {
Some ( r ) = > {
* cache = Some ( ( Instant ::now ( ) , r . clone ( ) ) ) ;
Some ( r )
}
None = > 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 ( ) ,
}
}
2026-10-22 21:00:07 +03:00
/// Counts the download and sends the browser to the file on GitHub (see [`file_url`]).
2026-10-19 11:00:10 +03:00
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 ( ) ;
} ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
let c = client ( & state , peer , & headers ) ;
2026-10-19 11:00:10 +03:00
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 > ( ) ) ;
if let Ok ( db ) = state . db . lock ( ) {
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
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 ) ] ,
) ;
}
}
2026-10-19 11:00:10 +03:00
let _ = db . execute (
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
" 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 ) " ,
2026-10-19 11:00:10 +03:00
rusqlite ::params! [
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
now_utc ( ) ,
2026-10-19 11:00:10 +03:00
asset . platform ,
release . version ,
asset . name ,
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
c . country ,
c . region ,
c . city ,
c . lang ,
referrer ,
c . visitor ,
kind ,
c . ua
2026-10-19 11:00:10 +03:00
] ,
) ;
}
2026-10-22 21:00:07 +03:00
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 ( ) )
2026-10-19 11:00:10 +03:00
}
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`).
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 ( )
}
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
fn number ( db : & rusqlite ::Connection , sql : & str ) -> i64 {
db . query_row ( sql , [ ] , | r | r . get ( 0 ) ) . unwrap_or ( 0 )
2026-10-19 11:00:10 +03:00
}
fn esc ( s : & str ) -> String {
s . replace ( '&' , " & " )
. replace ( '<' , " < " )
. replace ( '>' , " > " )
. replace ( '"' , " " " )
}
2026-10-22 21:00:07 +03:00
/// 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 ,
}
}
2026-10-19 11:00:10 +03:00
/// 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 ( ) {
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
out . push_str ( " <tr><td class=muted>Пока пусто</td></tr> " ) ;
2026-10-19 11:00:10 +03:00
}
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
}
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
/// SQL conditions for the periods of the summary (`ts` is UTC RFC 3339, the days follow
/// the server's time zone, TZ in the environment).
const PERIODS : & [ ( & str , & str ) ] = & [
( " Сегодня " , " date(ts, 'localtime') = date('now', 'localtime') " ) ,
( " 7 дней " , " ts >= strftime('%Y-%m-%dT%H:%M:%SZ', 'now', '-7 days') " ) ,
( " 30 дней " , " ts >= strftime('%Y-%m-%dT%H:%M:%SZ', 'now', '-30 days') " ) ,
( " Всё время " , " 1 " ) ,
] ;
/// 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' " ;
2026-10-19 11:00:10 +03:00
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 ( ) ;
} ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
// Summary: visitors (one per browser and day), who of them downloaded, downloads.
let mut summary = String ::from (
" <section class=wide><table class=summary><tr><th></th> " ,
2026-10-19 11:00:10 +03:00
) ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
for ( name , _ ) in PERIODS {
summary . push_str ( & format! ( " <th class=num> {name} </th> " ) ) ;
}
summary . push_str ( " </tr> " ) ;
let mut rows : Vec < ( & str , & str , Vec < String > ) > = vec! [
( " Посетители " , " открыли страницу; один браузер за день — один посетитель " , vec! [ ] ) ,
( " Скачали " , " посетители, которые после этого что-то скачали " , vec! [ ] ) ,
( " Конверсия " , " скачали / посетители " , vec! [ ] ) ,
( " Скачивания " , " все скачивания людьми, включая прямые ссылки и повторы " , vec! [ ] ) ,
2026-10-22 21:00:07 +03:00
( " из них Android " , " о б е сборки APK" , vec! [ ] ) ,
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
] ;
for ( _ , cond ) in PERIODS {
let visitors = number (
& db ,
& format! ( " SELECT COUNT(DISTINCT substr(ts, 1, 10) || visitor) {HUMAN_PV} AND {cond} " ) ,
) ;
let converted = number (
& db ,
& format! (
" SELECT COUNT(DISTINCT substr(d.ts, 1, 10) || d.visitor) FROM downloads d
WHERE d . kind = ' human ' AND d . platform < > ' checksums ' AND { }
AND EXISTS ( SELECT 1 FROM pageviews p WHERE p . visitor = d . visitor
AND substr ( p . ts , 1 , 10 ) = substr ( d . ts , 1 , 10 ) AND p . ts < = d . ts ) " ,
cond . replace ( " ts " , " d.ts " )
) ,
) ;
let downloads = number ( & db , & format! ( " SELECT COUNT(*) {HUMAN_DL} AND {cond} " ) ) ;
let rate = if visitors > 0 {
format! ( " {:.1} % " , converted as f64 * 100.0 / visitors as f64 )
} else {
" — " . into ( )
} ;
rows [ 0 ] . 2. push ( visitors . to_string ( ) ) ;
rows [ 1 ] . 2. push ( converted . to_string ( ) ) ;
rows [ 2 ] . 2. push ( rate ) ;
rows [ 3 ] . 2. push ( downloads . to_string ( ) ) ;
2026-10-22 21:00:07 +03:00
let android = number (
& db ,
& format! ( " SELECT COUNT(*) {HUMAN_DL} AND platform LIKE 'android%' AND {cond} " ) ,
) ;
rows [ 4 ] . 2. push ( android . to_string ( ) ) ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
}
for ( name , hint , cells ) in & rows {
summary . push_str ( & format! (
" <tr><td><b>{name}</b><br><small class=muted>{hint}</small></td> "
) ) ;
for c in cells {
summary . push_str ( & format! ( " <td class= \" num big \" > {c} </td> " ) ) ;
}
summary . push_str ( " </tr> " ) ;
}
summary . push_str ( " </table></section> " ) ;
// What was left out, all time.
let left_out = | table : & str | -> HashMap < String , i64 > {
pairs (
& db ,
& format! ( " SELECT kind, COUNT(*) FROM {table} WHERE kind <> 'human' GROUP BY 1 " ) ,
)
. into_iter ( )
. collect ( )
} ;
let ( dl_out , pv_out ) = ( left_out ( " downloads " ) , left_out ( " pageviews " ) ) ;
let get = | m : & HashMap < String , i64 > , k : & str | m . get ( k ) . copied ( ) . unwrap_or ( 0 ) ;
let excluded = format! (
" <p class=muted>Н е учтено за всё время (скачивания / просмотры): боты {} / {}, вы {} / {}, локальная сеть {} / {}.</p> " ,
get ( & dl_out , " bot " ) ,
get ( & pv_out , " bot " ) ,
get ( & dl_out , " owner " ) ,
get ( & pv_out , " owner " ) ,
get ( & dl_out , " local " ) ,
get ( & pv_out , " local " ) ,
) ;
// The last 30 days: visitors and downloads.
let by_day = | sql : String | -> HashMap < String , i64 > { pairs ( & db , & sql ) . into_iter ( ) . collect ( ) } ;
let since = " ts >= strftime('%Y-%m-%dT%H:%M:%SZ', 'now', '-31 days') " ;
let visits = by_day ( format! (
" SELECT date(ts, 'localtime'), COUNT(DISTINCT visitor) {HUMAN_PV} AND {since} GROUP BY 1 "
) ) ;
let downloads = by_day ( format! (
" SELECT date(ts, 'localtime'), COUNT(*) {HUMAN_DL} AND {since} GROUP BY 1 "
) ) ;
let days : Vec < String > = ( 0 .. 30 )
. rev ( )
. map ( | back | {
( chrono ::Local ::now ( ) - chrono ::Duration ::days ( back ) )
. format ( " %Y-%m-%d " )
. to_string ( )
} )
. collect ( ) ;
let max = days
. iter ( )
. map ( | d | visits . get ( d ) . copied ( ) . unwrap_or ( 0 ) . max ( downloads . get ( d ) . copied ( ) . unwrap_or ( 0 ) ) )
. max ( )
. unwrap_or ( 1 )
. max ( 1 ) ;
let mut chart = String ::from (
" <section class=wide><h2>30 дней <span class=legend><i class=v></i>посетители <i class=d></i>скачивания</span></h2><div class=chart> " ,
) ;
for day in & days {
let ( v , d ) = (
visits . get ( day ) . copied ( ) . unwrap_or ( 0 ) ,
downloads . get ( day ) . copied ( ) . unwrap_or ( 0 ) ,
) ;
let h = | n : i64 | ( n as f64 / max as f64 * 100.0 ) . round ( ) ;
2026-10-19 11:00:10 +03:00
chart . push_str ( & format! (
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
" <div title= \" {day}: посетителей {v}, скачиваний {d} \" ><p><span class=v style= \" height:{}% \" ></span><span class=d style= \" height:{}% \" ></span></p><small>{}</small></div> " ,
h ( v ) ,
h ( d ) ,
2026-10-19 11:00:10 +03:00
& day [ 8 .. ]
) ) ;
}
chart . push_str ( " </div></section> " ) ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
2026-10-22 21:00:07 +03:00
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> " ) ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
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 (
& db ,
& format! (
" SELECT COALESCE(country, '—') || ' · ' || COALESCE(region, '—') || COALESCE(' · ' || city, ''), COUNT(*) {HUMAN_DL} GROUP BY 1 ORDER BY 2 DESC LIMIT 30 "
) ,
) ;
let visitors_by_country = pairs (
& db ,
& format! ( " SELECT country, COUNT(DISTINCT substr(ts, 1, 10) || visitor) {HUMAN_PV} GROUP BY 1 ORDER BY 2 DESC LIMIT 30 " ) ,
) ;
let by_page = pairs (
& db ,
& format! ( " SELECT page, COUNT(DISTINCT substr(ts, 1, 10) || visitor) {HUMAN_PV} GROUP BY 1 ORDER BY 2 DESC " ) ,
) ;
let by_referrer = pairs (
& db ,
& format! ( " SELECT COALESCE(referrer, 'напрямую'), COUNT(DISTINCT substr(ts, 1, 10) || visitor) {HUMAN_PV} GROUP BY 1 ORDER BY 2 DESC LIMIT 20 " ) ,
) ;
2026-10-19 11:00:10 +03:00
let mut recent = String ::from (
2026-10-24 11:58:22 +03:00
" <section class=wide><h2>Последние скачивания (без ботов; ваши и из локальной сети — серым)</h2><table class=recent><tr><th>Время (UTC)</th><th>Файл</th><th>Версия</th><th>Где</th><th>Язык</th><th>Откуда</th><th>Кто</th></tr> " ,
2026-10-19 11:00:10 +03:00
) ;
if let Ok ( mut stmt ) = db . prepare (
2026-10-24 11:58:22 +03:00
" SELECT ts, platform, version, country, region, city, lang, referrer, kind, ua FROM downloads WHERE kind <> 'bot' ORDER BY id DESC LIMIT 50 " ,
2026-10-19 11:00:10 +03:00
) {
let rows = stmt . query_map ( [ ] , | r | {
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
( 0 .. 10 )
. map ( | i | r . get ::< _ , Option < String > > ( i ) . map ( | v | v . unwrap_or_default ( ) ) )
. collect ::< Result < Vec < _ > , _ > > ( )
2026-10-19 11:00:10 +03:00
} ) ;
for row in rows . into_iter ( ) . flatten ( ) . flatten ( ) {
let place = [ & row [ 3 ] , & row [ 4 ] , & row [ 5 ] ]
. iter ( )
. filter ( | s | ! s . is_empty ( ) )
. map ( | s | esc ( s ) )
. collect ::< Vec < _ > > ( )
. join ( " · " ) ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
let who = match row [ 8 ] . as_str ( ) {
" human " = > " человек " ,
" owner " = > " вы " ,
" local " = > " локальная сеть " ,
other = > other ,
} ;
let class = if row [ 8 ] = = " human " { " " } else { " class=muted " } ;
2026-10-19 11:00:10 +03:00
recent . push_str ( & format! (
2026-10-24 11:58:22 +03:00
" <tr{class}><td>{}</td><td>{}</td><td>{}</td><td class=wrap>{place}</td><td>{}</td><td class=wrap>{}</td><td title= \" {} \" >{who}</td></tr> " ,
2026-10-19 11:00:10 +03:00
esc ( & row [ 0 ] . replace ( 'T' , " " ) . replace ( 'Z' , " " ) ) ,
2026-10-22 21:00:07 +03:00
esc ( platform_label ( & row [ 1 ] ) ) ,
2026-10-19 11:00:10 +03:00
esc ( & row [ 2 ] ) ,
esc ( & row [ 6 ] ) ,
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
esc ( & row [ 7 ] ) ,
esc ( & row [ 9 ] ) ,
2026-10-19 11:00:10 +03:00
) ) ;
}
}
recent . push_str ( " </table></section> " ) ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
2026-10-19 11:00:10 +03:00
let page = format! (
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
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 :#1 b1f24 ; - - muted :#6 b7280 ; - - card :#fff ; - - line :#e5e7eb ; - - accent :#1 f6fa8 ; - - soft :#a9c8e2 } }
@ media ( prefers - color - scheme :dark ) { { :root { { - - bg :#16181 b ; - - fg :#e6e8eb ; - - muted :#9 aa1ab ; - - card :#1 f2226 ; - - line :#2 c3036 ; - - accent :#4 a9be0 ; - - soft :#2 f4b63 } } } }
2026-10-19 11:00:10 +03:00
body { { margin :0 ; font :15 px / 1.45 system - ui , sans - serif ; background :var ( - - bg ) ; color :var ( - - fg ) } }
main { { max - width :1100 px ; margin :0 auto ; padding :24 px 16 px } } h1 { { font - size :22 px ; margin :0 0 16 px } }
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
. grid { { display :grid ; grid - template - columns :repeat ( auto - fit , minmax ( 320 px , 1 fr ) ) ; gap :16 px ; margin - top :16 px } }
2026-10-19 11:00:10 +03:00
section { { background :var ( - - card ) ; border :1 px solid var ( - - line ) ; border - radius :10 px ; padding :14 px ; overflow - x :auto } }
section . wide { { margin - top :16 px } } h2 { { font - size :15 px ; margin :0 0 10 px } }
table { { border - collapse :collapse ; width :100 % } } td , th { { padding :4 px 6 px ; border - bottom :1 px solid var ( - - line ) ; text - align :left ; white - space :nowrap } }
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
. summary td { { padding :10 px 8 px } } . summary td :first - child { { white - space :normal } } . big { { font - size :24 px ; font - weight :600 } }
. grid td :first - child { { max - width :230 px ; overflow :hidden ; text - overflow :ellipsis } } . num { { text - align :right ; width :60 px } } . bar { { width :40 % } } . bar span { { display :block ; height :8 px ; border - radius :4 px ; background :var ( - - accent ) } }
2026-10-24 11:58:22 +03:00
. recent td . wrap { { white - space :normal ; overflow - wrap :anywhere ; min - width :120 px } }
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
. muted { { color :var ( - - muted ) } } . chart { { display :flex ; gap :3 px ; height :150 px } }
. chart div { { flex :1 ; display :flex ; flex - direction :column ; text - align :center } }
. chart p { { flex :1 ; margin :0 ; display :flex ; align - items :flex - end ; justify - content :center ; gap :1 px } }
. chart p span { { flex :1 ; max - width :10 px ; border - radius :2 px 2 px 0 0 ; min - height :1 px } }
. v { { background :var ( - - soft ) } } . d { { background :var ( - - accent ) } } . chart small { { color :var ( - - muted ) ; font - size :10 px } }
. legend { { font - weight :400 ; color :var ( - - muted ) ; margin - left :12 px } } . legend i { { display :inline - block ; width :10 px ; height :10 px ; border - radius :2 px ; margin :0 4 px 0 10 px ; vertical - align :- 1 px } }
2026-10-19 11:00:10 +03:00
a { { color :var ( - - accent ) } } < / style > < / head > < body > < main >
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
< h1 > ChessPenguin · с т а т и с т и к а < / h1 >
2026-10-22 21:00:07 +03:00
{ summary } { excluded } { android } { chart }
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
< 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 >
2026-10-19 11:00:10 +03:00
< / main > < / body > < / html > " #,
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
table ( " Скачивания по платформам " , & by_platform ) ,
table ( " Скачивания по версиям " , & by_version ) ,
table ( " Скачивания по странам " , & by_country ) ,
table ( " Скачивания по регионам и городам " , & by_region ) ,
table ( " Посетители по странам " , & visitors_by_country ) ,
table ( " Посетители по языку страницы " , & by_page ) ,
table ( " Откуда пришли посетители " , & by_referrer ) ,
2026-10-19 11:00:10 +03:00
) ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
// 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 ( )
2026-10-19 11:00:10 +03:00
}
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
/// `/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 {
2026-10-19 11:00:10 +03:00
if ! authorized ( & state . config , & headers ) {
return ask_password ( ) ;
}
let Ok ( db ) = state . db . lock ( ) else {
return StatusCode ::INTERNAL_SERVER_ERROR . into_response ( ) ;
} ;
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
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 ) {
2026-10-19 11:00:10 +03:00
let rows = stmt . query_map ( [ ] , | r | {
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
( 0 .. columns )
2026-10-19 11:00:10 +03:00
. 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' ) ;
}
}
(
[
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
( header ::CONTENT_TYPE , " text/csv; charset=utf-8 " . to_string ( ) ) ,
2026-10-19 11:00:10 +03:00
(
header ::CONTENT_DISPOSITION ,
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
format! ( " attachment; filename= \" {name} \" " ) ,
2026-10-19 11:00:10 +03:00
) ,
] ,
out ,
)
. into_response ( )
}
Website stats: page visitors, conversion, bots filtered out
site.js reports page views (POST /hit), so crawlers that do not run JavaScript are
not visitors. Downloads and views are classified as human, bot (no language, not a
browser, crawler user agent, or three files within ten minutes), owner (the browser
that opened /stats) or local network; only people are counted. Visitors are told
apart by a daily-salted hash, the IP is still not stored. Old rows are reclassified.
The stats page is in Russian: visitors, downloaders, conversion, downloads by period.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:45:24 +03:00
#[ 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} " ) ;
}
}
}