From d15989bff1f691eb35255d4c60232bca7f9a90c6 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 24 Oct 2026 13:57:07 +0300 Subject: [PATCH] Site: notices to the owner's Telegram bot and /stat Downloads by people, new installations, updates and a day's first run of an installation go to the owner's chat; /stat answers with today and all time (downloads, installations, active in 7 and 30 days, by platform). Installations are numbered in the order they first ran (installs table). Configured with TELEGRAM_TOKEN and TELEGRAM_CHAT; off without them. Co-Authored-By: Claude Opus 5.5 --- website/README.md | 10 +++ website/server/src/main.rs | 156 ++++++++++++++++++++++++++++++++- website/server/src/telegram.rs | 126 ++++++++++++++++++++++++++ 3 files changed, 290 insertions(+), 2 deletions(-) create mode 100644 website/server/src/telegram.rs diff --git a/website/README.md b/website/README.md index c30044c..7f758bb 100644 --- a/website/README.md +++ b/website/README.md @@ -80,6 +80,16 @@ shows installations that ran today, in 7 and 30 days, in all, and new ones in 7 platform, and the versions of the last 7 days. A program that cannot reach the site asks GitHub (uncounted); one with the update check turned off is not counted. +## Telegram + +With `TELEGRAM_TOKEN` (the owner's bot) and `TELEGRAM_CHAT` (the owner's chat id) in +`.env`, the site writes to the owner: «⬇️ Скачали …» for a person's download (not +crawlers, the owner or the local network), «🆕 Новая установка №N» for an installation's +first run, «⬆️ Обновилась …» when it runs a new version, «▶️ Запуск …» when it runs on a +new day (once a day at most). `/stat` answers with today and all time: downloads, +installations that ran and new ones, active in 7 and 30 days, by platform. Only the +owner's chat is listened to (long polling: one server per bot). + ## Development ```sh diff --git a/website/server/src/main.rs b/website/server/src/main.rs index b9019b6..3e994bc 100644 --- a/website/server/src/main.rs +++ b/website/server/src/main.rs @@ -11,6 +11,7 @@ //! `local` (the local network); the statistics count only `human`. mod site; +mod telegram; use std::collections::HashMap; use std::net::{IpAddr, SocketAddr}; @@ -113,6 +114,8 @@ struct AppState { /// The same without following redirects: to learn where GitHub sends a file. direct: reqwest::Client, release: tokio::sync::Mutex>, + /// The owner's Telegram bot (notices and `/stat`), when configured. + bot: Option>, /// The visitor-key salt and the local day it belongs to. salt: Mutex<(String, u64)>, } @@ -164,6 +167,12 @@ async fn main() { 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"); @@ -205,8 +214,20 @@ async fn main() { .build() .expect("http client"), release: tokio::sync::Mutex::new(None), + 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)) @@ -566,14 +587,60 @@ async fn api_update( if let (Some(install), Some(version), Some(platform)) = (install, version, platform) { let ip = client_ip(&state.config, peer, &headers); if !is_local(ip) { - let (country, _, _) = locate(&state, ip); + let (country, region, city) = locate(&state, ip); let day = chrono::Local::now().format("%Y-%m-%d").to_string(); - if let Ok(db) = state.db.lock() { + let notice = state.db.lock().ok().and_then(|db| { + // What this installation was before: its last version, and whether it + // already ran today. + let before: Option = 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 known: Option = db + .query_row("SELECT n FROM installs WHERE install = ?1", [&install], |r| r.get(0)) + .ok(); + 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); + 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); } } } @@ -616,6 +683,7 @@ async fn download( .and_then(|v| v.to_str().ok()) .and_then(|v| v.split('/').nth(2)) .map(|s| s.chars().take(64).collect::()); + 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 @@ -655,6 +723,25 @@ async fn download( c.ua ], ); + // People only: not crawlers, not the owner, not the local network. + 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::>() + .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() } @@ -785,6 +872,71 @@ fn platform_label(platform: &str) -> &str { } } +/// 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::>(); + 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); diff --git a/website/server/src/telegram.rs b/website/server/src/telegram.rs new file mode 100644 index 0000000..84f1d63 --- /dev/null +++ b/website/server/src/telegram.rs @@ -0,0 +1,126 @@ +//! Notices to the owner's Telegram bot: a download from the site, a new installation, an +//! installation that runs again on a new day or after an update; `/stat` answers with +//! the numbers of today and of all time. Only the owner's chat is written to and +//! listened to. Off without `TELEGRAM_TOKEN` and `TELEGRAM_CHAT` in the environment. + +use std::sync::Arc; +use std::time::Duration; + +use serde_json::{Value, json}; + +pub struct Bot { + token: String, + chat: i64, + http: reqwest::Client, +} + +impl Bot { + pub fn from_env() -> Option> { + let token = std::env::var("TELEGRAM_TOKEN").ok().filter(|t| !t.is_empty())?; + let chat = std::env::var("TELEGRAM_CHAT").ok()?.trim().parse().ok()?; + let http = reqwest::Client::builder() + .user_agent("chesspenguin-site") + // Long polling waits up to 50 s for a message. + .timeout(Duration::from_secs(70)) + .build() + .ok()?; + Some(Arc::new(Bot { token, chat, http })) + } + + fn url(&self, method: &str) -> String { + format!("https://api.telegram.org/bot{}/{method}", self.token) + } + + /// Sends `text` to the owner in the background (a failure is only logged). + pub fn send(self: &Arc, text: String) { + let bot = self.clone(); + tokio::spawn(async move { bot.send_now(&text).await }); + } + + async fn send_now(&self, text: &str) { + let body = json!({ + "chat_id": self.chat, + "text": text, + "disable_web_page_preview": true, + }); + match self.http.post(self.url("sendMessage")).json(&body).send().await { + Ok(r) if !r.status().is_success() => eprintln!("telegram: {}", r.status()), + Err(e) => eprintln!("telegram: {}", e.without_url()), + _ => {} + } + } + + /// Waits for the owner's commands (long polling) and answers them with `answer`. + pub async fn listen(self: Arc, answer: impl Fn(&str) -> Option) { + let mut offset: i64 = 0; + loop { + let got = self + .http + .get(format!("{}?timeout=50&offset={offset}", self.url("getUpdates"))) + .send() + .await; + let updates: Value = match got { + Ok(r) => r.json().await.unwrap_or(Value::Null), + Err(e) => { + eprintln!("telegram: {}", e.without_url()); + tokio::time::sleep(Duration::from_secs(30)).await; + continue; + } + }; + let Some(list) = updates["result"].as_array() else { + tokio::time::sleep(Duration::from_secs(30)).await; + continue; + }; + for u in list { + offset = offset.max(u["update_id"].as_i64().unwrap_or(0) + 1); + let m = &u["message"]; + if m["chat"]["id"].as_i64() != Some(self.chat) { + continue; + } + // "/stat", "/stat@chessPenguin_bot". + let command = m["text"].as_str().unwrap_or("").split(['@', ' ']).next().unwrap_or(""); + if let Some(text) = answer(command) { + self.send_now(&text).await; + } + } + } + } +} + +/// The flag of a country ("RU" → 🇷🇺), or nothing. +pub fn flag(country: Option<&str>) -> String { + match country { + Some(c) if c.len() == 2 && c.chars().all(|c| c.is_ascii_alphabetic()) => c + .to_ascii_uppercase() + .chars() + .filter_map(|c| char::from_u32(0x1F1E6 + (c as u32 - 'A' as u32))) + .collect(), + _ => String::new(), + } +} + +/// "🇷🇺 Moscow" / "🇷🇺 RU" / "": where someone is, as short as it is known. +pub fn place(country: Option<&str>, region: Option<&str>, city: Option<&str>) -> String { + let name = city.or(region).or(country).unwrap_or(""); + [flag(country), name.to_owned()] + .into_iter() + .filter(|s| !s.is_empty()) + .collect::>() + .join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flags_and_places() { + assert_eq!(flag(Some("RU")), "🇷🇺"); + assert_eq!(flag(Some("kz")), "🇰🇿"); + assert_eq!(flag(None), ""); + assert_eq!(flag(Some("—")), ""); + assert_eq!(place(Some("RU"), Some("Moscow"), Some("Moscow")), "🇷🇺 Moscow"); + assert_eq!(place(Some("UZ"), None, None), "🇺🇿 UZ"); + assert_eq!(place(None, None, None), ""); + } +}