From d3c87ae2693fb41c5d2a9b0d08571c752778ef8c Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 19 Oct 2026 21:10:22 +0300 Subject: [PATCH] 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). ## Языки