From d3c87ae2693fb41c5d2a9b0d08571c752778ef8c Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 19 Oct 2026 21:10:22 +0300 Subject: [PATCH 1/4] Games from Lichess and Chess.com by nickname (feature branch, not released) Probe of both public APIs at start (hidden when offline or changed), lookup, download into a database per platform with resumable updates, window and shelf card. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + README.md | 1 + README.ru.md | 1 + apps/desktop/src/app.rs | 29 ++ apps/desktop/src/board_search.rs | 5 + apps/desktop/src/i18n.rs | 218 ++++++++++ apps/desktop/src/library.rs | 64 +++ apps/desktop/src/main.rs | 2 + apps/desktop/src/online.rs | 720 +++++++++++++++++++++++++++++++ apps/desktop/src/online_ui.rs | 436 +++++++++++++++++++ apps/desktop/src/settings.rs | 6 + docs/dev/desktop.md | 4 +- 12 files changed, 1493 insertions(+), 1 deletion(-) create mode 100644 apps/desktop/src/online.rs create mode 100644 apps/desktop/src/online_ui.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index cf882c7..74f66b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Your games from Lichess and Chess.com: enter the nickname (another one for Chess.com if it + differs), see what was found, download the games into a database of their own and update + it later with one click; an interrupted download continues where it stopped. Only standard + chess is kept. The feature is offered only when the sites answer: ChessPenguin asks each + for a public profile at start (no data of yours is sent), so offline it stays hidden. + ## [0.6.3] — 2026-10-19 - Import notes (for example, Chess960 games shown without moves) are a quiet grey "ℹ" now diff --git a/README.md b/README.md index beb4d64..eb57c64 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ copy PGN/FEN, save a game to a new file. - **Looks** — 17 piece sets, 37 boards (flat colours and textures), 7 sound sets, dark and light themes. +- **Your online games** — download your games from Lichess and Chess.com by nickname (no login) into a database and update it with one click. - **Languages** — English, Русский, Français, Deutsch, Español, Italiano. | Game analysis: graph and report | Engine marks and better lines | diff --git a/README.ru.md b/README.ru.md index faaa67a..15fe1d2 100644 --- a/README.ru.md +++ b/README.ru.md @@ -26,6 +26,7 @@ - **Редактирование** — ввод ходов и вариантов, повышение и удаление линий, отмена/повтор, копирование PGN/FEN, сохранение партии в новый файл. - **Оформление** — 17 наборов фигур, 37 досок (цвета и текстуры), 7 наборов звуков, тёмная и светлая тема. +- **Ваши онлайн-партии** — загрузка своих партий с Lichess и Chess.com по нику (без входа) в базу и обновление одной кнопкой. - **Языки** — English, Русский, Français, Deutsch, Español, Italiano. | Анализ партии: график и отчёт | Отметки движка и лучшие варианты | diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 26633af..084e209 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -50,6 +50,9 @@ pub struct App { /// The offer to download Stockfish when an action needs an engine. engine_offer: crate::engine_offer::EngineOffer, offer_hook_done: bool, + /// Lichess / Chess.com: which answered at start, and the download window. + online_probe: crate::online::Probe, + online: crate::online_ui::OnlineDialog, /// A position to find in a database once the game is closed. find_after_close: Option<(PathBuf, shakmaty::Chess, Vec, bool)>, allow_quit: bool, @@ -137,6 +140,8 @@ impl App { find_after_close: None, engine_offer: crate::engine_offer::EngineOffer::new(), offer_hook_done: false, + online_probe: crate::online::Probe::start(ctx), + online: crate::online_ui::OnlineDialog::from_env(), allow_quit: false, applied_dark: None, debug: DebugStartup::from_env(), @@ -725,6 +730,9 @@ impl eframe::App for App { } } else { let dbs = self.settings.databases.clone(); + self.online_probe.poll(); + self.library.online = self.online_probe.any(); + self.library.online_busy = self.online.busy(); for a in self.library.show(ui, &dbs, &self.settings) { match a { LibraryAction::OpenGame { path, index, at } => { @@ -741,6 +749,8 @@ impl eframe::App for App { } LibraryAction::PastePgn => self.paste_pgn(&ctx), LibraryAction::AddDatabases => self.pick_databases(&ctx), + LibraryAction::OnlineGames => self.online.open_with(&self.settings), + LibraryAction::UpdateOnline(p) => self.online.update(&p, &ctx), LibraryAction::RemoveDatabase(p) => { self.settings.databases.retain(|d| *d != p); self.library.forget(&p); @@ -751,6 +761,25 @@ impl eframe::App for App { } } + let (events, changed) = self + .online + .show(&ctx, &self.online_probe, &mut self.settings); + self.settings_dirty |= changed; + for e in events { + match e { + crate::online_ui::OnlineEvent::Added(p) => { + let known = self.settings.databases.contains(&p); + self.settings.touch_database(&p); + if known { + self.library.reload(&p, &ctx); + } + self.library.select_db(&p, &ctx); + self.settings_dirty = true; + } + crate::online_ui::OnlineEvent::Updated(p) => self.library.reload(&p, &ctx), + } + } + self.settings_ui.download = self.engine_offer.stage(); let (actions, changed) = self.settings_ui.show(&ctx, &mut self.settings); self.settings_dirty |= changed; diff --git a/apps/desktop/src/board_search.rs b/apps/desktop/src/board_search.rs index 9ce519f..660e588 100644 --- a/apps/desktop/src/board_search.rs +++ b/apps/desktop/src/board_search.rs @@ -890,6 +890,11 @@ impl Background { pub fn progress(&self) -> usize { self.progress.load(Ordering::Relaxed) } + + /// Asks the work to stop; its result still arrives. + pub fn cancel(&self) { + self.cancel.store(true, Ordering::Relaxed); + } } impl Drop for Background { diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index d8b2861..7abc94c 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -1573,6 +1573,224 @@ const ROWS: &[[&str; 6]] = &[ "La búsqueda por posición necesita unos {n} MB de memoria libre para esta base.", "La ricerca per posizione richiede circa {n} MB di memoria libera per questa base.", ], + [ + "(already here: {n})", + "(уже есть: {n})", + "(déjà ici : {n})", + "(schon vorhanden: {n})", + "(ya aquí: {n})", + "(già presenti: {n})", + ], + [ + "A different nickname on Chess.com", + "На Chess.com другой ник", + "Un autre pseudo sur Chess.com", + "Anderer Nickname auf Chess.com", + "Otro apodo en Chess.com", + "Un altro nickname su Chess.com", + ], + [ + "Download your online games by nickname into a database", + "Загрузить свои онлайн-партии по нику в базу", + "Télécharger vos parties en ligne par pseudo dans une base", + "Ihre Online-Partien per Nickname in eine Datenbank laden", + "Descargar tus partidas en línea por apodo a una base", + "Scarica le tue partite online per nickname in una base", + ], + [ + "Fetch the games played since the last download", + "Загрузить партии, сыгранные после прошлой загрузки", + "Récupérer les parties jouées depuis le dernier téléchargement", + "Die seit dem letzten Download gespielten Partien holen", + "Descargar las partidas jugadas desde la última descarga", + "Scarica le partite giocate dall'ultimo download", + ], + ["Find", "Найти", "Rechercher", "Suchen", "Buscar", "Cerca"], + [ + "Games from", + "Партии с", + "Parties de", + "Partien von", + "Partidas de", + "Partite da", + ], + [ + "Letters, digits, _ and -, 2 to 30 characters", + "Латиница, цифры, _ и -, от 2 до 30 символов", + "Lettres, chiffres, _ et -, de 2 à 30 caractères", + "Buchstaben, Ziffern, _ und -, 2 bis 30 Zeichen", + "Letras, dígitos, _ y -, de 2 a 30 caracteres", + "Lettere, cifre, _ e -, da 2 a 30 caratteri", + ], + ["Nickname", "Ник", "Pseudo", "Nickname", "Apodo", "Nickname"], + [ + "Nickname on Chess.com", + "Ник на Chess.com", + "Pseudo sur Chess.com", + "Nickname auf Chess.com", + "Apodo en Chess.com", + "Nickname su Chess.com", + ], + [ + "Stop", + "Остановить", + "Arrêter", + "Anhalten", + "Detener", + "Ferma", + ], + [ + "The same nickname", + "Тот же ник", + "Le même pseudo", + "Derselbe Nickname", + "El mismo apodo", + "Lo stesso nickname", + ], + [ + "What is downloaded is kept; Update continues from there", + "Скачанное сохранится; «Обновить» продолжит с этого места", + "Ce qui est téléchargé est conservé ; « Mettre à jour » reprend à partir de là", + "Bereits Geladenes bleibt; „Aktualisieren“ setzt dort fort", + "Lo descargado se conserva; «Actualizar» continúa desde ahí", + "Quanto scaricato resta; «Aggiorna» riprende da lì", + ], + [ + "Your games from Lichess and Chess.com", + "Ваши партии с Lichess и Chess.com", + "Vos parties de Lichess et Chess.com", + "Ihre Partien von Lichess und Chess.com", + "Tus partidas de Lichess y Chess.com", + "Le tue partite da Lichess e Chess.com", + ], + [ + "Your online games become a database here, to search and analyse. Only the nickname is needed, no login.", + "Ваши онлайн-партии станут базой здесь: искать, разбирать, анализировать. Нужен только ник, входить в аккаунт не нужно.", + "Vos parties en ligne deviennent une base ici, pour chercher et analyser. Seul le pseudo est nécessaire, sans connexion.", + "Ihre Online-Partien werden hier zu einer Datenbank zum Suchen und Analysieren. Nur der Nickname wird gebraucht, keine Anmeldung.", + "Tus partidas en línea se convierten aquí en una base para buscar y analizar. Solo hace falta el apodo, sin iniciar sesión.", + "Le tue partite online diventano qui una base da cercare e analizzare. Serve solo il nickname, senza accesso.", + ], + [ + "as on the site", + "как на сайте", + "comme sur le site", + "wie auf der Seite", + "como en el sitio", + "come sul sito", + ], + [ + "updating…", + "обновляется…", + "mise à jour…", + "wird aktualisiert…", + "actualizando…", + "aggiornamento…", + ], + [ + "{p}: +{n} games, {t} in «{name}»", + "{p}: +{n} партий, всего {t} в «{name}»", + "{p} : +{n} parties, {t} dans « {name} »", + "{p}: +{n} Partien, {t} in „{name}“", + "{p}: +{n} partidas, {t} en «{name}»", + "{p}: +{n} partite, {t} in «{name}»", + ], + [ + "{p}: failed ({e})", + "{p}: не получилось ({e})", + "{p} : échec ({e})", + "{p}: fehlgeschlagen ({e})", + "{p}: error ({e})", + "{p}: non riuscito ({e})", + ], + [ + "{p}: nothing new, {t} games in «{name}»", + "{p}: новых нет, {t} партий в «{name}»", + "{p} : rien de nouveau, {t} parties dans « {name} »", + "{p}: nichts Neues, {t} Partien in „{name}“", + "{p}: nada nuevo, {t} partidas en «{name}»", + "{p}: niente di nuovo, {t} partite in «{name}»", + ], + [ + "{p}: stopped, {t} games kept in «{name}»", + "{p}: остановлено, сохранено {t} партий в «{name}»", + "{p} : arrêté, {t} parties conservées dans « {name} »", + "{p}: angehalten, {t} Partien in „{name}“ behalten", + "{p}: detenido, {t} partidas guardadas en «{name}»", + "{p}: fermato, {t} partite conservate in «{name}»", + ], + [ + "{p}: the site asks to wait a minute; then try again", + "{p}: сайт просит подождать минуту, потом попробуйте снова", + "{p} : le site demande d'attendre une minute, puis réessayez", + "{p}: die Seite bittet um eine Minute Geduld, dann erneut versuchen", + "{p}: el sitio pide esperar un minuto; luego inténtalo de nuevo", + "{p}: il sito chiede di attendere un minuto, poi riprova", + ], + [ + "{p}: {name} — games of {m} months", + "{p}: {name} — партии за {m} мес.", + "{p} : {name} — parties de {m} mois", + "{p}: {name} — Partien aus {m} Monaten", + "{p}: {name} — partidas de {m} meses", + "{p}: {name} — partite di {m} mesi", + ], + [ + "{p}: {name} — up to {n} games (about {m} min the first time)", + "{p}: {name} — до {n} партий (первый раз около {m} мин)", + "{p} : {name} — jusqu'à {n} parties (environ {m} min la première fois)", + "{p}: {name} — bis zu {n} Partien (beim ersten Mal etwa {m} Min.)", + "{p}: {name} — hasta {n} partidas (la primera vez, unos {m} min)", + "{p}: {name} — fino a {n} partite (la prima volta circa {m} min)", + ], + [ + "{p}: {n} games", + "{p}: {n} партий", + "{p} : {n} parties", + "{p}: {n} Partien", + "{p}: {n} partidas", + "{p}: {n} partite", + ], + [ + "{p}: {n} of up to {t} games", + "{p}: {n} из примерно {t} партий", + "{p} : {n} sur environ {t} parties", + "{p}: {n} von bis zu {t} Partien", + "{p}: {n} de hasta {t} partidas", + "{p}: {n} di circa {t} partite", + ], + [ + "✖ {p}: no answer ({e})", + "✖ {p}: нет ответа ({e})", + "✖ {p} : pas de réponse ({e})", + "✖ {p}: keine Antwort ({e})", + "✖ {p}: sin respuesta ({e})", + "✖ {p}: nessuna risposta ({e})", + ], + [ + "✖ {p}: no such player", + "✖ {p}: игрок не найден", + "✖ {p} : joueur introuvable", + "✖ {p}: Spieler nicht gefunden", + "✖ {p}: jugador no encontrado", + "✖ {p}: giocatore non trovato", + ], + [ + "⟳ Update", + "⟳ Обновить", + "⟳ Mettre à jour", + "⟳ Aktualisieren", + "⟳ Actualizar", + "⟳ Aggiorna", + ], + [ + "⬇ Download ({n})", + "⬇ Загрузить ({n})", + "⬇ Télécharger ({n})", + "⬇ Herunterladen ({n})", + "⬇ Descargar ({n})", + "⬇ Scarica ({n})", + ], [ "Checking engine…", "Проверка движка…", diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 3aa7bbb..5cca2ae 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -58,6 +58,10 @@ pub enum LibraryAction { NewGame, PastePgn, AddDatabases, + /// The window for downloading games from Lichess and Chess.com. + OnlineGames, + /// Fetch the new games of an online database. + UpdateOnline(PathBuf), RemoveDatabase(PathBuf), OpenSettings, } @@ -197,6 +201,10 @@ pub struct Library { view: Vec, view_key: Option<(PathBuf, String, SortKey, bool)>, scroll_to_selected: bool, + /// Lichess or Chess.com answered at start (the online games are offered). + pub online: bool, + /// Online databases being downloaded or updated. + pub online_busy: Vec, } impl Library { @@ -216,6 +224,8 @@ impl Library { view: Vec::new(), view_key: None, scroll_to_selected: false, + online: false, + online_busy: Vec::new(), } } @@ -288,6 +298,18 @@ impl Library { } } + /// Reads a database again (its file changed), keeping it selected if it was. + pub fn reload(&mut self, path: &Path, ctx: &egui::Context) { + let selected = self.selected_db.as_deref() == Some(path); + self.forget(path); + self.small.remove(path); + if selected { + self.select_db(path, ctx); + } else { + self.load(path, ctx); + } + } + pub fn forget(&mut self, path: &Path) { self.info.remove(path); self.large.remove(path); @@ -566,6 +588,14 @@ impl Library { { actions.push(LibraryAction::AddDatabases); } + if self.online + && ui + .button("🌐") + .on_hover_text(tr("Download your online games by nickname into a database")) + .clicked() + { + actions.push(LibraryAction::OnlineGames); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.button(tr("⚙ Settings")).clicked() { actions.push(LibraryAction::OpenSettings); @@ -629,6 +659,27 @@ impl Library { { actions.push(LibraryAction::AddDatabases); } + if self.online { + let (rect, resp) = ui.allocate_exact_size(vec2(150.0, 64.0), Sense::click()); + let visuals = ui.style().interact(&resp); + ui.painter() + .rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside); + for (dy, text) in [(-9.0, tr("Games from")), (9.0, "Lichess · Chess.com")] { + ui.painter().text( + rect.center() + vec2(0.0, dy), + egui::Align2::CENTER_CENTER, + text, + egui::FontId::proportional(14.0), + visuals.text_color(), + ); + } + if resp + .on_hover_text(tr("Download your online games by nickname into a database")) + .clicked() + { + actions.push(LibraryAction::OnlineGames); + } + } }); ui.add_space(8.0); } @@ -841,6 +892,19 @@ impl Library { if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() { self.notes_open = Some(path.clone()); } + if crate::online::is_online(&path) { + if self.online_busy.contains(&path) { + ui.add(egui::Spinner::new().size(14.0)); + ui.label(RichText::new(tr("updating…")).weak()); + } else if self.online + && ui + .small_button(tr("⟳ Update")) + .on_hover_text(tr("Fetch the games played since the last download")) + .clicked() + { + actions.push(LibraryAction::UpdateOnline(path.clone())); + } + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let small = self .small diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 531f84c..69966c7 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -15,6 +15,8 @@ mod i18n; mod large_db; mod library; mod notation; +mod online; +mod online_ui; mod report; mod review; mod settings; diff --git a/apps/desktop/src/online.rs b/apps/desktop/src/online.rs new file mode 100644 index 0000000..63f9aef --- /dev/null +++ b/apps/desktop/src/online.rs @@ -0,0 +1,720 @@ +//! The user's games from Lichess and Chess.com, by nickname (no login): each platform's +//! games become a PGN database of their own in `/online/`, with a small +//! state file next to it so that "Update" fetches only the new games (and continues an +//! interrupted download). Both public APIs are probed at start; a platform that does not +//! answer as expected (offline, the API changed) is simply not offered. +//! +//! Lichess: `GET /api/games/user/{name}` as NDJSON (`pgnInJson`), oldest first, from +//! `since`; anonymous requests are throttled to 20 games a second. Chess.com: the list of +//! monthly archives, then each month's games as JSON (their PGN inside), from the last +//! month already fetched. Only standard chess is kept (variants are not supported). + +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Platform { + Lichess, + ChessCom, +} + +impl Platform { + pub const ALL: [Platform; 2] = [Platform::Lichess, Platform::ChessCom]; + + pub fn name(self) -> &'static str { + match self { + Platform::Lichess => "Lichess", + Platform::ChessCom => "Chess.com", + } + } + + fn index(self) -> usize { + match self { + Platform::Lichess => 0, + Platform::ChessCom => 1, + } + } +} + +/// Lichess's anonymous export rate (games per second), for the time estimate. +pub const LICHESS_RATE: u64 = 20; + +fn agent(stream: bool) -> ureq::Agent { + let config = ureq::Agent::config_builder() + .user_agent(format!( + "ChessPenguin/{} (+https://chess.vrubel.xyz)", + env!("CARGO_PKG_VERSION") + )) + .http_status_as_error(false) + .timeout_connect(Some(Duration::from_secs(10))) + .timeout_recv_response(Some(Duration::from_secs(30))) + // A long export is one response: no limit on the body, only on the rest. + .timeout_recv_body(if stream { + None + } else { + Some(Duration::from_secs(60)) + }) + .build(); + ureq::Agent::new_with_config(config) +} + +/// What went wrong talking to a platform. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Failure { + /// No answer (offline, DNS, TLS, timeout). + Network(String), + /// "Too many requests": the platform asks to wait. + RateLimited, + /// An answer we do not understand (the API changed). + Unexpected(String), + /// Writing the database failed. + Disk(String), +} + +impl std::fmt::Display for Failure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Failure::Network(e) => write!(f, "network: {e}"), + Failure::RateLimited => write!(f, "rate limited"), + Failure::Unexpected(e) => write!(f, "unexpected answer: {e}"), + Failure::Disk(e) => write!(f, "{e}"), + } + } +} + +/// GET returning (status, body); the body of an error status is not read. +fn get(url: &str) -> Result<(u16, String), Failure> { + let mut resp = agent(false) + .get(url) + .header("Accept", "application/json") + .call() + .map_err(|e| Failure::Network(e.to_string()))?; + let status = resp.status().as_u16(); + if status == 429 { + return Err(Failure::RateLimited); + } + if status != 200 { + return Ok((status, String::new())); + } + let body = resp + .body_mut() + .with_config() + .limit(64 << 20) + .read_to_string() + .map_err(|e| Failure::Network(e.to_string()))?; + Ok((status, body)) +} + +fn json(url: &str) -> Result, Failure> { + match get(url)? { + (200, body) => serde_json::from_str(&body) + .map(Some) + .map_err(|e| Failure::Unexpected(e.to_string())), + (404, _) => Ok(None), + (code, _) => Err(Failure::Unexpected(format!("HTTP {code}"))), + } +} + +/// Whether the platform answers the way this code expects: the profile of an account +/// that has always existed (Lichess's own, Chess.com's founder's). +pub fn probe(p: Platform) -> bool { + let url = match p { + Platform::Lichess => "https://lichess.org/api/user/lichess", + Platform::ChessCom => "https://api.chess.com/pub/player/erik", + }; + matches!(json(url), Ok(Some(v)) if probe_answer_ok(p, &v)) +} + +/// The probe's answer has the fields this code relies on. +fn probe_answer_ok(p: Platform, v: &Value) -> bool { + match p { + Platform::Lichess => { + v["id"] == "lichess" && v["username"].is_string() && v["count"]["all"].is_u64() + } + Platform::ChessCom => v["player_id"].is_u64() && v["username"] == "erik", + } +} + +/// Both platforms probed (in parallel); `[lichess, chess.com]`. +pub fn probe_all() -> [bool; 2] { + std::thread::scope(|s| { + let l = s.spawn(|| probe(Platform::Lichess)); + let c = s.spawn(|| probe(Platform::ChessCom)); + [l.join().unwrap_or(false), c.join().unwrap_or(false)] + }) +} + +/// A nickname both platforms could have: 2–30 letters, digits, `_` or `-`. +pub fn valid_nick(nick: &str) -> bool { + (2..=30).contains(&nick.len()) + && nick + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') +} + +/// An account found by nickname. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Account { + pub platform: Platform, + /// As the platform spells it. + pub username: String, + /// Lichess: games of the account (all kinds, so an upper bound for ours). + pub games: Option, + /// Chess.com: months with games. + pub months: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Lookup { + Found(Account), + NotFound, + Failed(Failure), +} + +/// Looks the nickname up on the platform. +pub fn lookup(p: Platform, nick: &str) -> Lookup { + let nick = nick.trim(); + if !valid_nick(nick) { + return Lookup::NotFound; + } + let result = match p { + Platform::Lichess => json(&format!("https://lichess.org/api/user/{nick}")).map(|v| { + v.filter(|v| v["disabled"] != true).and_then(|v| { + Some(Account { + platform: p, + username: v["username"].as_str()?.to_owned(), + games: v["count"]["all"].as_u64(), + months: None, + }) + }) + }), + Platform::ChessCom => { + let lower = nick.to_ascii_lowercase(); + json(&format!("https://api.chess.com/pub/player/{lower}")).and_then(|v| { + let Some(username) = v.and_then(|v| v["username"].as_str().map(str::to_owned)) + else { + return Ok(None); + }; + // Chess.com answers in lower case; the user's spelling reads better. + let username = if username.eq_ignore_ascii_case(nick) { + nick.to_owned() + } else { + username + }; + let months = archives(&lower)?.len(); + Ok(Some(Account { + platform: p, + username, + games: None, + months: Some(months), + })) + }) + } + }; + match result { + Ok(Some(a)) => Lookup::Found(a), + Ok(None) => Lookup::NotFound, + Err(e) => Lookup::Failed(e), + } +} + +/// Chess.com's monthly archive URLs of a player, oldest first. +fn archives(lower: &str) -> Result, Failure> { + let v = json(&format!( + "https://api.chess.com/pub/player/{lower}/games/archives" + ))? + .ok_or_else(|| Failure::Unexpected("no archives".into()))?; + let list = v["archives"] + .as_array() + .ok_or_else(|| Failure::Unexpected("archives".into()))?; + Ok(list + .iter() + .filter_map(|u| u.as_str().map(str::to_owned)) + .collect()) +} + +/// Where the online databases live. +pub fn dir() -> Option { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("online")) +} + +/// The database file of an account: "Name (Lichess).pgn". +pub fn database_path(p: Platform, username: &str) -> Option { + dir().map(|d| d.join(format!("{username} ({}).pgn", p.name()))) +} + +fn state_path(pgn: &Path) -> PathBuf { + pgn.with_extension("online.json") +} + +/// What has been fetched into a database, for the next update. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct State { + pub platform: Option, + pub username: String, + /// Games written so far. + pub games: u64, + /// Lichess: creation time (ms) of the newest game fetched. + pub lichess_last: Option, + /// Chess.com: the newest month fetched ("2026/10") and the end time (s) of its + /// last game fetched. + pub chesscom_month: Option, + pub chesscom_last_end: Option, +} + +impl State { + pub fn load(pgn: &Path) -> Option { + let text = std::fs::read_to_string(state_path(pgn)).ok()?; + serde_json::from_str::(&text) + .ok() + .filter(|s| s.platform.is_some()) + } + + fn save(&self, pgn: &Path) -> Result<(), Failure> { + let text = serde_json::to_string_pretty(self).map_err(|e| Failure::Disk(e.to_string()))?; + let path = state_path(pgn); + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, text) + .and_then(|_| std::fs::rename(&tmp, &path)) + .map_err(|e| Failure::Disk(e.to_string())) + } +} + +/// An online database (it has a state file). +pub fn is_online(pgn: &Path) -> bool { + dir().is_some_and(|d| pgn.parent() == Some(d.as_path())) && state_path(pgn).exists() +} + +/// The result of a download. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Done { + pub path: PathBuf, + /// Games added by this run, and in the database now. + pub added: u64, + pub total: u64, + /// Stopped by the user; what was fetched is kept and the next update continues. + pub cancelled: bool, +} + +/// Appends games to the database file and keeps the state in step. +struct Writer { + path: PathBuf, + file: std::io::BufWriter, + state: State, + added: u64, +} + +impl Writer { + fn open(path: &Path, state: State) -> Result { + let disk = |e: std::io::Error| Failure::Disk(e.to_string()); + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).map_err(disk)?; + } + let file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .map_err(disk)?; + Ok(Writer { + path: path.to_owned(), + file: std::io::BufWriter::new(file), + state, + added: 0, + }) + } + + fn game(&mut self, pgn: &str) -> Result<(), Failure> { + let pgn = pgn.trim(); + if pgn.is_empty() { + return Ok(()); + } + self.file + .write_all(pgn.as_bytes()) + .and_then(|_| self.file.write_all(b"\n\n")) + .map_err(|e| Failure::Disk(e.to_string()))?; + self.added += 1; + self.state.games += 1; + Ok(()) + } + + /// Makes what was written durable, the state last (it never runs ahead of the file). + fn commit(&mut self) -> Result<(), Failure> { + self.file + .flush() + .map_err(|e| Failure::Disk(e.to_string()))?; + self.state.save(&self.path) + } + + fn done(mut self, cancelled: bool) -> Result { + self.commit()?; + Ok(Done { + path: self.path, + added: self.added, + total: self.state.games, + cancelled, + }) + } +} + +/// Fetches the games of `account` new since the last run into its database; `progress` +/// counts the games added. Cancelling keeps what was fetched. +pub fn download( + account: &Account, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result { + let path = database_path(account.platform, &account.username) + .ok_or_else(|| Failure::Disk("no data directory".into()))?; + download_to(account, &path, progress, cancel) +} + +/// [`download`] into the database at `path`. +fn download_to( + account: &Account, + path: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result { + let path = path.to_owned(); + let state = State::load(&path).unwrap_or_else(|| { + // A database without its state: start it anew rather than append duplicates. + let _ = std::fs::remove_file(&path); + State { + platform: Some(account.platform), + username: account.username.clone(), + ..State::default() + } + }); + let mut w = Writer::open(&path, state)?; + let cancelled = match account.platform { + Platform::Lichess => lichess(&mut w, progress, cancel), + Platform::ChessCom => chesscom(&mut w, progress, cancel), + }; + match cancelled { + Ok(c) => w.done(c), + Err(e) => { + // Keep what arrived before the failure; the next update continues. + let _ = w.commit(); + Err(e) + } + } +} + +/// `Ok(true)` when cancelled. +fn lichess(w: &mut Writer, progress: &AtomicUsize, cancel: &AtomicBool) -> Result { + let mut url = format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&pgnInJson=true\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence\ + &clocks=false&evals=false&opening=true", + w.state.username + ); + if let Some(last) = w.state.lichess_last { + url.push_str(&format!("&since={}", last + 1)); + } + let resp = agent(true) + .get(&url) + .header("Accept", "application/x-ndjson") + .call() + .map_err(|e| Failure::Network(e.to_string()))?; + match resp.status().as_u16() { + 200 => {} + 429 => return Err(Failure::RateLimited), + code => return Err(Failure::Unexpected(format!("HTTP {code}"))), + } + let reader = BufReader::new(resp.into_body().into_reader()); + for (n, line) in reader.lines().enumerate() { + if cancel.load(Ordering::Relaxed) { + return Ok(true); + } + let line = line.map_err(|e| Failure::Network(e.to_string()))?; + if line.trim().is_empty() { + continue; + } + let v: Value = + serde_json::from_str(&line).map_err(|e| Failure::Unexpected(e.to_string()))?; + let (Some(pgn), Some(created)) = (v["pgn"].as_str(), v["createdAt"].as_i64()) else { + return Err(Failure::Unexpected( + "a game without pgn or createdAt".into(), + )); + }; + if v["variant"] + .as_str() + .is_none_or(|x| x == "standard" || x == "fromPosition") + { + w.game(pgn)?; + progress.fetch_add(1, Ordering::Relaxed); + } + w.state.lichess_last = Some(created); + if n % 100 == 99 { + w.commit()?; + } + } + Ok(false) +} + +/// `Ok(true)` when cancelled. +fn chesscom(w: &mut Writer, progress: &AtomicUsize, cancel: &AtomicBool) -> Result { + let lower = w.state.username.to_ascii_lowercase(); + let months = archives(&lower)?; + for url in months { + // ".../games/2026/10" → "2026/10"; months before the last fetched are done. + let month = url.rsplitn(3, '/').take(2).collect::>(); + let month = format!( + "{}/{}", + month.get(1).unwrap_or(&""), + month.first().unwrap_or(&"") + ); + if w.state.chesscom_month.as_ref().is_some_and(|m| month < *m) { + continue; + } + if cancel.load(Ordering::Relaxed) { + return Ok(true); + } + let v = json(&url)?.ok_or_else(|| Failure::Unexpected(format!("{month}: not found")))?; + let games = v["games"] + .as_array() + .ok_or_else(|| Failure::Unexpected(format!("{month}: no games")))?; + let mut list: Vec<(i64, &str)> = games + .iter() + .filter(|g| g["rules"] == "chess") + .filter_map(|g| Some((g["end_time"].as_i64()?, g["pgn"].as_str()?))) + .collect(); + list.sort_by_key(|(t, _)| *t); + let same_month = w.state.chesscom_month.as_deref() == Some(month.as_str()); + let last = if same_month { + w.state.chesscom_last_end + } else { + None + }; + for (end, pgn) in list { + if last.is_some_and(|l| end <= l) { + continue; + } + w.game(pgn)?; + progress.fetch_add(1, Ordering::Relaxed); + w.state.chesscom_last_end = Some(end); + } + // The mark moves to this month even when it had no standard games (the end + // time then still belongs to an earlier month and is not compared). + w.state.chesscom_month = Some(month); + w.commit()?; + } + Ok(false) +} + +/// The probe results and what the window shows, kept by the application. +pub struct Probe { + job: Option>, + pub available: [bool; 2], + /// When the last probe finished (a platform that did not answer is asked again + /// after [`Probe::RETRY`]: the machine may have come online). + last: Option, + ctx: egui::Context, +} + +impl Probe { + const RETRY: Duration = Duration::from_secs(300); + + /// Starts probing both platforms in the background. + pub fn start(ctx: &egui::Context) -> Probe { + let mut p = Probe { + job: None, + available: [false; 2], + last: None, + ctx: ctx.clone(), + }; + p.spawn(); + p + } + + fn spawn(&mut self) { + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = self.ctx.clone(); + let spawned = std::thread::Builder::new() + .name("online-probe".into()) + .spawn(move || { + let _ = tx.send(probe_all()); + ctx.request_repaint(); + }); + self.job = spawned.ok().map(|_| rx); + } + + pub fn poll(&mut self) { + if let Some(rx) = &self.job + && let Ok(a) = rx.try_recv() + { + // A platform that answered once stays offered for the session (a later + // failure shows as an error in the window). + for (have, now) in self.available.iter_mut().zip(a) { + *have |= now; + } + self.job = None; + self.last = Some(std::time::Instant::now()); + } + if self.job.is_none() + && !self.available.iter().all(|a| *a) + && self.last.is_some_and(|t| t.elapsed() >= Self::RETRY) + { + self.spawn(); + } + } + + pub fn any(&self) -> bool { + self.available.iter().any(|a| *a) + } + + pub fn has(&self, p: Platform) -> bool { + self.available[p.index()] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Against the real sites, with an account given by `CP_ONLINE_NICK` (kept out of + /// the repository): lookup, an interrupted Lichess download continued without gaps + /// or duplicates, a full Chess.com download, and an update that adds nothing. Run + /// with `CP_ONLINE_NICK= cargo test -p chesspenguin online_live -- --ignored --nocapture`. + #[test] + #[ignore] + fn online_live() { + let Ok(nick) = std::env::var("CP_ONLINE_NICK") else { + eprintln!("skipped: no CP_ONLINE_NICK"); + return; + }; + assert_eq!(probe_all(), [true, true], "both platforms answer"); + assert_eq!( + lookup(Platform::Lichess, "no-such-player-cp-x9"), + Lookup::NotFound + ); + let dir = std::env::temp_dir().join(format!("cp-online-live-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let read_db = |path: &Path| { + let db = chess_core::PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false)) + .expect("opens"); + let mut sites = Vec::new(); + let mut problems = 0; + for i in 0..db.len() { + let g = db.load_game(i).expect("game"); + problems += usize::from(!g.diagnostics.is_empty()); + let e = &db.entries()[i]; + let site = e.tag("Link").or_else(|| e.tag("Site")).unwrap_or_default(); + sites.push(site.to_owned()); + } + (db.len(), sites, problems) + }; + + // Lichess: stop after about 150 games, twice, then compare with what the + // site says about those games: no gaps, no duplicates. + let Lookup::Found(li) = lookup(Platform::Lichess, &nick) else { + panic!("not on Lichess"); + }; + let path = dir.join("li.pgn"); + for round in 1..=2 { + let progress = AtomicUsize::new(0); + let cancel = AtomicBool::new(false); + let done = std::thread::scope(|s| { + s.spawn(|| { + while progress.load(Ordering::Relaxed) < 150 { + std::thread::sleep(Duration::from_millis(50)); + } + cancel.store(true, Ordering::Relaxed); + }); + download_to(&li, &path, &progress, &cancel).expect("downloads") + }); + eprintln!("lichess round {round}: {done:?}"); + assert!(done.cancelled && done.added >= 150); + } + let (n, sites, problems) = read_db(&path); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + assert_eq!(State::load(&path).unwrap().games as usize, n); + eprintln!("lichess: {n} games after two interrupted runs, {problems} with diagnostics"); + // The same games as one uninterrupted request for that many. + let (code, body) = get(&format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&max={n}\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&moves=false", + li.username + )) + .expect("answers"); + assert_eq!(code, 200); + // Asked for JSON, Lichess answers one game per line. + let expected: Vec = body + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter_map(|v| Some(format!("https://lichess.org/{}", v["id"].as_str()?))) + .collect(); + assert_eq!(sites, expected, "the first {n} games, in order"); + + // Chess.com: everything, then an update that finds nothing new. + let Lookup::Found(cc) = lookup(Platform::ChessCom, &nick) else { + panic!("not on Chess.com"); + }; + let path = dir.join("cc.pgn"); + let never = AtomicBool::new(false); + let done = download_to(&cc, &path, &AtomicUsize::new(0), &never).expect("downloads"); + eprintln!("chess.com: {done:?}"); + assert!(!done.cancelled && done.total > 0); + let again = download_to(&cc, &path, &AtomicUsize::new(0), &never).expect("updates"); + assert_eq!((again.added, again.total), (0, done.total)); + let (n, sites, problems) = read_db(&path); + assert_eq!(n as u64, done.total); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + eprintln!("chess.com: {n} games, {problems} with diagnostics"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn probe_answers() { + let li: Value = serde_json::from_str( + r#"{"id":"lichess","username":"Lichess","count":{"all":0,"rated":0}}"#, + ) + .unwrap(); + assert!(probe_answer_ok(Platform::Lichess, &li)); + // A changed API (renamed or missing fields) is not offered. + let changed: Value = + serde_json::from_str(r#"{"id":"lichess","username":"Lichess","games":0}"#).unwrap(); + assert!(!probe_answer_ok(Platform::Lichess, &changed)); + let cc: Value = + serde_json::from_str(r#"{"player_id":41,"username":"erik","status":"staff"}"#).unwrap(); + assert!(probe_answer_ok(Platform::ChessCom, &cc)); + let html = Value::String("maintenance".into()); + assert!(!probe_answer_ok(Platform::ChessCom, &html)); + assert!(!probe_answer_ok(Platform::Lichess, &html)); + } + + #[test] + fn nicknames() { + assert!(valid_nick("Magnus_C-1")); + assert!(!valid_nick("a")); + assert!(!valid_nick("bad nick")); + assert!(!valid_nick("../etc")); + assert!(!valid_nick(&"x".repeat(31))); + } + + #[test] + fn state_round_trip() { + let dir = std::env::temp_dir().join(format!("cp-online-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let pgn = dir.join("Someone (Lichess).pgn"); + let s = State { + platform: Some(Platform::Lichess), + username: "Someone".into(), + games: 3, + lichess_last: Some(1_700_000_000_000), + ..State::default() + }; + s.save(&pgn).unwrap(); + assert_eq!(State::load(&pgn), Some(s)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src/online_ui.rs b/apps/desktop/src/online_ui.rs new file mode 100644 index 0000000..8211585 --- /dev/null +++ b/apps/desktop/src/online_ui.rs @@ -0,0 +1,436 @@ +//! The window "Games from Lichess and Chess.com": one nickname (another one for +//! Chess.com if it differs), the platforms to look on, what was found, then the +//! downloads with their progress. Only the platforms that answered the probe at start +//! are offered (`online::Probe`). + +use egui::{RichText, Ui}; + +use crate::board_search::Background; +use crate::i18n::{tr, trf}; +use crate::online::{self, Account, Done, Failure, Lookup, Platform, Probe}; +use crate::settings::Settings; + +/// What the window asks of the application. +pub enum OnlineEvent { + /// A database was downloaded (or partly, then cancelled): put it on the shelf. + Added(std::path::PathBuf), + /// A database got new games: reload it. + Updated(std::path::PathBuf), +} + +struct Job { + account: Account, + /// Updating a database already on the shelf (not a first download). + update: bool, + work: Background>, +} + +#[derive(Default)] +pub struct OnlineDialog { + pub open: bool, + nick: String, + /// A different nickname on Chess.com, when asked for. + other: Option, + pick: [bool; 2], + lookup: Option>>, + found: Vec<(Platform, Lookup)>, + /// The nicknames `found` answers. + found_for: (String, String), + jobs: Vec, + results: Vec<(Platform, String, Result)>, + /// Dev hook (screenshots): look the nickname up once the probe answered, and + /// download what was found. + auto_find: bool, + auto_download: bool, +} + +fn count(n: u64) -> String { + crate::large_db::grouped(n as usize) +} + +impl OnlineDialog { + /// Opens the window with the nicknames used last time. + pub fn open_with(&mut self, settings: &Settings) { + if !self.open && self.jobs.is_empty() && self.lookup.is_none() { + self.nick = settings.online_nick.clone(); + self.other = settings.online_nick_chesscom.clone(); + self.pick = [true, true]; + self.found.clear(); + } + self.open = true; + } + + /// Dev hook: `CP_ONLINE=` opens the window and looks the nickname up, + /// `CP_ONLINE_DOWNLOAD=1` then downloads (screenshots, manual checks). + pub fn from_env() -> OnlineDialog { + let mut d = OnlineDialog::default(); + if let Ok(nick) = std::env::var("CP_ONLINE") { + d.open = true; + d.nick = nick; + d.pick = [true, true]; + d.auto_find = true; + d.auto_download = std::env::var("CP_ONLINE_DOWNLOAD").is_ok(); + } + d + } + + /// Databases being downloaded or updated. + pub fn busy(&self) -> Vec { + self.jobs + .iter() + .filter_map(|j| online::database_path(j.account.platform, &j.account.username)) + .collect() + } + + /// Fetches the new games of an online database on the shelf. + pub fn update(&mut self, path: &std::path::Path, ctx: &egui::Context) { + let Some(state) = online::State::load(path) else { + return; + }; + let Some(platform) = state.platform else { + return; + }; + if self.busy().iter().any(|p| p == path) { + return; + } + let account = Account { + platform, + username: state.username, + games: None, + months: None, + }; + self.start(account, true, ctx); + } + + fn start(&mut self, account: Account, update: bool, ctx: &egui::Context) { + let now = ctx.input(|i| i.time); + let a = account.clone(); + if let Some(work) = Background::spawn(ctx, now, move |progress, cancel| { + Some(online::download(&a, progress, cancel)) + }) { + self.jobs.push(Job { + account, + update, + work, + }); + } + } + + fn nick_for(&self, p: Platform) -> String { + match (p, &self.other) { + (Platform::ChessCom, Some(o)) => o.trim().to_owned(), + _ => self.nick.trim().to_owned(), + } + } + + /// Collects finished work; the window itself when open. + pub fn show( + &mut self, + ctx: &egui::Context, + probe: &Probe, + settings: &mut Settings, + ) -> (Vec, bool) { + let mut events = Vec::new(); + let mut changed = false; + if let Some(l) = &self.lookup + && let Some(r) = l.poll() + { + self.found = r.unwrap_or_default(); + self.lookup = None; + } + let mut i = 0; + while i < self.jobs.len() { + if let Some(r) = self.jobs[i].work.poll() { + let job = self.jobs.remove(i); + let r = r.unwrap_or(Err(Failure::Network("stopped".into()))); + if let Ok(done) = &r { + if job.update { + if done.added > 0 { + events.push(OnlineEvent::Updated(done.path.clone())); + } + } else if done.total > 0 { + events.push(OnlineEvent::Added(done.path.clone())); + } + } + self.results.retain(|(p, u, _)| { + !(*p == job.account.platform && *u == job.account.username) + }); + self.results + .push((job.account.platform, job.account.username, r)); + // An update finished with the window closed: say so once it is opened. + } else { + i += 1; + } + } + if !self.jobs.is_empty() || self.lookup.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } + if !self.open { + return (events, changed); + } + let mut open = true; + egui::Window::new(tr("Your games from Lichess and Chess.com")) + .open(&mut open) + .default_width(520.0) + .collapsible(false) + .pivot(egui::Align2::CENTER_TOP) + .default_pos(ctx.content_rect().center_top() + egui::vec2(0.0, 120.0)) + .show(ctx, |ui| { + changed |= self.body(ui, probe, settings); + }); + if !open { + self.open = false; + } + (events, changed) + } + + fn body(&mut self, ui: &mut Ui, probe: &Probe, settings: &mut Settings) -> bool { + let mut changed = false; + ui.label( + RichText::new(tr( + "Your online games become a database here, to search and analyse. Only the nickname is needed, no login.", + )) + .weak(), + ); + ui.add_space(6.0); + let both = probe.has(Platform::Lichess) && probe.has(Platform::ChessCom); + ui.horizontal(|ui| { + ui.label(tr("Nickname")); + let r = ui.add( + egui::TextEdit::singleline(&mut self.nick) + .hint_text(tr("as on the site")) + .desired_width(220.0), + ); + if r.changed() { + self.found.clear(); + } + }); + ui.horizontal(|ui| { + for p in Platform::ALL { + if probe.has(p) { + let i = p as usize; + if ui.checkbox(&mut self.pick[i], p.name()).changed() { + self.found.clear(); + } + } + } + }); + if both && self.pick[1] { + let mut clear = false; + let mut same = false; + match &mut self.other { + Some(o) => { + ui.horizontal(|ui| { + ui.label(tr("Nickname on Chess.com")); + clear |= ui + .add(egui::TextEdit::singleline(o).desired_width(180.0)) + .changed(); + same = ui + .small_button("✕") + .on_hover_text(tr("The same nickname")) + .clicked(); + }); + } + None => { + if ui.link(tr("A different nickname on Chess.com")).clicked() { + self.other = Some(self.nick.clone()); + clear = true; + } + } + } + if same { + self.other = None; + clear = true; + } + if clear { + self.found.clear(); + } + } + let wanted: Vec = Platform::ALL + .into_iter() + .filter(|p| probe.has(*p) && self.pick[*p as usize]) + .collect(); + let nicks = ( + self.nick_for(Platform::Lichess), + self.nick_for(Platform::ChessCom), + ); + let valid = wanted + .iter() + .all(|p| online::valid_nick(&self.nick_for(*p))); + ui.add_space(4.0); + ui.horizontal(|ui| { + let searching = self.lookup.is_some(); + let auto = self.auto_find && probe.any(); + if auto { + self.auto_find = false; + } + if ui + .add_enabled( + !wanted.is_empty() && valid && !searching, + egui::Button::new(tr("Find")), + ) + .clicked() + || (auto && !wanted.is_empty() && valid) + { + let list: Vec<(Platform, String)> = + wanted.iter().map(|p| (*p, self.nick_for(*p))).collect(); + self.found_for = nicks.clone(); + let now = ui.input(|i| i.time); + self.lookup = Background::spawn(ui.ctx(), now, move |_, _| { + Some( + list.into_iter() + .map(|(p, n)| (p, online::lookup(p, &n))) + .collect(), + ) + }); + settings.online_nick = self.nick.trim().to_owned(); + settings.online_nick_chesscom = self.other.as_ref().map(|o| o.trim().to_owned()); + changed = true; + } + if searching { + ui.add(egui::Spinner::new()); + } else if !self.nick.trim().is_empty() && !valid { + ui.label( + RichText::new(tr("Letters, digits, _ and -, 2 to 30 characters")) + .color(ui.visuals().warn_fg_color), + ); + } + }); + if self.found_for == nicks && !self.found.is_empty() { + ui.add_space(4.0); + let mut start: Vec = Vec::new(); + for (p, l) in &self.found { + ui.horizontal(|ui| match l { + Lookup::Found(a) => { + let have = online::database_path(a.platform, &a.username) + .and_then(|path| online::State::load(&path)); + let what = match (a.games, a.months) { + (Some(g), _) => { + let secs = g / online::LICHESS_RATE; + trf( + "{p}: {name} — up to {n} games (about {m} min the first time)", + &[ + ("p", &p.name()), + ("name", &a.username), + ("n", &count(g)), + ("m", &secs.div_ceil(60).max(1)), + ], + ) + } + (_, Some(m)) => trf( + "{p}: {name} — games of {m} months", + &[("p", &p.name()), ("name", &a.username), ("m", &m)], + ), + _ => format!("{}: {}", p.name(), a.username), + }; + ui.label(format!("✔ {what}")); + if let Some(s) = have { + ui.label( + RichText::new(trf( + "(already here: {n})", + &[("n", &count(s.games))], + )) + .weak(), + ); + } + if !self.jobs.iter().any(|j| j.account == *a) { + start.push(a.clone()); + } + } + Lookup::NotFound => { + ui.label( + RichText::new(trf("✖ {p}: no such player", &[("p", &p.name())])).weak(), + ); + } + Lookup::Failed(e) => { + ui.label( + RichText::new(trf( + "✖ {p}: no answer ({e})", + &[("p", &p.name()), ("e", e)], + )) + .color(ui.visuals().warn_fg_color), + ); + } + }); + } + let auto = std::mem::take(&mut self.auto_download) && !start.is_empty(); + if !start.is_empty() + && (ui + .button(trf("⬇ Download ({n})", &[("n", &start.len())])) + .clicked() + || auto) + { + // From the window the database goes (back) on the shelf, also when it + // was downloaded before and only gets the new games now. + for a in start { + self.start(a, false, ui.ctx()); + } + } + } + if !self.jobs.is_empty() || !self.results.is_empty() { + ui.separator(); + } + let mut stop = None; + for (k, j) in self.jobs.iter().enumerate() { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new().size(14.0)); + let n = j.work.progress() as u64; + let text = match j.account.games { + Some(total) if total > 0 => trf( + "{p}: {n} of up to {t} games", + &[ + ("p", &j.account.platform.name()), + ("n", &count(n)), + ("t", &count(total)), + ], + ), + _ => trf( + "{p}: {n} games", + &[("p", &j.account.platform.name()), ("n", &count(n))], + ), + }; + ui.label(text); + if ui + .small_button(tr("Stop")) + .on_hover_text(tr( + "What is downloaded is kept; Update continues from there", + )) + .clicked() + { + stop = Some(k); + } + }); + } + if let Some(k) = stop { + self.jobs[k].work.cancel(); + } + for (p, name, r) in &self.results { + let line = match r { + Ok(d) if d.cancelled => trf( + "{p}: stopped, {t} games kept in «{name}»", + &[("p", &p.name()), ("t", &count(d.total)), ("name", name)], + ), + Ok(d) if d.added == 0 => trf( + "{p}: nothing new, {t} games in «{name}»", + &[("p", &p.name()), ("t", &count(d.total)), ("name", name)], + ), + Ok(d) => trf( + "{p}: +{n} games, {t} in «{name}»", + &[ + ("p", &p.name()), + ("n", &count(d.added)), + ("t", &count(d.total)), + ("name", name), + ], + ), + Err(Failure::RateLimited) => trf( + "{p}: the site asks to wait a minute; then try again", + &[("p", &p.name())], + ), + Err(e) => trf("{p}: failed ({e})", &[("p", &p.name()), ("e", e)]), + }; + ui.label(line); + } + changed + } +} diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index e02f7d3..3572508 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -84,6 +84,10 @@ pub struct Settings { pub engines_discovered: bool, /// The sample databases were put on the shelf (see `examples::first_run_setup`). pub examples_added: bool, + /// The nickname last looked up on Lichess / Chess.com, and a different one for + /// Chess.com. + pub online_nick: String, + pub online_nick_chesscom: Option, } /// Options of the whole-game analysis (the engine is the active one). @@ -137,6 +141,8 @@ impl Default for Settings { review: ReviewSettings::default(), engines_discovered: false, examples_added: false, + online_nick: String::new(), + online_nick_chesscom: None, } } } diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index cc24c1a..754681d 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -9,6 +9,8 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i | `app.rs` | Состояние верхнего уровня: библиотека ⇄ партия, настройки, движок, фоновые диалоги (rfd в отдельных потоках), подтверждение закрытия изменённой партии | | `library.rs` | Полка баз, фоновое открытие через `chess_import::open` (PGN, ChessBase, архивы; прогресс, отмена), формат и «Замечания импорта» по каждой базе, таблица с поиском, сортировкой, клавиатурой | | `large_db.rs` | Большая база ChessBase: панель фильтров справа (игроки с подсказками, турнир, годы, Эло, результат, ECO, ходы, аннотации), фоновые проходы с отменой и задержкой 250 мс для текста, счётчик и прогресс, таблица из записей `.cbh`; компоновка — `docs/design/large-databases.md`; переключатель `[Фильтры | Доска]`, строка условий (чипы), колонка «Ход», «только этот порядок», «сильнейшие сверху»; при открытой доске в фоне строится, чего не хватает для быстрого поиска (`Base::prepare`: свой ускоритель без пригодного `.cbb`, дебютный индекс при достаточной памяти; каталог кэша `boosters/`) со строкой прогресса над доской | +| `online.rs` | Партии пользователя с Lichess и Chess.com по нику, без входа. Проверка API при старте (`Probe`: профиль `lichess` и `erik`, ожидаемые поля; не ответившая площадка не предлагается, повтор раз в 5 минут, ответившая остаётся до конца сессии). Поиск ника (`lookup`). Загрузка в `<данные>/online/«Ник (Площадка)».pgn` с файлом состояния `.online.json`: Lichess — NDJSON `pgnInJson`, `sort=dateAsc`, `since` = время последней партии + 1 (20 партий/с без входа), только стандартные шахматы и fromPosition, без часов и оценок; Chess.com — список архивов, затем месяцы JSON с последнего загруженного, `rules == "chess"`, отсечка по `end_time`. Партии дописываются в конец, состояние сохраняется после файла (каждые 100 партий / каждый месяц), так что прерванная загрузка продолжается «Обновить» без дублей. Ограничение: партия по переписке, начатая до последней загруженной и законченная позже, обновлением Lichess не подхватится (`since` считается по времени начала). Живой тест `online_live` (`CP_ONLINE_NICK=<ник>`, ник в репозиторий не кладётся) | +| `online_ui.rs` | Окно «Ваши партии с Lichess и Chess.com»: один ник, галочки площадок (только ответившие), ссылка «На Chess.com другой ник», «Найти» → что найдено (число партий и время первой загрузки для Lichess, месяцы для Chess.com), «Загрузить», прогресс и «Остановить» по каждой площадке, итог. События `Added` (база на полку) и `Updated` (перечитать). Карточка на полке и 🌐 в свёрнутой полке — только если площадка ответила; «⟳ Обновить» в шапке онлайн-базы | | `board_search.rs` | Доска поиска по позиции (решение 13, `docs/design/board-search.md`): ввод ходов, линия с переходами по ходам, продолжения со статистикой (полоса Б/Н/Ч, средний Эло, год; для книг — «N глав»), клавиши ←/→/Home/End/Backspace/1–9/F/Ctrl+Backspace, «Вернуть» после сброса, фоновые задачи `Background` с отменой | | `game_view.rs` | Экран партии: доска, шкала оценки, панель анализа, предпросмотр PV, нотация, панель инструментов, клавиатура | | `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках | @@ -42,7 +44,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe ``` `CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, -`CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). +`CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. `CP_ONLINE=<ник>` — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу загрузить). Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). ## Языки From 149699f70fbfcf73409205a2a53166767d489b74 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Tue, 20 Oct 2026 08:02:12 +0300 Subject: [PATCH 2/4] Online games: one database for both sites (several accounts per database), live test of it Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/i18n.rs | 2 + apps/desktop/src/online.rs | 231 +++++++++++++++++++++++++++------- apps/desktop/src/online_ui.rs | 149 +++++++++++++--------- 3 files changed, 279 insertions(+), 103 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index ac738b2..b0df8ad 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -3561,6 +3561,8 @@ mod tests { include_str!("settings_ui.rs"), include_str!("widgets.rs"), include_str!("reference.rs"), + include_str!("online.rs"), + include_str!("online_ui.rs"), include_str!("report.rs"), include_str!("board.rs"), include_str!("engine_download.rs"), diff --git a/apps/desktop/src/online.rs b/apps/desktop/src/online.rs index 63f9aef..1307618 100644 --- a/apps/desktop/src/online.rs +++ b/apps/desktop/src/online.rs @@ -244,22 +244,35 @@ pub fn dir() -> Option { .map(|d| d.data_local_dir().join("online")) } -/// The database file of an account: "Name (Lichess).pgn". +/// The database file of one account: "Name (Lichess).pgn". pub fn database_path(p: Platform, username: &str) -> Option { dir().map(|d| d.join(format!("{username} ({}).pgn", p.name()))) } +/// The database of several accounts in one: "Name (Lichess + Chess.com).pgn", named +/// after the first account. +pub fn combined_path(accounts: &[Account]) -> Option { + let first = accounts.first()?; + if accounts.len() == 1 { + return database_path(first.platform, &first.username); + } + let platforms = accounts + .iter() + .map(|a| a.platform.name()) + .collect::>() + .join(" + "); + dir().map(|d| d.join(format!("{} ({platforms}).pgn", first.username))) +} + fn state_path(pgn: &Path) -> PathBuf { pgn.with_extension("online.json") } -/// What has been fetched into a database, for the next update. +/// What has been fetched from one account into a database. #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] -pub struct State { +pub struct AccountState { pub platform: Option, pub username: String, - /// Games written so far. - pub games: u64, /// Lichess: creation time (ms) of the newest game fetched. pub lichess_last: Option, /// Chess.com: the newest month fetched ("2026/10") and the end time (s) of its @@ -268,12 +281,21 @@ pub struct State { pub chesscom_last_end: Option, } +/// What has been fetched into a database (from one account or several), for the next +/// update. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct State { + pub accounts: Vec, + /// Games written so far. + pub games: u64, +} + impl State { pub fn load(pgn: &Path) -> Option { let text = std::fs::read_to_string(state_path(pgn)).ok()?; serde_json::from_str::(&text) .ok() - .filter(|s| s.platform.is_some()) + .filter(|s| !s.accounts.is_empty() && s.accounts.iter().all(|a| a.platform.is_some())) } fn save(&self, pgn: &Path) -> Result<(), Failure> { @@ -284,6 +306,21 @@ impl State { .and_then(|_| std::fs::rename(&tmp, &path)) .map_err(|e| Failure::Disk(e.to_string())) } + + /// The accounts of the database, to update it. + pub fn accounts(&self) -> Vec { + self.accounts + .iter() + .filter_map(|a| { + Some(Account { + platform: a.platform?, + username: a.username.clone(), + games: None, + months: None, + }) + }) + .collect() + } } /// An online database (it has a state file). @@ -362,41 +399,66 @@ impl Writer { } } -/// Fetches the games of `account` new since the last run into its database; `progress` -/// counts the games added. Cancelling keeps what was fetched. +/// Fetches the games of `accounts` new since the last run into their database (one +/// database for all of them); `progress` counts the games added. Cancelling keeps what +/// was fetched. pub fn download( - account: &Account, + accounts: &[Account], progress: &AtomicUsize, cancel: &AtomicBool, ) -> Result { - let path = database_path(account.platform, &account.username) - .ok_or_else(|| Failure::Disk("no data directory".into()))?; - download_to(account, &path, progress, cancel) + let path = combined_path(accounts).ok_or_else(|| Failure::Disk("no data directory".into()))?; + download_to(accounts, &path, progress, cancel) } /// [`download`] into the database at `path`. fn download_to( - account: &Account, + accounts: &[Account], path: &Path, progress: &AtomicUsize, cancel: &AtomicBool, ) -> Result { let path = path.to_owned(); - let state = State::load(&path).unwrap_or_else(|| { + let mut state = State::load(&path).unwrap_or_else(|| { // A database without its state: start it anew rather than append duplicates. let _ = std::fs::remove_file(&path); - State { - platform: Some(account.platform), - username: account.username.clone(), - ..State::default() - } + State::default() }); + // Accounts not in the database yet start from their first game. + for a in accounts { + if !state + .accounts + .iter() + .any(|s| s.platform == Some(a.platform) && s.username.eq_ignore_ascii_case(&a.username)) + { + state.accounts.push(AccountState { + platform: Some(a.platform), + username: a.username.clone(), + ..AccountState::default() + }); + } + } let mut w = Writer::open(&path, state)?; - let cancelled = match account.platform { - Platform::Lichess => lichess(&mut w, progress, cancel), - Platform::ChessCom => chesscom(&mut w, progress, cancel), - }; - match cancelled { + let mut result = Ok(false); + for i in 0..w.state.accounts.len() { + let wanted = accounts.iter().any(|a| { + Some(a.platform) == w.state.accounts[i].platform + && a.username + .eq_ignore_ascii_case(&w.state.accounts[i].username) + }); + if !wanted { + continue; + } + result = match w.state.accounts[i].platform { + Some(Platform::Lichess) => lichess(&mut w, i, progress, cancel), + Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel), + None => Ok(false), + }; + if !matches!(result, Ok(false)) { + break; + } + } + match result { Ok(c) => w.done(c), Err(e) => { // Keep what arrived before the failure; the next update continues. @@ -406,15 +468,21 @@ fn download_to( } } -/// `Ok(true)` when cancelled. -fn lichess(w: &mut Writer, progress: &AtomicUsize, cancel: &AtomicBool) -> Result { +/// The games of account `i` of the writer's database from Lichess. `Ok(true)` when +/// cancelled. +fn lichess( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result { let mut url = format!( "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&pgnInJson=true\ &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence\ &clocks=false&evals=false&opening=true", - w.state.username + w.state.accounts[i].username ); - if let Some(last) = w.state.lichess_last { + if let Some(last) = w.state.accounts[i].lichess_last { url.push_str(&format!("&since={}", last + 1)); } let resp = agent(true) @@ -450,7 +518,7 @@ fn lichess(w: &mut Writer, progress: &AtomicUsize, cancel: &AtomicBool) -> Resul w.game(pgn)?; progress.fetch_add(1, Ordering::Relaxed); } - w.state.lichess_last = Some(created); + w.state.accounts[i].lichess_last = Some(created); if n % 100 == 99 { w.commit()?; } @@ -458,9 +526,15 @@ fn lichess(w: &mut Writer, progress: &AtomicUsize, cancel: &AtomicBool) -> Resul Ok(false) } -/// `Ok(true)` when cancelled. -fn chesscom(w: &mut Writer, progress: &AtomicUsize, cancel: &AtomicBool) -> Result { - let lower = w.state.username.to_ascii_lowercase(); +/// The games of account `i` of the writer's database from Chess.com. `Ok(true)` when +/// cancelled. +fn chesscom( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result { + let lower = w.state.accounts[i].username.to_ascii_lowercase(); let months = archives(&lower)?; for url in months { // ".../games/2026/10" → "2026/10"; months before the last fetched are done. @@ -470,7 +544,8 @@ fn chesscom(w: &mut Writer, progress: &AtomicUsize, cancel: &AtomicBool) -> Resu month.get(1).unwrap_or(&""), month.first().unwrap_or(&"") ); - if w.state.chesscom_month.as_ref().is_some_and(|m| month < *m) { + let a = &w.state.accounts[i]; + if a.chesscom_month.as_ref().is_some_and(|m| month < *m) { continue; } if cancel.load(Ordering::Relaxed) { @@ -486,9 +561,10 @@ fn chesscom(w: &mut Writer, progress: &AtomicUsize, cancel: &AtomicBool) -> Resu .filter_map(|g| Some((g["end_time"].as_i64()?, g["pgn"].as_str()?))) .collect(); list.sort_by_key(|(t, _)| *t); - let same_month = w.state.chesscom_month.as_deref() == Some(month.as_str()); + let a = &w.state.accounts[i]; + let same_month = a.chesscom_month.as_deref() == Some(month.as_str()); let last = if same_month { - w.state.chesscom_last_end + a.chesscom_last_end } else { None }; @@ -498,11 +574,11 @@ fn chesscom(w: &mut Writer, progress: &AtomicUsize, cancel: &AtomicBool) -> Resu } w.game(pgn)?; progress.fetch_add(1, Ordering::Relaxed); - w.state.chesscom_last_end = Some(end); + w.state.accounts[i].chesscom_last_end = Some(end); } // The mark moves to this month even when it had no standard games (the end // time then still belongs to an earlier month and is not compared). - w.state.chesscom_month = Some(month); + w.state.accounts[i].chesscom_month = Some(month); w.commit()?; } Ok(false) @@ -628,7 +704,8 @@ mod tests { } cancel.store(true, Ordering::Relaxed); }); - download_to(&li, &path, &progress, &cancel).expect("downloads") + download_to(std::slice::from_ref(&li), &path, &progress, &cancel) + .expect("downloads") }); eprintln!("lichess round {round}: {done:?}"); assert!(done.cancelled && done.added >= 150); @@ -652,7 +729,18 @@ mod tests { .filter_map(|l| serde_json::from_str::(l).ok()) .filter_map(|v| Some(format!("https://lichess.org/{}", v["id"].as_str()?))) .collect(); - assert_eq!(sites, expected, "the first {n} games, in order"); + // Ours are the reference's first games, in its order (the reference may hold a + // few more: Lichess does not count `max` exactly as we count games). + if expected.len() < sites.len() || sites[..] != expected[..sites.len()] { + let only_ours: Vec<_> = sites.iter().filter(|x| !expected.contains(x)).collect(); + let only_ref: Vec<_> = expected.iter().filter(|x| !sites.contains(x)).collect(); + let first = sites.iter().zip(&expected).position(|(a, b)| a != b); + panic!( + "differ: first at {first:?}, ours {} ref {}, only ours {only_ours:?}, only in the reference {only_ref:?}", + sites.len(), + expected.len() + ); + } // Chess.com: everything, then an update that finds nothing new. let Lookup::Found(cc) = lookup(Platform::ChessCom, &nick) else { @@ -660,16 +748,67 @@ mod tests { }; let path = dir.join("cc.pgn"); let never = AtomicBool::new(false); - let done = download_to(&cc, &path, &AtomicUsize::new(0), &never).expect("downloads"); + let done = download_to( + std::slice::from_ref(&cc), + &path, + &AtomicUsize::new(0), + &never, + ) + .expect("downloads"); eprintln!("chess.com: {done:?}"); assert!(!done.cancelled && done.total > 0); - let again = download_to(&cc, &path, &AtomicUsize::new(0), &never).expect("updates"); + let again = download_to( + std::slice::from_ref(&cc), + &path, + &AtomicUsize::new(0), + &never, + ) + .expect("updates"); assert_eq!((again.added, again.total), (0, done.total)); let (n, sites, problems) = read_db(&path); assert_eq!(n as u64, done.total); let unique: std::collections::HashSet<_> = sites.iter().collect(); assert_eq!(unique.len(), n, "no duplicates"); eprintln!("chess.com: {n} games, {problems} with diagnostics"); + + // Both into one database: Chess.com whole, then Lichess stopped twice; the + // second run adds Lichess games only, without duplicates. + let path = dir.join("both.pgn"); + let accounts = [cc.clone(), li.clone()]; + let mut totals = Vec::new(); + for round in 1..=2 { + let progress = AtomicUsize::new(0); + let cancel = AtomicBool::new(false); + let goal = if round == 1 { + done.total as usize + 100 + } else { + 100 + }; + let d = std::thread::scope(|s| { + s.spawn(|| { + while progress.load(Ordering::Relaxed) < goal { + std::thread::sleep(Duration::from_millis(50)); + } + cancel.store(true, Ordering::Relaxed); + }); + download_to(&accounts, &path, &progress, &cancel).expect("downloads") + }); + eprintln!("both, round {round}: {d:?}"); + assert!(d.cancelled); + totals.push(d.total); + } + let state = State::load(&path).unwrap(); + assert_eq!(state.accounts.len(), 2); + assert_eq!(state.accounts[0].platform, Some(Platform::ChessCom)); + assert!(state.accounts[0].chesscom_month.is_some()); + assert!(state.accounts[1].lichess_last.is_some()); + let (n, sites, problems) = read_db(&path); + assert_eq!(n as u64, totals[1]); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + let chesscom = sites.iter().filter(|s| s.contains("chess.com")).count() as u64; + assert_eq!(chesscom, done.total, "all of Chess.com, once"); + eprintln!("both: {n} games ({chesscom} from Chess.com), {problems} with diagnostics"); let _ = std::fs::remove_dir_all(&dir); } @@ -707,11 +846,13 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); let pgn = dir.join("Someone (Lichess).pgn"); let s = State { - platform: Some(Platform::Lichess), - username: "Someone".into(), + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "Someone".into(), + lichess_last: Some(1_700_000_000_000), + ..AccountState::default() + }], games: 3, - lichess_last: Some(1_700_000_000_000), - ..State::default() }; s.save(&pgn).unwrap(); assert_eq!(State::load(&pgn), Some(s)); diff --git a/apps/desktop/src/online_ui.rs b/apps/desktop/src/online_ui.rs index 8211585..b41bea6 100644 --- a/apps/desktop/src/online_ui.rs +++ b/apps/desktop/src/online_ui.rs @@ -19,7 +19,8 @@ pub enum OnlineEvent { } struct Job { - account: Account, + /// One account, or several downloaded into one database. + accounts: Vec, /// Updating a database already on the shelf (not a first download). update: bool, work: Background>, @@ -37,7 +38,11 @@ pub struct OnlineDialog { /// The nicknames `found` answers. found_for: (String, String), jobs: Vec, - results: Vec<(Platform, String, Result)>, + /// Per finished download: the platforms ("Lichess + Chess.com"), the database name + /// and the outcome. + results: Vec<(String, String, Result)>, + /// Two accounts found: download them into separate databases (one by default). + separate: bool, /// Dev hook (screenshots): look the nickname up once the probe answered, and /// download what was found. auto_find: bool, @@ -48,6 +53,22 @@ fn count(n: u64) -> String { crate::large_db::grouped(n as usize) } +/// "Lichess + Chess.com". +fn platforms(accounts: &[Account]) -> String { + accounts + .iter() + .map(|a| a.platform.name()) + .collect::>() + .join(" + ") +} + +/// The file name of a database without the extension. +fn db_name(path: &std::path::Path) -> String { + path.file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() +} + impl OnlineDialog { /// Opens the window with the nicknames used last time. pub fn open_with(&mut self, settings: &Settings) { @@ -78,7 +99,7 @@ impl OnlineDialog { pub fn busy(&self) -> Vec { self.jobs .iter() - .filter_map(|j| online::database_path(j.account.platform, &j.account.username)) + .filter_map(|j| online::combined_path(&j.accounts)) .collect() } @@ -87,29 +108,23 @@ impl OnlineDialog { let Some(state) = online::State::load(path) else { return; }; - let Some(platform) = state.platform else { - return; - }; if self.busy().iter().any(|p| p == path) { return; } - let account = Account { - platform, - username: state.username, - games: None, - months: None, - }; - self.start(account, true, ctx); + self.start(state.accounts(), true, ctx); } - fn start(&mut self, account: Account, update: bool, ctx: &egui::Context) { + fn start(&mut self, accounts: Vec, update: bool, ctx: &egui::Context) { + if accounts.is_empty() { + return; + } let now = ctx.input(|i| i.time); - let a = account.clone(); + let a = accounts.clone(); if let Some(work) = Background::spawn(ctx, now, move |progress, cancel| { Some(online::download(&a, progress, cancel)) }) { self.jobs.push(Job { - account, + accounts, update, work, }); @@ -152,11 +167,12 @@ impl OnlineDialog { events.push(OnlineEvent::Added(done.path.clone())); } } - self.results.retain(|(p, u, _)| { - !(*p == job.account.platform && *u == job.account.username) - }); - self.results - .push((job.account.platform, job.account.username, r)); + let label = platforms(&job.accounts); + let name = online::combined_path(&job.accounts) + .map(|p| db_name(&p)) + .unwrap_or_default(); + self.results.retain(|(_, n, _)| *n != name); + self.results.push((label, name, r)); // An update finished with the window closed: say so once it is opened. } else { i += 1; @@ -302,8 +318,6 @@ impl OnlineDialog { for (p, l) in &self.found { ui.horizontal(|ui| match l { Lookup::Found(a) => { - let have = online::database_path(a.platform, &a.username) - .and_then(|path| online::State::load(&path)); let what = match (a.games, a.months) { (Some(g), _) => { let secs = g / online::LICHESS_RATE; @@ -324,16 +338,7 @@ impl OnlineDialog { _ => format!("{}: {}", p.name(), a.username), }; ui.label(format!("✔ {what}")); - if let Some(s) = have { - ui.label( - RichText::new(trf( - "(already here: {n})", - &[("n", &count(s.games))], - )) - .weak(), - ); - } - if !self.jobs.iter().any(|j| j.account == *a) { + if !self.jobs.iter().any(|j| j.accounts.contains(a)) { start.push(a.clone()); } } @@ -353,17 +358,48 @@ impl OnlineDialog { } }); } + // Both platforms: one database by default (the player's games together). + let together = start.len() > 1 && !self.separate; + if start.len() > 1 { + let mut one = !self.separate; + if ui + .checkbox( + &mut one, + tr("Put the games of both sites into one database"), + ) + .on_hover_text(tr("Otherwise each site gets a database of its own")) + .changed() + { + self.separate = !one; + } + } + // Where the games go, and what is there already. + let targets: Vec> = if together { + vec![start.clone()] + } else { + start.iter().map(|a| vec![a.clone()]).collect() + }; + for t in &targets { + if let Some(path) = online::combined_path(t) { + let text = match online::State::load(&path) { + Some(s) => trf( + "Into «{name}» (already {n} games there; only new ones are added)", + &[("name", &db_name(&path)), ("n", &count(s.games))], + ), + None => trf( + "Into the new database «{name}»", + &[("name", &db_name(&path))], + ), + }; + ui.label(RichText::new(text).weak()); + } + } let auto = std::mem::take(&mut self.auto_download) && !start.is_empty(); - if !start.is_empty() - && (ui - .button(trf("⬇ Download ({n})", &[("n", &start.len())])) - .clicked() - || auto) - { + if !start.is_empty() && (ui.button(tr("⬇ Download")).clicked() || auto) { // From the window the database goes (back) on the shelf, also when it // was downloaded before and only gets the new games now. - for a in start { - self.start(a, false, ui.ctx()); + for t in targets { + self.start(t, false, ui.ctx()); } } } @@ -375,19 +411,15 @@ impl OnlineDialog { ui.horizontal(|ui| { ui.add(egui::Spinner::new().size(14.0)); let n = j.work.progress() as u64; - let text = match j.account.games { - Some(total) if total > 0 => trf( + let known: u64 = j.accounts.iter().filter_map(|a| a.games).sum(); + let label = platforms(&j.accounts); + let text = if known > 0 && j.accounts.iter().all(|a| a.games.is_some()) { + trf( "{p}: {n} of up to {t} games", - &[ - ("p", &j.account.platform.name()), - ("n", &count(n)), - ("t", &count(total)), - ], - ), - _ => trf( - "{p}: {n} games", - &[("p", &j.account.platform.name()), ("n", &count(n))], - ), + &[("p", &label), ("n", &count(n)), ("t", &count(known))], + ) + } else { + trf("{p}: {n} games", &[("p", &label), ("n", &count(n))]) }; ui.label(text); if ui @@ -405,19 +437,20 @@ impl OnlineDialog { self.jobs[k].work.cancel(); } for (p, name, r) in &self.results { + let p = p.as_str(); let line = match r { Ok(d) if d.cancelled => trf( "{p}: stopped, {t} games kept in «{name}»", - &[("p", &p.name()), ("t", &count(d.total)), ("name", name)], + &[("p", &p), ("t", &count(d.total)), ("name", name)], ), Ok(d) if d.added == 0 => trf( "{p}: nothing new, {t} games in «{name}»", - &[("p", &p.name()), ("t", &count(d.total)), ("name", name)], + &[("p", &p), ("t", &count(d.total)), ("name", name)], ), Ok(d) => trf( "{p}: +{n} games, {t} in «{name}»", &[ - ("p", &p.name()), + ("p", &p), ("n", &count(d.added)), ("t", &count(d.total)), ("name", name), @@ -425,9 +458,9 @@ impl OnlineDialog { ), Err(Failure::RateLimited) => trf( "{p}: the site asks to wait a minute; then try again", - &[("p", &p.name())], + &[("p", &p)], ), - Err(e) => trf("{p}: failed ({e})", &[("p", &p.name()), ("e", e)]), + Err(e) => trf("{p}: failed ({e})", &[("p", &p), ("e", e)]), }; ui.label(line); } From e0c99074e25d1900ccd523a3d843fea18351847e Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Tue, 20 Oct 2026 08:30:31 +0300 Subject: [PATCH 3/4] Online games: anyone's games, one download per database, crash-safe resume, unfinished Lichess games, friendly errors, progress per site MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - the window and the shelf speak of any player's games (yours, a pupil's, an opponent's) - a database is claimed by one download at a time; updates write into the database itself - merged databases of different nicknames get names of their own - the state remembers the file length and its last bytes: what a crash appended is cut off - a deleted database is downloaded again; a partial download goes on the shelf - Lichess games still being played are fetched once they end (correspondence) - downloads stop and save on quitting; results show as a toast when the window is closed - New games button with the time of the last download, disabled offline; 🌐 on online databases Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app.rs | 14 + apps/desktop/src/i18n.rs | 423 ++++++++++++++---------- apps/desktop/src/library.rs | 67 ++-- apps/desktop/src/online.rs | 512 +++++++++++++++++++++++++---- apps/desktop/src/online_ui.rs | 594 +++++++++++++++++++++++----------- apps/desktop/src/update_ui.rs | 21 +- apps/desktop/src/widgets.rs | 9 + 7 files changed, 1179 insertions(+), 461 deletions(-) diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 353df92..72cdd3c 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -892,6 +892,7 @@ impl eframe::App for App { self.online_probe.poll(); self.library.online = self.online_probe.any(); self.library.online_busy = self.online.busy(); + self.library.online_running = self.online.running(); for a in self.library.show(ui, &dbs, &self.settings) { match a { LibraryAction::OpenGame { path, index, at } => { @@ -937,6 +938,12 @@ impl eframe::App for App { self.settings_dirty = true; } crate::online_ui::OnlineEvent::Updated(p) => self.library.reload(&p, &ctx), + crate::online_ui::OnlineEvent::Open(p) => { + self.settings.touch_database(&p); + self.library.select_db(&p, &ctx); + self.settings_dirty = true; + } + crate::online_ui::OnlineEvent::Message(t) => self.toast(&ctx, t), } } // Updates: the badge next to Settings, the window, the status in Settings → About. @@ -1054,6 +1061,13 @@ impl eframe::App for App { fn on_exit(&mut self) { self.analysis.stop(); + // Downloads of online games stop and save what they got; a new database goes on + // the shelf with it (the next download continues it). + for p in self.online.stop_all() { + if crate::online::State::load(&p).is_some_and(|s| s.games > 0) { + self.settings.touch_database(&p); + } + } let _ = self.settings.save(); } } diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 16fac50..5c9e218 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -2079,14 +2079,6 @@ const ROWS: &[[&str; 6]] = &[ "Partidas de la base solo con los jugadores y el resultado, sin jugadas", "Partite della base con solo giocatori e risultato, senza mosse", ], - [ - "(already here: {n})", - "(уже есть: {n})", - "(déjà ici : {n})", - "(schon vorhanden: {n})", - "(ya aquí: {n})", - "(già presenti: {n})", - ], [ "A different nickname on Chess.com", "На Chess.com другой ник", @@ -2095,14 +2087,6 @@ const ROWS: &[[&str; 6]] = &[ "Otro apodo en Chess.com", "Un altro nickname su Chess.com", ], - [ - "Download your online games by nickname into a database", - "Загрузить свои онлайн-партии по нику в базу", - "Télécharger vos parties en ligne par pseudo dans une base", - "Ihre Online-Partien per Nickname in eine Datenbank laden", - "Descargar tus partidas en línea por apodo a una base", - "Scarica le tue partite online per nickname in una base", - ], [ "Fetch the games played since the last download", "Загрузить партии, сыгранные после прошлой загрузки", @@ -2112,14 +2096,6 @@ const ROWS: &[[&str; 6]] = &[ "Scarica le partite giocate dall'ultimo download", ], ["Find", "Найти", "Rechercher", "Suchen", "Buscar", "Cerca"], - [ - "Games from", - "Партии с", - "Parties de", - "Partien von", - "Partidas de", - "Partite da", - ], [ "Letters, digits, _ and -, 2 to 30 characters", "Латиница, цифры, _ и -, от 2 до 30 символов", @@ -2128,7 +2104,6 @@ const ROWS: &[[&str; 6]] = &[ "Letras, dígitos, _ y -, de 2 a 30 caracteres", "Lettere, cifre, _ e -, da 2 a 30 caratteri", ], - ["Nickname", "Ник", "Pseudo", "Nickname", "Apodo", "Nickname"], [ "Nickname on Chess.com", "Ник на Chess.com", @@ -2153,30 +2128,6 @@ const ROWS: &[[&str; 6]] = &[ "El mismo apodo", "Lo stesso nickname", ], - [ - "What is downloaded is kept; Update continues from there", - "Скачанное сохранится; «Обновить» продолжит с этого места", - "Ce qui est téléchargé est conservé ; « Mettre à jour » reprend à partir de là", - "Bereits Geladenes bleibt; „Aktualisieren“ setzt dort fort", - "Lo descargado se conserva; «Actualizar» continúa desde ahí", - "Quanto scaricato resta; «Aggiorna» riprende da lì", - ], - [ - "Your games from Lichess and Chess.com", - "Ваши партии с Lichess и Chess.com", - "Vos parties de Lichess et Chess.com", - "Ihre Partien von Lichess und Chess.com", - "Tus partidas de Lichess y Chess.com", - "Le tue partite da Lichess e Chess.com", - ], - [ - "Your online games become a database here, to search and analyse. Only the nickname is needed, no login.", - "Ваши онлайн-партии станут базой здесь: искать, разбирать, анализировать. Нужен только ник, входить в аккаунт не нужно.", - "Vos parties en ligne deviennent une base ici, pour chercher et analyser. Seul le pseudo est nécessaire, sans connexion.", - "Ihre Online-Partien werden hier zu einer Datenbank zum Suchen und Analysieren. Nur der Nickname wird gebraucht, keine Anmeldung.", - "Tus partidas en línea se convierten aquí en una base para buscar y analizar. Solo hace falta el apodo, sin iniciar sesión.", - "Le tue partite online diventano qui una base da cercare e analizzare. Serve solo il nickname, senza accesso.", - ], [ "as on the site", "как на сайте", @@ -2193,110 +2144,6 @@ const ROWS: &[[&str; 6]] = &[ "actualizando…", "aggiornamento…", ], - [ - "{p}: +{n} games, {t} in «{name}»", - "{p}: +{n} партий, всего {t} в «{name}»", - "{p} : +{n} parties, {t} dans « {name} »", - "{p}: +{n} Partien, {t} in „{name}“", - "{p}: +{n} partidas, {t} en «{name}»", - "{p}: +{n} partite, {t} in «{name}»", - ], - [ - "{p}: failed ({e})", - "{p}: не получилось ({e})", - "{p} : échec ({e})", - "{p}: fehlgeschlagen ({e})", - "{p}: error ({e})", - "{p}: non riuscito ({e})", - ], - [ - "{p}: nothing new, {t} games in «{name}»", - "{p}: новых нет, {t} партий в «{name}»", - "{p} : rien de nouveau, {t} parties dans « {name} »", - "{p}: nichts Neues, {t} Partien in „{name}“", - "{p}: nada nuevo, {t} partidas en «{name}»", - "{p}: niente di nuovo, {t} partite in «{name}»", - ], - [ - "{p}: stopped, {t} games kept in «{name}»", - "{p}: остановлено, сохранено {t} партий в «{name}»", - "{p} : arrêté, {t} parties conservées dans « {name} »", - "{p}: angehalten, {t} Partien in „{name}“ behalten", - "{p}: detenido, {t} partidas guardadas en «{name}»", - "{p}: fermato, {t} partite conservate in «{name}»", - ], - [ - "{p}: the site asks to wait a minute; then try again", - "{p}: сайт просит подождать минуту, потом попробуйте снова", - "{p} : le site demande d'attendre une minute, puis réessayez", - "{p}: die Seite bittet um eine Minute Geduld, dann erneut versuchen", - "{p}: el sitio pide esperar un minuto; luego inténtalo de nuevo", - "{p}: il sito chiede di attendere un minuto, poi riprova", - ], - [ - "{p}: {name} — games of {m} months", - "{p}: {name} — партии за {m} мес.", - "{p} : {name} — parties de {m} mois", - "{p}: {name} — Partien aus {m} Monaten", - "{p}: {name} — partidas de {m} meses", - "{p}: {name} — partite di {m} mesi", - ], - [ - "{p}: {name} — up to {n} games (about {m} min the first time)", - "{p}: {name} — до {n} партий (первый раз около {m} мин)", - "{p} : {name} — jusqu'à {n} parties (environ {m} min la première fois)", - "{p}: {name} — bis zu {n} Partien (beim ersten Mal etwa {m} Min.)", - "{p}: {name} — hasta {n} partidas (la primera vez, unos {m} min)", - "{p}: {name} — fino a {n} partite (la prima volta circa {m} min)", - ], - [ - "{p}: {n} games", - "{p}: {n} партий", - "{p} : {n} parties", - "{p}: {n} Partien", - "{p}: {n} partidas", - "{p}: {n} partite", - ], - [ - "{p}: {n} of up to {t} games", - "{p}: {n} из примерно {t} партий", - "{p} : {n} sur environ {t} parties", - "{p}: {n} von bis zu {t} Partien", - "{p}: {n} de hasta {t} partidas", - "{p}: {n} di circa {t} partite", - ], - [ - "✖ {p}: no answer ({e})", - "✖ {p}: нет ответа ({e})", - "✖ {p} : pas de réponse ({e})", - "✖ {p}: keine Antwort ({e})", - "✖ {p}: sin respuesta ({e})", - "✖ {p}: nessuna risposta ({e})", - ], - [ - "✖ {p}: no such player", - "✖ {p}: игрок не найден", - "✖ {p} : joueur introuvable", - "✖ {p}: Spieler nicht gefunden", - "✖ {p}: jugador no encontrado", - "✖ {p}: giocatore non trovato", - ], - [ - "⟳ Update", - "⟳ Обновить", - "⟳ Mettre à jour", - "⟳ Aktualisieren", - "⟳ Actualizar", - "⟳ Aggiorna", - ], - [ - "⬇ Download ({n})", - "⬇ Загрузить ({n})", - "⬇ Télécharger ({n})", - "⬇ Herunterladen ({n})", - "⬇ Descargar ({n})", - "⬇ Scarica ({n})", - ], [ "Checking…", "Проверяю…", @@ -2953,14 +2800,6 @@ const ROWS: &[[&str; 6]] = &[ "Tienes la {old}", "Hai la {old}", ], - [ - "Put the games of both sites into one database", - "Сложить партии с обоих сайтов в одну базу", - "Mettre les parties des deux sites dans une seule base", - "Partien beider Seiten in eine Datenbank legen", - "Poner las partidas de ambos sitios en una sola base", - "Mettere le partite di entrambi i siti in una sola base", - ], [ "Otherwise each site gets a database of its own", "Иначе у каждого сайта будет своя база", @@ -2970,21 +2809,269 @@ const ROWS: &[[&str; 6]] = &[ "Altrimenti ogni sito avrà la sua base", ], [ - "Into «{name}» (already {n} games there; only new ones are added)", - "В базу «{name}» (там уже {n} партий; добавятся только новые)", - "Dans « {name} » (déjà {n} parties ; seules les nouvelles sont ajoutées)", - "In „{name}“ (schon {n} Partien dort; nur neue kommen dazu)", - "En «{name}» (ya hay {n} partidas; solo se añaden las nuevas)", - "In «{name}» (già {n} partite; si aggiungono solo le nuove)", + "Download any player's games by nickname into a database: yours, a pupil's, an opponent's", + "Скачать партии любого игрока по нику в базу: свои, ученика, соперника", + "Télécharger les parties de n'importe quel joueur par pseudo dans une base : les vôtres, celles d'un élève, d'un adversaire", + "Partien beliebiger Spieler per Nickname in eine Datenbank laden: eigene, eines Schülers, eines Gegners", + "Descargar las partidas de cualquier jugador por apodo a una base: las tuyas, de un alumno, de un rival", + "Scarica le partite di qualsiasi giocatore per nickname in una base: le tue, di un allievo, di un avversario", ], [ - "Into the new database «{name}»", + "Online games", + "Онлайн-партии", + "Parties en ligne", + "Online-Partien", + "Partidas en línea", + "Partite online", + ], + [ + "No connection to Lichess and Chess.com", + "Нет связи с Lichess и Chess.com", + "Pas de connexion à Lichess et Chess.com", + "Keine Verbindung zu Lichess und Chess.com", + "Sin conexión con Lichess y Chess.com", + "Nessuna connessione a Lichess e Chess.com", + ], + [ + "⟳ New games", + "⟳ Новые партии", + "⟳ Nouvelles parties", + "⟳ Neue Partien", + "⟳ Partidas nuevas", + "⟳ Nuove partite", + ], + [ + "downloading… {n}", + "скачивается… {n}", + "téléchargement… {n}", + "wird geladen… {n}", + "descargando… {n}", + "download… {n}", + ], + [ + "Fetch the games played since the last download ({when})", + "Скачать партии, сыгранные после прошлой загрузки ({when})", + "Récupérer les parties jouées depuis le dernier téléchargement ({when})", + "Die seit dem letzten Download gespielten Partien holen ({when})", + "Descargar las partidas jugadas desde la última descarga ({when})", + "Scarica le partite giocate dall'ultimo download ({when})", + ], + [ + "{n} min ago", + "{n} мин назад", + "il y a {n} min", + "vor {n} Min.", + "hace {n} min", + "{n} min fa", + ], + [ + "{n} h ago", + "{n} ч назад", + "il y a {n} h", + "vor {n} Std.", + "hace {n} h", + "{n} h fa", + ], + [ + "{n} d ago", + "{n} дн. назад", + "il y a {n} j", + "vor {n} T.", + "hace {n} d", + "{n} g fa", + ], + [ + "Could not write the database: no permission to write or the disk is full.", + "Не удалось записать базу: нет прав на запись или диск заполнен.", + "Impossible d'écrire la base : pas de droit d'écriture ou disque plein.", + "Die Datenbank konnte nicht geschrieben werden: keine Schreibrechte oder die Festplatte ist voll.", + "No se pudo escribir la base: sin permiso de escritura o el disco está lleno.", + "Impossibile scrivere la base: nessun permesso di scrittura o disco pieno.", + ], + [ + "This database is being downloaded already.", + "Эта база уже скачивается.", + "Cette base est déjà en cours de téléchargement.", + "Diese Datenbank wird bereits geladen.", + "Esta base ya se está descargando.", + "Questa base è già in download.", + ], + [ + "Games from Lichess and Chess.com", + "Партии с Lichess и Chess.com", + "Parties de Lichess et Chess.com", + "Partien von Lichess und Chess.com", + "Partidas de Lichess y Chess.com", + "Partite da Lichess e Chess.com", + ], + [ + "Any player's games — yours, a pupil's, an opponent's — become a database here, to search and analyse. Only the nickname is needed, no login.", + "Партии любого игрока — свои, ученика, соперника — станут здесь базой для поиска и анализа. Нужен только ник, входить в аккаунт не нужно.", + "Les parties de n'importe quel joueur — les vôtres, celles d'un élève, d'un adversaire — deviennent ici une base pour chercher et analyser. Seul le pseudo est nécessaire, sans connexion.", + "Die Partien beliebiger Spieler — eigene, eines Schülers, eines Gegners — werden hier zu einer Datenbank zum Suchen und Analysieren. Nur der Nickname ist nötig, keine Anmeldung.", + "Las partidas de cualquier jugador — las tuyas, de un alumno, de un rival — se convierten aquí en una base para buscar y analizar. Solo hace falta el apodo, sin iniciar sesión.", + "Le partite di qualsiasi giocatore — le tue, di un allievo, di un avversario — diventano qui una base da cercare e analizzare. Serve solo il nickname, nessun accesso.", + ], + [ + "Player's nickname", + "Ник игрока", + "Pseudo du joueur", + "Nickname des Spielers", + "Apodo del jugador", + "Nickname del giocatore", + ], + [ + "Merge the games of both sites into one database", + "Объединить партии с обоих сайтов в одну базу", + "Réunir les parties des deux sites dans une seule base", + "Partien beider Seiten in einer Datenbank zusammenführen", + "Unir las partidas de ambos sitios en una sola base", + "Unire le partite di entrambi i siti in una sola base", + ], + [ + "What is downloaded is kept; downloading again continues from there", + "Скачанное сохранится; следующая загрузка продолжит с этого места", + "Ce qui est téléchargé est conservé ; le prochain téléchargement reprend à partir de là", + "Bereits Geladenes bleibt; der nächste Download setzt dort fort", + "Lo descargado se conserva; la próxima descarga continúa desde ahí", + "Il già scaricato resta; il prossimo download riprende da lì", + ], + [ + "You can close the window: the download goes on, and what is downloaded is kept.", + "Окно можно закрыть: загрузка продолжится, скачанное не пропадёт.", + "Vous pouvez fermer la fenêtre : le téléchargement continue et ce qui est téléchargé est conservé.", + "Das Fenster kann geschlossen werden: der Download läuft weiter, Geladenes bleibt erhalten.", + "Puedes cerrar la ventana: la descarga continúa y lo descargado se conserva.", + "Puoi chiudere la finestra: il download continua e il già scaricato resta.", + ], + [ + "Open the database", + "Открыть базу", + "Ouvrir la base", + "Datenbank öffnen", + "Abrir la base", + "Apri la base", + ], + [ + "{p} does not answer. Check the internet connection and try again.", + "{p} не отвечает. Проверьте подключение к интернету и попробуйте ещё раз.", + "{p} ne répond pas. Vérifiez la connexion Internet et réessayez.", + "{p} antwortet nicht. Prüfen Sie die Internetverbindung und versuchen Sie es erneut.", + "{p} no responde. Comprueba la conexión a internet e inténtalo de nuevo.", + "{p} non risponde. Controlla la connessione a internet e riprova.", + ], + [ + "{p} asks for a pause: too many requests in a row. Wait a minute and try again; what is downloaded is kept.", + "{p} просит сделать паузу: слишком много запросов подряд. Подождите минуту и попробуйте снова — скачанное сохранится.", + "{p} demande une pause : trop de requêtes d'affilée. Attendez une minute et réessayez ; ce qui est téléchargé est conservé.", + "{p} bittet um eine Pause: zu viele Anfragen hintereinander. Warten Sie eine Minute und versuchen Sie es erneut; Geladenes bleibt erhalten.", + "{p} pide una pausa: demasiadas solicitudes seguidas. Espera un minuto e inténtalo de nuevo; lo descargado se conserva.", + "{p} chiede una pausa: troppe richieste di fila. Aspetta un minuto e riprova; il già scaricato resta.", + ], + [ + "{p} answered in a way ChessPenguin does not understand: the site may have changed. Try later or update ChessPenguin.", + "{p} ответил непонятно — возможно, сайт что-то поменял. Попробуйте позже или обновите ChessPenguin.", + "{p} a répondu d'une façon que ChessPenguin ne comprend pas : le site a peut-être changé. Réessayez plus tard ou mettez ChessPenguin à jour.", + "{p} hat unverständlich geantwortet: die Seite hat sich vielleicht geändert. Versuchen Sie es später oder aktualisieren Sie ChessPenguin.", + "{p} respondió de una forma que ChessPenguin no entiende: quizá el sitio cambió. Inténtalo más tarde o actualiza ChessPenguin.", + "{p} ha risposto in un modo che ChessPenguin non capisce: forse il sito è cambiato. Riprova più tardi o aggiorna ChessPenguin.", + ], + [ + "“{name}”: stopped, {total} in the database", + "«{name}»: остановлено, в базе {total}", + "« {name} » : arrêté, {total} dans la base", + "„{name}“: angehalten, {total} in der Datenbank", + "«{name}»: detenido, {total} en la base", + "«{name}»: fermato, {total} nella base", + ], + [ + "“{name}”: no new games", + "«{name}»: новых партий нет", + "« {name} » : pas de nouvelles parties", + "„{name}“: keine neuen Partien", + "«{name}»: no hay partidas nuevas", + "«{name}»: nessuna partita nuova", + ], + [ + "“{name}”: +{added}, {total} in all", + "«{name}»: +{added}, всего {total}", + "« {name} » : +{added}, {total} en tout", + "„{name}“: +{added}, insgesamt {total}", + "«{name}»: +{added}, {total} en total", + "«{name}»: +{added}, {total} in tutto", + ], + [ + "“{name}”: {e}", + "«{name}»: {e}", + "« {name} » : {e}", + "„{name}“: {e}", + "«{name}»: {e}", + "«{name}»: {e}", + ], + [ + "{p}: {name} — {games}, about {m} min the first time", + "{p}: {name} — {games}, первый раз около {m} мин", + "{p} : {name} — {games}, environ {m} min la première fois", + "{p}: {name} — {games}, beim ersten Mal etwa {m} Min.", + "{p}: {name} — {games}, la primera vez unos {m} min", + "{p}: {name} — {games}, la prima volta circa {m} min", + ], + [ + "{p}: {name} — {games}", + "{p}: {name} — {games}", + "{p} : {name} — {games}", + "{p}: {name} — {games}", + "{p}: {name} — {games}", + "{p}: {name} — {games}", + ], + [ + "{p}: {name} — months with games: {m}", + "{p}: {name} — месяцев с партиями: {m}", + "{p} : {name} — mois avec des parties : {m}", + "{p}: {name} — Monate mit Partien: {m}", + "{p}: {name} — meses con partidas: {m}", + "{p}: {name} — mesi con partite: {m}", + ], + [ + "✖ {p}: no player with this nickname — check the spelling", + "✖ {p}: игрока с таким ником нет — проверьте написание", + "✖ {p} : aucun joueur avec ce pseudo — vérifiez l'orthographe", + "✖ {p}: kein Spieler mit diesem Nickname — prüfen Sie die Schreibweise", + "✖ {p}: no hay ningún jugador con este apodo — revisa cómo se escribe", + "✖ {p}: nessun giocatore con questo nickname — controlla come si scrive", + ], + [ + "Into “{name}” (already {n} there; only new games are added)", + "В базу «{name}» (там уже {n}; добавятся только новые)", + "Dans « {name} » (déjà {n} ; seules les nouvelles parties sont ajoutées)", + "In „{name}“ (schon {n} dort; nur neue Partien kommen dazu)", + "En «{name}» (ya hay {n}; solo se añaden las nuevas)", + "In «{name}» (già {n}; si aggiungono solo le nuove)", + ], + [ + "Into the new database “{name}”", "В новую базу «{name}»", "Dans la nouvelle base « {name} »", "In die neue Datenbank „{name}“", "En la nueva base «{name}»", "Nella nuova base «{name}»", ], + [ + "Lichess: {n} of about {t} · about {m} min left", + "Lichess: {n} из примерно {t} · осталось около {m} мин", + "Lichess : {n} sur environ {t} · encore environ {m} min", + "Lichess: {n} von etwa {t} · noch etwa {m} Min.", + "Lichess: {n} de unas {t} · quedan unos {m} min", + "Lichess: {n} di circa {t} · mancano circa {m} min", + ], + [ + "Chess.com: month {i} of {n} · {games}", + "Chess.com: месяц {i} из {n} · {games}", + "Chess.com : mois {i} sur {n} · {games}", + "Chess.com: Monat {i} von {n} · {games}", + "Chess.com: mes {i} de {n} · {games}", + "Chess.com: mese {i} di {n} · {games}", + ], [ "Checking engine…", "Проверка движка…", diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 8a838b7..e119fc5 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -207,6 +207,8 @@ pub struct Library { pub online: bool, /// Online databases being downloaded or updated. pub online_busy: Vec, + /// Games downloaded so far while downloads run (shown on the shelf card). + pub online_running: Option, /// A newer version to offer (its number), next to Settings. pub update: Option, /// File sizes of databases (`file_size`). @@ -232,6 +234,7 @@ impl Library { scroll_to_selected: false, online: false, online_busy: Vec::new(), + online_running: None, sizes: HashMap::new(), update: None, } @@ -618,7 +621,7 @@ impl Library { if self.online && ui .button("🌐") - .on_hover_text(tr("Download your online games by nickname into a database")) + .on_hover_text(tr("Download any player's games by nickname into a database: yours, a pupil's, an opponent's")) .clicked() { actions.push(LibraryAction::OnlineGames); @@ -701,17 +704,26 @@ impl Library { let visuals = ui.style().interact(&resp); ui.painter() .rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside); - for (dy, text) in [(-9.0, tr("Games from")), (9.0, "Lichess · Chess.com")] { - ui.painter().text( - rect.center() + vec2(0.0, dy), - egui::Align2::CENTER_CENTER, - text, - egui::FontId::proportional(14.0), - visuals.text_color(), - ); - } + let below = match self.online_running { + Some(n) => trf("downloading… {n}", &[("n", &large_db::grouped(n))]), + None => "Lichess · Chess.com".to_owned(), + }; + ui.painter().text( + rect.center() + vec2(0.0, -9.0), + egui::Align2::CENTER_CENTER, + format!("🌐 {}", tr("Online games")), + egui::FontId::proportional(15.0), + visuals.text_color(), + ); + ui.painter().text( + rect.center() + vec2(0.0, 11.0), + egui::Align2::CENTER_CENTER, + below, + egui::FontId::proportional(13.0), + ui.visuals().weak_text_color(), + ); if resp - .on_hover_text(tr("Download your online games by nickname into a database")) + .on_hover_text(tr("Download any player's games by nickname into a database: yours, a pupil's, an opponent's")) .clicked() { actions.push(LibraryAction::OnlineGames); @@ -768,7 +780,11 @@ impl Library { ui.painter().text( rect.left_top() + vec2(12.0, 10.0), egui::Align2::LEFT_TOP, - "🗄", + if crate::online::is_online(path) { + "🌐" + } else { + "🗄" + }, egui::FontId::proportional(22.0), text_color, ); @@ -933,13 +949,28 @@ impl Library { if self.online_busy.contains(&path) { ui.add(egui::Spinner::new().size(14.0)); ui.label(RichText::new(tr("updating…")).weak()); - } else if self.online - && ui - .small_button(tr("⟳ Update")) - .on_hover_text(tr("Fetch the games played since the last download")) + } else { + let when = crate::online::State::load(&path) + .and_then(|s| s.updated) + .map(crate::online::ago); + let hint = if !self.online { + tr("No connection to Lichess and Chess.com").to_owned() + } else if let Some(w) = when { + trf( + "Fetch the games played since the last download ({when})", + &[("when", &w)], + ) + } else { + tr("Fetch the games played since the last download").to_owned() + }; + if ui + .add_enabled(self.online, egui::Button::new(tr("⟳ New games")).small()) + .on_hover_text(&hint) + .on_disabled_hover_text(&hint) .clicked() - { - actions.push(LibraryAction::UpdateOnline(path.clone())); + { + actions.push(LibraryAction::UpdateOnline(path.clone())); + } } } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { diff --git a/apps/desktop/src/online.rs b/apps/desktop/src/online.rs index 1307618..56d8b8e 100644 --- a/apps/desktop/src/online.rs +++ b/apps/desktop/src/online.rs @@ -1,6 +1,7 @@ -//! The user's games from Lichess and Chess.com, by nickname (no login): each platform's -//! games become a PGN database of their own in `/online/`, with a small -//! state file next to it so that "Update" fetches only the new games (and continues an +//! A player's games from Lichess and Chess.com, by nickname (no login; anyone's: the +//! user's own, a pupil's, an opponent's): they become a PGN database in +//! `/online/` (one per site, or both sites in one), with a small state +//! file next to it so that "Update" fetches only the new games (and continues an //! interrupted download). Both public APIs are probed at start; a platform that does not //! answer as expected (offline, the API changed) is simply not offered. //! @@ -53,9 +54,9 @@ fn agent(stream: bool) -> ureq::Agent { .http_status_as_error(false) .timeout_connect(Some(Duration::from_secs(10))) .timeout_recv_response(Some(Duration::from_secs(30))) - // A long export is one response: no limit on the body, only on the rest. + // A long export is one response: hours for the body (a stalled one ends). .timeout_recv_body(if stream { - None + Some(Duration::from_secs(4 * 3600)) } else { Some(Duration::from_secs(60)) }) @@ -74,6 +75,8 @@ pub enum Failure { Unexpected(String), /// Writing the database failed. Disk(String), + /// The database is being downloaded already. + Busy, } impl std::fmt::Display for Failure { @@ -83,6 +86,7 @@ impl std::fmt::Display for Failure { Failure::RateLimited => write!(f, "rate limited"), Failure::Unexpected(e) => write!(f, "unexpected answer: {e}"), Failure::Disk(e) => write!(f, "{e}"), + Failure::Busy => write!(f, "the database is being downloaded already"), } } } @@ -249,19 +253,54 @@ pub fn database_path(p: Platform, username: &str) -> Option { dir().map(|d| d.join(format!("{username} ({}).pgn", p.name()))) } -/// The database of several accounts in one: "Name (Lichess + Chess.com).pgn", named -/// after the first account. +/// The database of several accounts in one: "Name (Lichess + Chess.com).pgn" when the +/// nicknames are the same, "Name (Lichess) + Other (Chess.com).pgn" otherwise (so that +/// another set of accounts never lands in the same file). pub fn combined_path(accounts: &[Account]) -> Option { let first = accounts.first()?; if accounts.len() == 1 { return database_path(first.platform, &first.username); } - let platforms = accounts + let same = accounts .iter() - .map(|a| a.platform.name()) - .collect::>() - .join(" + "); - dir().map(|d| d.join(format!("{} ({platforms}).pgn", first.username))) + .all(|a| a.username.eq_ignore_ascii_case(&first.username)); + let name = if same { + let platforms = accounts + .iter() + .map(|a| a.platform.name()) + .collect::>() + .join(" + "); + format!("{} ({platforms})", first.username) + } else { + accounts + .iter() + .map(|a| format!("{} ({})", a.username, a.platform.name())) + .collect::>() + .join(" + ") + }; + dir().map(|d| d.join(format!("{name}.pgn"))) +} + +/// The online databases already holding `account` (several when it was downloaded +/// alone and together with another one), those with more accounts first. +pub fn holding(account: &Account) -> Vec { + let Some(dir) = dir() else { + return Vec::new(); + }; + let Ok(entries) = std::fs::read_dir(&dir) else { + return Vec::new(); + }; + let mut found: Vec<(usize, PathBuf)> = entries + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "pgn")) + .filter_map(|p| { + let s = State::load(&p)?; + s.holds(account).then_some((s.accounts.len(), p)) + }) + .collect(); + found.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1))); + found.into_iter().map(|(_, p)| p).collect() } fn state_path(pgn: &Path) -> PathBuf { @@ -275,6 +314,11 @@ pub struct AccountState { pub username: String, /// Lichess: creation time (ms) of the newest game fetched. pub lichess_last: Option, + /// Lichess: games still being played when last fetched (id, creation time ms): + /// the next update asks again from the oldest of them, so that a long + /// (correspondence) game is fetched once it ends. + #[serde(default)] + pub lichess_pending: Vec<(String, i64)>, /// Chess.com: the newest month fetched ("2026/10") and the end time (s) of its /// last game fetched. pub chesscom_month: Option, @@ -288,8 +332,21 @@ pub struct State { pub accounts: Vec, /// Games written so far. pub games: u64, + /// When the last download finished (Unix seconds). + #[serde(default)] + pub updated: Option, + /// The length of the database file when the state was saved, and its last bytes: + /// what a crash appended after that is cut off before the next download (only if + /// the file still ends the same way there, i.e. nobody else changed it). + #[serde(default)] + pub bytes: Option, + #[serde(default)] + pub tail: Vec, } +/// How many last bytes of the file the state remembers. +const TAIL: usize = 64; + impl State { pub fn load(pgn: &Path) -> Option { let text = std::fs::read_to_string(state_path(pgn)).ok()?; @@ -307,6 +364,10 @@ impl State { .map_err(|e| Failure::Disk(e.to_string())) } + fn holds(&self, a: &Account) -> bool { + self.accounts.iter().any(|s| s.is(a)) + } + /// The accounts of the database, to update it. pub fn accounts(&self) -> Vec { self.accounts @@ -323,11 +384,52 @@ impl State { } } +impl AccountState { + fn is(&self, a: &Account) -> bool { + self.platform == Some(a.platform) && self.username.eq_ignore_ascii_case(&a.username) + } +} + +impl Account { + /// The same account (the counts aside). + pub fn same(&self, other: &Account) -> bool { + self.platform == other.platform && self.username.eq_ignore_ascii_case(&other.username) + } +} + /// An online database (it has a state file). pub fn is_online(pgn: &Path) -> bool { dir().is_some_and(|d| pgn.parent() == Some(d.as_path())) && state_path(pgn).exists() } +/// What a running download is doing, for the progress line: the account (its index in +/// the accounts passed to [`download`]), the games of that account so far, and for +/// Chess.com the months done of all. +#[derive(Debug, Default)] +pub struct Progress { + pub account: AtomicUsize, + pub games: AtomicUsize, + pub months_done: AtomicUsize, + pub months_total: AtomicUsize, +} + +fn now_secs() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64) +} + +/// "5 min ago", "3 h ago", "2 d ago" for a time in Unix seconds. +pub fn ago(t: i64) -> String { + use crate::i18n::trf; + let s = (now_secs() - t).max(0); + match s { + 0..3600 => trf("{n} min ago", &[("n", &(s / 60).max(1))]), + 3600..86400 => trf("{n} h ago", &[("n", &(s / 3600))]), + _ => trf("{n} d ago", &[("n", &(s / 86400))]), + } +} + /// The result of a download. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Done { @@ -339,30 +441,83 @@ pub struct Done { pub cancelled: bool, } +/// The databases being written now: one download per file at a time. +static WRITING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Holds a database for one download; released when dropped. +struct Claim(PathBuf); + +impl Claim { + fn take(path: &Path) -> Option { + let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); + if w.iter().any(|p| p == path) { + return None; + } + w.push(path.to_owned()); + Some(Claim(path.to_owned())) + } +} + +impl Drop for Claim { + fn drop(&mut self) { + let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); + w.retain(|p| *p != self.0); + } +} + /// Appends games to the database file and keeps the state in step. struct Writer { path: PathBuf, file: std::io::BufWriter, state: State, added: u64, + /// The file's length and last bytes as written (flushed or not). + len: u64, + tail: Vec, } impl Writer { - fn open(path: &Path, state: State) -> Result { + /// Opens the database for appending; a state that does not match the file (the file + /// is gone, or a crash left games after the state) is put right first. + fn open(path: &Path, mut state: State) -> Result { let disk = |e: std::io::Error| Failure::Disk(e.to_string()); if let Some(d) = path.parent() { std::fs::create_dir_all(d).map_err(disk)?; } let file = std::fs::OpenOptions::new() .create(true) + .read(true) .append(true) .open(path) .map_err(disk)?; + let mut len = file.metadata().map_err(disk)?.len(); + if let Some(b) = state.bytes + && len > b + && b as usize >= state.tail.len() + { + let mut end = vec![0; state.tail.len()]; + use std::io::{Read, Seek, SeekFrom}; + let mut f = &file; + f.seek(SeekFrom::Start(b - state.tail.len() as u64)) + .and_then(|_| f.read_exact(&mut end)) + .map_err(disk)?; + if end == state.tail { + file.set_len(b).map_err(disk)?; + len = b; + } + } + let tail = if len == state.bytes.unwrap_or(u64::MAX) { + std::mem::take(&mut state.tail) + } else { + Vec::new() + }; Ok(Writer { path: path.to_owned(), file: std::io::BufWriter::new(file), state, added: 0, + len, + tail, }) } @@ -371,10 +526,16 @@ impl Writer { if pgn.is_empty() { return Ok(()); } - self.file - .write_all(pgn.as_bytes()) - .and_then(|_| self.file.write_all(b"\n\n")) - .map_err(|e| Failure::Disk(e.to_string()))?; + for part in [pgn.as_bytes(), b"\n\n"] { + self.file + .write_all(part) + .map_err(|e| Failure::Disk(e.to_string()))?; + self.len += part.len() as u64; + self.tail.extend_from_slice(part); + } + if self.tail.len() > TAIL { + self.tail.drain(..self.tail.len() - TAIL); + } self.added += 1; self.state.games += 1; Ok(()) @@ -385,10 +546,15 @@ impl Writer { self.file .flush() .map_err(|e| Failure::Disk(e.to_string()))?; + self.state.bytes = Some(self.len); + self.state.tail = self.tail.clone(); self.state.save(&self.path) } fn done(mut self, cancelled: bool) -> Result { + if !cancelled { + self.state.updated = Some(now_secs()); + } self.commit()?; Ok(Done { path: self.path, @@ -399,38 +565,30 @@ impl Writer { } } -/// Fetches the games of `accounts` new since the last run into their database (one -/// database for all of them); `progress` counts the games added. Cancelling keeps what -/// was fetched. +/// Fetches the games of `accounts` new since the last run into the database at `path` +/// (one database for all of them); `progress` counts the games added, `status` tells +/// what is being fetched. Cancelling keeps what was fetched. One download per database +/// at a time ([`Failure::Busy`] otherwise). pub fn download( - accounts: &[Account], - progress: &AtomicUsize, - cancel: &AtomicBool, -) -> Result { - let path = combined_path(accounts).ok_or_else(|| Failure::Disk("no data directory".into()))?; - download_to(accounts, &path, progress, cancel) -} - -/// [`download`] into the database at `path`. -fn download_to( accounts: &[Account], path: &Path, progress: &AtomicUsize, cancel: &AtomicBool, + status: &Progress, ) -> Result { + let _claim = Claim::take(path).ok_or(Failure::Busy)?; let path = path.to_owned(); - let mut state = State::load(&path).unwrap_or_else(|| { - // A database without its state: start it anew rather than append duplicates. - let _ = std::fs::remove_file(&path); - State::default() - }); + let mut state = State::load(&path) + // The games are gone (the file was deleted): fetch them again. + .filter(|s| path.exists() || s.games == 0) + .unwrap_or_else(|| { + // A database without its state: start it anew rather than append duplicates. + let _ = std::fs::remove_file(&path); + State::default() + }); // Accounts not in the database yet start from their first game. for a in accounts { - if !state - .accounts - .iter() - .any(|s| s.platform == Some(a.platform) && s.username.eq_ignore_ascii_case(&a.username)) - { + if !state.holds(a) { state.accounts.push(AccountState { platform: Some(a.platform), username: a.username.clone(), @@ -441,17 +599,14 @@ fn download_to( let mut w = Writer::open(&path, state)?; let mut result = Ok(false); for i in 0..w.state.accounts.len() { - let wanted = accounts.iter().any(|a| { - Some(a.platform) == w.state.accounts[i].platform - && a.username - .eq_ignore_ascii_case(&w.state.accounts[i].username) - }); - if !wanted { + let Some(k) = accounts.iter().position(|a| w.state.accounts[i].is(a)) else { continue; - } + }; + status.account.store(k, Ordering::Relaxed); + status.games.store(0, Ordering::Relaxed); result = match w.state.accounts[i].platform { - Some(Platform::Lichess) => lichess(&mut w, i, progress, cancel), - Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel), + Some(Platform::Lichess) => lichess(&mut w, i, progress, cancel, status), + Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel, status), None => Ok(false), }; if !matches!(result, Ok(false)) { @@ -468,6 +623,56 @@ fn download_to( } } +#[cfg(test)] +fn download_to( + accounts: &[Account], + path: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result { + download(accounts, path, progress, cancel, &Progress::default()) +} + +/// Lichess's answer for one game, as far as the download cares. +struct LichessGame<'a> { + id: &'a str, + created: i64, + /// Still being played (not exported as a game yet). + playing: bool, + standard: bool, + pgn: &'a str, +} + +fn lichess_game(v: &Value) -> Option> { + Some(LichessGame { + id: v["id"].as_str()?, + created: v["createdAt"].as_i64()?, + playing: matches!(v["status"].as_str(), Some("created" | "started")), + standard: v["variant"] + .as_str() + .is_none_or(|x| x == "standard" || x == "fromPosition"), + pgn: v["pgn"].as_str()?, + }) +} + +/// What to do with a game of the Lichess export: `Some(write?)`, given the newest game +/// fetched before this run and the games pending then (unfinished). The export repeats +/// games from the oldest pending one on; those fetched already are skipped. +fn lichess_keep(a: &mut AccountState, g: &LichessGame, before: Option) -> bool { + let pending = a.lichess_pending.iter().position(|(id, _)| id == g.id); + if g.playing { + if pending.is_none() && g.standard { + a.lichess_pending.push((g.id.to_owned(), g.created)); + } + return false; + } + if let Some(k) = pending { + a.lichess_pending.remove(k); + return g.standard; + } + g.standard && before.is_none_or(|b| g.created > b) +} + /// The games of account `i` of the writer's database from Lichess. `Ok(true)` when /// cancelled. fn lichess( @@ -475,15 +680,25 @@ fn lichess( i: usize, progress: &AtomicUsize, cancel: &AtomicBool, + status: &Progress, ) -> Result { + let a = &w.state.accounts[i]; + let before = a.lichess_last; + let from = a + .lichess_pending + .iter() + .map(|(_, t)| *t) + .chain(before.map(|b| b + 1)) + .min(); + let pending_before: Vec = a.lichess_pending.iter().map(|(id, _)| id.clone()).collect(); let mut url = format!( - "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&pgnInJson=true\ + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=false&pgnInJson=true\ &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence\ &clocks=false&evals=false&opening=true", - w.state.accounts[i].username + a.username ); - if let Some(last) = w.state.accounts[i].lichess_last { - url.push_str(&format!("&since={}", last + 1)); + if let Some(from) = from { + url.push_str(&format!("&since={from}")); } let resp = agent(true) .get(&url) @@ -496,6 +711,7 @@ fn lichess( code => return Err(Failure::Unexpected(format!("HTTP {code}"))), } let reader = BufReader::new(resp.into_body().into_reader()); + let mut seen: Vec = Vec::new(); for (n, line) in reader.lines().enumerate() { if cancel.load(Ordering::Relaxed) { return Ok(true); @@ -506,23 +722,29 @@ fn lichess( } let v: Value = serde_json::from_str(&line).map_err(|e| Failure::Unexpected(e.to_string()))?; - let (Some(pgn), Some(created)) = (v["pgn"].as_str(), v["createdAt"].as_i64()) else { - return Err(Failure::Unexpected( - "a game without pgn or createdAt".into(), - )); - }; - if v["variant"] - .as_str() - .is_none_or(|x| x == "standard" || x == "fromPosition") - { - w.game(pgn)?; - progress.fetch_add(1, Ordering::Relaxed); + let g = lichess_game(&v) + .ok_or_else(|| Failure::Unexpected("a game without id, pgn or createdAt".into()))?; + if pending_before.iter().any(|id| id == g.id) { + seen.push(g.id.to_owned()); } - w.state.accounts[i].lichess_last = Some(created); + let a = &mut w.state.accounts[i]; + if lichess_keep(a, &g, before) { + let pgn = g.pgn.to_owned(); + w.game(&pgn)?; + progress.fetch_add(1, Ordering::Relaxed); + status.games.fetch_add(1, Ordering::Relaxed); + } + let a = &mut w.state.accounts[i]; + a.lichess_last = Some(a.lichess_last.map_or(g.created, |l| l.max(g.created))); if n % 100 == 99 { w.commit()?; } } + // The whole export arrived: a game pending before that did not come again is gone + // (deleted, or a variant that ended). + w.state.accounts[i] + .lichess_pending + .retain(|(id, _)| !pending_before.contains(id) || seen.contains(id)); Ok(false) } @@ -533,10 +755,14 @@ fn chesscom( i: usize, progress: &AtomicUsize, cancel: &AtomicBool, + status: &Progress, ) -> Result { let lower = w.state.accounts[i].username.to_ascii_lowercase(); let months = archives(&lower)?; + status.months_total.store(months.len(), Ordering::Relaxed); + status.months_done.store(0, Ordering::Relaxed); for url in months { + status.months_done.fetch_add(1, Ordering::Relaxed); // ".../games/2026/10" → "2026/10"; months before the last fetched are done. let month = url.rsplitn(3, '/').take(2).collect::>(); let month = format!( @@ -574,6 +800,7 @@ fn chesscom( } w.game(pgn)?; progress.fetch_add(1, Ordering::Relaxed); + status.games.fetch_add(1, Ordering::Relaxed); w.state.accounts[i].chesscom_last_end = Some(end); } // The mark moves to this month even when it had no standard games (the end @@ -633,11 +860,13 @@ impl Probe { self.job = None; self.last = Some(std::time::Instant::now()); } - if self.job.is_none() - && !self.available.iter().all(|a| *a) - && self.last.is_some_and(|t| t.elapsed() >= Self::RETRY) - { - self.spawn(); + if self.job.is_none() && !self.available.iter().all(|a| *a) { + match self.last { + Some(t) if t.elapsed() >= Self::RETRY => self.spawn(), + // Wake up for the retry even when nothing else repaints. + Some(t) => self.ctx.request_repaint_after(Self::RETRY - t.elapsed()), + None => {} + } } } @@ -654,6 +883,148 @@ impl Probe { mod tests { use super::*; + fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("cp-online-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn account(p: Platform, name: &str) -> Account { + Account { + platform: p, + username: name.into(), + games: None, + months: None, + } + } + + const GAME: &str = "[Event \"x\"]\n\n1. e4 e5 1-0"; + + #[test] + fn a_crash_leaves_no_duplicates() { + let dir = temp_dir("crash"); + let path = dir.join("db.pgn"); + let state = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "a".into(), + ..AccountState::default() + }], + ..State::default() + }; + let mut w = Writer::open(&path, state).unwrap(); + w.game(GAME).unwrap(); + w.game(GAME).unwrap(); + w.commit().unwrap(); + let good = std::fs::read(&path).unwrap(); + // Games written after the last commit, then the process died. + w.game(GAME).unwrap(); + w.file.flush().unwrap(); + drop(w); + assert!(std::fs::read(&path).unwrap().len() > good.len()); + let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); + assert_eq!(w.state.games, 2); + drop(w); + assert_eq!(std::fs::read(&path).unwrap(), good, "cut back to the state"); + + // Somebody else changed the file: it is left alone. + let mut other = good.clone(); + other[0] = b' '; + other.extend_from_slice(GAME.as_bytes()); + std::fs::write(&path, &other).unwrap(); + let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); + drop(w); + assert_eq!(std::fs::read(&path).unwrap(), other); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_deleted_database_is_downloaded_again() { + let dir = temp_dir("deleted"); + let path = dir.join("db.pgn"); + let state = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "a".into(), + lichess_last: Some(5), + ..AccountState::default() + }], + games: 7, + ..State::default() + }; + state.save(&path).unwrap(); + let never = AtomicBool::new(false); + // No account asked for: nothing fetched, only the state put right. + let d = download_to(&[], &path, &AtomicUsize::new(0), &never).unwrap(); + assert_eq!(d.total, 0); + let s = State::load(&path).unwrap_or_default(); + assert!(s.accounts.iter().all(|a| a.lichess_last.is_none())); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn one_download_per_database() { + let path = PathBuf::from("/nonexistent/cp-claim.pgn"); + let first = Claim::take(&path).expect("free"); + assert!(Claim::take(&path).is_none()); + let never = AtomicBool::new(false); + assert_eq!( + download_to(&[], &path, &AtomicUsize::new(0), &never), + Err(Failure::Busy) + ); + drop(first); + assert!(Claim::take(&path).is_some()); + } + + #[test] + fn names_of_merged_databases() { + let name = |a: &[Account]| { + combined_path(a) + .unwrap() + .file_name() + .unwrap() + .to_string_lossy() + .into_owned() + }; + let li = account(Platform::Lichess, "Magnus"); + assert_eq!(name(std::slice::from_ref(&li)), "Magnus (Lichess).pgn"); + let cc = account(Platform::ChessCom, "magnus"); + assert_eq!(name(&[li.clone(), cc]), "Magnus (Lichess + Chess.com).pgn"); + let other = account(Platform::ChessCom, "MagnusCarlsen"); + assert_eq!( + name(&[li, other]), + "Magnus (Lichess) + MagnusCarlsen (Chess.com).pgn" + ); + } + + #[test] + fn unfinished_lichess_games_come_later() { + let mut a = AccountState::default(); + let g = |id: &'static str, created: i64, playing: bool| LichessGame { + id, + created, + playing, + standard: true, + pgn: "", + }; + // First run: a correspondence game is still on, a later one is over. + assert!(!lichess_keep(&mut a, &g("corr", 10, true), None)); + assert!(lichess_keep(&mut a, &g("blitz", 20, false), None)); + assert_eq!(a.lichess_pending, vec![("corr".to_owned(), 10)]); + // The next run starts from the pending game: it is over now and is kept, the + // game fetched before is not repeated. + assert!(lichess_keep(&mut a, &g("corr", 10, false), Some(20))); + assert!(!lichess_keep(&mut a, &g("blitz", 20, false), Some(20))); + assert!(lichess_keep(&mut a, &g("new", 30, false), Some(20))); + assert!(a.lichess_pending.is_empty()); + // A variant game is neither kept nor waited for. + let mut v = g("960", 40, true); + v.standard = false; + assert!(!lichess_keep(&mut a, &v, Some(30))); + assert!(a.lichess_pending.is_empty()); + } + /// Against the real sites, with an account given by `CP_ONLINE_NICK` (kept out of /// the repository): lookup, an interrupted Lichess download continued without gaps /// or duplicates, a full Chess.com download, and an update that adds nothing. Run @@ -853,6 +1224,7 @@ mod tests { ..AccountState::default() }], games: 3, + ..State::default() }; s.save(&pgn).unwrap(); assert_eq!(State::load(&pgn), Some(s)); diff --git a/apps/desktop/src/online_ui.rs b/apps/desktop/src/online_ui.rs index b41bea6..c31c527 100644 --- a/apps/desktop/src/online_ui.rs +++ b/apps/desktop/src/online_ui.rs @@ -1,29 +1,54 @@ -//! The window "Games from Lichess and Chess.com": one nickname (another one for -//! Chess.com if it differs), the platforms to look on, what was found, then the -//! downloads with their progress. Only the platforms that answered the probe at start -//! are offered (`online::Probe`). +//! The window "Games from Lichess and Chess.com": a player's nickname (anyone's: the +//! user's own, a pupil's, an opponent's; another one for Chess.com if it differs), the +//! platforms to look on, what was found, then the downloads with their progress. Only the +//! platforms that answered the probe at start are offered (`online::Probe`). + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::Ordering; use egui::{RichText, Ui}; use crate::board_search::Background; -use crate::i18n::{tr, trf}; +use crate::i18n::{games, tr, trf}; use crate::online::{self, Account, Done, Failure, Lookup, Platform, Probe}; use crate::settings::Settings; /// What the window asks of the application. pub enum OnlineEvent { /// A database was downloaded (or partly, then cancelled): put it on the shelf. - Added(std::path::PathBuf), + Added(PathBuf), /// A database got new games: reload it. - Updated(std::path::PathBuf), + Updated(PathBuf), + /// Show this database (and the window closes). + Open(PathBuf), + /// A download finished while the window was closed: say how it went. + Message(String), } struct Job { /// One account, or several downloaded into one database. accounts: Vec, + path: PathBuf, /// Updating a database already on the shelf (not a first download). update: bool, + /// The database is new (so the totals of the accounts are what is left to fetch). + fresh: bool, + status: Arc, work: Background>, + /// When Stop was pressed: a download that does not stop soon (a stalled + /// connection) leaves the list; its database stays claimed until it ends. + stopped: Option, +} + +/// A finished download. +struct Outcome { + accounts: Vec, + path: PathBuf, + update: bool, + /// The platform that failed (`None`: the disk, or not known). + platform: Option, + result: Result, } #[derive(Default)] @@ -38,9 +63,7 @@ pub struct OnlineDialog { /// The nicknames `found` answers. found_for: (String, String), jobs: Vec, - /// Per finished download: the platforms ("Lichess + Chess.com"), the database name - /// and the outcome. - results: Vec<(String, String, Result)>, + results: Vec, /// Two accounts found: download them into separate databases (one by default). separate: bool, /// Dev hook (screenshots): look the nickname up once the probe answered, and @@ -49,26 +72,89 @@ pub struct OnlineDialog { auto_download: bool, } -fn count(n: u64) -> String { - crate::large_db::grouped(n as usize) -} - -/// "Lichess + Chess.com". -fn platforms(accounts: &[Account]) -> String { - accounts - .iter() - .map(|a| a.platform.name()) - .collect::>() - .join(" + ") +/// Where the found accounts go: all into one database (`together`) or each into its +/// own. A database already holding the accounts is kept (also when one site does not +/// answer this time: its partner's games still go where they went before). +fn targets(start: &[Account], together: bool) -> Vec<(Vec, PathBuf)> { + let groups: Vec> = if together { + vec![start.to_vec()] + } else { + start.iter().map(|a| vec![a.clone()]).collect() + }; + // Only one account found: any database holding it (the merged one first). + let any = start.len() == 1; + groups + .into_iter() + .filter_map(|g| { + let existing = online::holding(&g[0]).into_iter().find(|p| { + online::State::load(p).is_some_and(|s| { + let mine = s.accounts(); + any || (mine.len() == g.len() + && g.iter().all(|a| mine.iter().any(|m| m.same(a)))) + }) + }); + let path = existing.or_else(|| online::combined_path(&g))?; + Some((g, path)) + }) + .collect() } /// The file name of a database without the extension. -fn db_name(path: &std::path::Path) -> String { +fn db_name(path: &Path) -> String { path.file_stem() .map(|s| s.to_string_lossy().into_owned()) .unwrap_or_default() } +/// What went wrong, in words for a chess player (the technical text goes under +/// "Details"). +fn failure_text(platform: Option, e: &Failure) -> String { + let p = platform.map_or("—", Platform::name); + match e { + Failure::Network(_) => trf( + "{p} does not answer. Check the internet connection and try again.", + &[("p", &p)], + ), + Failure::RateLimited => trf( + "{p} asks for a pause: too many requests in a row. Wait a minute and try again; what is downloaded is kept.", + &[("p", &p)], + ), + Failure::Unexpected(_) => trf( + "{p} answered in a way ChessPenguin does not understand: the site may have changed. Try later or update ChessPenguin.", + &[("p", &p)], + ), + Failure::Disk(_) => { + tr("Could not write the database: no permission to write or the disk is full.") + .to_owned() + } + Failure::Busy => tr("This database is being downloaded already.").to_owned(), + } +} + +/// "“Name”: +12 games, 6 600 in all" and the like. +fn outcome_text(o: &Outcome) -> String { + let name = db_name(&o.path); + match &o.result { + Ok(d) if d.cancelled => trf( + "“{name}”: stopped, {total} in the database", + &[("name", &name), ("total", &games(d.total as usize))], + ), + Ok(d) if d.added == 0 => trf("“{name}”: no new games", &[("name", &name)]), + Ok(d) => trf( + "“{name}”: +{added}, {total} in all", + &[ + ("name", &name), + ("added", &games(d.added as usize)), + ("total", &games(d.total as usize)), + ], + ), + Err(e) => trf( + "“{name}”: {e}", + &[("name", &name), ("e", &failure_text(o.platform, e))], + ), + } +} + impl OnlineDialog { /// Opens the window with the nicknames used last time. pub fn open_with(&mut self, settings: &Settings) { @@ -96,37 +182,65 @@ impl OnlineDialog { } /// Databases being downloaded or updated. - pub fn busy(&self) -> Vec { - self.jobs + pub fn busy(&self) -> Vec { + self.jobs.iter().map(|j| j.path.clone()).collect() + } + + /// The games downloaded so far by the running jobs (for the shelf card), if any run. + pub fn running(&self) -> Option { + (!self.jobs.is_empty()).then(|| self.jobs.iter().map(|j| j.work.progress()).sum()) + } + + /// Stops the downloads and waits a little for them to save what they fetched (on + /// quitting: the next update then continues without duplicates). Returns the new + /// databases among them, to put on the shelf with what they got so far. + pub fn stop_all(&mut self) -> Vec { + let new = self + .jobs .iter() - .filter_map(|j| online::combined_path(&j.accounts)) - .collect() + .filter(|j| !j.update) + .map(|j| j.path.clone()) + .collect(); + for j in &self.jobs { + j.work.cancel(); + } + let start = std::time::Instant::now(); + while !self.jobs.is_empty() && start.elapsed() < std::time::Duration::from_secs(3) { + self.jobs.retain(|j| j.work.poll().is_none()); + std::thread::sleep(std::time::Duration::from_millis(30)); + } + new } /// Fetches the new games of an online database on the shelf. - pub fn update(&mut self, path: &std::path::Path, ctx: &egui::Context) { + pub fn update(&mut self, path: &Path, ctx: &egui::Context) { let Some(state) = online::State::load(path) else { return; }; - if self.busy().iter().any(|p| p == path) { - return; - } - self.start(state.accounts(), true, ctx); + self.start(state.accounts(), path.to_owned(), true, ctx); } - fn start(&mut self, accounts: Vec, update: bool, ctx: &egui::Context) { - if accounts.is_empty() { + fn start(&mut self, accounts: Vec, path: PathBuf, update: bool, ctx: &egui::Context) { + if self.jobs.iter().any(|j| j.path == path) { return; } + let fresh = online::State::load(&path).is_none(); let now = ctx.input(|i| i.time); let a = accounts.clone(); + let status = Arc::new(online::Progress::default()); + let (s, p) = (status.clone(), path.clone()); if let Some(work) = Background::spawn(ctx, now, move |progress, cancel| { - Some(online::download(&a, progress, cancel)) + Some(online::download(&a, &p, progress, cancel, &s)) }) { + self.results.retain(|o| o.path != path); self.jobs.push(Job { accounts, + path, update, + fresh, + status, work, + stopped: None, }); } } @@ -157,23 +271,43 @@ impl OnlineDialog { while i < self.jobs.len() { if let Some(r) = self.jobs[i].work.poll() { let job = self.jobs.remove(i); - let r = r.unwrap_or(Err(Failure::Network("stopped".into()))); - if let Ok(done) = &r { - if job.update { - if done.added > 0 { - events.push(OnlineEvent::Updated(done.path.clone())); - } - } else if done.total > 0 { - events.push(OnlineEvent::Added(done.path.clone())); + let result = r.unwrap_or(Err(Failure::Network("stopped".into()))); + // What a failed download got before the failure is kept: a new + // database goes on the shelf with it, an updated one is reloaded. + let total = match &result { + Ok(d) => d.total, + Err(_) => online::State::load(&job.path).map_or(0, |s| s.games), + }; + if job.update { + if result.as_ref().map_or(true, |d| d.added > 0) { + events.push(OnlineEvent::Updated(job.path.clone())); } + } else if total > 0 { + events.push(OnlineEvent::Added(job.path.clone())); } - let label = platforms(&job.accounts); - let name = online::combined_path(&job.accounts) - .map(|p| db_name(&p)) - .unwrap_or_default(); - self.results.retain(|(_, n, _)| *n != name); - self.results.push((label, name, r)); - // An update finished with the window closed: say so once it is opened. + let platform = match &result { + Err(Failure::Disk(_)) | Ok(_) => None, + Err(_) => job + .accounts + .get(job.status.account.load(Ordering::Relaxed)) + .map(|a| a.platform), + }; + let outcome = Outcome { + accounts: job.accounts, + path: job.path, + update: job.update, + platform, + result, + }; + if !self.open { + events.push(OnlineEvent::Message(outcome_text(&outcome))); + } + self.results.push(outcome); + } else if self.jobs[i] + .stopped + .is_some_and(|t| t.elapsed() > std::time::Duration::from_secs(10)) + { + self.jobs.remove(i); } else { i += 1; } @@ -185,33 +319,40 @@ impl OnlineDialog { return (events, changed); } let mut open = true; - egui::Window::new(tr("Your games from Lichess and Chess.com")) + egui::Window::new(tr("Games from Lichess and Chess.com")) .open(&mut open) - .default_width(520.0) + .default_width(540.0) .collapsible(false) .pivot(egui::Align2::CENTER_TOP) .default_pos(ctx.content_rect().center_top() + egui::vec2(0.0, 120.0)) .show(ctx, |ui| { - changed |= self.body(ui, probe, settings); + changed |= self.body(ui, probe, settings, &mut events); }); - if !open { + if !open || events.iter().any(|e| matches!(e, OnlineEvent::Open(_))) { self.open = false; } (events, changed) } - fn body(&mut self, ui: &mut Ui, probe: &Probe, settings: &mut Settings) -> bool { + fn body( + &mut self, + ui: &mut Ui, + probe: &Probe, + settings: &mut Settings, + events: &mut Vec, + ) -> bool { let mut changed = false; ui.label( RichText::new(tr( - "Your online games become a database here, to search and analyse. Only the nickname is needed, no login.", + "Any player's games — yours, a pupil's, an opponent's — become a database here, to search and analyse. Only the nickname is needed, no login.", )) .weak(), ); ui.add_space(6.0); let both = probe.has(Platform::Lichess) && probe.has(Platform::ChessCom); + let mut enter = false; ui.horizontal(|ui| { - ui.label(tr("Nickname")); + ui.label(tr("Player's nickname")); let r = ui.add( egui::TextEdit::singleline(&mut self.nick) .hint_text(tr("as on the site")) @@ -220,6 +361,7 @@ impl OnlineDialog { if r.changed() { self.found.clear(); } + enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); }); ui.horizontal(|ui| { for p in Platform::ALL { @@ -238,9 +380,9 @@ impl OnlineDialog { Some(o) => { ui.horizontal(|ui| { ui.label(tr("Nickname on Chess.com")); - clear |= ui - .add(egui::TextEdit::singleline(o).desired_width(180.0)) - .changed(); + let r = ui.add(egui::TextEdit::singleline(o).desired_width(180.0)); + clear |= r.changed(); + enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); same = ui .small_button("✕") .on_hover_text(tr("The same nickname")) @@ -280,13 +422,9 @@ impl OnlineDialog { if auto { self.auto_find = false; } - if ui - .add_enabled( - !wanted.is_empty() && valid && !searching, - egui::Button::new(tr("Find")), - ) - .clicked() - || (auto && !wanted.is_empty() && valid) + let can = !wanted.is_empty() && valid && !searching; + if ui.add_enabled(can, egui::Button::new(tr("Find"))).clicked() + || ((auto || enter) && can) { let list: Vec<(Platform, String)> = wanted.iter().map(|p| (*p, self.nick_for(*p))).collect(); @@ -313,157 +451,233 @@ impl OnlineDialog { } }); if self.found_for == nicks && !self.found.is_empty() { - ui.add_space(4.0); - let mut start: Vec = Vec::new(); - for (p, l) in &self.found { - ui.horizontal(|ui| match l { - Lookup::Found(a) => { - let what = match (a.games, a.months) { - (Some(g), _) => { - let secs = g / online::LICHESS_RATE; - trf( - "{p}: {name} — up to {n} games (about {m} min the first time)", - &[ - ("p", &p.name()), - ("name", &a.username), - ("n", &count(g)), - ("m", &secs.div_ceil(60).max(1)), - ], - ) - } - (_, Some(m)) => trf( - "{p}: {name} — games of {m} months", - &[("p", &p.name()), ("name", &a.username), ("m", &m)], - ), - _ => format!("{}: {}", p.name(), a.username), - }; - ui.label(format!("✔ {what}")); - if !self.jobs.iter().any(|j| j.accounts.contains(a)) { - start.push(a.clone()); - } - } - Lookup::NotFound => { - ui.label( - RichText::new(trf("✖ {p}: no such player", &[("p", &p.name())])).weak(), - ); - } - Lookup::Failed(e) => { - ui.label( - RichText::new(trf( - "✖ {p}: no answer ({e})", - &[("p", &p.name()), ("e", e)], - )) - .color(ui.visuals().warn_fg_color), - ); - } - }); - } - // Both platforms: one database by default (the player's games together). - let together = start.len() > 1 && !self.separate; - if start.len() > 1 { - let mut one = !self.separate; - if ui - .checkbox( - &mut one, - tr("Put the games of both sites into one database"), - ) - .on_hover_text(tr("Otherwise each site gets a database of its own")) - .changed() + self.found_ui(ui); + } + self.jobs_ui(ui); + self.results_ui(ui, events); + changed + } + + /// What was found, the choice of one database or separate ones, and Download. + fn found_ui(&mut self, ui: &mut Ui) { + ui.add_space(4.0); + let start: Vec = self + .found + .iter() + .filter_map(|(_, l)| match l { + Lookup::Found(a) + if !self + .jobs + .iter() + .any(|j| j.accounts.iter().any(|x| x.same(a))) => { - self.separate = !one; + Some(a.clone()) } - } - // Where the games go, and what is there already. - let targets: Vec> = if together { - vec![start.clone()] - } else { - start.iter().map(|a| vec![a.clone()]).collect() - }; - for t in &targets { - if let Some(path) = online::combined_path(t) { - let text = match online::State::load(&path) { - Some(s) => trf( - "Into «{name}» (already {n} games there; only new ones are added)", - &[("name", &db_name(&path)), ("n", &count(s.games))], + _ => None, + }) + .collect(); + // Accounts some database already holds (then the "first time" estimate is wrong). + let held = |a: &Account| !online::holding(a).is_empty(); + for (p, l) in &self.found { + match l { + Lookup::Found(a) => { + let what = match (a.games, a.months) { + (Some(g), _) if !held(a) => { + let secs = g / online::LICHESS_RATE; + trf( + "{p}: {name} — {games}, about {m} min the first time", + &[ + ("p", &p.name()), + ("name", &a.username), + ("games", &games(g as usize)), + ("m", &secs.div_ceil(60).max(1)), + ], + ) + } + (Some(g), _) => trf( + "{p}: {name} — {games}", + &[ + ("p", &p.name()), + ("name", &a.username), + ("games", &games(g as usize)), + ], ), - None => trf( - "Into the new database «{name}»", - &[("name", &db_name(&path))], + (_, Some(m)) => trf( + "{p}: {name} — months with games: {m}", + &[("p", &p.name()), ("name", &a.username), ("m", &m)], ), + _ => format!("{}: {}", p.name(), a.username), }; - ui.label(RichText::new(text).weak()); + ui.label(format!("✔ {what}")); } - } - let auto = std::mem::take(&mut self.auto_download) && !start.is_empty(); - if !start.is_empty() && (ui.button(tr("⬇ Download")).clicked() || auto) { - // From the window the database goes (back) on the shelf, also when it - // was downloaded before and only gets the new games now. - for t in targets { - self.start(t, false, ui.ctx()); + Lookup::NotFound => { + ui.label( + RichText::new(trf( + "✖ {p}: no player with this nickname — check the spelling", + &[("p", &p.name())], + )) + .weak(), + ); + } + Lookup::Failed(e) => { + ui.label( + RichText::new(format!("✖ {}", failure_text(Some(*p), e))) + .color(ui.visuals().warn_fg_color), + ); } } } - if !self.jobs.is_empty() || !self.results.is_empty() { - ui.separator(); + if start.is_empty() { + return; } + // Both platforms: one database by default (the player's games together). + let together = start.len() > 1 && !self.separate; + if start.len() > 1 { + let mut one = !self.separate; + if ui + .checkbox( + &mut one, + tr("Merge the games of both sites into one database"), + ) + .on_hover_text(tr("Otherwise each site gets a database of its own")) + .changed() + { + self.separate = !one; + } + } + // Where the games go, and what is there already. + let targets = targets(&start, together); + for (_, path) in &targets { + let text = match online::State::load(path) { + Some(s) => trf( + "Into “{name}” (already {n} there; only new games are added)", + &[("name", &db_name(path)), ("n", &games(s.games as usize))], + ), + None => trf( + "Into the new database “{name}”", + &[("name", &db_name(path))], + ), + }; + ui.label(RichText::new(text).weak()); + } + ui.add_space(4.0); + let auto = std::mem::take(&mut self.auto_download); + if crate::widgets::primary(ui, tr("⬇ Download")).clicked() || auto { + // From the window the database goes (back) on the shelf, also when it was + // downloaded before and only gets the new games now. + for (t, path) in targets { + self.start(t, path, false, ui.ctx()); + } + } + } + + /// The running downloads: the database, the site and how far it got, Stop. + fn jobs_ui(&mut self, ui: &mut Ui) { + if self.jobs.is_empty() { + return; + } + ui.separator(); let mut stop = None; for (k, j) in self.jobs.iter().enumerate() { ui.horizontal(|ui| { ui.add(egui::Spinner::new().size(14.0)); - let n = j.work.progress() as u64; - let known: u64 = j.accounts.iter().filter_map(|a| a.games).sum(); - let label = platforms(&j.accounts); - let text = if known > 0 && j.accounts.iter().all(|a| a.games.is_some()) { - trf( - "{p}: {n} of up to {t} games", - &[("p", &label), ("n", &count(n)), ("t", &count(known))], - ) - } else { - trf("{p}: {n} games", &[("p", &label), ("n", &count(n))]) - }; - ui.label(text); + ui.label(RichText::new(db_name(&j.path)).strong()); if ui .small_button(tr("Stop")) .on_hover_text(tr( - "What is downloaded is kept; Update continues from there", + "What is downloaded is kept; downloading again continues from there", )) .clicked() { stop = Some(k); } }); + let s = &j.status; + let Some(a) = j.accounts.get(s.account.load(Ordering::Relaxed)) else { + continue; + }; + let n = s.games.load(Ordering::Relaxed) as u64; + match (a.platform, a.games) { + (Platform::Lichess, Some(total)) if j.fresh && total > 0 => { + let left = total.saturating_sub(n) / online::LICHESS_RATE; + ui.label(trf( + "Lichess: {n} of about {t} · about {m} min left", + &[ + ("n", &crate::large_db::grouped(n as usize)), + ("t", &crate::large_db::grouped(total as usize)), + ("m", &left.div_ceil(60).max(1)), + ], + )); + ui.add(egui::ProgressBar::new((n as f32 / total as f32).min(1.0))); + } + (Platform::ChessCom, _) if s.months_total.load(Ordering::Relaxed) > 0 => { + let (done, all) = ( + s.months_done.load(Ordering::Relaxed), + s.months_total.load(Ordering::Relaxed), + ); + ui.label(trf( + "Chess.com: month {i} of {n} · {games}", + &[("i", &done), ("n", &all), ("games", &games(n as usize))], + )); + ui.add(egui::ProgressBar::new(done as f32 / all as f32)); + } + (p, _) => { + ui.label(format!("{}: {}", p.name(), games(n as usize))); + } + } } if let Some(k) = stop { self.jobs[k].work.cancel(); + self.jobs[k] + .stopped + .get_or_insert_with(std::time::Instant::now); } - for (p, name, r) in &self.results { - let p = p.as_str(); - let line = match r { - Ok(d) if d.cancelled => trf( - "{p}: stopped, {t} games kept in «{name}»", - &[("p", &p), ("t", &count(d.total)), ("name", name)], - ), - Ok(d) if d.added == 0 => trf( - "{p}: nothing new, {t} games in «{name}»", - &[("p", &p), ("t", &count(d.total)), ("name", name)], - ), - Ok(d) => trf( - "{p}: +{n} games, {t} in «{name}»", - &[ - ("p", &p), - ("n", &count(d.added)), - ("t", &count(d.total)), - ("name", name), - ], - ), - Err(Failure::RateLimited) => trf( - "{p}: the site asks to wait a minute; then try again", - &[("p", &p)], - ), - Err(e) => trf("{p}: failed ({e})", &[("p", &p), ("e", e)]), - }; - ui.label(line); + ui.label( + RichText::new(tr( + "You can close the window: the download goes on, and what is downloaded is kept.", + )) + .weak(), + ); + } + + /// The finished downloads: how they went, Open the database / Try again. + fn results_ui(&mut self, ui: &mut Ui, events: &mut Vec) { + if self.results.is_empty() { + return; + } + ui.separator(); + let mut retry = None; + for (k, o) in self.results.iter().enumerate() { + match &o.result { + Ok(d) => { + ui.horizontal_wrapped(|ui| { + ui.label(format!("✔ {}", outcome_text(o))); + if d.total > 0 && ui.button(tr("Open the database")).clicked() { + events.push(OnlineEvent::Open(o.path.clone())); + } + }); + } + Err(e) => { + ui.label( + RichText::new(format!("⚠ {}", outcome_text(o))) + .color(ui.visuals().warn_fg_color), + ); + ui.horizontal(|ui| { + if ui.button(tr("Try again")).clicked() { + retry = Some(k); + } + egui::CollapsingHeader::new(tr("Details")) + .id_salt(("online-details", k)) + .show(ui, |ui| { + ui.label(RichText::new(e.to_string()).small().weak()); + }); + }); + } + } + } + if let Some(k) = retry { + let o = self.results.remove(k); + self.start(o.accounts, o.path, o.update, ui.ctx()); } - changed } } diff --git a/apps/desktop/src/update_ui.rs b/apps/desktop/src/update_ui.rs index 8023bbb..ba3b058 100644 --- a/apps/desktop/src/update_ui.rs +++ b/apps/desktop/src/update_ui.rs @@ -209,7 +209,7 @@ impl UpdateDialog { ui.label(tr("It starts after a restart. Unsaved games are asked about first; databases and settings stay as they are.")); ui.add_space(6.0); ui.horizontal(|ui| { - if primary(ui, tr("⟳ Restart now")).clicked() { + if crate::widgets::primary(ui, tr("⟳ Restart now")).clicked() { events.push(UpdateEvent::Restart(exe.clone())); } if ui.button(tr("Later")).clicked() { @@ -226,7 +226,7 @@ impl UpdateDialog { ui.label(tr("2. In the window of the disk image, drag the ChessPenguin icon onto the Applications folder and choose Replace.")); ui.label(tr("3. Start ChessPenguin from Applications.")); ui.add_space(6.0); - if primary(ui, tr("Quit ChessPenguin")).clicked() { + if crate::widgets::primary(ui, tr("Quit ChessPenguin")).clicked() { events.push(UpdateEvent::Quit); } return; @@ -296,7 +296,7 @@ impl UpdateDialog { )); ui.add_space(6.0); ui.horizontal(|ui| { - if primary(ui, action(retry, tr("⬆ Update"))).clicked() { + if crate::widgets::primary(ui, action(retry, tr("⬆ Update"))).clicked() { self.start(release, k, ui.ctx()); } self.not_now(ui, release, events); @@ -309,7 +309,7 @@ impl UpdateDialog { )); ui.add_space(6.0); ui.horizontal(|ui| { - if primary(ui, action(retry, tr("⬇ Download"))).clicked() { + if crate::widgets::primary(ui, action(retry, tr("⬇ Download"))).clicked() { self.start(release, kind, ui.ctx()); } self.not_now(ui, release, events); @@ -322,7 +322,7 @@ impl UpdateDialog { )); ui.add_space(6.0); ui.horizontal(|ui| { - if primary(ui, action(retry, tr("⬇ Download"))).clicked() { + if crate::widgets::primary(ui, action(retry, tr("⬇ Download"))).clicked() { self.start(release, k, ui.ctx()); } self.not_now(ui, release, events); @@ -385,15 +385,6 @@ fn heading(ui: &mut Ui, release: &Release) { ui.add_space(6.0); } -/// The main button of the window: filled, a little taller. -fn primary(ui: &mut Ui, label: &str) -> egui::Response { - ui.add( - egui::Button::new(RichText::new(label).strong()) - .fill(ui.visuals().selection.bg_fill) - .min_size(egui::vec2(0.0, 30.0)), - ) -} - /// A command in a monospace box with a Copy button beside it. fn command_line(ui: &mut Ui, command: &str, events: &mut Vec) { ui.horizontal(|ui| { @@ -406,7 +397,7 @@ fn command_line(ui: &mut Ui, command: &str, events: &mut Vec) { ui.set_max_width(width); ui.add(egui::Label::new(RichText::new(command).monospace()).wrap()); }); - if primary(ui, tr("Copy")).clicked() { + if crate::widgets::primary(ui, tr("Copy")).clicked() { events.push(UpdateEvent::CopyText(command.to_owned())); } }); diff --git a/apps/desktop/src/widgets.rs b/apps/desktop/src/widgets.rs index 5e5d516..dad8cea 100644 --- a/apps/desktop/src/widgets.rs +++ b/apps/desktop/src/widgets.rs @@ -39,3 +39,12 @@ pub fn update_button(ui: &mut egui::Ui, label: &str) -> egui::Response { ui.button(egui::RichText::new(label).color(ui.visuals().hyperlink_color)) .on_hover_text(crate::i18n::tr("A new version of ChessPenguin is out")) } + +/// The main button of a window: filled, a little taller. +pub fn primary(ui: &mut egui::Ui, label: &str) -> egui::Response { + ui.add( + egui::Button::new(egui::RichText::new(label).strong()) + .fill(ui.visuals().selection.bg_fill) + .min_size(egui::vec2(0.0, 30.0)), + ) +} From d0846daf9b2bbb881178ae51fd5fcddabb538168 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Tue, 20 Oct 2026 08:50:18 +0300 Subject: [PATCH 4/4] ChessPenguin 0.8.0: games from Lichess and Chess.com Pending Lichess games are asked about by id; broken connections are retried with waits; a file lock keeps two running ChessPenguins from writing one database. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 18 +- Cargo.lock | 8 +- Cargo.toml | 2 +- README.md | 2 +- apps/desktop/src/library.rs | 2 +- apps/desktop/src/online.rs | 274 ++++++++++++------ docs/dev/desktop.md | 4 +- ...thub.vrubelroman.chessPenguin.metainfo.xml | 5 + 8 files changed, 207 insertions(+), 108 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1543535..8128635 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,14 +2,18 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). -## [Unreleased] +## [0.8.0] — 2026-10-20 -- Your games from Lichess and Chess.com: enter the nickname (another one for Chess.com if it - differs), see what was found and download the games into a database — one for both sites - by default ("Put the games of both sites into one database"), or one per site — and update - it later with one click; an interrupted download continues where it stopped. Only standard - chess is kept. The feature is offered only when the sites answer: ChessPenguin asks each - for a public profile at start (no data of yours is sent), so offline it stays hidden. +- Games from Lichess and Chess.com: anyone's games by nickname — yours, a pupil's, an + opponent's, a champion's (no login; another nickname for Chess.com if it differs). See what + was found, download the games into a database — both sites merged into one by default, or + one per site — and later fetch the new ones with "⟳ New games" in the database header. The + progress shows per site with the time left; the window may be closed meanwhile (the result + then shows as a message). An interrupted download — stopped, failed, or the program closed — + keeps what it got and continues where it stopped, without duplicates (also after a crash); + games still being played (correspondence) are fetched once they end. Only standard chess is + kept. The feature is offered only when the sites answer: ChessPenguin asks each for a public + profile at start (nothing of yours is sent), so offline it stays hidden. ## [0.7.1] — 2026-10-20 diff --git a/Cargo.lock b/Cargo.lock index dbe61ff..d603e90 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -661,7 +661,7 @@ dependencies = [ [[package]] name = "chess-core" -version = "0.7.1" +version = "0.8.0" dependencies = [ "encoding_rs", "pgn-reader", @@ -671,7 +671,7 @@ dependencies = [ [[package]] name = "chess-import" -version = "0.7.1" +version = "0.8.0" dependencies = [ "chess-core", "encoding_rs", @@ -684,7 +684,7 @@ dependencies = [ [[package]] name = "chesspenguin" -version = "0.7.1" +version = "0.8.0" dependencies = [ "arboard", "chess-core", @@ -4284,7 +4284,7 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "uci" -version = "0.7.1" +version = "0.8.0" dependencies = [ "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index af4c638..e75728c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/chess-core", "crates/chess-import", "crates/uci", "apps/desktop"] [workspace.package] -version = "0.7.1" +version = "0.8.0" edition = "2024" rust-version = "1.97" license = "GPL-3.0-or-later" diff --git a/README.md b/README.md index eb57c64..0492e32 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ copy PGN/FEN, save a game to a new file. - **Looks** — 17 piece sets, 37 boards (flat colours and textures), 7 sound sets, dark and light themes. -- **Your online games** — download your games from Lichess and Chess.com by nickname (no login) into a database and update it with one click. +- **Online games** — download anyone's games from Lichess and Chess.com by nickname (yours, a pupil's, an opponent's; no login) into a database, both sites merged or one per site, and fetch the new ones with one click. - **Languages** — English, Русский, Français, Deutsch, Español, Italiano. | Game analysis: graph and report | Engine marks and better lines | diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index e119fc5..afd6d3b 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -705,7 +705,7 @@ impl Library { ui.painter() .rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside); let below = match self.online_running { - Some(n) => trf("downloading… {n}", &[("n", &large_db::grouped(n))]), + Some(n) => trf("downloading… {n}", &[("n", &crate::i18n::games(n))]), None => "Lichess · Chess.com".to_owned(), }; ui.painter().text( diff --git a/apps/desktop/src/online.rs b/apps/desktop/src/online.rs index 56d8b8e..197a6d8 100644 --- a/apps/desktop/src/online.rs +++ b/apps/desktop/src/online.rs @@ -91,27 +91,63 @@ impl std::fmt::Display for Failure { } } +/// Makes a request again when the connection broke (Lichess drops connections for a +/// minute or so after an export was cut short), waiting `waits` seconds in between; +/// stops waiting when cancelled. +fn retrying( + waits: &[u64], + cancel: &AtomicBool, + mut request: impl FnMut() -> Result, +) -> Result { + let mut waits = waits.iter(); + loop { + match request() { + Ok(r) => return Ok(r), + Err(e) => { + let Some(&secs) = waits.next() else { + return Err(Failure::Network(e.to_string())); + }; + for _ in 0..secs * 10 { + if cancel.load(Ordering::Relaxed) { + return Err(Failure::Network(e.to_string())); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + } + } +} + +/// Waits before the attempts of a download request: about a minute in all. +const DOWNLOAD_WAITS: &[u64] = &[3, 10, 20, 30]; + /// GET returning (status, body); the body of an error status is not read. fn get(url: &str) -> Result<(u16, String), Failure> { - let mut resp = agent(false) - .get(url) - .header("Accept", "application/json") - .call() - .map_err(|e| Failure::Network(e.to_string()))?; - let status = resp.status().as_u16(); - if status == 429 { - return Err(Failure::RateLimited); - } - if status != 200 { - return Ok((status, String::new())); - } - let body = resp - .body_mut() - .with_config() - .limit(64 << 20) - .read_to_string() - .map_err(|e| Failure::Network(e.to_string()))?; - Ok((status, body)) + let never = AtomicBool::new(false); + // The whole exchange is repeated: a connection may also break in the body. + retrying(&[2, 5], &never, || { + let mut resp = agent(false) + .get(url) + .header("Accept", "application/json") + .call()?; + let status = resp.status().as_u16(); + if status != 200 { + return Ok((status, String::new())); + } + let body = resp + .body_mut() + .with_config() + .limit(64 << 20) + .read_to_string()?; + Ok((status, body)) + }) + .and_then(|(status, body)| { + if status == 429 { + Err(Failure::RateLimited) + } else { + Ok((status, body)) + } + }) } fn json(url: &str) -> Result, Failure> { @@ -577,6 +613,19 @@ pub fn download( status: &Progress, ) -> Result { let _claim = Claim::take(path).ok_or(Failure::Busy)?; + // Another ChessPenguin running may download into the same database: a file lock + // (released when the file closes, also if the process dies). + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).map_err(|e| Failure::Disk(e.to_string()))?; + } + let lock = std::fs::File::create(path.with_extension("online.lock")) + .map_err(|e| Failure::Disk(e.to_string()))?; + if let Err(e) = lock.try_lock() { + return Err(match e { + std::fs::TryLockError::WouldBlock => Failure::Busy, + std::fs::TryLockError::Error(e) => Failure::Disk(e.to_string()), + }); + } let path = path.to_owned(); let mut state = State::load(&path) // The games are gone (the file was deleted): fetch them again. @@ -640,25 +689,26 @@ struct LichessGame<'a> { /// Still being played (not exported as a game yet). playing: bool, standard: bool, - pgn: &'a str, + /// Present for finished games (an unfinished one may come without it). + pgn: Option<&'a str>, } fn lichess_game(v: &Value) -> Option> { - Some(LichessGame { + let g = LichessGame { id: v["id"].as_str()?, created: v["createdAt"].as_i64()?, playing: matches!(v["status"].as_str(), Some("created" | "started")), standard: v["variant"] .as_str() .is_none_or(|x| x == "standard" || x == "fromPosition"), - pgn: v["pgn"].as_str()?, - }) + pgn: v["pgn"].as_str(), + }; + (g.playing || g.pgn.is_some()).then_some(g) } -/// What to do with a game of the Lichess export: `Some(write?)`, given the newest game -/// fetched before this run and the games pending then (unfinished). The export repeats -/// games from the oldest pending one on; those fetched already are skipped. -fn lichess_keep(a: &mut AccountState, g: &LichessGame, before: Option) -> bool { +/// Whether to write a game of the Lichess export; an unfinished one is remembered as +/// pending instead (asked about by id next time), a pending one that ended is written. +fn lichess_keep(a: &mut AccountState, g: &LichessGame) -> bool { let pending = a.lichess_pending.iter().position(|(id, _)| id == g.id); if g.playing { if pending.is_none() && g.standard { @@ -668,50 +718,25 @@ fn lichess_keep(a: &mut AccountState, g: &LichessGame, before: Option) -> b } if let Some(k) = pending { a.lichess_pending.remove(k); - return g.standard; } - g.standard && before.is_none_or(|b| g.created > b) + g.standard } -/// The games of account `i` of the writer's database from Lichess. `Ok(true)` when -/// cancelled. -fn lichess( - w: &mut Writer, - i: usize, - progress: &AtomicUsize, +/// A pending game Lichess no longer returns is given up after a year. +const PENDING_DAYS: i64 = 365; + +/// Reads a Lichess NDJSON answer line by line. `Ok(true)` when cancelled. +fn lichess_lines( + resp: ureq::http::Response, cancel: &AtomicBool, - status: &Progress, + mut each: impl FnMut(usize, &Value) -> Result<(), Failure>, ) -> Result { - let a = &w.state.accounts[i]; - let before = a.lichess_last; - let from = a - .lichess_pending - .iter() - .map(|(_, t)| *t) - .chain(before.map(|b| b + 1)) - .min(); - let pending_before: Vec = a.lichess_pending.iter().map(|(id, _)| id.clone()).collect(); - let mut url = format!( - "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=false&pgnInJson=true\ - &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence\ - &clocks=false&evals=false&opening=true", - a.username - ); - if let Some(from) = from { - url.push_str(&format!("&since={from}")); - } - let resp = agent(true) - .get(&url) - .header("Accept", "application/x-ndjson") - .call() - .map_err(|e| Failure::Network(e.to_string()))?; match resp.status().as_u16() { 200 => {} 429 => return Err(Failure::RateLimited), code => return Err(Failure::Unexpected(format!("HTTP {code}"))), } let reader = BufReader::new(resp.into_body().into_reader()); - let mut seen: Vec = Vec::new(); for (n, line) in reader.lines().enumerate() { if cancel.load(Ordering::Relaxed) { return Ok(true); @@ -722,30 +747,83 @@ fn lichess( } let v: Value = serde_json::from_str(&line).map_err(|e| Failure::Unexpected(e.to_string()))?; - let g = lichess_game(&v) + each(n, &v)?; + } + Ok(false) +} + +const LICHESS_PARAMS: &str = "pgnInJson=true&clocks=false&evals=false&opening=true"; + +/// The games of account `i` of the writer's database from Lichess: first the pending +/// (unfinished last time) ones by id, then the new ones. `Ok(true)` when cancelled. +fn lichess( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let write = |w: &mut Writer, v: &Value| -> Result { + let g = lichess_game(v) .ok_or_else(|| Failure::Unexpected("a game without id, pgn or createdAt".into()))?; - if pending_before.iter().any(|id| id == g.id) { - seen.push(g.id.to_owned()); - } - let a = &mut w.state.accounts[i]; - if lichess_keep(a, &g, before) { - let pgn = g.pgn.to_owned(); + if lichess_keep(&mut w.state.accounts[i], &g) + && let Some(pgn) = g.pgn + { + let pgn = pgn.to_owned(); w.game(&pgn)?; progress.fetch_add(1, Ordering::Relaxed); status.games.fetch_add(1, Ordering::Relaxed); } + Ok(g.created) + }; + let pending: Vec = w.state.accounts[i] + .lichess_pending + .iter() + .map(|(id, _)| id.clone()) + .collect(); + for chunk in pending.chunks(300) { + let resp = retrying(DOWNLOAD_WAITS, cancel, || { + agent(true) + .post(&format!( + "https://lichess.org/api/games/export/_ids?{LICHESS_PARAMS}" + )) + .header("Accept", "application/x-ndjson") + .send(chunk.join(",")) + })?; + if lichess_lines(resp, cancel, |_, v| write(w, v).map(|_| ()))? { + return Ok(true); + } + } + let year_ago = now_secs() * 1000 - PENDING_DAYS * 86_400_000; + w.state.accounts[i] + .lichess_pending + .retain(|(_, created)| *created > year_ago); + w.commit()?; + + let a = &w.state.accounts[i]; + let mut url = format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=false\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&{LICHESS_PARAMS}", + a.username + ); + if let Some(last) = a.lichess_last { + url.push_str(&format!("&since={}", last + 1)); + } + let resp = retrying(DOWNLOAD_WAITS, cancel, || { + agent(true) + .get(&url) + .header("Accept", "application/x-ndjson") + .call() + })?; + lichess_lines(resp, cancel, |n, v| { + let created = write(w, v)?; let a = &mut w.state.accounts[i]; - a.lichess_last = Some(a.lichess_last.map_or(g.created, |l| l.max(g.created))); + a.lichess_last = Some(a.lichess_last.map_or(created, |l| l.max(created))); if n % 100 == 99 { w.commit()?; } - } - // The whole export arrived: a game pending before that did not come again is gone - // (deleted, or a variant that ended). - w.state.accounts[i] - .lichess_pending - .retain(|(id, _)| !pending_before.contains(id) || seen.contains(id)); - Ok(false) + Ok(()) + }) } /// The games of account `i` of the writer's database from Chess.com. `Ok(true)` when @@ -1001,28 +1079,33 @@ mod tests { #[test] fn unfinished_lichess_games_come_later() { let mut a = AccountState::default(); - let g = |id: &'static str, created: i64, playing: bool| LichessGame { + let g = |id: &'static str, playing: bool| LichessGame { id, - created, + created: 10, playing, standard: true, - pgn: "", + pgn: (!playing).then_some("1. e4 *"), }; - // First run: a correspondence game is still on, a later one is over. - assert!(!lichess_keep(&mut a, &g("corr", 10, true), None)); - assert!(lichess_keep(&mut a, &g("blitz", 20, false), None)); + // First run: a correspondence game is still on, another one is over. + assert!(!lichess_keep(&mut a, &g("corr", true))); + assert!(lichess_keep(&mut a, &g("blitz", false))); assert_eq!(a.lichess_pending, vec![("corr".to_owned(), 10)]); - // The next run starts from the pending game: it is over now and is kept, the - // game fetched before is not repeated. - assert!(lichess_keep(&mut a, &g("corr", 10, false), Some(20))); - assert!(!lichess_keep(&mut a, &g("blitz", 20, false), Some(20))); - assert!(lichess_keep(&mut a, &g("new", 30, false), Some(20))); + // Asked about by id: still on, then over. + assert!(!lichess_keep(&mut a, &g("corr", true))); + assert_eq!(a.lichess_pending.len(), 1); + assert!(lichess_keep(&mut a, &g("corr", false))); assert!(a.lichess_pending.is_empty()); // A variant game is neither kept nor waited for. - let mut v = g("960", 40, true); + let mut v = g("960", true); v.standard = false; - assert!(!lichess_keep(&mut a, &v, Some(30))); + assert!(!lichess_keep(&mut a, &v)); assert!(a.lichess_pending.is_empty()); + // An unfinished game may come without its PGN, a finished one may not. + let json = |s: &str| serde_json::from_str::(s).unwrap(); + let on = json(r#"{"id":"a","createdAt":1,"status":"started"}"#); + assert!(lichess_game(&on).is_some_and(|g| g.playing)); + let over = json(r#"{"id":"a","createdAt":1,"status":"mate"}"#); + assert!(lichess_game(&over).is_none()); } /// Against the real sites, with an account given by `CP_ONLINE_NICK` (kept out of @@ -1068,15 +1151,17 @@ mod tests { for round in 1..=2 { let progress = AtomicUsize::new(0); let cancel = AtomicBool::new(false); + let over = AtomicBool::new(false); let done = std::thread::scope(|s| { s.spawn(|| { - while progress.load(Ordering::Relaxed) < 150 { + while progress.load(Ordering::Relaxed) < 150 && !over.load(Ordering::Relaxed) { std::thread::sleep(Duration::from_millis(50)); } cancel.store(true, Ordering::Relaxed); }); - download_to(std::slice::from_ref(&li), &path, &progress, &cancel) - .expect("downloads") + let r = download_to(std::slice::from_ref(&li), &path, &progress, &cancel); + over.store(true, Ordering::Relaxed); + r.expect("downloads") }); eprintln!("lichess round {round}: {done:?}"); assert!(done.cancelled && done.added >= 150); @@ -1150,6 +1235,7 @@ mod tests { for round in 1..=2 { let progress = AtomicUsize::new(0); let cancel = AtomicBool::new(false); + let over = AtomicBool::new(false); let goal = if round == 1 { done.total as usize + 100 } else { @@ -1157,12 +1243,14 @@ mod tests { }; let d = std::thread::scope(|s| { s.spawn(|| { - while progress.load(Ordering::Relaxed) < goal { + while progress.load(Ordering::Relaxed) < goal && !over.load(Ordering::Relaxed) { std::thread::sleep(Duration::from_millis(50)); } cancel.store(true, Ordering::Relaxed); }); - download_to(&accounts, &path, &progress, &cancel).expect("downloads") + let r = download_to(&accounts, &path, &progress, &cancel); + over.store(true, Ordering::Relaxed); + r.expect("downloads") }); eprintln!("both, round {round}: {d:?}"); assert!(d.cancelled); diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 16f7223..c0b45ab 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -11,6 +11,8 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i | `large_db.rs` | Большая база ChessBase: панель фильтров справа (игроки с подсказками, турнир, годы, Эло, результат, ECO, ходы, аннотации), фоновые проходы с отменой и задержкой 250 мс для текста, счётчик и прогресс, таблица из записей `.cbh`; компоновка — `docs/design/large-databases.md`; переключатель `[Фильтры | Доска]`, строка условий (чипы), колонка «Ход», «только этот порядок», «сильнейшие сверху»; при открытой доске в фоне строится, чего не хватает для быстрого поиска (`Base::prepare`: свой ускоритель без пригодного `.cbb`, дебютный индекс при достаточной памяти; каталог кэша `boosters/`) со строкой прогресса над доской | | `update.rs` | Обновления: проверка последнего выпуска (GitHub API, при старте, отключается в «О программе»), вид установки (`detect`: zip на Windows, `.app` на macOS, AppImage — только если исполняемый файл внутри `$APPDIR`, архив tar.gz по соседним файлам, `/usr/bin` → pacman/dpkg/rpm, Flatpak по `FLATPAK_ID`, иначе «другое»), выбор файла выпуска по окончанию имени, загрузка с проверкой SHA-256 из `SHA256SUMS.txt`, замена исполняемого файла (`replace_file`: копия рядом и одно переименование; на Windows работающий `.exe` переименовывается в `.old`, удаляется при следующем запуске), команды для пакетов (`cd <папка> && sudo apt/dnf/zypper/pacman … ./файл`, все слова в одинарных кавычках, если в них есть что-то кроме безопасных символов), папка «Загрузки» (XDG, затем `~/.config/user-dirs.dirs` пользователя — у Flatpak своя папка настроек, затем `~/Downloads`, затем домашняя). Тесты: версии, файлы для каждого вида, команды и экранирование (через `sh`), замена работающего исполняемого файла (CI на Windows и macOS тоже), обновление архива из локального «выпуска» | | `update_ui.rs` | Окно «Обновление ChessPenguin»: «Вышла версия X · У вас Y · Что нового», один сценарий на вид установки с главной кнопкой, «Не сейчас», «Пропустить эту версию» (`skipped_version`); скачивание с прогрессом (окно можно закрыть, кнопка у «Настроек» показывает проценты); итог: «Перезапустить сейчас / Позже», шаги для macOS с «Закрыть ChessPenguin», команда с «Копировать», «Открыть папку» и шагами для пакетов; ошибки понятными словами, исходный текст — в «Подробностях». Перезапуск: `request_close(QuitApp)`, в `finish_close` настройки сохраняются, новый процесс запускается без переменных `CP_*`; отмена вопроса о партиях отменяет и перезапуск | +| `online.rs` | Онлайн-партии: проба обоих API при старте (повтор через 5 минут), поиск ника, загрузка в PGN-базу в `/online/` с файлом состояния `.online.json` (аккаунты базы, отметки Lichess `since`/незаконченные партии и Chess.com месяц/время, число партий, длина файла и его последние байты — хвост после аварии обрезается), одна загрузка на файл (`Claim`), имена `Ник (Lichess + Chess.com).pgn` или `A (Lichess) + B (Chess.com).pgn`. Живой тест `online_live` (ник — только через `CP_ONLINE_NICK`). | +| `online_ui.rs` | Окно «Партии с Lichess и Chess.com»: ник игрока (любого: свой, ученика, соперника; другой ник для Chess.com), площадки, ответившие на пробу, «Найти» (Enter), найденное, «Объединить партии с обоих сайтов в одну базу» (по умолчанию), строка «В базу …» (`targets`: база, где эти аккаунты уже есть, иначе новая), «Скачать», прогресс по сайту (Lichess: из N, оставшееся время; Chess.com: месяц i из n), «Остановить», итоги с «Открыть базу» / «Попробовать снова» и «Подробностями»; при закрытом окне итог — тостом; `stop_all` при выходе. | | `board_search.rs` | Доска поиска по позиции (решение 13, `docs/design/board-search.md`): ввод ходов, линия с переходами по ходам, продолжения со статистикой (полоса Б/Н/Ч, средний Эло, год; для книг — «N глав»), клавиши ←/→/Home/End/Backspace/1–9/F/Ctrl+Backspace, «Вернуть» после сброса, фоновые задачи `Background` с отменой | | `game_view.rs` | Экран партии: доска, шкала оценки, панель анализа, предпросмотр PV, нотация, панель инструментов, клавиатура | | `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках | @@ -44,7 +46,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe ``` `CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, -`CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. `CP_ONLINE=<ник>` — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу загрузить). Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). +`CP_ONLINE=<ник>` — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. `CP_ONLINE=<ник>` — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу загрузить). Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). ## Языки diff --git a/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml b/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml index 4e0a8aa..5dfdb1d 100644 --- a/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml +++ b/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml @@ -43,6 +43,11 @@ BoardGame + + +

Games from Lichess and Chess.com: download anyone's games by nickname — yours, a pupil's, an opponent's — into a database, both sites merged or one per site, and fetch the new ones with one click. Interrupted downloads continue without duplicates.

+
+

Updates: ChessPenguin tells when a new version is out and updates itself where it can (Windows, AppImage, the Linux archive); for packages it downloads the new one and shows the command that installs it.