diff --git a/AGENTS.md b/AGENTS.md index 0cdc3b21..803d9dc3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -302,3 +302,8 @@ Storage and folder screens inherit a one-row, 16 KiB local snapshot budget; Collections uses six projected rows. Capacity, file eligibility and removal previews belong to the companion; render paths never scan folders. Preserve reading sidecars and exclude the foreground book from removal previews. + +Device-local library projections use their own reserved owner without changing catalog +ownership. They inherit the same screen/widget row, byte and one-batch limits; folder and +sidecar work stays on the companion. Login adoption checkpoints secrets and its migration +marker together in the existing encrypted vault; never activate a second lifecycle writer. diff --git a/ROADMAP.md b/ROADMAP.md index 482d8892..421f2d83 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -20,7 +20,7 @@ CrossInk 2.x only; 1.6 is retired). | Server-free Android catalog operations: companion-owned covers, refresh, copies, recommendations and end-of-book snapshots and commands. | Android; X4 Pro, X4, X3 later under Android-first ruling | building: covers, mirror planning and query/store reads migrated; copies, grouping, recommendations and finish pending | | Independent optional account, sync and OPDS logins, encrypted credentials, origin-aware sign-out and account-wide reading statistics through the library interface. | Android; X4 Pro, X4, X3 later | building (Android F12-K foundation and F12-N plugin screens implemented; device acceptance and firmware follow) | | Configure one Book list widget with presets, paged counted sources and local Custom filters in the Home editor. | Android building; X4 Pro, X4, X3 follow Android | building (approved design rev 16; device acceptance pending) | -| Three-page Android Home, Library and Stats layout with Library widgets, shared filtered lists/search and saving custom filters as Home tiles. | Android building; X4 Pro, X4, X3 deferred by Android-first ruling | building (authorised 2026-11-25; device acceptance pending) | +| Two-page Android Home and Stats default (§4), with Library widgets, shared filtered lists/search and saving custom filters as Home tiles. | Android building; X4 Pro, X4, X3 deferred by Android-first ruling | building (authorised 2026-11-25; device acceptance pending) | | Clear, editable Custom reading values, apply-then-edit quick choices, device-local margins and one-time KOReader copy with Undo. | Android building (approved rev 16); X4 Pro, X4, X3 deferred to firmware implementation | building (F12-M; implemented, device acceptance pending) | | On-device Home editor: add/remove/move/resize widgets, manage and name pages, reset and atomically save layouts. | Android building (authorised 2026-11-25); X4 Pro, X4, X3 deferred to firmware implementation | building (device acceptance pending) | | Default owned Home for fresh installs and upgrades, additive migration, once-only upgrade news and clear signed-out shelves; paged widgets share one budgeted batch per paint. | Android; X4 Pro, X4, X3 later | building (authorised 2026-11-25; device acceptance pending) | diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/DeviceLibrary.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/DeviceLibrary.kt new file mode 100644 index 00000000..b09abdec --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/DeviceLibrary.kt @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion + +import java.io.File +import java.security.MessageDigest + +/** Device files have an identity even before a server is configured. Only the companion + * scans and parses native sidecars; LibraryReadModel still bounds every published window. */ +class DeviceLibrary(private val roots: List) : ServerAdapter { + override val id = "device" + companion object { const val OWNER = "device-local" } + private val books by lazy { + roots.distinctBy { it.canonicalPath }.flatMap { root -> + if (!root.isDirectory) emptyList() else root.walkTopDown().onEnter { + BulkWork.checkpoint() + Places.inside(it,listOf(root)) != null && !java.nio.file.Files.isSymbolicLink(it.toPath()) && !it.name.endsWith(".sdr") + }.filter { it.isFile && it.extension.lowercase() in setOf("epub","pdf","mobi","azw","azw3","fb2","djvu","cbz","cbr","txt") && + Places.inside(it,listOf(root)) != null }.map(::book).toList() + }.distinctBy { it["key"] } + } + private fun sidecar(file: File) = File(file.parentFile,"${file.nameWithoutExtension}.sdr") + private fun book(file: File): Map { + BulkWork.checkpoint() + val metadata=File(sidecar(file),"metadata.${file.extension}.lua") + val data=if(metadata.isFile && metadata.length()<=1048576 && Places.inside(metadata,roots)!=null) runCatching { + val text=metadata.readText(Charsets.ISO_8859_1).replaceFirst(Regex("\\A(?:--[^\\n]*\\n)?\\s*return\\s+"),"") + LuaValue.parse(text.toByteArray(Charsets.ISO_8859_1)) as? Map<*,*> + }.getOrNull() else null + val props=data?.get("doc_props") as? Map<*,*> + val summary=data?.get("summary") as? Map<*,*> + val fraction=(data?.get("percent_finished") as? Number)?.toDouble()?.takeIf { it.isFinite() && it in 0.0..1.0 } + val status=when(summary?.get("status")) { "complete" -> "finished"; "reading" -> "reading"; "abandoned" -> "abandoned"; else -> if(fraction!=null && fraction>0) "reading" else "unread" } + val hash=MessageDigest.getInstance("SHA-256").digest(file.canonicalPath.toByteArray()).joinToString("") { "%02x".format(it) } + val cover=sidecar(file).listFiles()?.filter { it.isFile && it.nameWithoutExtension=="cover" && Places.inside(it,roots)!=null }?.sortedBy { it.name }?.firstOrNull() + return mapOf("key" to "device:book:$hash","title" to LuaValue.boundedText((props?.get("title") as? String)?.let(LuaValue::utf8) ?: file.nameWithoutExtension,256), + "authors" to listOfNotNull((props?.get("authors") as? String)?.let { LuaValue.boundedText(LuaValue.utf8(it),256) }), + "local_path" to LuaValue.str(file.canonicalPath),"on_device" to true,"status" to status,"progress" to fraction?.times(100), + "last_read" to (metadata.lastModified()/1000).takeIf { metadata.isFile },"cover_path" to cover?.path?.let(LuaValue::str), + "formats" to listOf(file.extension.lowercase()),"available" to mapOf("cover" to (cover!=null)),"downloadable" to false) + } + override fun localFiles(owner: String): List? = if(owner==OWNER) books.map { + LocalBook(File(LuaValue.utf8(it["local_path"] as String)),it["status"]=="finished",null) + } else null + override fun project(owner: String, request: Map<*,*>): Map { + if(owner!=OWNER) return mapOf("error" to "unauthorized") + val fresh=mapOf("saved" to true,"origin" to "local-device") + fun rows(items: List<*>) = mapOf("items" to items,"freshness" to fresh) + val op=request["op"] + if(op=="capabilities") return mapOf("onDevice" to true,"readingStats" to true,"catalog" to true,"detail" to true,"download" to false, + "lists" to mapOf("read" to false,"save" to false),"wantToRead" to false,"progress" to mapOf("read" to true,"write" to false), + "status" to mapOf("read" to true,"write" to false)) + if(op in setOf("lists","collections")) return rows(emptyList()) + if(op=="sources") { + val definitions=listOf(Triple("device","On this device",books.size),Triple("reading","Reading now",books.count { it["status"]=="reading" }),Triple("finished","Finished",books.count { it["status"]=="finished" })) + val offset=((request["offset"] as? Number)?.toInt() ?: 0).coerceAtLeast(0) + val limit=((request["limit"] as? Number)?.toInt() ?: 6).coerceIn(1,6) + val items=if(request["category"] in setOf("lists","authors")) emptyList() else definitions.drop(offset).take(limit).map { (src,title,count) -> mapOf("src" to src,"title" to title,"count" to count) } + return rows(items)+mapOf("total" to if(items.isEmpty()) 0 else definitions.size) + } + if(op=="catalog.state") return mapOf("state" to "idle","freshness" to fresh) + if(op=="library.summary") return mapOf("total" to books.size,"on_device" to books.size,"freshness" to fresh) + if(op in setOf("book","reader","progress","status","cover")) { + val row=books.firstOrNull { if(op=="reader") it["local_path"]==request["path"] else it["key"]==request["key"] } ?: return rows(emptyList()) + return when(op) { + "cover" -> mapOf("local_path" to row["cover_path"],"freshness" to fresh) + "progress","status" -> row + mapOf("freshness" to fresh) + else -> rows(listOf(row)) + } + } + if(op !in setOf("window","counts","facets","groups")) return rows(emptyList()) + val filter=(request["query"] as? Map<*,*>).orEmpty().entries.associate { it.key.toString() to it.value } + LibraryFilter.validate(filter) + val source=request["source"] + val sourceFilter=when(source) { "reading" -> mapOf("show" to "reading"); "finished" -> mapOf("show" to "finished"); "want-to-read" -> mapOf("wtr" to true); else -> emptyMap() } + var selected=if(source !in setOf("all","library/all","on-device","reading","finished","search")) emptyList() else books.filter { LibraryFilter.matches(it,sourceFilter) && LibraryFilter.matches(it,filter) } + val sort=if(filter["sort"]==null && source=="reading") filter+mapOf("sort" to "last","dir" to "desc") else filter + selected=selected.sortedWith(LibraryFilter.comparator(sort)) + if(request["exclude_current"]==true && source=="reading") selected=selected.drop(1) + val offset=((request["offset"] as? Number)?.toInt() ?: 0).coerceAtLeast(0) + val limit=((request["limit"] as? Number)?.toInt() ?: 24).coerceIn(1,24) + if(op=="groups") return SeriesPresentation.groups(selected,filter,offset,limit.coerceAtLeast(5), + ((request["preview"] as? Number)?.toInt() ?: 3).coerceIn(1,9), + ((request["group_limit"] as? Number)?.toInt() ?: 2).coerceIn(1,6))+mapOf("freshness" to fresh) + if(op=="counts") return mapOf("total" to selected.size,"freshness" to fresh) + if(op=="facets") return LibraryFacets(request["field"].toString(),filter,System.currentTimeMillis()/1000).let { facet -> + selected.forEach { facet.include(it) }; facet.page(offset,limit)+mapOf("freshness" to fresh) } + return rows(selected.drop(offset).take(limit)) + mapOf("total" to selected.size,"next" to (offset+limit).takeIf { it RemoteReadingStats?)? = null, private val accountState: () -> Map = { mapOf("signedIn" to false) }, private val accountStats: (String) -> Map<*, *>? = { null }, - private val adapter: ServerAdapter = ServerAdapters.forStore(store, clock = clock, - fallbackReadingStats = fallbackReadingStats, accountState = accountState, accountStats = accountStats), + private val adapter: ServerAdapter? = null, ) { companion object { const val MAX_BYTES = 16384 @@ -27,18 +26,23 @@ class LibraryReadModel( var changed = false require(requests.size <= MAX_BATCH) // Never take ownership from a read command, nor expose a prior account's data. - if (store.meta("owner") != owner) return false - val storage by lazy { DeviceStorage(store, adapter) } + if (owner != DeviceLibrary.OWNER && store.meta("owner") != owner) return false + val local = owner == DeviceLibrary.OWNER + val projection = if (local) DeviceLibrary(DeviceStorage.folders.map { + java.io.File(store.root.parentFile?.parentFile?.parentFile ?: store.root,it) + } + DeviceStorage.downloadRoot(store.root)) else adapter ?: ServerAdapters.forStore(store, clock = clock, + fallbackReadingStats = fallbackReadingStats, accountState = accountState, accountStats = accountStats) + val storage by lazy { DeviceStorage(store, projection) } val power by lazy { battery() } - val account by lazy { accountStats(owner) } - val stats by lazy { ReadingStats.display(AccountStats.combine(readingStats(), adapter.cachedReadingStats(owner), account, clock()), clock(), AccountStats.zone(account)) } + val account by lazy { if (local) null else accountStats(owner) } + val stats by lazy { ReadingStats.display(AccountStats.combine(readingStats(), if (local) null else projection.cachedReadingStats(owner), account, clock()), clock(), AccountStats.zone(account)) } for (encoded in requests) { val start = System.nanoTime() val request = encoded as? String ?: continue if (request.length > 8192) continue val args = LuaValue.parse(request.toByteArray(Charsets.ISO_8859_1)) as? Map<*, *> ?: continue store.transaction { - if (store.meta("owner") != owner) return@transaction + if (!local && store.meta("owner") != owner) return@transaction val result = try { when (args["op"]) { "storage.summary" -> storage.summary(owner,(args["exclude_path"] as? String)?.let(LuaValue::utf8),(args["current_folder"] as? String)?.let(LuaValue::utf8)) "reader.controls" -> ReaderControls.project(args["native"] as? Map<*, *> ?: emptyMap()) @@ -48,8 +52,8 @@ class LibraryReadModel( "mode-estimates" -> BatteryEstimate.modeRows(power, (args["limit"] as? Number)?.toInt() ?: 3) "battery" -> power "sleep.choices" -> SleepChoiceWindow.project(SleepChoices.read(SleepScreen.dir()), args) - "capabilities" -> adapter.capabilities(owner) + mapOf("battery" to true) - else -> adapter.project(owner, args) + "capabilities" -> projection.capabilities(owner) + mapOf("battery" to true) + else -> projection.project(owner, args) } } catch (_: IllegalArgumentException) { mapOf("error" to "unsupported", "items" to emptyList()) } val items = result["items"] as? List<*> val measuredRows = items.orEmpty().size + items.orEmpty().sumOf { diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerAdapters.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerAdapters.kt index 1402861b..36b32874 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerAdapters.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerAdapters.kt @@ -12,6 +12,7 @@ import net.fledgewing.orbitcompanion.server.bookorbit.BookOrbitProjection import net.fledgewing.orbitcompanion.server.bookorbit.BookOrbitLibrary import net.fledgewing.orbitcompanion.server.bookorbit.CacheStore import net.fledgewing.orbitcompanion.server.bookorbit.ConnectorPlugin +import net.fledgewing.orbitcompanion.server.bookorbit.LegacyLoginAdoption import net.fledgewing.orbitcompanion.server.bookorbit.SleepChoicesProjection /** The only production composition root allowed to import an implementation. */ @@ -27,6 +28,9 @@ object ServerAdapters { fun session(ctx: Context, id: String = "bookorbit"): ServerAdapter { require(id == "bookorbit") { "unknown adapter" } val credentials = ServerCredentials(EncryptedAccountVault.android(ctx)) + LegacyLoginAdoption.run(credentials, + java.io.File(android.os.Environment.getExternalStorageDirectory(), "koreader/settings.reader.lua"), + java.io.File(android.os.Environment.getExternalStorageDirectory(), "koreader/settings/opds.lua")) val account = BookOrbitAccount(credentials.accountVault, AccountHttp, setupOnSignIn = { false }) return BookOrbitServerAdapter(credentials, account, ConnectorHttp, legacyAccount = { net.fledgewing.orbitcompanion.server.bookorbit.LegacyCoverSource.read( @@ -36,6 +40,7 @@ object ServerAdapters { AdapterWorker.acquireCoverReference(ctx,creds,owner,reference,refresh,done) }, coverJob = { creds, owner, key, done -> AdapterWorker.acquireCover(ctx,creds,owner,key,done) }) } + fun projectionStore(root: java.io.File): ProjectionStore = CacheStore(root) val cachedLists: CachedListProjection get() = SleepChoicesProjection val connector: ConnectorInstaller get() = ConnectorPlugin val runtime: ServerRuntime get() = AdapterWorker diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt index d57c4637..fb18ff2e 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt @@ -29,6 +29,32 @@ object Worker { fun busy() = ServerAdapters.runtime.busy() val mirrorRunning get() = ServerAdapters.runtime.mirrorRunning fun progressLine() = ServerAdapters.runtime.progressLine() - fun onIntent(ctx: Context, i: Intent) = ServerAdapters.runtime.onIntent(ctx, i) + fun onIntent(ctx: Context, i: Intent) { + if (i.action == ACTION_PATCH && i.getStringExtra("owner") == DeviceLibrary.OWNER && i.hasExtra("library_batch")) { + val encoded=i.getStringExtra("library_batch")?.takeIf { it.length<=131072 } ?: return + val app=ctx.applicationContext + BulkWork.attach(app) + BulkWork.executor.execute { + runCatching { + val requests=LuaValue.parse(LuaValue.str(encoded).toByteArray(Charsets.ISO_8859_1)) as? List<*> ?: return@runCatching + ServerAdapters.projectionStore(root()).use { store -> + val model=LibraryReadModel(store,readingStats={ + ReadingStats.read(File(root().parentFile,"statistics.sqlite3"),System.currentTimeMillis()/1000) + },battery={ StatsStore.get(app).batterySnapshot(System.currentTimeMillis(),java.time.ZoneId.systemDefault()) }) + if(model.publish(DeviceLibrary.OWNER,requests)) { + val spool=File(root(),"events").apply { mkdirs() } + val file=File(spool,"device-${java.util.UUID.randomUUID()}.lua") + android.util.AtomicFile(file).let { atomic -> + val out=atomic.startWrite() + try { out.write(LuaValue.encode(mapOf("kind" to "library","owner" to DeviceLibrary.OWNER))); atomic.finishWrite(out) } + catch(e: Exception) { atomic.failWrite(out); throw e } + } + ServerAdapters.runtime.onIntent(app,Intent(ACTION_PATCH).putExtra("drain_events","1")) + } + } + }.onFailure { OLog.w("library.device publication unavailable") } + } + } else ServerAdapters.runtime.onIntent(ctx,i) + } internal fun nativeFooterRepair(before: String, after: String, token: String) = ServerAdapters.runtime.nativeFooterRepair(before, after, token) } diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitServerAdapter.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitServerAdapter.kt index 22ec34b3..764da573 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitServerAdapter.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitServerAdapter.kt @@ -40,7 +40,7 @@ internal class BookOrbitServerAdapter(private val credentials: ServerCredentials "username" to accountState["username"], "server" to accountState["server"], "account" to mapOf("set" to (accountState["signedIn"] == true), "origin" to "user".takeIf { accountState["signedIn"] == true }), "sync" to status("sync"), "opds" to status("opds"), "owner" to sourceOwner, - "catalog" to mapOf("cachedDetail" to (legacy!=null),"canRefresh" to (legacy!=null || credentials.login("sync")?.owner()==sourceOwner))) + "catalog" to mapOf("cachedDetail" to (legacy!=null || credentials.login("sync")?.let { it.adopted && it.owner()==sourceOwner }==true),"canRefresh" to (legacy!=null || credentials.login("sync")?.owner()==sourceOwner))) } override fun signIn(server: String, username: String, password: CharArray) { try { diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLoginAdoption.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLoginAdoption.kt new file mode 100644 index 00000000..ea60f599 --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLoginAdoption.kt @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import java.io.File + +/** Worker-only upgrade bridge. Source files remain owned by their existing writers. + * No HTTP, plaintext destination, password logging or position-writer activation. */ +internal object LegacyLoginAdoption { + fun run(credentials: ServerCredentials, settings: File, opds: File) { + if (credentials.legacyImported()) return + // Storage may not be accessible on the first process launch. Retry after it is granted. + if (!settings.isFile && !opds.isFile) return + if (settings.isFile && !settings.canRead() || opds.isFile && !opds.canRead()) return + val legacy = LegacyCoverSource.read(settings) + val logins = mutableMapOf() + legacy?.let { + logins["sync"] = ServerCredentials.Login(it.credentials.server, it.credentials.user, + it.credentials.key, "user", it.owner) + } + // KOReader's independent OPDS login is optional. Only the current server is eligible; + // multiple matching logins are ambiguous and must remain under native OPDS ownership. + if (opds.isFile && opds.length() in 1..4194304) { + val text = opds.readText(Charsets.ISO_8859_1) + val literal = StatusMarginRepair.literalTable(text, "servers") + val rows = literal?.let { LuaValue.parse(it.toByteArray(Charsets.ISO_8859_1)) as? List<*> }.orEmpty() + fun server(row: Map<*,*>): String? { + val url=(row["url"] as? String)?.let(LuaValue::utf8) ?: return null + val base=url.substringBefore("/opds").takeIf { url == "$it/opds" || url.startsWith("$it/opds/") } ?: return null + return base.takeIf { it.endsWith("/api/v1") && (legacy==null || it==legacy.credentials.server) } + } + val matches = rows.mapNotNull { it as? Map<*, *> }.filter { server(it)!=null } + matches.singleOrNull()?.let { row -> + val user = (row["username"] as? String)?.let(LuaValue::utf8) + val secret = (row["password"] as? String)?.let(LuaValue::utf8) + val base=server(row)!! + if (!user.isNullOrBlank() && !secret.isNullOrEmpty()) + logins["opds"] = ServerCredentials.Login(base,user,secret,"user",legacy?.owner) + } + } + credentials.adoptLegacy(logins) + } +} diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ServerCredentials.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ServerCredentials.kt index c14d1562..3fe553d0 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ServerCredentials.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ServerCredentials.kt @@ -4,10 +4,10 @@ import net.fledgewing.orbitcompanion.* /** Three independent optional logins in one encrypted document. No secret-bearing toString. */ class ServerCredentials(private val vault: AccountVault) { - internal class Login(val server: String, val user: String, val secret: String, val origin: String, private val accountOwner: String? = null) { + internal class Login(val server: String, val user: String, val secret: String, val origin: String, private val accountOwner: String? = null, val adopted: Boolean = false) { override fun toString() = "ServerLogin(redacted)" fun owner() = accountOwner ?: ("login:" + BookOrbitLibrary.namespace(user + "|" + server).removePrefix("bo:")) - fun encoded() = mapOf("server" to server, "user" to LuaValue.str(user), "secret" to LuaValue.str(secret), "origin" to origin, "accountOwner" to accountOwner) + fun encoded() = mapOf("server" to server, "user" to LuaValue.str(user), "secret" to LuaValue.str(secret), "origin" to origin, "accountOwner" to accountOwner, "adopted" to adopted) } private var data = vault.load().orEmpty().toMutableMap() private fun mutate(block: () -> Unit) { @@ -32,7 +32,7 @@ class ServerCredentials(private val vault: AccountVault) { @Synchronized internal fun login(kind: String): Login? { require(kind in KINDS) val raw = data[kind] as? Map<*, *> ?: return null - return Login(raw["server"] as String, LuaValue.utf8(raw["user"] as String), LuaValue.utf8(raw["secret"] as String), raw["origin"] as String, raw["accountOwner"] as? String) + return Login(raw["server"] as String, LuaValue.utf8(raw["user"] as String), LuaValue.utf8(raw["secret"] as String), raw["origin"] as String, raw["accountOwner"] as? String, raw["adopted"] == true) } @Synchronized fun status(kind: String): Map { val login = login(kind) @@ -45,5 +45,19 @@ class ServerCredentials(private val vault: AccountVault) { return true } @Synchronized fun remove(kind: String) { require(kind in KINDS); mutate { data.remove(kind) } } + @Synchronized internal fun legacyImported() = data["legacyImported"] == true + + /** One atomic encrypted checkpoint. A restart cannot expose half the imported logins, + * overwrite a newer login, or resurrect one the reader subsequently removed. */ + @Synchronized internal fun adoptLegacy(logins: Map) { + if (data["legacyImported"] == true) return + mutate { + for ((kind, login) in logins) { + require(kind in KINDS && login.origin == "user") + if (data[kind] == null) data[kind] = login.encoded() + mapOf("adopted" to true) + } + data["legacyImported"] = true + } + } companion object { val KINDS = setOf("sync", "opds") } } diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/AccountAdapterTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/AccountAdapterTest.kt index e467aa42..5d452696 100644 --- a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/AccountAdapterTest.kt +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/AccountAdapterTest.kt @@ -64,6 +64,23 @@ class AccountAdapterTest { fun origin(kind: String) = (adapter.state()[kind] as Map<*,*>)["origin"] fun canSync() = adapter.position("a".repeat(32)) } + @Test fun adoptedUpgradeLoginsSyncAndDownloadWithoutAnAccountOrNetworkSetup() { + val k=Kit() + val legacyOwner="fixture|https://library.invalid/api/v1" + k.credentials.adoptLegacy(mapOf( + "sync" to ServerCredentials.Login("https://library.invalid/api/v1","fixture-sync","a".repeat(32),"user",legacyOwner), + "opds" to ServerCredentials.Login("https://library.invalid/api/v1","fixture-opds","fixture-private","user",legacyOwner))) + assertTrue(k.calls.isEmpty()); assertEquals(0,k.syncCreates); assertEquals(0,k.opdsCreates) + assertEquals(legacyOwner,k.adapter.owner()); assertEquals(legacyOwner,k.adapter.positionOwner()) + assertEquals(false,k.adapter.state()["signedIn"]) + assertEquals(true,(k.adapter.state()["sync"] as Map<*,*>)["available"]) + assertEquals(true,(k.adapter.state()["catalog"] as Map<*,*>)["cachedDetail"]) + k.canSync() + assertEquals("a".repeat(32),k.calls.last().second["x-auth-key"]) + val row=((k.adapter.catalog()["items"] as List<*>).single() as Map<*,*>) + assertTrue(k.adapter.download(row["key"] as String,File("unused-upgrade-destination"))) + k.adapter.signOut(); k.canSync(); assertEquals("user",k.origin("opds")) + } @Test fun coverCommandResolvesOnlyCurrentAccountKeysInsideAdapter() { val k=Kit(); k.user("sync") val owner=k.credentials.login("sync")!!.owner() diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/AccountVaultTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/AccountVaultTest.kt index cec851e2..122876b8 100644 --- a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/AccountVaultTest.kt +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/AccountVaultTest.kt @@ -43,5 +43,18 @@ class AccountVaultTest { assertEquals("user",reloaded.status("sync")["origin"]) reloaded.remove("sync"); assertFalse(file.exists()) } + @Test fun importedPasswordIsOnlyPersistedInsideTheExistingEncryptedVault() { + val root=Files.createTempDirectory("import-encrypted").toFile() + try { + val file=java.io.File(root,"account.enc") + val key=KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + val vault=EncryptedAccountVault(file) { key } + val credentials=ServerCredentials(vault) + credentials.adoptLegacy(mapOf("opds" to ServerCredentials.Login("https://library.invalid/api/v1","fixture","import-secret","user"))) + assertFalse(String(file.readBytes()).contains("import-secret")) + assertEquals("import-secret",ServerCredentials(vault).login("opds")!!.secret) + assertEquals(listOf("account.enc"),root.listFiles()!!.map { it.name }) + } finally { root.deleteRecursively() } + } } diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/DeviceLibraryTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/DeviceLibraryTest.kt new file mode 100644 index 00000000..3b630759 --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/DeviceLibraryTest.kt @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import org.junit.Assert.* +import org.junit.Test +import java.io.File +import java.nio.file.Files + +class DeviceLibraryTest { + @Test fun localProjectionsWorkWithoutAdapterOrCatalogOwnershipAndAfterSignOut() { + val volume=Files.createTempDirectory("device-library").toFile() + try { + val folder=File(volume,"Books").apply { mkdirs() } + val book=File(folder,"fixture.epub").apply { writeText("fixture") } + val sidecar=File(folder,"fixture.sdr").apply { mkdirs() } + File(sidecar,"metadata.epub.lua").writeText("return {[\"doc_props\"]={[\"title\"]=\"Local title\"},[\"summary\"]={[\"status\"]=\"reading\"},[\"percent_finished\"]=0.25}") + val cover=File(sidecar,"cover.jpg").apply { writeText("fixture cover") } + val cache=File(volume,"koreader/settings/orbit-cache").apply { mkdirs() } + CacheStore(cache,{}) { JdbcSql(it) }.use { store -> + // No adapter is available: its methods must never be consulted for device data. + val unavailable=object : ServerAdapter { + override val id="unavailable" + override fun project(owner: String,request: Map<*,*>): Map = error("remote projection") + override fun cachedReadingStats(owner: String): RemoteReadingStats? = error("remote stats") + } + val model=LibraryReadModel(store,{99},{},readingStats={ mapOf("state" to "ready","total_seconds" to 600) }, + battery={ mapOf("level" to 75) },accountStats={ error("account stats") },adapter=unavailable) + fun read(op: String, vararg args: Pair): Map<*,*> { + val request=String(LuaValue.encode(mapOf("op" to op,"limit" to 1,"bytes" to 16384)+args),Charsets.ISO_8859_1) + model.publish(DeviceLibrary.OWNER,listOf(request)) + val body=store.db().query("SELECT body FROM library_views WHERE owner=? AND request=?",DeviceLibrary.OWNER,request) { it.bytes(0)!! }.single() + assertTrue(body.size<=16384) + return LuaValue.parse(body) as Map<*,*> + } + for(previousOwner in listOf(null,"previous-account")) { + if(previousOwner!=null) store.own(previousOwner) + val data=read("window","source" to "on-device") + val row=(data["items"] as List<*>).single() as Map<*,*> + assertEquals("Local title",row["title"]); assertEquals(book.canonicalPath,row["local_path"]) + assertEquals(25.0,(row["progress"] as Number).toDouble(),0.001) + assertEquals(cover.path,read("cover","key" to row["key"])["local_path"]) + assertEquals(true,read("capabilities")["onDevice"]) + assertEquals(false,read("capabilities")["download"]) + assertEquals(75L,read("battery")["level"]) + assertFalse(read("reading.stats").containsKey("error")) + assertEquals(previousOwner,store.meta("owner")) + assertFalse(model.publish("wrong-account",listOf("{op=\"battery\"}"))) + } + val request=String(LuaValue.encode(mapOf("op" to "battery","limit" to 1,"bytes" to 256)),Charsets.ISO_8859_1) + LibraryReadModel(store,{99},{},battery={ mapOf("oversized" to "x".repeat(17000)) },adapter=unavailable).publish(DeviceLibrary.OWNER,listOf(request)) + val result=store.db().query("SELECT body FROM library_views WHERE owner=? AND request=?",DeviceLibrary.OWNER,request) { LuaValue.parse(it.bytes(0)!!) as Map<*,*> }.single() + assertEquals("budget",result["error"]) + } + } finally { volume.deleteRecursively() } + } + @Test fun windowsAreBoundedFilteredAndDoNotFollowEscapingLinks() { + val root=Files.createTempDirectory("device-window").toFile() + val outside=Files.createTempDirectory("outside-device").toFile() + try { + for(i in 1..30) File(root,"Book $i.epub").writeText("fixture") + File(outside,"Private.epub").writeText("fixture") + Files.createSymbolicLink(File(root,"escape").toPath(),outside.toPath()) + val adapter=DeviceLibrary(listOf(root)) + val page=adapter.project(DeviceLibrary.OWNER,mapOf("op" to "window","source" to "on-device","limit" to 6,"query" to mapOf("sort" to "title"))) + assertEquals(6,(page["items"] as List<*>).size); assertEquals(30,page["total"]) + val search=adapter.project(DeviceLibrary.OWNER,mapOf("op" to "window","source" to "on-device","query" to mapOf("q" to "Book 20"))) + assertEquals(1,(search["items"] as List<*>).size) + assertEquals("unauthorized",adapter.project("other",mapOf("op" to "window"))["error"]) + } finally { root.deleteRecursively(); outside.deleteRecursively() } + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLoginAdoptionTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLoginAdoptionTest.kt new file mode 100644 index 00000000..5f3758c9 --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLoginAdoptionTest.kt @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import org.junit.Assert.* +import org.junit.Test +import java.io.File +import java.nio.file.Files + +class LegacyLoginAdoptionTest { + private class Vault : AccountVault { + var value: Map? = null + var failBefore=false + var failAfter=false + override fun load()=value + override fun save(value: Map?) { + if(failBefore) error("fixture crash before checkpoint") + this.value=value?.toMap() + if(failAfter) error("fixture crash after checkpoint") + } + } + private fun fixture(root: File): Pair { + val settings=File(root,"settings.reader.lua") + settings.writeBytes(LuaValue.encode(mapOf("bookorbit" to mapOf("server_url" to "https://library.invalid/api/v1", + "username" to LuaValue.str("fixture-读者"),"userkey" to "a".repeat(32)))).let { "return ".toByteArray()+it }) + val opds=File(root,"opds.lua") + opds.writeText("return {[\"servers\"]={{[\"url\"]=\"https://library.invalid/api/v1/opds\",[\"username\"]=\"fixture-opds\",[\"password\"]=\"fixture-private\"}}}") + return settings to opds + } + @Test fun upgradePreservesBothIndependentLoginsAndLegacyCatalogIdentity() { + val root=Files.createTempDirectory("legacy-adopt").toFile() + try { + val (settings,opds)=fixture(root); val original=settings.readBytes(); val v=Vault() + val c=ServerCredentials(v); LegacyLoginAdoption.run(c,settings,opds) + for(kind in ServerCredentials.KINDS) { + assertEquals(true,c.status(kind)["set"]); assertEquals("user",c.status(kind)["origin"]) + assertEquals(LegacyCoverSource.read(settings)!!.owner,c.login(kind)!!.owner()) + } + assertEquals("fixture-读者",c.login("sync")!!.user) + assertEquals("a".repeat(32),c.login("sync")!!.secret) + assertEquals("fixture-private",c.login("opds")!!.secret) + c.accountVault.save(mapOf("access" to "fixture")); c.accountVault.save(null) + assertNotNull(c.login("sync")); assertNotNull(c.login("opds")) + c.remove("sync"); c.remove("opds") + val restarted=ServerCredentials(v); LegacyLoginAdoption.run(restarted,settings,opds) + assertNull(restarted.login("sync")); assertNull(restarted.login("opds")) + assertArrayEquals(original,settings.readBytes()) + } finally { root.deleteRecursively() } + } + @Test fun noLoginAndUnavailableStorageDoNotInventCredentials() { + val root=Files.createTempDirectory("legacy-empty").toFile() + try { + val v=Vault(); val c=ServerCredentials(v); val settings=File(root,"settings.reader.lua"); val opds=File(root,"opds.lua") + LegacyLoginAdoption.run(c,settings,opds); assertNull(v.value) + settings.writeText("return {}") + LegacyLoginAdoption.run(c,settings,opds) + assertTrue(c.legacyImported()); assertNull(c.login("sync")); assertNull(c.login("opds")) + } finally { root.deleteRecursively() } + } + @Test fun upgradeCanAdoptAnIndependentOpdsLoginWithoutSync() { + val root=Files.createTempDirectory("legacy-opds-only").toFile() + try { + val (settings,opds)=fixture(root); settings.writeText("return {}") + val c=ServerCredentials(Vault()); LegacyLoginAdoption.run(c,settings,opds) + assertNull(c.login("sync")); assertEquals("user",c.status("opds")["origin"]) + assertEquals("fixture-private",c.login("opds")!!.secret) + } finally { root.deleteRecursively() } + } + @Test fun crashesBeforeAndAfterTheAtomicCheckpointAreIdempotent() { + val root=Files.createTempDirectory("legacy-crash").toFile() + try { + val (settings,opds)=fixture(root) + for(after in listOf(false,true)) { + val v=Vault().apply { failBefore=!after; failAfter=after } + val c=ServerCredentials(v) + assertThrows(IllegalStateException::class.java) { LegacyLoginAdoption.run(c,settings,opds) } + assertNull(c.login("sync")); assertNull(c.login("opds")) + v.failBefore=false; v.failAfter=false + val restarted=ServerCredentials(v); LegacyLoginAdoption.run(restarted,settings,opds) + assertTrue(restarted.legacyImported()); assertNotNull(restarted.login("sync")); assertNotNull(restarted.login("opds")) + } + } finally { root.deleteRecursively() } + } + @Test fun currentLoginsWinAndUnrelatedOpdsIsNeverAdopted() { + val root=Files.createTempDirectory("legacy-current").toFile() + try { + val (settings,opds)=fixture(root); val c=ServerCredentials(Vault()) + c.set("sync",ServerCredentials.Login("https://other.invalid/api/v1","new-user","b".repeat(32),"user")) + opds.writeText(opds.readText().replace("library.invalid","unrelated.invalid")) + LegacyLoginAdoption.run(c,settings,opds) + assertEquals("new-user",c.login("sync")!!.user); assertNull(c.login("opds")) + } finally { root.deleteRecursively() } + } +} diff --git a/android/koreader/orbit.koplugin/ko/library.lua b/android/koreader/orbit.koplugin/ko/library.lua index a6b9f8c8..61083a52 100644 --- a/android/koreader/orbit.koplugin/ko/library.lua +++ b/android/koreader/orbit.koplugin/ko/library.lua @@ -4,7 +4,8 @@ -- inspect a server plugin, credentials or protocol records. Tests may inject this interface. if not rawget(getfenv(1),"LibraryAdapter") then LibraryAdapter={sent={},order={},ready={}} -function LibraryAdapter.owner() return LibraryAdapter.managed_owner end +LibraryAdapter.LOCAL_OWNER="device-local" +function LibraryAdapter.owner() return LibraryAdapter.managed_owner or LibraryAdapter.LOCAL_OWNER end function LibraryAdapter.read(request,op) if op=="account.state" and LibraryAdapter.account_snapshot then return LibraryAdapter.account_snapshot, LibraryAdapter.account_bytes diff --git a/android/koreader/orbit.koplugin/ko/store.lua b/android/koreader/orbit.koplugin/ko/store.lua index ab2020f2..bd0d0195 100644 --- a/android/koreader/orbit.koplugin/ko/store.lua +++ b/android/koreader/orbit.koplugin/ko/store.lua @@ -147,7 +147,9 @@ Store.within = within -- Ready-to-draw 0.12 results: one row, size checked by SQLite before decoding. -- Reuse the same owner/reading/busy gate as all existing cache reads. function Store.library(owner, request) - return within(owner, "library:" .. request, function(conn) + -- Device rows share this DB without claiming or reading the catalog's owner. + local catalog_owner = owner ~= "device-local" and owner or nil + return within(catalog_owner, "library:" .. request, function(conn) local r = rows(conn, "SELECT body FROM library_views WHERE owner=? AND request=? AND length(body)<=16384", owner, request)[1] local body = r and r[1] diff --git a/android/koreader/orbit.koplugin/logic/home_plan.lua b/android/koreader/orbit.koplugin/logic/home_plan.lua index 0df08372..c53209d2 100644 --- a/android/koreader/orbit.koplugin/logic/home_plan.lua +++ b/android/koreader/orbit.koplugin/logic/home_plan.lua @@ -78,6 +78,7 @@ function disabledText(app, disabler, hint) end -- One additive Android 0.12 cutover; all other settings and ledgers stay untouched. +-- No saved layout is rewritten: absent layouts use Layout.default() (M8C Home / Stats). function HomePlan.migrate012(settings) if settings.home_012_migrated then return false end local upgrade = next(settings) ~= nil diff --git a/android/koreader/orbit.koplugin/logic/layout.lua b/android/koreader/orbit.koplugin/logic/layout.lua index 97e5d35a..2b0a6205 100644 --- a/android/koreader/orbit.koplugin/logic/layout.lua +++ b/android/koreader/orbit.koplugin/logic/layout.lua @@ -188,10 +188,6 @@ function Layout.default() placement("resume","continue-reading",0,0,4,3),books("also","Also reading","reading",0,3), placement("lists","lists",2,3,2,3),placement("library","library",0,5,2,1), books("recent","Recently added","recent",0,6),books("want","Want to read","wtr",2,6)})}, - {id="library",tab="Library",name="Library",placements=arr({ - placement("library-overview","library",0,0,2,2), - placement("device","booklist",2,0,2,3,{title="On device",src="device",style=1}), - books("finished","Finished","finished",0,2)})}, {id="stats",tab="Insights",name="Stats",placements=arr({ placement("year","year-in-reading",0,0,4,3),placement("battery","battery",0,3,2,2), placement("hours","when-you-read",2,3,2,2),placement("week","this-week",0,5,2,3), diff --git a/android/koreader/test/booklist_flows.lua b/android/koreader/test/booklist_flows.lua index 38994a77..e3ae1f42 100644 --- a/android/koreader/test/booklist_flows.lua +++ b/android/koreader/test/booklist_flows.lua @@ -104,10 +104,10 @@ return function(test,eq,ok,E,W,Widget,withHost) for _,line in ipairs(filter.dialog.buttons) do for _,b in ipairs(line) do if b.text=="+ Save as a Book list on Home" then save=b.callback end end end ok(save); save() eq(e.model.index,originalIndex); eq(e.model.selected,"also") - eq(#e.model.document.pages,#original.pages); eq(#e.model.document.pages[2].placements,#original.pages[2].placements+1); ok(cfg.notice:find("Library",1,true)) + eq(#e.model.document.pages,#original.pages+1); eq(e.model.document.pages[2],original.pages[2]); eq(#e.model.document.pages[3].placements,1); ok(cfg.notice:find("Custom filter",1,true)) eq(E.S.home_layout,original); eq(cfg.cfg.query.show,"unread") press(cfg,"Done"); eq(cfg.alive,false); ok(e:done()) - eq(#E.S.home_layout.pages[2].placements,4) + eq(#E.S.home_layout.pages[3].placements,1) eq(E.S.home_layout.pages[1].placements[2].settings.src,"custom") end) end) diff --git a/android/koreader/test/home_editor_flows.lua b/android/koreader/test/home_editor_flows.lua index 0faaed7f..6ca4bb02 100644 --- a/android/koreader/test/home_editor_flows.lua +++ b/android/koreader/test/home_editor_flows.lua @@ -92,7 +92,7 @@ return function(test,eq,ok,E,W,Widget,withHost) test("Home editor: pages, keyboard rename, manual name retention, reset",function() withHost(function() local e=editor(); local m=e.model - click(e,"+ Page"); eq(m.index,2); eq(m:page().name,"Page 4") + click(e,"+ Page"); eq(m.index,2); eq(m:page().name,"Page 3") local id=m:page().id local Input=require("ui/widget/inputdialog") local keyboard=Input.onShowKeyboard; Input.onShowKeyboard=function() end @@ -106,7 +106,7 @@ return function(test,eq,ok,E,W,Widget,withHost) ok(m:add("booklist")); eq(m:page().name,"My shelves") click(e,"Move ›"); eq(m.index,3); eq(m:page().id,id) click(e,"Move ‹"); eq(m.index,2) - click(e,"Delete page"); W.shown[#W.shown].ok_callback(); eq(#m.document.pages,3) + click(e,"Delete page"); W.shown[#W.shown].ok_callback(); eq(#m.document.pages,2) click(e,"Reset"); W.shown[#W.shown].ok_callback(); eq(m.index,1); eq(m:page().name,"Home") eq(#m:page().placements,6) while #m.document.pages>1 do ok(m:pageAction("remove")) end; local before=m.document diff --git a/android/koreader/test/home_host_flows.lua b/android/koreader/test/home_host_flows.lua index 9e74bff9..f0128f12 100644 --- a/android/koreader/test/home_host_flows.lua +++ b/android/koreader/test/home_host_flows.lua @@ -306,22 +306,22 @@ return function(test,eq,ok,E,W,Widget) h:onCloseWidget(); eq(E.Library.listener,nil) end) end) - test("Home wiring: all three required default pages draw and Stats shares one bounded row",function() + test("Home wiring: both approved default pages draw and Stats shares one bounded row",function() withHost(function(batches,reads) E.S.home_layout=nil local h=E.HomeHost.create(); E.HomeHost.active=h; W.shown={h} local rectangles=0 local bb={paintRect=function(_,x,y,w,h,color) ok(w>=0 and h>=0); ok(color~=nil); rectangles=rectangles+1 end} - for page=1,3 do + for page=1,2 do eq(h.index,page) h[1]:paintTo(bb,0,0) ok(E.Budgets.check(E.Budgets.screens.home,h.metrics)) eq(h.metrics.spawns,0); eq(h.metrics.network,0); eq(h.metrics.roundTrips,1) - if page<3 then h:onNext() end + if page<2 then h:onNext() end end local stats=0 for _,a in ipairs(reads) do if a.op=="reading.stats" then stats=stats+1 end end - eq(stats,1); eq(#batches,3) + eq(stats,1); eq(#batches,2) ok(rectangles>=400,"real Year, weekly and hourly renderers painted") end) end) @@ -540,7 +540,7 @@ return function(test,eq,ok,E,W,Widget) eq(E.HomeHostPlan.snapshot({items={}}).state,"offline-without-data") eq(E.HomeHostPlan.snapshot({items={{key="b"}},freshness={saved=true,offline=true}}).state,"offline-with-data") local registry=E.HomeHost.installed() - eq(#E.HomeHostPlan.resolve(E.Layout.default(),registry,{}).pages,3) + eq(#E.HomeHostPlan.resolve(E.Layout.default(),registry,{}).pages,2) local projected=E.HomeHostPlan.resolve(E.Layout.default(),registry,{wantToRead=false,lists={read=false},battery=false}) for _,p in ipairs(projected.pages[1].placements) do ok(p.widget ~= "lists" and p.instance ~= "want") end end) diff --git a/android/koreader/test/layout_tests.lua b/android/koreader/test/layout_tests.lua index e5a039f2..601c6b5e 100644 --- a/android/koreader/test/layout_tests.lua +++ b/android/koreader/test/layout_tests.lua @@ -31,29 +31,34 @@ local function projected(d,page) local resolved=assert(L.resolve(d,"android-tablet",R)); return resolved.pages[page or 1] end -test("layout: required M8C Home, Library and Stats defaults are exact, independent copies",function() - local d=valid(L.default()); eq(#d.pages,3); eq(d.grids["android-tablet"].cols,4); eq(d.grids["android-tablet"].rows,8) - eq(d.pages[1].name,"Home"); eq(d.pages[2].name,"Library"); eq(d.pages[3].name,"Stats") +test("layout: approved §4 M8C Home and Stats defaults are exact, independent copies",function() + local d=valid(L.default()); eq(#d.pages,2); eq(d.grids["android-tablet"].cols,4); eq(d.grids["android-tablet"].rows,8) + eq(d.pages[1].name,"Home"); eq(d.pages[2].name,"Stats") local expected={{"continue-reading",0,0,4,3},{"booklist",0,3,2,2},{"lists",2,3,2,3},{"library",0,5,2,1},{"booklist",0,6,2,2},{"booklist",2,6,2,2}} for i,e in ipairs(expected) do local p=d.pages[1].placements[i] eq(p.widget,e[1]); eq(p.x,e[2]); eq(p.y,e[3]); eq(p.w,e[4]); eq(p.h,e[5]) end eq(d.pages[1].placements[2].settings.sort,3); eq(d.pages[1].placements[2].settings.title,"Also reading"); eq(d.pages[1].placements[6].settings.src,"wtr") - eq(d.pages[3].placements[1].w,4); eq(d.pages[3].placements[1].h,3) + eq(d.pages[2].placements[1].w,4); eq(d.pages[2].placements[1].h,3) local stats={{"year-in-reading",0,0,4,3},{"battery",0,3,2,2},{"when-you-read",2,3,2,2}, {"this-week",0,5,2,3},{"reading-records",2,5,2,3}} - for i,e in ipairs(stats) do local p=d.pages[3].placements[i] + for i,e in ipairs(stats) do local p=d.pages[2].placements[i] eq(p.widget,e[1]); eq(p.x,e[2]); eq(p.y,e[3]); eq(p.w,e[4]); eq(p.h,e[5]) end - local library={{"library",0,0,2,2},{"booklist",2,0,2,3},{"booklist",0,2,2,2}} - for i,e in ipairs(library) do local p=d.pages[2].placements[i] - eq(p.widget,e[1]); eq(p.x,e[2]); eq(p.y,e[3]); eq(p.w,e[4]); eq(p.h,e[5]) - end - eq(d.pages[2].placements[2].settings.src,"device"); eq(d.pages[2].placements[3].settings.src,"finished") d.pages[1].placements[1].x=9; eq(L.default().pages[1].placements[1].x,0) valid(round(L.default())) end) +test("layout: upgrading an existing three-page layout never replaces it with the default",function() + local saved=L.default() + table.insert(saved.pages,2,{id="library",tab="Library",name="My library",named=true,placements={tile("overview","library",0,0,2,2)}}) + local raw=assert(L.serialize(saved,codec)) + local settings={home_screen="server",home_layout=raw} + ok(M.HomePlan.migrate012(settings)); eq(settings.home_layout,raw) + local restored=assert(L.parse(settings.home_layout,codec)); eq(#restored.pages,3); eq(restored.pages[2].name,"My library") + eq(#L.default().pages,2) +end) + test("layout: schema, types, IDs, cardinalities and resource bounds",function() bad(function(d) d.schemaVersion=2 end); bad(function(d) d.revision=0 end) bad(function(d) d.pages={} end); bad(function(d) d.pages[2].id=d.pages[1].id end) diff --git a/android/koreader/test/test_flows.lua b/android/koreader/test/test_flows.lua index da298259..8a33ac2a 100644 --- a/android/koreader/test/test_flows.lua +++ b/android/koreader/test/test_flows.lua @@ -4915,6 +4915,41 @@ local function withStore(dir, fn) if not okf then error(err, 0) end end +test("library device owner: local SQLite rows survive sign-out without adopting the catalog", function() + local dir, st = fixtureStore() + st:run("CREATE TABLE library_views(owner TEXT,request TEXT,body BLOB,at INTEGER,PRIMARY KEY(owner,request))") + local request="device-owner-regression" + local body=RE.Cache.encode({items={{key="device:book:fixture",title="On this device"}}}) + st:run("INSERT INTO library_views VALUES(?,?,?,1)","device-local",request,body) + st:run("INSERT INTO library_views VALUES(?,?,?,1)",DBFX.owner,request,RE.Cache.encode({items={{title="Account catalog"}}})) + local decode,reading,conn=RE.Cache.decode,RE.reading,RE.Db.conn + local success,err=pcall(function() withStore(dir,function() + RE.reading=function() return false end + local localRow,bytes=RE.Store.library("device-local",request) + eq(localRow.items[1].title,"On this device"); eq(bytes,#body) + eq(RE.Store.meta(st.conn,"owner"),DBFX.owner,"local reads never reassign catalog ownership") + eq(RE.Store.library(DBFX.owner,request).items[1].title,"Account catalog") + eq(RE.Store.library("wrong-account",request),nil,"remote owners retain their guard") + st:run("DELETE FROM meta WHERE k='owner'") + eq(RE.Store.library("device-local",request).items[1].title,"On this device") + eq(RE.Store.meta(st.conn,"owner"),nil,"a never-signed-in reader stays unowned") + eq(RE.Store.library(DBFX.owner,request),nil,"device access cannot expose an old account") + local decoded=0 + RE.Cache.decode=function(raw) decoded=decoded+#raw; return decode(raw) end + st:run("UPDATE library_views SET body=? WHERE owner=?",string.rep("x",16385),"device-local") + eq(RE.Store.library("device-local",request),nil); eq(decoded,0,"SQL rejects oversized local snapshots before decoding") + st:run("UPDATE library_views SET body=? WHERE owner=?",body,"device-local") + local warm=RE.Store.library("device-local",request) + RE.reading=function() return true end + RE.Db.conn=function() error("reading must use the already decoded device row") end + eq(RE.Store.library("device-local",request),warm) + eq(RE.Store.library("device-local","cold-device-row"),nil) + end) end) + RE.Cache.decode,RE.reading,RE.Db.conn=decode,reading,conn + st:close(); os.execute("rm -rf '" .. dir .. "'") + ok(success,err) +end) + -- @fixture catalog/bulk-refresh/catalog.json @fixture catalog/bulk-refresh/schema.sql diff --git a/android/koreader/test/test_library.lua b/android/koreader/test/test_library.lua index e53c5818..4d81e64f 100644 --- a/android/koreader/test/test_library.lua +++ b/android/koreader/test/test_library.lua @@ -200,13 +200,13 @@ return function(test, eq, ok, here, Cache) local reads=0 local e=setmetatable({Cache=Cache,Library={}, serverPlugin=function() error("render accessed a server plugin") end, - Store={library=function(owner,request) reads=reads+1; eq(owner,"opaque-owner"); eq(request,"bounded"); return {items={}},32 end}}, {__index=_G}) + Store={library=function(owner,request) reads=reads+1; ok(owner=="opaque-owner" or owner=="device-local"); eq(request,"bounded"); return {items={}},32 end}}, {__index=_G}) setfenv(assert(loadfile(root.."ko/library.lua")),e)() e.LibraryAdapter.managed_owner="opaque-owner" eq(e.LibraryAdapter.owner(),"opaque-owner") local r,bytes=e.LibraryAdapter.read("bounded"); eq(#r.items,0);eq(bytes,32);eq(reads,1) e.LibraryAdapter.managed_owner=nil - eq(e.LibraryAdapter.read("bounded"),nil);eq(reads,1) + eq(e.LibraryAdapter.owner(),"device-local"); ok(e.LibraryAdapter.read("bounded")); eq(reads,2) end) test("storage: local IO and directory providers work without a backend", function() @@ -266,7 +266,7 @@ return function(test, eq, ok, here, Cache) local body=Cache.encode(state) local e=setmetatable({Cache=Cache,ServerCache={encode=Cache.encode,decode=Cache.decode},Budgets={MAX_SNAPSHOT=16384},Companion={workerProblem=function() end,AUTHORITY="fixture",PACKAGE="fixture"}, Jni={call=function() return {ok="1",body=body} end},serverPlugin=function() return nil end, - Store={library=function() error("no catalog should be read") end}}, {__index=_G}) + Store={library=function(owner) eq(owner,"device-local"); return nil end}}, {__index=_G}) setfenv(assert(loadfile(root .. "ko/library.lua")),e)() e.LibraryAdapter.accountReturned() local a,n=e.LibraryAdapter.read("opaque","account.state") diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 0fcf177f..110ef3e4 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -79,11 +79,11 @@ Counts include settings exposure as separate rows; they are not feature quality | Grouped BookSync settings and sync/power mode presets | 🟡 Android 0.12 Mode card, in-reader sleep timeout, Home row order, installed-channel/reader summaries and paged sleep choices; **deliberately deferred: Android-first implementation authorised 2026-11-25; source build is unreleased and requires device acceptance. Mode estimates require measured rates and observed use; Android owns timeout permission and effective power policy.**. [docs/design/booksync-home/F12-D-NOTES.md:1](../docs/design/booksync-home/F12-D-NOTES.md#L1), [docs/design/booksync-home/F12-E-NOTES.md:3](../docs/design/booksync-home/F12-E-NOTES.md#L3), [docs/design/booksync-home/F12-G-SETTINGS.md:1](../docs/design/booksync-home/F12-G-SETTINGS.md#L1) | ❌ Settings presentation and bounded sleep browsing follow Android; **deliberately deferred: Android-first Settings implementation authorised 2026-11-25. Native firmware power/settings integration follows Android.**. [docs/design/booksync-home/F12-D-NOTES.md:1](../docs/design/booksync-home/F12-D-NOTES.md#L1), [docs/design/booksync-home/F12-G-SETTINGS.md:1](../docs/design/booksync-home/F12-G-SETTINGS.md#L1) | ❌ Settings presentation and bounded sleep browsing follow Android; **deliberately deferred: Android-first Settings implementation authorised 2026-11-25. Native firmware power/settings integration follows Android.**. [docs/design/booksync-home/F12-D-NOTES.md:1](../docs/design/booksync-home/F12-D-NOTES.md#L1), [docs/design/booksync-home/F12-G-SETTINGS.md:1](../docs/design/booksync-home/F12-G-SETTINGS.md#L1) | ❌ Settings presentation and bounded sleep browsing follow Android; **deliberately deferred: Android-first Settings implementation authorised 2026-11-25. Native firmware power/settings integration follows Android. X3 also requires measured flash fit.**. [docs/design/booksync-home/F12-D-NOTES.md:1](../docs/design/booksync-home/F12-D-NOTES.md#L1), [docs/design/booksync-home/F12-G-SETTINGS.md:1](../docs/design/booksync-home/F12-G-SETTINGS.md#L1) | | Server-first Year, This week, hourly reading and Records widgets (0.12 foundation) | 🟡 0.12 account-first days, hours, weekly sessions, finished counts and goals; cached connector fallback with per-field provenance, integrated into Home with one shared snapshot per paint; **deliberately deferred: Android build authorised 2026-11-25; device acceptance and local finish/goal settings remain pending. No server inclusion watermark: local today stays separate.**. [docs/design/booksync-home/F12-F-NOTES.md:3](../docs/design/booksync-home/F12-F-NOTES.md#L3), [docs/design/bookorbit-account.md:1](../docs/design/bookorbit-account.md#L1), [docs/design/booksync-home/F12-J-NOTES.md:3](../docs/design/booksync-home/F12-J-NOTES.md#L3) | ❌ Home-integrated account-first Stats follow Android; firmware implementation deferred; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows the Android widgets.**. [docs/design/booksync-home/F12-F-NOTES.md:3](../docs/design/booksync-home/F12-F-NOTES.md#L3) | ❌ Home-integrated account-first Stats follow Android; firmware implementation deferred; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows the Android widgets.**. [docs/design/booksync-home/F12-F-NOTES.md:3](../docs/design/booksync-home/F12-F-NOTES.md#L3) | ❌ Home-integrated account-first Stats follow Android; firmware implementation deferred; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows the Android widgets.**. [docs/design/booksync-home/F12-F-NOTES.md:3](../docs/design/booksync-home/F12-F-NOTES.md#L3) | | Owned reusable filter sheet (0.12 foundation; unreleased) | 🟡 Reusable filter sheet wired into owned lists and Search, with Save as a Book list on Home (feature/0.12; unreleased); **deliberately deferred: device acceptance and richer grouped-list presentation follow the Android foundation**. [android/koreader/orbit.koplugin/ko/filter_sheet.lua:3](../android/koreader/orbit.koplugin/ko/filter_sheet.lua#L3) | ❌ Shared filter sheet and Save to Home wiring follow Android; same neutral filter and counting contract; **deliberately deferred: maintainer-authorised Android-first 0.12 build; firmware implementation follows**. [ROADMAP.md:36](../ROADMAP.md#L36) | ❌ Shared filter sheet and Save to Home wiring follow Android; same neutral filter and counting contract; **deliberately deferred: maintainer-authorised Android-first 0.12 build; firmware implementation follows**. [ROADMAP.md:36](../ROADMAP.md#L36) | ❌ Shared filter sheet and Save to Home wiring follow Android; same neutral filter and counting contract; **deliberately deferred: maintainer-authorised Android-first 0.12 build; firmware implementation follows**. [ROADMAP.md:36](../ROADMAP.md#L36) | -| Default BookSync Home with three pages, starter shelves, Library and Stats | 🟡 Implemented on feature/0.12: default Home, Library and Stats pages for installs and upgrades; preserves saved layouts and sync settings, shows upgrade news once, and offers sign-in from empty first-run shelves; retains design-review Settings/Battery destinations, page titles/Back and minimum touch targets; **deliberately deferred: device acceptance, battery history, cached covers and richer book actions follow the staged Android build**. [android/koreader/orbit.koplugin/ko/home_host.lua:1](../android/koreader/orbit.koplugin/ko/home_host.lua#L1) | ❌ Default Home cutover, upgrade news, three-page wiring and filtered lists follow the Android build; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows later**. [docs/design/booksync-home/F12-J-NOTES.md:3](../docs/design/booksync-home/F12-J-NOTES.md#L3) | ❌ Default Home cutover, upgrade news, three-page wiring and filtered lists follow the Android build; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows later**. [docs/design/booksync-home/F12-J-NOTES.md:3](../docs/design/booksync-home/F12-J-NOTES.md#L3) | ❌ Default Home cutover, upgrade news, three-page wiring and filtered lists follow the Android build; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows later**. [docs/design/booksync-home/F12-J-NOTES.md:3](../docs/design/booksync-home/F12-J-NOTES.md#L3) | +| Default BookSync Home with two M8C pages, starter shelves and Stats | 🟡 Implemented on feature/0.12: approved §4 Home and Stats defaults for M8C installs and upgrades; preserves saved layouts and sync settings, shows upgrade news once, and offers sign-in from empty first-run shelves; retains design-review Settings/Battery destinations, page titles/Back and minimum touch targets; local windows, stats and custom covers also work without a server owner; **deliberately deferred: device acceptance, battery history, cached covers and richer book actions follow the staged Android build**. [android/koreader/orbit.koplugin/ko/home_host.lua:1](../android/koreader/orbit.koplugin/ko/home_host.lua#L1) | ❌ Default Home cutover, upgrade news, device-specific default pages and filtered lists follow the Android build; device-local ownership follows in the firmware slice; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows later**. [docs/design/booksync-home/F12-J-NOTES.md:3](../docs/design/booksync-home/F12-J-NOTES.md#L3) | ❌ Default Home cutover, upgrade news, device-specific default pages and filtered lists follow the Android build; device-local ownership follows in the firmware slice; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows later**. [docs/design/booksync-home/F12-J-NOTES.md:3](../docs/design/booksync-home/F12-J-NOTES.md#L3) | ❌ Default Home cutover, upgrade news, device-specific default pages and filtered lists follow the Android build; device-local ownership follows in the firmware slice; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows later**. [docs/design/booksync-home/F12-J-NOTES.md:3](../docs/design/booksync-home/F12-J-NOTES.md#L3) | | Owned Series page and grouped Library/Search progress | 🟡 Implemented on feature/0.12: ordered primary/secondary Series members, read/reading/device status, progress dots, next-book preview, grouped Library and Search cover rows, and Back to the originating filters/page; **deliberately deferred: bulk next-series download jobs, cached covers and device acceptance remain with the staged Android owners**. [android/koreader/orbit.koplugin/ko/series.lua:1](../android/koreader/orbit.koplugin/ko/series.lua#L1), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SeriesPresentation.kt:1](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SeriesPresentation.kt#L1) | ❌ Owned Series and grouped progress presentation follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware comes later**. [docs/design/booksync-home/DESIGN-NOTES.md:1](../docs/design/booksync-home/DESIGN-NOTES.md#L1) | ❌ Owned Series and grouped progress presentation follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware comes later**. [docs/design/booksync-home/DESIGN-NOTES.md:1](../docs/design/booksync-home/DESIGN-NOTES.md#L1) | ❌ Owned Series and grouped progress presentation follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware comes later**. [docs/design/booksync-home/DESIGN-NOTES.md:1](../docs/design/booksync-home/DESIGN-NOTES.md#L1) | | Owned reader top panel, Book info and Details progress (0.12 implementation) | 🟡 Plain progress bar, cached reading stats, measured usual-use battery line and manual Sync in the top panel; battery line links to the owned Battery page and uses its companion-formatted label; shared Settings action; header action icons, separate bottom scrubber with bounded chapter/bookmark ticks, native Contents/annotations/Go to/search/bookmark dispatch and two-column quick settings with merged Custom editors; **deliberately deferred: 0.12 Android implementation is building, not released or device validated; battery estimates need measured rates and 24 h of observed use, while reading stats require saved KOReader records plus the tracked-file ledger.**. [android/koreader/orbit.koplugin/ko/reader_panel.lua:1](../android/koreader/orbit.koplugin/ko/reader_panel.lua#L1), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ReaderBookStats.kt:1](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ReaderBookStats.kt#L1), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BatteryEstimate.kt:10](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BatteryEstimate.kt#L10) | ❌ Owned reader top/bottom panels, native action controls and progress follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; this slice does not change firmware. Implement on this reader in the later Xteink slice. The companion-backed battery model is Android-only in this increment.; this design review changes Android only under the same ruling; reader-panel parity remains deferred to that platform’s firmware slice under Android-first authorization**. [ROADMAP.md:36](../ROADMAP.md#L36), [docs/design/booksync-home/F12-E-NOTES.md:3](../docs/design/booksync-home/F12-E-NOTES.md#L3) | ❌ Owned reader top/bottom panels, native action controls and progress follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; this slice does not change firmware. Implement on this reader in the later Xteink slice. The companion-backed battery model is Android-only in this increment.; this design review changes Android only under the same ruling; reader-panel parity remains deferred to that platform’s firmware slice under Android-first authorization**. [ROADMAP.md:36](../ROADMAP.md#L36), [docs/design/booksync-home/F12-E-NOTES.md:3](../docs/design/booksync-home/F12-E-NOTES.md#L3) | ❌ Owned reader top/bottom panels, native action controls and progress follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; this slice does not change firmware. X3 also requires measured flash fit. The companion-backed battery model is Android-only in this increment.; this design review changes Android only under the same ruling; reader-panel parity remains deferred to that platform’s firmware slice under Android-first authorization**. [ROADMAP.md:36](../ROADMAP.md#L36), [docs/design/booksync-home/F12-E-NOTES.md:3](../docs/design/booksync-home/F12-E-NOTES.md#L3) | | On-device Home widget and page editor (0.12; unreleased) | 🟡 Opt-in BookSync Home: add/remove, arrow move, allowed-size resize, page names/order, reset and atomic save; **deliberately deferred: device visual/performance acceptance; Android implementation is unreleased**. [android/koreader/orbit.koplugin/ko/home_editor.lua:1](../android/koreader/orbit.koplugin/ko/home_editor.lua#L1) | ❌ Firmware editor follows; **deliberately deferred: maintainer-authorised Android-first 0.12 build; Xteink implementation follows**. [ROADMAP.md:20](../ROADMAP.md#L20) | ❌ Firmware editor follows; **deliberately deferred: maintainer-authorised Android-first 0.12 build; Xteink implementation follows**. [ROADMAP.md:20](../ROADMAP.md#L20) | ❌ Firmware editor follows; **deliberately deferred: maintainer-authorised Android-first 0.12 build; Xteink implementation follows**. [ROADMAP.md:20](../ROADMAP.md#L20) | -| Independent account, sync and OPDS logins (0.12 Android screens) | 🟡 Owned plugin forms, independent encrypted logins, provenance-aware sign-out, provisioning result and sync setup actions; **deliberately deferred: browser/OIDC sign-in, firmware phone pairing and real-device acceptance follow; Android-first implementation authorised 2026-11-25.**. [docs/design/bookorbit-account.md:1](../docs/design/bookorbit-account.md#L1), [android/koreader/orbit.koplugin/ko/account.lua:4](../android/koreader/orbit.koplugin/ko/account.lua#L4) | ❌ Account login and token storage follow Android; **deliberately deferred: maintainer authorised Android-first account screens on 2026-11-25; firmware account adapter, credential storage and phone pairing follow.**. [docs/design/bookorbit-account.md:1](../docs/design/bookorbit-account.md#L1) | ❌ Account login and token storage follow Android; **deliberately deferred: maintainer authorised Android-first account screens on 2026-11-25; firmware account adapter, credential storage and phone pairing follow.**. [docs/design/bookorbit-account.md:1](../docs/design/bookorbit-account.md#L1) | ❌ Account login and token storage follow Android; **deliberately deferred: maintainer authorised Android-first account screens on 2026-11-25; firmware account adapter, credential storage and phone pairing follow.**. [docs/design/bookorbit-account.md:1](../docs/design/bookorbit-account.md#L1) | +| Independent account, sync and OPDS logins (0.12 Android screens) | 🟡 Owned plugin forms, independent encrypted logins, provenance-aware sign-out, provisioning result and sync setup actions; upgrades atomically adopt existing independent logins in the encrypted vault without changing credentials or catalog identity; **deliberately deferred: browser/OIDC sign-in, firmware phone pairing and real-device acceptance follow; Android-first implementation authorised 2026-11-25.**. [docs/design/bookorbit-account.md:1](../docs/design/bookorbit-account.md#L1), [android/koreader/orbit.koplugin/ko/account.lua:4](../android/koreader/orbit.koplugin/ko/account.lua#L4) | ❌ Account login and token storage follow Android; legacy-login adoption follows with the firmware account model; **deliberately deferred: maintainer authorised Android-first account screens on 2026-11-25; firmware account adapter, credential storage and phone pairing follow.**. [docs/design/bookorbit-account.md:1](../docs/design/bookorbit-account.md#L1) | ❌ Account login and token storage follow Android; legacy-login adoption follows with the firmware account model; **deliberately deferred: maintainer authorised Android-first account screens on 2026-11-25; firmware account adapter, credential storage and phone pairing follow.**. [docs/design/bookorbit-account.md:1](../docs/design/bookorbit-account.md#L1) | ❌ Account login and token storage follow Android; legacy-login adoption follows with the firmware account model; **deliberately deferred: maintainer authorised Android-first account screens on 2026-11-25; firmware account adapter, credential storage and phone pairing follow.**. [docs/design/bookorbit-account.md:1](../docs/design/bookorbit-account.md#L1) | | Clear, editable Custom reading styles and apply-then-edit quick choices | 🟡 Font and weight, device-local margins, line spacing and contrast; editors, native-style copy with Undo, and clear sync labels. Device acceptance pending.; **deliberately deferred: unreleased Android implementation awaits device visual and performance acceptance; firmware follows separately**. [android/koreader/orbit.koplugin/ko/custom_reading.lua:1](../android/koreader/orbit.koplugin/ko/custom_reading.lua#L1), [android/koreader/test/reader_panel_flows.lua:170](../android/koreader/test/reader_panel_flows.lua#L170) | ❌ Custom style editors await the firmware slice; KOReader copy does not apply.; **deliberately deferred: maintainer authorized Android first on 2026-11-25; firmware follows with device-specific margin ranges.**. [docs/design/booksync-home/DESIGN-NOTES.md:715](../docs/design/booksync-home/DESIGN-NOTES.md#L715) | ❌ Custom style editors await the firmware slice; KOReader copy does not apply.; **deliberately deferred: maintainer authorized Android first on 2026-11-25; firmware follows with device-specific margin ranges.**. [docs/design/booksync-home/DESIGN-NOTES.md:715](../docs/design/booksync-home/DESIGN-NOTES.md#L715) | ❌ Custom style editors await the firmware slice; KOReader copy does not apply.; **deliberately deferred: maintainer authorized Android first on 2026-11-25; firmware follows with device-specific margin ranges.**. [docs/design/booksync-home/DESIGN-NOTES.md:715](../docs/design/booksync-home/DESIGN-NOTES.md#L715) | | BookSync Home battery widget and snapshot Battery page | 🟡 Six widget sizes, Overview/Rates/Daily/Charges and Settings link; **deliberately deferred: 0.12 Android source implementation is building, unreleased and awaiting device validation. Grouped rates, page/refresh efficiency and export/compare actions remain later work; missing evidence is labelled explicitly.**. [docs/design/booksync-home/F12-O-NOTES.md:1](../docs/design/booksync-home/F12-O-NOTES.md#L1) | ❌ Owned battery widget and page follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; implement the snapshot widget and page in the later Xteink slice.**. [docs/design/booksync-home/F12-O-NOTES.md:1](../docs/design/booksync-home/F12-O-NOTES.md#L1) | ❌ Owned battery widget and page follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; implement the snapshot widget and page in the later Xteink slice.**. [docs/design/booksync-home/F12-O-NOTES.md:1](../docs/design/booksync-home/F12-O-NOTES.md#L1) | ❌ Owned battery widget and page follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; implement the snapshot widget and page in the later Xteink slice. X3 also requires measured flash fit.**. [docs/design/booksync-home/F12-O-NOTES.md:1](../docs/design/booksync-home/F12-O-NOTES.md#L1) | | Home editor Book list configuration (0.12 foundation; unreleased) | 🟡 One Book list renderer with friendly presets, settings, paged counted sources and local Custom filters; **deliberately deferred: real-device acceptance and release follow the Android 0.12 foundation**. [android/koreader/orbit.koplugin/ko/booklist_config.lua:3](../android/koreader/orbit.koplugin/ko/booklist_config.lua#L3) | ❌ Book list settings and sources follow Android; shared cfg and focus logic are ready for firmware integration; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware implementation follows**. [docs/design/booksync-home/DESIGN-NOTES.md:809](../docs/design/booksync-home/DESIGN-NOTES.md#L809) | ❌ Book list settings and sources follow Android; shared cfg and focus logic are ready for firmware integration; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware implementation follows**. [docs/design/booksync-home/DESIGN-NOTES.md:809](../docs/design/booksync-home/DESIGN-NOTES.md#L809) | ❌ Book list settings and sources follow Android; shared cfg and focus logic are ready for firmware integration; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware implementation follows**. [docs/design/booksync-home/DESIGN-NOTES.md:809](../docs/design/booksync-home/DESIGN-NOTES.md#L809) | diff --git a/docs/design/booksync-home/DESIGN-NOTES.md b/docs/design/booksync-home/DESIGN-NOTES.md index 88399abc..716d3767 100644 --- a/docs/design/booksync-home/DESIGN-NOTES.md +++ b/docs/design/booksync-home/DESIGN-NOTES.md @@ -750,8 +750,8 @@ the M8C Font Custom segment shows its value ("Baskerville +1"); contrast values Owned Home is the Android 0.12 default on both fresh installs and upgrades. The legacy Home selector is retired from the shared settings schema and Settings; old internal navigation remains only for compatibility while transport moves. -The existing `logic/layout.lua:181` defaults provide Home, Library and Stats, -including Also reading, Recently added, Want to read, On device and Finished. +The existing `logic/layout.lua:181` defaults follow §4: Home and Stats on the M8C, including Also reading, Recently +added and Want to read. On device and Finished remain Book list presets. A saved layout (including class overrides) remains authoritative; this cutover never resets it or copies catalogs, logins, outbox or reading intents. @@ -789,11 +789,6 @@ handles both Back and outside taps; Done acknowledges explicitly before closing. The regression double follows that native path rather than InfoMessage's separate `dismiss_callback`. The compatibility guard now requires the native callback field. -Pass 3 integration ruling: the first-run task explicitly requires three Android -default pages. Keep Home, Library and Stats and the existing starter shelves, -while retaining pass 4's navigation and touch fixes. This explicit task requirement -supersedes pass 4's two-page default adjustment; saved layouts remain untouched. - The upgrade sheet's Done action declares a 50 px content height, in addition to native padding/borders. Pinned KOReader `9192014d8bd82a91dc1012473be0f238dedfdb54` `frontend/ui/widget/buttontable.lua:88` forwards an explicit height; without it, @@ -1024,3 +1019,31 @@ keeps a declared budget inherited by Library: six sleep choices and 16 KiB per page, zero render network/subprocesses; device settings are a lifecycle-cached row. Counts and choice decoding stay in the companion; paints/calls log info timing spans. Device latency and Android power-policy acceptance remain pending. + +### Pass 3 follow-ups (Android, 2026-11-26) + +The M8C uses §4's two default pages, Home and Stats, with the exact approved +placements; the X4's three-page default remains a later firmware slice. Existing +saved layouts remain authoritative, including any saved Library page. + +Existing device-entered logins are imported as `user` (§21–§22): they predate +account sign-in, remain independent, and survive account sign-out. This differs +from a connector found on the server during an explicit account sign-in, which +has account provenance. `ServerAdapters.kt:29` composes the worker-only import; +`server/bookorbit/ServerCredentials.kt:16` checkpoints both logins and the marker +in the existing encrypted vault, preserving newer logins and the legacy catalog +identity. A crash before or after that atomic save is safe to retry. No source +credential file or legacy position/lifecycle queue is changed. Native OPDS source: +pinned KOReader `9192014d8bd82a91dc1012473be0f238dedfdb54`, +`plugins/opds.koplugin/main.lua:15`, `:63` and `opdsbrowser.lua:248`. Existing +sync source: pinned BookOrbit `c1dd6b4f1947ff50843a155e12e70f1e7d15f0c7`, +`koreader-plugin/bookorbit.koplugin/main.lua:145`, `:155` and `:264`. + +Signed-out projections use the reserved device owner without claiming or reading +a previous account's catalog. Reuse `LibraryReadModel.kt:30` for materialization, +`ReadingStats.kt:24` and `LibraryFilter.kt:30` for local stats and filtering, and +`DeviceStorage.kt:19` for local folder choices. Native metadata and custom covers +are read only by the companion; the plugin receives bounded windows. All existing +caller budgets and info timing spans apply: zero network/subprocess work while +painting, at most one batch per Home paint, at most 24 display rows and 16 KiB per +widget. Host test timings do not establish device performance acceptance. diff --git a/docs/design/booksync-home/F12-J-NOTES.md b/docs/design/booksync-home/F12-J-NOTES.md index 87b0c64b..3b03f3a2 100644 --- a/docs/design/booksync-home/F12-J-NOTES.md +++ b/docs/design/booksync-home/F12-J-NOTES.md @@ -4,8 +4,8 @@ Android implementation authorised 2026-11-25; X4 Pro, X4 and X3 follow later by explicit maintainer ruling. The approved design sources were read with `git show origin/design/booksync-home:docs/design/booksync-home/`: DESIGN.md §3.5, §6 and §8.5, DESIGN-NOTES.md revision 10, layout.schema.json and prototype.html. -Rev 10 still has two M8C pages. This task explicitly requests three: Home, -Library (Library 2×2, On device, Finished), then Stats. The four-column M8C +The approved §4 M8C default has two pages, Home and Stats. Library, On device +and Finished remain available as widgets and Book list presets. The four-column M8C Stats layout retains the approved Year 4×3, Battery, weekly/hourly and Records placements. Defaults change only for readers without a saved valid layout. @@ -77,7 +77,7 @@ Info spans cover library calls, host paints and each widget's drawing. Targets remain unconfirmed: Home <500 ms, widget <50 ms, cached window <30 ms, editor <100 ms; host tests establish deterministic limits, not device performance. -Flow tests draw all three pages with real stats renderers, verify one stats read +Flow tests draw the default pages with real stats renderers, verify one stats read and one batch per paint, drive list Filter → Show picker → Unread → Save → Go to Home → reopen, and drive Search with its filter button. Pure placement tests exercise new-page naming without changing the prior document. Device acceptance, cached covers and richer details/actions remain later work. diff --git a/shared/features.json b/shared/features.json index a7116e7a..ef6efbe7 100644 --- a/shared/features.json +++ b/shared/features.json @@ -5380,12 +5380,12 @@ }, { "id": "owned-home", - "feature": "Default BookSync Home with three pages, starter shelves, Library and Stats", + "feature": "Default BookSync Home with two M8C pages, starter shelves and Stats", "category": "Behaviour", "platforms": { "android": { "status": "partial", - "note": "Implemented on feature/0.12: default Home, Library and Stats pages for installs and upgrades; preserves saved layouts and sync settings, shows upgrade news once, and offers sign-in from empty first-run shelves; retains design-review Settings/Battery destinations, page titles/Back and minimum touch targets", + "note": "Implemented on feature/0.12: approved §4 Home and Stats defaults for M8C installs and upgrades; preserves saved layouts and sync settings, shows upgrade news once, and offers sign-in from empty first-run shelves; retains design-review Settings/Battery destinations, page titles/Back and minimum touch targets; local windows, stats and custom covers also work without a server owner", "reason": "deliberately deferred: device acceptance, battery history, cached covers and richer book actions follow the staged Android build", "evidence": [ { @@ -5397,7 +5397,7 @@ }, "x4_pro": { "status": "missing", - "note": "Default Home cutover, upgrade news, three-page wiring and filtered lists follow the Android build", + "note": "Default Home cutover, upgrade news, device-specific default pages and filtered lists follow the Android build; device-local ownership follows in the firmware slice", "reason": "deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows later", "evidence": [ { @@ -5408,7 +5408,7 @@ }, "x4": { "status": "missing", - "note": "Default Home cutover, upgrade news, three-page wiring and filtered lists follow the Android build", + "note": "Default Home cutover, upgrade news, device-specific default pages and filtered lists follow the Android build; device-local ownership follows in the firmware slice", "reason": "deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows later", "evidence": [ { @@ -5419,7 +5419,7 @@ }, "x3": { "status": "missing", - "note": "Default Home cutover, upgrade news, three-page wiring and filtered lists follow the Android build", + "note": "Default Home cutover, upgrade news, device-specific default pages and filtered lists follow the Android build; device-local ownership follows in the firmware slice", "reason": "deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware follows later", "evidence": [ { @@ -5616,7 +5616,7 @@ "platforms": { "android": { "status": "partial", - "note": "Owned plugin forms, independent encrypted logins, provenance-aware sign-out, provisioning result and sync setup actions", + "note": "Owned plugin forms, independent encrypted logins, provenance-aware sign-out, provisioning result and sync setup actions; upgrades atomically adopt existing independent logins in the encrypted vault without changing credentials or catalog identity", "reason": "deliberately deferred: browser/OIDC sign-in, firmware phone pairing and real-device acceptance follow; Android-first implementation authorised 2026-11-25.", "evidence": [ { @@ -5633,7 +5633,7 @@ }, "x4_pro": { "status": "missing", - "note": "Account login and token storage follow Android", + "note": "Account login and token storage follow Android; legacy-login adoption follows with the firmware account model", "reason": "deliberately deferred: maintainer authorised Android-first account screens on 2026-11-25; firmware account adapter, credential storage and phone pairing follow.", "evidence": [ { @@ -5646,7 +5646,7 @@ }, "x4": { "status": "missing", - "note": "Account login and token storage follow Android", + "note": "Account login and token storage follow Android; legacy-login adoption follows with the firmware account model", "reason": "deliberately deferred: maintainer authorised Android-first account screens on 2026-11-25; firmware account adapter, credential storage and phone pairing follow.", "evidence": [ { @@ -5659,7 +5659,7 @@ }, "x3": { "status": "missing", - "note": "Account login and token storage follow Android", + "note": "Account login and token storage follow Android; legacy-login adoption follows with the firmware account model", "reason": "deliberately deferred: maintainer authorised Android-first account screens on 2026-11-25; firmware account adapter, credential storage and phone pairing follow.", "evidence": [ {