Website: Android screenshots first for a visitor on Android
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

Seven phone screens one by one (home with a put-aside game, a database's
games, the Opera game, Stockfish, the play sheet, «Who to play», a game
against Rodent IV) open the gallery and the lightbox on Android, under «On
the phone», before «On the computer»; the hero shows the four phone screens.
Other visitors see the page as before. Nine languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-27 15:47:09 +03:00
parent 20d9d018bb
commit 12e4c7d5e9
59 changed files with 645 additions and 82 deletions

View file

@ -47,8 +47,18 @@ pub const PLATFORMS: &[(&str, &str)] = &[
/// 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",
"windows",
"macos",
"deb",
"rpm",
"arch",
"aur",
"appimage",
"flatpak",
"tarball",
"other",
"android",
"android-noengine",
];
/// New installations counted per address and day.
@ -88,11 +98,14 @@ impl Config {
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(),
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", ""),
@ -215,7 +228,10 @@ async fn main() {
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());
eprintln!(
"network database {} not used: {e}; clouds are not told apart",
config.asn_path.display()
);
None
}
};
@ -342,11 +358,42 @@ struct Client {
/// 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",
"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 {
@ -356,7 +403,9 @@ fn is_local(ip: IpAddr) -> bool {
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)))
|| v6
.to_ipv4_mapped()
.is_some_and(|v4| is_local(IpAddr::V4(v4)))
}
}
}
@ -370,14 +419,21 @@ fn looks_like_bot(ua: &str, lang: Option<&str>) -> bool {
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 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 owner = text(header::COOKIE)
.split(';')
.any(|c| c.trim() == "cp_owner=1");
let kind = if owner {
"owner"
} else if is_local(ip) {
@ -454,7 +510,10 @@ async fn hit(
}
// 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 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))
@ -596,7 +655,11 @@ async fn api_release(State(state): State<Shared>) -> Response {
);
resp
}
None => (StatusCode::SERVICE_UNAVAILABLE, "release information unavailable").into_response(),
None => (
StatusCode::SERVICE_UNAVAILABLE,
"release information unavailable",
)
.into_response(),
}
}
@ -623,8 +686,10 @@ async fn api_update(
.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 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 == '-')
@ -640,7 +705,11 @@ async fn api_update(
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))
.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());
@ -688,15 +757,21 @@ async fn api_update(
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}") };
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}")),
_ 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,
}
});
@ -716,7 +791,11 @@ async fn api_update(
})).collect::<Vec<_>>(),
}))
.into_response(),
None => (StatusCode::SERVICE_UNAVAILABLE, "release information unavailable").into_response(),
None => (
StatusCode::SERVICE_UNAVAILABLE,
"release information unavailable",
)
.into_response(),
}
}
@ -795,14 +874,22 @@ async fn download(
)
.unwrap_or(false);
if kind == "human" && asset.platform != "checksums" && !again {
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 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}") };
let line = if line.is_empty() {
String::new()
} else {
format!("\n{line}")
};
notice = Some(format!(
"⬇️ Скачали {} · {}{line}",
platform_label(asset.platform),
@ -916,7 +1003,10 @@ fn authorized(config: &Config, headers: &HeaderMap) -> bool {
fn ask_password() -> Response {
(
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Basic realm=\"ChessPenguin stats\"")],
[(
header::WWW_AUTHENTICATE,
"Basic realm=\"ChessPenguin stats\"",
)],
"Password required",
)
.into_response()
@ -984,11 +1074,16 @@ fn stat_text(state: &AppState) -> String {
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 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 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\
@ -1003,7 +1098,13 @@ fn stat_text(state: &AppState) -> String {
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)?)))
.query_map([], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, i64>(1)?,
r.get::<_, i64>(2)?,
))
})
.ok()?
.flatten()
.collect::<Vec<_>>();
@ -1110,21 +1211,49 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
// 1. The main numbers.
let mut main_rows: Vec<(&str, &str, Vec<i64>)> = vec![
("Посетители сайта", "открыли страницу; один браузер за день — один посетитель", vec![]),
("Скачивания", "файлы программы, скачанные людьми с сайта", vec![]),
("Новые установки", "программа запущена впервые (считается с версии 1.0.1)", vec![]),
("Работающие установки", "разные установки, запускавшиеся за период", 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)),
&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[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)),
&format!(
"SELECT COUNT(DISTINCT install) FROM launches WHERE {}",
since_day(from)
),
));
}
let mut main = String::from("<section><table class=summary><tr><th></th>");
@ -1133,7 +1262,9 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
}
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>"));
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>"));
}
@ -1157,9 +1288,16 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
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 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 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>(),
@ -1170,7 +1308,11 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
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 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>",
@ -1187,16 +1329,26 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
let charts = format!(
"<div class=pair>{}{}</div>",
chart("Сайт", (&visits, "посетители"), (&downloads, "скачивания")),
chart("Программы", (&running, "работали"), (&fresh, "новые установки")),
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_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"),
&format!(
"SELECT platform, COUNT(*) {HUMAN_DL} AND date(ts, 'localtime') >= '{d30}' GROUP BY 1"
),
)
.into_iter()
.collect();
@ -1210,7 +1362,9 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
.collect();
let inst_30: HashMap<String, i64> = pairs(
&db,
&format!("SELECT platform, COUNT(DISTINCT install) FROM launches WHERE day >= '{d30}' GROUP BY 1"),
&format!(
"SELECT platform, COUNT(DISTINCT install) FROM launches WHERE day >= '{d30}' GROUP BY 1"
),
)
.into_iter()
.collect();
@ -1220,7 +1374,11 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
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>();
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() {
@ -1258,7 +1416,9 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
// 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"),
&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.
@ -1278,11 +1438,15 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
);
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"),
&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"),
&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.
@ -1337,7 +1501,10 @@ async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
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(&format!(
"<tr><td class=time>{}</td><td class=wrap>{text}</td></tr>",
esc(&ts[..16.min(ts.len())])
));
}
recent.push_str("</table></section>");
@ -1455,10 +1622,23 @@ mod tests {
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(
"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"] {
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"] {

View file

@ -36,6 +36,17 @@ const SHOTS: &[&str] = &[
"09-looks",
];
/// The Android screens (static/screenshots/phone), shown first to a visitor on Android.
const PHONE_SHOTS: &[&str] = &[
"01-home",
"02-games",
"03-game",
"04-engine",
"05-play",
"06-who",
"07-rodent",
];
/// Strings the page script needs (download panel, buttons, lightbox).
const CLIENT_KEYS: &[&str] = &[
"btn_windows",
@ -168,7 +179,12 @@ impl Site {
.collect();
let lang_links: String = LANGS
.iter()
.map(|(c, name, _)| format!("<a href=\"{}\" hreflang=\"{c}\" data-lang=\"{c}\">{name}</a>", Self::path(c)))
.map(|(c, name, _)| {
format!(
"<a href=\"{}\" hreflang=\"{c}\" data-lang=\"{c}\">{name}</a>",
Self::path(c)
)
})
.collect::<Vec<_>>()
.join(" · ");
let locale = LANGS
@ -192,6 +208,34 @@ impl Site {
)
})
.collect();
let phone_gallery: String = PHONE_SHOTS
.iter()
.enumerate()
.map(|(i, stem)| {
let n = i + 1;
format!(
"<li><a href=\"/screenshots/phone/{stem}.png\" data-phone=\"{n}\"><picture>\
<source type=\"image/webp\" srcset=\"/screenshots/phone/{stem}-360.webp 360w, /screenshots/phone/{stem}-720.webp 720w\" sizes=\"(min-width: 900px) 200px, (min-width: 640px) 30vw, 44vw\">\
<img src=\"/screenshots/phone/{stem}-360.jpg\" width=\"1080\" height=\"2400\" loading=\"lazy\" alt=\"{alt}\"></picture></a>\
<p>{cap}</p></li>",
alt = attr(self.t(lang, &format!("phone_alt{n}"))),
cap = self.t(lang, &format!("phone{n}")),
)
})
.collect();
let phone_shots: Vec<Value> = PHONE_SHOTS
.iter()
.enumerate()
.map(|(i, stem)| {
json!({
"full": format!("/screenshots/phone/{stem}.png"),
"src": format!("/screenshots/phone/{stem}-1080.webp"),
"fallback": format!("/screenshots/phone/{stem}-720.jpg"),
"caption": self.t(lang, &format!("phone{}", i + 1)),
"alt": self.t(lang, &format!("phone_alt{}", i + 1)),
})
})
.collect();
let t: serde_json::Map<String, Value> = CLIENT_KEYS
.iter()
.map(|k| (k.to_string(), Value::String(self.t(lang, k).to_string())))
@ -228,6 +272,7 @@ impl Site {
"version": release.map(|r| r.version.clone()),
"assets": assets,
"shots": shots,
"phoneShots": phone_shots,
"t": t,
});
let json_ld = json!({
@ -252,6 +297,7 @@ impl Site {
("{{lang_links}}", lang_links),
("{{root_redirect}}", root_redirect.to_string()),
("{{gallery}}", gallery),
("{{phone_gallery}}", phone_gallery),
// `</` must not close the script element the JSON sits in.
("{{client_json}}", client.to_string().replace("</", "<\\/")),
("{{json_ld}}", json_ld.to_string().replace("</", "<\\/")),
@ -284,7 +330,12 @@ impl Site {
fn fill_release(&self, mut html: String, lang: &str, release: Option<&Release>) -> String {
let version = release.map_or("", |r| r.version.as_str());
html = html.replace("{version}", version);
html = html.replace("{date}", &release.map(|r| date(&r.published, lang)).unwrap_or_default());
html = html.replace(
"{date}",
&release
.map(|r| date(&r.published, lang))
.unwrap_or_default(),
);
for (platform, _) in crate::PLATFORMS {
let asset = release.and_then(|r| r.assets.iter().find(|a| a.platform == *platform));
html = html.replace(
@ -337,7 +388,9 @@ impl Site {
const ROOT_REDIRECT: &str = r#"<script>(function(){var L=["ru","fr","de","es","it","pt","uz","kk"],p=null;try{p=localStorage.getItem("lang")}catch(e){}if(!p){var ls=navigator.languages||[navigator.language||""];for(var i=0;i<ls.length;i++){var c=(ls[i]||"").slice(0,2).toLowerCase();if(c==="en"||L.indexOf(c)>=0){p=c;break}}}if(p&&p!=="en"&&L.indexOf(p)>=0){location.replace("/"+p+"/"+location.hash)}})();</script>"#;
fn attr(s: &str) -> String {
s.replace('&', "&amp;").replace('"', "&quot;").replace('<', "&lt;")
s.replace('&', "&amp;")
.replace('"', "&quot;")
.replace('<', "&lt;")
}
/// "14 MB", "8.4 MB" (decimal megabytes, as browsers and Finder show).
@ -362,15 +415,122 @@ fn date(rfc3339: &str, lang: &str) -> String {
return String::new();
}
let months: [&str; 12] = match lang {
"ru" => ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"],
"fr" => ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"],
"de" => ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
"es" => ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
"it" => ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"],
"pt" => ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
"uz" => ["yanvar", "fevral", "mart", "aprel", "may", "iyun", "iyul", "avgust", "sentabr", "oktabr", "noyabr", "dekabr"],
"kk" => ["қаңтар", "ақпан", "наурыз", "сәуір", "мамыр", "маусым", "шілде", "тамыз", "қыркүйек", "қазан", "қараша", "желтоқсан"],
_ => ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
"ru" => [
"января",
"февраля",
"марта",
"апреля",
"мая",
"июня",
"июля",
"августа",
"сентября",
"октября",
"ноября",
"декабря",
],
"fr" => [
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre",
],
"de" => [
"Januar",
"Februar",
"März",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember",
],
"es" => [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre",
],
"it" => [
"gennaio",
"febbraio",
"marzo",
"aprile",
"maggio",
"giugno",
"luglio",
"agosto",
"settembre",
"ottobre",
"novembre",
"dicembre",
],
"pt" => [
"janeiro",
"fevereiro",
"março",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro",
],
"uz" => [
"yanvar", "fevral", "mart", "aprel", "may", "iyun", "iyul", "avgust", "sentabr",
"oktabr", "noyabr", "dekabr",
],
"kk" => [
"қаңтар",
"ақпан",
"наурыз",
"сәуір",
"мамыр",
"маусым",
"шілде",
"тамыз",
"қыркүйек",
"қазан",
"қараша",
"желтоқсан",
],
_ => [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
],
};
let month = months[m - 1];
match lang {

View file

@ -16,7 +16,9 @@ pub struct Bot {
impl Bot {
pub fn from_env() -> Option<Arc<Bot>> {
let token = std::env::var("TELEGRAM_TOKEN").ok().filter(|t| !t.is_empty())?;
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")
@ -43,7 +45,13 @@ impl Bot {
"text": text,
"disable_web_page_preview": true,
});
match self.http.post(self.url("sendMessage")).json(&body).send().await {
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()),
_ => {}
@ -56,7 +64,10 @@ impl Bot {
loop {
let got = self
.http
.get(format!("{}?timeout=50&offset={offset}", self.url("getUpdates")))
.get(format!(
"{}?timeout=50&offset={offset}",
self.url("getUpdates")
))
.send()
.await;
let updates: Value = match got {
@ -84,7 +95,12 @@ impl Bot {
continue;
}
// "/stat", "/stat@chessPenguin_bot".
let command = m["text"].as_str().unwrap_or("").split(['@', ' ']).next().unwrap_or("");
let command = m["text"]
.as_str()
.unwrap_or("")
.split(['@', ' '])
.next()
.unwrap_or("");
if let Some(text) = answer(command) {
self.send_now(&text).await;
}
@ -125,7 +141,10 @@ mod tests {
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("RU"), Some("Moscow"), Some("Moscow")),
"🇷🇺 Moscow"
);
assert_eq!(place(Some("UZ"), None, None), "🇺🇿 UZ");
assert_eq!(place(None, None, None), "");
}

View file

@ -40,6 +40,22 @@ def derive():
print(stem)
def derive_phone():
"""The Android screens (1080x2400, shots/raw/phone): narrow thumbnails for the gallery."""
out = os.path.join(OUT, "phone")
os.makedirs(out, exist_ok=True)
for path in sorted(glob.glob(os.path.join(RAW, "phone", "[0-9]*.png"))):
stem = os.path.splitext(os.path.basename(path))[0]
im = Image.open(path).convert("RGB")
for w in (360, 720, 1080):
small = im if w == im.width else im.resize((w, round(im.height * w / im.width)), Image.LANCZOS)
small.save(os.path.join(out, f"{stem}-{w}.webp"), "WEBP", quality=84, method=6)
if w in (360, 720):
small.save(os.path.join(out, f"{stem}-{w}.jpg"), "JPEG", quality=86, optimize=True, progressive=True)
im.save(os.path.join(out, f"{stem}.png"), "PNG", optimize=True)
print("phone/" + stem)
def og_image():
w, h = 1200, 630
img = Image.new("RGB", (w, h), (22, 23, 24))
@ -67,4 +83,5 @@ def og_image():
if __name__ == "__main__":
derive()
derive_phone()
og_image()

View file

@ -101,6 +101,10 @@ fi
# 06-android is four phone screens (the emulator, English, dark theme, Green and Merida):
# a database's games, the Opera game at 8.Nc3, the play sheet with Rodent IV (Tal) and the
# «Who to play» list at its top — side by side on 3840x2160 (shots/raw/06-android.png).
# The same screens one by one for the Android gallery (shots/raw/phone/NN-name.png, 1080x2400,
# English, dark, demo mode of the status bar: clock 5:35, Wi-Fi and battery): the home screen
# with a put-aside game, the database's games, the Opera game at 8.Nc3, Stockfish on it, the
# play sheet, «Who to play», a game against Rodent IV (Tal).
shot 07-filters "${dark_big}" 6 "CP_FILTER=player=carlsen magnus;years=2015-2026;elo=2600" "${tournament}"
shot 08-position-search "${dark_big}" 8 "CP_BOARD=e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6" "${tournament}"
shot 09-looks "${light_games}" 4 NOCACHE CP_OPEN=0 CP_PLY=23 CP_SETTINGS=board

View file

@ -155,6 +155,22 @@
"shot8": "Jede Partie finden, die eine Stellung erreicht, mit den Folgezügen und ihren Ergebnissen.",
"alt9": "Brett- und Figureneinstellungen im hellen Design: Figurensätze, Zugnotation und Bretter, das gewählte Brett hinter dem Fenster.",
"shot9": "Ganz nach Ihrem Geschmack: 17 Figurensätze, 37 Bretter, Züge in Buchstaben oder Figurinen, Figurenanimation, dunkles und helles Design.",
"gallery_phone": "Auf dem Handy",
"gallery_desktop": "Auf dem Computer",
"phone_alt1": "Der Startbildschirm der App: die Karte einer vertagten Partie gegen Rodent IV, die Knöpfe „Spielen“ und „Neue Partie“, die eigene Datenbank und PGN-, ChessBase- und 7z-Dateien.",
"phone1": "Ihre Datenbanken und Dateien; oben wartet eine vertagte Partie.",
"phone_alt2": "Die Partienliste von „Classic games“: Morphy, Anderssen, Lasker und andere mit Ergebnis, Turnier, Jahr und ECO-Code.",
"phone2": "Partien einer Datenbank: Spieler, Ergebnis, Turnier, Eröffnung.",
"phone_alt3": "Morphys Opernpartie nach 8.Sc3 mit Kommentar und Variante unter dem Brett.",
"phone3": "Eine kommentierte Partie mit Anmerkungen und Varianten.",
"phone_alt4": "Stockfish-Analyse: Bewertung +3.2 in Tiefe 26, die beste Linie und Pfeile auf dem Brett.",
"phone4": "Stockfish auf dem Handy: Bewertung, beste Linie, Pfeile.",
"phone_alt5": "Das Blatt „Gegen den Computer spielen“: Rodent IV gewählt, der Charakter Tal, Stärke 2800, Farbe und Name des Spielers.",
"phone5": "Maia spielt wie ein Mensch, Rodent IV mit Stil.",
"phone_alt6": "Die Liste „Gegen wen spielen“: große Spieler von Aljechin bis Kortschnoi, jeder mit einer Zeile zum Stil.",
"phone6": "Rodent als einer von 22 großen Spielern oder einem Dutzend Charakteren.",
"phone_alt7": "Eine Partie gegen Rodent IV 2800 im Stil von Tal, ein Sizilianer, mit den Knöpfen Zurücknehmen, Aufgeben und Remis.",
"phone7": "Eine Partie gegen Tal: zurücknehmen, aufgeben oder Remis anbieten.",
"btn_android": "Für Android herunterladen",
"and_requires": "Alphaversion. Benötigt Android 12 oder neuer.",
"and_intro": "Zwei Varianten derselben App: Datenbanken und Partien ansehen, Züge eingeben und eigene Datenbanken führen, gegen Maia und Rodent spielen, Eröffnungen lernen und mit Stockfish analysieren. Geöffnete Dateien werden nur gelesen.",

View file

@ -155,6 +155,22 @@
"shot8": "Find every game that reaches a position, with the moves played next and how they scored.",
"alt9": "Board and piece settings in the light theme: piece sets, move notation and boards, the chosen board behind the window.",
"shot9": "Make it yours: 17 piece sets, 37 boards, moves in letters or figurines, piece animation, dark and light themes.",
"gallery_phone": "On the phone",
"gallery_desktop": "On the computer",
"phone_alt1": "The app's home screen: the card of a put-aside game against Rodent IV, the Play and New game buttons, your own database and PGN, ChessBase and 7z files.",
"phone1": "Your databases and files; a put-aside game waits on top.",
"phone_alt2": "The game list of “Classic games”: Morphy, Anderssen, Lasker and others with the result, event, year and ECO code.",
"phone2": "A database's games: players, result, event, opening.",
"phone_alt3": "Morphy's Opera Game after 8.Nc3 with a comment and a variation under the board.",
"phone3": "An annotated game with comments and variations.",
"phone_alt4": "Stockfish analysis: evaluation +3.2 at depth 26, the best line and arrows on the board.",
"phone4": "Stockfish on the phone: evaluation, best line, arrows.",
"phone_alt5": "The “Play against the computer” sheet: Rodent IV chosen, the Tal character, strength 2800, the colour and the player's name.",
"phone5": "Maia plays like a human, Rodent IV with a style.",
"phone_alt6": "The “Who to play” list: great players from Alekhine to Kortchnoi, each with a line about the style.",
"phone6": "Rodent as one of 22 great players or a dozen characters.",
"phone_alt7": "A game against Rodent IV 2800 in Tal's style, a Sicilian, with the Take back, Resign and Draw buttons.",
"phone7": "A game against Tal: take back, resign or offer a draw.",
"btn_android": "Download for Android",
"and_requires": "Alpha version. Requires Android 12 or newer.",
"and_intro": "Two builds of one app: browse databases and games, enter moves and keep your own databases, play against Maia and Rodent, learn an opening, and analyse with Stockfish. Files you open are only read.",

View file

@ -155,6 +155,22 @@
"shot8": "Encuentra cada partida que llega a una posición, con las jugadas siguientes y sus resultados.",
"alt9": "Ajustes de tablero y piezas en el tema claro: juegos de piezas, notación de jugadas y tableros, con el tablero elegido detrás de la ventana.",
"shot9": "A tu gusto: 17 juegos de piezas, 37 tableros, jugadas con letras o figuras, animación de piezas, temas oscuro y claro.",
"gallery_phone": "En el teléfono",
"gallery_desktop": "En el ordenador",
"phone_alt1": "La pantalla de inicio de la app: la tarjeta de una partida aplazada contra Rodent IV, los botones «Jugar» y «Nueva partida», tu propia base y archivos PGN, ChessBase y 7z.",
"phone1": "Tus bases y archivos; arriba espera una partida aplazada.",
"phone_alt2": "La lista de partidas de «Classic games»: Morphy, Anderssen, Lasker y otros, con el resultado, el torneo, el año y el código ECO.",
"phone2": "Las partidas de una base: jugadores, resultado, torneo, apertura.",
"phone_alt3": "La partida de la Ópera de Morphy tras 8.Cc3, con un comentario y una variante bajo el tablero.",
"phone3": "Una partida comentada con notas y variantes.",
"phone_alt4": "Análisis de Stockfish: evaluación +3.2 a profundidad 26, la mejor línea y flechas en el tablero.",
"phone4": "Stockfish en el teléfono: evaluación, mejor línea, flechas.",
"phone_alt5": "La hoja «Jugar contra el ordenador»: Rodent IV elegido, el carácter Tal, fuerza 2800, el color y el nombre del jugador.",
"phone5": "Maia juega como una persona, Rodent IV con estilo.",
"phone_alt6": "La lista «Contra quién jugar»: grandes jugadores de Alekhine a Korchnói, cada uno con una línea sobre su estilo.",
"phone6": "Rodent como uno de 22 grandes jugadores o una docena de caracteres.",
"phone_alt7": "Una partida contra Rodent IV 2800 al estilo de Tal, una siciliana, con los botones Deshacer, Rendirse y Tablas.",
"phone7": "Una partida contra Tal: deshacer, rendirse u ofrecer tablas.",
"btn_android": "Descargar para Android",
"and_requires": "Versión alfa. Requiere Android 12 o posterior.",
"and_intro": "Dos versiones de una misma app: explora bases y partidas, introduce jugadas y lleva tus propias bases, juega contra Maia y Rodent, aprende una apertura y analiza con Stockfish. Los archivos que abres solo se leen.",

View file

@ -155,6 +155,22 @@
"shot8": "Trouvez chaque partie qui atteint une position, avec les coups joués ensuite et leurs résultats.",
"alt9": "Réglages de l'échiquier et des pièces en thème clair : jeux de pièces, notation des coups et échiquiers, l'échiquier choisi derrière la fenêtre.",
"shot9": "À votre goût : 17 jeux de pièces, 37 échiquiers, coups en lettres ou en figurines, animation des pièces, thèmes sombre et clair.",
"gallery_phone": "Sur le téléphone",
"gallery_desktop": "Sur l’ordinateur",
"phone_alt1": "L’écran d’accueil de l’application : la carte d’une partie ajournée contre Rodent IV, les boutons « Jouer » et « Nouvelle partie », votre base et des fichiers PGN, ChessBase et 7z.",
"phone1": "Vos bases et fichiers ; une partie ajournée attend en haut.",
"phone_alt2": "La liste des parties de « Classic games » : Morphy, Anderssen, Lasker et d’autres, avec le résultat, le tournoi, l’année et le code ECO.",
"phone2": "Les parties d’une base : joueurs, résultat, tournoi, ouverture.",
"phone_alt3": "La partie de l’Opéra de Morphy après 8.Cc3, avec un commentaire et une variante sous l’échiquier.",
"phone3": "Une partie commentée avec ses notes et ses variantes.",
"phone_alt4": "Analyse de Stockfish : évaluation +3.2 à la profondeur 26, la meilleure ligne et des flèches sur l’échiquier.",
"phone4": "Stockfish dans le téléphone : évaluation, meilleure ligne, flèches.",
"phone_alt5": "La feuille « Jouer contre l’ordinateur » : Rodent IV choisi, le caractère Tal, force 2800, la couleur et le nom du joueur.",
"phone5": "Maia joue comme un humain, Rodent IV avec du style.",
"phone_alt6": "La liste « Contre qui jouer » : les grands joueurs d’Alekhine à Kortchnoï, chacun avec une ligne sur son style.",
"phone6": "Rodent en l’un des 22 grands joueurs ou d’une douzaine de caractères.",
"phone_alt7": "Une partie contre Rodent IV 2800 dans le style de Tal, une sicilienne, avec les boutons Reprendre, Abandonner et Nulle.",
"phone7": "Une partie contre Tal : reprendre un coup, abandonner ou proposer la nulle.",
"btn_android": "Télécharger pour Android",
"and_requires": "Version alpha. Nécessite Android 12 ou plus récent.",
"and_intro": "Deux versions d’une même application : parcourez bases et parties, saisissez des coups et tenez vos propres bases, jouez contre Maia et Rodent, apprenez une ouverture et analysez avec Stockfish. Les fichiers ouverts sont seulement lus.",

View file

@ -155,6 +155,22 @@
"shot8": "Trova ogni partita che raggiunge una posizione, con le mosse giocate dopo e i loro risultati.",
"alt9": "Impostazioni di scacchiera e pezzi nel tema chiaro: set di pezzi, notazione delle mosse e scacchiere, con la scacchiera scelta dietro la finestra.",
"shot9": "Come piace a te: 17 set di pezzi, 37 scacchiere, mosse in lettere o figurine, animazione dei pezzi, tema scuro e chiaro.",
"gallery_phone": "Sul telefono",
"gallery_desktop": "Sul computer",
"phone_alt1": "La schermata iniziale dell’app: la scheda di una partita sospesa contro Rodent IV, i pulsanti «Gioca» e «Nuova partita», il tuo database e file PGN, ChessBase e 7z.",
"phone1": "I tuoi database e file; in alto aspetta una partita sospesa.",
"phone_alt2": "L’elenco delle partite di «Classic games»: Morphy, Anderssen, Lasker e altri, con risultato, torneo, anno e codice ECO.",
"phone2": "Le partite di un database: giocatori, risultato, torneo, apertura.",
"phone_alt3": "La partita dell’Opera di Morphy dopo 8.Cc3, con un commento e una variante sotto la scacchiera.",
"phone3": "Una partita commentata con note e varianti.",
"phone_alt4": "Analisi di Stockfish: valutazione +3.2 a profondità 26, la linea migliore e frecce sulla scacchiera.",
"phone4": "Stockfish sul telefono: valutazione, linea migliore, frecce.",
"phone_alt5": "Il foglio «Gioca contro il computer»: scelto Rodent IV, il carattere Tal, forza 2800, il colore e il nome del giocatore.",
"phone5": "Maia gioca come una persona, Rodent IV con uno stile.",
"phone_alt6": "L’elenco «Contro chi giocare»: grandi giocatori da Alekhine a Korchnoi, ognuno con una riga sullo stile.",
"phone6": "Rodent come uno dei 22 grandi giocatori o una dozzina di caratteri.",
"phone_alt7": "Una partita contro Rodent IV 2800 nello stile di Tal, una siciliana, con i pulsanti Ritira, Abbandona e Patta.",
"phone7": "Una partita contro Tal: ritirare la mossa, abbandonare o proporre patta.",
"btn_android": "Scarica per Android",
"and_requires": "Versione alfa. Richiede Android 12 o successivo.",
"and_intro": "Due versioni della stessa app: sfoglia database e partite, inserisci mosse e tieni i tuoi database, gioca contro Maia e Rodent, impara un’apertura e analizza con Stockfish. I file aperti vengono solo letti.",

View file

@ -155,6 +155,22 @@
"shot8": "Позицияға жеткен барлық партияны, келесі жүрістер мен олардың нәтижелерімен табыңыз.",
"alt9": "Ашық тақырыптағы тақта мен фигуралар баптаулары: фигуралар жиындары, жүрістер жазбасы және тақталар, терезе артында таңдалған тақта.",
"shot9": "Өзіңізге бейімдеңіз: 17 фигуралар жиыны, 37 тақта, жүрістер әріптермен не фигура белгілерімен, фигуралар анимациясы, қараңғы және ашық тақырыптар.",
"gallery_phone": "Телефонда",
"gallery_desktop": "Компьютерде",
"phone_alt1": "Қосымшаның басты экраны: Rodent IV-пен кейінге қалдырылған ойын картасы, «Ойнау» және «Жаңа ойын» түймелері, өз базаңыз және PGN, ChessBase, 7z файлдары.",
"phone1": "Базаларыңыз бен файлдарыңыз; жоғарыда қалдырылған ойын күтіп тұр.",
"phone_alt2": "«Classic games» базасының ойындар тізімі: Морфи, Андерсен, Ласкер және басқалар — нәтиже, турнир, жыл және ECO коды.",
"phone2": "База ойындары: ойыншылар, нәтиже, турнир, дебют.",
"phone_alt3": "Морфидің «Опера ойыны» 8.Nc3-тен кейін, тақтаның астында түсініктеме мен нұсқа.",
"phone3": "Түсініктемелер мен нұсқалары бар түсіндірмелі ойын.",
"phone_alt4": "Stockfish талдауы: 26 тереңдікте +3.2 баға, ең жақсы жол және тақтадағы көрсеткілер.",
"phone4": "Телефондағы Stockfish: баға, ең жақсы жол, көрсеткілер.",
"phone_alt5": "«Компьютермен ойын» парағы: Rodent IV таңдалған, «Таль» мінезі, күші 2800, түс және ойыншының аты.",
"phone5": "Maia адамдай ойнайды, Rodent IV — өз стилімен.",
"phone_alt6": "«Кіммен ойнау» тізімі: Алехиннен Корчнойға дейінгі ұлы шахматшылар, әрқайсысының стилі туралы бір жол.",
"phone6": "Rodent — 22 ұлы шахматшының немесе ондаған мінездің бірі.",
"phone_alt7": "Таль стиліндегі Rodent IV 2800-мен ойын, сицилия қорғанысы, «Қайтару», «Берілу» және «Тең» түймелері.",
"phone7": "Тальмен ойын: жүрісті қайтару, берілу немесе тең ойын ұсыну.",
"btn_android": "Android үшін жүктеп алу",
"and_requires": "Альфа нұсқа. Android 12 немесе жаңарақ керек.",
"and_intro": "Бір қосымшаның екі нұсқасы: базалар мен ойындарды қараңыз, жүрістерді енгізіп, өз базаларыңызды жүргізіңіз, Maia және Rodent-пен ойнаңыз, дебюттерді үйреніңіз және Stockfish-пен талдаңыз. Ашылған файлдар тек оқылады.",

View file

@ -155,6 +155,22 @@
"shot8": "Encontre todas as partidas que chegam a uma posição, com os lances jogados a seguir e seus resultados.",
"alt9": "Configurações de tabuleiro e peças no tema claro: conjuntos de peças, notação dos lances e tabuleiros, com o tabuleiro escolhido atrás da janela.",
"shot9": "Do seu jeito: 17 conjuntos de peças, 37 tabuleiros, lances com letras ou figurinhas, animação das peças, temas escuro e claro.",
"gallery_phone": "No telefone",
"gallery_desktop": "No computador",
"phone_alt1": "A tela inicial do app: o cartão de uma partida adiada contra o Rodent IV, os botões «Jogar» e «Nova partida», a sua base e arquivos PGN, ChessBase e 7z.",
"phone1": "As suas bases e arquivos; uma partida adiada espera no topo.",
"phone_alt2": "A lista de partidas de «Classic games»: Morphy, Anderssen, Lasker e outros, com resultado, torneio, ano e código ECO.",
"phone2": "As partidas de uma base: jogadores, resultado, torneio, abertura.",
"phone_alt3": "A partida da Ópera de Morphy depois de 8.Cc3, com um comentário e uma variante sob o tabuleiro.",
"phone3": "Uma partida comentada com notas e variantes.",
"phone_alt4": "Análise do Stockfish: avaliação +3.2 na profundidade 26, a melhor linha e setas no tabuleiro.",
"phone4": "Stockfish no telefone: avaliação, melhor linha, setas.",
"phone_alt5": "A folha «Jogar contra o computador»: Rodent IV escolhido, o caráter Tal, força 2800, a cor e o nome do jogador.",
"phone5": "A Maia joga como uma pessoa, o Rodent IV com estilo.",
"phone_alt6": "A lista «Contra quem jogar»: grandes jogadores de Alekhine a Korchnoi, cada um com uma linha sobre o estilo.",
"phone6": "O Rodent como um de 22 grandes jogadores ou uma dúzia de caracteres.",
"phone_alt7": "Uma partida contra o Rodent IV 2800 no estilo de Tal, uma siciliana, com os botões Voltar, Desistir e Empate.",
"phone7": "Uma partida contra Tal: voltar lance, desistir ou propor empate.",
"btn_android": "Baixar para Android",
"and_requires": "Versão alfa. Requer Android 12 ou mais recente.",
"and_intro": "Duas versões do mesmo app: veja bases e partidas, insira lances e mantenha as suas próprias bases, jogue contra a Maia e o Rodent, aprenda uma abertura e analise com o Stockfish. Os arquivos abertos são apenas lidos.",

View file

@ -155,6 +155,22 @@
"shot8": "Найдите все партии с позицией — с ходами, которые в ней играли, и их результатами.",
"alt9": "Настройки досок и фигур в светлой теме: наборы фигур, запись ходов и доски, за окном — выбранная доска.",
"shot9": "Под себя: 17 наборов фигур, 37 досок, ходы буквами или фигурками, анимация фигур, тёмная и светлая темы.",
"gallery_phone": "На телефоне",
"gallery_desktop": "На компьютере",
"phone_alt1": "Главный экран приложения: карточка отложенной партии с Rodent IV, кнопки «Играть» и «Новая партия», своя база и файлы PGN, ChessBase и 7z.",
"phone1": "Ваши базы и файлы; отложенная партия ждёт наверху.",
"phone_alt2": "Список партий базы «Classic games»: Морфи, Андерсен, Ласкер и другие, с результатом, турниром, годом и кодом ECO.",
"phone2": "Партии базы: игроки, результат, турнир, дебют.",
"phone_alt3": "«Партия в опере» Морфи после 8.Nc3 с комментарием и вариантом под доской.",
"phone3": "Аннотированная партия с комментариями и вариантами.",
"phone_alt4": "Анализ Stockfish: оценка +3.2 на глубине 26, лучшая линия и стрелки на доске.",
"phone4": "Stockfish в телефоне: оценка, лучшая линия, стрелки.",
"phone_alt5": "Лист «Игра с компьютером»: выбран Rodent IV, характер «Таль», сила 2800, цвет и имя игрока.",
"phone5": "Maia играет как человек, Rodent IV — со стилем.",
"phone_alt6": "Список «С кем играть»: великие шахматисты от Алехина до Корчного, у каждого строка о стиле.",
"phone6": "Rodent — один из 22 великих шахматистов или дюжины характеров.",
"phone_alt7": "Партия с Rodent IV 2800 в стиле Таля, сицилианская защита, кнопки «Ход назад», «Сдаться» и «Ничья».",
"phone7": "Партия с Талем: ход назад, сдаться или предложить ничью.",
"btn_android": "Скачать для Android",
"and_requires": "Альфа-версия. Нужен Android 12 или новее.",
"and_intro": "Две сборки одного приложения: смотрите базы и партии, вводите ходы и ведите свои базы, играйте с Maia и Rodent, учите дебюты и анализируйте со Stockfish. Открытые файлы приложение только читает.",

View file

@ -155,6 +155,22 @@
"shot8": "Pozitsiyaga kelgan barcha partiyalarni keyingi yurishlar va ularning natijalari bilan toping.",
"alt9": "Yorugʻ mavzudagi taxta va figura sozlamalari: figuralar toʻplamlari, yurishlar yozuvi va taxtalar, oyna ortida tanlangan taxta.",
"shot9": "Oʻzingizga moslang: 17 ta figuralar toʻplami, 37 ta taxta, yurishlar harflarda yoki figura belgilarida, figura animatsiyasi, qorongʻi va yorugʻ mavzular.",
"gallery_phone": "Telefonda",
"gallery_desktop": "Kompyuterda",
"phone_alt1": "Ilovaning bosh ekrani: Rodent IV bilan keyinga qoldirilgan o‘yin kartasi, «O‘ynash» va «Yangi o‘yin» tugmalari, o‘z bazangiz hamda PGN, ChessBase va 7z fayllar.",
"phone1": "Bazalaringiz va fayllaringiz; tepada qoldirilgan o‘yin kutib turibdi.",
"phone_alt2": "«Classic games» bazasining o‘yinlar ro‘yxati: Morfi, Anderssen, Lasker va boshqalar — natija, turnir, yil va ECO kodi bilan.",
"phone2": "Baza o‘yinlari: o‘yinchilar, natija, turnir, debyut.",
"phone_alt3": "Morfining «Opera o‘yini» 8.Nc3 dan keyin, taxta ostida izoh va variant bilan.",
"phone3": "Izohlar va variantlar bilan izohli o‘yin.",
"phone_alt4": "Stockfish tahlili: 26-chuqurlikda +3.2 baho, eng yaxshi chiziq va taxtada strelkalar.",
"phone4": "Telefonda Stockfish: baho, eng yaxshi chiziq, strelkalar.",
"phone_alt5": "«Kompyuter bilan o‘yin» varag‘i: Rodent IV tanlangan, «Tal» xarakteri, kuch 2800, rang va o‘yinchi ismi.",
"phone5": "Maia odamdek o‘ynaydi, Rodent IV — o‘z uslubi bilan.",
"phone_alt6": "«Kim bilan o‘ynash» ro‘yxati: Alyoxindan Korchnoygacha buyuk shaxmatchilar, har biri uslubi haqida bir satr bilan.",
"phone6": "Rodent — 22 buyuk shaxmatchidan yoki o‘nlab xarakterlardan biri.",
"phone_alt7": "Tal uslubidagi Rodent IV 2800 bilan o‘yin, sitsiliya himoyasi, «Qaytarish», «Taslim bo‘lish» va «Durang» tugmalari.",
"phone7": "Tal bilan o‘yin: yurishni qaytarish, taslim bo‘lish yoki durang taklif qilish.",
"btn_android": "Android uchun yuklab olish",
"and_requires": "Alfa versiya. Android 12 yoki yangirogʻi kerak.",
"and_intro": "Bitta ilovaning ikki yig‘masi: bazalar va o‘yinlarni ko‘ring, yurishlarni kiriting va o‘z bazalaringizni yuriting, Maia va Rodent bilan o‘ynang, debyutlarni o‘rganing va Stockfish bilan tahlil qiling. Ochilgan fayllar faqat o‘qiladi.",

View file

@ -103,6 +103,13 @@
<section class="wrap block" id="screenshots">
<h2>{{t:gallery_title}}</h2>
<div id="phone-shots" hidden>
<h3 class="gallery-h">{{t:gallery_phone}}</h3>
<ol class="gallery phones">
{{phone_gallery}}
</ol>
<h3 class="gallery-h">{{t:gallery_desktop}}</h3>
</div>
<ol class="gallery">
{{gallery}}
</ol>

View file

@ -109,10 +109,16 @@ p { margin: 0 0 12px; }
.gallery a { border-radius: 8px; aspect-ratio: 16 / 9; }
.gallery img { width: 100%; height: 100%; object-fit: cover; }
.gallery p { margin: 10px 0 0; font-size: 15px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
@media (max-width: 899px) { .gallery { grid-template-columns: repeat(2, 1fr); } }
.gallery.phones { grid-template-columns: repeat(4, 1fr); margin-bottom: 48px; }
.gallery.phones a { aspect-ratio: 9 / 20; border-radius: 12px; }
.gallery.phones p { font-size: 14px; -webkit-line-clamp: 3; }
.gallery-h { font-size: 18px; color: var(--text-2); margin: 0 0 16px; }
@media (max-width: 899px) { .gallery { grid-template-columns: repeat(2, 1fr); } .gallery.phones { grid-template-columns: repeat(3, 1fr); } }
@media (max-width: 639px) {
.gallery { display: flex; overflow-x: auto; scroll-snap-type: x mandatory; gap: 12px; padding-bottom: 8px; }
.gallery li { flex: 0 0 85%; scroll-snap-align: start; }
.gallery.phones { margin-bottom: 32px; }
.gallery.phones li { flex: 0 0 44%; }
}
/* Features */

View file

@ -262,6 +262,32 @@
a.addEventListener("click", function () { remember(a.dataset.lang); });
});
// --- Android: the phone's screenshots first ---------------------------------------
// The phone screens open the gallery and the lightbox; the desktop ones follow, and
// the hero shows the four phone screens instead of the desktop window.
var phone = CP.phoneShots || [];
if (sys.os === "android" && phone.length) {
var desktop = CP.shots || [];
document.querySelectorAll("[data-shot]").forEach(function (a) {
a.dataset.shot = String(parseInt(a.dataset.shot, 10) + phone.length);
});
document.querySelectorAll("[data-phone]").forEach(function (a) { a.dataset.shot = a.dataset.phone; });
CP.shots = phone.concat(desktop);
$("phone-shots").hidden = false;
var both = -1;
desktop.forEach(function (s, i) { if (/06-android/.test(s.full)) both = i; });
var hero = document.querySelector(".hero-shot");
if (hero && both >= 0) {
var s = desktop[both], stem = s.full.replace(/\.png$/, "");
hero.querySelector("a").href = s.full;
hero.querySelector("a").dataset.shot = String(phone.length + both + 1);
hero.querySelector("source").srcset = stem + "-1280.webp 1280w, " + stem + "-1920.webp 1920w";
hero.querySelector("img").src = s.fallback;
hero.querySelector("img").alt = s.alt;
hero.querySelector("figcaption").textContent = s.caption;
}
}
// --- Lightbox --------------------------------------------------------------------
var lb = $("lightbox"), img = $("lb-img"), cap = $("lb-cap"), count = $("lb-count"), full = $("lb-full");
var shots = CP.shots || [], cur = 0, opener = null, viaHistory = false;

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB