diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d36ecf..6291e09 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,17 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
## [Unreleased]
+- Android: **games from Lichess and Chess.com** — «Add a database» → «Games from Lichess
+ and Chess.com»: any player's games by nickname (yours, a pupil's, an opponent's; no login,
+ another nickname for Chess.com if it differs) become a database on the phone, both sites
+ merged into one by default. «Download new games» — in the database's menu and over its
+ games list — fetches only the games played since; a download that was stopped, failed or
+ cut off by a closed app continues where it stopped, without duplicates. The games of such
+ a database are listed from the most recent one. The download goes on when the screen is
+ left; the list shows its progress and says how it ended. Only standard chess is kept. The
+ app asks the sites only when told to (both builds may now use the internet for this).
+- The downloads of games from Lichess and Chess.com are one shared part of the desktop and
+ Android apps.
- Android: the status bar and the navigation bar follow the theme chosen in the app: with
the dark theme on a light phone their icons are light again (they stayed dark on dark).
diff --git a/Cargo.lock b/Cargo.lock
index 11e16d9..ff6cdd7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -806,6 +806,7 @@ dependencies = [
"game-review",
"getrandom 0.3.4",
"image",
+ "online-games",
"rfd",
"rodio",
"serde",
@@ -2416,6 +2417,7 @@ dependencies = [
"chess-core",
"chess-import",
"game-review",
+ "online-games",
"shakmaty",
"thiserror 2.0.21",
"uci",
@@ -3003,6 +3005,16 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "online-games"
+version = "0.13.0"
+dependencies = [
+ "chess-core",
+ "serde",
+ "serde_json",
+ "ureq",
+]
+
[[package]]
name = "option-ext"
version = "0.2.0"
diff --git a/Cargo.toml b/Cargo.toml
index 1963335..904f387 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -5,6 +5,7 @@ members = [
"crates/chess-import",
"crates/uci",
"crates/game-review",
+ "crates/online-games",
"crates/mobile-api",
"apps/desktop",
]
@@ -37,6 +38,7 @@ chess-core = { path = "crates/chess-core" }
chess-import = { path = "crates/chess-import" }
uci = { path = "crates/uci" }
game-review = { path = "crates/game-review" }
+online-games = { path = "crates/online-games" }
[profile.dev.package."*"]
opt-level = 2
diff --git a/androidApp/app/src/light/AndroidManifest.xml b/androidApp/app/src/light/AndroidManifest.xml
index ab9d809..4980d1a 100644
--- a/androidApp/app/src/light/AndroidManifest.xml
+++ b/androidApp/app/src/light/AndroidManifest.xml
@@ -1,6 +1,5 @@
-
+
-
diff --git a/androidApp/app/src/main/AndroidManifest.xml b/androidApp/app/src/main/AndroidManifest.xml
index 0ed3b3f..0a4c62d 100644
--- a/androidApp/app/src/main/AndroidManifest.xml
+++ b/androidApp/app/src/main/AndroidManifest.xml
@@ -1,5 +1,7 @@
+
+
{
- DatabasesScreen(onOpen = { backStack.add(Games(it)) }, onAdded = ::show, onSettings = { backStack.add(SettingsKey) })
+ DatabasesScreen(
+ onOpen = { backStack.add(Games(it)) },
+ onAdded = ::show,
+ onSettings = { backStack.add(SettingsKey) },
+ onOnline = { backStack.add(OnlineKey) },
+ )
}
entry { key ->
GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) })
@@ -112,6 +128,16 @@ fun MainNavigation() {
entry {
BoardStyleScreen(onBack = { backStack.removeLastOrNull() })
}
+ entry {
+ OnlineScreen(
+ onBack = { backStack.removeLastOrNull() },
+ // The downloaded database instead of this screen: "back" goes to the list.
+ onOpen = { id ->
+ backStack.removeLastOrNull()
+ backStack.add(Games(id))
+ },
+ )
+ }
entry {
AboutScreen(onBack = { backStack.removeLastOrNull() })
}
diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt
index d13ec55..9d2f866 100644
--- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt
+++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt
@@ -39,6 +39,10 @@ enum class Source {
/// A copy kept inside the app (`files/copies/`): games pasted from the clipboard, a
/// file opened from another app, which gives access to it only for a while.
Copy,
+
+ /// A player's games downloaded from Lichess and Chess.com (`files/online/`, with the
+ /// state of the download beside it, android-ui.md §23).
+ Online,
}
/// A database on the list. The file itself is never changed.
@@ -63,6 +67,8 @@ data class DbEntry(
val renamed: Boolean = false,
/// A copy's SHA-256: the same file opened again is not copied twice.
val sha256: String? = null,
+ /// A downloaded database: when its last download finished (Unix seconds).
+ val updated: Long? = null,
)
/// Text or a file with no games in it.
@@ -111,6 +117,8 @@ data class FolderScan(val tree: Uri, val name: String, val found: List)
class Library(private val context: Context) {
private val file = File(context.filesDir, "library.json")
private val copies = File(context.filesDir, "copies")
+ /// Downloaded databases (android-ui.md §23).
+ val onlineDir = File(context.filesDir, "online")
private val json = Json { ignoreUnknownKeys = true }
private val _entries = MutableStateFlow(load())
val entries: StateFlow> = _entries.asStateFlow()
@@ -124,6 +132,16 @@ class Library(private val context: Context) {
init {
releaseUnused()
+ // A download cut short by a closed app wrote games the list does not know of yet.
+ update { list -> list.map(::withOnlineState) }
+ }
+
+ /// A downloaded database with the number of games and the time of its last download
+ /// as its state file has them (they change while the list does not look).
+ private fun withOnlineState(e: DbEntry): DbEntry {
+ if (e.source != Source.Online) return e
+ val info = uniffi.mobile_api.onlineDatabase(onlineFile(e).path) ?: return e
+ return e.copy(games = info.games.toInt(), updated = info.updated ?: e.updated)
}
/// Gives back the access to files and folders no database on the list uses (a
@@ -132,6 +150,13 @@ class Library(private val context: Context) {
private fun releaseUnused() {
val kept = _entries.value.filter { it.source == Source.Copy }.map { it.location }.toSet()
copies.listFiles()?.filter { it.name !in kept }?.forEach { it.delete() }
+ // A downloaded database left behind (the app closed while "Undo" was offered).
+ // Names may hold dots ("Name (Lichess + Chess.com).pgn"): whole names are compared.
+ val online = _entries.value.filter { it.source == Source.Online }.flatMap {
+ val stem = it.location.removeSuffix(".pgn")
+ listOf("$stem.pgn", "$stem.online.json", "$stem.online.lock")
+ }.toSet()
+ onlineDir.listFiles()?.filter { it.name !in online }?.forEach { it.delete() }
val used = _entries.value.mapNotNull { it.tree ?: it.location.takeIf { _ -> it.source == Source.File || it.source == Source.ChessBase } }.toSet()
for (p in context.contentResolver.persistedUriPermissions) {
if (p.uri.toString() !in used) {
@@ -263,6 +288,42 @@ class Library(private val context: Context) {
}
}
+ /// The file of a downloaded database.
+ fun onlineFile(e: DbEntry): File = File(onlineDir, e.location)
+
+ /// Puts a downloaded database (a file of [onlineDir]) on the list, or gives its entry.
+ fun addOnline(file: File): DbEntry = synchronized(this) {
+ _entries.value.firstOrNull { it.source == Source.Online && it.location == file.name }?.let { return it }
+ val entry = DbEntry(
+ id = UUID.randomUUID().toString(),
+ name = file.name.substringBeforeLast('.'),
+ source = Source.Online,
+ location = file.name,
+ fileName = file.name,
+ games = 0,
+ format = "PGN",
+ )
+ update { it + entry }
+ entry
+ }
+
+ /// A downloaded database got new games: it is read again when next opened. The old
+ /// one is not closed: a screen may still show it; it is freed once nothing holds it.
+ suspend fun downloaded(id: String, games: Int, updated: Long?) {
+ lock.withLock {
+ open.remove(id)
+ update { list -> list.map { if (it.id == id) it.copy(games = games, updated = updated ?: it.updated) else it } }
+ }
+ }
+
+ /// Takes a downloaded database that got no games off the list, with its files.
+ fun dropEmpty(id: String) {
+ val e = entry(id) ?: return
+ update { it.filterNot { x -> x.id == id } }
+ open.remove(id)?.close()
+ uniffi.mobile_api.deleteOnlineDatabase(onlineFile(e).path)
+ }
+
fun rename(id: String, name: String) = update { list -> list.map { if (it.id == id) it.copy(name = name, renamed = true) else it } }
/// Takes the database off the list (the file stays where it is). Returns its place,
@@ -286,6 +347,10 @@ class Library(private val context: Context) {
File(copies, entry.location).delete()
return
}
+ if (entry.source == Source.Online) {
+ uniffi.mobile_api.deleteOnlineDatabase(onlineFile(entry).path)
+ return
+ }
// The permission of a folder is given back with the last of its databases, also
// counting those whose "Undo" is still offered.
val granted = entry.tree ?: entry.location
@@ -433,7 +498,8 @@ class Library(private val context: Context) {
fun restore(place: Int, entry: DbEntry) {
pending.remove(entry)
- update { it.toMutableList().apply { add(place.coerceIn(0, size), entry) } }
+ // A download may have gone on while it was off the list.
+ update { it.toMutableList().apply { add(place.coerceIn(0, size), withOnlineState(entry)) } }
}
/// The same file on the list, picked through another way (its URI differs).
@@ -452,6 +518,14 @@ class Library(private val context: Context) {
}
}.getOrNull()
+ /// The games of a database that `query` finds, in the order the list shows them: a
+ /// downloaded database from the most recent game down (android-ui.md §23), the others
+ /// as in the file. Slow for a big database: call it off the main thread.
+ fun listed(id: String, db: Database, query: String): List {
+ val found = db.find(query)
+ return if (entry(id)?.source == Source.Online) db.newestFirst(found) else found
+ }
+
/// The open database of an entry (opened in the background the first time).
suspend fun database(id: String): Result = lock.withLock {
open[id]?.let { return@withLock Result.success(it) }
@@ -466,6 +540,10 @@ class Library(private val context: Context) {
e.fileName,
android.os.ParcelFileDescriptor.open(File(copies, e.location), android.os.ParcelFileDescriptor.MODE_READ_ONLY).detachFd(),
)
+ Source.Online -> openFile(
+ e.fileName,
+ android.os.ParcelFileDescriptor.open(onlineFile(e), android.os.ParcelFileDescriptor.MODE_READ_ONLY).detachFd(),
+ )
}
}
}
diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/OnlineDownloads.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/OnlineDownloads.kt
new file mode 100644
index 0000000..02f139e
--- /dev/null
+++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/OnlineDownloads.kt
@@ -0,0 +1,89 @@
+package io.github.vrubelroman.chesspenguin.data
+
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharedFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import uniffi.mobile_api.DownloadState
+import uniffi.mobile_api.OnlineAccount
+import uniffi.mobile_api.OnlineDownload
+import uniffi.mobile_api.onlineDatabase
+import java.io.File
+import java.util.concurrent.ConcurrentHashMap
+
+/// A download of a database and how it stands (or how it ended); `fresh` when the
+/// database did not exist before it (its first download).
+data class DownloadView(val accounts: List, val state: DownloadState, val fresh: Boolean = false)
+
+/// A download that has ended, for the snackbar of the screen that is shown then.
+data class Finished(val id: String, val name: String, val view: DownloadView, val games: Int)
+
+/// The downloads of games from Lichess and Chess.com (android-ui.md §23). They belong to
+/// the app, not to a screen: leaving the screen does not stop them, and the list of
+/// databases shows how they go.
+class OnlineDownloads(private val library: Library, private val scope: CoroutineScope) {
+ private val _views = MutableStateFlow>(emptyMap())
+ /// By database id: the running downloads, and the last one of each database.
+ val views: StateFlow> = _views.asStateFlow()
+
+ private val running = ConcurrentHashMap()
+
+ private val _finished = MutableSharedFlow(extraBufferCapacity = 8)
+ /// Each download as it ends (android-ui.md §23.3: a snackbar says how it went).
+ val finished: SharedFlow = _finished.asSharedFlow()
+
+ /// Where the downloaded databases are kept.
+ val dir: File get() = library.onlineDir
+
+ /// Starts fetching the new games of `accounts` into the database file `path` (put on
+ /// the list at once); one download per database. Returns the database's entry.
+ fun start(accounts: List, path: String): DbEntry {
+ val fresh = !File(path).exists()
+ val entry = library.addOnline(File(path))
+ if (running.containsKey(entry.id)) return entry
+ val d = OnlineDownload.start(accounts, path)
+ running[entry.id] = d
+ scope.launch(Dispatchers.IO) {
+ while (true) {
+ val s = d.state()
+ _views.update { it + (entry.id to DownloadView(accounts, s, fresh)) }
+ if (!s.running) break
+ delay(POLL_MS)
+ }
+ running.remove(entry.id)
+ d.close()
+ val info = onlineDatabase(path)
+ val games = info?.games?.toInt() ?: 0
+ // No game at all (no standard chess there, or it failed at once): not a database.
+ val name = library.entry(entry.id)?.name ?: entry.name
+ if (games == 0) library.dropEmpty(entry.id) else library.downloaded(entry.id, games, info?.updated)
+ _views.value[entry.id]?.let { _finished.tryEmit(Finished(entry.id, name, it, games)) }
+ }
+ return entry
+ }
+
+ /// Fetches the games played since the last download of a database.
+ fun update(entry: DbEntry) {
+ val path = library.onlineFile(entry).path
+ val info = onlineDatabase(path) ?: return
+ start(info.accounts, path)
+ }
+
+ /// Stops a download; what it fetched stays.
+ fun cancel(id: String) {
+ running[id]?.cancel()
+ }
+
+ fun isRunning(id: String): Boolean = running.containsKey(id)
+
+ private companion object {
+ const val POLL_MS = 400L
+ }
+}
diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AddDatabase.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AddDatabase.kt
index 945adfe..fed6e0f 100644
--- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AddDatabase.kt
+++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AddDatabase.kt
@@ -17,6 +17,7 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.CloudDownload
import androidx.compose.material.icons.outlined.ContentPaste
import androidx.compose.material.icons.outlined.Description
import androidx.compose.material.icons.outlined.Folder
@@ -52,10 +53,11 @@ import io.github.vrubelroman.chesspenguin.data.FolderScan
import io.github.vrubelroman.chesspenguin.data.Found
import io.github.vrubelroman.chesspenguin.data.Source
-/// "Add a database": games in the clipboard, a file, or every database in a folder.
+/// "Add a database": games in the clipboard, a file, every database in a folder, or a
+/// player's games from Lichess and Chess.com.
@OptIn(ExperimentalMaterial3Api::class)
@Composable
-fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onPaste: (() -> Unit)?, onDismiss: () -> Unit) {
+fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onPaste: (() -> Unit)?, onOnline: () -> Unit, onDismiss: () -> Unit) {
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.navigationBarsPadding().padding(bottom = 24.dp)) {
Text(
@@ -74,6 +76,13 @@ fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onPaste: (() -> Unit)?, o
modifier = Modifier.clickable(role = Role.Button, onClick = onPaste).padding(horizontal = 8.dp),
)
}
+ ListItem(
+ headlineContent = { Text(stringResource(R.string.online_title)) },
+ supportingContent = { Text(stringResource(R.string.add_online_hint)) },
+ leadingContent = { Icon(Icons.Outlined.CloudDownload, null) },
+ colors = ListItemDefaults.colors(containerColor = Color.Transparent),
+ modifier = Modifier.clickable(role = Role.Button, onClick = onOnline).padding(horizontal = 8.dp),
+ )
ListItem(
headlineContent = { Text(stringResource(R.string.add_file)) },
supportingContent = { Text(stringResource(R.string.add_file_hint)) },
diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt
index f414ac8..03b2487 100644
--- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt
+++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt
@@ -37,6 +37,7 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
+import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
@@ -69,6 +70,9 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import io.github.vrubelroman.chesspenguin.R
+import androidx.compose.material3.LinearProgressIndicator
+import io.github.vrubelroman.chesspenguin.data.DownloadView
+import io.github.vrubelroman.chesspenguin.data.Finished
import io.github.vrubelroman.chesspenguin.data.DbEntry
import io.github.vrubelroman.chesspenguin.data.FolderScan
import io.github.vrubelroman.chesspenguin.data.Source
@@ -78,13 +82,27 @@ import kotlinx.coroutines.launch
/// The first screen: the databases on the list (android-ui.md §3).
@OptIn(ExperimentalMaterial3Api::class)
@Composable
-fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSettings: () -> Unit) {
+fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSettings: () -> Unit, onOnline: () -> Unit) {
val library = app().library
+ val downloads = app().downloads
+ val views by downloads.views.collectAsState()
val entries by library.entries.collectAsState()
val snackbar = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
val removedText = stringResource(R.string.removed)
val removedCopyText = stringResource(R.string.removed_copy)
+ val removedOnlineText = stringResource(R.string.online_removed)
+ val resourcesForSnack = LocalResources.current
+ val openText = stringResource(R.string.online_open_short)
+ // How a download ended, said while this screen is shown (android-ui.md §23.3).
+ LaunchedEffect(Unit) {
+ downloads.finished.collect { f ->
+ val text = finishedText(resourcesForSnack, f) ?: return@collect
+ snackbar.currentSnackbarData?.dismiss()
+ val canOpen = f.games > 0 && library.entry(f.id) != null
+ if (snackbar.showSnackbar(text, if (canOpen) openText else null, withDismissAction = false) == SnackbarResult.ActionPerformed) onOpen(f.id)
+ }
+ }
val undoText = stringResource(R.string.undo)
val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) onOpen(library.addFile(uri).id)
@@ -157,17 +175,27 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
items(entries, key = { it.id }) { e ->
DatabaseRow(
e,
+ download = views[e.id],
onOpen = { onOpen(e.id) },
onRename = { renaming = e },
+ onUpdate = { downloads.update(e) },
+ onStop = { downloads.cancel(e.id) },
onRemove = {
+ // A download into it stops first: its file goes with it.
+ downloads.cancel(e.id)
val removed = library.remove(e.id) ?: return@DatabaseRow
scope.launch {
snackbar.currentSnackbarData?.dismiss()
var restored = false
try {
// A copy is deleted, not only taken off the list.
- val text = if (e.source == Source.Copy) removedCopyText else removedText
- if (snackbar.showSnackbar(text, undoText, withDismissAction = false) == SnackbarResult.ActionPerformed) {
+ val text = when (e.source) {
+ Source.Copy -> removedCopyText
+ Source.Online -> removedOnlineText
+ else -> removedText
+ }
+ // Not for ever: the deleted file goes once "Undo" is gone.
+ if (snackbar.showSnackbar(text, undoText, withDismissAction = false, duration = SnackbarDuration.Long) == SnackbarResult.ActionPerformed) {
library.restore(removed.first, removed.second)
restored = true
}
@@ -216,6 +244,10 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
}
}
},
+ onOnline = {
+ choosing = false
+ onOnline()
+ },
onDismiss = { choosing = false },
)
}
@@ -283,45 +315,85 @@ private fun Empty(modifier: Modifier, onAdd: () -> Unit, onSamples: () -> Unit)
@OptIn(ExperimentalFoundationApi::class)
@Composable
-private fun DatabaseRow(e: DbEntry, onOpen: () -> Unit, onRename: () -> Unit, onRemove: () -> Unit, modifier: Modifier) {
+private fun DatabaseRow(
+ e: DbEntry,
+ download: DownloadView?,
+ onOpen: () -> Unit,
+ onRename: () -> Unit,
+ onUpdate: () -> Unit,
+ onStop: () -> Unit,
+ onRemove: () -> Unit,
+ modifier: Modifier,
+) {
var menu by remember { mutableStateOf(false) }
val format = badge(e)
+ val running = download?.state?.running == true
+ val failure = download?.state?.failure?.takeIf { !running }
val subtitle = e.games?.let {
stringResource(R.string.games_with_format, pluralStringResource(R.plurals.games_count, it, groupDigits(it)), e.format ?: format)
} ?: stringResource(R.string.not_opened, formatName(e))
- // A copy kept in the app says so: removing it deletes it.
- val shownSubtitle = if (e.source == Source.Copy) subtitle + " · " + stringResource(R.string.db_copy) else subtitle
- Row(
- modifier
- .fillMaxWidth()
- .height(72.dp)
- .combinedClickable(onClick = onOpen, onLongClick = { menu = true })
- .padding(start = 16.dp, end = 4.dp),
- verticalAlignment = Alignment.CenterVertically,
- ) {
- FormatBadge(format)
- Column(Modifier.weight(1f).padding(start = 16.dp)) {
- Text(displayName(e), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
- Text(
- shownSubtitle,
- style = MaterialTheme.typography.bodyMedium,
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
+ val shownSubtitle = when {
+ // A copy kept in the app says so: removing it deletes it.
+ e.source == Source.Copy -> subtitle + " · " + stringResource(R.string.db_copy)
+ e.source != Source.Online -> subtitle
+ // A downloaded database: how its download goes, or when it was last brought up to date.
+ running -> stringResource(R.string.online_downloading, groupDigits(((e.games ?: 0) + download.state.added.toInt())))
+ else -> pluralStringResource(R.plurals.games_count, e.games ?: 0, groupDigits(e.games ?: 0)) + " · " + when {
+ // The games stay in the line: the database is not empty because a site failed.
+ failure != null -> onlineProblemShort(failure)
+ e.updated == null -> stringResource(R.string.online_unfinished)
+ System.currentTimeMillis() - e.updated * 1000 < 60_000 -> stringResource(R.string.online_updated_now)
+ else -> stringResource(
+ R.string.online_updated,
+ DateUtils.getRelativeTimeSpanString(e.updated * 1000, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString(),
)
}
- Box {
- IconButton(onClick = { menu = true }) { Icon(Icons.Rounded.MoreVert, stringResource(R.string.menu)) }
- DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
- DropdownMenuItem(text = { Text(stringResource(R.string.rename)) }, onClick = {
- menu = false
- onRename()
- })
- DropdownMenuItem(text = { Text(stringResource(R.string.remove)) }, onClick = {
- menu = false
- onRemove()
- })
+ }
+ Box(modifier) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .height(72.dp)
+ .combinedClickable(onClick = onOpen, onLongClick = { menu = true })
+ .padding(start = 16.dp, end = 4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ FormatBadge(format)
+ Column(Modifier.weight(1f).padding(start = 16.dp)) {
+ Text(displayName(e), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(
+ shownSubtitle,
+ style = MaterialTheme.typography.bodyMedium,
+ color = if (failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
}
+ Box {
+ IconButton(onClick = { menu = true }) { Icon(Icons.Rounded.MoreVert, stringResource(R.string.menu)) }
+ DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
+ if (e.source == Source.Online) {
+ DropdownMenuItem(text = { Text(stringResource(if (running) R.string.online_stop_download else R.string.online_update)) }, onClick = {
+ menu = false
+ if (running) onStop() else onUpdate()
+ })
+ }
+ DropdownMenuItem(text = { Text(stringResource(R.string.rename)) }, onClick = {
+ menu = false
+ onRename()
+ })
+ DropdownMenuItem(text = { Text(stringResource(R.string.remove)) }, onClick = {
+ menu = false
+ onRemove()
+ })
+ }
+ }
+ }
+ // A download going on: a thin bar along the bottom of the row (§23.3).
+ if (running) {
+ val share = downloadShare(download)
+ val bar = Modifier.fillMaxWidth().height(2.dp).align(Alignment.BottomStart)
+ if (share != null) LinearProgressIndicator(progress = { share }, modifier = bar) else LinearProgressIndicator(bar)
}
}
}
@@ -358,3 +430,16 @@ private fun pastedName(db: Database, dated: String): String {
}
return dated
}
+
+/// The snackbar of a finished download: "“Name”: +12, 1 246 games in all", "“Name”: no
+/// new games", "“Name”: Lichess does not answer"; none when it was stopped or got nothing.
+fun finishedText(res: android.content.res.Resources, f: Finished): String? {
+ val s = f.view.state
+ val games = res.getQuantityString(R.plurals.games_count, f.games, groupDigits(f.games))
+ s.failure?.let { return res.getString(R.string.online_snack_failed, f.name, problemShort(res, it)) }
+ return when {
+ s.cancelled || f.games == 0 -> null
+ s.added == 0UL -> res.getString(R.string.online_snack_none, f.name)
+ else -> res.getString(R.string.online_snack_added, f.name, groupDigits(s.added.toInt()), games)
+ }
+}
diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt
index 42219a6..c1fc119 100644
--- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt
+++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt
@@ -145,7 +145,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
return@LaunchedEffect
}
// After the process was restarted the list is gone: the same search finds it again.
- val list = games ?: withContext(Dispatchers.Default) { database.find(query) }.also {
+ val list = games ?: withContext(Dispatchers.Default) { app.library.listed(db, database, query) }.also {
games = it
app.shown[db] = it
}
diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt
index f726e56..4f1dff6 100644
--- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt
+++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt
@@ -57,6 +57,13 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import io.github.vrubelroman.chesspenguin.R
+import io.github.vrubelroman.chesspenguin.data.Source
+import androidx.compose.ui.zIndex
+import androidx.compose.ui.platform.LocalResources
+import androidx.compose.material3.SnackbarHostState
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material.icons.rounded.Download
import io.github.vrubelroman.chesspenguin.theme.Tabular
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
@@ -76,7 +83,8 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
val entry = entries.firstOrNull { it.id == db }
var database by remember { mutableStateOf(null) }
var failed by remember { mutableStateOf(null) }
- LaunchedEffect(db) {
+ // Read again when a download brought new games into it (android-ui.md §23).
+ LaunchedEffect(db, entry?.games, entry?.updated) {
app.library.database(db).onSuccess { database = it }.onFailure { failed = it }
}
var searching by rememberSaveable { mutableStateOf(false) }
@@ -87,7 +95,7 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
LaunchedEffect(database, query) {
val d = database ?: return@LaunchedEffect
if (query.isNotEmpty()) delay(250)
- val found = withContext(Dispatchers.Default) { d.find(query) }
+ val found = withContext(Dispatchers.Default) { app.library.listed(db, d, query) }
rows.clear()
shown = found
// New results start at the top.
@@ -95,6 +103,18 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
app.shown[db] = found
}
val scroll = TopAppBarDefaults.pinnedScrollBehavior()
+ val download = app.downloads.views.collectAsState().value[db]
+ val snackbar = remember { SnackbarHostState() }
+ val resources = LocalResources.current
+ // How a download of this database ended (§23.3); the list reads it again by itself.
+ LaunchedEffect(db) {
+ app.downloads.finished.collect { f ->
+ if (f.id != db) return@collect
+ val text = finishedText(resources, f) ?: return@collect
+ snackbar.currentSnackbarData?.dismiss()
+ snackbar.showSnackbar(text)
+ }
+ }
val focus = remember { FocusRequester() }
val keyboard = LocalSoftwareKeyboardController.current
BackHandler(searching) {
@@ -153,13 +173,28 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
}) { Icon(Icons.Rounded.Close, stringResource(R.string.clear)) }
} else if (database != null) {
IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) }
+ // A downloaded database: its new games from here, where they are
+ // looked for (android-ui.md §23.3); ✕ while they come.
+ if (entry?.source == Source.Online) {
+ if (download?.state?.running == true) {
+ IconButton(onClick = { app.downloads.cancel(db) }) { Icon(Icons.Rounded.Close, stringResource(R.string.online_stop_download)) }
+ } else {
+ IconButton(onClick = { entry.let { app.downloads.update(it) } }) { Icon(Icons.Rounded.Download, stringResource(R.string.online_update)) }
+ }
+ }
}
},
scrollBehavior = scroll,
)
},
+ snackbarHost = { SnackbarHost(snackbar) },
) { padding ->
Box(Modifier.fillMaxSize().padding(padding)) {
+ download?.takeIf { it.state.running }?.let { v ->
+ val share = downloadShare(v)
+ val bar = Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopStart).zIndex(1f)
+ if (share != null) LinearProgressIndicator(progress = { share }, modifier = bar) else LinearProgressIndicator(bar)
+ }
val games = shown
when {
failed != null -> Message(stringResource(R.string.open_failed), openProblem(failed!!)) {
diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/OnlineScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/OnlineScreen.kt
new file mode 100644
index 0000000..cf7fa77
--- /dev/null
+++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/OnlineScreen.kt
@@ -0,0 +1,500 @@
+package io.github.vrubelroman.chesspenguin.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.selection.toggleable
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.rounded.ArrowBack
+import androidx.compose.material3.Button
+import androidx.compose.material3.Checkbox
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Switch
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.produceState
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalSoftwareKeyboardController
+import androidx.compose.ui.res.pluralStringResource
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.LiveRegionMode
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.heading
+import androidx.compose.ui.semantics.liveRegion
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import androidx.lifecycle.viewmodel.compose.viewModel
+import io.github.vrubelroman.chesspenguin.R
+import io.github.vrubelroman.chesspenguin.data.DownloadView
+import io.github.vrubelroman.chesspenguin.data.Source
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.async
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import uniffi.mobile_api.AccountLookup
+import uniffi.mobile_api.OnlineAccount
+import uniffi.mobile_api.OnlineFailure
+import uniffi.mobile_api.OnlineProblem
+import uniffi.mobile_api.Site
+import uniffi.mobile_api.findAccount
+import uniffi.mobile_api.onlineDatabase
+import uniffi.mobile_api.onlineTargets
+import uniffi.mobile_api.validNickname
+import java.io.File
+import kotlin.math.ceil
+
+/// Lichess gives about this many games a second to an anonymous export.
+private const val LICHESS_GAMES_PER_SECOND = 20.0
+
+fun siteName(s: Site): String = when (s) {
+ Site.LICHESS -> "Lichess"
+ Site.CHESS_COM -> "Chess.com"
+}
+
+/// "1 234 games" in the language of the interface.
+@Composable
+fun gamesText(n: Long): String {
+ val k = n.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
+ return pluralStringResource(R.plurals.games_count, k, groupDigits(k))
+}
+
+/// Seconds Lichess needs for `games` games.
+private fun lichessSeconds(games: Long): Double = games / LICHESS_GAMES_PER_SECOND
+
+/// What went wrong, in words for a chess player (android-ui.md §23.4).
+@Composable
+fun onlineProblemText(f: OnlineFailure): String {
+ val site = f.site?.let(::siteName) ?: "—"
+ return when (f.problem) {
+ OnlineProblem.NETWORK -> stringResource(R.string.online_err_network, site)
+ OnlineProblem.RATE_LIMITED -> stringResource(R.string.online_err_rate, site)
+ OnlineProblem.UNEXPECTED -> stringResource(R.string.online_err_unexpected, site)
+ OnlineProblem.DISK -> stringResource(R.string.online_err_disk)
+ OnlineProblem.BUSY -> stringResource(R.string.online_err_busy)
+ }
+}
+
+/// The short form, for the subtitle of a database and the snackbar (§23.3).
+fun problemShort(res: android.content.res.Resources, f: OnlineFailure): String {
+ val site = f.site?.let(::siteName)
+ return when {
+ site != null && f.problem == OnlineProblem.NETWORK -> res.getString(R.string.online_short_network, site)
+ site != null && f.problem == OnlineProblem.RATE_LIMITED -> res.getString(R.string.online_short_rate, site)
+ else -> res.getString(R.string.online_short_failed)
+ }
+}
+
+@Composable
+fun onlineProblemShort(f: OnlineFailure): String = problemShort(androidx.compose.ui.platform.LocalResources.current, f)
+
+/// What a running download is doing: "Lichess: 1 200 of about 6 541 · about 5 min left",
+/// "Chess.com: month 12 of 84 · 340 games".
+@Composable
+fun downloadProgressText(v: DownloadView): String {
+ val s = v.state
+ val account = v.accounts.getOrNull(s.account.toInt())
+ val games = s.accountGames.toLong()
+ return when (account?.site) {
+ Site.LICHESS -> {
+ val total = account.games?.toLong() ?: 0
+ if (total > games) {
+ val minutes = ceil(lichessSeconds(total - games) / 60.0).toInt().coerceAtLeast(1)
+ stringResource(R.string.online_progress_lichess, groupDigits(games.toInt()), groupDigits(total.toInt()), minutes)
+ } else {
+ stringResource(R.string.online_progress_count, "Lichess", gamesText(games))
+ }
+ }
+ Site.CHESS_COM -> if (s.monthsTotal > 0u) {
+ stringResource(R.string.online_progress_chesscom, s.monthsDone.toInt(), s.monthsTotal.toInt(), gamesText(games))
+ } else {
+ stringResource(R.string.online_progress_count, "Chess.com", gamesText(games))
+ }
+ null -> stringResource(R.string.online_downloading, groupDigits(s.added.toInt()))
+ }
+}
+
+/// How a finished download went: "Done: 473 games" the first time, "+12, 1 246 games in
+/// all" later.
+@Composable
+fun downloadResultText(v: DownloadView): String {
+ val s = v.state
+ s.failure?.let { return onlineProblemText(it) }
+ val total = s.total?.toLong() ?: 0
+ return when {
+ s.cancelled -> stringResource(R.string.online_stopped, gamesText(total))
+ total == 0L -> stringResource(R.string.online_no_games)
+ s.added == 0UL -> stringResource(R.string.online_no_new, gamesText(total))
+ v.fresh -> stringResource(R.string.online_done, gamesText(total))
+ else -> stringResource(R.string.online_added, groupDigits(s.added.toInt()), gamesText(total))
+ }
+}
+
+/// The share of the whole download done, when it is known: each account is an equal part
+/// (Lichess counted by its games, Chess.com by months).
+fun downloadShare(v: DownloadView): Float? {
+ val s = v.state
+ val i = s.account.toInt()
+ val account = v.accounts.getOrNull(i) ?: return null
+ val part = when (account.site) {
+ Site.LICHESS -> account.games?.takeIf { it > 0UL }?.let { (s.accountGames.toDouble() / it.toDouble()).toFloat() }
+ Site.CHESS_COM -> s.monthsTotal.takeIf { it > 0u }?.let { s.monthsDone.toFloat() / it.toFloat() }
+ } ?: return null
+ return ((i + part.coerceIn(0f, 1f)) / v.accounts.size).coerceIn(0f, 1f)
+}
+
+/// The search of the screen: kept when the phone is turned (android-ui.md §23.2).
+class OnlineSearch : ViewModel() {
+ var found by mutableStateOf?>(null)
+ var chosen by mutableStateOf(setOf())
+ var searching by mutableStateOf(false)
+
+ fun find(forLichess: String, forChessCom: String) {
+ if (searching) return
+ searching = true
+ viewModelScope.launch {
+ val result = withContext(Dispatchers.IO) {
+ val li = async { findAccount(Site.LICHESS, forLichess) }
+ val cc = async { findAccount(Site.CHESS_COM, forChessCom) }
+ mapOf(Site.LICHESS to li.await(), Site.CHESS_COM to cc.await())
+ }
+ found = result
+ chosen = result.filterValues { it is AccountLookup.Found }.keys
+ searching = false
+ }
+ }
+
+ fun forget() {
+ found = null
+ }
+}
+
+/// A nickname is shown as wrong only for a character it may not have or when it is too
+/// long; a short one is still being typed.
+private fun badNick(nick: String): Boolean {
+ val t = nick.trim()
+ return t.length > 30 || t.any { !(it.isLetterOrDigit() && it.code < 128) && it != '_' && it != '-' }
+}
+
+/// "Games from Lichess and Chess.com" (android-ui.md §23.2): a nickname, what was found on
+/// each site, the download and how it goes.
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun OnlineScreen(onBack: () -> Unit, onOpen: (String) -> Unit) {
+ val app = app()
+ val downloads = app.downloads
+ val views by downloads.views.collectAsState()
+ val entries by app.library.entries.collectAsState()
+ val search: OnlineSearch = viewModel()
+ val keyboard = LocalSoftwareKeyboardController.current
+ var nick by rememberSaveable { mutableStateOf("") }
+ // A different nickname on Chess.com, once asked for.
+ var other by rememberSaveable { mutableStateOf(null) }
+ var together by rememberSaveable { mutableStateOf(true) }
+ // The databases this screen started downloading; the found accounts are hidden then,
+ // until the next search.
+ var started by rememberSaveable { mutableStateOf(listOf()) }
+ var launched by rememberSaveable { mutableStateOf(false) }
+
+ val nickOk = validNickname(nick)
+ val otherOk = other?.let { it.isBlank() || validNickname(it) } ?: true
+ fun find() {
+ if (!nickOk || !otherOk) return
+ keyboard?.hide()
+ launched = false
+ val forLichess = nick.trim()
+ search.find(forLichess, other?.trim()?.takeIf { it.isNotEmpty() } ?: forLichess)
+ }
+
+ val found = search.found
+ val accounts: List = found.orEmpty()
+ .filterKeys { it in search.chosen }
+ .values.mapNotNull { (it as? AccountLookup.Found)?.account }
+ val merge = together && accounts.size > 1
+ // Where the games go, and how many are there already; read again when a download ends.
+ val ended = started.count { views[it]?.state?.running == false }
+ val targets by produceState(emptyList>(), accounts, merge, ended) {
+ value = withContext(Dispatchers.IO) {
+ if (accounts.isEmpty()) {
+ emptyList()
+ } else {
+ onlineTargets(downloads.dir.path, accounts, merge).map { t ->
+ t.path to (if (t.exists) onlineDatabase(t.path)?.games?.toLong() else null)
+ }
+ }
+ }
+ }
+ // A database's name as on the list (it may have been renamed), else its file's.
+ fun nameOf(path: String): String {
+ val file = File(path).name
+ return entries.firstOrNull { it.source == Source.Online && it.location == file }?.name ?: file.removeSuffix(".pgn")
+ }
+
+ Scaffold(
+ topBar = {
+ TopAppBar(
+ navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } },
+ title = { Text(stringResource(R.string.online_title)) },
+ )
+ },
+ ) { padding ->
+ Column(
+ Modifier
+ .fillMaxSize()
+ .padding(padding)
+ .imePadding()
+ .verticalScroll(rememberScrollState())
+ .navigationBarsPadding()
+ .padding(horizontal = 16.dp, vertical = 8.dp),
+ ) {
+ Text(stringResource(R.string.online_intro), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Spacer(Modifier.height(16.dp))
+ NickField(
+ value = nick,
+ label = stringResource(if (other == null) R.string.online_nick else R.string.online_nick_lichess),
+ bad = badNick(nick),
+ onChange = {
+ nick = it
+ search.forget()
+ },
+ onDone = ::find,
+ )
+ if (other == null) {
+ TextButton(onClick = { other = "" }, contentPadding = PaddingValues(0.dp)) { Text(stringResource(R.string.online_other)) }
+ } else {
+ Spacer(Modifier.height(8.dp))
+ NickField(
+ value = other.orEmpty(),
+ label = stringResource(R.string.online_other_nick),
+ bad = badNick(other.orEmpty()),
+ onChange = {
+ other = it
+ search.forget()
+ },
+ onDone = ::find,
+ )
+ TextButton(onClick = {
+ other = null
+ search.forget()
+ }, contentPadding = PaddingValues(0.dp)) { Text(stringResource(R.string.online_same_nick)) }
+ }
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
+ if (search.searching) {
+ CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
+ Spacer(Modifier.size(12.dp))
+ Text(stringResource(R.string.online_searching), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
+ }
+ val enabled = nickOk && otherOk && !search.searching
+ // After a search the main button of the screen is "Download".
+ if (found != null && !launched) {
+ OutlinedButton(onClick = ::find, enabled = enabled) { Text(stringResource(R.string.online_find)) }
+ } else {
+ Button(onClick = ::find, enabled = enabled) { Text(stringResource(R.string.online_find)) }
+ }
+ }
+
+ if (found != null && !launched) {
+ Spacer(Modifier.height(16.dp))
+ HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
+ Spacer(Modifier.height(8.dp))
+ for (site in listOf(Site.LICHESS, Site.CHESS_COM)) {
+ val r = found[site] ?: continue
+ FoundRow(site, r, site in search.chosen, onToggle = { on -> search.chosen = if (on) search.chosen + site else search.chosen - site }, onRetry = ::find)
+ }
+ if (found.values.count { it is AccountLookup.Found } > 1 && search.chosen.size > 1) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .heightIn(min = 64.dp)
+ .toggleable(value = together, role = Role.Switch, onValueChange = { together = it }),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(stringResource(R.string.online_merge), style = MaterialTheme.typography.bodyLarge)
+ Text(stringResource(R.string.online_merge_hint), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ Switch(checked = together, onCheckedChange = null)
+ }
+ }
+ for ((path, games) in targets) {
+ val name = nameOf(path)
+ Text(
+ if (games != null) {
+ stringResource(R.string.online_into_existing, name, gamesText(games))
+ } else {
+ stringResource(R.string.online_into_new, name)
+ },
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.padding(vertical = 4.dp),
+ )
+ }
+ if (accounts.isNotEmpty()) {
+ Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.End) {
+ Button(onClick = {
+ val groups = onlineTargets(downloads.dir.path, accounts, merge)
+ started = groups.map { downloads.start(it.accounts, it.path).id }
+ launched = true
+ }) { Text(stringResource(R.string.online_download)) }
+ }
+ }
+ }
+
+ // The downloads started here: how they go, then how they went.
+ for (id in started) {
+ val v = views[id] ?: continue
+ Spacer(Modifier.height(16.dp))
+ DownloadCard(
+ name = entries.firstOrNull { it.id == id }?.name ?: v.accounts.joinToString(" + ") { it.username },
+ view = v,
+ onStop = { downloads.cancel(id) },
+ onOpen = if (!v.state.running && (v.state.total ?: 0UL) > 0UL && entries.any { it.id == id }) ({ onOpen(id) }) else null,
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun NickField(value: String, label: String, bad: Boolean, onChange: (String) -> Unit, onDone: () -> Unit) {
+ OutlinedTextField(
+ value = value,
+ onValueChange = onChange,
+ label = { Text(label) },
+ placeholder = { Text(stringResource(R.string.online_nick_hint)) },
+ singleLine = true,
+ isError = bad,
+ supportingText = if (bad) ({ Text(stringResource(R.string.online_nick_rule)) }) else null,
+ keyboardOptions = KeyboardOptions(
+ capitalization = KeyboardCapitalization.None,
+ autoCorrectEnabled = false,
+ keyboardType = KeyboardType.Ascii,
+ imeAction = ImeAction.Search,
+ ),
+ keyboardActions = KeyboardActions(onSearch = { onDone() }),
+ modifier = Modifier.fillMaxWidth(),
+ )
+}
+
+/// What one site gave for the nickname: the account to tick, "no such player", or why it
+/// did not answer.
+@Composable
+private fun FoundRow(site: Site, r: AccountLookup, checked: Boolean, onToggle: (Boolean) -> Unit, onRetry: () -> Unit) {
+ when (r) {
+ is AccountLookup.Found -> {
+ val a = r.account
+ val lichess = a.games?.toLong()
+ val detail = when {
+ lichess != null -> {
+ val upTo = pluralStringResource(R.plurals.games_up_to, lichess.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(), groupDigits(lichess.toInt()))
+ val secs = lichessSeconds(lichess)
+ if (secs < 60) {
+ stringResource(R.string.online_lichess_quick, upTo)
+ } else {
+ stringResource(R.string.online_lichess_found, upTo, ceil(secs / 60.0).toInt())
+ }
+ }
+ a.months != null -> stringResource(R.string.online_chesscom_found, a.months!!.toInt())
+ else -> ""
+ }
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .heightIn(min = 64.dp)
+ .toggleable(value = checked, role = Role.Checkbox, onValueChange = onToggle),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Checkbox(checked = checked, onCheckedChange = null)
+ Column(Modifier.weight(1f).padding(start = 12.dp)) {
+ Text("${siteName(site)} · ${a.username}", style = MaterialTheme.typography.bodyLarge)
+ if (detail.isNotEmpty()) {
+ Text(detail, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ }
+ }
+ }
+ AccountLookup.NotFound -> Text(
+ stringResource(R.string.online_not_found, siteName(site)),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.heightIn(min = 48.dp).padding(start = 36.dp, top = 12.dp),
+ )
+ is AccountLookup.Failed -> Column(Modifier.padding(start = 36.dp, top = 8.dp)) {
+ Text(onlineProblemText(r.failure), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error)
+ TextButton(onClick = onRetry, contentPadding = PaddingValues(0.dp)) { Text(stringResource(R.string.online_try_again)) }
+ }
+ }
+}
+
+/// A download started on this screen: its progress and Stop, then its result and Open.
+@Composable
+private fun DownloadCard(name: String, view: DownloadView, onStop: () -> Unit, onOpen: (() -> Unit)?) {
+ val s = view.state
+ Column(Modifier.fillMaxWidth()) {
+ Text(name, style = MaterialTheme.typography.titleMedium, modifier = Modifier.semantics { heading() })
+ Spacer(Modifier.height(4.dp))
+ if (s.running) {
+ // Not a live region: it changes a few times a second (TalkBack would not stop).
+ Text(downloadProgressText(view), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Spacer(Modifier.height(8.dp))
+ val share = downloadShare(view)
+ if (share != null) {
+ LinearProgressIndicator(progress = { share }, modifier = Modifier.fillMaxWidth())
+ } else {
+ LinearProgressIndicator(Modifier.fillMaxWidth())
+ }
+ Spacer(Modifier.height(8.dp))
+ Text(stringResource(R.string.online_leave), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
+ OutlinedButton(onClick = onStop, modifier = Modifier.padding(top = 8.dp)) { Text(stringResource(R.string.online_stop)) }
+ }
+ } else {
+ Text(
+ downloadResultText(view),
+ style = MaterialTheme.typography.bodyMedium,
+ color = if (s.failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite },
+ )
+ if (onOpen != null) {
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
+ Button(onClick = onOpen, modifier = Modifier.padding(top = 8.dp)) { Text(stringResource(R.string.online_open)) }
+ }
+ }
+ }
+ }
+}
diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml
index 3c0dbe8..76d4cc0 100644
--- a/androidApp/app/src/main/res/values-de/strings.xml
+++ b/androidApp/app/src/main/res/values-de/strings.xml
@@ -3,7 +3,7 @@
Aljechin
Hier erscheinen Ihre Datenbanken
- Fügen Sie eine Datei oder einen Ordner mit Datenbanken hinzu: PGN, ChessBase, .zip- und .7z-Archive — vom Telefon oder aus der Cloud.
+ Fügen Sie eine PGN-Datei, eine ChessBase-Datenbank oder ein .zip/.7z-Archiv hinzu – vom Telefon oder aus der Cloud – oder laden Sie Partien von Lichess und Chess.com.
Datenbank hinzufügen
Beispielpartien öffnen
noch nicht geöffnet · %1$s
@@ -271,4 +271,61 @@
- %1$d Stellung, etwa %2$s
- %1$d Stellungen, etwa %2$s
+
+ Partien von Lichess und Chess.com
+ Partien beliebiger Spieler per Nickname: eigene, eines Schülers, eines Gegners
+ Die Partien des Spielers werden zu einer Datenbank auf dem Telefon – zum Suchen, Ansehen und Analysieren. Nur der Nickname ist nötig, keine Anmeldung.
+ Nickname des Spielers
+ wie auf der Seite
+ Anderer Nickname auf Chess.com
+ Nickname auf Chess.com
+ Derselbe Nickname
+ Lateinische Buchstaben, Ziffern, _ und -, 2 bis 30 Zeichen
+ Suchen
+ Suche auf den Seiten…
+ %1$s · beim ersten Mal etwa %2$d Min.
+ Monate mit Partien: %1$d
+ %1$s: kein Spieler mit diesem Nickname – Schreibweise prüfen
+ Beide Seiten in einer Datenbank zusammenführen
+ Sonst bekommt jede Seite eine eigene Datenbank
+ In die neue Datenbank „%1$s“
+ In „%1$s“ (schon %2$s dort; nur neue Partien kommen dazu)
+ Herunterladen
+ Lichess: %1$s von etwa %2$s · noch etwa %3$d Min.
+ %1$s: %2$s
+ Chess.com: Monat %1$d von %2$d · %3$s
+ Anhalten
+ +%1$s, insgesamt %2$s
+ Keine neuen Partien, %1$s in der Datenbank
+ Angehalten, %1$s in der Datenbank
+ Dort gibt es keine Partien im Standardschach.
+ Datenbank öffnen
+ Erneut versuchen
+ %1$s antwortet nicht. Prüfen Sie die Internetverbindung und versuchen Sie es erneut.
+ %1$s bittet um eine Pause: zu viele Anfragen hintereinander. Warten Sie eine Minute und versuchen Sie es erneut; Geladenes bleibt erhalten.
+ %1$s hat unverständlich geantwortet: die Seite hat sich vielleicht geändert. Versuchen Sie es später oder aktualisieren Sie ChessPenguin.
+ Die Datenbank konnte nicht geschrieben werden: auf dem Telefon ist kein Platz mehr.
+ Diese Datenbank wird bereits geladen.
+ %1$s antwortet nicht
+ %1$s bittet um eine Pause
+ Der Download wurde unterbrochen
+ Neue Partien laden
+ Download anhalten
+ Wird geladen · %1$s
+ aktualisiert %1$s
+ unvollständig
+ Geladene Datenbank gelöscht
+ Nickname auf Lichess
+ %1$s · beim ersten Mal unter einer Minute
+ Sie können diesen Bildschirm verlassen: die Datenbank ist in der Liste, der Download läuft weiter.
+ Fertig: %1$s
+ gerade aktualisiert
+ „%1$s“: +%2$s, insgesamt %3$s
+ „%1$s“: keine neuen Partien
+ „%1$s“: %2$s
+ Öffnen
+
+ - bis zu %1$s Partie
+ - bis zu %1$s Partien
+
diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml
index 255014f..163c810 100644
--- a/androidApp/app/src/main/res/values-es/strings.xml
+++ b/androidApp/app/src/main/res/values-es/strings.xml
@@ -3,7 +3,7 @@
Alekhine
Aquí aparecerán tus bases
- Añade un archivo o una carpeta de bases: PGN, ChessBase, archivos .zip y .7z — desde el teléfono o la nube.
+ Añade un archivo PGN, una base ChessBase o un archivo .zip/.7z — desde el teléfono o la nube — o descarga partidas de Lichess y Chess.com.
Añadir base
Abrir partidas de ejemplo
aún sin abrir · %1$s
@@ -276,4 +276,62 @@
- %1$d posiciones, unos %2$s
- %1$d posiciones, unos %2$s
+
+ Partidas de Lichess y Chess.com
+ Partidas de cualquier jugador por apodo: las tuyas, de un alumno, de un rival
+ Las partidas del jugador se convierten en una base en el teléfono, para buscar, ver y analizar. Solo hace falta el apodo, sin iniciar sesión.
+ Apodo del jugador
+ como en el sitio
+ Otro apodo en Chess.com
+ Apodo en Chess.com
+ El mismo apodo
+ Letras latinas, dígitos, _ y -, de 2 a 30 caracteres
+ Buscar
+ Buscando en los sitios…
+ %1$s · la primera vez unos %2$d min
+ meses con partidas: %1$d
+ %1$s: no hay ningún jugador con este apodo; revisa cómo se escribe
+ Unir ambos sitios en una sola base
+ Si no, cada sitio tendrá su propia base
+ En la nueva base «%1$s»
+ En «%1$s» (ya hay %2$s; solo se añaden las nuevas)
+ Descargar
+ Lichess: %1$s de unas %2$s · quedan unos %3$d min
+ %1$s: %2$s
+ Chess.com: mes %1$d de %2$d · %3$s
+ Detener
+ +%1$s, %2$s en total
+ No hay partidas nuevas, %1$s en la base
+ Detenido, %1$s en la base
+ Allí no hay partidas de ajedrez estándar.
+ Abrir la base
+ Reintentar
+ %1$s no responde. Comprueba la conexión a internet e inténtalo de nuevo.
+ %1$s pide una pausa: demasiadas solicitudes seguidas. Espera un minuto e inténtalo de nuevo; lo descargado se conserva.
+ %1$s respondió de una forma que ChessPenguin no entiende: quizá el sitio cambió. Inténtalo más tarde o actualiza ChessPenguin.
+ No se pudo escribir la base: el teléfono no tiene espacio.
+ Esta base ya se está descargando.
+ %1$s no responde
+ %1$s pide una pausa
+ La descarga se interrumpió
+ Descargar partidas nuevas
+ Detener la descarga
+ Descargando · %1$s
+ actualizada %1$s
+ incompleta
+ Base descargada eliminada
+ Apodo en Lichess
+ %1$s · la primera vez menos de un minuto
+ Puedes salir de esta pantalla: la base ya está en la lista y la descarga continúa.
+ Listo: %1$s
+ actualizada ahora mismo
+ «%1$s»: +%2$s, %3$s en total
+ «%1$s»: no hay partidas nuevas
+ «%1$s»: %2$s
+ Abrir
+
+ - hasta %1$s partida
+ - hasta %1$s partidas
+ - hasta %1$s partidas
+
diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml
index 2ecb523..c1443fb 100644
--- a/androidApp/app/src/main/res/values-fr/strings.xml
+++ b/androidApp/app/src/main/res/values-fr/strings.xml
@@ -3,7 +3,7 @@
Alekhine
Vos bases apparaîtront ici
- Ajoutez un fichier ou un dossier de bases : PGN, ChessBase, archives .zip et .7z — depuis votre téléphone ou le cloud.
+ Ajoutez un fichier PGN, une base ChessBase ou une archive .zip/.7z — depuis le téléphone ou le cloud — ou téléchargez des parties de Lichess et Chess.com.
Ajouter une base
Ouvrir les parties d’exemple
pas encore ouverte · %1$s
@@ -276,4 +276,62 @@
- %1$d positions, environ %2$s
- %1$d positions, environ %2$s
+
+ Parties de Lichess et Chess.com
+ Les parties de n\'importe quel joueur par pseudo : les vôtres, d\'un élève, d\'un adversaire
+ Les parties du joueur deviennent une base sur le téléphone, à chercher, voir et analyser. Seul le pseudo est nécessaire, sans connexion.
+ Pseudo du joueur
+ comme sur le site
+ Un autre pseudo sur Chess.com
+ Pseudo sur Chess.com
+ Le même pseudo
+ Lettres latines, chiffres, _ et -, de 2 à 30 caractères
+ Rechercher
+ Recherche sur les sites…
+ %1$s · environ %2$d min la première fois
+ mois avec des parties : %1$d
+ %1$s : aucun joueur avec ce pseudo — vérifiez l\'orthographe
+ Réunir les deux sites dans une seule base
+ Sinon chaque site a sa propre base
+ Dans la nouvelle base « %1$s »
+ Dans « %1$s » (déjà %2$s ; seules les nouvelles parties sont ajoutées)
+ Télécharger
+ Lichess : %1$s sur environ %2$s · encore environ %3$d min
+ %1$s : %2$s
+ Chess.com : mois %1$d sur %2$d · %3$s
+ Arrêter
+ +%1$s, %2$s en tout
+ Pas de nouvelles parties, %1$s dans la base
+ Arrêté, %1$s dans la base
+ Aucune partie d\'échecs standard là-bas.
+ Ouvrir la base
+ Réessayer
+ %1$s ne répond pas. Vérifiez la connexion Internet et réessayez.
+ %1$s demande une pause : trop de requêtes d\'affilée. Attendez une minute et réessayez ; ce qui est téléchargé est conservé.
+ %1$s 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.
+ Impossible d\'écrire la base : le téléphone n\'a plus de place.
+ Cette base est déjà en cours de téléchargement.
+ %1$s ne répond pas
+ %1$s demande une pause
+ Le téléchargement s\'est interrompu
+ Télécharger les nouvelles parties
+ Arrêter le téléchargement
+ Téléchargement · %1$s
+ mise à jour %1$s
+ incomplète
+ Base téléchargée supprimée
+ Pseudo sur Lichess
+ %1$s · moins d\'une minute la première fois
+ Vous pouvez quitter cet écran : la base est dans la liste et le téléchargement continue.
+ Terminé : %1$s
+ mise à jour à l\'instant
+ « %1$s » : +%2$s, %3$s en tout
+ « %1$s » : pas de nouvelles parties
+ « %1$s » : %2$s
+ Ouvrir
+
+ - jusqu\'à %1$s partie
+ - jusqu\'à %1$s parties
+ - jusqu\'à %1$s parties
+
diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml
index 7ed0c23..30c0b4a 100644
--- a/androidApp/app/src/main/res/values-it/strings.xml
+++ b/androidApp/app/src/main/res/values-it/strings.xml
@@ -3,7 +3,7 @@
Alekhine
Qui compariranno i tuoi database
- Aggiungi un file o una cartella di database: PGN, ChessBase, archivi .zip e .7z — dal telefono o dal cloud.
+ Aggiungi un file PGN, un database ChessBase o un archivio .zip/.7z — dal telefono o dal cloud — oppure scarica partite da Lichess e Chess.com.
Aggiungi database
Apri le partite di esempio
non ancora aperto · %1$s
@@ -276,4 +276,62 @@
- %1$d posizioni, circa %2$s
- %1$d posizioni, circa %2$s
+
+ Partite da Lichess e Chess.com
+ Partite di qualsiasi giocatore per nickname: le tue, di un allievo, di un avversario
+ Le partite del giocatore diventano una base sul telefono, da cercare, vedere e analizzare. Serve solo il nickname, senza accesso.
+ Nickname del giocatore
+ come sul sito
+ Un altro nickname su Chess.com
+ Nickname su Chess.com
+ Lo stesso nickname
+ Lettere latine, cifre, _ e -, da 2 a 30 caratteri
+ Cerca
+ Cerco sui siti…
+ %1$s · la prima volta circa %2$d min
+ mesi con partite: %1$d
+ %1$s: nessun giocatore con questo nickname — controlla come è scritto
+ Unire entrambi i siti in una sola base
+ Altrimenti ogni sito avrà la sua base
+ Nella nuova base «%1$s»
+ In «%1$s» (già %2$s; si aggiungono solo le nuove)
+ Scarica
+ Lichess: %1$s di circa %2$s · mancano circa %3$d min
+ %1$s: %2$s
+ Chess.com: mese %1$d di %2$d · %3$s
+ Ferma
+ +%1$s, %2$s in tutto
+ Nessuna partita nuova, %1$s nella base
+ Fermato, %1$s nella base
+ Lì non ci sono partite di scacchi standard.
+ Apri la base
+ Riprova
+ %1$s non risponde. Controlla la connessione a internet e riprova.
+ %1$s chiede una pausa: troppe richieste di fila. Aspetta un minuto e riprova; il già scaricato resta.
+ %1$s ha risposto in un modo che ChessPenguin non capisce: forse il sito è cambiato. Riprova più tardi o aggiorna ChessPenguin.
+ Impossibile scrivere la base: il telefono non ha spazio.
+ Questa base è già in download.
+ %1$s non risponde
+ %1$s chiede una pausa
+ Il download si è interrotto
+ Scarica le partite nuove
+ Ferma il download
+ Download in corso · %1$s
+ aggiornata %1$s
+ incompleta
+ Base scaricata eliminata
+ Nickname su Lichess
+ %1$s · la prima volta meno di un minuto
+ Puoi uscire da questa schermata: la base è già nell\'elenco e il download continua.
+ Fatto: %1$s
+ aggiornata adesso
+ «%1$s»: +%2$s, %3$s in tutto
+ «%1$s»: nessuna partita nuova
+ «%1$s»: %2$s
+ Apri
+
+ - fino a %1$s partita
+ - fino a %1$s partite
+ - fino a %1$s partite
+
diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml
index 71e1498..cfd02a9 100644
--- a/androidApp/app/src/main/res/values-ru/strings.xml
+++ b/androidApp/app/src/main/res/values-ru/strings.xml
@@ -3,7 +3,7 @@
Алехин
Здесь будут ваши базы
- Добавьте файл или папку с базами: PGN, ChessBase, архивы .zip и .7z — с телефона или из облака.
+ Добавьте файл PGN, базу ChessBase или архив .zip/.7z — с телефона или из облака — или скачайте партии с Lichess и Chess.com.
Добавить базу
Открыть примеры партий
ещё не открывалась · %1$s
@@ -281,4 +281,63 @@
- Позиций: %1$d, примерно %2$s
- Позиций: %1$d, примерно %2$s
+
+ Партии с Lichess и Chess.com
+ Партии любого игрока по нику: свои, ученика, соперника
+ Партии игрока станут базой на телефоне — искать, смотреть, анализировать. Нужен только ник, входить на сайт не нужно.
+ Ник игрока
+ как на сайте
+ На Chess.com другой ник
+ Ник на Chess.com
+ Тот же ник
+ Латиница, цифры, _ и -, от 2 до 30 символов
+ Найти
+ Ищу на сайтах…
+ %1$s · первый раз около %2$d мин
+ месяцев с партиями: %1$d
+ %1$s: игрока с таким ником нет — проверьте написание
+ Объединить оба сайта в одну базу
+ Иначе у каждого сайта будет своя база
+ В новую базу «%1$s»
+ В базу «%1$s» (там уже %2$s; добавятся только новые)
+ Скачать
+ Lichess: %1$s из примерно %2$s · осталось около %3$d мин
+ %1$s: %2$s
+ Chess.com: месяц %1$d из %2$d · %3$s
+ Остановить
+ +%1$s, всего %2$s
+ Новых партий нет, в базе %1$s
+ Остановлено, в базе %1$s
+ Партий в обычные шахматы там нет.
+ Открыть базу
+ Попробовать ещё раз
+ %1$s не отвечает. Проверьте подключение к интернету и попробуйте ещё раз.
+ %1$s просит сделать паузу: слишком много запросов подряд. Подождите минуту и попробуйте снова — скачанное сохранится.
+ %1$s ответил непонятно — возможно, сайт что-то поменял. Попробуйте позже или обновите ChessPenguin.
+ Не удалось записать базу: на телефоне не хватает места.
+ Эта база уже скачивается.
+ %1$s не отвечает
+ %1$s просит паузу
+ Скачивание прервалось
+ Скачать новые партии
+ Остановить скачивание
+ Скачивается · %1$s
+ обновлено %1$s
+ не докачана
+ Скачанная база удалена
+ Ник на Lichess
+ %1$s · первый раз меньше минуты
+ Можно уйти с этого экрана: база уже в списке, скачивание продолжится.
+ Готово: %1$s
+ обновлено только что
+ «%1$s»: +%2$s, всего %3$s
+ «%1$s»: новых партий нет
+ «%1$s»: %2$s
+ Открыть
+
+ - до %1$s партии
+ - до %1$s партий
+ - до %1$s партий
+ - до %1$s партии
+
diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml
index ed2d0e7..1394891 100644
--- a/androidApp/app/src/main/res/values/strings.xml
+++ b/androidApp/app/src/main/res/values/strings.xml
@@ -4,7 +4,7 @@
Alekhine
Your databases will appear here
- Add a file or a folder of databases: PGN, ChessBase, .zip and .7z archives — from your phone or the cloud.
+ Add a PGN file, a ChessBase database or a .zip/.7z archive — from your phone or the cloud — or download games from Lichess and Chess.com.
Add database
Open sample games
not opened yet · %1$s
@@ -274,4 +274,61 @@
- %1$d position, about %2$s
- %1$d positions, about %2$s
+
+ Games from Lichess and Chess.com
+ Any player\'s games by nickname: yours, a pupil\'s, an opponent\'s
+ The player\'s games become a database on your phone, to search, view and analyse. Only the nickname is needed, no login.
+ Player\'s nickname
+ as on the site
+ A different nickname on Chess.com
+ Nickname on Chess.com
+ The same nickname
+ Latin letters, digits, _ and -, 2 to 30 characters
+ Find
+ Looking on the sites…
+ %1$s · about %2$d min the first time
+ months with games: %1$d
+ %1$s: no player with this nickname — check the spelling
+ Merge both sites into one database
+ Otherwise each site gets a database of its own
+ Into the new database “%1$s”
+ Into “%1$s” (%2$s there already; only new games are added)
+ Download
+ Lichess: %1$s of about %2$s · about %3$d min left
+ %1$s: %2$s
+ Chess.com: month %1$d of %2$d · %3$s
+ Stop
+ +%1$s, %2$s in all
+ No new games, %1$s in the database
+ Stopped, %1$s in the database
+ No games of standard chess there.
+ Open the database
+ Try again
+ %1$s does not answer. Check the internet connection and try again.
+ %1$s asks for a pause: too many requests in a row. Wait a minute and try again; what is downloaded is kept.
+ %1$s answered in a way ChessPenguin does not understand: the site may have changed. Try later or update ChessPenguin.
+ Could not write the database: the phone is out of space.
+ This database is being downloaded already.
+ %1$s does not answer
+ %1$s asks for a pause
+ The download stopped
+ Download new games
+ Stop the download
+ Downloading · %1$s
+ updated %1$s
+ not finished
+ Downloaded database deleted
+ Nickname on Lichess
+ %1$s · under a minute the first time
+ You can leave this screen: the database is on the list and the download goes on.
+ Done: %1$s
+ updated just now
+ “%1$s”: +%2$s, %3$s in all
+ “%1$s”: no new games
+ “%1$s”: %2$s
+ Open
+
+ - up to %1$s game
+ - up to %1$s games
+
diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml
index c2a28cc..fac1c12 100644
--- a/apps/desktop/Cargo.toml
+++ b/apps/desktop/Cargo.toml
@@ -25,6 +25,7 @@ rodio.workspace = true
directories.workspace = true
serde.workspace = true
serde_json.workspace = true
+online-games.workspace = true
# Downloading the official Stockfish on request (decision 14).
ureq = "3.4"
flate2 = "1.1"
diff --git a/apps/desktop/src/online.rs b/apps/desktop/src/online.rs
index 197a6d8..dae2c32 100644
--- a/apps/desktop/src/online.rs
+++ b/apps/desktop/src/online.rs
@@ -1,282 +1,15 @@
-//! 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.
-//!
-//! 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).
+//! Games from Lichess and Chess.com on the desktop: the databases live in
+//! `/online/`; the downloads themselves are the `online-games` crate's
+//! (shared with the Android app). Both public APIs are probed at start; a platform that
+//! does not answer as expected (offline, the API changed) is simply not offered.
-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: hours for the body (a stalled one ends).
- .timeout_recv_body(if stream {
- Some(Duration::from_secs(4 * 3600))
- } 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),
- /// The database is being downloaded already.
- Busy,
-}
-
-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}"),
- Failure::Busy => write!(f, "the database is being downloaded already"),
- }
- }
-}
-
-/// 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 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> {
- 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())
-}
+pub use online_games::{
+ Account, Done, Failure, LICHESS_RATE, Lookup, Platform, Progress, State, download, lookup,
+ probe_all, valid_nick,
+};
/// Where the online databases live.
pub fn dir() -> Option {
@@ -284,181 +17,25 @@ pub fn dir() -> Option {
.map(|d| d.data_local_dir().join("online"))
}
-/// 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" 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 same = accounts
- .iter()
- .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.
+/// The online databases already holding `account` (see [`online_games::holding`]).
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 {
- pgn.with_extension("online.json")
-}
-
-/// What has been fetched from one account into a database.
-#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
-pub struct AccountState {
- pub platform: Option,
- 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,
- 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,
- /// 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()?;
- serde_json::from_str::(&text)
- .ok()
- .filter(|s| !s.accounts.is_empty() && s.accounts.iter().all(|a| a.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()))
- }
-
- 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
- .iter()
- .filter_map(|a| {
- Some(Account {
- platform: a.platform?,
- username: a.username.clone(),
- games: None,
- months: None,
- })
- })
- .collect()
- }
-}
-
-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)
- }
+ dir().map_or_else(Vec::new, |d| online_games::holding(&d, account))
}
/// 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()
+ dir().is_some_and(|d| online_games::is_online(&d, pgn))
}
-/// 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)
+/// Where the found accounts go (see [`online_games::targets`]).
+pub fn targets(start: &[Account], together: bool) -> Vec<(Vec, PathBuf)> {
+ dir().map_or_else(Vec::new, |d| online_games::targets(&d, start, together))
}
/// "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);
+ let s = (online_games::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))]),
@@ -466,429 +43,6 @@ pub fn ago(t: i64) -> String {
}
}
-/// 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,
-}
-
-/// 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 {
- /// 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,
- })
- }
-
- fn game(&mut self, pgn: &str) -> Result<(), Failure> {
- let pgn = pgn.trim();
- if pgn.is_empty() {
- return Ok(());
- }
- 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(())
- }
-
- /// 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.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,
- added: self.added,
- total: self.state.games,
- cancelled,
- })
- }
-}
-
-/// 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],
- path: &Path,
- progress: &AtomicUsize,
- cancel: &AtomicBool,
- 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.
- .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.holds(a) {
- state.accounts.push(AccountState {
- platform: Some(a.platform),
- username: a.username.clone(),
- ..AccountState::default()
- });
- }
- }
- let mut w = Writer::open(&path, state)?;
- let mut result = Ok(false);
- for i in 0..w.state.accounts.len() {
- 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, status),
- Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel, status),
- 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.
- let _ = w.commit();
- Err(e)
- }
- }
-}
-
-#[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,
- /// Present for finished games (an unfinished one may come without it).
- pgn: Option<&'a str>,
-}
-
-fn lichess_game(v: &Value) -> Option> {
- 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(),
- };
- (g.playing || g.pgn.is_some()).then_some(g)
-}
-
-/// 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 {
- a.lichess_pending.push((g.id.to_owned(), g.created));
- }
- return false;
- }
- if let Some(k) = pending {
- a.lichess_pending.remove(k);
- }
- g.standard
-}
-
-/// 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,
- mut each: impl FnMut(usize, &Value) -> Result<(), Failure>,
-) -> Result {
- 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()))?;
- 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 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(created, |l| l.max(created)));
- if n % 100 == 99 {
- w.commit()?;
- }
- Ok(())
- })
-}
-
-/// 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,
- 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!(
- "{}/{}",
- month.get(1).unwrap_or(&""),
- month.first().unwrap_or(&"")
- );
- let a = &w.state.accounts[i];
- if a.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 a = &w.state.accounts[i];
- let same_month = a.chesscom_month.as_deref() == Some(month.as_str());
- let last = if same_month {
- a.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);
- 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
- // time then still belongs to an earlier month and is not compared).
- w.state.accounts[i].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>,
@@ -956,366 +110,3 @@ impl Probe {
self.available[p.index()]
}
}
-
-#[cfg(test)]
-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, playing: bool| LichessGame {
- id,
- created: 10,
- playing,
- standard: true,
- pgn: (!playing).then_some("1. e4 *"),
- };
- // 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)]);
- // 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", true);
- v.standard = false;
- 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
- /// 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 over = AtomicBool::new(false);
- let done = std::thread::scope(|s| {
- s.spawn(|| {
- while progress.load(Ordering::Relaxed) < 150 && !over.load(Ordering::Relaxed) {
- std::thread::sleep(Duration::from_millis(50));
- }
- cancel.store(true, Ordering::Relaxed);
- });
- 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);
- }
- 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();
- // 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 {
- panic!("not on Chess.com");
- };
- let path = dir.join("cc.pgn");
- let never = AtomicBool::new(false);
- 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(
- 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 over = 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 && !over.load(Ordering::Relaxed) {
- std::thread::sleep(Duration::from_millis(50));
- }
- cancel.store(true, Ordering::Relaxed);
- });
- let r = download_to(&accounts, &path, &progress, &cancel);
- over.store(true, Ordering::Relaxed);
- r.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);
- }
-
- #[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 {
- accounts: vec![AccountState {
- platform: Some(Platform::Lichess),
- username: "Someone".into(),
- lichess_last: Some(1_700_000_000_000),
- ..AccountState::default()
- }],
- games: 3,
- ..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
index ea50147..853cbb9 100644
--- a/apps/desktop/src/online_ui.rs
+++ b/apps/desktop/src/online_ui.rs
@@ -73,31 +73,9 @@ pub struct OnlineDialog {
focus: bool,
}
-/// 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).
+/// Where the found accounts go (see [`online_games::targets`]).
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()
+ online::targets(start, together)
}
/// The file name of a database without the extension.
diff --git a/crates/mobile-api/Cargo.toml b/crates/mobile-api/Cargo.toml
index 6e87cd0..91ee992 100644
--- a/crates/mobile-api/Cargo.toml
+++ b/crates/mobile-api/Cargo.toml
@@ -25,6 +25,7 @@ bindgen = ["uniffi/cli"]
chess-core.workspace = true
chess-import.workspace = true
game-review.workspace = true
+online-games.workspace = true
shakmaty.workspace = true
thiserror.workspace = true
uci.workspace = true
diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs
index dbcc1f9..c79e3ce 100644
--- a/crates/mobile-api/src/lib.rs
+++ b/crates/mobile-api/src/lib.rs
@@ -12,9 +12,14 @@ use chess_core::{Game, MoveKind, NodeId};
use shakmaty::Position;
mod engine;
+mod online;
mod review;
pub use engine::{Analysis, Analyzer, EngineFailure, EngineLine, LineStep};
+pub use online::{
+ AccountLookup, DownloadState, OnlineAccount, OnlineDatabase, OnlineDownload, OnlineFailure,
+ OnlineProblem, OnlineTarget, Site,
+};
pub use review::{GameReview, MoveJudgement, ReviewMove, ReviewPoint, ReviewState, SideReview};
uniffi::setup_scaffolding!();
@@ -319,6 +324,29 @@ impl Database {
.collect()
}
+ /// These games (from [`Database::find`]) from the most recent to the oldest, by the
+ /// time they were played (`UTCDate` and `UTCTime` when there, else `Date`); games of
+ /// the same time keep the newer place in the file first. For downloaded databases,
+ /// where both sites' games are appended oldest first.
+ pub fn newest_first(&self, indices: Vec) -> Vec {
+ let Some(pgn) = self.db.as_pgn() else {
+ return indices;
+ };
+ let entries = pgn.entries();
+ let when = |i: u32| {
+ let Some(e) = entries.get(i as usize) else {
+ return String::new();
+ };
+ match (e.tag("UTCDate"), e.tag("UTCTime")) {
+ (Some(d), Some(t)) => format!("{d} {t}"),
+ _ => e.tag("Date").unwrap_or("").to_owned(),
+ }
+ };
+ let mut keyed: Vec<(String, u32)> = indices.into_iter().map(|i| (when(i), i)).collect();
+ keyed.sort_by(|a, b| b.cmp(a));
+ keyed.into_iter().map(|(_, i)| i).collect()
+ }
+
/// The rows of these games (from [`Database::find`]), in this order.
pub fn rows_of(&self, indices: Vec) -> Vec {
let Some(pgn) = self.db.as_pgn() else {
@@ -611,6 +639,19 @@ mod tests {
assert!(g.nodes.iter().any(|n| !n.main_line));
}
+ #[test]
+ fn downloaded_games_come_newest_first() {
+ let pgn = b"[White \"a\"][UTCDate \"2020.01.02\"][UTCTime \"10:00:00\"]\n\n1. e4 *\n\n\
+ [White \"b\"][UTCDate \"2020.01.02\"][UTCTime \"09:00:00\"]\n\n1. e4 *\n\n\
+ [White \"c\"][Date \"2021.05.01\"]\n\n1. e4 *\n\n\
+ [White \"d\"][UTCDate \"2019.12.31\"][UTCTime \"23:59:59\"]\n\n1. e4 *\n"
+ .to_vec();
+ let db = open_bytes("t.pgn".into(), pgn).unwrap();
+ let order = db.newest_first(db.find(String::new()));
+ let names: Vec = db.rows_of(order).into_iter().map(|r| r.white).collect();
+ assert_eq!(names, ["c", "a", "b", "d"]);
+ }
+
#[test]
fn bytes_open_like_files() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/classics.pgn");
diff --git a/crates/mobile-api/src/online.rs b/crates/mobile-api/src/online.rs
new file mode 100644
index 0000000..75e3d4c
--- /dev/null
+++ b/crates/mobile-api/src/online.rs
@@ -0,0 +1,362 @@
+//! A player's games from Lichess and Chess.com for the Android app: the `online-games`
+//! crate (the same downloads, state files and resuming as on the desktop) with its
+//! download on a thread of its own. The app looks accounts up, starts a download into a
+//! file of its own folder, asks for the progress while it runs, and can stop it; what
+//! was fetched stays, and the next download continues without duplicates.
+//!
+//! Every call that talks to a site blocks: call it off the main thread.
+
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+
+use online_games::{Account, Done, Failure, Lookup, Platform, Progress, State};
+
+/// A site.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum Site {
+ Lichess,
+ ChessCom,
+}
+
+impl From for Platform {
+ fn from(s: Site) -> Self {
+ match s {
+ Site::Lichess => Platform::Lichess,
+ Site::ChessCom => Platform::ChessCom,
+ }
+ }
+}
+
+impl From for Site {
+ fn from(p: Platform) -> Self {
+ match p {
+ Platform::Lichess => Site::Lichess,
+ Platform::ChessCom => Site::ChessCom,
+ }
+ }
+}
+
+/// An account on a site.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct OnlineAccount {
+ pub site: Site,
+ /// As the site spells it.
+ pub username: String,
+ /// Lichess: the games of the account (of all kinds, so at most this many).
+ pub games: Option,
+ /// Chess.com: the months with games.
+ pub months: Option,
+}
+
+impl From<&Account> for OnlineAccount {
+ fn from(a: &Account) -> Self {
+ OnlineAccount {
+ site: a.platform.into(),
+ username: a.username.clone(),
+ games: a.games,
+ months: a.months.map(|m| m as u32),
+ }
+ }
+}
+
+impl From<&OnlineAccount> for Account {
+ fn from(a: &OnlineAccount) -> Self {
+ Account {
+ platform: a.site.into(),
+ username: a.username.clone(),
+ games: a.games,
+ months: a.months.map(|m| m as usize),
+ }
+ }
+}
+
+/// What went wrong talking to a site.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum OnlineProblem {
+ /// No answer (offline, a timeout).
+ Network,
+ /// The site asks for a pause: too many requests.
+ RateLimited,
+ /// An answer this version does not understand (the site changed).
+ Unexpected,
+ /// The database could not be written (the phone is full).
+ Disk,
+ /// The database is being downloaded already.
+ Busy,
+}
+
+/// A problem, the site it came from (when known), and the technical text.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct OnlineFailure {
+ pub problem: OnlineProblem,
+ pub site: Option,
+ pub detail: String,
+}
+
+fn failure(e: &Failure, site: Option) -> OnlineFailure {
+ let problem = match e {
+ Failure::Network(_) => OnlineProblem::Network,
+ Failure::RateLimited => OnlineProblem::RateLimited,
+ Failure::Unexpected(_) => OnlineProblem::Unexpected,
+ Failure::Disk(_) => OnlineProblem::Disk,
+ Failure::Busy => OnlineProblem::Busy,
+ };
+ OnlineFailure {
+ problem,
+ site,
+ detail: e.to_string(),
+ }
+}
+
+/// What looking a nickname up on a site gave.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
+pub enum AccountLookup {
+ Found { account: OnlineAccount },
+ NotFound,
+ Failed { failure: OnlineFailure },
+}
+
+/// A nickname both sites could have: 2–30 letters, digits, `_` or `-`.
+#[uniffi::export]
+pub fn valid_nickname(nick: String) -> bool {
+ online_games::valid_nick(nick.trim())
+}
+
+/// Looks the nickname up on the site (blocks: it asks the site).
+#[uniffi::export]
+pub fn find_account(site: Site, nick: String) -> AccountLookup {
+ match online_games::lookup(site.into(), &nick) {
+ Lookup::Found(a) => AccountLookup::Found {
+ account: (&a).into(),
+ },
+ Lookup::NotFound => AccountLookup::NotFound,
+ Lookup::Failed(e) => AccountLookup::Failed {
+ failure: failure(&e, Some(site)),
+ },
+ }
+}
+
+/// Accounts and the database file they are downloaded into.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct OnlineTarget {
+ pub accounts: Vec,
+ pub path: String,
+ /// The file is there already (its new games are fetched).
+ pub exists: bool,
+}
+
+/// Where the found accounts go in `dir`: all into one database (`together`) or each into
+/// its own; a database already holding them is kept.
+#[uniffi::export]
+pub fn online_targets(
+ dir: String,
+ accounts: Vec,
+ together: bool,
+) -> Vec {
+ let accounts: Vec = accounts.iter().map(Into::into).collect();
+ online_games::targets(Path::new(&dir), &accounts, together)
+ .into_iter()
+ .map(|(group, path)| OnlineTarget {
+ accounts: group.iter().map(Into::into).collect(),
+ exists: path.exists(),
+ path: path.to_string_lossy().into_owned(),
+ })
+ .collect()
+}
+
+/// What a downloaded database holds.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct OnlineDatabase {
+ pub accounts: Vec,
+ /// Games written into it.
+ pub games: u64,
+ /// When the last download finished (Unix seconds); none while it never finished.
+ pub updated: Option,
+}
+
+/// The state of the database at `path`, when it is a downloaded one.
+#[uniffi::export]
+pub fn online_database(path: String) -> Option {
+ let s = State::load(Path::new(&path))?;
+ Some(OnlineDatabase {
+ accounts: s.accounts().iter().map(Into::into).collect(),
+ games: s.games,
+ updated: s.updated,
+ })
+}
+
+/// Deletes a downloaded database and the files beside it (its state).
+#[uniffi::export]
+pub fn delete_online_database(path: String) {
+ let p = PathBuf::from(path);
+ for f in [
+ p.clone(),
+ p.with_extension("online.json"),
+ p.with_extension("online.lock"),
+ ] {
+ let _ = std::fs::remove_file(f);
+ }
+}
+
+/// How a download stands.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct DownloadState {
+ pub running: bool,
+ /// The account being fetched (an index into the download's accounts).
+ pub account: u32,
+ /// Games of that account so far.
+ pub account_games: u64,
+ /// Games added by this download so far.
+ pub added: u64,
+ /// Chess.com: months done of all.
+ pub months_done: u32,
+ pub months_total: u32,
+ /// When it has ended: the games added and in the database now; stopped by the user.
+ pub total: Option,
+ pub cancelled: bool,
+ pub failure: Option,
+}
+
+struct Shared {
+ progress: AtomicUsize,
+ status: Progress,
+ cancel: AtomicBool,
+ result: Mutex>>,
+}
+
+/// A download of accounts into one database.
+#[derive(uniffi::Object)]
+pub struct OnlineDownload {
+ shared: Arc,
+}
+
+#[uniffi::export]
+impl OnlineDownload {
+ /// Starts fetching the games of `accounts` new since the last time into the database
+ /// at `path` (created when it is not there). Returns at once.
+ #[uniffi::constructor]
+ pub fn start(accounts: Vec, path: String) -> Arc {
+ let shared = Arc::new(Shared {
+ progress: AtomicUsize::new(0),
+ status: Progress::default(),
+ cancel: AtomicBool::new(false),
+ result: Mutex::new(None),
+ });
+ let work = shared.clone();
+ let accounts: Vec = accounts.iter().map(Into::into).collect();
+ let spawned = std::thread::Builder::new()
+ .name("online-download".into())
+ .spawn(move || {
+ let r = online_games::download(
+ &accounts,
+ Path::new(&path),
+ &work.progress,
+ &work.cancel,
+ &work.status,
+ );
+ // The account being fetched when it failed: the site to name.
+ let site = accounts
+ .get(work.status.account.load(Ordering::Relaxed))
+ .map(|a| a.platform.into());
+ *lock(&work.result) = Some(r.map_err(|e| failure(&e, site)));
+ });
+ if let Err(e) = spawned {
+ *lock(&shared.result) = Some(Err(OnlineFailure {
+ problem: OnlineProblem::Disk,
+ site: None,
+ detail: e.to_string(),
+ }));
+ }
+ Arc::new(OnlineDownload { shared })
+ }
+
+ /// Stops it soon; what was fetched is kept.
+ pub fn cancel(&self) {
+ self.shared.cancel.store(true, Ordering::Relaxed);
+ }
+
+ pub fn state(&self) -> DownloadState {
+ let s = &self.shared;
+ let result = lock(&s.result).clone();
+ let (total, cancelled, failure) = match &result {
+ Some(Ok(d)) => (Some(d.total), d.cancelled, None),
+ Some(Err(f)) => (None, false, Some(f.clone())),
+ None => (None, false, None),
+ };
+ DownloadState {
+ running: result.is_none(),
+ account: s.status.account.load(Ordering::Relaxed) as u32,
+ account_games: s.status.games.load(Ordering::Relaxed) as u64,
+ added: result
+ .as_ref()
+ .and_then(|r| r.as_ref().ok())
+ .map_or(s.progress.load(Ordering::Relaxed) as u64, |d| d.added),
+ months_done: s.status.months_done.load(Ordering::Relaxed) as u32,
+ months_total: s.status.months_total.load(Ordering::Relaxed) as u32,
+ total,
+ cancelled,
+ failure,
+ }
+ }
+}
+
+fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> {
+ m.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn nicknames_and_targets() {
+ assert!(valid_nickname(" Magnus_C-1 ".into()));
+ assert!(!valid_nickname("../etc".into()));
+ let dir = std::env::temp_dir().join(format!("mobile-online-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let li = OnlineAccount {
+ site: Site::Lichess,
+ username: "Magnus".into(),
+ games: Some(10),
+ months: None,
+ };
+ let cc = OnlineAccount {
+ site: Site::ChessCom,
+ username: "magnus".into(),
+ games: None,
+ months: Some(3),
+ };
+ let d = dir.to_string_lossy().into_owned();
+ let one = online_targets(d.clone(), vec![li.clone(), cc.clone()], true);
+ assert_eq!(one.len(), 1);
+ assert!(one[0].path.ends_with("Magnus (Lichess + Chess.com).pgn"));
+ assert!(!one[0].exists);
+ let two = online_targets(d, vec![li, cc], false);
+ assert_eq!(two.len(), 2);
+ assert!(online_database(two[0].path.clone()).is_none());
+ }
+
+ #[test]
+ fn a_download_that_cannot_write_says_so() {
+ // A folder that cannot be made: the download ends with a disk problem.
+ let acc = OnlineAccount {
+ site: Site::Lichess,
+ username: "someone".into(),
+ games: None,
+ months: None,
+ };
+ let d = OnlineDownload::start(vec![acc], "/proc/cp-no-such-dir/db.pgn".into());
+ let mut s = d.state();
+ for _ in 0..100 {
+ if !s.running {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ s = d.state();
+ }
+ assert!(!s.running);
+ assert_eq!(s.failure.map(|f| f.problem), Some(OnlineProblem::Disk));
+ assert_eq!(s.total, None);
+ }
+}
diff --git a/crates/online-games/Cargo.toml b/crates/online-games/Cargo.toml
new file mode 100644
index 0000000..2443f57
--- /dev/null
+++ b/crates/online-games/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "online-games"
+description = "A player's games from Lichess and Chess.com by nickname, kept as a PGN database that later fetches only the new games (the desktop and Android apps share it)"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+license.workspace = true
+authors.workspace = true
+publish = false
+
+[dependencies]
+serde.workspace = true
+serde_json.workspace = true
+ureq = "3.4"
+
+[dev-dependencies]
+chess-core.workspace = true
diff --git a/crates/online-games/src/lib.rs b/crates/online-games/src/lib.rs
new file mode 100644
index 0000000..8fb77e7
--- /dev/null
+++ b/crates/online-games/src/lib.rs
@@ -0,0 +1,1260 @@
+//! 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 a folder of the
+//! app (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). The
+//! desktop and the Android app share this; each passes its own folder.
+//!
+//! 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",
+ }
+ }
+
+ pub 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: hours for the body (a stalled one ends).
+ .timeout_recv_body(if stream {
+ Some(Duration::from_secs(4 * 3600))
+ } 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),
+ /// The database is being downloaded already.
+ Busy,
+}
+
+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}"),
+ Failure::Busy => write!(f, "the database is being downloaded already"),
+ }
+ }
+}
+
+/// 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 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> {
+ 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())
+}
+
+/// The database file of one account in `dir`: "Name (Lichess).pgn".
+pub fn database_path(dir: &Path, p: Platform, username: &str) -> PathBuf {
+ dir.join(format!("{username} ({}).pgn", p.name()))
+}
+
+/// 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(dir: &Path, accounts: &[Account]) -> Option {
+ let first = accounts.first()?;
+ if accounts.len() == 1 {
+ return Some(database_path(dir, first.platform, &first.username));
+ }
+ let same = accounts
+ .iter()
+ .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(" + ")
+ };
+ Some(dir.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(dir: &Path, account: &Account) -> Vec {
+ 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 {
+ pgn.with_extension("online.json")
+}
+
+/// What has been fetched from one account into a database.
+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
+pub struct AccountState {
+ pub platform: Option,
+ 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,
+ 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,
+ /// 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()?;
+ serde_json::from_str::(&text)
+ .ok()
+ .filter(|s| !s.accounts.is_empty() && s.accounts.iter().all(|a| a.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()))
+ }
+
+ 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
+ .iter()
+ .filter_map(|a| {
+ Some(Account {
+ platform: a.platform?,
+ username: a.username.clone(),
+ games: None,
+ months: None,
+ })
+ })
+ .collect()
+ }
+}
+
+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 of `dir` (it has a state file).
+pub fn is_online(dir: &Path, pgn: &Path) -> bool {
+ pgn.parent() == Some(dir) && state_path(pgn).exists()
+}
+
+/// 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).
+pub fn targets(dir: &Path, 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 = holding(dir, &g[0]).into_iter().find(|p| {
+ 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(|| combined_path(dir, &g))?;
+ Some((g, path))
+ })
+ .collect()
+}
+
+/// 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,
+}
+
+/// Now, in Unix seconds.
+pub fn now_secs() -> i64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| d.as_secs() as i64)
+}
+
+/// 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,
+}
+
+/// 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 {
+ /// 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,
+ })
+ }
+
+ fn game(&mut self, pgn: &str) -> Result<(), Failure> {
+ let pgn = pgn.trim();
+ if pgn.is_empty() {
+ return Ok(());
+ }
+ 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(())
+ }
+
+ /// 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.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,
+ added: self.added,
+ total: self.state.games,
+ cancelled,
+ })
+ }
+}
+
+/// 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],
+ path: &Path,
+ progress: &AtomicUsize,
+ cancel: &AtomicBool,
+ 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.
+ .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.holds(a) {
+ state.accounts.push(AccountState {
+ platform: Some(a.platform),
+ username: a.username.clone(),
+ ..AccountState::default()
+ });
+ }
+ }
+ let mut w = Writer::open(&path, state)?;
+ let mut result = Ok(false);
+ for i in 0..w.state.accounts.len() {
+ 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, status),
+ Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel, status),
+ 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.
+ let _ = w.commit();
+ Err(e)
+ }
+ }
+}
+
+#[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,
+ /// Present for finished games (an unfinished one may come without it).
+ pgn: Option<&'a str>,
+}
+
+fn lichess_game(v: &Value) -> Option> {
+ 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(),
+ };
+ (g.playing || g.pgn.is_some()).then_some(g)
+}
+
+/// 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 {
+ a.lichess_pending.push((g.id.to_owned(), g.created));
+ }
+ return false;
+ }
+ if let Some(k) = pending {
+ a.lichess_pending.remove(k);
+ }
+ g.standard
+}
+
+/// 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,
+ mut each: impl FnMut(usize, &Value) -> Result<(), Failure>,
+) -> Result {
+ 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()))?;
+ 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 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(created, |l| l.max(created)));
+ if n % 100 == 99 {
+ w.commit()?;
+ }
+ Ok(())
+ })
+}
+
+/// 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,
+ 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!(
+ "{}/{}",
+ month.get(1).unwrap_or(&""),
+ month.first().unwrap_or(&"")
+ );
+ let a = &w.state.accounts[i];
+ if a.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 a = &w.state.accounts[i];
+ let same_month = a.chesscom_month.as_deref() == Some(month.as_str());
+ let last = if same_month {
+ a.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);
+ 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
+ // time then still belongs to an earlier month and is not compared).
+ w.state.accounts[i].chesscom_month = Some(month);
+ w.commit()?;
+ }
+ Ok(false)
+}
+
+#[cfg(test)]
+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(Path::new("/online"), 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, playing: bool| LichessGame {
+ id,
+ created: 10,
+ playing,
+ standard: true,
+ pgn: (!playing).then_some("1. e4 *"),
+ };
+ // 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)]);
+ // 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", true);
+ v.standard = false;
+ 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
+ /// 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 online-games 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 over = AtomicBool::new(false);
+ let done = std::thread::scope(|s| {
+ s.spawn(|| {
+ while progress.load(Ordering::Relaxed) < 150 && !over.load(Ordering::Relaxed) {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ cancel.store(true, Ordering::Relaxed);
+ });
+ 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);
+ }
+ 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();
+ // 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 {
+ panic!("not on Chess.com");
+ };
+ let path = dir.join("cc.pgn");
+ let never = AtomicBool::new(false);
+ 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(
+ 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 over = 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 && !over.load(Ordering::Relaxed) {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ cancel.store(true, Ordering::Relaxed);
+ });
+ let r = download_to(&accounts, &path, &progress, &cancel);
+ over.store(true, Ordering::Relaxed);
+ r.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);
+ }
+
+ #[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 {
+ accounts: vec![AccountState {
+ platform: Some(Platform::Lichess),
+ username: "Someone".into(),
+ lichess_last: Some(1_700_000_000_000),
+ ..AccountState::default()
+ }],
+ games: 3,
+ ..State::default()
+ };
+ s.save(&pgn).unwrap();
+ assert_eq!(State::load(&pgn), Some(s));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/docs/design/android-ui.md b/docs/design/android-ui.md
index 4809af8..411ceaa 100644
--- a/docs/design/android-ui.md
+++ b/docs/design/android-ui.md
@@ -27,7 +27,7 @@
4. **Ходы листаются кнопками внизу, под большим пальцем.** Свайпов по доске и по нотации нет. Единственный жест «вбок» — системный «назад».
5. **Соседняя партия открывается стрелками ‹ › в верхней панели.** Перейти к ходу и перейти к партии невозможно перепутать: у кнопок разные места, формы и размеры значков.
6. **Движок включается одной кнопкой — в каждой партии заново.** Открытая партия всегда начинается с выключенным движком. Он сам выключается, когда человек выходит из партии, приложение уходит в фон или гаснет экран. Старая оценка не показывается для новой позиции ни на миг. В сборке без движка эта же кнопка предлагает его скачать (§8.4).
-7. **Приложение работает без интернета.** Сеть нужна только для облачного файла и для скачивания движка в сборке без него.
+7. **Приложение работает без интернета.** Сеть нужна только для облачного файла, для скачивания движка в сборке без него и для партий с Lichess и Chess.com (§23) — и только после нажатия человека.
8. **Вид — спокойный и аккуратный:** цвета и доска те же, что на компьютере и сайте, Material 3 без украшений (§10).
## 1. Источники: что заимствуем
@@ -1337,6 +1337,51 @@ FAB открывает лист, а не сразу системный выбо
- `review_next` на компьютере «Перейти к следующей» согласуется только с «неточностью» и «ошибкой», а не с «зевком»; на телефоне — нейтрально «к следующему такому ходу». Компьютеру — по желанию то же.
- Остальные пять языков для строк с *: «Erneut» / «Von vorn» (de), «Empezar de nuevo» (es), «Recommencer» (fr), «Ricomincia» (it) для `review_restart`; «Analyse ausblenden», «Ocultar el análisis», «Masquer l'analyse», «Nascondi l'analisi» для `review_hide`; `review_next` — «Zum nächsten solchen Zug», «Ir a la siguiente jugada así», «Aller au coup suivant de ce type», «Vai alla prossima mossa di questo tipo»; `review_engine_paused` — с заглавной: «Pausiert: …», «En pausa: …», «En pause : …», «In pausa: …».
+### 14.8. Партии с Lichess и Chess.com (§23)
+
+Слова — как на компьютере (`apps/desktop/src/i18n.rs`, блок онлайн-партий), где строка там есть. ✎ — изменить, + — добавить. `{games}` — `games_count` («473 партии»), `{n}` — число с пробелами между разрядами (`groupDigits`), никогда не голый `%d` для числа партий.
+
+| Ключ | RU | EN |
+|---|---|---|
+| `online_title` | Партии с Lichess и Chess.com | Games from Lichess and Chess.com |
+| `online_title_short` + (только если длинный заголовок обрезается, §23.2) | Lichess и Chess.com | Lichess and Chess.com |
+| `add_online_hint` | Партии любого игрока по нику: свои, ученика, соперника | Any player's games by nickname: yours, a pupil's, an opponent's |
+| `online_intro` ✎ (не повторять подпись листа) | Партии игрока станут базой на телефоне — искать, смотреть, анализировать. Нужен только ник, входить на сайт не нужно. | The player's games become a database on your phone, to search, view and analyse. Only the nickname is needed, no login. |
+| `online_nick` / `online_nick_lichess` + (когда открыто второе поле) | Ник игрока / Ник на Lichess | Player's nickname / Nickname on Lichess |
+| `online_nick_hint` | как на сайте | as on the site |
+| `online_other` / `online_other_nick` / `online_same_nick` | На Chess.com другой ник / Ник на Chess.com / Тот же ник | A different nickname on Chess.com / Nickname on Chess.com / The same nickname |
+| `online_nick_rule` | Латиница, цифры, _ и -, от 2 до 30 символов | Latin letters, digits, _ and -, 2 to 30 characters |
+| `online_find` / `online_searching` | Найти / Ищу на сайтах… | Find / Looking on the sites… |
+| `games_up_to` + (plurals) | до {n} партии (one) / до {n} партий (few, many) / до {n} партии (other) | up to {n} game / up to {n} games |
+| `online_lichess_found` ✎ | {up_to} · первый раз около {m} мин | {up_to} · about {m} min the first time |
+| `online_lichess_quick` + | {up_to} · первый раз меньше минуты | {up_to} · under a minute the first time |
+| `online_chesscom_found` | месяцев с партиями: {m} | months with games: {m} |
+| `online_not_found` ✎ (как на компьютере) | {site}: игрока с таким ником нет — проверьте написание | {site}: no player with this nickname — check the spelling |
+| `online_merge` / `online_merge_hint` | Объединить оба сайта в одну базу / Иначе у каждого сайта будет своя база | Merge both sites into one database / Otherwise each site gets a database of its own |
+| `online_into_new` / `online_into_existing` | В новую базу «{name}» / В базу «{name}» (там уже {games}; добавятся только новые) | Into the new database “{name}” / Into “{name}” ({games} there already; only new games are added) |
+| `online_download` / `online_stop` / `online_open` | Скачать / Остановить / Открыть базу | Download / Stop / Open the database |
+| `online_progress_lichess` ✎ (`{t}` — число, без слова) | Lichess: {n} из примерно {t} · осталось около {m} мин | Lichess: {n} of about {t} · about {m} min left |
+| `online_progress_chesscom` | Chess.com: месяц {i} из {k} · {games} | Chess.com: month {i} of {k} · {games} |
+| `online_leave` + | Можно уйти с этого экрана: база уже в списке, скачивание продолжится. | You can leave this screen: the database is on the list and the download goes on. |
+| `online_done` + (первое скачивание) | Готово: {games} | Done: {games} |
+| `online_added` ✎ (`{n}` с разрядами) | +{n}, всего {games} | +{n}, {games} in all |
+| `online_no_new` / `online_stopped` | Новых партий нет, в базе {games} / Остановлено, в базе {games} | No new games, {games} in the database / Stopped, {games} in the database |
+| `online_no_games` | Партий в обычные шахматы там нет. | No games of standard chess there. |
+| `online_try_again` | Попробовать ещё раз | Try again |
+| `online_err_*` | §23.4, как на компьютере; `online_err_disk` — «на телефоне не хватает места» | as on the desktop; `online_err_disk` — “the phone is out of space” |
+| `online_short_network` / `online_short_rate` / `online_short_failed` | {site} не отвечает / {site} просит паузу / Скачивание прервалось | {site} does not answer / {site} asks for a pause / The download stopped |
+| `online_update` / `online_stop_download` | Скачать новые партии / Остановить скачивание | Download new games / Stop the download |
+| `online_downloading` | Скачивается · {n} | Downloading · {n} |
+| `online_updated` / `online_updated_now` + / `online_unfinished` | обновлено {when} / обновлено только что / не докачана | updated {when} / updated just now / not finished |
+| `online_snack_added` + / `online_snack_none` + / `online_snack_failed` + | «{name}»: +{n}, всего {games} / «{name}»: новых партий нет / «{name}»: {short} | “{name}”: +{n}, {games} in all / “{name}”: no new games / “{name}”: {short} |
+| `online_removed` | Скачанная база удалена | Downloaded database deleted |
+| `db_empty_body` ✎ | Добавьте файл PGN, базу ChessBase или архив .zip/.7z — с телефона или из облака — или скачайте партии с Lichess и Chess.com. | Add a PGN file, a ChessBase database or a .zip/.7z archive — from your phone or the cloud — or download games from Lichess and Chess.com. |
+
+- **Почему `games_up_to`.** «до» и «из примерно» требуют родительного падежа: «до 24 партий», а `games_count` даёт «24 партии». В `online_progress_lichess` проще всего, как на компьютере, подставить голое число. В de/es/fr/it падеж не меняется — там `games_up_to` повторяет `games_count` с предлогом: «bis zu {n} Partien», «hasta {n} partidas», «jusqu'à {n} parties», «fino a {n} partite».
+- **`online_added`:** сейчас `+%1$d` — «+6541» без пробела, а рядом «6 541 партия». Подставлять `groupDigits`.
+- **Новые строки, другие языки.** `online_leave`: «Sie können diesen Bildschirm verlassen: die Datenbank ist in der Liste, der Download läuft weiter.» / «Puedes salir de esta pantalla: la base ya está en la lista y la descarga continúa.» / «Vous pouvez quitter cet écran : la base est dans la liste et le téléchargement continue.» / «Puoi uscire da questa schermata: la base è già nell'elenco e il download continua.» `online_done`: «Fertig: {games}» / «Listo: {games}» / «Terminé : {games}» / «Fatto: {games}». `online_updated_now`: «gerade aktualisiert» / «actualizada ahora mismo» / «mise à jour à l'instant» / «aggiornata adesso». `online_nick_lichess`: «Nickname auf Lichess» / «Apodo en Lichess» / «Pseudo sur Lichess» / «Nickname su Lichess». `online_not_found`, `online_snack_*` — с компьютера (`✖` не ставить).
+- **Мелочи остальных языков.** it `online_downloading` «Download · {n}» читается как кнопка — лучше «Download in corso · {n}». fr `online_title` как на компьютере («de Lichess et Chess.com») — оставить ради единства.
+
## 15. Первая версия и дальше
### 15.1. Первая версия
@@ -1355,7 +1400,7 @@ FAB открывает лист, а не сразу системный выбо
3. Справочник позиции (как вкладка «Справочник» на компьютере) и поиск по позиции.
4. Перевод комментариев (`translation-ui.md`).
5. Отчёт по партии.
-6. Скачивание партий с Lichess и Chess.com по нику.
+6. ~~Скачивание партий с Lichess и Chess.com по нику.~~ Сделано (§23).
7. «Поделиться» картинкой позиции.
8. Порядок баз перетаскиванием, фильтры для малых баз.
9. Магазины приложений: F-Droid, Google Play.
@@ -1538,3 +1583,104 @@ FAB открывает лист, а не сразу системный выбо
- §21.6 — «Пауза: идёт анализ партии» с заглавной, без ▾.
- §12.3, §14.7 — озвучивание и таблица строк; правки «Скрыть анализ», «Лучшая линия · ход …», «к следующему такому ходу»; `review_no_line` удалить.
- По итогам тестирования (2026-10-23): поворот телефона во время анализа не останавливает его насовсем — анализ продолжается сам, как после возврата из фона; посчитанное пишется в кэш и по ходу работы (раз в 10 с), чтобы падение приложения не теряло минуты работы; «Дополнить» считает с тем же качеством, что и первый прогон (один отчёт — одно качество), поэтому оценка времени при «Дополнить» берёт прежнее качество, а выбор качества относится к «Заново»; у партии без ходов пункт ⋮ неактивен; пат в конце, как и мат, движку не отдаётся; в альбомной ориентации правая колонка не заходит под системные кнопки.
+
+## 23. Партии с Lichess и Chess.com (2026-10-23)
+
+То же, что на компьютере (0.8.0, `CHANGELOG.md`): партии любого игрока по нику — свои, ученика, соперника — без входа на сайт, в базу PGN; позже «Скачать новые партии» добавляет только новые. Скачивание, файл состояния, продолжение после обрыва без повторов — общий крейт `online-games`, тот же, что на компьютере.
+
+Сеть: обе сборки получают разрешение INTERNET (раньше сборка с движком в сеть не ходила). В сеть ничего не уходит, пока человек сам не нажал «Найти» или «Скачать»; при запуске сайты не опрашиваются (на компьютере опрашиваются — на телефоне это лишний трафик и батарея).
+
+### 23.1. Пути пользователя
+
+1. **Первый раз.** Базы → «Добавить базу» → «Партии с Lichess и Chess.com» (первая строка листа, после «Вставить из буфера», если она есть) → экран: ник → «Найти» → что нашлось на каждом сайте → «Скачать». Ход скачивания виден на этом же экране; с экрана можно уйти — база уже в списке, её строка показывает «Скачивается · 1 234». Когда готово — «Открыть базу».
+2. **Новые партии.** Механизм — докачка (решение владельца): «Скачать новые партии» берёт только партии, сыгранные после прошлого скачивания. Два входа: строка базы → ⋮ и значок ⤓ в верхней панели «Партий» этой базы (§23.3). Итог — снекбар «Magnus: +12, всего 1 246» или «Magnus: новых партий нет», как на компьютере. Без снекбара человек не узнаёт, что докачка прошла впустую: подпись «обновлено 1 мин назад» этого не говорит.
+3. **Разные ники.** Ссылка «На Chess.com другой ник» открывает второе поле; первое тогда называется «Ник на Lichess».
+4. **Оба сайта.** Найдены оба — по умолчанию одна база «Ник (Lichess + Chess.com)»; выключенный переключатель «Объединить оба сайта в одну базу» делает две.
+5. **Обрыв.** Нет сети, сайт просит паузу, приложение закрыли — скачанное остаётся в базе, подпись «не докачана» или текст ошибки, «Скачать новые партии» продолжает с того же места без повторов.
+6. **Удаление.** «Убрать из списка» удаляет скачанную базу с телефона, как копию (§20), со снекбаром «Скачанная база удалена · Вернуть»; идущее скачивание при этом останавливается.
+7. **Ничего не скачалось** (на сайте только варианты шахмат или ошибка с первого запроса) — базы с нулём партий не бывает: строка исчезает из списка, а на экране скачивания остаётся причина.
+
+Отдельной кнопки «Lichess» на экране «Базы» нет: вход в листе «Добавить базу» достаточно заметен (это первая постоянная строка), а лишняя кнопка спорила бы с FAB. Пустой экран (§3.1) упоминает сайты в тексте `db_empty_body` — так новичок узнаёт о возможности до того, как откроет лист.
+
+### 23.2. Экран «Партии с Lichess и Chess.com»
+
+```
+┌────────────────────────────────────┐
+│ ← Партии с Lichess и Chess.com │
+│ │
+│ Скачать партии любого игрока по │
+│ нику: свои, ученика, соперника. │
+│ ┌ Ник игрока ──────────────────┐ │ поле, «как на сайте»
+│ └──────────────────────────────┘ │
+│ На Chess.com другой ник │ ссылка → второе поле
+│ [Найти] │
+│ ─────────────────────────────── │
+│ ☑ Lichess · Magnus │ после поиска
+│ до 6 541 партии · ≈ 6 мин │
+│ ☑ Chess.com · magnus │
+│ месяцев с партиями: 84 │
+│ Объединить оба сайта в одну (●) │ только если отмечены оба
+│ базу │
+│ Иначе у каждого сайта своя база │
+│ В новую базу «Magnus (Lichess + │
+│ Chess.com)» │
+│ [Скачать] │
+└────────────────────────────────────┘
+```
+
+Уточнения после ревью (2026-10-23):
+
+- **Поля экрана 16 dp** (§10.1), не 24: 24 — для листов. Ссылка «На Chess.com другой ник» выровнена по левому краю поля (у `TextButton` свой отступ 12 dp — его убрать `contentPadding`, иначе ссылка «съезжает» вправо, как на снимке).
+- **Заголовок в верхней панели** — `online_title`. Он переносится на две строки и при шрифте 200 % занимает три; если тестировщик увидит обрезку, в панели показывать короткое `online_title_short` «Lichess и Chess.com», а полное имя оставить в листе «Добавить базу».
+- **Вводный текст** `bodyMedium` (14sp), не `bodyLarge`: это пояснение, а не содержание; так поле ника поднимается выше клавиатуры.
+- **Правило ника** — красным, только если в нике есть недопустимый знак или в нём больше 30 знаков. Ник из одной буквы, пока его печатают, не ошибка: «Найти» просто неактивна. Ребёнок не должен видеть красное после первой же буквы.
+- **«Найти»** скрывает клавиатуру (результаты иначе остаются под ней) и прокручивает к ним. После поиска, пока ник не изменён, «Найти» становится контурной: главная кнопка на экране одна — «Скачать».
+- **Строка Lichess:** «до 6 541 партии · первый раз около 6 мин». «До» — потому что в счёт сайта входят и варианты шахмат, которые не скачиваются. Число с предлогом склоняется отдельным plurals `games_up_to` (RU: «до 1 партии», «до 24 партий», «до 6 541 партии»), а не через `games_count` — «до 24 партии» неграмотно. Если на скачивание нужно меньше минуты — «первый раз меньше минуты».
+- **Не найден** — как на компьютере: «Lichess: игрока с таким ником нет — проверьте написание», без галочки. Сайт не ответил — текст ошибки (§23.4) цветом `error` и «Попробовать ещё раз».
+- **Переключатель** «Объединить оба сайта в одну базу» — строка 64 dp целиком переключает (`toggleable`, роль Switch); по умолчанию включён.
+- **Куда:** «В новую базу «…»» или «В базу «…» (там уже 1 234; добавятся только новые)». Имя — как в списке баз (с учётом переименования), а не имя файла.
+- **После «Скачать»** кнопка «Скачать» и галочки скрываются, пока человек не нажмёт «Найти» снова (новый ник или те же). Иначе в конце на экране две заполненные кнопки — «Скачать» и «Открыть базу», и повторное «Скачать» неочевидно, что делает.
+- **Карточка скачивания:** имя базы (`titleMedium`), строка хода («Lichess: 1 200 из примерно 6 541 · осталось около 5 мин», «Chess.com: месяц 12 из 84 · 340 партий»; общее число — цифрами, без слова «партий»), полоса, под ней `online_leave` «Можно уйти с этого экрана: база уже в списке, скачивание продолжится» и «Остановить» (контурная).
+ - Полоса при двух сайтах в одной базе — общая: доля = (номер сайта + доля сайта) / число сайтов. Сейчас она доходит до конца на Lichess и снова начинается с нуля на Chess.com.
+- **Итог:** первое скачивание — «Готово: 6 541 партия»; докачка — «+12, всего 1 246»; без новых — «Новых партий нет, в базе 1 234»; остановлено — «Остановлено, в базе 1 200». Затем «Открыть базу» (заполненная). Ошибка — текст §23.4 цветом `error`, и при этом, если в базе что-то есть, тоже «Открыть базу».
+- **Поворот экрана** сохраняет найденное (`found`, отметки) — человек не должен искать заново.
+
+### 23.3. Строка такой базы в списке
+
+- Значок формата «PGN», подпись: «1 234 партии · обновлено 3 ч назад»; пока не закончено ни одно скачивание — «1 234 партии · не докачана». Меньше минуты назад — «обновлено только что» (не «1 минуту назад»).
+- Во время скачивания: «Скачивается · 1 234» и полоса 2 dp по низу строки; ⋮ → «Остановить скачивание» (первым пунктом, на месте «Скачать новые партии»).
+- Ошибка последнего скачивания — подпись цветом `error`, число партий остаётся: «1 234 партии · Lichess не отвечает». Сейчас счёт пропадает, и база выглядит пустой. ⋮ → «Скачать новые партии» пробует снова.
+- Конец любого скачивания, пока виден экран «Базы» (в том числе начатого на экране §23.2, если человек ушёл с него), — снекбар 4 с: «Magnus: +12, всего 1 246» / «Magnus: новых партий нет» / «Magnus: Lichess не отвечает» (короткая форма). Действие снекбара — «Открыть», если в базе есть партии. Это единственная обратная связь докачки из списка (§23.1 п. 2).
+- **Верхняя панель «Партий» такой базы:** рядом с поиском значок `download` (Material Symbols), описание «Скачать новые партии». Пока идёт скачивание — на его месте ✕ «Остановить скачивание», под панелью полоса 2 dp; по концу — тот же снекбар, и список перечитывается сам, оставаясь на месте прокрутки. Зачем: базу своих партий открывают каждый день, и «новые партии» ищут там, где партии, а не в ⋮ списка баз. Свайп «потянуть, чтобы обновить» не делаем: жест скрытый, а ребёнок его не найдёт (§0 п. 4).
+
+### 23.4. Тексты ошибок
+
+Как на компьютере: «{site} не отвечает. Проверьте подключение к интернету и попробуйте ещё раз.»; «{site} просит сделать паузу…»; «{site} ответил непонятно…»; «Не удалось записать базу: на телефоне не хватает места.»; «Эта база уже скачивается.» Короткие формы для строки базы и снекбара: «{site} не отвечает», «{site} просит паузу», «Скачивание прервалось».
+
+### 23.5. Порядок партий (решение владельца, 2026-10-23)
+
+- В скачанной базе партии идут **от последней сыгранной к первой**: по `UTCDate` + `UTCTime`, если их нет — по `Date`; партии двух сайтов перемешаны по времени. Остальные базы — в порядке файла, как раньше.
+- ‹ › в партии и поиск идут в том же порядке; номер в строке партии — место в этом списке (№ 1 — самая свежая).
+- После докачки новые партии оказываются наверху — поэтому список после «Скачать новые партии» возвращается к началу только если человек и так был в начале; иначе остаётся на месте.
+- Вторая строка партии такой базы (предложение, nice): полная дата вместо года — «блиц · 12 мар. 2026 · C42». Год у всех партий за последний месяц одинаков и не помогает найти «вчерашнюю».
+
+### 23.6. TalkBack
+
+- Строка хода скачивания **не** живая область: она меняется 2–3 раза в секунду, и TalkBack читал бы её без остановки. Живая область (`Polite`) — только итог и ошибки; ход читается по фокусу.
+- «Ищу на сайтах…» и найденные строки — живая область `Polite` один раз, после поиска.
+- Найденная строка: «Lichess, Magnus, до 6 541 партии, первый раз около 6 минут, флажок, отмечен».
+- Строка базы во время скачивания: «Magnus (Lichess + Chess.com), скачивается, 1 234».
+- Значок в «Партиях»: «Скачать новые партии, кнопка» / «Остановить скачивание, кнопка».
+
+## 24. Ревью «Партий с Lichess и Chess.com» (2026-10-23)
+
+Ревью реализации (`OnlineScreen.kt`, `DatabasesScreen.kt`, `AddDatabase.kt`, `OnlineDownloads.kt`, строки `online_*` на шести языках) и снимков с эмулятора. Что изменено в спецификации:
+
+- §0 п. 7 — сеть нужна и для партий с сайтов, только по нажатию; §15.2 п. 6 — сделано.
+- §23.1 — докачка как механизм обновления (решение владельца); второй вход «Скачать новые партии» — значок в «Партиях» этой базы; итог докачки — снекбар; база без партий исчезает; отдельной кнопки на «Базах» нет, о сайтах говорит пустой экран.
+- §23.2 — поля 16 dp; вводный текст 14sp и без повтора подписи листа; правило ника не краснеет от первой буквы; «Найти» прячет клавиатуру; «Скачать» скрывается после запуска (две заполненные кнопки в конце); общая полоса для двух сайтов; подсказка «можно уйти с экрана»; «Готово: N партий» вместо «+N, всего N» при первом скачивании; имя базы — как в списке; найденное переживает поворот.
+- §23.3 — ошибка не прячет число партий; «обновлено только что»; снекбар по концу скачивания; значок в верхней панели «Партий».
+- §23.5 — порядок партий от последней (решение владельца), ‹ › и поиск в том же порядке.
+- §23.6 — TalkBack: ход скачивания не живая область.
+- §14.8 — таблица строк; падеж после «до» и «из примерно» (`games_up_to`, голое число), разряды в `online_added`.
+- По итогам тестирования (2026-10-23): найденное на экране §23.2 живёт вместе с экраном (у каждого экрана навигации своё хранилище состояния и ViewModel) — повторный вход начинается с чистого экрана, поворот найденное сохраняет; число партий и время обновления скачанной базы при запуске и после «Вернуть» берутся из файла состояния скачивания (докачка, оборванная закрытием приложения, сразу видна в строке); снекбар «База удалена · Вернуть» держится 10 с, а не бесконечно. Известно: при шрифте 130 % подпись строки базы обрезается многоточием.