diff --git a/AGENTS.md b/AGENTS.md index 219692c5..77ab5da4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -123,6 +123,8 @@ construct a full bookmark index on a panel paint. Native actions stay behind Lib Cover lookups use a one-row, 16 KiB local-only budget with zero round-trips; post-paint cover batches are limited to four and only the companion fetches or writes images. +Copy replacement and finish outboxes are companion-owned, account scoped and checkpointed before legacy sources retire. Grouped lists and end-of-book cards are bounded projections; local recommendation review has eight rows. No catalog transport or whole-list aggregation runs in Lua. Keep queue checkpoints available while reading; pause background transfer work, never persistence of reader intent. + Catalog progress is one companion-published row (16 KiB) with zero polling round-trips. Catalog/root windows decode at most 24 display rows; native Home batches count every nested book/name plus their stats row. Plans, query interpretation, refresh policy and search stay diff --git a/ROADMAP.md b/ROADMAP.md index afb8314a..75ad0e91 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -16,6 +16,7 @@ CrossInk 2.x only; 1.6 is retired). ## Next release (0.12): BookSync Home | Outcome | Platforms | Status | +| Finish the server-free catalog cutover: companion-owned copies, grouping, settings recommendations and end-of-book snapshots/outboxes. | Android (Xteink deferred under Android-first ruling) | building on feature/0.12 (F12-Q2 step 4) | |---|---|---| | Word of the day, local Reading buddy and hardware Light picker widgets; Highlight and A year ago await authorized server snapshots. | Android; X4 Pro/X4/X3 deferred to firmware | building (device acceptance pending) | | 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 | diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CommandProvider.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CommandProvider.kt index c9e99212..63f25301 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CommandProvider.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CommandProvider.kt @@ -42,7 +42,7 @@ class CommandProvider : ContentProvider() { val COMMANDS = setOf( Contract.NET_UP, Contract.NET_DONE, Contract.WIFI_OFF, Contract.SLEEP_NOW, Contract.SETTINGS, Contract.STATS, Contract.RELAUNCH, Contract.SETUP_LATER, Contract.REPORT, SleepScreen.ACTION_POOL, - Worker.ACTION_STORAGE, Worker.ACTION_COPIES, Worker.ACTION_SLEEP_REFRESH, + Worker.ACTION_STORAGE, Worker.ACTION_SLEEP_REFRESH, Worker.ACTION_SQLITE_STRESS, Worker.ACTION_PATCH, Updater.ACTION_UPDATE, ) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt index 9921e118..f071b06f 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt @@ -101,6 +101,36 @@ object LibraryAccount { var result: Map? = null command(ctx, { result = it.catalog(page,limit) }, { done(result,it) }, invalidate = false) } + fun recommendedSettings(ctx:Context,args:Map<*,*>,done:(Map?,String?)->Unit) { + val app=ctx.applicationContext + queue.execute { + val start=System.nanoTime() + val result=runCatching { + val definitions=adapter(app).recommendedSettings() + if(args["definitions"]==true) mapOf("items" to definitions) else { + val result=RecommendationPlan.evaluate(definitions,args) + val destination=java.io.File(android.os.Environment.getExternalStorageDirectory(),"koreader/settings/orbit-recommended.json") + destination.parentFile?.mkdirs() + val tmp=java.io.File(destination.path+".new") + val rows=(result["items"] as? List<*>).orEmpty().map { raw -> + val row=raw as Map<*,*>;row.filterKeys { it in setOf("id","label","state","yours","orbit","was","reason") } + } + tmp.writeText(org.json.JSONObject(mapOf("v" to 1,"at" to System.currentTimeMillis(),"items" to rows)).toString()) + check(tmp.renameTo(destination));result + } + } + OLog.i("library.recommendations ms=${(System.nanoTime()-start)/1_000_000}") + main.post { result.fold({done(it,null)},{done(null,"unavailable")}) } + } + } + fun catalogAction(ctx: Context, owner: String, action: String, args: Map<*,*>, done: (Map?,String?) -> Unit) { + val app=ctx.applicationContext + queue.execute { + try { adapter(app).catalogAction(owner,action,args) { value,error -> main.post { done(value,error) } } } + catch(e: ServerFailure) { main.post { done(null,e.kind) } } + catch(_: Exception) { main.post { done(null,"unavailable") } } + } + } fun catalogControl(ctx: Context, owner: String, action: String, manual: Boolean, done: (Map?,String?) -> Unit) { val app=ctx.applicationContext queue.execute { diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/OrbitService.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/OrbitService.kt index 6c981a48..292fed8f 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/OrbitService.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/OrbitService.kt @@ -52,7 +52,7 @@ object Commands { return SleepScreen.onPool(ctx, intent.getStringExtra("reason") ?: "plugin") } // The cache worker's jobs (docs/design/companion-worker.md): every mode, no service needed. - if (intent.action == Worker.ACTION_STORAGE || intent.action == Worker.ACTION_COPIES || intent.action == Worker.ACTION_SLEEP_REFRESH || intent.action == Worker.ACTION_SQLITE_STRESS || intent.action == Worker.ACTION_PATCH) return Worker.onIntent(ctx, intent) + if (intent.action == Worker.ACTION_STORAGE || intent.action == Worker.ACTION_SLEEP_REFRESH || intent.action == Worker.ACTION_SQLITE_STRESS || intent.action == Worker.ACTION_PATCH) return Worker.onIntent(ctx, intent) // The plugin's "Check for updates": every mode (the plugin downloads nothing itself). if (intent.action == Updater.ACTION_UPDATE) return Updater.onPluginAsked(ctx.applicationContext, intent.getStringExtra("reason") ?: "plugin") val action = intent.action ?: return diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/RecommendationPlan.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/RecommendationPlan.kt new file mode 100644 index 00000000..31f73c7f --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/RecommendationPlan.kt @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion + +/** Eight local settings, never a catalog. The connector supplies its native binding descriptors; + * observations and compare-before-write acknowledgements stay behind Library on the reader. */ +object RecommendationPlan { + fun evaluate(definitions:List>,args:Map<*,*>):Map { + require(definitions.size<=8) + val record=(args["record"] as? Map<*,*>).orEmpty() + val prior=(record["items"] as? Map<*,*>).orEmpty().toMutableMap() + val backup=(args["backup"] as? Map<*,*>).orEmpty().toMutableMap() + val observed=(args["observations"] as? Map<*,*>).orEmpty() + val choices=(args["choices"] as? Map<*,*>).orEmpty() + val failed=(args["failed"] as? List<*>).orEmpty() + val writes=mutableListOf>() + val rows=definitions.map { item -> + val id=item["id"] as String + val obs=(observed[id] as? Map<*,*>).orEmpty() + val current=obs["current"];val ours=item["ours"] + val status=prior[id] + var next=status + val choice=choices[id] ?: choices["all"].takeUnless { it=="ours" && status=="kept" || it=="undo" && item["required_by"]=="wifi" && args["wifi"]==true } + val available=obs["available"]==true + fun apply() { + backup[id]=mapOf("had" to obs.containsKey("current"),"prior" to current,"ours" to ours) + writes.add(mapOf("id" to id,"expected" to current,"value" to ours));next="applied" + } + if(choice=="mine" && status=="conflict") next="kept" + else if(choice=="undo" && status=="applied" || args["lost"]==true && !available && status=="applied") { + val saved=backup[id] as? Map<*,*> + if(saved!=null && current==saved["ours"]) writes.add(mapOf("id" to id,"expected" to current,"value" to saved["prior"])) + backup.remove(id);next=if(args["lost"]==true) "unavailable" else "kept" + } else if(available && choice=="ours" && status in setOf("kept","conflict")) apply() + else if(args["ack"]!=true && (status==null || status=="unavailable")) { + next=when { + !available -> "unavailable" + current==ours -> if(backup[id]!=null) "applied" else "already" + current==obs["default"] || item["stock"]!=null && current==item["stock"] -> "applied" + else -> "conflict" + } + if(next=="applied" && current!=ours) apply() + } + if(id in failed) next="unavailable" + prior[id]=next + item+mapOf("state" to next,"section" to when(next) { "conflict" -> "To review";"applied","already" -> "Applied";"kept" -> "Kept yours";else -> "Unavailable" }, + "needs_wifi" to (item["required_by"]=="wifi" && args["wifi"]==true),"yours" to label(item,current),"orbit" to label(item,ours), + "was" to label(item,(backup[id] as? Map<*,*>)?.get("prior")),"reason" to obs["reason"]) + } + val conflicts=prior.values.count { it=="conflict" } + val applied=writes.count { w -> prior[w["id"]]=="applied" } + val unseen=((record["unseen"] as? Number)?.toInt().orZero()+applied-(if(args["ack"]==true) failed.toSet().size else 0)).coerceAtLeast(0) + val line=when { unseen>0 && conflicts>0 -> "Applied $unseen · $conflicts to review"; unseen>0 -> "Applied $unseen recommended settings · Review"; conflicts>0 -> "Review $conflicts recommended settings";else -> null } + val ordered=rows.sortedBy { when(it["state"]) { "conflict" -> 0;"applied" -> 1;"already" -> 2;"kept" -> 3;else -> 4 } } + val result=mapOf("items" to ordered,"use_all" to (conflicts>0),"undo_all" to prior.values.any { it=="applied" },"writes" to writes,"record" to mapOf("rev" to 1,"items" to prior,"unseen" to unseen),"backup" to backup, + "conflicts" to conflicts,"seen_line" to (if(conflicts>0) LuaValue.str("Review $conflicts recommended settings") else null),"line" to line?.let(LuaValue::str),"report" to if(conflicts>0) "partial" else if("kept" in prior.values) "reviewed" else "applied") + require(LuaValue.encode(result).size<=16384);return result + } + private fun Int?.orZero()=this ?: 0 + private fun label(item:Map,v:Any?):String { + val labels=(item["value_labels"] as? Map<*,*>).orEmpty() + return when(v) { + null -> "Unset" + true -> "On" + false -> "Off" + is Map<*,*> -> if(v.isEmpty()) "Nothing" else v.keys.map { labels[it] as? String ?: "Custom action" }.sorted().joinToString(" + ") + else -> labels[v.toString()] as? String ?: v.toString() + }.take(200) + } +} diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerAdapter.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerAdapter.kt index 4d24d40a..7c4e0a74 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerAdapter.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerAdapter.kt @@ -6,6 +6,7 @@ import java.io.File * normalize protocol data before returning it; unsupported operations are explicit. Renderers * use LibraryReadModel, never this transport-facing interface. */ interface ServerAdapter { + fun recommendedSettings(): List> = emptyList() val id: String fun project(owner: String, request: Map<*, *>): Map = unsupported() fun capabilities(owner: String) = project(owner, mapOf("op" to "capabilities")) @@ -17,6 +18,7 @@ interface ServerAdapter { fun lists(owner: String, limit: Int, offset: Int = 0) = project(owner, mapOf("op" to "lists", "limit" to limit, "offset" to offset)) fun sources(owner: String, category: String, limit: Int = 6, offset: Int = 0) = project(owner, mapOf("op" to "sources", "category" to category, "limit" to limit, "offset" to offset)) + fun catalogAction(owner: String, action: String, args: Map<*,*>, done: (Map?,String?) -> Unit) = done(null,"unsupported") fun catalogControl(owner: String, action: String, manual: Boolean, done: (Map?,String?) -> Unit) = done(null,"unsupported") fun manifest(owner: String): Map = unsupported() fun cover(owner: String, key: String): Map = unsupported() 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 36b32874..c963460a 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 @@ -35,6 +35,7 @@ object ServerAdapters { return BookOrbitServerAdapter(credentials, account, ConnectorHttp, legacyAccount = { net.fledgewing.orbitcompanion.server.bookorbit.LegacyCoverSource.read( java.io.File(android.os.Environment.getExternalStorageDirectory(),"koreader/settings.reader.lua")) }, + actionJob = { creds,owner,action,args,done -> AdapterWorker.catalogAction(ctx,creds,owner,action,args,done) }, catalogJob = { creds,owner,action,manual,done -> AdapterWorker.catalogControl(ctx,creds,owner,action,manual,done) }, coverReferenceJob = { creds, owner, reference, refresh, done -> AdapterWorker.acquireCoverReference(ctx,creds,owner,reference,refresh,done) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerCommands.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerCommands.kt index a680fe21..24b624d7 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerCommands.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerCommands.kt @@ -10,7 +10,7 @@ object ServerCommands { private class Pending(val at: Long, var body: Map? = null) private val jobs = linkedMapOf() @Synchronized fun start(ctx: Context, op: String, args: Map<*, *>): String { - require(op in setOf("device.sleep","storage.free","storage.folder","sync.verify.next","sync.verify.result","sync.activate","sync.capture","sync.pull","sync.decide","sync.answer","sync.override","sync.drain","sync.read","sync.write","catalog.window","catalog.control","covers.acquire","downloads.start","account.signIn","account.signOut","login.save","login.remove","login.replace")) + require(op in setOf("device.sleep","storage.free","storage.folder","sync.verify.next","sync.verify.result","sync.activate","sync.capture","sync.pull","sync.decide","sync.answer","sync.override","sync.drain","sync.read","sync.write","catalog.window","catalog.control","catalog.action","settings.recommendations","covers.acquire","downloads.start","account.signIn","account.signOut","login.save","login.remove","login.replace")) val now = System.currentTimeMillis() jobs.entries.removeAll { now - it.value.at > 120000 } require(jobs.size < 32) @@ -38,6 +38,8 @@ object ServerCommands { LibraryAccount.position(ctx,document,update,::finish) } "catalog.window" -> LibraryAccount.catalog(ctx,(args["page"] as? Number)?.toInt() ?: 1,(args["limit"] as? Number)?.toInt()?.coerceIn(1,24) ?: 24,::finish) + "settings.recommendations" -> LibraryAccount.recommendedSettings(ctx,args,::finish) + "catalog.action" -> LibraryAccount.catalogAction(ctx,args["owner"] as? String ?: throw IllegalArgumentException("owner"),text("action"),args,::finish) "catalog.control" -> LibraryAccount.catalogControl(ctx,args["owner"] as? String ?: throw IllegalArgumentException("owner"),text("action"),args["manual"]==true,::finish) "covers.acquire" -> if (args["reference"] != null) LibraryAccount.acquireCoverReference(ctx,text("reference"),args["refresh"]==true,args["owner"] as? String ?: throw IllegalArgumentException("owner"),::finish) 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 fb18ff2e..ebcc05db 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 @@ -18,7 +18,6 @@ interface ServerRuntime { /** Command routing only. The selected adapter owns transport and all legacy protocol state. */ object Worker { const val ACTION_STORAGE = "${Contract.PACKAGE}.action.STORAGE" - const val ACTION_COPIES = "${Contract.PACKAGE}.action.COPIES" const val ACTION_SLEEP_REFRESH = "${Contract.PACKAGE}.action.SLEEP_REFRESH" const val ACTION_SQLITE_STRESS = "${Contract.PACKAGE}.action.SQLITE_STRESS" const val ACTION_PATCH = "${Contract.PACKAGE}.action.PATCH" diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/AdapterWorker.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/AdapterWorker.kt index 60bb0eeb..7a6defd9 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/AdapterWorker.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/AdapterWorker.kt @@ -17,7 +17,6 @@ import java.net.URL */ object AdapterWorker : ServerRuntime { const val ACTION_STORAGE = "${Contract.PACKAGE}.action.STORAGE" - const val ACTION_COPIES = "${Contract.PACKAGE}.action.COPIES" const val ACTION_SLEEP_REFRESH = "${Contract.PACKAGE}.action.SLEEP_REFRESH" /** The shared-storage stress test's writer (docs/design/sqlite-cache.md "Stress test"); no login. */ const val ACTION_SQLITE_STRESS = "${Contract.PACKAGE}.action.SQLITE_STRESS" @@ -45,7 +44,7 @@ object AdapterWorker : ServerRuntime { private set /** Work in hand: an automatic Wi-Fi off waits for it. */ - override fun busy(): Boolean = mirrorRunning || synchronized(lock) { patches.isNotEmpty() || pending != null || storage != null || sleep != null || pickers != null } + override fun busy(): Boolean = mirrorRunning || catalogActionRunning || synchronized(lock) { patches.isNotEmpty() || pending != null || storage != null || sleep != null || pickers != null } private var worker: CacheWorker? = null @@ -167,6 +166,30 @@ object AdapterWorker : ServerRuntime { start() } + @Volatile private var catalogActionRunning=false + /** Auto Wi-Fi off must include an executing command after it leaves the pending queue. */ + internal fun catalogActionWork(work: () -> T): T { + catalogActionRunning=true + return try { work() } finally { catalogActionRunning=false } + } + + fun catalogAction(ctx: Context, credentials: CacheWorker.Creds, owner: String, action: String, args: Map<*,*>, + done: (Map?,String?) -> Unit) { + app=ctx.applicationContext + BulkWork.attach(ctx) + synchronized(lock) { patches.addLast { catalogActionWork { + val start=System.nanoTime() + val result=runCatching { + if(owner!=LibraryAccount.owner() || worker().store.meta("owner")!=owner) throw ServerFailure("canceled") + CatalogWorkflow(worker(),credentials,owner,ConnectorHttp,reading={ Reading.now(ctx) }, + current={ owner==LibraryAccount.owner() },checkpoint=BulkWork::checkpoint).command(action,args) + } + OLog.i("library.catalog.action ms=${(System.nanoTime()-start)/1_000_000}") + result.fold({ done(it,null) },{ done(null,(it as? ServerFailure)?.kind ?: "unavailable") }) + } }; lock.notifyAll() } + start() + } + /** One sole-writer command. The plugin sends an action and opaque owner, never a plan/login. */ fun catalogControl(ctx: Context, credentials: CacheWorker.Creds, owner: String, action: String, manual: Boolean, done: (Map?,String?) -> Unit) { @@ -245,11 +268,6 @@ object AdapterWorker : ServerRuntime { synchronized(lock) { storage = a; lock.notifyAll() } return start() } - if (i.action == ACTION_PATCH && i.hasExtra("plugin_state")) { - val state = i.getStringExtra("plugin_state") ?: return - synchronized(lock) { patches.addLast { worker().savePluginState(LuaValue.str(state)) }; lock.notifyAll() } - return start() - } if (i.action == ACTION_PATCH && i.hasExtra("library_batch")) { val encoded = i.getStringExtra("library_batch")?.takeIf { it.length <= 131072 } ?: return val owner = i.getStringExtra("owner") ?: return @@ -263,11 +281,6 @@ object AdapterWorker : ServerRuntime { }; lock.notifyAll() } return start() } - if (i.action == ACTION_PATCH && i.hasExtra("remember_id")) { - val id = i.getStringExtra("remember_id")?.toLongOrNull() ?: return - synchronized(lock) { patches.addLast { worker().rememberDetail(id) }; lock.notifyAll() } - return start() - } if (i.action == ACTION_PATCH && i.hasExtra("board_year")) { val encoded = i.getStringExtra("board_year") ?: return val key = i.getStringExtra("board_key") ?: return @@ -290,46 +303,12 @@ object AdapterWorker : ServerRuntime { } return start() } - if (i.action == ACTION_PATCH && i.hasExtra("old_hash")) { - val old = i.getStringExtra("old_hash") ?: return - val new = i.getStringExtra("new_hash") ?: return - val path = i.getStringExtra("copy_path") - synchronized(lock) { patches.addLast { - HashSidecar.carry(File(root().parentFile?.parentFile, "hashdocsettings"), old, new, BulkWork::checkpoint) - if (path != null) worker().carryCopySettings(path, old, new) - }; lock.notifyAll() } - return start() - } if (i.action == ACTION_PATCH && i.getStringExtra("drain_events") == "1") { val ack = i.getStringExtra("events_ack") synchronized(lock) { patches.addLast { worker().drainEvents(ack) }; lock.notifyAll() } return start() } if (i.action == ACTION_PATCH) return - if (i.action == ACTION_COPIES) { - val prepare = i.getStringExtra("prepare") - val ask = i.getStringExtra("ask") - val reason = i.getStringExtra("reason") ?: "plugin" - val credentials = creds(i) - val template = i.getStringExtra("template") - synchronized(lock) { - patches.addLast { - if (prepare != null && credentials != null && template != null) { - val job = LuaValue.parse(LuaValue.str(prepare).toByteArray(Charsets.ISO_8859_1)) as? Map<*, *> ?: return@addLast - worker().prepareCopy(job, template, credentials) - } else { - if (ask != null) { - val file = File(root(), "copies/ask.lua") - file.parentFile?.mkdirs() - file.writeBytes(LuaValue.str(ask).toByteArray(Charsets.ISO_8859_1)) - } - worker().copies(reason) - } - } - lock.notifyAll() - } - return start() - } app = ctx.applicationContext val creds = creds(i) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt index 9b37f45c..13ffa233 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt @@ -119,6 +119,11 @@ internal class BookOrbitProjection(private val store: CacheStore, private val cl override fun project(owner: String, a: Map<*, *>): Map { if (store.meta("owner") != owner) return mapOf("error" to "unauthorized", "items" to emptyList()) val op = a["op"] + if (op == "copies.state") { + val state=CatalogWorkflow.load(java.io.File(store.root,"workflows/${BookOrbitLibrary.namespace(owner)}.lua")) + return mapOf("pending" to (state["copies"] as? List<*>).orEmpty().size,"row_count" to 1) + } + if (op == "reader.finish") return FinishLogic.snapshot(store,owner,a) if (op == "connector.root") return connectorRoot(owner) if (op == "connector.home") return connectorHome(owner,a) if (op == "connector.catalog") return connectorCatalog(owner,a) @@ -252,7 +257,7 @@ internal class BookOrbitProjection(private val store: CacheStore, private val cl val source = if (op == "library.summary") "library/all" else if (op == "series") mapOf("kind" to "series", "key" to a["key"]) else a["source"] val kind = if (source is String) source else (source as? Map<*, *>)?.get("kind") as? String val sourceKey = (source as? Map<*, *>)?.get("key") - require(kind in setOf("library/all", "all", "reading", "want-to-read", "recently-added", "finished", "on-device", "list", "collection", "series", "author", "search")) + require(kind in setOf("library/all", "all", "reading", "want-to-read", "recently-added", "finished", "on-device", "list", "collection", "series", "author", "search", "selection")) val g = store.meta("bulk_active")?.toLongOrNull() ?: return empty(false) // Secondary contexts are not complete at base publication; never turn an unknown source into an empty list. if ((kind in setOf("series", "list", "collection") || op == "groups" && f["group"] == "series") && store.meta("bulk_complete")?.toLongOrNull() != g) return empty(false) @@ -261,6 +266,23 @@ internal class BookOrbitProjection(private val store: CacheStore, private val cl val local = localPaths?.keys if ((a["field"] == "where" || kind == "on-device" || f["where"] in setOf("on-device", "server-only")) && local == null) return empty(false) val membership = when (kind) { + "selection" -> { + val selection=(source as? Map<*,*>)?.get("selection") as? Map<*,*> ?: emptyMap() + val selected=linkedMapOf>() + var offset=0 + while(true) { + val window=connectorCatalog(owner,mapOf("view" to "books","selection" to selection,"offset" to offset,"limit" to 24)) + if((window["freshness"] as? Map<*,*>)?.get("saved")!=true) return empty(false) + val rows=(window["items"] as? List<*>).orEmpty() + for(raw in rows) { + val b=raw as? Map<*,*> ?: continue + (b["reference"] as? Number)?.toLong()?.let { selected[it]=emptyMap() } + } + if(rows.isEmpty() || window["more"]!=true) break + offset+=rows.size + } + selected + } "list", "series", "collection" -> { val id = BookOrbitLibrary.id(owner, kind, sourceKey) ?: return mapOf("error" to "missing") val section = when(kind) { "list" -> "smart-scopes"; "collection" -> "collections"; else -> "series" } 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 05d28a38..572bd8b5 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 @@ -11,9 +11,11 @@ internal class BookOrbitServerAdapter(private val credentials: ServerCredentials private val coverReferenceJob: (CacheWorker.Creds?, String, String, Boolean, (Map?, String?) -> Unit) -> Unit = { _, _, _, _, done -> done(null,"unsupported") }, private val legacyAccount: () -> LegacyCoverSource.Account? = { null }, + private val actionJob: (CacheWorker.Creds, String, String, Map<*,*>, (Map?,String?) -> Unit) -> Unit = { _,_,_,_,done -> done(null,"unsupported") }, private val catalogJob: (CacheWorker.Creds, String, String, Boolean, (Map?,String?) -> Unit) -> Unit = { _,_,_,_,done -> done(null,"unsupported") }, private val coverJob: (CacheWorker.Creds, String, Long, (Map?, String?) -> Unit) -> Unit = { _, _, _, done -> done(null,"unsupported") }) : ServerAdapter { + override fun recommendedSettings()=RecommendedSettings.items override val id = "bookorbit" internal interface ConnectorTransport { fun request(server: String, path: String, method: String, body: Map?, headers: Map): BookOrbitAccount.Reply @@ -56,7 +58,12 @@ internal class BookOrbitServerAdapter(private val credentials: ServerCredentials val current=credentials.login("sync") if(current==null) { val key=(old["userkey"] as? String)?.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) } - if(key!=null) credentials.set("sync",ServerCredentials.Login(server,user,key,"user")) + if(key!=null) { + // Preserve the proven native catalog namespace when adopting its login. + // Existing managed logins are untouched; their queue provenance stays intact. + val native=legacyAccount()?.takeIf { it.credentials.server.trimEnd('/').equals(server.trimEnd('/'),true) && it.credentials.user==user } + credentials.set("sync",ServerCredentials.Login(server,user,key,"user",native?.owner)) + } } val selected=credentials.login("sync") val fallback=if(selected?.server==server && selected.user==user) selected.owner() @@ -124,8 +131,20 @@ internal class BookOrbitServerAdapter(private val credentials: ServerCredentials return CapturedPosition((raw["percentage"] as? Number)?.toDouble(),raw["progress"] as? String, (raw["ts"] as? Number)?.toLong() ?: 0L,raw["status"]=="complete") } - override fun lifecyclePhase(entry: LifecycleQueue.Entry, phase: String, checkpoint: ByteArray, openPath: String?) = - (sync ?: throw ServerFailure("writer-active")).phase(entry,phase,checkpoint,openPath) + override fun lifecyclePhase(entry: LifecycleQueue.Entry, phase: String, checkpoint: ByteArray, openPath: String?): SyncPhaseResult { + val result=(sync ?: throw ServerFailure("writer-active")).phase(entry,phase,checkpoint,openPath) + // Match owns identity; catalog observes its completed result without another writer. + if(phase=="match" && result.complete && entry.owner==owner()) { + val match=(LuaValue.parse(result.checkpoint) as? Map<*,*>)?.get("match") as? Map<*,*> + val snapshot=LuaValue.parse(entry.payload) as? Map<*,*> + val c=credentials.login("sync") + if(c!=null && match?.get("bookId")!=null && snapshot?.get("file") is String) { + actionJob(CacheWorker.Creds(c.server,c.user,c.secret),entry.owner,"local.observe",mapOf( + "reference" to match["bookId"],"file_reference" to match["bookFileId"],"document" to entry.document,"path" to snapshot["file"])) { _,_ -> } + } + } + return result + } override fun lifecycleComplete(checkpoint: ByteArray): Boolean = ((LuaValue.parse(checkpoint) as? Map<*, *>)?.get("remote_pending") as? Map<*, *>).isNullOrEmpty() override fun nextSyncVerification(owner: String, document: String) = @@ -139,8 +158,8 @@ internal class BookOrbitServerAdapter(private val credentials: ServerCredentials } override fun state(): Map { val accountState = account.state() - val legacy=if(credentials.login("sync")==null && credentials.login("opds")==null) legacyAccount() else null val sourceOwner=owner() + val legacy=legacyAccount()?.takeIf { it.owner==sourceOwner } fun status(kind: String): Map { val c = credentials.login(kind) return credentials.status(kind) + mapOf("server" to c?.server, "username" to c?.user?.let(LuaValue::str), @@ -253,6 +272,13 @@ internal class BookOrbitServerAdapter(private val credentials: ServerCredentials require(LuaValue.encode(result).size <= 16384) return result } + override fun catalogAction(owner: String, action: String, args: Map<*,*>, done: (Map?,String?) -> Unit) { + require(owner == owner()) + val c=credentials.login("sync")?.takeIf { it.owner()==owner }?.let { login("sync") } + val legacy=legacyAccount()?.takeIf { it.owner==owner } + val creds=c?.let { CacheWorker.Creds(it.server,it.user,it.secret) } ?: legacy?.credentials ?: throw ServerFailure("unauthorized") + actionJob(creds,owner,action,args,done) + } override fun catalogControl(owner: String, action: String, manual: Boolean, done: (Map?,String?) -> Unit) { require(owner.length in 1..4096) require(action in setOf("full","resume","refresh","incremental","covers","stop")) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CacheWorker.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CacheWorker.kt index 94687948..496e0295 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CacheWorker.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CacheWorker.kt @@ -107,6 +107,9 @@ class CacheWorker( if (n > 0) log("store: removed $n files of the cache before the database") } + /** Publication retains this worker's timing logger (including host test injection). */ + internal fun publishLibrary(owner: String,requests: List) = LibraryReadModel(store,log=log).publish(owner,requests) + /** The detail template saved with the last plan (what a check of a detail path needs). */ private fun detailTemplate(): String? = store.meta("detail_template") @@ -159,12 +162,6 @@ class CacheWorker( event(ev) } - fun savePluginState(encoded: String) { - val bytes = encoded.toByteArray(Charsets.ISO_8859_1) - require(LuaValue.parse(bytes) is Map<*, *>) - check(write(File(root, "plugin-state.lua"), bytes)) - } - fun rememberDetail(id: Long) { val detail = store.detail(id)?.first as? Map<*, *> ?: return val file = File(root.parentFile, "orbit-detail-cache.lua") @@ -318,38 +315,27 @@ class CacheWorker( ((b?.let { LuaValue.parse(it) } as? Map<*, *>)?.get("tags") as? List<*>)?.mapNotNull { it as? String } } - /** - * The plugin's COPIES: which copies on this reader changed in the library. The ask - * (copies/ask.lua, written by the plugin; no login in it): `books` ({ md5, path, book_id, - * file_id, incompatible }), `eob` (book id -> { files, saved_at }: the end-of-book cache). - * The details come from the newer of the end-of-book cache and the database (CopiesLogic). - * Answers with { kind = "copies", why, checked, found = { { md5, path, book_id, file_id, why } }, gone }. - */ - fun copies(why: String) { + /** Reuse the existing saved-detail lookup for neutral copy commands. The worker owns + * catalog joins, freshness precedence, file existence and ordering; Lua gets one count row. */ + data class CopyCheck(val checked: Int,val found: List>,val gone: Int) + fun changedCopies(books: List>,eob: Map<*,*> = emptyMap()): CopyCheck { checkpoint() - val ask = read(File(root, "copies/ask.lua")) as? Map<*, *> - if (ask == null) { - event(sortedMapOf("kind" to "copies", "why" to why, "err" to "no ask")) - return - } - val books = (ask["books"] as? List<*>)?.mapNotNull { it as? Map<*, *> } ?: emptyList() - val want = books.mapNotNull { (it["book_id"] as? Long)?.toString() }.toHashSet() - val details = HashMap() - for ((k, v) in ask["eob"] as? Map<*, *> ?: emptyMap()) { - val d = v as? Map<*, *> ?: continue - details[k.toString()] = CopiesLogic.Detail(d["files"] as? List<*>, (d["saved_at"] as? Number)?.toLong() ?: 0L) + val want=books.mapNotNull { (it["book_id"] as? Number)?.toLong()?.toString() }.toHashSet() + val details=HashMap() + for((key,value) in eob) { + val d=value as? Map<*,*> ?: continue + details[key.toString()]=CopiesLogic.Detail(d["files"] as? List<*>,(d["saved_at"] as? Number)?.toLong() ?: 0L) } - for (id in want) { + for(id in want) { checkpoint() - val saved = store.detail(id.toLong()) ?: store.bookItem(id.toLong())?.let { it to (store.db().query("SELECT item_at FROM books WHERE id=?", id.toLong()) { row -> row.long(0) ?: 0L }.firstOrNull() ?: 0L) } ?: continue - val (body, at) = saved - val files = (body as? Map<*, *>)?.get("files") as? List<*> ?: continue - if (CopiesLogic.newer(details[id], at)) details[id] = CopiesLogic.Detail(files, at) + val saved=store.detail(id.toLong()) ?: store.bookItem(id.toLong())?.let { it to + (store.db().query("SELECT item_at FROM books WHERE id=?",id.toLong()) { row -> row.long(0) ?: 0L }.firstOrNull() ?: 0L) } ?: continue + val files=(saved.first as? Map<*,*>)?.get("files") as? List<*> ?: continue + if(CopiesLogic.newer(details[id],saved.second)) details[id]=CopiesLogic.Detail(files,saved.second) } - val found = CopiesLogic.candidates(books, details) - val present = found.filter { File(LuaValue.utf8(it["path"] as String)).isFile } - event(sortedMapOf("kind" to "copies", "why" to why, "checked" to books.size.toLong(), "found" to present, - "gone" to (found.size - present.size).toLong())) + val found=CopiesLogic.candidates(books,details) + val present=found.filter { File(LuaValue.utf8(it["path"] as String)).isFile } + return CopyCheck(books.size,present,found.size-present.size) } fun carryCopySettings(path: String, old: String, new: String) { @@ -368,38 +354,6 @@ class CacheWorker( if (stats.isFile) AndroidSql(stats, wal = true).use { db -> db.exec("UPDATE OR IGNORE book SET md5=? WHERE md5=?", new, old) } } - /** A bounded preparation result: all network, file sampling and JSON work stays here. */ - fun prepareCopy(job: Map<*, *>, template: String, creds: Creds) { - val path = job["path"] as? String ?: return - val ev = sortedMapOf("kind" to "copy_prepared", "path" to path) - try { - checkpoint() - val file = File(LuaValue.utf8(path)).canonicalFile - require(bookRoots.any { file.path.startsWith(it.canonicalPath + File.separator) }) - val id = (job["book_id"] as? Number)?.toLong() ?: error("book missing") - val request = template.replace(MirrorLogic.SENTINEL, id.toString()) - val reply = http.get(url(creds, request), headers(creds), null, MAX_BODY) - require(reply.code == 200 && reply.body != null) - val body = decodeJson(String(reply.body!!, Charsets.UTF_8)) as? Map<*, *> ?: error("detail missing") - val fields = setOf("id", "title", "authors", "seriesId", "seriesName", "seriesIndex", "files", "readStatus") - ev["detail"] = body.filterKeys { it in fields } - val digest = java.security.MessageDigest.getInstance("MD5") - java.io.RandomAccessFile(file, "r").use { input -> - val bytes = ByteArray(1024) - for (offset in listOf(0L) + (0..10).map { 1024L shl (2 * it) }) { - checkpoint() - input.seek(offset) - val n = input.read(bytes) - if (n < 0) break - digest.update(bytes, 0, n) - } - } - ev["md5"] = digest.digest().joinToString("") { "%02x".format(it) } - require(LuaValue.encode(ev).size <= 48000) - } catch (_: Exception) { ev.remove("detail"); ev["err"] = "preparation failed" } - event(ev) - } - /** Acknowledged mailbox; listing/parsing event files belongs to this worker only. */ private val mailbox by lazy { EventMailbox(root, checkpoint) } fun drainEvents(ack: String?) = mailbox.publish(ack) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflow.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflow.kt new file mode 100644 index 00000000..b06a1563 --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflow.kt @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import java.io.File +import java.security.MessageDigest + +/** Catalog actions share CacheWorker's sole writer. Queue files are account scoped and survive + * cache resets. No lifecycle/position queue is drained or rewritten here. */ +internal class CatalogWorkflow(private val worker: CacheWorker, private val creds: CacheWorker.Creds, + private val owner: String, private val transport: BookOrbitServerAdapter.ConnectorTransport, + private val reading: () -> Boolean = { false }, private val current: () -> Boolean = { true }, + private val checkpoint: () -> Unit = {}, private val now: () -> Long = { System.currentTimeMillis()/1000 }) { + private val store get()=worker.store + private val file=File(worker.root,"workflows/${BookOrbitLibrary.namespace(owner)}.lua") + private val state=load(file).toMutableMap() + private val jobs=(state["finishes"] as? Map<*,*>).orEmpty().entries.associate { it.key.toString() to (it.value as Map<*,*>).toMutableMap() }.toMutableMap() + private val copies=(state["copies"] as? List<*>).orEmpty().mapNotNull { it as? Map<*,*> }.toMutableList() + private val downloads=(state["downloads"] as? Map<*,*>).orEmpty().toMutableMap() + private fun check() { if(!current() || store.meta("owner")!=owner) throw ServerFailure("canceled") } + private fun save() { + check(); state["finishes"]=jobs;state["copies"]=copies;state["downloads"]=downloads + file.parentFile?.mkdirs(); val tmp=File(file.path+".new") + tmp.outputStream().use { it.write(LuaValue.encode(state)); it.fd.sync() } + check(); check(tmp.renameTo(file)) + } + private fun request(path:String,method:String="GET",body:Map?=null):Map<*,*> { + checkpoint();check() + val r=transport.request(creds.server,path,method,body,mapOf("Accept" to "application/json","x-auth-user" to creds.user,"x-auth-key" to creds.key)) + if(r.code !in 200..299) throw HttpFailure(r.code) + return r.value as? Map<*,*> ?: emptyMap() + } + private class HttpFailure(val code:Int):Exception() + private fun number(v:Any?)=(v as? Number)?.toLong() ?: (v as? String)?.toLongOrNull() + private fun id(args:Map<*,*>):Long? = BookOrbitLibrary.id(owner,"book",args["key"]) + ?: number(args["reference"])?.takeIf { it>0 } + ?: (args["path"] as? String)?.let { p -> ledger().firstOrNull { it["path"]==p }?.get("book_id") }?.let(::number) + private fun settings():Map<*,*> { + val f=File(worker.root.parentFile?.parentFile,"settings.reader.lua") + if(!f.isFile || f.length()>4194304) return emptyMap() + return StatusMarginRepair.literalTable(f.readText(Charsets.ISO_8859_1),"bookorbit")?.let { + LuaValue.parse(it.toByteArray(Charsets.ISO_8859_1)) as? Map<*,*> + }.orEmpty() + } + private fun delivery():Map { + val preferences=settings() + val key=LuaValue.str(creds.server)+"|"+LuaValue.str(creds.user) + val remote=(preferences["catalog_delivery_server_profiles"] as? Map<*,*>)?.get(key) as? String + val legacy=(preferences["catalog_delivery_profiles"] as? Map<*,*>)?.get(key) + val variant=remote?.takeIf { it in setOf("original","audioless_epub") } ?: if(legacy=="original") "original" else "audioless_epub" + val device=globalSetting("device_id") as? String + return mapOf("variant" to variant)+(device?.let { mapOf("deviceId" to it) } ?: emptyMap()) + } + private fun globalSetting(key:String):Any? { + val f=File(worker.root.parentFile?.parentFile,"settings.reader.lua") + if(!f.isFile || f.length()>4194304) return null + // Settings contains executable headers in some KOReader versions. Parse literals only. + val text=f.readText(Charsets.ISO_8859_1) + val field=Regex("\\[\\s*[\"']"+Regex.escape(key)+"[\"']\\s*]\\s*=\\s*(\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*')").find(text)?.groupValues?.get(1) ?: return null + return LuaValue.parse(("return {value="+field+"}").toByteArray(Charsets.ISO_8859_1)).let { (it as? Map<*,*>)?.get("value") } + } + + private fun detail(id:Long):Map<*,*> { + val raw=request("/koreader/plugin/catalog/books/$id?"+MirrorLogic.encQuery(delivery())) + require(number(raw["id"])==id);store.putDetail(id,raw,now());return raw + } + /** Reads the account's persisted native state on the worker; never asks Lua to scan it. */ + private fun ledger():List> { + val nativeOwner=LuaValue.str(creds.server.trimEnd('/'))+"|"+LuaValue.str(creds.user) + val dir=worker.root.parentFile + val legacy=File(dir,"bookorbit_sync_state.lua") + val primary=load(legacy) + val native=if(primary["account_identity"]==nativeOwner) primary else { + val hash=MessageDigest.getInstance("MD5").digest(nativeOwner.toByteArray(Charsets.ISO_8859_1)).joinToString("") { "%02x".format(it) } + load(File(dir,"bookorbit_sync_state_$hash.lua" )) + } + val loaded=(native["books"] as? Map<*,*>)?.mapNotNull { (hash,value) -> + val b=value as? Map<*,*> ?: return@mapNotNull null + val path=b["file"] as? String ?: return@mapNotNull null + if(b["bookId"]==null) return@mapNotNull null + mapOf("md5" to hash,"path" to path,"book_id" to b["bookId"],"file_id" to b["fileId"],"incompatible" to b["positionIncompatible"]) + } + val ask=load(File(worker.root,"copies/ask.lua")) + val previous=if(ask["owner"]==owner) (ask["books"] as? List<*>).orEmpty().mapNotNull { it as? Map<*,*> } else emptyList() + val books=(loaded ?: previous).toMutableList() + for(row in previous) { + if(row["awaiting_native"]!=true && row["owned_sync"]!=true) continue + val path=row["path"] as? String ?: continue + if(books.any { it["path"]==path && it["md5"]==row["md5"] && it["book_id"]==row["book_id"] && it["awaiting_native"]!=true }) continue + if(!File(LuaValue.utf8(path)).isFile) continue + books.removeAll { it["path"]==path };books.add(row) + if(row["awaiting_native"]==true) worker.event(mapOf("kind" to "download.saved","owner" to owner,"path" to path,"document" to row["md5"],"reference" to row["book_id"],"file_reference" to row["file_id"])) + } + val dest=File(worker.root,"copies/ask.lua");dest.parentFile?.mkdirs() + val tmp=File(dest.path+".new");tmp.writeBytes(LuaValue.encode(mapOf("owner" to owner,"books" to books)));check(tmp.renameTo(dest)) + return books + } + /** Checkpoint complete legacy queues before marking their sources imported. Sources remain + * intact for recovery; the durable marker prevents retry resurrection after acknowledgement. */ + private fun migrate() { + if(state["migrated"]==true) return + val ask=load(File(worker.root,"copies/ask.lua")) + val claim=File(worker.root,"workflows/legacy-owner.lua") + val priorOwner=load(claim)["owner"] + val sourceOwner=priorOwner ?: ask["owner"] + if(sourceOwner!=null && sourceOwner!=owner) { + // Preserve the source's owner even if this account refreshes the local file ledger. + if(!claim.exists()) { + claim.parentFile?.mkdirs();val tmp=File(claim.path+".new") + tmp.outputStream().use { it.write(LuaValue.encode(mapOf("owner" to sourceOwner)));it.fd.sync() } + check();check(tmp.renameTo(claim)) + } + state["migrated"]=true;save();return + } + val legacy=load(File(worker.root,"plugin-state.lua")) + for(raw in ((legacy["copies"] as? Map<*,*>)?.get("queue") as? List<*>).orEmpty()) { + val job=raw as? Map<*,*> ?: continue + if(copies.none { it["path"]==job["path"] }) copies.add(job) + } + val finish=load(File(worker.root.parentFile,"orbit-finish-queue.lua")) + for((hash,raw) in (finish["jobs"] as? Map<*,*>).orEmpty()) { + val j=raw as? Map<*,*> ?: continue + jobs.putIfAbsent(hash.toString(),(j+mapOf("token" to (j["token"] ?: java.util.UUID.randomUUID().toString()))).toMutableMap()) + } + downloads.putAll((finish["downloads"] as? Map<*,*>).orEmpty()) + // Claim the source for this account before publishing the migration marker. A crash + // leaves the untouched source retryable by the same owner, never by another account. + if(!claim.exists()) { + claim.parentFile?.mkdirs();val tmp=File(claim.path+".new") + tmp.outputStream().use { it.write(LuaValue.encode(mapOf("owner" to owner)));it.fd.sync() } + check();check(tmp.renameTo(claim)) + } + val details=load(File(worker.root.parentFile,"orbit-detail-cache.lua"))["books"] as? Map<*,*> + for((key,value) in details.orEmpty()) { + val id=number(key) ?: continue;val d=value as? Map<*,*> ?: continue + val at=number(d["saved_at"]) ?: 0L + if(CopiesLogic.newer(store.detail(id)?.let { CopiesLogic.Detail(null,it.second) },at)) store.putDetail(id,d,at) + } + state["migrated"]=true; save() + } + fun command(action:String,args:Map<*,*>):Map { + check(); migrate() + val path=args["path"] as? String + val hash=args["document"] as? String + when(action) { + "copies.check" -> if(args["enabled"]!=false && !reading()) checkCopies(args["open_path"] as? String) + "copies.ack" -> { + copies.removeAll { it["token"]==args["token"] && it["phase"]=="identity" };save() + } + "finish.mark" -> { + require(hash!=null && Regex("[a-fA-F0-9]{32}").matches(hash)) + if(args["complete"]==true) { + val book=id(args) + val status=(book?.let { store.detail(it)?.first } as? Map<*,*>)?.get("readStatus") + jobs[hash]=mutableMapOf("hash" to hash,"book_id" to book,"file" to path,"ready" to false, + "token" to java.util.UUID.randomUUID().toString(),"created_at" to now(),"finished_on" to java.time.Instant.ofEpochSecond(now()).atZone(java.time.ZoneId.systemDefault()).toLocalDate().toString(), + "final_pos" to mapOf("percentage" to args["percentage"]),"status_seen" to status,"rating" to jobs[hash]?.get("rating")) + } else jobs.remove(hash) + save() + } + "finish.rate" -> { jobs[hash]?.set("rating", args["rating"] ?: "clear"); save() } + "finish.leave" -> { jobs[hash]?.set("ready",true); save() } + "finish.validate" -> return mapOf("apply" to (jobs[hash]?.get("phase")=="writeback" && jobs[hash]?.get("token")==args["token"])) + "finish.ack" -> { if(jobs[hash]?.get("phase")=="writeback" && jobs[hash]?.get("token")==args["token"]) jobs.remove(hash); save() } + "finish.drain" -> if(!reading()) { drain(args["manual"]==true); pendingDownloads() } + "finish.download" -> { + val book=id(args) ?: throw ServerFailure("missing") + if(args["later"]==true) { downloads[book.toString()]=mapOf("book_id" to book);save() } + else { + val target=args["destination"] as? String + val selected=if(args["file_reference"]!=null) CopiesLogic.pick((detail(book)["files"] as? List<*>).orEmpty(),args["file_reference"]) else null + return mapOf("local_path" to download(book,target,selected,catalog=true)) + } + } + "local.observe" -> { + val book=number(args["reference"]) ?: throw ServerFailure("missing") + require(path!=null && hash!=null && Regex("[a-fA-F0-9]{32}").matches(hash)) + if(bookFile(path).isFile) recordLocal(book,args["file_reference"],path,hash,ownedSync=true) + } + "finish.prepare" -> { + val book=id(args) + if(args["local_only"]!=true && !reading()) book?.let { detail(it) } + return mapOf("key" to book?.let { BookOrbitLibrary.key(owner,"book",it) },"reference" to book,"document" to hash,"path" to path,"owner" to owner,"row_count" to 1) + } + "initialize" -> ledger() + else -> throw ServerFailure("unsupported") + } + val retained=store.db().query("SELECT request FROM library_views WHERE owner=? LIMIT 64",LuaValue.utf8(owner)) { it.text(0)?.let(LuaValue::str) }.filterNotNull() + .filter { (LuaValue.parse(it.toByteArray(Charsets.ISO_8859_1)) as? Map<*,*>)?.get("op") in setOf("reader.finish","copies.state") } + for(batch in retained.chunked(16)) worker.publishLibrary(owner,batch) + worker.event(mapOf("kind" to "library","owner" to owner)) + return mapOf("ok" to true) + } + private fun checkCopies(open:String?) { + val books=ledger() + for(job in worker.changedCopies(books).found) if(copies.none { it["path"]==job["path"] }) copies.add(job) + save() + for(job in copies.toList()) { + checkpoint();check(); if(reading()) break + if(job["phase"]=="identity") { copyEvent(job);continue } + if(job["phase"]=="transfer") { + val path=job["path"] as? String ?: continue + if(path==open) continue + if(runCatching { partial(bookFile(path))==job["new"] }.getOrDefault(false)) { + val landed=job+mapOf("phase" to "identity");copies[copies.indexOf(job)]=landed;save();copyEvent(landed);continue + } + } + val path=job["path"] as? String ?: continue + if(path==open) continue + try { + val before=(job["old"] as? String) ?: partial(bookFile(path)) + val book=number(job["book_id"]) ?: continue + val d=detail(book) + val f=CopiesLogic.pick((d["files"] as? List<*>).orEmpty(),job["file_id"]) ?: continue + if(CopiesLogic.decide(before,f)!="replace") { copies.remove(job);save();continue } + // Save replacement identity before changing bytes. A crash after rename can + // finish identity repair from this checkpoint without downloading again. + val token=java.util.UUID.randomUUID().toString() + val prepared=job+mapOf("token" to token,"old" to before,"new" to f["fileHash"],"file_id" to f["id"],"phase" to "transfer") + copies[copies.indexOf(job)]=prepared;save() + download(book,path,f) + val landed=prepared+mapOf("phase" to "identity") + copies[copies.indexOf(prepared)]=landed;save() + copyEvent(landed) + } catch(_:Exception) { /* durable retry; the old file remains until verified rename */ } + } + } + private fun repair(job:Map<*,*>) { + val old=job["old"] as? String ?: return;val new=job["new"] as? String ?: return + HashSidecar.carry(File(worker.root.parentFile?.parentFile,"hashdocsettings"),old,new,checkpoint) + worker.carryCopySettings(job["path"] as String,old,new) + } + private fun copyEvent(job:Map<*,*>) { + repair(job) + val book=number(job["book_id"]) ?: throw ServerFailure("missing") + val path=job["path"] as String;val hash=job["new"] as String + recordLocal(book,job["file_id"],path,hash) + worker.event(mapOf("kind" to "copy.identity","owner" to owner,"path" to path,"before" to job["old"],"after" to hash, + "reference" to book,"file_reference" to job["file_id"],"token" to job["token"])) + } + private fun download(book:Long,target:String?,selected:Map<*,*>?=null,deferred:Boolean=false,catalog:Boolean=false):String { + val local=BookOrbitLibrary.localPaths(store,owner)?.get(book) + if(target==null && local!=null) return local + val d=if(selected==null) detail(book) else null + val f=selected ?: CopiesLogic.pick((d?.get("files") as? List<*>).orEmpty(),null) ?: throw ServerFailure("missing") + val expected=f["fileHash"] as? String ?: throw ServerFailure("invalid") + require(Regex("[a-fA-F0-9]{32}").matches(expected)) + val external=worker.root.parentFile?.parentFile?.parentFile ?: throw ServerFailure("forbidden") + val downloadRoot=(globalSetting("download_dir") ?: globalSetting("home_dir") ?: globalSetting("lastdir")) as? String + val directory=downloadRoot?.let { File(LuaValue.utf8(it)) } ?: File(external,"books") + val devicePath=(f["devicePath"] as? String)?.let(LuaValue::utf8)?.split('/','\\')?.filter { it.isNotEmpty() } + require(devicePath==null || devicePath.all { it!="." && it!=".." && it.length<=255 }) + val title=(d?.get("title") as? String)?.let(LuaValue::utf8) ?: "book-$book" + val authors=(d?.get("authors") as? List<*>)?.firstOrNull()?.toString()?.let(LuaValue::utf8) + val filename=(title+(if(authors!=null) " - $authors" else "")).replace(Regex("[/:*?\"<>|\\\\]+")," ") + .replace(Regex("\\s+")," ").trim().ifBlank { "book-$book" }+"."+(f["format"] as? String ?: "epub").lowercase() + val destination=if(target!=null) File(LuaValue.utf8(target)) else File(directory,devicePath?.joinToString("/") ?: filename) + require(Places.inside(destination,listOf(external))!=null) + if((target==null || catalog) && destination.isFile && (target==null || partial(destination).equals(expected,true))) { + if(!partial(destination).equals(expected,true)) throw ServerFailure("exists") + recordDownload(book,f,destination,expected,deferred,d?.get("title")) + return LuaValue.str(destination.path) + } + val part=File(destination.path+".booksync-part");destination.parentFile?.mkdirs() + val params=mapOf("variant" to (f["downloadVariant"] as? String ?: delivery()["variant"].orEmpty()),"selection" to (f["selection"] as? String ?: "")) + try { + checkpoint();check() + val ok=transport.download(creds.server,"/koreader/plugin/catalog/files/${f["id"]}/download?"+MirrorLogic.encQuery(params), + mapOf("x-auth-user" to creds.user,"x-auth-key" to creds.key,"Accept" to "application/octet-stream"),part) + check(ok && part.isFile && partial(part).equals(expected,true)) + check(); if(reading() && target!=null) throw ServerFailure("reading") + check(part.renameTo(destination)) + if(target==null || catalog) recordDownload(book,f,destination,expected,deferred,d?.get("title")) + return LuaValue.str(destination.path) + } finally { part.delete() } + } + private fun bookFile(path:String):File { + val file=File(LuaValue.utf8(path)) + require(Places.inside(file,listOf(worker.root.parentFile!!.parentFile!!.parentFile!!))!=null) + return file + } + private fun recordLocal(book:Long,fileReference:Any?,path:String,hash:String,ownedSync:Boolean=false) { + check() + val ask=load(File(worker.root,"copies/ask.lua")) + val rows=if(ask["owner"]==owner) (ask["books"] as? List<*>).orEmpty().mapNotNull { it as? Map<*,*> } else emptyList() + val kept=rows.filter { it["path"]!=path }+mapOf("md5" to hash,"path" to path,"book_id" to book,"file_id" to fileReference,"awaiting_native" to !ownedSync,"owned_sync" to ownedSync) + val dest=File(worker.root,"copies/ask.lua");dest.parentFile?.mkdirs();val tmp=File(dest.path+".new") + tmp.outputStream().use { it.write(LuaValue.encode(mapOf("owner" to owner,"books" to kept)));it.fd.sync() } + check();check(tmp.renameTo(dest)) + } + private fun recordDownload(book:Long,f:Map<*,*>,destination:File,hash:String,deferred:Boolean,title:Any?) { + val path=LuaValue.str(destination.path) + recordLocal(book,f["id"],path,hash) + worker.event(mapOf("kind" to "download.saved","owner" to owner,"path" to path,"document" to hash,"reference" to book,"file_reference" to f["id"],"deferred" to deferred,"title" to title)) + } + private fun drain(manual:Boolean) { + for((hash,job) in jobs.entries.sortedBy { number(it.value["created_at"]) ?: 0L }) { + check(); if(reading()) return + if(job["phase"]=="writeback") { finishEvent(hash,job);continue } + if(job["ready"]!=true || !manual && (job["parked"]==true || (number(job["next_try_at"]) ?: 0L)>now())) continue + try { + val id=number(job["book_id"]) + if(id==null) { jobs.remove(hash);save();continue } + val remote=detail(id) + val write=FinishLogic.sendStatus(job["status_seen"],remote["readStatus"]) + if(write) request("/koreader/plugin/catalog/books/$id/read-status","PUT",mapOf("status" to "read")) + if(job["rating"]!=null) request("/koreader/plugin/catalog/books/$id/rating","PUT",mapOf("rating" to job["rating"].takeIf { it!="clear" })) + job["phase"]="writeback";job["status_written"]=write;save();finishEvent(hash,job) + } catch(e:HttpFailure) { + when(e.code) { + 401 -> return + 400,403,404 -> { jobs.remove(hash);save() } + else -> retry(job) + } + } catch(_:Exception) { retry(job) } + } + } + private fun retry(job:MutableMap) { + val attempts=(number(job["attempts"]) ?: 0L)+1;job["attempts"]=attempts + job["next_try_at"]=now()+minOf(3600,60L shl (attempts-1).coerceAtMost(6).toInt());job["parked"]=attempts>=5;save() + } + private fun finishEvent(hash:String,j:Map<*,*>) = worker.event(mapOf("kind" to "finish.applied","owner" to owner,"document" to hash, + "token" to j["token"],"path" to j["file"],"complete" to j["status_written"],"date" to j["finished_on"],"rated" to (j["rating"]!=null),"rating" to j["rating"].takeIf { it!="clear" })) + private fun pendingDownloads() { + for((key,value) in downloads.toMap()) { + if(reading()) return + val id=number((value as? Map<*,*>)?.get("book_id")) ?: continue + try { download(id,null,deferred=true);downloads.remove(key);save() } catch(_:Exception) { } + } + } + companion object { + internal fun load(file:File):Map<*,*> { + if(!file.isFile) return emptyMap() + require(file.length()<=16777216) { "workflow source exceeds import limit" } + val parsed=LuaValue.parse(file.readBytes()) + require(parsed is Map<*,*> || parsed is List<*> && parsed.isEmpty()) { "invalid workflow source" } + return (parsed as? Map<*,*>).orEmpty() + } + internal fun partial(file:File):String { + val digest=MessageDigest.getInstance("MD5") + java.io.RandomAccessFile(file,"r").use { input -> + val bytes=ByteArray(1024) + for(offset in listOf(0L)+(0..10).map { 1024L shl (2*it) }) { + input.seek(offset);val n=input.read(bytes);if(n<0) break;digest.update(bytes,0,n) + } + } + return digest.digest().joinToString("") { "%02x".format(it) } + } + } +} diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesLogic.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesLogic.kt index aec644bb..2a5cf700 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesLogic.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesLogic.kt @@ -8,6 +8,15 @@ import net.fledgewing.orbitcompanion.* * CopiesPlan.candidates; the replacement download stays in the plugin). */ object CopiesLogic { + fun pick(files: List<*>, id: Any?): Map<*,*>? { + val rows=files.mapNotNull { it as? Map<*,*> }.filter { (it["format"] as? String)?.lowercase() in setOf("epub","pdf","cbz","fb2","mobi","azw3","djvu","txt","html","rtf","doc") } + return rows.firstOrNull { id!=null && it["id"]==id } ?: rows.firstOrNull { it["role"]=="primary" } ?: rows.firstOrNull() + } + fun decide(local: String, file: Map<*,*>): String { + val hash=file["fileHash"] as? String + return if(hash.isNullOrBlank()) "unknown" else if(hash.equals(local,true)) "same" else "replace" + } + /** A saved book detail's files, and when it was saved (os.time seconds). */ data class Detail(val files: List<*>?, val at: Long) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/FinishLogic.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/FinishLogic.kt new file mode 100644 index 00000000..acba482c --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/FinishLogic.kt @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import java.io.File + +/** Worker-only finish decisions; sheets receive two preselected display cards, never catalogs. */ +internal object FinishLogic { + fun sendStatus(seen:Any?,remote:Any?) = remote!="read" && !(remote in setOf("rereading","on_hold","abandoned") && remote!=seen) + private fun number(v:Any?)=(v as? Number)?.toDouble() ?: (v as? String)?.toDoubleOrNull() + private fun fmt(n:Double)=if(n==n.toLong().toDouble()) n.toLong().toString() else n.toString() + fun snapshot(store:CacheStore,owner:String,args:Map<*,*>):Map { + val path=args["path"] as? String + val entry=BookOrbitLibrary.localEntries(store,owner)?.firstOrNull { it["path"]==path } + val id=BookOrbitLibrary.id(owner,"book",args["key"]) ?: (entry?.get("book_id") as? Number)?.toLong() + val d=id?.let { (store.detail(it)?.first ?: store.bookItem(it)) as? Map<*,*> }.orEmpty() + val state=CatalogWorkflow.load(File(store.root,"workflows/${BookOrbitLibrary.namespace(owner)}.lua")) + val hash=args["document"] as? String ?: entry?.get("md5") + val job=(state["finishes"] as? Map<*,*>)?.get(hash) as? Map<*,*> + val paths=BookOrbitLibrary.localPaths(store,owner).orEmpty() + fun card(b:Map<*,*>,line:String):Map { + val bid=(b["id"] as? Number)?.toLong() + return mapOf("line" to LuaValue.str(line),"title" to (b["title"] as? String)?.let { LuaValue.boundedText(LuaValue.utf8(it),160) },"book_id" to bid?.let { BookOrbitLibrary.key(owner,"book",it) }, + "book" to mapOf("cover_path" to bid?.let { store.meta("cover_file_$it") }?.takeIf { File(LuaValue.utf8(it)).isFile }), + "local_path" to paths[bid],"action" to if(paths[bid]!=null) "open" else "download") + } + val members=(d["seriesMembers"] as? List<*>).orEmpty().mapNotNull { it as? Map<*,*> } + val index=number(d["seriesIndex"]) + var next:Map?=null + var nextId:Any?=null + if(d["seriesId"]!=null && index!=null) { + val sorted=members.filter { it["id"]!=id && number(it["seriesIndex"])!=null } + .sortedWith(compareBy> { number(it["seriesIndex"]) }.thenBy { (it["id"] as? Number)?.toLong() }) + val after=sorted.firstOrNull { number(it["seriesIndex"])!!>index } + if(after!=null) { + val n=number(after["seriesIndex"])!!;val whole=kotlin.math.floor(index)+1 + next=if(n>whole) mapOf("line" to LuaValue.str("Book ${fmt(whole)} isn't in your library")) else { + nextId=after["id"];card(after,"Next in series · Book ${fmt(n)}"+(if(after["readStatus"]=="read") " · Read" else "")) + } + } else { + val unread=sorted.firstOrNull { it["readStatus"]!="read" } + next=if(unread==null) mapOf("line" to LuaValue.str("You've finished the series")) else { + nextId=unread["id"];card(unread,"Last book · not read yet: Book ${fmt(number(unread["seriesIndex"])!!)}") + } + } + } + val read=members.filter { it["readStatus"]=="read" }.map { it["id"] }.toSet() + val related=(d["relatedSections"] as? List<*>).orEmpty().mapNotNull { it as? Map<*,*> }.associateBy { it["id"] } + val author=(d["authors"] as? List<*>)?.firstOrNull() as? String + var suggestion:Map?=null + for(source in listOf("author","similar")) { + val selected=(related[source]?.get("books") as? List<*>).orEmpty().mapNotNull { it as? Map<*,*> } + .firstOrNull { it["id"]!=id && it["id"]!=nextId && it["id"] !in read && it["readStatus"]!="read" } ?: continue + suggestion=card(selected,if(source=="author" && author!=null) "Also by ${LuaValue.utf8(author)}" else "You might like");break + } + val title=d["title"] ?: path?.substringAfterLast('/') ?: "" + return mapOf("key" to id?.let { BookOrbitLibrary.key(owner,"book",it) },"title" to LuaValue.boundedText(LuaValue.utf8(title.toString()),256),"author" to author?.let { LuaValue.boundedText(LuaValue.utf8(it),80) }, + "stars" to (job?.get("rating") ?: args["rating"]).takeIf { it!="clear" },"undo" to (job!=null),"can_mark" to (job==null), + "status" to LuaValue.str(if(job!=null) "✓ Marked as finished" else "Not marked as finished"), + "next" to next,"suggestion" to suggestion,"row_count" to (1+(if(next?.get("book_id")!=null) 1 else 0)+(if(suggestion!=null) 1 else 0)), + "freshness" to mapOf("saved" to d.isNotEmpty())) + } +} diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/RecommendedSettings.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/RecommendedSettings.kt new file mode 100644 index 00000000..89065494 --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/RecommendedSettings.kt @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion.server.bookorbit + +/** Local native binding identifiers only; no credentials or protocol objects leave the adapter. */ +internal object RecommendedSettings { + val items=listOf( + mapOf("id" to "bo.auto_sync","kind" to "connector","key" to "auto_sync","ours" to true,"label" to "Connector: Auto-sync"), + mapOf("id" to "bo.sync_forward","kind" to "connector","key" to "sync_forward","ours" to 2L,"label" to "Connector: When the library is further ahead"), + mapOf("id" to "bo.home","kind" to "connector","key" to "catalog_auto_open","ours" to "home","label" to "Connector: Make the library home"), + mapOf("id" to "ko.wifi_on","kind" to "ko","key" to "wifi_enable_action","ours" to "turn_on","stock" to "prompt","needs" to "wifi","required_by" to "wifi","label" to "KOReader: Action when Wi-Fi is off"), + mapOf("id" to "g.sync_sleep","kind" to "gesture","key" to "hold_top_right_corner","ours" to mapOf("orbit_sync_and_sleep" to true),"label" to "Gesture: hold top-right corner"), + mapOf("id" to "g.sync_all","kind" to "gesture","key" to "hold_top_left_corner","ours" to mapOf("bookorbit_sync_now" to true),"label" to "Gesture: hold top-left corner"), + mapOf("id" to "g.this_book","kind" to "gesture","key" to "one_finger_swipe_bottom_edge_right","ours" to mapOf("bookorbit_this_book" to true),"label" to "Gesture: swipe right along the bottom edge"), + mapOf("id" to "g.apps","kind" to "gesture","key" to "two_finger_swipe_north","ours" to mapOf("orbit_open_apps" to true),"needs" to "apps","label" to "Gesture: two-finger swipe up") + ).map { item -> + val labels=when(item["key"]) { + "sync_forward" -> mapOf("1" to "Ask","2" to "Silent","3" to "Don't sync") + "catalog_auto_open" -> mapOf("off" to "Off","filemanager" to "File browser","home" to "Library home") + "wifi_enable_action" -> mapOf("turn_on" to "Turn on","prompt" to "Ask","ignore" to "Ignore") + else -> mapOf("orbit_sync_and_sleep" to "BookSync: Sync and sleep","bookorbit_sync_now" to "BookSync: Sync all books", + "bookorbit_this_book" to "BookSync: This book","orbit_open_apps" to "BookSync: Other apps", + "increase_frontlight" to "Brighter frontlight","toggle_page_flipping" to "Page flipping") + } + item+mapOf("value_labels" to labels) + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/RecommendationPlanTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/RecommendationPlanTest.kt new file mode 100644 index 00000000..70ef0457 --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/RecommendationPlanTest.kt @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion + +import org.junit.Assert.* +import org.junit.Test + +class RecommendationPlanTest { + private val items=listOf(mapOf("id" to "local","kind" to "ko","key" to "action","ours" to "turn_on","stock" to "prompt","label" to "Wi-Fi action"), + mapOf("id" to "gesture","kind" to "gesture","key" to "tap","ours" to mapOf("sync" to true),"label" to "Tap")) + private fun obs(value:Any?=null,default:Any?=null,available:Boolean=true)=mapOf("available" to available,"current" to value,"default" to default) + private fun plan(observations:Map,record:Any?=null,backup:Any?=null,choices:Any?=null,lost:Boolean=false)= + RecommendationPlan.evaluate(items,mapOf("observations" to observations,"record" to record,"backup" to backup,"choices" to choices,"lost" to lost)) + @Test fun defaultsAreAppliedWithBackupAndCustomValuesBecomeConflicts() { + val result=plan(mapOf("local" to obs("prompt"),"gesture" to obs(mapOf("other" to true)))) + assertEquals(1,(result["writes"] as List<*>).size) + val states=(result["record"] as Map<*,*>)["items"] as Map<*,*> + assertEquals("applied",states["local"]);assertEquals("conflict",states["gesture"]) + assertEquals("prompt",((result["backup"] as Map<*,*>)["local"] as Map<*,*>)["prior"]) + } + @Test fun laterPassDoesNotResetUserChanges() { + val first=plan(mapOf("local" to obs(),"gesture" to obs())) + val second=plan(mapOf("local" to obs("ignore"),"gesture" to obs(mapOf("mine" to true))),first["record"],first["backup"]) + assertTrue((second["writes"] as List<*>).isEmpty()) + } + @Test fun missingSettingsWaitUntilTheirCapabilityReturns() { + val first=plan(mapOf("local" to obs(available=false),"gesture" to obs(available=false))) + val second=plan(mapOf("local" to obs(),"gesture" to obs()),first["record"],first["backup"]) + assertEquals(2,(second["writes"] as List<*>).size) + } + @Test fun explicitUseAndKeepHaveTheSameRulesInBothFrontends() { + val first=plan(mapOf("local" to obs("ignore"),"gesture" to obs(mapOf("mine" to true)))) + val second=plan(mapOf("local" to obs("ignore"),"gesture" to obs(mapOf("mine" to true))),first["record"],first["backup"],mapOf("local" to "ours","gesture" to "mine")) + assertEquals(1,(second["writes"] as List<*>).size) + assertEquals("kept",((second["record"] as Map<*,*>)["items"] as Map<*,*>)["gesture"]) + } + @Test fun bulkUseLeavesPreviouslyKeptItemsAloneButExplicitUseCanChangeThem() { + val first=plan(mapOf("local" to obs("ignore"),"gesture" to obs(mapOf("mine" to true)))) + val kept=plan(mapOf("local" to obs("ignore"),"gesture" to obs(mapOf("mine" to true))),first["record"],first["backup"],mapOf("all" to "mine")) + val bulk=plan(mapOf("local" to obs("ignore"),"gesture" to obs(mapOf("mine" to true))),kept["record"],kept["backup"],mapOf("all" to "ours")) + assertTrue((bulk["writes"] as List<*>).isEmpty()) + val explicit=plan(mapOf("local" to obs("ignore"),"gesture" to obs(mapOf("mine" to true))),kept["record"],kept["backup"],mapOf("local" to "ours")) + assertEquals(1,(explicit["writes"] as List<*>).size) + } + @Test fun failedNativeWritesAreNotCountedAsAppliedDuringAcknowledgement() { + val first=plan(mapOf("local" to obs(),"gesture" to obs())) + val ack=RecommendationPlan.evaluate(items,mapOf("ack" to true,"failed" to listOf("local","gesture"), + "record" to first["record"],"backup" to first["backup"])) + assertEquals(0,((ack["record"] as Map<*,*>)["unseen"] as Number).toInt()) + } + @Test fun undoRestoresOnlyWhileCurrentValueIsOurs() { + val first=plan(mapOf("local" to obs("prompt"),"gesture" to obs())) + val second=plan(mapOf("local" to obs("turn_on"),"gesture" to obs(mapOf("user" to true))),first["record"],first["backup"],mapOf("all" to "undo")) + val writes=second["writes"] as List<*> + assertEquals(1,writes.size);assertEquals("prompt",(writes[0] as Map<*,*>)["value"]) + } + @Test fun losingCapabilityUndoesOnlyTheAppliedStillMatchingValue() { + val first=plan(mapOf("local" to obs("prompt"),"gesture" to obs())) + val second=plan(mapOf("local" to obs("turn_on",available=false),"gesture" to obs(mapOf("user" to true),available=false)),first["record"],first["backup"],lost=true) + assertEquals(1,(second["writes"] as List<*>).size) + } + @Test fun snapshotAndDefinitionCountAreBounded() { + val result=plan(mapOf("local" to obs(),"gesture" to obs())) + assertTrue(LuaValue.encode(result).size<=16384) + try { RecommendationPlan.evaluate(List(9){items[0]},emptyMap());fail("missing budget") } catch(_:IllegalArgumentException) { } + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogSyncHandoffTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogSyncHandoffTest.kt new file mode 100644 index 00000000..274048a2 --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogSyncHandoffTest.kt @@ -0,0 +1,56 @@ +// 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 CatalogSyncHandoffTest { + private class Vault:AccountVault { + var data:Map?=null + override fun load()=data + override fun save(value:Map?) { data=value } + } + private fun fixture(existing:Boolean,check:(BookOrbitServerAdapter,ServerCredentials,String,File)->Unit) { + val root=Files.createTempDirectory("catalog-sync-handoff").toFile() + try { + val settings=File(root,"settings").also { it.mkdirs() } + val server="https://library.example/api/v1";val user="reader";val secret="a".repeat(32) + val legacyOwner="$user|$server" + val vault=Vault();val credentials=ServerCredentials(vault) + if(existing) credentials.set("sync",ServerCredentials.Login(server,user,secret,"user")) + val account=BookOrbitAccount(credentials.accountVault,object:BookOrbitAccount.Http { + override fun request(server:String,path:String,method:String,body:Map?,bearer:String?):BookOrbitAccount.Reply = error("migration is local") + },setupOnSignIn={false}) + val adapter=BookOrbitServerAdapter(credentials,account,object:BookOrbitServerAdapter.ConnectorTransport { + override fun request(server:String,path:String,method:String,body:Map?,headers:Map):BookOrbitAccount.Reply = error("migration cannot fetch") + override fun download(server:String,path:String,headers:Map,destination:File):Boolean = error("migration cannot download") + },legacyAccount={LegacyCoverSource.Account(legacyOwner,CacheWorker.Creds(server,user,secret))}, + actionJob={ c,owner,action,_,done -> assertEquals(server,c.server);assertEquals(user,c.user);assertEquals("initialize",action);done(mapOf("owner" to owner),null) }) + val document="b".repeat(32);val id="entry_${document}_100_1" + fun literal(file:File,data:Map) { file.parentFile?.mkdirs();file.writeBytes("return ".toByteArray()+LuaValue.encode(data)) } + literal(File(root,"settings.reader.lua"),mapOf("bookorbit" to mapOf("server_url" to server,"username" to user,"userkey" to secret))) + literal(File(settings,"bookorbit_sync_state.lua"),mapOf("account_identity" to "$server|$user","books" to mapOf(document to mapOf("file" to "/fixture/book.epub","bookId" to 7L)))) + literal(File(settings,"bookorbit-lifecycle-outbox/${id}_g1.lua"),mapOf("version" to 1,"id" to id,"generation" to 1,"payload_generation" to 1,"digest" to document,"acknowledged" to emptyMap())) + literal(File(settings,"bookorbit-lifecycle-outbox/${id}_payload_g1.lua"),mapOf("version" to 1,"id" to id,"digest" to document,"snapshot" to mapOf("digest" to document,"file" to "/fixture/book.epub","ts" to 100,"percentage" to .5))) + val before=adapter.owner()!! + val pending=File(settings,"orbit-cache/workflows/${BookOrbitLibrary.namespace(before)}.lua") + literal(pending,mapOf("migrated" to true,"finishes" to mapOf(document to mapOf("ready" to true)))) + JdbcSql(File(root,"journal.db")).use { sql -> assertEquals(1,adapter.importLifecycle(LifecycleQueue(sql),settings,true)) } + assertEquals(before,adapter.owner()) + assertTrue(pending.isFile) + assertEquals(pending.name,BookOrbitLibrary.namespace(adapter.owner()!!)+".lua") + adapter.catalogAction(adapter.owner()!!,"initialize",emptyMap()) { result,error -> assertNull(error);assertEquals(before,result!!["owner"]) } + check(adapter,credentials,legacyOwner,pending) + } finally { root.deleteRecursively() } + } + @Test fun adoptingLegacySyncKeepsCatalogCacheAndWorkflowProvenance()=fixture(false) { adapter,credentials,legacy,_ -> + assertEquals(legacy,adapter.owner());assertEquals(legacy,credentials.login("sync")!!.owner()) + assertEquals(true,(adapter.state()["catalog"] as Map<*,*>)["cachedDetail"]) + } + @Test fun anExistingManagedLoginKeepsItsOriginalNamespace()=fixture(true) { adapter,credentials,legacy,_ -> + assertNotEquals(legacy,adapter.owner());assertEquals(credentials.login("sync")!!.owner(),adapter.owner()) + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflowTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflowTest.kt new file mode 100644 index 00000000..6cad4a9c --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflowTest.kt @@ -0,0 +1,241 @@ +// 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 CatalogWorkflowTest { + private class World : AutoCloseable { + val external=Files.createTempDirectory("catalog-actions").toFile() + val root=File(external,"koreader/settings/orbit-cache") + val owner="reader|https://books.example" + val creds=CacheWorker.Creds("https://books.example","reader","synthetic-key") + val old=File(external,"books/old.epub").apply { parentFile!!.mkdirs();writeText("old bytes") } + val replacement="new book bytes".toByteArray() + val hash=File(external,"sample").let { it.writeBytes(replacement);CatalogWorkflow.partial(it).also { _ -> it.delete() } } + val worker=CacheWorker(root,{_,_,_,_->error("unexpected legacy HTTP")},log={},openSql={JdbcSql(it)},bookRoots=listOf(external)) + var reading=false;var current=true;var code=200;var downloadOk=true;var readStatus="unread";var clock=100L + var fileReference=70L + val calls=mutableListOf() + val transport=object:BookOrbitServerAdapter.ConnectorTransport { + override fun request(server:String,path:String,method:String,body:Map?,headers:Map):BookOrbitAccount.Reply { + calls.add("$method $path") + assertEquals("synthetic-key",headers["x-auth-key"]) + return BookOrbitAccount.Reply(code,if(method=="GET") detail() else emptyMap()) + } + override fun download(server:String,path:String,headers:Map,destination:File):Boolean { + calls.add("DOWNLOAD $path");if(downloadOk) destination.writeBytes(replacement);return downloadOk + } + } + fun detail()=mapOf("id" to 7L,"title" to "A synthetic book","authors" to listOf("Example writer"),"readStatus" to readStatus, + "files" to listOf(mapOf("id" to fileReference,"format" to "EPUB","role" to "primary","fileHash" to hash,"devicePath" to "Fiction/Next.epub","downloadVariant" to "audioless_epub","selection" to "revision"))) + init { + worker.store.own(owner) + File(root.parentFile,"bookorbit_sync_state.lua").writeBytes(LuaValue.encode(mapOf("account_identity" to "https://books.example|reader", + "books" to mapOf(CatalogWorkflow.partial(old) to mapOf("file" to old.path,"bookId" to 7L,"fileId" to 70L,"positionIncompatible" to true))))) + worker.store.putDetail(7,detail(),100) + } + fun run(action:String,args:Map = emptyMap())=CatalogWorkflow(worker,creds,owner,transport,{reading},{current},now={clock}).command(action,args) + fun state()=CatalogWorkflow.load(File(root,"workflows/${BookOrbitLibrary.namespace(owner)}.lua")) + fun jobs()=(state()["finishes"] as? Map<*,*>).orEmpty() + fun copies()=state()["copies"] as List<*> + fun events()=File(root,"events").listFiles().orEmpty().filter { it.extension=="lua" }.mapNotNull { LuaValue.parse(it.readBytes()) as? Map<*,*> } + fun mark()=run("finish.mark",mapOf("path" to old.path,"document" to CatalogWorkflow.partial(old),"complete" to true,"percentage" to 1.0)) + override fun close() { worker.store.close();external.deleteRecursively() } + } + @Test fun ownedSyncMatchSurvivesNativeLedgerRefreshAndPreparesOfflineFinish()=World().use { w -> + val matched=File(w.external,"books/matched.epub").apply { writeText("matched bytes") } + val hash=CatalogWorkflow.partial(matched) + w.run("local.observe",mapOf("reference" to 8L,"file_reference" to 80L,"path" to matched.path,"document" to hash)) + w.run("initialize") + w.reading=true + val prepared=w.run("finish.prepare",mapOf("path" to matched.path,"document" to hash,"local_only" to true)) + assertEquals(BookOrbitLibrary.key(w.owner,"book",8),prepared["key"]) + assertEquals(8L,prepared["reference"]);assertEquals(1,prepared["row_count"]) + assertTrue(LuaValue.encode(prepared).size<=16384);assertTrue(w.calls.isEmpty()) + assertTrue(w.events().none { it["kind"]=="download.saved" }) + } + @Test fun ownedSyncObservationRejectsAnOutsideFile()=World().use { w -> + val outside=Files.createTempFile("catalog-outside",".epub").toFile() + try { + try { w.run("local.observe",mapOf("reference" to 8L,"path" to outside.path,"document" to CatalogWorkflow.partial(outside)));fail("outside path") } + catch(_:IllegalArgumentException) { } + } finally { outside.delete() } + } + @Test fun nativeRecommendationLabelsAreProjectedAndAllEightRowsFitTheBudget() { + val definitions=RecommendedSettings.items + val observations=definitions.associate { it["id"] as String to mapOf("available" to true,"current" to it["ours"]) } + val result=RecommendationPlan.evaluate(definitions,mapOf("observations" to observations)) + assertEquals(8,(result["items"] as List<*>).size);assertTrue(LuaValue.encode(result).size<=16384) + val row=(result["items"] as List<*>).map { it as Map<*,*> }.single { it["id"]=="g.sync_all" } + assertEquals("BookSync: Sync all books",row["orbit"]) + } + @Test fun activeCatalogCommandKeepsAutomaticWifiOffWaitingAfterDequeue() { + assertFalse(AdapterWorker.busy()) + AdapterWorker.catalogActionWork { assertTrue(AdapterWorker.busy()) } + assertFalse(AdapterWorker.busy()) + } + @Test fun failedCatalogCommandAlwaysReleasesTheAutomaticWifiHold() { + try { AdapterWorker.catalogActionWork { assertTrue(AdapterWorker.busy());error("synthetic failure") };fail("expected failure") } + catch(_:IllegalStateException) { } + assertFalse(AdapterWorker.busy()) + } + // @fixture bookorbit/catalog-book.delivery-variants.json + @Test fun preparedDeliveryFixtureSelectsReadableVariantAndArtifactHash() { + val fixture=LuaValue.fromJson(File("../../../shared/fixtures/bookorbit/catalog-book.delivery-variants.json").readText()) as Map<*,*> + val prepared=fixture["with_variant"] as Map<*,*> + val source=fixture["without_variant"] as Map<*,*> + val selected=CopiesLogic.pick(prepared["files"] as List<*>,901L)!! + assertEquals(902L,selected["id"]);assertEquals("audioless_epub",selected["downloadVariant"]) + assertEquals("sel-902",selected["selection"]) + assertNotEquals((CopiesLogic.pick(source["files"] as List<*>,902L)!!)["fileHash"],selected["fileHash"]) + } + @Test fun anotherAccountCannotClaimLegacyQueuesByRefreshingTheLedgerFirst()=World().use { w -> + File(w.root,"copies").mkdirs() + File(w.root,"copies/ask.lua").writeBytes(LuaValue.encode(mapOf("owner" to w.owner,"books" to emptyList()))) + File(w.root.parentFile,"orbit-finish-queue.lua").writeBytes(LuaValue.encode(mapOf("jobs" to mapOf("old-intent" to mapOf("ready" to true,"book_id" to 7L))))) + val other="other|https://books.example" + w.worker.store.own(other) + CatalogWorkflow(w.worker,CacheWorker.Creds(w.creds.server,"other","synthetic-key"),other,w.transport).command("initialize",emptyMap()) + w.worker.store.own(w.owner);w.run("initialize") + assertTrue(w.jobs().containsKey("old-intent")) + } + @Test fun accountSpecificNativeStateDoesNotRequireARedundantOwnerProperty()=World().use { w -> + val primary=File(w.root.parentFile,"bookorbit_sync_state.lua") + val native=CatalogWorkflow.load(primary);primary.writeBytes(LuaValue.encode(mapOf("account_identity" to "other"))) + val identity="https://books.example|reader" + val digest=java.security.MessageDigest.getInstance("MD5").digest(identity.toByteArray()).joinToString("") { "%02x".format(it) } + File(w.root.parentFile,"bookorbit_sync_state_$digest.lua").writeBytes(LuaValue.encode(mapOf("books" to native["books"]))) + w.run("initialize") + assertEquals(7L,BookOrbitLibrary.localEntries(w.worker.store,w.owner)!!.single()["book_id"]) + } + @Test fun staleFinishEventCannotAcknowledgeANewerMark()=World().use { w -> + val hash=CatalogWorkflow.partial(w.old);w.mark();w.run("finish.leave",mapOf("document" to hash));w.run("finish.drain") + val old=w.events().single { it["kind"]=="finish.applied" } + assertEquals(true,w.run("finish.validate",mapOf("document" to hash,"token" to old["token"]))["apply"]) + w.mark() + assertEquals(false,w.run("finish.validate",mapOf("document" to hash,"token" to old["token"]))["apply"]) + w.run("finish.ack",mapOf("document" to hash,"token" to old["token"]));assertEquals(1,w.jobs().size) + } + @Test fun copyFetchUsesCompanionDeliveryAndVerifiedAtomicReplacement()=World().use { w -> + w.run("copies.check") + assertArrayEquals(w.replacement,w.old.readBytes()) + assertTrue(w.calls.any { it.contains("variant=audioless_epub") }) + assertTrue(w.calls.any { it.startsWith("DOWNLOAD") && it.contains("selection=revision") }) + val identity=w.events().single { it["kind"]=="copy.identity" } + assertEquals(w.hash,identity["after"]);assertEquals(1,w.copies().size) + val request=String(LuaValue.encode(mapOf("op" to "copies.state","limit" to 1,"bytes" to 16384)),Charsets.ISO_8859_1) + LibraryReadModel(w.worker.store,log={}).publish(w.owner,listOf(request)) + val snapshot=w.worker.store.db().query("SELECT body FROM library_views WHERE request=?",request) { it.bytes(0)!! }.single() + assertTrue(snapshot.size<=16384) + val counts=LuaValue.parse(snapshot) as Map<*,*>;assertEquals(1L,counts["pending"]);assertEquals(1L,counts["row_count"]) + w.run("copies.ack",mapOf("token" to identity["token"]));assertTrue(w.copies().isEmpty()) + } + @Test fun replacementToAnotherPrimaryFilePublishesTheNewHashAndFileReference()=World().use { w -> + w.fileReference=71L;w.worker.store.putDetail(7,w.detail(),101) + w.run("copies.check") + val event=w.events().single { it["kind"]=="copy.identity" } + assertEquals(71L,event["file_reference"]) + val local=BookOrbitLibrary.localEntries(w.worker.store,w.owner)!!.single { it["path"]==w.old.path } + assertEquals(w.hash,local["md5"]);assertEquals(71L,local["file_id"]) + } + @Test fun failedTransferKeepsOldBytesAndDurableQueue()=World().use { w -> + val before=w.old.readBytes();w.downloadOk=false;w.run("copies.check") + assertArrayEquals(before,w.old.readBytes());assertEquals(1,w.copies().size) + w.downloadOk=true;w.run("copies.check");assertArrayEquals(w.replacement,w.old.readBytes()) + } + @Test fun replacementNeverRunsWhileReadingOrForTheOpenBook()=World().use { w -> + w.reading=true;w.run("copies.check");assertTrue(w.calls.isEmpty()) + w.reading=false;w.run("copies.check",mapOf("open_path" to w.old.path));assertTrue(w.calls.isEmpty());assertEquals(1,w.copies().size) + } + @Test fun disabledCopiesDoNoNetworkOrReplacement()=World().use { w -> w.run("copies.check",mapOf("enabled" to false));assertTrue(w.calls.isEmpty()) } + @Test fun restartAfterRenameFinishesIdentityBeforeRetiringTheJob()=World().use { w -> + val before=CatalogWorkflow.partial(w.old) + w.run("initialize") + val dest=File(w.root,"workflows/${BookOrbitLibrary.namespace(w.owner)}.lua") + dest.writeBytes(LuaValue.encode(w.state()+mapOf("copies" to listOf(mapOf("path" to w.old.path,"book_id" to 7L,"file_id" to 70L,"old" to before,"new" to w.hash,"phase" to "transfer","token" to "recovered"))))) + w.old.writeBytes(w.replacement);w.run("copies.check") + assertTrue(w.calls.isEmpty());assertEquals("recovered",w.events().single { it["kind"]=="copy.identity" }["token"]) + } + @Test fun legacyQueuesAreCheckpointedOnceAndSurviveCacheReset()=World().use { w -> + File(w.root,"plugin-state.lua").writeBytes(LuaValue.encode(mapOf("copies" to mapOf("queue" to listOf(mapOf("path" to w.old.path,"book_id" to 7L)))))) + File(w.root.parentFile,"orbit-finish-queue.lua").writeBytes(LuaValue.encode(mapOf("jobs" to mapOf("legacy" to mapOf("hash" to "legacy","book_id" to 7L,"ready" to true,"phase" to "writeback"))))) + w.run("initialize");assertEquals(1,w.copies().size);assertEquals(1,w.jobs().size) + w.run("finish.ack",mapOf("document" to "legacy","token" to (w.jobs()["legacy"] as Map<*,*>)["token"]));w.run("initialize");assertTrue(w.jobs().isEmpty()) + w.worker.store.own("other");w.worker.store.own(w.owner);w.run("initialize");assertEquals(1,w.copies().size) + assertTrue(File(w.root.parentFile,"orbit-finish-queue.lua").isFile) + } + @Test fun otherAccountCannotRunCapturedWork()=World().use { w -> + w.current=false + try { w.run("copies.check");fail("owner changed") } catch(e:ServerFailure) { assertEquals("canceled",e.kind) } + assertTrue(w.calls.isEmpty()) + } + @Test fun finishWaitsForLeaveAndNativeOutboxThenStatusRatingWritebackAck()=World().use { w -> + val hash=CatalogWorkflow.partial(w.old);w.mark();w.run("finish.drain");assertTrue(w.calls.isEmpty()) + w.run("finish.rate",mapOf("document" to hash,"rating" to 4L));w.run("finish.leave",mapOf("document" to hash));w.run("finish.drain") + assertEquals(listOf("GET","PUT","PUT"),w.calls.map { it.substringBefore(' ') }) + val ev=w.events().single { it["kind"]=="finish.applied" };assertEquals(4L,ev["rating"]);assertEquals(true,ev["complete"]) + assertTrue(w.jobs().isNotEmpty());w.run("finish.ack",mapOf("document" to hash,"token" to ev["token"]));assertTrue(w.jobs().isEmpty()) + } + @Test fun undoCancelsUnsentFinish()=World().use { w -> + w.mark();w.run("finish.mark",mapOf("document" to CatalogWorkflow.partial(w.old),"complete" to false));assertTrue(w.jobs().isEmpty());w.run("finish.drain");assertTrue(w.calls.isEmpty()) + } + @Test fun finishServerErrorBacksOffAndManualRetryKeepsRating()=World().use { w -> + val hash=CatalogWorkflow.partial(w.old);w.mark();w.run("finish.leave",mapOf("document" to hash));w.code=500;w.run("finish.drain") + assertEquals(1L,(w.jobs()[hash] as Map<*,*>)["attempts"]) + val count=w.calls.size;w.run("finish.drain");assertEquals(count,w.calls.size) + w.code=200;w.run("finish.drain",mapOf("manual" to true));assertTrue(w.events().any { it["kind"]=="finish.applied" }) + } + @Test fun authPreservesFinishAndPermanentRefusalDropsIt()=World().use { w -> + val hash=CatalogWorkflow.partial(w.old);w.mark();w.run("finish.leave",mapOf("document" to hash));w.code=401;w.run("finish.drain");assertEquals(1,w.jobs().size) + w.code=404;w.run("finish.drain");assertTrue(w.jobs().isEmpty()) + } + @Test fun readingNeverDrainsFinishOrFetchesDetail()=World().use { w -> w.mark();w.reading=true;w.run("finish.drain");w.run("finish.prepare",mapOf("path" to w.old.path));assertTrue(w.calls.isEmpty()) } + @Test fun deliberateRemoteStatusIsKeptWhileRatingIsSent()=World().use { w -> + val hash=CatalogWorkflow.partial(w.old);w.mark();w.run("finish.leave",mapOf("document" to hash));w.readStatus="abandoned" + w.run("finish.rate",mapOf("document" to hash,"rating" to 5L));w.run("finish.drain") + assertFalse(w.calls.any { it.endsWith("read-status") });assertTrue(w.calls.any { it.endsWith("rating") }) + } + @Test fun deferredDownloadUsesCompanionTransportAndKeepsFolderLayout()=World().use { w -> + val key=BookOrbitLibrary.key(w.owner,"book",7) + w.run("finish.download",mapOf("key" to key,"later" to true));assertTrue(w.calls.isEmpty()) + w.run("finish.drain");assertTrue(File(w.external,"books/Fiction/Next.epub").isFile) + assertTrue(w.events().any { it["kind"]=="download.saved" });assertTrue((w.state()["downloads"] as? Map<*,*>).orEmpty().isEmpty()) + } + @Test fun explicitNativeCatalogDestinationUsesNeutralReferenceAndPublishesLocalLedgerImmediately()=World().use { w -> + val target=File(w.external,"books/chosen.epub") + val result=w.run("finish.download",mapOf("reference" to 7L,"destination" to target.path,"file_reference" to 70L)) + assertEquals(target.path,result["local_path"]);assertArrayEquals(w.replacement,target.readBytes()) + assertEquals(target.path,BookOrbitLibrary.localPaths(w.worker.store,w.owner)!![7L]) + w.run("finish.download",mapOf("reference" to 7L,"destination" to target.path,"file_reference" to 70L)) + assertEquals(1,w.calls.count { it.startsWith("DOWNLOAD") }) + // The native event reader can be delayed by foreground reading or a process restart. + w.run("initialize") + assertTrue(BookOrbitLibrary.localEntries(w.worker.store,w.owner)!!.any { it["path"]==target.path }) + assertTrue(w.events().any { it["kind"]=="download.saved" && it["path"]==target.path }) + } + @Test fun finishedSheetReadsOnlyBoundedSnapshotWithNextAndSuggestion()=World().use { w -> + w.run("initialize") + w.worker.store.putDetail(7,w.detail()+mapOf("seriesId" to 1L,"seriesIndex" to 1L, + "seriesMembers" to (2L..300L).map { mapOf("id" to it+10,"title" to "Book $it","seriesIndex" to it,"readStatus" to "unread") }, + "relatedSections" to listOf(mapOf("id" to "author","books" to (500L..800L).map { mapOf("id" to it,"title" to "Suggestion $it") }))),100) + val result=FinishLogic.snapshot(w.worker.store,w.owner,mapOf("path" to w.old.path)) + assertEquals(3,result["row_count"]);assertNotNull(result["next"]);assertNotNull(result["suggestion"]) + assertTrue(LuaValue.encode(result).size<=16384);assertFalse(result.containsKey("seriesMembers"));assertTrue(w.calls.isEmpty()) + val request=String(LuaValue.encode(mapOf("op" to "reader.finish","path" to w.old.path,"limit" to 2,"bytes" to 16384)),Charsets.ISO_8859_1) + LibraryReadModel(w.worker.store,log={}).publish(w.owner,listOf(request)) + val bounded=w.worker.store.db().query("SELECT body FROM library_views WHERE request=?",request) { LuaValue.parse(it.bytes(0)!!) as Map<*,*> }.single() + assertEquals("budget",bounded["error"]) + } + @Test fun nextGapIsNotSkippedAndReadSuggestionsAreExcluded()=World().use { w -> + w.run("initialize");w.worker.store.putDetail(7,w.detail()+mapOf("seriesId" to 1L,"seriesIndex" to 1L, + "seriesMembers" to listOf(mapOf("id" to 9L,"seriesIndex" to 3L,"readStatus" to "read")), + "relatedSections" to listOf(mapOf("id" to "author","books" to listOf(mapOf("id" to 9L,"title" to "Read"),mapOf("id" to 10L,"title" to "Unread"))))),100) + val result=FinishLogic.snapshot(w.worker.store,w.owner,mapOf("path" to w.old.path)) + assertEquals("Book 2 isn't in your library",(result["next"] as Map<*,*>)["line"]) + assertEquals("Unread",(result["suggestion"] as Map<*,*>)["title"]) + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesTest.kt index c62b82a5..212aa97d 100644 --- a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesTest.kt +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesTest.kt @@ -14,37 +14,12 @@ class CopiesTest { private fun files(id: Long, hash: String) = listOf(sortedMapOf("id" to id, "fileHash" to hash)) - @Test fun preparationFetchesDeliveryVariantAndSamplesTheFileInTheWorker() { - val base = Files.createTempDirectory("copy-prepare").toFile() - val root = File(base, "orbit-cache") - try { - val file = File(base, "Books/book.epub").apply { parentFile!!.mkdirs(); writeText("synthetic book bytes") } - var requested = "" - CacheWorker(root, { url, _, _, _ -> - requested = url - CacheWorker.Reply(200, "{\"id\":7,\"title\":\"Synthetic\",\"files\":[{\"id\":70,\"fileHash\":\"new\"}]}".toByteArray()) - }, log = {}, openSql = { JdbcSql(it) }, bookRoots = listOf(base)).let { w -> - w.prepareCopy(mapOf("path" to file.path, "book_id" to 7L), - "/koreader/plugin/catalog/books/${MirrorLogic.SENTINEL}?variant=audioless_epub", - CacheWorker.Creds("https://books.example", "reader", "key")) - assertEquals("https://books.example/koreader/plugin/catalog/books/7?variant=audioless_epub", requested) - val ev = LuaValue.parse(File(root, "events").listFiles()!!.single { it.extension == "lua" }.readBytes()) as Map<*, *> - assertEquals("copy_prepared", ev["kind"]) - assertEquals(7L, (ev["detail"] as Map<*, *>)["id"]) - val hash = java.security.MessageDigest.getInstance("MD5").digest(file.readBytes()).joinToString("") { "%02x".format(it) } - assertEquals(hash, ev["md5"]) - } - } finally { base.deleteRecursively() } - } - @Test fun detailPersistenceRunsFromTheCompanionSnapshot() { val base = Files.createTempDirectory("detail-persist").toFile() try { CacheWorker(File(base, "orbit-cache"), { _, _, _, _ -> CacheWorker.Reply(0) }, log = {}, openSql = { JdbcSql(it) }).let { w -> w.store.putDetail(7, mapOf("id" to 7L, "title" to "Synthetic", "files" to files(70, "hash")), 1) w.rememberDetail(7) - w.savePluginState(String(LuaValue.encode(mapOf("detail_variant" to "original")), Charsets.ISO_8859_1)) - assertEquals("original", (LuaValue.parse(File(base, "orbit-cache/plugin-state.lua").readBytes()) as Map<*, *>)["detail_variant"]) val saved = LuaValue.parse(File(base, "orbit-detail-cache.lua").readBytes()) as Map<*, *> assertEquals("Synthetic", (((saved["books"] as Map<*, *>)["7"]) as Map<*, *>)["title"]) } @@ -81,12 +56,11 @@ class CopiesTest { "eob" to sortedMapOf("2" to sortedMapOf("files" to files(20, "old2"), "saved_at" to 100L), "4" to sortedMapOf("files" to files(40, "cur4"), "saved_at" to 100L)), "owner" to owner, "server" to server, "detail_template" to template, "sentinel" to "987654321"))) - w.copies("test") - val ev = File(root, "events").listFiles()!!.filter { it.extension == "lua" }.single().let { LuaValue.parse(it.readBytes()) as Map<*, *> } - assertEquals("copies", ev["kind"]) - assertEquals(3L, ev["checked"]) - assertEquals(listOf("${books.path}/b.epub"), (ev["found"] as List<*>).map { (it as Map<*, *>)["path"] }) - assertEquals("the changed copy no longer on the reader", 1L, ev["gone"]) + val ask=LuaValue.parse(File(root,"copies/ask.lua").readBytes()) as Map<*,*> + val result=w.changedCopies((ask["books"] as List<*>).map { it as Map<*,*> },ask["eob"] as Map<*,*>) + assertEquals(3,result.checked) + assertEquals(listOf("${books.path}/b.epub"),result.found.map { it["path"] }) + assertEquals(1,result.gone) root.deleteRecursively() } } diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LibraryTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LibraryTest.kt index 6e82aa28..9c6c5272 100644 --- a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LibraryTest.kt +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LibraryTest.kt @@ -41,6 +41,19 @@ class LibraryTest { "tags" to listOf("Space"), "status" to "reading", "want_to_read" to true, "on_device" to true, "pages" to 200, "rating" to 4, "added" to "2026-11-01", "rank" to 0, "last_read" to "2026-11-03") + @Test fun connectorSelectionGroupingKeepsTheOriginalSubsetAndBoundsNestedRows() { + store().use { st -> + seed(st) + // The same saved query windows used by the native list, not a Lua-held catalog. + for(i in 1L..5L) st.putItem(mapOf("id" to i,"title" to "Book $i","authors" to listOf(if(i<4) "A" else "B")),100) + val source=mapOf("kind" to "selection","selection" to mapOf("ids" to "2,4")) + val result=read(st,mapOf("op" to "groups","source" to source,"query" to mapOf("group" to "author"),"limit" to 8)) + assertEquals(2L,(result["total"] as Number).toLong()) + assertTrue(LuaValue.encode(result).size<=16384) + assertTrue((result["row_count"] as Number).toInt()<=8) + val text=result.toString();assertTrue(text.contains("Book 2"));assertTrue(text.contains("Book 4"));assertFalse(text.contains("Book 1")) + } + } @Test fun nestedRowsCannotUnderreportTheInheritedCallerBudget() { store().use { st -> val adapter=object : ServerAdapter { diff --git a/android/docs/INTERFACE.md b/android/docs/INTERFACE.md index 7e16a2bf..4880a4fb 100644 --- a/android/docs/INTERFACE.md +++ b/android/docs/INTERFACE.md @@ -49,10 +49,9 @@ companion's "KOReader patch installed" row uses it when it can't read the file). | `SLEEP_REFRESH` | `reason`, `from`, `rules`, `open_id`, `every`, `storage_limit_mb`, `server`, `user`, `userkey`; or `reason`, `scopes_only=1` and the login | Cap `cache_worker`: refresh the sleep screen's pool on the worker thread (`SleepPoolBuilder`): Leave out's member lists once a day, the shuffle bag, the books checked and their covers fetched by ETag, then `pool.json`, `covers/`, `bag.lua`, `leave_out.lua` and `scopes.json` written and the picture redrawn. With `scopes_only` it writes the pickers' files only (`scopes.json`, `tags.json`), never a pool. Each refresh counts the tags again. Answers with a `sleep_pool` event. Needs no service. The login is never written or logged. | | `SQLITE_STRESS` | `seconds` (default 120) | Debug (docs/design/sqlite-cache.md "Stress test"): writes `orbit-cache/stress.db` nonstop for that long, one 100-row page per transaction, then logs `sqlite-stress writer: …` and writes `orbit-cache/stress-writer.lua` `{writes, errors, max_wait_ms, integrity, first_error, at}`. No login, no service. | | `SLEEP_POOL` | `reason`, `wake` | Companion cap `sleep_screen`: the files in `koreader/settings/orbit-sleep/` changed (below). The picture sink redraws `Pictures/Orbit/sleep.png`; the screen saver reads them at the next sleep. With `wake` = `"1"` (reason `wake`): KOReader resumed after a real sleep (the screen went off, not an app switch); with Every sleep the picture moves on for the next sleep, once per wake (the service's screen-on counts as the same wake). Needs no service. | -| `PATCH` | `reason`, `id` (a book id, or empty), `fields` (a Lua literal of the changed fields, or empty), `stale_home` (`"1"`/`"0"`); or `wipe` = `"1"`; `remember_id`, `plugin_state`; `old_hash`, `new_hash`, `copy_path` | Cap `cache_worker`: a write the plugin made (`Cache.writeEffect`), patched into the saved book, the lists that name it and other saved replies; Home marked stale. `wipe` empties the database. In order with the checks. `plugin_state` atomically persists the in-memory plugin state; `remember_id` persists the saved detail for the end-of-book sheet; copy identity migration updates sidecar/statistics in the worker. No login. Needs no service. | +| `PATCH` | `reason`, `library_batch`, `owner`, `drain_events`, `events_ack`, `board_year`, `board_key`, `board_now` | Bounded neutral read-model batches, durable mailbox acknowledgement and the remaining calendar compatibility projection. Copy/finish queues and their identity migration use `catalog.action`; no plugin state or raw copy-detail template is accepted. | | `STORAGE` | `reason`, `limit` (bytes, empty: none), `cover_dir`, `mirror_covers` (`"1"`/`"0"`) | Cap `cache_worker`: count everything BookSync stores (`orbit.db` and the cover folder) and, over `limit`, remove what StorageLogic says: the oldest browsing replies and plain covers first, then covers saved for offline, never lists and books saved for offline nor Home. The companion removes them itself and answers with a `storage` event. No login. Needs no service. | | `PATCH` (0.12 library) | `library_batch` (Lua literal array of encoded neutral requests, ≤16 entries, ≤128 KiB), `owner` | Same caller-checked worker queue. No login or network. Materializes bounded results in `library_views` in the existing owned SQLite database, with owner checks before and inside publication. The plugin reads ready results through `Library`; filtering, grouping, sorting, counts and joins stay in Kotlin. See [F12-A notes](../../docs/design/booksync-home/F12-A-NOTES.md) for operations, budgets and pending/empty states. | -| `COPIES` | `reason`, `ask` (Lua literal); or `prepare` (one queued copy), `template`, `server`, `user`, `userkey` | Cap `cache_worker`: which copies on the reader changed in the library (docs/design/keep-copies-current.md), from the in-memory `ask`, persisted by the companion in `koreader/settings/orbit-cache/copies/ask.lua` (below): the newer of the end-of-book cache's, the cache's and the database's saved details per book, compared with each copy's hash, and only copies whose file is on the reader. Answers with a `copies` event; the plugin queues and downloads them. `prepare` fetches the delivery detail using the supplied template and samples the existing file hash, answering with `copy_prepared` (`path`, `detail`, `md5`, or `err`). Only preparation needs a login. Needs no service. | | `UPDATE` | `reason` | The plugin's "Check for updates" (it downloads nothing itself: the plugin and the companion ship together). A check by hand, as from the companion's Update page: a newer release installs the companion and then the plugin of that release; an up-to-date companion installs the plugin of its own release when the one on disk is older (PatchInstaller). Every mode; needs no service. | | `SLEEP_NOW` | `reason` (`sync_and_sleep` or `sync_and_sleep_failed`) | `DevicePolicyManager.lockNow()` when the device-admin approval (`force-lock` only) is granted; otherwise logged and the screen stays on. At most one per 5 s. (The accessibility `GLOBAL_ACTION_LOCK_SCREEN` fallback is not in companion v1; add it only if the firmware blocks device admin.) | @@ -113,9 +112,9 @@ read-only. The small files beside it are Lua literals in the cache's format (`Ca | File | Written by | Holds | |---|---|---| | `orbit.db`, `.nomedia` | companion | lists by position naming books by id, each book once (its list item, detail and search text), other replies by key, the covers kept, the Full refresh's jobs, `meta` (owner, detail template, storage totals, the run's %) | -| `plugin-state.lua` | companion, from `PATCH.plugin_state` | the detail variant it reads and the copies queue | -| `events/.lua` | companion (private spool; never enumerated by the plugin) | a check's answer: `{kind = "checked", key, changed, at}`, `{…, unchanged, saved}` or `{…, err}`; a sleep pool refresh: `{kind = "sleep_pool", why, items, kept, probed, left_out, unknown, skipped, carried, retired, every, fallback, listed, scopes}` (or `scopes_only`, or `err`); a copies lookup: `{kind = "copies", why, checked, found = {{md5, path, book_id, file_id, why}}, gone}`; a storage count: `{kind = "storage", why, totals, removed = {cache, cover, mirror_cover}, used, after, limit}` | -| `copies/ask.lua` | companion, from each `COPIES.ask` | `books` (`md5`, `path`, `book_id`, `file_id`, `incompatible`), `eob` (book id -> `files`, `saved_at`), `owner`, `server`, `detail_template`, `sentinel` | +| `plugin-state.lua` | retained legacy source, companion reads only | the old copies queue remains intact after its account-scoped workflow checkpoint | +| `events/.lua` | companion (private spool; never enumerated by the plugin) | a check's answer: `{kind = "checked", key, changed, at}`, `{…, unchanged, saved}` or `{…, err}`; a sleep pool refresh: `{kind = "sleep_pool", why, items, kept, probed, left_out, unknown, skipped, carried, retired, every, fallback, listed, scopes}` (or `scopes_only`, or `err`); neutral copy identity, download-link and finish writeback acknowledgements; a storage count: `{kind = "storage", why, totals, removed = {cache, cover, mirror_cover}, used, after, limit}` | +| `copies/ask.lua` | companion | account-scoped local file ledger, refreshed from persisted native state; never constructed or decoded by Lua | | covers, in the plugin's thumbnail folder | companion | `.jpg` and `.etag`, as the plugin names them | W27 startup maintenance uses `PATCH` variants on the same required worker: @@ -124,8 +123,6 @@ W27 startup maintenance uses `PATCH` variants on the same required worker: only that batch's spool files and atomically publishes the next batch (at most eight events, under 64 KiB). The plugin reads one fixed filename; duplicate ids are ignored. Child-process metadata travels with the subprocess result, with no directory spool or UI scan. -- `old_hash`, `new_hash` copies a hash sidecar on the worker. Only two 32-character lowercase - hex hashes are accepted; paths derive from KOReader's fixed `hashdocsettings` folder. - `board_year` (Lua literal), `board_key`, `board_now` computes the dashboard calendar and reads local daily statistics on the worker; a `board_year` event returns `{key, data={values,start,today}}`. The UI uses the last snapshot while the next one is pending. @@ -553,8 +550,8 @@ counts nested books/names and its stats row, and materializes one batched reques The Lua connector translates display records into its existing widget inputs; it never receives backend response JSON. Cached windows open offline without asking to connect. New materializations redraw only their still-visible initiating view. -Remaining grouping, copies, recommendations and end-of-book transport are separate -follow-up slices. No replacement sync/lifecycle writer is enabled here. +Grouping, copies, recommendations and end-of-book now use companion commands/projections +(see below). No replacement sync/lifecycle writer is enabled here. JNI replies include `id`, `body`, `owner` and `pending` in addition to the original status/proof fields. Bundle strings carry Unicode text; encoded Lua model values @@ -562,3 +559,35 @@ convert through UTF-8 exactly once, with 8 KiB request and 16 KiB result byte li The model's ISO-8859-1 byte-string convention is only for model values/local files, not Java Bundle text. `SERVER_STATE` accepts `reload="1"` for a lifecycle refresh of cached identity; polling uses `reload="0"` and performs no server transport. + + +### Companion-owned catalog actions (0.12, F12-Q2 step 4) + +`SERVER_COMMAND` operation `catalog.action` accepts one opaque `owner`, a neutral `action` +and bounded arguments. The existing adapter resolves credentials privately and queues work +on the sole cache writer. Supported actions are `initialize`, `copies.check`, `copies.ack`, +`finish.prepare`, `finish.mark`, `finish.rate`, `finish.leave`, `finish.drain`, `finish.validate`, +`finish.ack` and `finish.download` (including `later=true`). Reader actions identify one local +`path`/`document`; download actions carry an opaque book `key`. No URL, backend detail JSON, +auth header or native query template comes from Lua. + +Account-scoped files under `orbit-cache/workflows/` retain copy/finish jobs and deferred +downloads independently of cache resets. Legacy queue files remain intact after checkpointing; +a durable source-owner claim prevents cross-account migration. Copy transfer verifies the +prepared delivery artifact before atomic rename and checkpoints identity repair for replay. +Finish status/rating follows the owned sync writer, with backoff and deliberate remote +status precedence; token-validated writeback acknowledgement cannot retire a newer mark. +The owned lifecycle journal remains the sole position writer. Its completed match phase sends an internal `local.observe` action to retain catalog file identity. `finish.prepare` with `local_only=true` returns one bounded local identity row without network. + +`reader.finish` is a ready-to-draw summary plus at most two selected cards (three charged rows, +16 KiB). `copies.state` is one local count row. Native list selections use the existing bounded +`groups`/`window` projections through the owned list UI; the companion interprets the selection. +Screen/widget budgets are declared in `logic/budgets.lua`; paints use zero network/forks and +at most one batched materialization request, with info-level spans. + +`SERVER_COMMAND` operation `settings.recommendations` supplies eight neutral native-setting +binding descriptors or evaluates eight observations and review choices. Its bounded snapshot +contains decisions, compare-before-write operations, backup/Undo state, labels and counts. +Only KOReader applies native settings; the companion writes `orbit-recommended.json` for its +review page. Review paints read the lifecycle-cached library snapshot with zero round-trips. +Small queue checkpoints remain available while reading; background transfers pause. diff --git a/android/koreader/orbit.koplugin/ko/base.lua b/android/koreader/orbit.koplugin/ko/base.lua index 81de0825..53ec3e8b 100644 --- a/android/koreader/orbit.koplugin/ko/base.lua +++ b/android/koreader/orbit.koplugin/ko/base.lua @@ -43,3 +43,11 @@ function fmt(seconds) end --------------------------------------------------------------------------------------------- + +-- Shared native-hook chain, once per feature. No transport or catalog interpretation. +function wrap(Cls,name,make,feature) + local stock=rawget(Cls,"__orbit_stock") or {};rawset(Cls,"__orbit_stock",stock) + local key=feature and (feature..":"..name) or name + if stock[key] then return end + stock[key]=Cls[name];Cls[name]=make(stock[key]) +end diff --git a/android/koreader/orbit.koplugin/ko/companion.lua b/android/koreader/orbit.koplugin/ko/companion.lua index d0a23c56..0e06f532 100644 --- a/android/koreader/orbit.koplugin/ko/companion.lua +++ b/android/koreader/orbit.koplugin/ko/companion.lua @@ -27,7 +27,6 @@ Companion.ACTION = { -- The storage limit: the companion counts and removes (OC.storageCount). STORAGE = Companion.PACKAGE .. ".action.STORAGE", -- Keep copies current: the companion finds the changed copies (Copies.ask). - COPIES = Companion.PACKAGE .. ".action.COPIES", -- The sleep screen's pool: the companion lists, checks and fetches the covers (Sleep.refresh). SLEEP_REFRESH = Companion.PACKAGE .. ".action.SLEEP_REFRESH", -- Debug: the shared-storage SQLite stress test's writer (ko/sqlite_stress.lua). diff --git a/android/koreader/orbit.koplugin/ko/endsheet.lua b/android/koreader/orbit.koplugin/ko/endsheet.lua index 42b7ebaf..07102214 100644 --- a/android/koreader/orbit.koplugin/ko/endsheet.lua +++ b/android/koreader/orbit.koplugin/ko/endsheet.lua @@ -55,14 +55,14 @@ end function EndSheet:onTapAnywhere(_arg, ges) local y0 = self.screen_h - (self.sheet_h or 0) if ges and ges.pos and ges.pos.y < y0 then - Server.endAction("back") + Library.endAction("back") return true end return false end function EndSheet:onClose() - Server.endAction("back") + Library.endAction("back") return true end @@ -80,32 +80,32 @@ function EndSheet:rows() local ui, b = self.ui, self.book local function add(r) table.insert(rows, r) end local status = { kind = "status", text = m.status } - if m.undo then status.label, status.action = "Undo", function() Server.endAction("undo",ui, b) end - elseif m.can_mark then status.label, status.action = "Mark as finished", function() Server.endAction("mark",ui, b) end end + if m.undo then status.label, status.action = "Undo", function() Library.endAction("undo",ui, b) end + elseif m.can_mark then status.label, status.action = "Mark as finished", function() Library.endAction("mark",ui, b) end end add(status) add({ kind = "title", text = m.title }) - if m.author then add({ kind = "author", text = "by " .. m.author .. " ›", action = function() Server.endAction("author",ui, b, m.author) end }) end + if m.author then add({ kind = "author", text = "by " .. m.author .. " ›", action = function() Library.endAction("author",ui, b, m.author) end }) end if m.series_line then add({ kind = "series", text = m.series_line }) end for n = 1, 5 do - add({ kind = "star", n = n, text = (m.stars and n <= m.stars) and "★" or "☆", action = function() Server.endAction("star",ui, b, n) end }) + add({ kind = "star", n = n, text = (m.stars and n <= m.stars) and "★" or "☆", action = function() Library.endAction("star",ui, b, n) end }) end add({ kind = "hint", text = m.stars and "Tap a star · tap it again to clear" or "Tap a star to rate it" }) - add({ kind = "review", text = "Review ›", action = function() Server.endAction("review",ui) end }) + add({ kind = "review", text = "Review ›", action = function() Library.endAction("review",ui) end }) local function card(c) local busy = cs and cs.book_id == c.book_id if busy and cs.failure == "failed" then add({ kind = "notice", text = "Couldn't connect · your finish is saved and will be sent later" }) - add({ kind = "button", text = "Try again", action = function() Server.endAction("retry",ui, b, c.book_id, c.title) end }) - add({ kind = "button", text = "Get it at the next sync", secondary = true, action = function() Server.endAction("later",ui, b, c.book_id, c.title) end }) + add({ kind = "button", text = "Try again", action = function() Library.endAction("retry",ui, b, c.book_id, c.title) end }) + add({ kind = "button", text = "Get it at the next sync", secondary = true, action = function() Library.endAction("later",ui, b, c.book_id, c.title) end }) return elseif busy and cs.failure == "error" then add({ kind = "notice", text = "Download failed: " .. tostring(cs.err or "server error") }) - add({ kind = "button", text = "Try again", action = function() Server.endAction("retry",ui, b, c.book_id, c.title) end }) + add({ kind = "button", text = "Try again", action = function() Library.endAction("retry",ui, b, c.book_id, c.title) end }) return end add({ kind = "card", text = tostring(c.title), sub = busy and cs.text or c.sub, book = c.book, label = busy and cs.text and "" or (c.action == "open" and "Open" or "Download & open"), - action = function() Server.endAction("book",ui, b, c.book_id, c.title) end }) + action = function() Library.endAction("book",ui, b, c.book_id, c.title, c.local_path) end }) end local nxt = m.next if nxt then @@ -117,18 +117,14 @@ function EndSheet:rows() add({ kind = "label", text = s.line }) card(s) end - add({ kind = "footer", text = "‹ Back to book", action = function() Server.endAction("back") end }) - add({ kind = "footer", text = "Home", action = function() Server.endAction("home",ui) end }) + add({ kind = "footer", text = "‹ Back to book", action = function() Library.endAction("back") end }) + add({ kind = "footer", text = "Home", action = function() Library.endAction("home",ui) end }) return rows end -- The cover for a card: the plugin's cached thumbnail when the catalog has one, else nil. local function coverPath(book) - local p = serverPlugin(liveUI()) - local cat = p and p.catalog_browser - if not (cat and book and Compat.callable(cat.thumbnailDisplay)) then return nil end - local okc, path = pcall(cat.thumbnailDisplay, cat, book) - return okc and type(path) == "string" and path or nil + return type(book)=="table" and book.cover_path or nil end -- One row's widget at width w and planned height h. @@ -239,6 +235,7 @@ function EndSheet:rowWidget(block, w, h, mt) end function EndSheet:build() + local finish=Budgets.span("end-of-book.draw",now_s,log) local Blitbuffer = require("ffi/blitbuffer") local Geom = require("ui/geometry") local BottomContainer = W("container/bottomcontainer") @@ -282,4 +279,5 @@ function EndSheet:build() } self.rule_widget = rule self[1] = BottomContainer:new{ dimen = Geom:new{ w = self.screen_w, h = self.screen_h }, self.frame } + finish() end diff --git a/android/koreader/orbit.koplugin/ko/finish.lua b/android/koreader/orbit.koplugin/ko/finish.lua new file mode 100644 index 00000000..6db21b3b --- /dev/null +++ b/android/koreader/orbit.koplugin/ko/finish.lua @@ -0,0 +1,139 @@ +-- SPDX-License-Identifier: AGPL-3.0-or-later +-- Reader hooks only. Catalog decisions, outboxes and downloads belong to the companion. +FinishUI={session={},jobs={},intent={},page_digests=setmetatable({}, {__mode="k"})} +local function book(ui) return Library.nativeReader and Library.nativeReader(ui) end +local function dispatch(action,b,extra,done) + local args={path=b and b.file,document=b and b.digest,key=b and type(b.key)=="string" and b.key} + for k,v in pairs(extra or {}) do args[k]=v end + return Library.catalogAction(action,args,done or function() end) +end +function FinishUI.onMarked(ui) + local b=book(ui);if not b then return end + FinishUI.intent[b.digest]=(FinishUI.intent[b.digest] or 0)+1 + local complete=b.summary.status=="complete" + FinishUI.jobs[b.digest]=complete and {final_pos={percentage=b.percentage}} or nil + FinishUI.session[b.digest]={forward=0,released=not complete} + dispatch("finish.mark",b,{complete=complete,percentage=b.percentage}) + if Library.noteReaderMark then Library.noteReaderMark(b) end +end +function FinishUI.onLeave(ui) + local b=book(ui);if not b then return end + if Library.noteReaderLeave then Library.noteReaderLeave(b) end + if b.summary.status=="complete" or FinishUI.jobs[b.digest] or FinishUI.sheet then dispatch("finish.leave",b) end +end +function FinishUI.leaveForHome(ui) + local had=FinishUI.sheet~=nil;FinishUI.closeSheet() + ui=ui or liveUI() + FinishUI.onLeave(ui) + local b=book(ui) + if b and FinishUI.jobs[b.digest] and not FinishUI.sending then + FinishUI.sending=true + -- Home paints first; native writer/network setup never runs on its render path. + UIManager:nextTick(function() Library.finishCurrent(function() FinishUI.sending=nil end) end) + end + return had +end +function FinishUI.hold(digest,fraction,status) + if status~="complete" or type(fraction)~="number" then return false end + local j=FinishUI.jobs[digest];local s=FinishUI.session[digest] or {} + local final=j and j.final_pos and tonumber(j.final_pos.percentage) or 1 + return Finish.holdPush(final*100,fraction*100,s.forward,s.released) +end +function FinishUI.onPage(ui,page) + local b=FinishUI.page_digests[ui] + if not b or not ui.document or b.file~=ui.document.file then return end + local s=FinishUI.session[b.digest] or {forward=0};FinishUI.session[b.digest]=s + if s.last and page>s.last then s.forward=s.forward+1 end;s.last=page +end +function FinishUI.model(b) + local paint=Library.paint("end-of-book") + local m=paint:widget("end-of-book"):read("reader.finish",{path=b.file,document=b.digest,rating=b.summary.rating,limit=3}) + paint:flush() + return m or {title=b.file:match("([^/]+)$"),status=b.summary.status=="complete" and "✓ Marked as finished" or "Not marked as finished",undo=b.summary.status=="complete",can_mark=b.summary.status~="complete",stars=b.summary.rating} +end +function FinishUI.showSheet(ui,b) + FinishUI.closeSheet();FinishUI.card_state=nil + FinishUI.sheet=EndSheet:new{ui=ui,book=b,model=FinishUI.model(b)} + UIManager:show(FinishUI.sheet) -- gate: exception (the reader reached the end) +end +function FinishUI.refreshSheet(ui,b) + if FinishUI.sheet and FinishUI.sheet.ui==ui and FinishUI.sheet.book==b then + FinishUI.sheet:update(FinishUI.model(b),FinishUI.card_state) + end +end +function FinishUI.closeSheet() + local s=FinishUI.sheet;FinishUI.sheet=nil;if s then UIManager:close(s) end +end +FinishUI.actions={} +function FinishUI.actions.undo(ui,b) ui.status:markBook(false);FinishUI.refreshSheet(ui,b) end +function FinishUI.actions.mark(ui,b) ui.status:markBook(true);FinishUI.refreshSheet(ui,b) end +function FinishUI.actions.star(ui,b,n) + local summary=b.doc_settings:readSetting("summary") or {} + summary.rating=summary.rating~=n and n or nil;b.summary=summary;b.doc_settings:saveSetting("summary",summary) + dispatch("finish.rate",b,{rating=summary.rating},function() FinishUI.refreshSheet(ui,b) end) +end +function FinishUI.actions.review(ui) FinishUI.closeSheet();if ui.status then ui.status:onShowBookStatus() end end +function FinishUI.actions.author(ui,b,name) + FinishUI.closeSheet();Library.openGrouped(name,{kind="author",key=name},{group="series"}) +end +function FinishUI.actions.back() FinishUI.closeSheet() end +function FinishUI.actions.home(ui) FinishUI.leaveForHome(ui);if state.module then state.module:onOrbitGoHome() end end +function FinishUI.actions.book(ui,b,key,title,local_path) + local sheet=FinishUI.sheet + FinishUI.onLeave(ui) + if local_path then FinishUI.closeSheet();return Library.open({local_path=local_path}) end + FinishUI.card_state={book_id=key,text="Connecting…"};FinishUI.refreshSheet(ui,b) + -- The existing sole position/lifecycle writer drains before the companion sends the finish. + -- Downloads follow its completion; no new writer or transport is installed here. + Library.finishCurrent(function(ok) + if FinishUI.sheet~=sheet or not sheet then return end + if not ok then FinishUI.card_state={book_id=key,failure="failed"};FinishUI.refreshSheet(ui,b);return end + dispatch("finish.download",b,{key=key},function(result) + if FinishUI.sheet~=sheet then return end + if result.error then + FinishUI.card_state={book_id=key,failure="failed"};FinishUI.refreshSheet(ui,b) + elseif result.local_path then + FinishUI.closeSheet();Library.open(result) + end + end) + end) +end +FinishUI.actions.retry=FinishUI.actions.book +function FinishUI.actions.later(ui,b,key) dispatch("finish.download",b,{key=key,later=true});FinishUI.closeSheet() end +function FinishUI.drain(p,manual,done) + if reading() then if done then done() end;return end + Library.catalogAction("finish.drain",{manual=manual==true},function() if done then done() end end) +end +function FinishUI.installPluginHooks(p) if Library.installFinishHooks then return Library.installFinishHooks(p) end end +-- Native events are small, already-loaded records. No catalog work on a page turn. +local ok,ReaderStatus=pcall(require,"apps/reader/modules/readerstatus") +if ok and type(ReaderStatus)=="table" and type(ReaderStatus.markBook)=="function" and type(ReaderStatus.onEndOfBook)=="function" then + wrap(ReaderStatus,"markBook",function(stock) return function(self,...) + local r=stock(self,...);FinishUI.onMarked(self.ui);return r + end end,"finish") + wrap(ReaderStatus,"onEndOfBook",function(stock) return function(self,...) + local b=book(self.ui) + if S.eob_sheet==false or not b or not b.key then return stock(self,...) end + if b.summary.status~="complete" and S.eob_auto~=false then self:markBook(true);b=book(self.ui) end + FinishUI.showSheet(self.ui,b);return true + end end,"finish") +end +for _,name in ipairs({"onCloseWidget","onSuspend","onReaderReady","onPageUpdate"}) do + local stock=OrbitAndroid[name] + OrbitAndroid[name]=function(self,...) + if name=="onCloseWidget" or name=="onSuspend" then FinishUI.onLeave(self.ui) end + if name=="onCloseWidget" then FinishUI.closeSheet() end + if name=="onReaderReady" then + local b=book(self.ui) + FinishUI.reader_key=nil + if b then + FinishUI.page_digests[self.ui]={file=b.file,digest=b.digest} + local ui=self.ui + dispatch("finish.prepare",b,{local_only=true},function(result) + if self.ui==ui and ui.document and ui.document.file==b.file and not result.error then FinishUI.reader_key=result end + end) + end + elseif name=="onPageUpdate" then FinishUI.onPage(self.ui,...) end + return stock(self,...) + end +end diff --git a/android/koreader/orbit.koplugin/ko/home_host.lua b/android/koreader/orbit.koplugin/ko/home_host.lua index 9d54d349..2ec79296 100644 --- a/android/koreader/orbit.koplugin/ko/home_host.lua +++ b/android/koreader/orbit.koplugin/ko/home_host.lua @@ -342,6 +342,7 @@ function HomeHost.show() UIManager:show(InfoMessage:new{text=problem}) -- gate: user action (Home) return false end + if FinishUI then FinishUI.leaveForHome(liveUI()) end if HomeHost.active then UIManager:close(HomeHost.active) end -- The explicit Home action is leaving the reading foreground. Permit its bounded -- cached reads during construction, before UIManager has pushed the new screen. diff --git a/android/koreader/orbit.koplugin/ko/library.lua b/android/koreader/orbit.koplugin/ko/library.lua index b8c25c40..796a9a87 100644 --- a/android/koreader/orbit.koplugin/ko/library.lua +++ b/android/koreader/orbit.koplugin/ko/library.lua @@ -7,6 +7,9 @@ LibraryAdapter={sent={},order={},ready={}} LibraryAdapter.LOCAL_OWNER="device-local" function LibraryAdapter.owner() return LibraryAdapter.managed_owner or LibraryAdapter.LOCAL_OWNER end function LibraryAdapter.read(request,op) + if op=="settings.recommendations" and LibraryAdapter.recommendations then + return LibraryAdapter.recommendations,#Cache.encode(LibraryAdapter.recommendations) + end if op=="account.state" and LibraryAdapter.account_snapshot then return LibraryAdapter.account_snapshot, LibraryAdapter.account_bytes end @@ -68,6 +71,14 @@ function LibraryAdapter.syncNow(reader) return reader:onOrbitSyncAndSleep(true) function LibraryAdapter.syncCurrent(done) return ReadingSync.run("manual",function(ok,why) done(ok,why or (ok and "Synced" or "Saved · delivery pending")) end) end +-- A successful transport drain may retain closed-sidecar applications. Those do not +-- delay the finish; transport errors do. SyncOwner remains the sole position writer. +function LibraryAdapter.finishCurrent(done) + return ReadingSync.run("manual",function(ok,why) + if why then return done(false,why) end + return Library.catalogAction("finish.drain",{manual=true},function(result) done(not result.error,result.error) end) + end) +end -- KOReader already computes this on page/position updates, even with its footer hidden. -- No document scan, sidecar read or second progress writer on a panel paint. function LibraryAdapter.readerPosition(path) @@ -268,6 +279,9 @@ function Library.subscribe(callback) end end function Library.changed(event) + if FinishUI and FinishUI.sheet and event.kind=="library" then + local sheet=FinishUI.sheet;FinishUI.refreshSheet(sheet.ui,sheet.book) + end if Library.listener then Library.listener(event) end end function Library.open(row) @@ -478,6 +492,8 @@ function Library.catalogSnapshot() end function Library.refreshCatalog(action,manual) local owner=LibraryAdapter.owner() + local catalog=(LibraryAdapter.account_snapshot or {}).catalog or {} + if not manual and catalog.canRefresh~=true then return false end local problem=Companion.workerProblem() if not owner or problem then if manual and not reading() then @@ -548,7 +564,46 @@ if OrbitAndroid then local result=init(self,...) if Library.connectorReady then Library.connectorReady() end Library.accountReturned() + Library.catalogAction("initialize",{},function() end) Library.watchEvents() return result end end + +function Library.catalogAction(action,args,done) + args=args or {};args.action=action;args.owner=LibraryAdapter.owner() + if not args.owner then if done then done({error="unavailable"}) end;return false end + return command(action,function() return LibraryAdapter.command("catalog.action",args,done or function() end) end) +end +function Library.recommendations(args,done) + return command("recommendations",function() return LibraryAdapter.command("settings.recommendations",args,function(result) + if not result.error and not args.definitions then LibraryAdapter.recommendations=result end + done(result) + end) end) +end +function Library.endAction(name,...) return FinishUI.actions[name](...) end +function Library.openGrouped(title,source,query) + if HomeHost.show() and HomeHost.active then HomeHost.active:showList(title,source,query) end +end +function Library.copiesTick(why) + if S.keep_copies_current==false or reading() or Library.copies_pending then return end + if Library.copies_at and now_s()-Library.copies_at<600 and why~="full refresh" then return end + Library.copies_at=now_s();Library.copies_pending=true + local ui=liveUI() + return Library.catalogAction("copies.check",{enabled=true,open_path=ui and ui.document and ui.document.file},function() + Library.copies_pending=nil + end) +end + +function Library.cachedAccountState() return LibraryAdapter.account_snapshot or {} end + +-- Finish follows the existing sole position writer and its outbox; no replacement writer. +function Library.finishCurrent(done) + if not LibraryAdapter.finishCurrent then done(false,"Sync unavailable");return false end + return command("finish-current",function() return LibraryAdapter.finishCurrent(done) end) +end + +-- Native catalog compatibility uses neutral references and companion-owned transfer only. +function Library.catalogDownload(reference,destination,file_reference,done) + return Library.catalogAction("finish.download",{reference=reference,destination=destination,file_reference=file_reference},done) +end diff --git a/android/koreader/orbit.koplugin/ko/recommendations.lua b/android/koreader/orbit.koplugin/ko/recommendations.lua new file mode 100644 index 00000000..030f89f9 --- /dev/null +++ b/android/koreader/orbit.koplugin/ko/recommendations.lua @@ -0,0 +1,171 @@ +-- SPDX-License-Identifier: AGPL-3.0-or-later +-- Bounded local-setting observations/actions. The companion chooses, labels and counts rows. +Recommendations={items={},snapshot={items={}}} +local function context() local ui=liveUI();return ui and ui.gestures end +local function equal(a,b) + if a==b then return true end + if type(a)~="table" or type(b)~="table" then return false end + for k,v in pairs(a) do if not equal(v,b[k]) then return false end end + for k in pairs(b) do if a[k]==nil then return false end end + return true +end +local function observe(item,raw) + local unavailable=(item.needs and not Companion.has(item.needs)) or + item.required_by=="wifi" and not S.wifi_via_companion + local obs + if item.kind=="connector" then obs=Library.observeSetting and Library.observeSetting(item) or {available=false,reason="Connector unavailable"} + elseif item.kind=="ko" then obs={available=true,current=G_reader_settings:readSetting(item.key)} + elseif item.kind=="gesture" then + local g=context();local defaults=g and g.default_settings and g.default_settings.data + if g and defaults and defaults.gesture_reader then + obs={available=true,current=(g.data.gesture_reader or {})[item.key],default=defaults.gesture_reader[item.key]} + else obs={available=false,reason="Turn on KOReader's Gestures plugin"} end + else obs={available=false} end + if unavailable and not raw then obs.available=false;obs.reason="Needs companion capability" end + return obs +end +local function write(item,value) + if item.kind=="connector" then return Library.writeSetting and Library.writeSetting(item,value) end + if item.kind=="ko" then + if value==nil then G_reader_settings:delSetting(item.key) else G_reader_settings:saveSetting(item.key,value) end + return true + end + local g=context();if not g then return false end + g.data.gesture_reader=g.data.gesture_reader or {};g.data.gesture_reader[item.key]=value;g.updated=true + if g.onFlushSettings then g:onFlushSettings() end;return true +end +function Recommendations.pass(why,choices,lost,done) + if Recommendations.pending then return end + if #Recommendations.items==0 then + Recommendations.pending=true + return Library.recommendations({definitions=true},function(result) + if result.error then Recommendations.pending=nil;return end + Recommendations.items=result.items or {};if #Recommendations.items>0 then Recommendations.pass(why,choices,lost,done) end + end) + end + local observations={} + for i,item in ipairs(Recommendations.items) do if i<=8 then observations[item.id]=observe(item) end end + local unseen=S.recommended and S.recommended.unseen or 0 + Recommendations.pending=true + return Library.recommendations({observations=observations,record=S.recommended,backup=S.recommended_backup,choices=choices,lost=lost,wifi=S.wifi_via_companion and Companion.has("wifi")},function(result) + Recommendations.pending=nil;if result.error then return end + -- Persist backups before native writes. An interrupted pass can recover Undo. + S.recommended_backup=result.backup + S.recommended=S.recommended or {items={}} + S.recommended.items=S.recommended.items or {} + for _,op in ipairs(result.writes or {}) do S.recommended.items[op.id]="unavailable" end + saveSettings() + local failed={} + for i,op in ipairs(result.writes or {}) do + if i>8 then break end + for _,item in ipairs(Recommendations.items) do + if item.id==op.id then + -- A user action while the worker ran wins; never overwrite it on return. + local same=equal(observe(item,true).current,op.expected) + local worked,took=false,false + if same then worked,took=pcall(write,item,op.value) end + if not same or not worked or not took then + failed[#failed+1]=op.id;result.record.items[op.id]="unavailable" + end + end + end + end + S.recommended,S.recommended_backup=result.record,result.backup;saveSettings() + local actual={} + for _,item in ipairs(Recommendations.items) do actual[item.id]=observe(item) end + Library.recommendations({ack=true,failed=failed,observations=actual,record=result.record,backup=result.backup,wifi=S.wifi_via_companion and Companion.has("wifi")},function(snapshot) + Recommendations.pending=nil;if snapshot.error then return end + Recommendations.snapshot=snapshot + S.recommended=snapshot.record;saveSettings() + if (snapshot.record.unseen or 0)>unseen then Recommendations.line_pending=true;Recommendations.reviewed=false end + Recommendations.report(why,true) + if Recommendations.onSnapshot then Recommendations.onSnapshot() end + if done then done(snapshot) end + end) + end) +end +function Recommendations.report(why,force) + local snapshot=Recommendations.snapshot + Companion.send(Companion.ACTION.REPORT,{reason=why,signed_in=Library.cachedAccountState().signedIn and "1" or "0",recommended=snapshot.report or "none",conflicts=tostring(snapshot.conflicts or 0)}) +end +function Recommendations.applyChoices(why) + local choices={} + for _,c in ipairs(SettingsSync.choices(S.recommended_choice)) do choices[c.id]=c.what end + if next(choices) then Recommendations.pass(why,choices,false,function() Shared.set("recommended_choice","") end) end +end +function OrbitAndroid:recommendedPass(why) + Recommendations.pass(why,nil,false,function() self:maybeRecommendedLine() end) +end +function OrbitAndroid:maybeRecommendedLine(where) + if not Recommendations.line_pending or (where or self:whereNow())=="reader" then return end + Recommendations.line_pending=false + if Recommendations.snapshot.line then orbitNote(Recommendations.snapshot.line.." · Tools › BookSync › Recommended settings",4) end +end +function OrbitAndroid:recommendedMenuText() + local line=Recommendations.snapshot.line + if Recommendations.reviewed then line=Recommendations.snapshot.seen_line end + return line and ("Recommended settings: "..line) or "Recommended settings" +end +function OrbitAndroid:showRecommended(why) + local finish=Budgets.span("recommendations.draw",now_s,log) + local paint=Library.paint("settings-recommendations") + local snapshot=paint:widget("recommendations"):read("settings.recommendations",{limit=8}) or {items={}} + paint:flush(true) + local items={} + local function choice(id,what) + if what=="mine" then + for _,item in ipairs(snapshot.items or {}) do + if (id==item.id or id=="all") and item.state=="conflict" and item.needs_wifi then + S.wifi_via_companion=false;saveSettings() + end + end + end + Recommendations.pass("review",{[id]=what},false) + end + if snapshot.use_all then + items[#items+1]={text="Use all of BookSync's",callback=function() choice("all","ours") end} + items[#items+1]={text="Keep all mine",callback=function() choice("all","mine") end} + end + local section + for i,row in ipairs(snapshot.items or {}) do + if i>8 then break end + local item=row + if item.section~=section then + section=item.section;items[#items+1]={text=section,bold=true,callback=function() end} + end + items[#items+1]={text=item.label,mandatory=item.state=="applied" and (tostring(item.orbit).." (was: "..tostring(item.was)..")") or item.state=="unavailable" and item.reason or tostring(item.yours or ""), + dim=item.state=="already" or item.state=="unavailable",callback=function() + if item.state=="already" or item.state=="unavailable" then return end + local d + d=require("ui/widget/buttondialog"):new{title=item.label,buttons={{ + {text="Use BookSync's",callback=function() UIManager:close(d);choice(item.id,"ours") end}, + {text=item.state=="applied" and "Undo" or "Keep mine",callback=function() + UIManager:close(d) + local function apply() + if item.needs_wifi then S.wifi_via_companion=false;saveSettings() end + choice(item.id,item.state=="applied" and "undo" or "mine") + end + if item.state=="applied" and item.needs_wifi then + UIManager:show(ConfirmBox:new{text="Wi-Fi switching needs this. Turn it off and undo?",ok_callback=apply}) -- gate: user action (Recommended settings menu) + else apply() end + end}}}} + UIManager:show(d) -- gate: user action (Recommended settings menu) + end} + end + if snapshot.undo_all then items[#items+1]={text="Undo all",callback=function() choice("all","undo") end} end + if #items==0 then items[1]={text="Preparing recommended settings…"};Recommendations.pass(why) end + Recommendations.reviewed=true;Recommendations.line_pending=false + if S.recommended then S.recommended.unseen=0;saveSettings() end + items[#items+1]={text="Done",callback=function() if self.rec_menu then UIManager:close(self.rec_menu);self.rec_menu=nil end end} + self.rec_menu=require("ui/widget/menu"):new{title="Recommended settings",item_table=items,is_borderless=true,covers_fullscreen=true} + UIManager:show(self.rec_menu) -- gate: user action (Recommended settings menu) + local visible=self.rec_menu + Recommendations.onSnapshot=function() + if self.rec_menu~=visible or UIManager:getTopmostVisibleWidget()~=visible then return end + UIManager:close(visible);self.rec_menu=nil;self:showRecommended("refresh") + end + finish();return self.rec_menu +end +function silentWifiOn() -- first pass runs after the neutral library has loaded + UIManager:nextTick(function() Recommendations.pass("load") end) +end diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit.lua index 7c2dd7af..655288f8 100644 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit.lua +++ b/android/koreader/orbit.koplugin/ko/server/bookorbit.lua @@ -16,7 +16,7 @@ end compat_seen = setmetatable({}, { __mode = "k" }) compat_logged = {} -Grouping = nil -- lists by series and by author; defined with the catalog hooks below +EOB=setmetatable({}, {__index=function(_,key) return FinishUI and FinishUI[key] end}) -- lifecycle bridge until library initialization -- The plugin's version (main.lua:54/95: BookOrbit.PLUGIN_VERSION; _meta.lua has none). function pluginVersion(p) @@ -91,10 +91,10 @@ function Server.openLogin(p) return p:promptLogin() end -- Legacy service bridge. Only reviewed lifecycle/sheet modules use this facade. function Server.cacheClient() return OC.client() end function Server.readerIdle() - if Copies and Copies.tick then pcall(Copies.tick,"book closed") end - if EOB and EOB.drain and not reading() then - local p=serverPlugin() - if p then EOB.drain(p,false,function() end) end + if Library.copiesTick then pcall(Library.copiesTick,"book closed") end + if FinishUI and not reading() and not FinishUI.sending then + FinishUI.sending=true + Library.finishCurrent(function() FinishUI.sending=nil end) end end function Server.watchCache() return OC.watchChecks() end @@ -102,35 +102,33 @@ function Server.cacheBusy() if OC and OC.busy then return OC.busy() end end function Server.refreshLibrary(...) return OC.menuFullRefresh(...) end function Server.resumeCache(...) if Mirror and Mirror.kick then return Mirror.kick(...) end end function Server.fullRefreshNotice() return Mirror and (Mirror.notices or Mirror.fullRunning()) end -function Server.installGrouping(...) return Grouping.install(...) end +function Server.installGrouping(...) return Server.installGroupViews(...) end function Server.countStorage(...) if OC and OC.storageCount then return OC.storageCount(...) end end function Server.refreshCovers(...) if Mirror and Mirror.coverPass then return Mirror.coverPass(...) end end -function Server.reportRecommended(...) if Rec then return Rec.report(...) end end -function Server.applyRecommended(...) if Rec then return Rec.applyChoices(...) end end -function Server.capabilitiesLost(...) if Rec then return Rec.capsLost(...) end end -function Server.capabilitiesGained(...) if Rec then return Rec.pass(...) end end -function Server.endSheetOpen() return EOB and EOB.sheet~=nil end -function Server.leaveEndSheet(...) return EOB and EOB.leaveForHome(...) end -function Server.endAction(name,...) return EOB.actions[name](...) end +function Server.reportRecommended(...) if Recommendations then return Recommendations.report(...) end end +function Server.applyRecommended(...) if Recommendations then return Recommendations.applyChoices(...) end end +function Server.capabilitiesLost(...) if Recommendations then return Recommendations.pass("caps lost",nil,true) end end +function Server.capabilitiesGained(...) if Recommendations then return Recommendations.pass("capabilities gained") end end +function Server.endSheetOpen() return FinishUI and FinishUI.sheet~=nil end +function Server.leaveEndSheet(...) return FinishUI and FinishUI.leaveForHome(...) end +function Server.endAction(name,...) return Library.endAction(name,...) end function Server.localBookId(path) local cat=Mirror and Mirror.catalog and Mirror.catalog() if not (path and cat and type(cat.on_device)=="table") then return nil end for id,p in pairs(cat.on_device) do if p==path then return tonumber(id) end end end function Server.quietLegacy(quiet) - quiet(Copies,{"ask","tick","pump","found","prepared"}) quiet(OC,{"watchChecks","applyEvents","landed","redraw_soon","redraw","storageCount","storageCounted","rechecked"}) quiet(Mirror,{"tick","kick","poll","ran","finish","coverPass"}) quiet(LF,{"quiet","paintTiles","quietSwitch"}) end function Server.timeLegacy(wrap) - for _,name in ipairs({"EOB","OC","LF","Mirror","Copies"}) do + for _,name in ipairs({"OC","LF","Mirror"}) do wrap(getfenv(1)[name],name) end end -- Temporary non-transport compatibility for the finish adapter while its parallel cutover lands. -Sync = { waitOutbox=function(_,_,done) return ReadingSync.run("close",done) end } -- Covers have one owner even with legacy catalog caching disabled. Never call the upstream -- downloader: these low-level methods can be reached inside an upstream subprocess. @@ -216,16 +214,6 @@ function OC.client() if p and p.catalog_browser and p.catalog_browser.client then return p.catalog_browser.client end return p and Compat.callable(p.newClient) and p:newClient() or nil end -function OC.state() - if not OC._state then - local state=Cache.decode(Store.readFile(Store.dir().."/plugin-state.lua") or "") - OC._state=type(state)=="table" and state or {} - end - return OC._state -end -function OC.saveState() - if not Companion.workerProblem() then Companion.send(Companion.ACTION.PATCH,{plugin_state=Cache.encode(OC.state())}) end -end function OC.watchChecks() return Library.watchEvents() end function OC.drainEvents() return Library.pollEvents() end function OC.applyEvents(events) return Library.applyEvents(events) end @@ -270,7 +258,7 @@ function Mirror.tick(why) end function Mirror.kick(why) if Sleep and Sleep.kick then Sleep.kick(why) end - if Copies and Copies.tick then pcall(Copies.tick,why) end + if Library and Library.copiesTick then pcall(Library.copiesTick,why) end UIManager:scheduleIn(1,function() Mirror.tick(why) end) end -- The parent explicitly revalidates the visible local references through the library. @@ -313,13 +301,9 @@ end function Server.installCatalogRuntime() Store.directory=OC.dir + Server.bindCatalogActions() Library.compatTick=function(t) if OC.storage_asked and t-OC.storage_asked>=60 then OC.storage_asked=nil end - if Copies and Copies.asked and t-Copies.asked>=Copies.WAIT_S then Copies.asked=nil end - if Copies and Copies.prepare_at and t-Copies.prepare_at>=Copies.WAIT_S then - Copies.preparing,Copies.prepare_at,Copies.busy=nil,nil,nil - Copies.stop("companion preparation timed out") - end if LF and LF.year_waiting and t-LF.year_waiting>60 then LF.year_waiting=nil end if Sleep and Sleep.waited then Sleep.waited(t) end end @@ -352,10 +336,8 @@ function Server.installCatalogRuntime() OC.storageCounted(ev) elseif ev.kind == "sleep_pool" and Sleep then Sleep.landed(ev) - elseif ev.kind == "copy_prepared" and Copies then - Copies.prepared(ev) - elseif ev.kind == "copies" and Copies then - Copies.found(ev) + elseif ev.kind=="copy.identity" or ev.kind=="finish.applied" or ev.kind=="download.saved" then + Server.applyCatalogEvent(ev) end end Library.catalogStarted=function() @@ -382,12 +364,12 @@ function Server.installCatalogRuntime() end Library.catalogFinished=function(status) Server.catalogChanged({owner=LibraryAdapter.owner()}) - if Copies and Copies.tick then pcall(Copies.tick,"catalog refresh") end + if Library.copiesTick then pcall(Library.copiesTick,"catalog refresh") end end Library.watchEvents() end -- Compatibility shapes are assembled from BookSync display records, never HTTP/JSON. The --- remaining copies/EOB slice still uses native identifiers; catalog queries are worker-owned. +-- native compatibility shapes use identifiers only here; catalog queries are worker-owned. function Server.installCatalogApi(Api,Catalog) if not Library or type(Api)~="table" then return false end if #Compat.missingOn(Api,{request="function",requestBlocking="function",runInSubprocess="function",query="function"})>0 then return false end @@ -446,11 +428,8 @@ function Server.installCatalogApi(Api,Catalog) end -- A legacy Catalog.fetch closure can only use local catalog reads. Prevent another -- operation in that closure from performing transport synchronously on the UI thread. - if Compat.callable(Api.download) then - wrap(Api,"download",function(stock) return function(self,...) - if Server.catalog_paint then return nil,"cancelled" end - return stock(self,...) - end end,"catalog-local") + for _,name in ipairs({"download","downloadBlocking"}) do + if Compat.callable(Api[name]) then Api[name]=function() return nil,"companion_owned" end end end if Compat.callable(Api.request) then wrap(Api,"request",function(stock) return function(self,...) @@ -461,6 +440,19 @@ function Server.installCatalogApi(Api,Catalog) end if type(Catalog)=="table" and not Catalog._booksync_catalog then Catalog._booksync_catalog=true + if Compat.callable(Catalog.downloadFile) then + Catalog.downloadFile=function(self,path,detail,file,reporter) + local generation=self.download_generation + if Compat.callable(self.nextDownloadGeneration) then generation=self:nextDownloadGeneration() end + return Library.catalogDownload(detail.id,path,file and file.id,function(result) + if self.catalog_closed or self.download_generation~=generation then return end + if reporter and reporter.finished then reporter.finished(not result.error,result.error,result.local_path,not result.error) + elseif result.error and Compat.callable(self.showWriteError) then self:showWriteError(result.error) + elseif Compat.callable(self.refreshCurrent) then self:refreshCurrent() end + end) + end + end + if Compat.callable(Catalog.initialDashboardContext) then wrap(Catalog,"initialDashboardContext",function(stock) return function(self,...) local before=Library.catalog_opening;Library.catalog_opening=true @@ -568,3 +560,103 @@ function Server.catalogChanged(event) if LF and Compat.callable(cat.refreshCurrent) then LF.refreshKeepingCovers(cat) end end) end + +-- Minimal native binding. UI and shared lifecycle hooks call the neutral Library/FinishUI. +function Server.installGroupViews() + local cat=Server.loaded("catalog") + if type(cat)~="table" or not Compat.callable(cat.listSortSheetModel) or not Compat.callable(cat.listRun) then return false end + wrap(cat,"listSortSheetModel",function(stock) return function(self,sheet) + local m=stock(self,sheet) + if m and m.rows and self:listKind()=="books" then + table.insert(m.rows,1,{label="By author",action={kind="booksync-group",group="author"}}) + table.insert(m.rows,1,{label="By series",action={kind="booksync-group",group="series"}}) + end + return m + end end,"owned-groups") + wrap(cat,"listRun",function(stock) return function(self,action,region,hold) + if not hold and type(action)=="table" and action.kind=="booksync-group" then + local context=self.current_context or {};local p=context.params or {} + local names={libraryId="library",collectionId="collection",smartScopeId="list",seriesId="series",author="author",ids="ids",q="search",readStatus="status",format="format",sort="sort",order="direction"} + local selection={};for k,n in pairs(names) do if p[k]~=nil then selection[n]=tostring(p[k]) end end + Library.openGrouped(context.title or "Library",{kind="selection",selection=selection},{group=action.group}) + return true + end + return stock(self,action,region,hold) + end end,"owned-groups") + return true +end + +function Server.bindCatalogActions() + EOB=FinishUI -- temporary compatibility for F12-Q's lifecycle/push holds; no second outbox + Library.nativeReader=function(ui) + local p=ui and ui.bookorbit + if not (ui and ui.document and ui.doc_settings) then return end + local digest=ui.doc_settings:readSetting("partial_md5_checksum") + if type(digest)~="string" and p and type(p.getDocumentDigest)=="function" then + local ok,value=pcall(p.getDocumentDigest,p);if ok then digest=value end + end + if type(digest)~="string" then return end + local state=Server.loaded("state_manager") + local b=state and state.getBook and state.getBook(digest) + local pct=LibraryAdapter.readerPosition(ui.document.file) + local prepared=FinishUI.reader_key + if not prepared or prepared.path~=ui.document.file or prepared.document~=digest or prepared.owner~=LibraryAdapter.owner() then prepared=nil end + return {digest=digest,file=ui.document.file,key=prepared and prepared.key or b and b.bookId and true,book_id=prepared and prepared.reference or b and b.bookId, + percentage=pct,summary=ui.doc_settings:readSetting("summary") or {},doc_settings=ui.doc_settings,plugin=p} + end + Library.noteReaderMark=function(b) if LocalState then LocalState.noteMark(b,b.summary.status) end end + Library.noteReaderLeave=function(b) + if LocalState then LocalState.put(b.digest,{pending=true,bookId=b.book_id,percent=b.percentage and b.percentage*100,status=b.summary.status}) end + if LF and LF.noteOnDevice then LF.noteOnDevice(b.book_id,b.file) end + end + Library.observeSetting=function(item) + local p=serverPlugin(liveUI()) + if not p then return {available=false,reason="Connector unavailable"} end + local defaults=p.default_settings + if type(defaults)~="table" then return {available=false,reason="Connector defaults unavailable"} end + if item.key=="catalog_auto_open" and not Compat.settable(p.settings,item.key,item.ours) then return {available=false,reason="Connector home setting unavailable"} end + local current=p.settings[item.key] + if type(S.osm_saved_plugin)=="table" and next(S.osm_saved_plugin) and p.settings.sync_forward==3 and p.settings.sync_backward==3 and + (item.key=="sync_forward" or item.key=="sync_backward" or item.key=="auto_sync") then current=S.osm_saved_plugin[item.key] end + return {available=true,current=current,default=defaults[item.key]} + end + Library.writeSetting=function(item,value) + local p=serverPlugin(liveUI());if not p then return false end + if type(S.osm_saved_plugin)=="table" and next(S.osm_saved_plugin) and p.settings.sync_forward==3 and p.settings.sync_backward==3 and + (item.key=="sync_forward" or item.key=="sync_backward" or item.key=="auto_sync") then + S.osm_saved_plugin[item.key]=value;saveSettings();return true + end + p.settings[item.key]=value + G_reader_settings:flush();return true + end + +end +function Server.applyCatalogEvent(ev) + if ev.owner~=LibraryAdapter.owner() then return end + local sm=Server.loaded("state_manager") + if ev.kind=="copy.identity" and sm and sm.repairFileIdentity then + sm.repairFileIdentity(ev.path,ev.before,ev.after) + if ev.reference and ev.file_reference and sm.linkFile then sm.linkFile(ev.after,ev.file_reference,ev.reference,ev.path) end + Library.catalogAction("copies.ack",{token=ev.token}) + elseif ev.kind=="download.saved" and sm and sm.linkFile then + sm.linkFile(ev.document,ev.file_reference,ev.reference,ev.path) + if ev.deferred then Gate.show("downloaded book",function() + UIManager:show(require("ui/widget/infomessage"):new{text="Downloaded: "..tostring(ev.title or "Book"),timeout=3}) -- gate: Gate.show + end) end + elseif ev.kind=="finish.applied" then + local epoch=FinishUI.intent[ev.document] or 0 + Library.catalogAction("finish.validate",{document=ev.document,token=ev.token},function(result) + if not result.apply or ev.owner~=LibraryAdapter.owner() or epoch~=(FinishUI.intent[ev.document] or 0) then return end + local side=Server.loaded("sidecar") + if not (side and sm and sm.mutate) then return end + local st={status_known=ev.complete,status=ev.complete and "complete" or nil,status_modified=ev.date,rating_known=ev.rated,rating=ev.rating} + local ui=liveUI() + if ui and ui.document and ui.document.file==ev.path then side.applyServerStateLive(ui,st) + elseif ev.path then side.applyServerStateSidecar(ev.path,st) end + sm.mutate(function(session) local b=session:getBook(ev.document);if b then side.rememberServerState(b,st) end end) + if LocalState then LocalState.noteSent(ev.document) end + FinishUI.jobs[ev.document]=nil + Library.catalogAction("finish.ack",{document=ev.document,token=ev.token}) + end) + end +end diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua deleted file mode 100644 index 11a4b9b6..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua +++ /dev/null @@ -1,235 +0,0 @@ --- SPDX-License-Identifier: AGPL-3.0-or-later --- Copyright (c) 2026 Fledgewing. Part of BookSync (see android/koreader/LICENSE). --- Part of orbit.koplugin: loaded by main.lua into the plugin's shared environment, in the --- order main.lua lists (docs/design/orbit-plugin.md "Module layout"). - --- Keep book copies current (v0.11.1, docs/design/keep-copies-current.md). A copy whose library --- file changed on the server (BookOrbit writes metadata into the file, so its hash moves) is --- downloaded again in the background, through the plugin's own Download path (delivery variant, --- hash checked, atomic rename), to the same path. Its KOReader sidecar stays: the path is the --- same, the text unchanged, so positions, highlights and bookmarks still fit. What KOReader and --- BookOrbit key by the file's hash moves to the new hash. Only online, never while reading, one --- book at a time, from a queue kept on disk. - -Copies = {} --- Transitional detail template is private to the remaining copies command (step 4). -function Copies.detailPath(client,id) return client:query("/koreader/plugin/catalog/books/"..tostring(id),{}) end - - -local lfs_ok, lfs = pcall(require, "libs/libkoreader-lfs") - -local function index() - local st = OC.state() - st.copies = st.copies or { queue = {} } - st.copies.queue = st.copies.queue or {} - return st.copies -end -Copies.state = index - -Copies.WAIT_S = 60 --- Replacements are numbered, so an answer to an ask made before one doesn't queue it again. -Copies.seq, Copies.done_seq = 0, {} - -local function stateManager() - local sm = package.loaded["bookorbit_state_manager"] - if type(sm) == "table" and type(sm.state) == "function" then return sm end -end - -local function openFile() - local ui = liveUI() - return ui and ui.document and ui.document.file or nil -end - --- The companion writes copies/ask.lua; KOReader sends only in-memory state. --- Asks Orbit Companion which copies changed (COPIES, docs/design/companion-worker.md). The ask --- is small and comes from memory: BookOrbit's state books, the end-of-book cache's file lists, --- and how the mirror names a book's detail; the companion reads the saved details (the cache's --- and the mirror's), compares the hashes and checks the files are on the reader. Returns true --- when asked. -function Copies.ask(why) - if S.keep_copies_current == false then return false end - if Copies.asked and OC.now() - Copies.asked < Copies.WAIT_S then return false end - local problem = Companion.workerProblem(_("to keep copies current")) - if problem then - if Copies.problem ~= problem then Copies.problem = problem; log("copies: not checked:", problem) end - return false - end - Copies.problem = nil - local sm = stateManager() - if not sm then return false end - local okb, books = pcall(function() local st = sm.state(); return st and st.books end) - if not okb or type(books) ~= "table" then return false end - local list, want = {}, {} - for md5, b in pairs(books) do - if type(b) == "table" and type(b.file) == "string" and b.bookId ~= nil then - table.insert(list, { md5 = md5, path = b.file, book_id = b.bookId, file_id = b.fileId, incompatible = b.positionIncompatible == true }) - want[tostring(b.bookId)] = true - end - end - local eob = {} - local okc, c = pcall(EOB.cache) - for id, v in pairs(okc and type(c) == "table" and c or {}) do - if want[tostring(id)] and type(v) == "table" and type(v.files) == "table" then eob[tostring(id)] = { files = v.files, saved_at = v.saved_at } end - end - local ask = { books = list, eob = eob, sentinel = Mirror.SENTINEL } - local client = OC.client() - -- How the mirror names a book's detail (its saved details count too). - local okp, path = pcall(function() return client and Copies.detailPath(client, Mirror.SENTINEL) end) - if okp and path then ask.owner, ask.server, ask.detail_template = OC.owner(client), client.server_url, path end - Copies.asked, Copies.asked_seq = OC.now(), Copies.seq - Companion.send(Companion.ACTION.COPIES, { reason = tostring(why), ask = ServerCache.encode(ask) }) - OC.watchChecks() - return true -end - --- The companion's answer: the changed copies join the queue, which then runs when it may. -function Copies.found(ev) - local asked = Copies.asked_seq or 0 - Copies.asked = nil - if ev.err then return log("copies: not checked:", tostring(ev.err)) end - local c = index() - -- A copy replaced while the companion looked was looked up with its old hash. - local fresh = {} - for _, f in ipairs(type(ev.found) == "table" and ev.found or {}) do - if (Copies.done_seq[f.path] or 0) <= asked then table.insert(fresh, f) end - end - local added = CopiesPlan.enqueue(c.queue, fresh) - local n = ev.checked or 0 - if added > 0 then - log(string.format("copies: checked %d copies (%s); %d changed; replacing", n, tostring(ev.why), #c.queue)) - OC.saveState() - elseif #c.queue == 0 then - log(string.format("copies: checked %d copies (%s); %s", n, tostring(ev.why), - (ev.gone or 0) == 0 and "all match the library" or "the changed ones are gone from the reader")) - end - if #c.queue > 0 and not Copies.busy and not Copies.active then Copies.pump() end -end - -function Copies.stop(why) - if Copies.active then - log("copies: paused (" .. why .. "),", #index().queue, "left; it resumes later") - Wifi.release("copies") - end - Copies.active = nil -end - -local function finish() - if Copies.active then - log("copies: done;", Copies.replaced or 0, "replaced,", Copies.failed or 0, "failed") - Wifi.release("copies") - end - Copies.active, Copies.replaced, Copies.failed = nil, nil, nil -end - --- After the new file is in place: the sidecar's stored hash, KOReader's hash-keyed folder and --- statistics, and BookOrbit's state (repairFileIdentity: the plugin's own path for a file whose --- bytes changed, bookorbit_state_manager.lua:453). -function Copies.carry(path, old, new) - if not Companion.workerProblem() then - Companion.send(Companion.ACTION.PATCH, { reason = "copy identity", old_hash = old, new_hash = new, copy_path = path }) - end - local sm = stateManager() - if sm and type(sm.repairFileIdentity) == "function" then - local okr, err = pcall(sm.repairFileIdentity, path, old, new) - if not okr then log("copies: state repair failed:", tostring(err)) end - end -end - -local function nextJob(c, outcome, job, detail) - table.remove(c.queue, 1) - OC.saveState() - log("copies:", outcome, tostring(job.path), detail or "") - UIManager:scheduleIn(1, Copies.pump) -end - -function Copies.pump() - if Copies.busy then return end - local c = index() - local job = c.queue[1] - if not job then return finish() end - if S.keep_copies_current == false then return Copies.stop("turned off") end - if reading() then return Copies.stop("reading") end - if not NetworkMgr:isConnected() then return Copies.stop("offline") end - if openFile() == job.path then - -- The open book is never replaced under the reader: it goes last, and waits for its close. - if #c.queue == 1 then return Copies.stop("the book is open") end - table.remove(c.queue, 1); table.insert(c.queue, job) - return UIManager:nextTick(Copies.pump) - end - local p = serverPlugin(liveUI()) - local cat = p and EOB.headlessCatalog(p) - if not cat then return Copies.stop("no BookOrbit plugin") end - if not Copies.active then - Copies.active = true - Wifi.acquire("copies") - log("copies: running;", #c.queue, "to go; Wi-Fi held until it ends") - end - Copies.busy = true - local client = cat.client - local Delivery = require("bookorbit_delivery") - local template = client:query("/koreader/plugin/catalog/books/" .. Mirror.SENTINEL, - { deviceId = client.device_id, variant = Delivery.preference(cat.settings or {}, client) }) - Copies.preparing, Copies.prepare_at = job, OC.now() - Companion.send(Companion.ACTION.COPIES, { reason = "prepare replacement", prepare = ServerCache.encode(job), - template = template, server = client.server_url, user = client.username, userkey = client.userkey }) - OC.watchChecks() -end - -function Copies.prepared(ev) - local job = Copies.preparing - if not job or ev.path ~= job.path then return end - Copies.preparing, Copies.prepare_at = nil, nil - local c = index() - if c.queue[1] ~= job then Copies.busy = nil; return end - local p = serverPlugin(liveUI()) - local cat = p and EOB.headlessCatalog(p) - local detail = ev.detail - if not cat or reading() or openFile() == job.path then - Copies.busy = nil - return Copies.stop("reading or catalog closed") - end - if type(detail) ~= "table" then - Copies.busy = nil - Copies.failed = (Copies.failed or 0) + 1 - return nextJob(c, "could not prepare the book;", job, tostring(ev.err)) - end - local files = Compat.callable(cat.supportedFiles) and cat:supportedFiles(detail) or detail.files or {} - local file = CopiesPlan.pick(files, job.file_id) - local old = ev.md5 or job.md5 - local act = CopiesPlan.decide(old, file) - if act ~= "replace" then - Copies.busy = nil - return nextJob(c, act == "same" and "already current:" or "no hash to check against; left as is:", job) - end - local t0 = now_s() - cat:downloadFile(job.path, detail, file, { - progress = function() end, - finished = function(ok, ferr) - Copies.busy = nil - if not ok then - Copies.failed = (Copies.failed or 0) + 1 - return nextJob(c, "replace failed (" .. tostring(ferr) .. "); the old copy stays:", job) - end - local new = file.fileHash -- downloadFile already verifies the delivered artifact hash - Copies.carry(job.path, old, new) - Copies.replaced = (Copies.replaced or 0) + 1 - Copies.seq = Copies.seq + 1 - Copies.done_seq[job.path] = Copies.seq - nextJob(c, "replaced", job, string.format("(%s -> %s, %ds; sidecar kept)", tostring(old), tostring(new), now_s() - t0)) - end, - }) -end - --- Online and not reading: find changed copies (at most every 10 min) and work the queue. -function Copies.tick(why) - if S.keep_copies_current == false or Copies.busy or Copies.active then return end - if reading() or not NetworkMgr:isConnected() then - if why == "full refresh" then log("copies: check waits (" .. (reading() and "reading" or "offline") .. ")") end - return - end - local t = now_s() - if not Copies.scanned_at or t - Copies.scanned_at > 600 or why == "full refresh" then - if Copies.ask(why) then Copies.scanned_at = t end - end - if #index().queue > 0 then Copies.pump() end -end diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit/endofbook.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/endofbook.lua deleted file mode 100644 index 355e59c2..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/endofbook.lua +++ /dev/null @@ -1,714 +0,0 @@ --- SPDX-License-Identifier: AGPL-3.0-or-later --- Copyright (c) 2026 Fledgewing. Part of BookSync (see android/koreader/LICENSE). --- Part of orbit.koplugin: loaded by main.lua into the plugin's shared environment, in the --- order main.lua lists (docs/design/orbit-plugin.md "Module layout"). - --- End of book on Android (docs/design/end-of-book/DESIGN.md §3, §4, §7; ROADMAP 1 and 2). --- * Turning past the last page of a BookOrbit book marks it finished (KOReader's markBook) and --- opens the Orbit sheet over the last page: Undo, stars, the next book in the series, one --- suggestion, the author's page, Back to book / Home. --- * Every "finished" (the sheet, or KOReader's own Mark as finished) is a FinishJob in --- settings/orbit-finish-queue.lua. Leaving the book makes it ready; the next network-up sends --- it after the plugin's outbox (Sync.waitOutbox): guard read, read-status, rating, then the --- server's state written back so the plugin's next pull doesn't revert it (server S7). --- * A finished book's progress push 10+ points below the end is held (§7, server S3/S4). --- Hooks, each behind EOB.compat: KOReader's ReaderStatus (readerstatus.lua :38 onEndOfBook, --- :212 markBook); the plugin's BookOrbit:enqueueLifecycleSnapshot (main.lua:394), --- :updateProgress and :pushProgressAfterBookSync (live pushes, bookorbit_progress_sync.lua :295, --- :284, mixed in at main.lua:99), :newClient (:272); bookorbit_api.lua :737 catalogBook, --- :705 catalogSetReadStatus, :709 catalogSetRating; bookorbit_state_manager.lua :253 getBook, --- :307 mutate, :348 onDeviceMaps; bookorbit_sidecar.lua :276 rememberServerState, --- :401 applyServerStateLive, :411 applyServerStateSidecar; the catalog class's download --- (bookorbit_catalog_download.lua :166 downloadDefaultFile, :213 downloadFile) and author page --- (bookorbit_catalog.lua :1181 loadBooks). ---------------------------------------------------------------------------------------------- - -EOB = { page_digests = setmetatable({}, { __mode = "k" }), jobs = nil, details = nil, session = {}, sheet = nil, wants_download = nil } -EOB.QUEUE_FILE = "orbit-finish-queue.lua" -EOB.CACHE_FILE = "orbit-detail-cache.lua" -EOB.CACHE_MAX = 32 -EOB.COMPAT = { - plugin = { newClient = "function", getDocumentDigest = "function" }, - api = { catalogBook = "function", catalogSetReadStatus = "function", catalogSetRating = "function" }, - state = { getBook = "function", mutate = "function", onDeviceMaps = "function" }, - sidecar = { rememberServerState = "function", applyServerStateLive = "function", applyServerStateSidecar = "function" }, -} -EOB.CATALOG = { downloadDefaultFile = "function", downloadFile = "function", loadBooks = "function" } --- Used when present (the detail page's path): fetchDeliveryBook, supportedFiles. - -local function settingsDir() - local okd, DataStorage = pcall(require, "datastorage") - return okd and DataStorage:getSettingsDir() or "." -end - -local function store(name) - local LuaSettings = require("luasettings") - return LuaSettings:open(settingsDir() .. "/" .. name) -end - --- The plugin's modules this feature calls; nil and one log line when the plugin changed. -function EOB.mods() - local m = { - api = package.loaded["bookorbit_api"], - state = package.loaded["bookorbit_state_manager"], - sidecar = package.loaded["bookorbit_sidecar"], - } - local missing = {} - for k, needs in pairs(EOB.COMPAT) do - if k ~= "plugin" then - if type(m[k]) ~= "table" then table.insert(missing, k) - else for _, n in ipairs(Compat.missingOn(m[k], needs)) do table.insert(missing, k .. "." .. n) end end - end - end - if #missing > 0 then - if not compat_logged.end_of_book then - compat_logged.end_of_book = true - table.sort(missing) - log("compat: end of book off (plugin changed): missing " .. table.concat(missing, ", ")) - end - return nil - end - return m -end - -function EOB.usable(p) - return p ~= nil and #Compat.missingOn(p, EOB.COMPAT.plugin) == 0 and EOB.mods() ~= nil -end - ----------------------------------------------------------------- the queue and the detail cache - -function EOB.queue() - if not EOB.jobs then - local okq, q = pcall(function() return store(EOB.QUEUE_FILE):readSetting("jobs") end) - EOB.jobs = (okq and type(q) == "table") and q or {} - end - return EOB.jobs -end - -function EOB.save() - local oks, err = pcall(function() - local st = store(EOB.QUEUE_FILE) - st:saveSetting("jobs", EOB.queue()) - st:saveSetting("downloads", EOB.wants_download or {}) - st:flush() - end) - if not oks then log("end of book: can't save the queue:", err) end -end - -function EOB.downloads() - if not EOB.wants_download then - local okq, q = pcall(function() return store(EOB.QUEUE_FILE):readSetting("downloads") end) - EOB.wants_download = (okq and type(q) == "table") and q or {} - end - return EOB.wants_download -end - -function EOB.cache() - if not EOB.details then - local okc, c = pcall(function() return store(EOB.CACHE_FILE):readSetting("books") end) - EOB.details = (okc and type(c) == "table") and c or {} - end - return EOB.details -end - --- Keeps what the sheet draws from a book detail (server S13), newest EOB.CACHE_MAX books. -function EOB.remember(detail) - if type(detail) ~= "table" or detail.id == nil then return end - local keep = { id = detail.id, title = detail.title, authors = detail.authors, seriesId = detail.seriesId, - seriesName = detail.seriesName, seriesIndex = detail.seriesIndex, readStatus = detail.readStatus, - rating = detail.rating, files = detail.files, seriesMembers = detail.seriesMembers, - relatedSections = detail.relatedSections, saved_at = os.time() } - local c = EOB.cache() - c[tostring(detail.id)] = keep - local ids = {} - for k, v in pairs(c) do table.insert(ids, { k = k, at = v.saved_at or 0 }) end - table.sort(ids, function(a, b) return a.at > b.at end) - for i = EOB.CACHE_MAX + 1, #ids do c[ids[i].k] = nil end - -- The companion persists its saved detail by id. Never serialize/flush the - -- growing detail cache on KOReader's UI thread. - if not Companion.workerProblem() then - Companion.send(Companion.ACTION.PATCH, { reason = "remember detail", remember_id = tostring(detail.id) }) - end -end - --- The open book: { digest, file, book_id, summary, doc_settings } or nil when it isn't a --- BookOrbit book (no server id: the end screen stays KOReader's). -function EOB.bookOf(ui) - local p = ui and ui.bookorbit - local m = EOB.mods() - if not (p and m and ui.document and ui.doc_settings) or not EOB.usable(p) then return nil end - local okd, digest = pcall(p.getDocumentDigest, p) - if not okd or type(digest) ~= "string" then return nil end - EOB.page_digests[ui] = { file = ui.document.file, digest = digest } - local okb, book = pcall(m.state.getBook, digest) - local id = okb and type(book) == "table" and book.bookId or nil - return { digest = digest, file = ui.document.file, book_id = id, summary = ui.doc_settings:readSetting("summary") or {}, - doc_settings = ui.doc_settings, plugin = p } -end - --- Is this book on the device? Its path, from the plugin's map (byBookId: id -> file record). -function EOB.onDevice(book_id) - local m = EOB.mods() - if not m or book_id == nil then return nil end - local okm, maps = pcall(m.state.onDeviceMaps) - local rec = okm and type(maps) == "table" and maps.byBookId and maps.byBookId[book_id] or nil - if type(rec) == "table" then return rec.file or rec.path end - if type(rec) == "string" then return rec end - return nil -end - ----------------------------------------------------------------- marking (§3, §4 hooks) - --- KOReader's markBook ran (any route: the sheet, the end dialog, the menus). complete -> a job --- (unsent until the book is left); anything else -> the unsent job is gone. -function EOB.onMarked(ui) - local b = EOB.bookOf(ui) - if not b then return end - local q = EOB.queue() - if b.summary.status == "complete" then - local pct = nil - pcall(function() pct = ui.bookorbit:getLastPercent() end) - local job = Finish.put(q, Finish.newJob({ hash = b.digest, book_id = b.book_id, file = b.file, - finished_on = Finish.day(os.time()), final_pos = { percentage = pct }, - status_seen = EOB.cache()[tostring(b.book_id)] and EOB.cache()[tostring(b.book_id)].readStatus or nil, - now = os.time() })) - job.ready = false - EOB.session[b.digest] = { forward = 0, released = false } - log("end of book: marked finished", b.book_id or "(no id)", "| sends after the book is left") - else - if Finish.cancel(q, b.digest) then log("end of book: unmarked; nothing will be sent") end - if EOB.session[b.digest] then EOB.session[b.digest].released = true end - end - EOB.save() - if LocalState then LocalState.noteMark(b, b.summary.status) end -end - --- Leaving the book (close, suspend, Home, another book): its job is ready to send. -function EOB.onLeave(ui) - local b = EOB.bookOf(ui) - -- Home is painted over the open book, which has sent nothing yet: its position and status - -- go into the local overlay first, so the first paint already shows them (item 4). - if b and LocalState then - local okp, pct = pcall(b.plugin.getLastPercent, b.plugin) - local fields = { pending = true, bookId = b.book_id } - if okp and type(pct) == "number" then fields.percent = math.floor(pct * 1000 + 0.5) / 10 end - if type(b.summary.status) == "string" then fields.status = b.summary.status end - pcall(LocalState.put, b.digest, fields) - pcall(LF.noteOnDevice, b.book_id, ui and ui.document and ui.document.file) - log("home: noted the open book for Home:", tostring(fields.percent) .. "%", tostring(fields.status)) - end - local job = b and EOB.queue()[b.digest] - if job and not job.ready then - job.ready = true - EOB.save() - log("end of book: left the book; the finish goes with the next sync") - end -end - -function EOB.installReaderHooks() - local okr, ReaderStatus = pcall(require, "apps/reader/modules/readerstatus") - if not okr or type(ReaderStatus) ~= "table" then return false end - if #Compat.missingOn(ReaderStatus, { onEndOfBook = "function", markBook = "function" }) > 0 then - log("compat: end of book off: KOReader's ReaderStatus changed") - return false - end - wrap(ReaderStatus, "markBook", function(stock) return function(self, mark_read) - local r = stock(self, mark_read) - local okm, err = pcall(EOB.onMarked, self.ui) - if not okm then log("end of book: mark hook failed:", err) end - return r - end end, "eob") - wrap(ReaderStatus, "onEndOfBook", function(stock) return function(self, ...) - if S.eob_sheet == false then return stock(self, ...) end - local b = EOB.bookOf(self.ui) - if not b or not b.book_id then return stock(self, ...) end - if (b.summary.status ~= "complete") and S.eob_auto ~= false then self:markBook(true) end - local oks, err = pcall(EOB.showSheet, self.ui, b) - if not oks then - log("end of book: sheet failed, KOReader's own end screen instead:", err) - return stock(self, ...) - end - return true - end end, "eob") - return true -end - ----------------------------------------------------------------- the sheet (§4) - --- What the sheet shows, from the cached detail: { title, author, stars, next = card, --- suggestion = { line, title, book_id, action }, status }. -function EOB.model(b) - local d = EOB.cache()[tostring(b.book_id)] or { id = b.book_id } - local job = EOB.queue()[b.digest] - local n = Finish.next(d) - local card = n and Finish.nextCard(n, n.book and EOB.onDevice(n.book.id) ~= nil) or nil - local sugg = Finish.suggestions(d, Finish.SUGGEST_ANDROID, n and n.book and n.book.id)[1] - local s = nil - if sugg then - local author = Finish.author(d) - s = { line = sugg.source == "author" and author and ("Also by " .. author) or "You might like", - title = sugg.book.title, book_id = sugg.book.id, action = EOB.onDevice(sugg.book.id) and "open" or "download" } - end - local rating = job and job.rating - if rating == "clear" then rating = nil elseif rating == nil then rating = tonumber(b.summary.rating) end - return { - status = job and "✓ Marked as finished" or "Not marked as finished", - undo = job ~= nil, - can_mark = job == nil, - title = d.title or (b.file and b.file:match("([^/]+)$")) or "", - author = Finish.author(d), - stars = rating, - next = card, - suggestion = s, - } -end - --- Actions behind the sheet's taps (the widget calls these; the tests call them directly). -EOB.actions = {} - -function EOB.actions.undo(ui, b) - ui.status:markBook(false) -- "Mark as reading": KOReader's own route; our hook drops the job - EOB.closeSheet() - UIManager:show(require("ui/widget/infomessage"):new{ text = "Not marked as finished", timeout = 2 }) -- gate: exception (end-of-book sheet) -end - -function EOB.actions.mark(ui, b) - ui.status:markBook(true) - EOB.refreshSheet(ui, b) -end - -function EOB.actions.star(ui, b, n) - local job = EOB.queue()[b.digest] - local cur = job and job.rating or tonumber(b.summary.rating) - if cur == "clear" then cur = nil end - local summary = b.doc_settings:readSetting("summary") or {} - if cur == n then summary.rating = nil else summary.rating = n end - b.doc_settings:saveSetting("summary", summary) - if job then Finish.setRating(job, n, cur); EOB.save() end - EOB.refreshSheet(ui, b) -end - -function EOB.actions.review(ui) - EOB.closeSheet() - if ui.status and ui.status.onShowBookStatus then ui.status:onShowBookStatus() end -end - -function EOB.actions.author(ui, b, name) - EOB.closeSheet() - EOB.withCatalog(ui, function(cat) cat:loadBooks({ author = name, sort = "series" }, name, true) end) -end - -function EOB.actions.back() EOB.closeSheet() end - -function EOB.actions.home(ui) - EOB.leaveForHome(ui) - if state.module then state.module:onOrbitGoHome() end -end - --- Any Home while the book stays open underneath (BookOrbit home opens over the reader): the --- sheet closes first, and Home counts as leaving the book, so the finish is sent now rather --- than whenever the book is finally closed. -function EOB.leaveForHome(ui) - local had_sheet = EOB.sheet ~= nil - EOB.closeSheet() - ui = ui or liveUI() - if not (ui and ui.document) then return had_sheet end - local b = EOB.bookOf(ui) - -- Home is painted over the open book, which has sent nothing yet: its position and status - -- go into the local overlay first, so the first paint already shows them (item 4). - if b and LocalState then - local okp, pct = pcall(b.plugin.getLastPercent, b.plugin) - local fields = { pending = true, bookId = b.book_id } - if okp and type(pct) == "number" then fields.percent = math.floor(pct * 1000 + 0.5) / 10 end - if type(b.summary.status) == "string" then fields.status = b.summary.status end - pcall(LocalState.put, b.digest, fields) - pcall(LF.noteOnDevice, b.book_id, ui and ui.document and ui.document.file) - log("home: noted the open book for Home:", tostring(fields.percent) .. "%", tostring(fields.status)) - end - local job = b and EOB.queue()[b.digest] - if job and not job.ready then - job.ready = true - EOB.save() - log("end of book: Home counts as leaving the book; sending the finish now") - EOB.sendSoon(b.plugin) - end - return had_sheet -end - --- Network up, then the plugin's outbox, then our drain (the Sync.waitOutbox hook below). -function EOB.sendSoon(p) - if not p then return end - Wifi.acquire("eob_send") - Net.up(p, { reason = "eob_send", cap = 20, need_server = true }, function(ok) - if not ok then - Wifi.release("eob_send") - log("end of book: no network; the finish goes with the next sync") - return - end - Sync.waitOutbox(p, 20, function() Wifi.release("eob_send") end) - end) -end - --- Open or download-and-open a book from the sheet (§4 "Download & open"). -function EOB.actions.book(ui, b, book_id, title) - local path = EOB.onDevice(book_id) - if path then - EOB.closeSheet() - return EOB.openBook(ui, path) - end - EOB.downloadAndOpen(ui, b, book_id, title) -end - -function EOB.openBook(ui, path) - EOB.onLeave(ui) - UIManager:nextTick(function() - log("orbit: closing reader because end-of-book selected another book") - require("apps/reader/readerui"):showReader(path) - end) -end - --- The plugin's catalog class with what its download and list code need, without opening the --- catalog screen: its own download (progress through our reporter), match-check and link. -function EOB.headlessCatalog(p) - local Catalog = package.loaded["bookorbit_catalog"] - if type(Catalog) ~= "table" or #Compat.missingOn(Catalog, EOB.CATALOG) > 0 then return nil end - local cat = setmetatable({ client = p:newClient(), settings = p.settings, plugin = p, ui = p.ui, - catalog_closed = true, stack = {}, item_table = {} }, { __index = Catalog }) - cat.refreshOnDevice = function() end - -- false, not nil: the download checks each with "self.x and self:x()" (bookorbit_catalog_download.lua - -- :291-300), and nil would fall through to the class. - cat.updateItems, cat.markStackDirty, cat.bookMode, cat.dashboardMode, cat.detailMode = false, false, false, false, false - cat.detailShowDownloadProgress = false - return cat -end - --- The catalog screen for the author page: the plugin's own catalog (opened if needed). -function EOB.withCatalog(ui, fn) - local p = serverPlugin(ui) - if not p then return end - local cat = p.catalog_browser - if cat then return fn(cat) end - pluginEvent(ui, p, "BookOrbitOpenDashboard") - UIManager:scheduleIn(0.3, function() - if p.catalog_browser then fn(p.catalog_browser) end - end) -end - -function EOB.downloadAndOpen(ui, b, book_id, title) - local p = b.plugin - EOB.setCard(ui, b, book_id, "Connecting…") - Wifi.acquire("eob_download") - Net.up(p, { reason = "eob_download", cap = 20, need_server = true }, function(ok) - if not ok then - Wifi.release("eob_download") - return EOB.setCard(ui, b, book_id, nil, "failed") - end - -- The finish goes first on this connection (§3: final position -> status). - EOB.onLeave(ui) - EOB.drain(p, false, function() - EOB.download(p, book_id, function(dl_ok, path_or_err) - Wifi.release("eob_download") - if not dl_ok then return EOB.setCard(ui, b, book_id, nil, "error", path_or_err) end - EOB.closeSheet() - EOB.openBook(ui, path_or_err) - end, function(text) EOB.setCard(ui, b, book_id, text) end) - end) - end) -end - --- Downloads a book through the plugin (detail, then its default file). done(ok, path | err); --- progress(text) while it runs. -function EOB.download(p, book_id, done, progress) - local cat = EOB.headlessCatalog(p) - if not cat then return done(false, "the BookOrbit plugin changed") end - -- The detail page's Download button's own path: the detail with this reader's delivery variant - -- (bookorbit_catalog_download.lua:92 fetchDeliveryBook), whose files carry the selection and - -- the hash of what the server actually streams (server enrichDeliveryFiles). Without the - -- variant the hash is the source file's and an audio-free rebuild fails it (hash_mismatch). - local detail, err - if Compat.callable(cat.fetchDeliveryBook) then detail, err = cat:fetchDeliveryBook(book_id) - else detail, err = cat.client:catalogBook(book_id) end - if type(detail) ~= "table" then return done(false, err) end - -- A file this reader opens (detail supportedFiles :382), the primary one first. - local files = Compat.callable(cat.supportedFiles) and cat:supportedFiles(detail) or detail.files or {} - local file - for _, f in ipairs(files) do if f.role == "primary" then file = f break end end - file = file or files[1] - if not file then return done(false, "no file this reader can open") end - local target - -- downloadDefaultFile names the file the plugin's way, then hands over to checkDownloadFile. - cat.checkDownloadFile = function(_self, local_path) target = local_path end - cat:downloadDefaultFile(detail, file) - if not target then return done(false, "no download path") end - local okl, lfs = pcall(require, "libs/libkoreader-lfs") - if okl and lfs.attributes(target, "mode") == "file" then return done(true, target) end - local reporter = { - progress = function(received, total) - if progress then - local mb = function(n) return string.format("%.1f", (n or 0) / 1048576) end - local pct = total and total > 0 and math.floor(100 * (received or 0) / total) or 0 - progress(string.format("Downloading %d%% · %s of %s MB", pct, mb(received), mb(total))) - end - end, - finished = function(ok, ferr, path) done(ok, ok and (path or target) or ferr) end, - } - cat:downloadFile(target, detail, file, reporter) -end - --- The card's state while downloading: text (progress), or a failure: "failed" (couldn't connect: --- Try again / Get it at the next sync), "error" (the server said no: Try again). -function EOB.setCard(ui, b, book_id, text, failure, err) - EOB.card_state = { book_id = book_id, text = text, failure = failure, err = err } - if failure then log("end of book: download", failure, tostring(err or "")) end - EOB.refreshSheet(ui, b) -end - -function EOB.actions.retry(ui, b, book_id, title) EOB.downloadAndOpen(ui, b, book_id, title) end - -function EOB.actions.later(ui, b, book_id, title) - EOB.downloads()[tostring(book_id)] = { book_id = book_id, title = title, at = os.time() } - EOB.save() - EOB.card_state = nil - EOB.closeSheet() - UIManager:show(require("ui/widget/infomessage"):new{ text = "It downloads at the next sync", timeout = 2 }) -- gate: exception (end-of-book sheet) -end - -function EOB.showSheet(ui, b) - EOB.closeSheet() - EOB.card_state = nil - EOB.sheet = EndSheet:new{ ui = ui, book = b, model = EOB.model(b) } - UIManager:show(EOB.sheet) -- gate: exception (the reader reached the end) - log("end of book: sheet shown for", b.book_id) -end - -function EOB.refreshSheet(ui, b) - if not EOB.sheet then return end - EOB.sheet:update(EOB.model(b), EOB.card_state) -end - -function EOB.closeSheet() - if EOB.sheet then - local s = EOB.sheet - EOB.sheet = nil - UIManager:close(s) - end -end - ----------------------------------------------------------------- sending (§3) - --- After the plugin's outbox: every ready job, then wanted downloads, then the open book's detail --- for the sheet. Runs only with the network up (Sync.waitOutbox's callers bring it up). -function EOB.drain(p, manual, done) - done = done or function() end - -- Outbox waits also complete during reading. These finish/detail operations - -- include synchronous catalog calls and file writes: wait for the next lifecycle - -- sync outside reading, rather than running them on a page's input loop. - if reading() then return done() end - if not EOB.usable(p) then return done() end - local m = EOB.mods() - local client = p:newClient() - local now = os.time() - local sent = 0 - for _, job in ipairs(Finish.due(EOB.queue(), now, manual)) do - if job.ready then - local r = EOB.sendJob(p, m, client, job, now) - if r == "sent" or r == "drop" then EOB.queue()[job.hash] = nil; sent = sent + 1 end - if r == "auth" then - UIManager:show(require("ui/widget/infomessage"):new{ text = "Sign in to BookOrbit to send", timeout = 3 }) -- gate: exception (end-of-book sheet) - break - end - end - end - EOB.save() - if sent > 0 and EOB.sheet then - UIManager:show(require("ui/widget/infomessage"):new{ text = "Finished · sent", timeout = 2 }) -- gate: exception (end-of-book sheet) - end - EOB.refreshOpenDetail(p, client) - EOB.pendingDownloads(p, done) -end - --- One job: guard read -> read-status -> rating -> write back. "sent" | "retry" | "auth" | "drop". -function EOB.sendJob(p, m, client, job, now) - local function fail(code, step) - local what = Finish.onError(job, code, now) - log("end of book:", step, "failed (" .. tostring(code) .. ") ->", what, job.parked and "(parked)" or "") - return what - end - if not job.book_id then - -- No server id: the plugin's book-states from the summary carry it (§3 "No book_id"). - log("end of book: no book id; the plugin's own state sync carries the finish") - return "sent" - end - local detail, err = client:catalogBook(job.book_id) - if type(detail) ~= "table" then return fail(err, "guard read") end - EOB.remember(detail) - local plan = Finish.plan(job, detail.readStatus) - if plan.read_status then - local okr, rerr = client:catalogSetReadStatus(job.book_id, "read") - if not okr then return fail(rerr, "read-status") end - else - log("end of book: read-status skipped:", plan.reason) - end - if plan.rating ~= nil then - local okt, terr = client:catalogSetRating(job.book_id, plan.rating ~= "clear" and plan.rating or nil) - if not okt then return fail(terr, "rating") end - end - EOB.writeBack(p, m, job, plan) - log("end of book: sent", job.book_id, plan.read_status and "read" or "(status kept)", - plan.rating ~= nil and ("rating " .. tostring(plan.rating)) or "") - if LocalState then LocalState.noteSent(job.hash) end - return "sent" -end - --- Step 6: the server's new state into KOReader's summary and the plugin's synced state, so the --- plugin's next state pull keeps it (server S7). -function EOB.writeBack(p, m, job, plan) - local st = { status_known = plan.read_status, status = plan.read_status and "complete" or nil, - status_modified = job.finished_on or os.date("%Y-%m-%d"), - rating_known = plan.rating ~= nil, rating = (plan.rating ~= "clear") and plan.rating or nil } - pcall(function() - local ui = p.ui - if ui and ui.document and ui.document.file == job.file then - m.sidecar.applyServerStateLive(ui, st) - elseif job.file then - m.sidecar.applyServerStateSidecar(job.file, st) - end - end) - local okw, werr = pcall(m.state.mutate, function(session) - local book = session:getBook(job.hash) - if book then m.sidecar.rememberServerState(book, st) end - end) - if not okw then log("end of book: write back failed:", werr) end -end - --- The open book's detail for the sheet (written when online, so the sheet never waits). -function EOB.refreshOpenDetail(p, client) - local b = EOB.bookOf(liveUI()) - if not b or not b.book_id then return end - local cached = EOB.cache()[tostring(b.book_id)] - if cached and os.time() - (cached.saved_at or 0) < 600 then return end - local detail = client:catalogBook(b.book_id) - if type(detail) == "table" then EOB.remember(detail) end -end - --- "Get it at the next sync": downloads asked for while out of range, announced by a toast. -function EOB.pendingDownloads(p, done) - local list = {} - for k, v in pairs(EOB.downloads()) do table.insert(list, { k = k, v = v }) end - local function nextOne(i) - local it = list[i] - if not it then return done() end - EOB.download(p, it.v.book_id, function(ok, res) - if ok then - EOB.downloads()[it.k] = nil - EOB.save() - local title = tostring(it.v.title or "") - Gate.show("downloaded " .. title, function() -- gate: Gate.show - UIManager:show(require("ui/widget/infomessage"):new{ text = "Downloaded: " .. title, timeout = 3 }) - end) - else - log("end of book: next-sync download failed:", tostring(res)) - end - nextOne(i + 1) - end) - end - nextOne(1) -end - ----------------------------------------------------------------- stale-push hold (§7) - --- A push of this book's position should wait: finished here, and 10+ points below the end --- with fewer than 10 page turns forward this session. -function EOB.hold(digest, fraction, summary_status) - if summary_status ~= "complete" or type(fraction) ~= "number" then return false end - local job = EOB.queue()[digest] - local final = job and job.final_pos and tonumber(job.final_pos.percentage) or 1 - local s = EOB.session[digest] or {} - return Finish.holdPush(final * 100, fraction * 100, s.forward, s.released) -end - -function EOB.installPluginHooks(p) - if EOB.plugin_hooked or not EOB.usable(p) then return end - local Cls = getmetatable(p) and getmetatable(p).__index - if type(Cls) ~= "table" or #Compat.missingOn(Cls, { enqueueLifecycleSnapshot = "function", updateProgress = "function" }) > 0 then - return - end - EOB.plugin_hooked = true - wrap(Cls, "enqueueLifecycleSnapshot", function(stock) return function(self, snap, reason) - if type(snap) == "table" and EOB.hold(snap.digest, snap.percentage, snap.status) then - log("end of book: holding a stale position for a finished book (" .. tostring(reason) .. ")") - snap.percentage, snap.progress = nil, nil - end - if LocalState and type(snap) == "table" then pcall(LocalState.noteSnapshot, snap) end - return stock(self, snap, reason) - end end, "eob") - local function liveHold(self) - local b = EOB.bookOf(self.ui) - if not b then return false end - local okp, pct = pcall(self.getLastPercent, self) - if okp and EOB.hold(b.digest, pct, b.summary.status) then - log("end of book: holding a stale live push for a finished book") - return true - end - return false - end - for _, name in ipairs({ "updateProgress", "pushProgressAfterBookSync" }) do - if Compat.callable(Cls[name]) then - wrap(Cls, name, function(stock) return function(self, ...) - if liveHold(self) then return end - return stock(self, ...) - end end, "eob") - end - end -end - --- Page turns forward this session release the hold (§7). -function EOB.onPage(ui, page) - local b = ui and EOB.page_digests[ui] - if not b or not ui.document or b.file ~= ui.document.file then return end - local s = EOB.session[b.digest] or { forward = 0 } - EOB.session[b.digest] = s - if s.last and page > s.last then s.forward = (s.forward or 0) + 1 end - s.last = page -end - ----------------------------------------------------------------- wiring - --- The finish drain follows every outbox wait that went well (wake, open, reading, sleep). -do - local stockWait = Sync.waitOutbox - function Sync.waitOutbox(p, cap, cb) - return stockWait(p, cap, function(ok, why, el) - if not ok then return cb(ok, why, el) end - local okd, err = pcall(EOB.drain, p, false, function() cb(ok, why, el) end) - if not okd then log("end of book: drain failed:", err); cb(ok, why, el) end - end) - end -end - -do - local base_close = OrbitAndroid.onCloseWidget - function OrbitAndroid:onCloseWidget(...) - if self.ui and self.ui.document then pcall(EOB.onLeave, self.ui) end - EOB.closeSheet() - return base_close(self, ...) - end - local base_suspend = OrbitAndroid.onSuspend - function OrbitAndroid:onSuspend(...) - if self.ui and self.ui.document then pcall(EOB.onLeave, self.ui) end - return base_suspend(self, ...) - end - local base_page = OrbitAndroid.onPageUpdate - function OrbitAndroid:onPageUpdate(page, ...) - if type(page) == "number" then pcall(EOB.onPage, self.ui, page) end - return base_page(self, page, ...) - end - local base_ready = OrbitAndroid.onReaderReady - function OrbitAndroid:onReaderReady(...) - local p = serverPlugin(self.ui) - if p then pcall(EOB.installPluginHooks, p) end - pcall(EOB.bookOf, self.ui) -- prime the digest once; page turns never read plugin state - return base_ready(self, ...) - end -end -EOB.installReaderHooks() diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit/grouping.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/grouping.lua deleted file mode 100644 index 904c3f73..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/grouping.lua +++ /dev/null @@ -1,322 +0,0 @@ --- SPDX-License-Identifier: AGPL-3.0-or-later --- Copyright (c) 2026 Fledgewing. Part of BookSync (see android/koreader/LICENSE). --- Part of orbit.koplugin: loaded by main.lua into the plugin's shared environment, in the --- order main.lua lists (docs/design/orbit-plugin.md "Module layout"). - --- Lists by series and by author (v0.6.0): the KOReader side of Group. The plugin's own views --- draw everything; the patch wraps methods on its catalog class (bookorbit_catalog.lua; the --- list methods are copied onto that class by CatalogLists.install, bookorbit_catalog_lists.lua --- :1492-1496, so wrapping CatalogLists would change nothing) and on its API class --- (bookorbit_api.lua). Each wrapper passes through unchanged unless its own mark is there: --- - a list's Sort sheet (listSortSheetModel, :659; rows :707-713) gets "By series" and --- "By author" (action orbit-group) on every book list: a library, collection, smart scope, --- On device, and the whole library's lists (All books, Recently updated; v0.11.2); --- - orbit-group reads the list's books once (catalogBooks, 100 a page, "Reading N of M --- books…"), holds them (Group.remember), and opens the plugin's Series or Authors view --- (loadSection, bookorbit_catalog.lua:974) for them: listSectionParams (:246) hands the --- request to fetch (:881), which answers it from the held books (Group.sectionBody), and --- switchTo (:847) tags the context with orbit_group, so paging, the A-Z rail, sort, the --- filter and reloads (reloadSection :1047, listReload :336) all keep working; --- - listRun (:739) opens a row in the list (open-series / open-author), and the chips; --- - listHeader (:1155) and listToolbar (:1115) say which list, and carry the chips; --- - the API's query (:386) never sends the patch's orbit* marks; catalogBooks (:714) and --- catalogManifest (:720) answer orbitLocal (a smart scope's row past 200 books) from the --- held books. ---------------------------------------------------------------------------------------------- -Grouping = { installed = false } - -function bookCount(n) - return n == 1 and "1 book" or string.format("%d books", n) -end - --- The held list a context belongs to: from its orbit_group, or its request's orbitGroup. -function heldOf(context) - context = context or {} - local token = (context.orbit_group and context.orbit_group.token) or (context.params and context.params.orbitGroup) - return token and Group.held[token] or nil, token -end - --- Reads every book of the current list (inside a connected job), then opens the grouped view. -function Grouping.start(cat, section) - local context = cat.current_context or {} - local params = context.params or {} - local list = Group.listOf(params) - if not list then return end - local function open(token) - cat:loadSection(section, { orbit_group = { token = token, section = section } }) - end - if context.orbit_snapshot and Group.held[context.orbit_snapshot] then - return open(context.orbit_snapshot) - end - cat:runConnected(function() - local t0 = now_s() - local books, total, page = {}, nil, 1 - while true do - local label = total and string.format("Reading %d of %d books…", #books, total) or "Reading the list…" - local q = Group.fetchParams(params, page) - local body, err = cat:fetch(label, function() return cat.client:catalogBooks(q) end) - if not body then - if err ~= "cancelled" then - cat:showRetry(err, function() Grouping.start(cat, section) end) - end - return - end - local items = body.items or {} - for _, b in ipairs(items) do table.insert(books, b) end - total = tonumber(body.total) or total - if #items == 0 or (total and #books >= total) or body.hasNext == false then break end - page = page + 1 - end - local token = Group.remember({ list = list, params = params, title = context.title or "", books = books }) - context.orbit_snapshot = token - log("lists: read", #books, "books of", list.section, tostring(list.id or ""), "for", section, - string.format("in %d ms (%d page(s))", math.floor((now_s() - t0) * 1000 + 0.5), page)) - UIManager:nextTick(function() open(token) end) - end) -end - --- Opens a row of a grouped view: a series' books (in the list), an author's books by series. -function Grouping.openRow(cat, kind, entry) - local context = cat.current_context or {} - local og = context.orbit_group - local snap = Group.held[og.token] - if not snap then return false end - if kind == "open-author" then - cat:loadSection("series", { orbit_group = { token = og.token, section = "series", author = entry.title } }) - return true - end - local key = entry.orbitKey - local books = Group.select(snap.books, og.author, key) - local marks = { orbitGroup = og.token, orbitAuthor = og.author, orbitSeries = key } - local target, flat - if key == Group.STANDALONE then - target, flat = { sort = "title" }, true - else - target = cat:paramsForEntry("series", entry) - if og.author then target.author = og.author end - end - local p, how = Group.drill(snap.list, snap.params, books, target, marks, flat) - log("lists: open", entry.title, "in", snap.list.section, tostring(snap.list.id), "(" .. how .. ", " .. #books .. " books)") - cat:loadBooks(p, entry.title, true) - return true -end - --- The chips: an author's books by series, all of them flat, or the author with no list. -function Grouping.chip(cat, chip) - local context = cat.current_context or {} - local params = context.params or {} - local snap, token = heldOf(context) - local author = (context.orbit_group and context.orbit_group.author) or params.orbitAuthor - if chip == "whole-series" then - local whole = { sort = "series", seriesId = params.seriesId, series = params.series } - return cat:loadBooks(whole, context.title, true) - end - if chip == "all-by-author" and author then - return cat:loadBooks({ author = author, sort = "series" }, author, true) - end - if not snap or not author then return end - if chip == "by-series" then - return cat:loadSection("series", { orbit_group = { token = token, section = "series", author = author }, replace = true }) - end - if chip == "all-books" then - local books = Group.select(snap.books, author, nil) - local p = Group.drill(snap.list, snap.params, books, { sort = "title" }, { orbitGroup = token, orbitAuthor = author }, true) - return cat:loadBooks(p, author, false) - end -end - -function chipButton(label, on, chip, icon) - return { icon = icon, label = label, on = on, action = { kind = "orbit-chip", chip = chip }, key = "orbit-" .. chip } -end - -function authorChips(on) - return { - chipButton("By series", on == "by-series", "by-series", "layers-2"), - chipButton("All books", on == "all-books", "all-books", "book"), - chipButton("All by author", false, "all-by-author", "user"), - } -end - --- Wraps one class method once per feature; the function it wrapped stays callable as --- Cls.__orbit_stock[key] (key: the method name for grouping, ":" otherwise). --- Features share one chain per method, in install order: grouping (at init) first, then --- local-first and end of book (docs/design/local-first/DESIGN.md "Sharing hooks"). -function wrap(Cls, name, make, feature) - local stock = rawget(Cls, "__orbit_stock") or {} - rawset(Cls, "__orbit_stock", stock) - local key = feature and (feature .. ":" .. name) or name - if stock[key] then return end - stock[key] = Cls[name] - Cls[name] = make(stock[key]) -end - -function Grouping.install(why) - if Grouping.installed then return true end - local Catalog = package.loaded["bookorbit_catalog"] - local Api = package.loaded["bookorbit_api"] - if type(Catalog) ~= "table" or type(Api) ~= "table" then return false end - local missing = {} - for _, m in ipairs(Compat.missingOn(Catalog, Compat.CATALOG_CLASS)) do table.insert(missing, m) end - for _, m in ipairs(Compat.missingOn(Api, Compat.API_CLASS)) do table.insert(missing, "api." .. m) end - if #missing > 0 then - if not compat_logged.grouping then - compat_logged.grouping = true - log("compat: lists by series and author off (plugin changed): missing " .. table.concat(missing, ", ")) - end - return false - end - Grouping.installed = true - - wrap(Api, "query", function(stock) return function(self, path, params) - return stock(self, path, Group.strip(params)) - end end) - wrap(Api, "catalogBooks", function(stock) return function(self, params) - if type(params) == "table" and params.orbitLocal == "1" then - local books = Group.localBooks(params) - if not books then return nil, 404 end - return Group.booksBody(books, params) - end - return stock(self, params) - end end) - wrap(Api, "catalogManifest", function(stock) return function(self, params) - if type(params) == "table" and params.orbitLocal == "1" then - local books = Group.localBooks(params) - if not books then return nil, 404 end - local p = Group.strip(params) - p.ids = Group.ids(books, Group.MANIFEST_IDS_MAX) - return stock(self, p) - end - return stock(self, params) - end end) - - wrap(Catalog, "listSortSheetModel", function(stock) return function(self, sheet) - local m = stock(self, sheet) - local context = self.current_context or {} - local params = context.params or {} - if type(m) == "table" and type(m.rows) == "table" and self:listKind() == "books" - and Group.listOf(params) and not params.orbitGroup then - table.insert(m.rows, 1, { icon = "user", label = "By author", value = "authors in this list", chevron = true, - action = { kind = "orbit-group", section = "authors" }, key = "orbit-authors" }) - table.insert(m.rows, 1, { icon = "layers-2", label = "By series", value = "series in this list", chevron = true, - action = { kind = "orbit-group", section = "series" }, key = "orbit-series" }) - end - return m - end end) - - wrap(Catalog, "listRun", function(stock) return function(self, action, region, hold) - local context = self.current_context or {} - local kind = type(action) == "table" and action.kind - if not hold and kind == "orbit-group" then - context.list_sheet = nil - pcall(self.updateItems, self, nil, true) -- the sheet closes while the list is read - return Grouping.start(self, action.section) - elseif not hold and kind == "orbit-chip" then - return Grouping.chip(self, action.chip) - elseif not hold and (kind == "open-series" or kind == "open-author") and context.orbit_group - and not context.dashboard_source_index and action.entry then - if Grouping.openRow(self, kind, action.entry) then return end - end - return stock(self, action, region, hold) - end end) - - -- A grouped view's request: marked by loadSection, taken by listSectionParams, answered by fetch. - wrap(Catalog, "loadSection", function(stock) return function(self, section, opts) - opts = opts or {} - local og = opts.orbit_group - local cur = self.current_context or {} - if not og and opts.replace and cur.kind == "section" and cur.section == section and cur.orbit_group then - og = cur.orbit_group - end - self._orbit_pending = og and Group.held[og.token] and { section = section, group = og } or nil - return stock(self, section, opts) - end end) - wrap(Catalog, "listSectionParams", function(stock) return function(self, section, opts) - local params = stock(self, section, opts) - local pend = self._orbit_pending - self._orbit_pending = nil - if pend and pend.section == section then self._orbit_next = { group = pend.group, params = params or {} } end - return params - end end) - wrap(Catalog, "fetch", function(stock) return function(self, text, fn, opts) - local nxt = self._orbit_next - if nxt then - self._orbit_next = nil - local snap = Group.held[nxt.group.token] - if snap then - local og = nxt.group - local t0 = os.clock() - -- The groups are built once per held list (and author); paging, sort and filter - -- reuse them. - snap.rows = snap.rows or {} - local rk = og.section .. "|" .. tostring(og.author or "") - local built = snap.rows[rk] - if not built then - local books = og.author and Group.select(snap.books, og.author, nil) or snap.books - built = { rows = og.section == "authors" and Group.authors(books) or Group.series(books), - extra = og.author and Group.standalone(books) or nil } - snap.rows[rk] = built - log(string.format("lists: grouped %d books of %s by %s in %d ms", #snap.books, tostring(snap.list.section), - og.section == "authors" and "author" or "series", math.floor((os.clock() - t0) * 1000 + 0.5))) - end - self._orbit_tag = og - return Group.sectionBody(built.rows, og.section, nxt.params, built.extra) - end - end - return stock(self, text, fn, opts) - end end) - wrap(Catalog, "switchTo", function(stock) return function(self, title, item_table, context, push) - local tag = self._orbit_tag - self._orbit_tag = nil - if tag and type(context) == "table" and context.kind == "section" then context.orbit_group = tag end - return stock(self, title, item_table, context, push) - end end) - - wrap(Catalog, "listHeader", function(stock) return function(self, kind, context) - local h = stock(self, kind, context) - local snap = heldOf(context) - if type(h) ~= "table" or not snap or h.select then return h end - local name = snap.title ~= "" and snap.title or "this list" - local og = context.orbit_group - if og and og.author then - local n = #Group.select(snap.books, og.author, nil) - h.title, h.title_data = og.author, true - h.sub = string.format("%s in %s · by series", bookCount(n), name) - elseif og then - h.title = string.format(og.section == "authors" and "Authors in %s" or "Series in %s", name) - h.title_data = true - elseif kind == "seriespage" or kind == "books" then - local n = tonumber(context.total) or #(context.books or {}) - if kind == "seriespage" then - local summary = context.series_summary or {} - n = tonumber(summary.total) or n - local b = context.books and context.books[1] - local who = b and b.authors and b.authors[1] - h.sub = (who and (who .. " · ") or "") .. string.format("%s in %s", bookCount(n), name) - else - local sort = Compat.callable(self.listSortLabel) and (" · " .. self:listSortLabel(context.params or {})) or "" - h.sub = string.format("%s in %s", bookCount(n), name) .. sort - end - end - return h - end end) - - wrap(Catalog, "listToolbar", function(stock) return function(self, kind, context) - local buttons = stock(self, kind, context) - local snap = heldOf(context) - if not snap then return buttons end - local og = context.orbit_group - local params = context.params or {} - if og and og.author then return authorChips("by-series") end - if kind == "books" and params.orbitAuthor and not params.orbitSeries then return authorChips("all-books") end - if kind == "seriespage" then - buttons = type(buttons) == "table" and buttons or {} - table.insert(buttons, chipButton("Whole series", false, "whole-series", "layers-2")) - end - return buttons - end end) - - log("lists: by series and by author on (" .. tostring(why) .. ")") - return true -end - ---------------------------------------------------------------------------------------------- diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit/recommended.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/recommended.lua deleted file mode 100644 index 026e4673..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/recommended.lua +++ /dev/null @@ -1,497 +0,0 @@ --- SPDX-License-Identifier: AGPL-3.0-or-later --- Copyright (c) 2026 Fledgewing. Part of BookSync (see android/koreader/LICENSE). --- Part of orbit.koplugin: loaded by main.lua into the plugin's shared environment, in the --- order main.lua lists (docs/design/orbit-plugin.md "Module layout"). - --- Recommended settings, applied by themselves at setup and on updates (docs/design/addon-mode.md --- §5; the decisions are logic/server/bookorbit/recommended.lua's). This side reads and writes each item, keeps --- the backup (S.recommended_backup) and shows the line and the review page. ---------------------------------------------------------------------------------------------- - -Rec = { session_applied = 0, line_pending = false } - --- What a pass reads: the BookOrbit plugin, KOReader's Gestures plugin (it may be off). -function Rec.context(ui) - ui = liveUI() or ui - return { p = serverPlugin(ui), gestures = ui and ui.gestures or nil } -end - --- KOReader's stock gesture defaults in books: the Gestures plugin keeps defaults.lua as --- Gestures.default_settings (gestures.koplugin main.lua:229), read the way it marks "(default)" --- (main.lua:249, :310-312), so device-dependent defaults (a frontlight) come out right. -local function gestureDefaults(g) - local ds = g and g.default_settings - local data = type(ds) == "table" and ds.data or nil - return type(data) == "table" and type(data.gesture_reader) == "table" and data.gesture_reader or nil -end - --- { available, reason, current, default } for one item. --- raw: read the value even when the item's capability is missing (Undo after a cap went away). -function Rec.observe(it, ctx, raw) - if it.needs and not raw and not Companion.has(it.needs) then - return { available = false, reason = Rec.capReason(it.needs) } - end - if it.kind == "bo" then - local p = ctx.p - if not p or type(p.settings) ~= "table" then return { available = false, reason = _("needs the BookOrbit plugin") } end - local defaults = p.default_settings - if type(defaults) ~= "table" then return { available = false, reason = _("BookOrbit changed: its defaults can't be read") } end - if it.key == "catalog_auto_open" and not Compat.settable(p.settings, it.key, it.ours) then - return { available = false, reason = _("BookOrbit changed: Make BookOrbit home") } - end - if it.key == "auto_sync" and not hasHandler(p, "BookOrbitToggleAutoSync") then - return { available = false, reason = _("BookOrbit changed: Auto-sync can't be turned on") } - end - -- Under OrbiSmart the plugin's further ahead / behind are Orbit's (ko/server/bookorbit/orbismart.lua); the - -- reader's own value, kept for Custom, is the one recommended and reviewed. - local saved = OSM and OSM.savedPluginSetting and OSM.savedPluginSetting(it.key) - if saved ~= nil then return { available = true, current = saved.value, default = defaults[it.key] } end - return { available = true, current = p.settings[it.key], default = defaults[it.key] } - elseif it.kind == "ko" then - if it.required_by == "wifi" and not S.wifi_via_companion and not raw then - return { available = false, reason = _("needs Wi-Fi via BookSync Companion") } - end - return { available = true, current = G_reader_settings:readSetting(it.key), default = nil } - elseif it.kind == "gesture" then - local g = ctx.gestures - local defaults = gestureDefaults(g) - if not g or type(g.data) ~= "table" or not defaults then - return { available = false, reason = _("Turn on KOReader's Gestures plugin") } - end - local mine = type(g.data.gesture_reader) == "table" and g.data.gesture_reader or {} - return { available = true, current = mine[it.key], default = defaults[it.key] } - end - return { available = false, reason = "unknown item" } -end - -function Rec.capReason(cap) - if not Companion.installed() then return _("needs BookSync Companion") end - if cap == "wifi" then return _("needs Wi-Fi switching in BookSync Companion") end - if cap == "apps" then return _("needs Full mode in BookSync Companion") end - return _("needs BookSync Companion") -end - --- Write one item. value nil: back to unset. Returns true when the value took. -function Rec.write(it, ctx, value) - if it.kind == "bo" then - local p = ctx.p - if not p then return false end - if OSM and OSM.setSavedPluginSetting and OSM.setSavedPluginSetting(it.key, Recommended.copy(value)) then - G_reader_settings:flush() - return true - elseif it.key == "auto_sync" then - -- The plugin's own toggle also registers its reader events (main.lua:1416-1448). - if (p.settings.auto_sync == true) ~= (value == true) then - pluginEvent(liveUI(), p, "BookOrbitToggleAutoSync", value == true, true, true) - end - else - -- Saved the way the plugin's own settings page saves (bookorbit_settings_page.lua:822-825); - -- under OrbiSmart into the value kept for Custom. - if not (OSM and OSM.setSavedPluginSetting and OSM.setSavedPluginSetting(it.key, Recommended.copy(value))) then - p.settings[it.key] = Recommended.copy(value) - end - end - G_reader_settings:flush() - return Recommended.equal(p.settings[it.key], value) - elseif it.kind == "ko" then - if value == nil and G_reader_settings.delSetting then G_reader_settings:delSetting(it.key) - else G_reader_settings:saveSetting(it.key, value) end - return Recommended.equal(G_reader_settings:readSetting(it.key), value) - elseif it.kind == "gesture" then - local g = ctx.gestures - if not g or type(g.data) ~= "table" then return false end - -- The same write path the plugin uses for its shortcut (bookorbit_shortcut.lua:111-117). - g.data.gesture_reader = g.data.gesture_reader or {} - g.data.gesture_reader[it.key] = Recommended.copy(value) - g.updated = true - if g.onFlushSettings then g:onFlushSettings() end - return true - end - return false -end - -function Rec.saveRecord(record) - S.recommended = record - S.recommended_backup = S.recommended_backup or {} - saveSettings() -end - --- One pass (§5.3): looks only at items no pass settled. only: { [id] = true } (the load-time pass --- for KOReader's Wi-Fi action). Returns the plan. -function Rec.pass(why, ui, only) - local ctx = Rec.context(ui) - local plan = Recommended.plan(Recommended.ITEMS, S.recommended, function(it) return Rec.observe(it, ctx) end, only) - if #plan.decisions == 0 then return plan end - S.recommended_backup = S.recommended_backup or {} - local okmap = {} - for _i, d in ipairs(plan.decisions) do - if d.state == "at_default" then - local entry = Recommended.backup(d.obs, d.item, os.time()) - local okw, took = pcall(Rec.write, d.item, ctx, d.item.ours) - if okw and took then - S.recommended_backup[d.item.id] = entry - else - okmap[d.item.id] = false - log("recommended:", d.item.id, "could not be applied:", tostring(took)) - end - end - end - local record, applied = Recommended.record(S.recommended, plan, os.time(), okmap) - Rec.saveRecord(record) - Rec.session_applied = Rec.session_applied + applied - if applied > 0 then Rec.line_pending = true end - local parts = {} - for _i, d in ipairs(plan.decisions) do - table.insert(parts, d.item.id .. "=" .. (record.items[d.item.id] or "?") .. (d.obs.reason and ("(" .. d.obs.reason .. ")") or "")) - end - log("recommended (" .. why .. "): applied", applied, "| to review", plan.conflicts, "|", table.concat(parts, " ")) - if why ~= "load" then pcall(Rec.report, "recommended " .. why, false, ui) end - return plan -end - --- The line for the menu and the toast, from the record: unseen applied + conflicts waiting. -function Rec.line() - local c = Recommended.counts(S.recommended) - return Recommended.lineText(type(S.recommended) == "table" and S.recommended.unseen or 0, c.conflict) -end - --- After a pass that changed something: the line for 4 s, off a book only (§5.4). In a book it --- waits for the next off-book moment (Home, the menu, the setup box's checks). -function OrbitAndroid:maybeRecommendedLine(where) - if not Rec.line_pending then return end - where = where or self:whereNow() - if where == "reader" then return end - local text = Rec.line() - Rec.line_pending = false - if not text then return end - log("recommended: line shown in " .. where .. ": " .. text) - orbitNote(_(text) .. " · " .. _("Tools › BookSync › Recommended settings"), 4) -end - --- Start: a pass once the BookOrbit plugin instance can be found (module.lua's next-tick fallback). -function OrbitAndroid:recommendedPass(why) - local okp, err = pcall(Rec.pass, why, self.ui) - -- The first report of this process, changed or not: the companion may have been updated. - pcall(Rec.report, why, true, self.ui) - if not okp then log("recommended: pass failed:", tostring(err)) return end - self:maybeRecommendedLine() -end - ---------------------------------------------------------------------------------------------- --- Review page (§5.5): To review (Use Orbit's / Keep mine), Applied (with Undo), Kept yours, --- Unavailable; Use all of Orbit's, Keep all mine, Undo all. ---------------------------------------------------------------------------------------------- - -local function setStatus(id, st) - S.recommended = S.recommended or { rev = Recommended.REV, items = {} } - S.recommended.items = S.recommended.items or {} - S.recommended.items[id] = st - saveSettings() -end - --- "Use Orbit's" on a conflict or a kept item: apply with a backup. -function Rec.useOrbits(it, ctx) - local obs = Rec.observe(it, ctx) - if not obs.available then return false, obs.reason end - local entry = Recommended.backup(obs, it, os.time()) - local okw, took = pcall(Rec.write, it, ctx, it.ours) - if not (okw and took) then return false, tostring(took) end - S.recommended_backup = S.recommended_backup or {} - S.recommended_backup[it.id] = entry - setStatus(it.id, "applied") - log("recommended:", it.id, "Use Orbit's") - return true -end - -function Rec.keepMine(it) - setStatus(it.id, "kept") - log("recommended:", it.id, "Keep mine") -end - --- Undo one applied item. Returns "undone" | "changed" (the user changed it since; left as is). -function Rec.undo(it, ctx) - local entry = (S.recommended_backup or {})[it.id] - local current = Rec.observe(it, ctx, true).current - if not Recommended.undoable(entry, current) then - setStatus(it.id, "kept") - log("recommended:", it.id, "undo: changed since; left as is") - return "changed" - end - pcall(Rec.write, it, ctx, entry.had and entry.prior or nil) - S.recommended_backup[it.id] = nil - setStatus(it.id, "kept") - log("recommended:", it.id, "undone (back to", Recommended.valueLabel(it, entry.prior) .. ")") - return "undone" -end - --- Capabilities went away (Full → Add-on, §8 step 4): undo what needed them, if Orbit set it. -function Rec.capsLost(why, ui) - local ctx = Rec.context(ui) - for _i, it in ipairs(Recommended.lostCaps(S.recommended, Companion.has)) do - local r = Rec.undo(it, ctx) - -- Unavailable again, so the pass re-offers it if the capability comes back. - setStatus(it.id, "unavailable") - log("recommended:", it.id, "capability", it.needs, "gone (" .. why .. "):", r) - end -end - --- KOReader's Wi-Fi action while Wi-Fi switching is on: switching can't work without it. -local function wifiNeeded(it) return it.required_by == "wifi" and S.wifi_via_companion and Companion.has("wifi") end - -function OrbitAndroid:showRecommended(why) - local ctx = Rec.context(self.ui) - if type(S.recommended) == "table" and (S.recommended.unseen or 0) > 0 then - S.recommended.unseen = 0 - saveSettings() - end - log("recommended: review page (" .. tostring(why) .. ")") - local items = {} - local status = type(S.recommended) == "table" and S.recommended.items or {} - local function reopen() - if self.rec_menu then UIManager:close(self.rec_menu); self.rec_menu = nil end - UIManager:scheduleIn(0.1, function() self:showRecommended("refresh") end) - end - local function note(text) UIManager:show(InfoMessage:new{ text = text, timeout = 3 }) end -- gate: user action (Recommended settings menu) - local function dialog(title, buttons) - local ButtonDialog = require("ui/widget/buttondialog") - local d - local row = {} - for _i, b in ipairs(buttons) do - table.insert(row, { text = b[1], callback = function() UIManager:close(d); b[2]() end }) - end - d = ButtonDialog:new{ title = title, buttons = { row } } - UIManager:show(d) -- gate: user action (Recommended settings menu) - return d - end - local groups = { conflict = {}, applied = {}, already = {}, kept = {}, unavailable = {} } - for _i, it in ipairs(Recommended.ITEMS) do - local st = status[it.id] - if groups[st] then table.insert(groups[st], it) end - end - local function cur(it) - local obs = Rec.observe(it, ctx) - return obs.available and Recommended.valueLabel(it, obs.current) or nil, obs - end - local function header(text) table.insert(items, { text = text, bold = true, dim = false, callback = function() end }) end - if #groups.conflict > 0 then - header(_("To review")) - table.insert(items, { text = _("Use all of BookSync's"), callback = function() - for _i, it in ipairs(groups.conflict) do Rec.useOrbits(it, ctx) end - Rec.report("review"); reopen() - end }) - table.insert(items, { text = _("Keep all mine"), callback = function() - for _i, it in ipairs(groups.conflict) do - if wifiNeeded(it) then S.wifi_via_companion = false; saveSettings() end - Rec.keepMine(it) - end - Rec.report("review"); reopen() - end }) - for _i, it in ipairs(groups.conflict) do - local yours = cur(it) or "?" - local orbit = Recommended.valueLabel(it, it.ours) - table.insert(items, { text = _(it.label), mandatory = string.format(_("yours: %s · BookSync's: %s"), yours, orbit), - callback = function() - local keep = { _("Keep mine"), function() Rec.keepMine(it); Rec.report("review"); reopen() end } - if wifiNeeded(it) then - keep = { _("Turn Wi-Fi switching off"), function() - S.wifi_via_companion = false; saveSettings() - log("recommended: Wi-Fi via Orbit Companion turned off (kept KOReader's Wi-Fi action)") - Rec.keepMine(it); Rec.report("review"); reopen() - end } - end - dialog(_(it.label) .. "\n" .. (wifiNeeded(it) and _("Wi-Fi switching needs this.") .. "\n" or ""), { - { _("Use BookSync's"), function() - local okd, why2 = Rec.useOrbits(it, ctx) - if not okd then note(tostring(why2)) end - Rec.report("review"); reopen() - end }, - keep, - }) - end }) - end - end - if #groups.applied + #groups.already > 0 then - header(_("Applied")) - for _i, it in ipairs(groups.applied) do - local entry = (S.recommended_backup or {})[it.id] - local was = entry and Recommended.valueLabel(it, entry.prior) or "?" - table.insert(items, { text = _(it.label), mandatory = string.format(_("%s (was: %s)"), Recommended.valueLabel(it, it.ours), was), - callback = function() - dialog(_(it.label), { { _("Undo"), function() - local function go() - local r = Rec.undo(it, ctx) - if r == "changed" then note(_("Changed since; left as is.")) end - Rec.report("review"); reopen() - end - if wifiNeeded(it) then - UIManager:show(ConfirmBox:new{ -- gate: user action (Recommended settings menu) - text = _("Wi-Fi switching needs this. Turn off Wi-Fi via BookSync Companion and undo?"), - ok_text = _("Turn off and undo"), - ok_callback = function() S.wifi_via_companion = false; saveSettings(); go() end, - }) - else go() end - end } }) - end }) - end - for _i, it in ipairs(groups.already) do - table.insert(items, { text = _(it.label), mandatory = Recommended.valueLabel(it, it.ours), dim = true, callback = function() end }) - end - end - if #groups.kept > 0 then - header(_("Kept yours")) - for _i, it in ipairs(groups.kept) do - table.insert(items, { text = _(it.label), mandatory = cur(it) or "", - callback = function() - dialog(_(it.label), { { _("Use BookSync's"), function() - local okd, why2 = Rec.useOrbits(it, ctx) - if not okd then note(tostring(why2)) end - Rec.report("review"); reopen() - end } }) - end }) - end - end - if #groups.unavailable > 0 then - header(_("Unavailable")) - for _i, it in ipairs(groups.unavailable) do - local _v, obs = cur(it) - table.insert(items, { text = _(it.label), mandatory = obs.reason or "", dim = true, callback = function() end }) - end - end - if #groups.applied > 0 then - table.insert(items, { text = _("Undo all"), callback = function() - local skipped = false - for _i, it in ipairs(groups.applied) do - if wifiNeeded(it) then skipped = true else Rec.undo(it, ctx) end - end - if skipped then note(_("KOReader's Wi-Fi action stays: Wi-Fi switching needs it.")) end - Rec.report("review"); reopen() - end }) - end - if #items == 0 then - table.insert(items, { text = _("No recommended settings yet. They are applied at the next start."), callback = function() end }) - end - table.insert(items, { text = _("Done"), callback = function() - if self.rec_menu then UIManager:close(self.rec_menu); self.rec_menu = nil end - end }) - local Menu = require("ui/widget/menu") - self.rec_menu = Menu:new{ - title = _("Recommended settings"), - item_table = items, - is_borderless = true, - is_popout = false, - covers_fullscreen = true, - close_callback = function() if self.rec_menu then UIManager:close(self.rec_menu); self.rec_menu = nil end end, - } - UIManager:show(self.rec_menu) -- gate: user action (Recommended settings menu) - return self.rec_menu -end - --- The menu row: "Recommended settings" with the line while there is something to say. -function OrbitAndroid:recommendedMenuText() - local line = Rec.line() - return line and (_("Recommended settings: ") .. _(line)) or _("Recommended settings") -end - --- REPORT to the companion (docs/design/addon-mode.md §7.3): one yes/no about the BookOrbit --- login (isLoggedIn, never the server, the account or the key), the recommended settings' --- state and how many wait for review. Sent at start, after a pass or a review change, and --- whenever the answer changed (checked on each refresh: start, resume, menu). force: send even --- when unchanged. -function Rec.reportFields(ui) - local p = serverPlugin(liveUI() or ui) - local signed = nil - if p then - local okl, v = pcall(p.isLoggedIn, p) - if okl then signed = v and "1" or "0" end - end - return { - signed_in = signed or "", - recommended = Recommended.reportState(S.recommended), - conflicts = tostring(Recommended.counts(S.recommended).conflict), - } -end - -function Rec.report(why, force, ui) - if not Companion.installed() then return end - pcall(Rec.writeReview, ui) - local f = Rec.reportFields(ui) - local key = f.signed_in .. "|" .. f.recommended .. "|" .. f.conflicts - if not force and Rec.last_report == key then return end - Rec.last_report = key - f.reason = why - Companion.send(Companion.ACTION.REPORT, f) -end - --- The review list for the companion (docs/design/companion-settings.md §5.8): --- koreader/settings/orbit-recommended.json, { v, at, items = [{ id, label, state, yours, orbit, was }] }. -function Rec.writeReview(ui) - local okd, DataStorage = pcall(require, "datastorage") - if not okd then return false end - local ctx = Rec.context(liveUI() or ui) - local status = type(S.recommended) == "table" and S.recommended.items or {} - local items = {} - for _i, it in ipairs(Recommended.ITEMS) do - local st = status[it.id] - if st then - local okc, obs = pcall(Rec.observe, it, ctx) - local entry = (S.recommended_backup or {})[it.id] - table.insert(items, { id = it.id, label = it.label, state = st, - yours = okc and obs and obs.available and Recommended.valueLabel(it, obs.current) or "", - orbit = Recommended.valueLabel(it, it.ours), - was = entry and Recommended.valueLabel(it, entry.prior) or "", - reason = okc and obs and obs.reason or "" }) - end - end - local body = SleepPool.json({ v = 1, at = os.time() * 1000, items = items }) - if Rec.review_body == body:gsub('"at":%d+,', "") then return true end - local path = DataStorage:getSettingsDir() .. "/orbit-recommended.json" - local f = io.open(path .. ".orbit-new", "wb") - if not f then return false end - f:write(body) - f:close() - if not os.rename(path .. ".orbit-new", path) then os.remove(path .. ".orbit-new"); return false end - Rec.review_body = body:gsub('"at":%d+,', "") - return true -end - --- The companion's choices on its review page (the shared key recommended_choice, "id=ours;…"): --- applied here, because only KOReader can write KOReader's and BookOrbit's settings; then cleared. -function Rec.applyChoices(why) - local list = SettingsSync.choices(S.recommended_choice) - if #list == 0 then return end - local ctx = Rec.context(liveUI()) - local status = type(S.recommended) == "table" and S.recommended.items or {} - local function each(id, fn) - for _i, it in ipairs(Recommended.ITEMS) do - if id == "all" or it.id == id then fn(it) end - end - end - for _i, c in ipairs(list) do - each(c.id, function(it) - local st = status[it.id] - if c.what == "ours" and (st == "conflict" or st == "kept") then - local okd, err = Rec.useOrbits(it, ctx) - log("recommended: " .. it.id .. " -> Orbit's (from the companion)", okd and "" or tostring(err)) - elseif c.what == "mine" and st == "conflict" then - if it.required_by == "wifi" and S.wifi_via_companion and Companion.has("wifi") then Shared.set("wifi_via_companion", false) end - Rec.keepMine(it) - log("recommended: " .. it.id .. " -> kept yours (from the companion)") - elseif c.what == "undo" and st == "applied" and not (it.required_by == "wifi" and S.wifi_via_companion and Companion.has("wifi")) then - Rec.undo(it, ctx) - log("recommended: " .. it.id .. " -> undone (from the companion)") - end - end) - end - Shared.set("recommended_choice", "") - Rec.report("companion review " .. tostring(why), true) -end - --- KOReader's "Action when Wi-Fi is off" → Turn on, at load (before any UI): with the companion --- switching Wi-Fi, KOReader asks for Wi-Fi without a prompt. Through the engine: applied only --- at KOReader's default, with a backup; a value the user chose is listed for review instead. -function silentWifiOn() - local okp, err = pcall(Rec.pass, "load", nil, { ["ko.wifi_on"] = true }) - if not okp then log("recommended: load pass failed:", tostring(err)) end -end - ---------------------------------------------------------------------------------------------- diff --git a/android/koreader/orbit.koplugin/logic/budgets.lua b/android/koreader/orbit.koplugin/logic/budgets.lua index e1ca6b85..af71f088 100644 --- a/android/koreader/orbit.koplugin/logic/budgets.lua +++ b/android/koreader/orbit.koplugin/logic/budgets.lua @@ -130,3 +130,11 @@ Budgets.screens["settings-sleep-choices"].displayRows = 10 Budgets.screens["catalog-refresh"] = budget(1,16384,50) Budgets.screens["catalog-refresh"].roundTrips = 0 + +-- One finish summary plus two selected cards; recommendation review has eight settings. +Budgets.screens["end-of-book"] = budget(3,16384,50) +Budgets.widgets["end-of-book"] = budget(3,16384,50) +Budgets.screens["settings-recommendations"] = budget(8,16384,50) +Budgets.widgets["recommendations"] = budget(8,16384,50) +Budgets.screens["copies-state"] = budget(1,16384,30) +Budgets.screens["copies-state"].roundTrips = 0 diff --git a/android/koreader/orbit.koplugin/main.lua b/android/koreader/orbit.koplugin/main.lua index 93530424..9604b3c6 100644 --- a/android/koreader/orbit.koplugin/main.lua +++ b/android/koreader/orbit.koplugin/main.lua @@ -35,9 +35,9 @@ local KO = { "ko/server/bookorbit/quiesce.lua", "ko/server/bookorbit.lua", "ko/net.lua", "ko/wifi.lua", "ko/updater.lua", "ko/background.lua", "ko/runtime.lua", "ko/clicks_channel.lua", "ko/keys.lua", "ko/module.lua", "ko/start.lua", "ko/home.lua", "ko/sleep.lua", "ko/reading_sync.lua", - "ko/test_sync_path.lua", "ko/companion_ui.lua", "ko/server/bookorbit/recommended.lua", "ko/menu.lua", - "ko/wifi_backend.lua", "ko/server/bookorbit/grouping.lua", "ko/endsheet.lua", "ko/server/bookorbit/endofbook.lua", - "ko/server/bookorbit/local_view.lua", "ko/db.lua", "ko/store.lua", "ko/badge.lua", "ko/server/bookorbit/copies.lua", "ko/sleepscreen.lua", + "ko/test_sync_path.lua", "ko/companion_ui.lua", "ko/recommendations.lua", "ko/menu.lua", + "ko/wifi_backend.lua", "ko/endsheet.lua", "ko/finish.lua", + "ko/server/bookorbit/local_view.lua", "ko/db.lua", "ko/store.lua", "ko/badge.lua", "ko/sleepscreen.lua", "ko/sqlite_stress.lua", "ko/library.lua", "ko/position_sync.lua", "ko/covers.lua", "ko/account.lua", "ko/reading_style.lua", "ko/custom_reading.lua", "ko/reader_panel.lua", "ko/filter_sheet.lua", "ko/reading_stats.lua", "ko/home_widgets.lua", "ko/storage.lua", "ko/clock.lua", "ko/local_widgets.lua", "ko/battery.lua", "ko/home_host.lua", "ko/series.lua", "ko/home_editor.lua", "ko/booklist_config.lua", "ko/settings_view.lua", "ko/status_layout.lua", "ko/notices.lua", "ko/main_loop.lua", } diff --git a/android/koreader/test/catalog_actions_flows.lua b/android/koreader/test/catalog_actions_flows.lua new file mode 100644 index 00000000..5fb66978 --- /dev/null +++ b/android/koreader/test/catalog_actions_flows.lua @@ -0,0 +1,197 @@ +-- SPDX-License-Identifier: AGPL-3.0-or-later +return function(t) +local E,W,test,eq,ok=t.E,t.W,t.test,t.eq,t.ok +local function isolated(fn) + local action,native,position,reading=E.Library.catalogAction,E.Library.nativeReader,E.Library.finishCurrent,E.reading + E.Library.finishCurrent=function(done) done(true) end + local oldsheet=E.FinishUI.sheet + E.FinishUI.sheet=nil + local success,why=pcall(fn) + E.FinishUI.closeSheet();E.FinishUI.sheet=oldsheet + E.Library.catalogAction,E.Library.nativeReader,E.Library.finishCurrent,E.reading=action,native,position,reading + if not success then error(why) end +end +local function fixture() + local ui,m=t.newUI(true) + ui.doc_settings={readSetting=function(self,k) return self[k] end,saveSetting=function(self,k,v) self[k]=v end} + local b={digest=string.rep("a",32),file="/books/synthetic.epub",key=true,summary={},doc_settings=ui.doc_settings} + E.Library.nativeReader=function() return b end + return ui,m,b +end +test("catalog actions: mark, rate, undo and leave dispatch neutral commands",function() isolated(function() + local ui,m,b=fixture();local calls={} + E.Library.catalogAction=function(op,args,done) calls[#calls+1]={op,args};if done then done({ok=true}) end end + b.summary.status="complete";E.FinishUI.onMarked(ui) + eq(calls[1][1],"finish.mark");eq(calls[1][2].complete,true);eq(calls[1][2].path,b.file) + ok(calls[1][2].server==nil and calls[1][2].userkey==nil) + E.FinishUI.actions.star(ui,b,4);eq(calls[2][1],"finish.rate");eq(calls[2][2].rating,4) + E.FinishUI.actions.star(ui,b,4);eq(calls[3][2].rating,nil) + E.FinishUI.onLeave(ui);eq(calls[4][1],"finish.leave") + b.summary.status="reading";E.FinishUI.onMarked(ui);eq(calls[5][2].complete,false) +end) end) +test("catalog actions: automatic refresh requires the neutral capability",function() + local snapshot,command=E.LibraryAdapter.account_snapshot,E.LibraryAdapter.command + local success,why=pcall(function() + E.LibraryAdapter.account_snapshot={catalog={canRefresh=false}} + E.LibraryAdapter.command=function() error("refresh without capability") end + eq(E.Library.refreshCatalog("resume",false),false) + E.LibraryAdapter.account_snapshot={catalog={}} + eq(E.Library.refreshCatalog("incremental",false),false) + end) + E.LibraryAdapter.account_snapshot,E.LibraryAdapter.command=snapshot,command + if not success then error(why) end +end) +test("catalog actions: unmarked reader leave needs no companion command",function() isolated(function() + local ui,m,b=fixture();E.FinishUI.jobs[b.digest]=nil + E.Library.catalogAction=function() error("unnecessary leave command") end + E.FinishUI.onLeave(ui) +end) end) +test("catalog actions: finish snapshot paint is bounded and contains no catalog algorithms",function() isolated(function() + local ui,m,b=fixture();local adapter=E.LibraryAdapter;local requests={} + E.LibraryAdapter={read=function(raw) + local args=E.Cache.decode(raw);eq(args.op,"reader.finish");eq(args.limit,3) + return {title="Synthetic",status="Saved",row_count=3,next={book_id="opaque-next"},suggestion={book_id="opaque-suggestion"}},300 + end,request=function(batch) requests[#requests+1]=batch;return true end} + local success,why=pcall(function() + local model=E.FinishUI.model(b);eq(model.title,"Synthetic");eq(#requests,1);eq(#requests[1],1) + end) + E.LibraryAdapter=adapter;if not success then error(why) end +end) end) +test("catalog actions: queued copies dispatch once outside reading with open path protection",function() isolated(function() + local ui,m,b=fixture();local calls={};local enabled=E.S.keep_copies_current + E.S.keep_copies_current=true;E.Library.copies_at=nil;E.Library.copies_pending=nil + E.Library.catalogAction=function(op,args,done) calls[#calls+1]={op,args};done({ok=true});return true end + E.reading=function() return true end;E.Library.copiesTick("full refresh");eq(#calls,0) + E.reading=function() return false end;E.Library.copiesTick("full refresh");eq(#calls,1) + eq(calls[1][1],"copies.check");eq(calls[1][2].open_path,ui.document.file) + E.Library.copiesTick("background");eq(#calls,1) + E.S.keep_copies_current=false;E.Library.copiesTick("full refresh");eq(#calls,1) + E.S.keep_copies_current=enabled +end) end) +test("catalog actions: page turns release stale-push hold without any library read",function() isolated(function() + local ui,m,b=fixture() + E.FinishUI.jobs[b.digest]={final_pos={percentage=1}} + E.FinishUI.session[b.digest]={forward=0} + E.FinishUI.page_digests[ui]={file=ui.document.file,digest=b.digest} + E.Library.catalogAction=function() error("page turn dispatched") end + ok(E.FinishUI.hold(b.digest,.5,"complete")) + for page=1,11 do E.FinishUI.onPage(ui,page) end + ok(not E.FinishUI.hold(b.digest,.5,"complete")) + E.FinishUI.session[b.digest].released=true + ok(not E.FinishUI.hold(b.digest,.1,"complete")) +end) end) +test("catalog actions: failed or departed download never reopens a book",function() isolated(function() + local ui,m,b=fixture();local pending;local opened=0;local open=E.Library.open + E.Library.open=function() opened=opened+1 end + E.Library.catalogAction=function(op,args,done) pending=done;return true end + local sheet={ui=ui,book=b,update=function() end};E.FinishUI.sheet=sheet + E.FinishUI.actions.book(ui,b,"opaque","Synthetic") + E.FinishUI.sheet=nil;pending({local_path="/books/next.epub"});eq(opened,0) + E.Library.open=open +end) end) +test("catalog actions: recommendation observation unwraps the saved native value and checks compatibility",function() + local ui,m=t.newUI(false);local p=ui.bookorbit + local saved,mode=E.S.osm_saved_plugin,E.S.sync_mode + p.default_settings={sync_forward=1} + E.S.osm_saved_plugin={sync_forward=3};E.S.sync_mode="balanced" + p.settings.sync_forward,p.settings.sync_backward=3,3 + local success,why=pcall(function() + local obs=E.Library.observeSetting({key="sync_forward"});eq(obs.available,true);eq(obs.current,3) + E.S.sync_mode="custom";E.S.osm_saved_plugin.sync_forward=2 + eq(E.Library.observeSetting({key="sync_forward"}).current,2) + ok(E.Library.writeSetting({key="sync_forward"},1));eq(E.S.osm_saved_plugin.sync_forward,1);eq(p.settings.sync_forward,3) + p.default_settings=nil;eq(E.Library.observeSetting({key="sync_forward"}).available,false) + end) + E.S.osm_saved_plugin,E.S.sync_mode=saved,mode + if not success then error(why) end +end) +test("catalog actions: finish follows the owned writer even with pending closed-sidecar work",function() + local run,action=E.ReadingSync.run,E.Library.catalogAction;local order={} + E.ReadingSync.run=function(moment,done) eq(moment,"manual");order[#order+1]="owned-writer";done(false,nil) end + E.Library.catalogAction=function(op,args,done) order[#order+1]=op;done({ok=true}) end + local success,why=pcall(function() + local done + E.LibraryAdapter.finishCurrent(function(ok) done=ok end) + eq(done,true);eq(order[1],"owned-writer");eq(order[2],"finish.drain") + E.ReadingSync.run=function(_,cb) cb(false,"offline") end + E.LibraryAdapter.finishCurrent(function(ok) eq(ok,false) end);eq(#order,2) + end) + E.ReadingSync.run,E.Library.catalogAction=run,action + if not success then error(why) end +end) +test("catalog actions: native download actions dispatch to companion and never invoke native transport",function() + local sent;local download=E.Library.catalogDownload + local api={request=function() error("native request") end,requestBlocking=function() error("native blocking request") end, + runInSubprocess=function() error("native fork") end,query=function() end, + download=function() error("native download") end,downloadBlocking=function() error("native blocking download") end} + local cat={downloadFile=function() error("stock transfer") end} + E.Library.catalogDownload=function(reference,path,file,done) sent={reference,path,file};done({local_path=path});return true end + local success,why=pcall(function() + ok(E.Server.installCatalogApi(api,cat));eq(api:download(),nil);eq(api:downloadBlocking(),nil) + local reported + local instance=setmetatable({},{__index=cat}) + instance:downloadFile("/books/new.epub",{id=7},{id=70},{finished=function(ok,err,path) reported={ok,err,path} end}) + eq(sent[1],7);eq(sent[2],"/books/new.epub");eq(sent[3],70);eq(reported[1],true);eq(reported[3],"/books/new.epub") + end) + E.Library.catalogDownload=download;if not success then error(why) end +end) +test("catalog actions: leaving for Home schedules the existing writer after its paint",function() isolated(function() + local ui,m,b=fixture();local nextTick=t.UIManager.nextTick;local scheduled;local calls=0 + E.FinishUI.jobs[b.digest]={};E.FinishUI.sending=nil + E.Library.catalogAction=function() end + E.Library.finishCurrent=function(done) calls=calls+1;done(true) end + t.UIManager.nextTick=function(_,fn) scheduled=fn end + local success,why=pcall(function() + E.FinishUI.leaveForHome(ui);eq(calls,0);ok(scheduled);scheduled();eq(calls,1) + end) + t.UIManager.nextTick=nextTick;E.FinishUI.sending=nil + if not success then error(why) end +end) end) +test("catalog actions: finish leaves and drains the existing writer before a remote download",function() isolated(function() + local ui,m,b=fixture();local order={} + E.Library.catalogAction=function(op,args,done) order[#order+1]=op;if done then done({error="offline"}) end end + E.Library.finishCurrent=function(done) order[#order+1]="existing-writer";done(true) end + E.FinishUI.sheet={ui=ui,book=b,update=function() end} + E.FinishUI.actions.book(ui,b,"opaque","Synthetic") + eq(order[1],"finish.leave");eq(order[2],"existing-writer");eq(order[3],"finish.download") +end) end) +test("catalog actions: a saved next book opens offline without a network command",function() isolated(function() + local ui,m,b=fixture();local opened;local open=E.Library.open + E.Library.open=function(row) opened=row.local_path;return true end + E.Library.finishCurrent=function() error("local book requested sync") end + E.Library.catalogAction=function(op) eq(op,"finish.leave") end + E.FinishUI.actions.book(ui,b,"opaque","Synthetic","/books/local.epub") + eq(opened,"/books/local.epub");E.Library.open=open +end) end) +test("catalog actions: native grouping opens an owned scoped projection without reading the list",function() + local old=package.loaded.bookorbit_catalog;local open=E.Library.openGrouped + local cat={listKind=function() return "books" end,listSortSheetModel=function() return {rows={}} end,listRun=function() error("unexpected native list action") end} + package.loaded.bookorbit_catalog=cat + local called + E.Library.openGrouped=function(title,source,query) called={title,source,query} end + local success,why=pcall(function() + ok(E.Server.installGroupViews()) + local instance=setmetatable({current_context={title="Synthetic list",params={smartScopeId=9,ids="2,4"}}},{__index=cat}) + local model=instance:listSortSheetModel();eq(#model.rows,2) + instance:listRun(model.rows[1].action) + eq(called[2].kind,"selection");eq(called[2].selection.list,"9");eq(called[2].selection.ids,"2,4");eq(called[3].group,"series") + end) + package.loaded.bookorbit_catalog=old;E.Library.openGrouped=open + if not success then error(why) end +end) +test("catalog actions: end sheet uses only the library action dispatcher",function() isolated(function() + local ui,m,b=fixture();local endAction=E.Library.endAction;local calls={} + E.Library.endAction=function(name) calls[#calls+1]=name end + local sheet=E.EndSheet:new{ui=ui,book=b,model={title="Synthetic",status="Saved",can_mark=true}} + for _,row in ipairs(sheet:rows()) do if row.kind=="status" then row.action() end end + eq(calls[1],"mark");sheet:onClose();eq(calls[2],"back") + E.Library.endAction=endAction +end) end) +test("catalog actions: every added screen and widget has strict deterministic budgets",function() + for _,id in ipairs({"end-of-book","settings-recommendations","copies-state"}) do + local b=E.Budgets.get("screens",id);eq(b.network,0);eq(b.spawns,0);ok(b.roundTrips<=1);ok(b.snapshotBytes<=16384) + ok(not E.Budgets.check(b,{rows=b.rows+1,bytes=0,spawns=0,roundTrips=0,network=0,snapshotBytes=0})) + end + for _,id in ipairs({"end-of-book","recommendations"}) do E.Budgets.get("widgets",id) end +end) +end diff --git a/android/koreader/test/test_flows.lua b/android/koreader/test/test_flows.lua index 00b3190d..3e781fb8 100644 --- a/android/koreader/test/test_flows.lua +++ b/android/koreader/test/test_flows.lua @@ -916,9 +916,6 @@ local function fresh(mode, idle) end local function done() W.simulate_companion = false; W.radio, W.wifi, W.owner = nil, true, nil end -test("wifi: KOReader asks for Wi-Fi silently (turn_on), in every mode", function() - ok(store.wifi_enable_action == "turn_on", "wifi_enable_action") -end) test("wifi: wake with Wi-Fi off brings it up, then restores it off after the pull", function() fresh("always_on") @@ -1331,6 +1328,12 @@ test("contract: every command, call, page, launch command, status key, file and for _, k in ipairs(C.status) do ok(src:find("%." .. k .. "%f[^%w_]"), "status key " .. k .. " is read") end local mailbox_file = assert(io.open(here .. "/../../companion/app/src/main/java/net/fledgewing/orbitcompanion/EventMailbox.kt", "rb")) local mailbox_source = mailbox_file:read("*a"); mailbox_file:close() + local workflows=assert(io.open(here .. "/../../companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt","rb")) + mailbox_source=mailbox_source..workflows:read("*a");workflows:close() + local cache=assert(io.open(here .. "/../../companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CacheWorker.kt","rb")) + mailbox_source=mailbox_source..cache:read("*a");cache:close() + local actions=assert(io.open(here .. "/../../companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflow.kt","rb")) + mailbox_source=mailbox_source..actions:read("*a");actions:close() for _, f in ipairs(C.files) do local name = f.path:gsub("/$", ""):match("[^/]+$") local source = f.reader == "companion" and (src .. mailbox_source) or src @@ -1372,7 +1375,7 @@ local function recWorld(in_book) ui.gestures.data.gesture_reader = { two_finger_swipe_north = { increase_frontlight = 0 } } store.orbit_android.recommended, store.orbit_android.recommended_backup = nil, nil store.wifi_enable_action = nil - RE.Rec.session_applied, RE.Rec.line_pending = 0, false + RE.Recommendations.session_applied, RE.Recommendations.line_pending = 0, false RE.installed_cache.at = -1000 W.shown = {} return ui, m, p @@ -1393,150 +1396,12 @@ local function pressDialog(label) error("no dialog button " .. label) end -test("recommended: a fresh KOReader at first start: every item applied with a backup, one line off-book", function() - local ui, m, p = recWorld(false) - m:recommendedPass("start") - ok(p.settings.auto_sync == true, "auto-sync through the plugin's toggle") - ok(p.settings.sync_forward == 2, "Silent") - ok(p.settings.catalog_auto_open == "home", "Make library home") - ok(store.wifi_enable_action == "turn_on", "KOReader turns Wi-Fi on") - local g = ui.gestures.data.gesture_reader - ok(g.hold_top_right_corner.orbit_sync_and_sleep and g.hold_top_left_corner.bookorbit_sync_now - and g.one_finger_swipe_bottom_edge_right.bookorbit_this_book and g.two_finger_swipe_north.orbit_open_apps, "gestures") - ok(ui.gestures.flushed, "gestures flushed") - local b = store.orbit_android.recommended_backup - ok(b["g.apps"].had and b["g.apps"].prior.increase_frontlight == 0, "backup of the frontlight gesture") - ok(b["ko.wifi_on"] and not b["ko.wifi_on"].had, "backup: Wi-Fi action was unset") - ok(shownText("Applied 8 recommended settings · Review"), "the line") - ok(m:recommendedMenuText() == "Recommended settings: Applied 8 recommended settings · Review", m:recommendedMenuText()) - -- A second start: nothing new, silent, and a value changed by hand since stays. - p.settings.sync_forward = 3 - W.shown = {} - m:recommendedPass("start") - ok(p.settings.sync_forward == 3, "never changed back") - ok(#W.shown == 0, "silent") - -- The review page clears the line. - local menu = m:showRecommended("test") - ok(menuRow(menu, "Applied"), "Applied section") - ok(m:recommendedMenuText() == "Recommended settings", "line cleared once seen") - run(1) -end) -test("recommended: a customised KOReader keeps every changed value; review offers Use BookSync's / Keep mine", function() - local ui, m, p = recWorld(false) - p.settings.sync_forward = 3 - ui.gestures.data.gesture_reader.hold_top_left_corner = { toc = true } - m:recommendedPass("start") - ok(p.settings.sync_forward == 3, "the user's value stays") - ok(ui.gestures.data.gesture_reader.hold_top_left_corner.toc, "the user's gesture stays") - ok(p.settings.auto_sync == true, "at-default items still applied") - ok(shownText("Applied 6 · 2 to review"), "the line counts both") - local menu = m:showRecommended("test") - local row = menuRow(menu, "BookOrbit › When BookOrbit is further ahead") - ok(row and row.mandatory == "yours: Don't sync · BookSync's: Silent", row and row.mandatory) - row.callback() - pressDialog("Use BookSync's") - ok(p.settings.sync_forward == 2, "Use BookSync's applies") - ok(store.orbit_android.recommended.items["bo.sync_forward"] == "applied", "recorded") - run(1) - menu = m.rec_menu - menuRow(menu, "Gesture in books: hold top-left corner").callback() - pressDialog("Keep mine") - ok(store.orbit_android.recommended.items["g.sync_all"] == "kept", "kept") - ok(ui.gestures.data.gesture_reader.hold_top_left_corner.toc, "kept unchanged") - run(1) - -- Kept stays kept on later passes. - m:recommendedPass("start") - ok(ui.gestures.data.gesture_reader.hold_top_left_corner.toc, "a pass never revisits kept") - run(1) -end) -test("recommended: Undo restores the backup; a value changed since is left as is; Undo all", function() - local ui, m, p = recWorld(false) - m:recommendedPass("start") - local menu = m:showRecommended("test") - menuRow(menu, "Gesture in books: two-finger swipe up").callback() - pressDialog("Undo") - ok(ui.gestures.data.gesture_reader.two_finger_swipe_north.increase_frontlight == 0, "frontlight back") - ok(store.orbit_android.recommended.items["g.apps"] == "kept", "then shown under Kept yours") - run(1) - -- Changed by hand after Orbit set it: Undo leaves it. - p.settings.catalog_auto_open = "filemanager" - menuRow(m.rec_menu, "BookOrbit › Make BookOrbit home").callback() - pressDialog("Undo") - ok(p.settings.catalog_auto_open == "filemanager", "left as is") - ok(shownText("Changed since; left as is."), "says so") - run(1) - menuRow(m.rec_menu, "Undo all").callback() - ok(p.settings.auto_sync == false and p.settings.sync_forward == 1, "plugin values back") - ok(ui.gestures.data.gesture_reader.hold_top_right_corner == nil, "gesture back to nothing") - ok(store.wifi_enable_action == "turn_on", "KOReader's Wi-Fi action stays while Wi-Fi switching needs it") - ok(shownText("Wi-Fi switching needs it"), "says why") - run(1) -end) -test("recommended: in a book the settings are written, the line waits for the file browser", function() - local ui, m, p = recWorld(true) - m:recommendedPass("start") - ok(p.settings.auto_sync == true, "written in a book") - ok(not shownText("Applied"), "no line in a book") - local ui2, m2 = newUI(false) - m2:maybeSetupPrompt("home") - ok(shownText("Applied 8 recommended settings"), "shown off the book") - run(1) -end) -test("recommended: missing pieces wait: no BookOrbit plugin, Gestures off; applied on the start they appear", function() - local ui, m, p = recWorld(false) - ui.bookorbit = nil - local gestures = ui.gestures - ui.gestures = nil - m:recommendedPass("start") - local items = store.orbit_android.recommended.items - ok(items["bo.auto_sync"] == "unavailable" and items["g.apps"] == "unavailable", "unavailable, not failed") - ok(items["ko.wifi_on"] == "applied", "the rest applied") - local menu = m:showRecommended("test") - ok(menuRow(menu, "Gesture in books: hold top-right corner").mandatory == "Turn on KOReader's Gestures plugin", "the reason") - run(1) - ui.bookorbit, ui.gestures = p, gestures - m:recommendedPass("start") - ok(items["bo.auto_sync"] == "applied" and items["g.apps"] == "applied", "applied once they load") - run(1) -end) -test("recommended: at load, KOReader's Wi-Fi action is set only with the companion, and backed up", function() - recWorld(false) - W.companion = false - RE.installed_cache.at = -1000 - RE.silentWifiOn() - ok(store.wifi_enable_action == nil, "no companion: left alone") - W.companion = true - RE.installed_cache.at = -1000 - RE.silentWifiOn() - ok(store.wifi_enable_action == "turn_on", "with the companion") - ok(store.orbit_android.recommended_backup["ko.wifi_on"], "with a backup") - -- A value the user chose is never overwritten: listed instead. - recWorld(false) - store.wifi_enable_action = "ignore" - RE.silentWifiOn() - ok(store.wifi_enable_action == "ignore", "kept") - ok(store.orbit_android.recommended.items["ko.wifi_on"] == "conflict", "to review") - store.wifi_enable_action = "turn_on" -end) - -test("recommended: Keep mine on KOReader's Wi-Fi action offers to turn Wi-Fi switching off instead", function() - local ui, m = recWorld(false) - store.wifi_enable_action = "ignore" - m:recommendedPass("start") - local menu = m:showRecommended("test") - menuRow(menu, "KOReader › Action when Wi-Fi is off").callback() - pressDialog("Turn Wi-Fi switching off") - ok(store.orbit_android.wifi_via_companion == false, "switching off") - ok(store.wifi_enable_action == "ignore", "theirs kept") - store.orbit_android.wifi_via_companion = true - store.wifi_enable_action = "turn_on" - run(1) -end) + ---------------------------------------------------------------- companion caps (addon-mode §6) @@ -1595,38 +1460,7 @@ test("caps: Add-on degrades: Sync and sleep asks for the power button, Other app run(5) end) -test("caps: without Wi-Fi switching, KOReader's Wi-Fi action is left alone at load", function() - capsReset() - capsFile("addon", ADDON) - recWorld(false) - capsFile("addon", ADDON) - RE.Companion.cap_set = nil - RE.silentWifiOn() - ok(store.wifi_enable_action == nil, "left alone") - ok(store.orbit_android.recommended.items["ko.wifi_on"] == "unavailable", "waits for the capability") - capsReset() - store.wifi_enable_action = "turn_on" -end) -test("caps: Full → Add-on undoes KOReader's Wi-Fi action and the apps gesture only; back to Full re-applies them", function() - capsReset() - local ui, m, p = recWorld(false) - capsFile("full", FULL) - RE.Shared.refresh("test") - m:recommendedPass("start") - ok(store.wifi_enable_action == "turn_on" and ui.gestures.data.gesture_reader.two_finger_swipe_north.orbit_open_apps, "applied in Full") - capsFile("addon", ADDON) - RE.Shared.refresh("resume") - ok(store.wifi_enable_action == nil, "Wi-Fi action undone") - ok(ui.gestures.data.gesture_reader.two_finger_swipe_north.increase_frontlight == 0, "apps gesture undone") - ok(p.settings.auto_sync == true and ui.gestures.data.gesture_reader.hold_top_right_corner.orbit_sync_and_sleep, "reading settings stay") - capsFile("full", FULL) - RE.Shared.refresh("resume") - ok(store.wifi_enable_action == "turn_on" and ui.gestures.data.gesture_reader.two_finger_swipe_north.orbit_open_apps, "picked up again") - capsReset() - store.wifi_enable_action = "turn_on" - run(5) -end) test("caps: plugin only, a newer plugin on disk: asks to reopen KOReader, never quits with nobody to relaunch it", function() capsReset() @@ -1644,30 +1478,6 @@ test("caps: plugin only, a newer plugin on disk: asks to reopen KOReader, never capsReset() end) -test("report: signed in yes/no and the recommended state go to the companion, never the login itself", function() - capsReset() - local ui, m, p = recWorld(false) - p.settings.sync_forward = 3 - W.broadcasts = {} - RE.Rec.last_report = nil - m:recommendedPass("start") - local r = lastBroadcast(".REPORT") - ok(r, "REPORT sent") - ok(r.extras.signed_in == "1" and r.extras.recommended == "partial" and r.extras.conflicts == "1", "fields") - for k, v in pairs(r.extras) do - ok(not tostring(v):find("example.test", 1, true), "no server in " .. k) - end - ok(r.extras.server_url == nil and r.extras.username == nil and r.extras.userkey == nil, "no login fields") - -- Unchanged: not sent again on a refresh; a sign-out is. - W.broadcasts = {} - RE.Shared.refresh("resume") - ok(not lastBroadcast(".REPORT"), "nothing new: no report") - p.signed_out = true - RE.Shared.refresh("resume") - ok(lastBroadcast(".REPORT") and lastBroadcast(".REPORT").extras.signed_in == "0", "sign-out reported") - p.signed_out = nil - run(2) -end) test("commands: signin opens BookOrbit's sign-in; recommended opens the review page", function() local ui, m, p = recWorld(false) @@ -2850,129 +2660,10 @@ local lists_server = { urls = {}, books = { local LCat, LApi = fakeCatalogClass(lists_server) local stock_listRun, stock_fetch = LCat.listRun, LCat.fetch -test("lists: a plugin without a hook -> the feature stays off, the plugin unchanged", function() - local header = LCat.listHeader - LCat.listHeader = nil - package.loaded["bookorbit_catalog"], package.loaded["bookorbit_api"] = LCat, LApi - newUI(false) - ok(LCat.listRun == stock_listRun and LCat.fetch == stock_fetch, "nothing wrapped") - ok(rawget(LCat, "__orbit_stock") == nil, "no marks") - LCat.listHeader = header -end) - -test("lists: By series on a collection reads its books once and opens the plugin's Series view", function() - newUI(false) -- installs now that every hook is there - ok(LCat.listRun ~= stock_listRun, "wrapped") - local cat = newCatalog(LCat, LApi, { kind = "books", title = "Kids shelf", params = { collectionId = 4, readStatus = "unread", sort = "author", page = 2 } }) - local m = cat:listSortSheetModel({}) - ok(m.rows[1].key == "orbit-series" and m.rows[2].key == "orbit-authors" and m.rows[3].key == "device", "rows at the top") - cat:listRun({ kind = "orbit-group", section = "series" }) - run(1) - ok(#lists_server.urls == 3, "three pages of two: " .. #lists_server.urls) - for _, u in ipairs(lists_server.urls) do - ok(u:find("collectionId=4", 1, true) and u:find("readStatus=unread", 1, true) and u:find("size=100", 1, true), "the list's filters: " .. u) - ok(not u:find("orbit", 1, true), "no marks sent") - end - ok(cat.labels[2] == "Reading 2 of 5 books…", "progress: " .. tostring(cat.labels[2])) - local ctx = cat.current_context - ok(ctx.kind == "section" and ctx.section == "series" and ctx.orbit_group, "the Series view, tagged") - ok(lists_server.sections == nil, "the sections endpoint never asked") - ok(ctx.total == 3 and #ctx.entries == 2, "a screen of 2 of 3 series") - ok(ctx.entries[1].title == "Nsibidi" and ctx.buckets[1].key == "N", "A-Z with buckets") - ok(cat:listHeader("series", ctx).title == "Series in Kids shelf", "header") - -- Paging (listGoPage -> reloadSection -> loadSection replace) stays in the list. - cat:loadSection("series", { replace = true, offset = 2 }) - ok(cat.current_context.orbit_group and cat.current_context.entries[1].title == "Skyward", "page 2 from the held books") - ok(#lists_server.urls == 3, "no new reads") - -- A row: the server's series page with the collection ANDed in. - cat:listRun({ kind = "open-series", entry = cat.current_context.entries[1] }) - local p = cat.loaded.params - ok(p.collectionId == 4 and p.series == "Skyward" and p.readStatus == "unread" and p.ids == nil, "collection + series") - ok(p.orbitGroup == ctx.orbit_group.token, "marked") - -- That page's header and its Whole series chip. - local page = { kind = "books", title = "Skyward", params = p, total = 1, books = { lists_server.books[3] } } - cat.current_context = page - ok(cat:listHeader("seriespage", page).sub == "Brandon Sanderson · 1 book in Kids shelf", "sub: " .. tostring(cat:listHeader("seriespage", page).sub)) - local tb = cat:listToolbar("seriespage", page) - ok(tb[1].key == "tb-sort" and tb[2].key == "orbit-whole-series", "Whole series chip") - cat:listRun(tb[2].action) - ok(cat.loaded.params.series == "Skyward" and cat.loaded.params.collectionId == nil and cat.loaded.params.orbitGroup == nil, "the whole series") - -- Back on the list, By series again: no new reads. - cat.current_context = { kind = "books", title = "Kids shelf", params = { collectionId = 4 }, orbit_snapshot = ctx.orbit_group.token } - cat:listRun({ kind = "orbit-group", section = "series" }) - ok(#lists_server.urls == 3 and cat.current_context.orbit_group, "instant the second time") -end) - -test("lists: By author on a list; an author by series; Not in a series; the chips", function() - lists_server.urls = {} - local cat = newCatalog(LCat, LApi, { kind = "books", title = "Unread fantasy", params = { smartScopeId = 3 } }) - cat:listRun({ kind = "orbit-group", section = "authors" }) - run(1) - local ctx = cat.current_context - ok(ctx.section == "authors" and ctx.total == 3, "3 authors") - ok(cat:listHeader("authors", ctx).title == "Authors in Unread fantasy", "header") - local bs = ctx.entries[1] - ok(bs.title == "Brandon Sanderson" and bs.count == 2, "Brandon first A-Z") - cat:listRun({ kind = "open-author", entry = bs }) - local by = cat.current_context - ok(by.section == "series" and by.orbit_group.author == "Brandon Sanderson", "the author's books by series") - ok(cat.pushed == true, "pushed: Back returns to the authors") - ok(by.total == 2 and by.entries[1].title == "Skyward" and by.entries[2].title == "Not in a series", "series, then Not in a series") - local h = cat:listHeader("series", by) - ok(h.title == "Brandon Sanderson" and h.sub == "2 books in Unread fantasy · by series", "header: " .. tostring(h.sub)) - local chips = cat:listToolbar("series", by) - ok(#chips == 3 and chips[1].on and chips[1].label == "By series" and chips[3].label == "All by author", "chips") - -- A list's series: by id (the server ignores other filters with smartScopeId). - cat:listRun({ kind = "open-series", entry = by.entries[1] }) - local p = cat.loaded.params - ok(p.ids == "3" and p.smartScopeId == nil and p.series == "Skyward" and p.author == "Brandon Sanderson", "ids + series + author") - cat:listRun({ kind = "open-series", entry = by.entries[2] }) - ok(cat.loaded.params.ids == "4" and cat.loaded.params.series == nil and cat.loaded.title == "Not in a series", "standalones, flat") - cat:listRun(chips[2].action) - ok(cat.loaded.params.ids == "3,4" and cat.loaded.push == false, "All books: flat, in place") - cat:listRun(chips[3].action) - ok(cat.loaded.params.author == "Brandon Sanderson" and cat.loaded.params.ids == nil and cat.loaded.params.orbitGroup == nil, "All by author: no list filter") - ok(#lists_server.urls == 3, "read once") -end) - -test("lists: a smart-scope series past 200 books comes from the books held here", function() - lists_server.urls = {} - local saved = lists_server.books - lists_server.books = {} - for i = 1, 201 do lists_server.books[i] = { id = i, title = "Vol " .. i, authors = { "A" }, seriesId = 1, seriesName = "Long", seriesIndex = tostring(i) } end - local cat = newCatalog(LCat, LApi, { kind = "books", title = "Big", params = { smartScopeId = 5 } }) - cat:listRun({ kind = "orbit-group", section = "series" }) - run(1) - cat:listRun({ kind = "open-series", entry = cat.current_context.entries[1] }) - local p = cat.loaded.params - ok(p.orbitLocal == "1" and p.ids == nil, "held") - local before = #lists_server.urls - local body = cat.client:catalogBooks({ orbitGroup = p.orbitGroup, orbitLocal = "1", orbitSeries = p.orbitSeries, seriesId = 1, sort = "series", size = 100, page = 3 }) - ok(#lists_server.urls == before, "answered here") - ok(body.total == 201 and #body.items == 1 and body.items[1].id == 201, "page 3 of the held books") - cat.client:catalogManifest({ orbitGroup = p.orbitGroup, orbitLocal = "1", orbitSeries = p.orbitSeries }) - ok(lists_server.manifest:find("ids=1,2,3", 1, true) and not lists_server.manifest:find("orbit", 1, true), "Download all goes by id") - lists_server.books = saved -end) - -test("lists: pass-through when nothing is marked", function() - lists_server.urls = {} - local cat = newCatalog(LCat, LApi, { kind = "books", title = "Search", params = { sort = "title", q = "sky" } }) - ok(#cat:listSortSheetModel({}).rows == 1, "a search: no rows") - cat:listRun({ kind = "back" }) - ok(cat.stock_run == "back", "other actions: the plugin's") - cat.current_context = { kind = "section", section = "series" } - cat:listRun({ kind = "open-series", entry = { title = "X" } }) - ok(cat.stock_run == "open-series", "the server-wide Series view: the plugin's") - cat:loadSection("series", { replace = true }) - ok(lists_server.sections == 1 and cat.current_context.orbit_group == nil, "the server answers") - ok(cat:listHeader("series", cat.current_context).title == "Series", "header unchanged") - ok(cat:listToolbar("series", cat.current_context)[1].key == "tb-sort", "toolbar unchanged") - ok(cat.client:query("/books", { sort = "title" }) == "/books?sort=title", "query unchanged") - cat.client:catalogBooks({ sort = "title", page = 1 }) - ok(#lists_server.urls == 1, "books from the server") - package.loaded["bookorbit_catalog"], package.loaded["bookorbit_api"] = nil, nil -end) + + + + ---------------------------------------------------------------- end of book (ROADMAP 1, 2) @@ -3023,155 +2714,12 @@ local series_detail = { id = 42, title = "Sea of Monsters", authors = { "Rick Ri relatedSections = {} } eob.details = { [42] = series_detail, [43] = { id = 43, title = "Titan's Curse", files = { { id = 9, format = "epub" } } } } -test("end of book: a plugin without a module -> KOReader's own end screen", function() - package.loaded["bookorbit_state_manager"] = nil - local ui = bookUI() - W.stock_end = 0 - ui.status:onEndOfBook() - ok(W.stock_end == 1 and E.EOB.sheet == nil, "stock end screen") - ok(ui.doc_settings.data.summary.status == "reading", "nothing marked") -end) -test("end of book: the last page marks it finished, opens the sheet; Undo takes it back", function() - eobModules() - E.EOB.remember(series_detail) - local ui = bookUI() - W.stock_end = 0 - ui.status:onEndOfBook() - ok(W.stock_end == 0, "the BookSync sheet instead of KOReader's") - ok(ui.doc_settings.data.summary.status == "complete", "marked finished") - local job = E.EOB.queue()["d1"] - ok(job and job.book_id == 42 and job.ready == false, "a job, not sent while the book is open") - ok(sheetRow("status", "Marked as finished") and sheetRow("author", "Rick Riordan"), "status and author") - ok(sheetRow("label", "Next in series · Book 3"), "next card: " .. tostring((sheetRow("label") or {}).text)) - ok(sheetRow("card", "Titan's Curse"), "download and open the next book") - sheetRow("status").action() - ok(ui.doc_settings.data.summary.status == "reading" and E.EOB.queue()["d1"] == nil, "Undo: reading, no job") - ok(E.EOB.sheet == nil, "sheet closed") - -- Auto-mark off: the sheet offers the mark instead. - E.S.eob_auto = false - ui.status:onEndOfBook() - ok(ui.doc_settings.data.summary.status == "reading" and sheetRow("status", "Not marked"), "not marked") - sheetRow("status").action() - ok(E.EOB.queue()["d1"] and sheetRow("status", "Marked as finished"), "marked from the sheet") - E.S.eob_auto = true - sheetRow("status").action() -end) - -test("end of book: stars, leave, sync -> guard read, read-status, rating, written back", function() - eobModules() - local ui, m = bookUI() - ui.status:onEndOfBook() - sheetRow("star", nil) -- first star row - local stars = {} - for _, r in ipairs(E.EOB.sheet:rows()) do if r.kind == "star" then table.insert(stars, r) end end - stars[4].action() - ok(E.EOB.queue()["d1"].rating == 4 and ui.doc_settings.data.summary.rating == 4, "4 stars kept") - E.EOB.actions.back() - eob.calls = {} - E.Sync.waitOutbox(ui.bookorbit, 10, function() end) - run(5) - ok(#eob.calls == 0 or not table.concat(eob.calls, ","):find("status:", 1, true), "nothing sent with the book open") - m:onCloseWidget() - ReaderUI.instance = nil -- KOReader destroys the reader after CloseWidget - ok(E.EOB.queue()["d1"].ready, "ready once the book is left") - E.Sync.waitOutbox(ui.bookorbit, 10, function() W.waited = true end) - run(5) - local c = table.concat(eob.calls, ",") - ok(c:find("book:42,status:42:read,rating:42:4", 1, true), "in order: " .. c) - ok(E.EOB.queue()["d1"] == nil and W.waited, "sent, then the caller goes on") - ok(eob.state and eob.state.server and eob.state.server.status == "complete" and eob.state.server.rating == 4, "written back") -end) -test("end of book: a server error retries later; 404 drops", function() - eobModules() - local ui, m = bookUI() - ui.status:markBook(true) - m:onCloseWidget() - ReaderUI.instance = nil -- the book was closed; the next sync runs outside reading - eob.fail, eob.calls = 503, {} - E.EOB.drain(ui.bookorbit, false) - local job = E.EOB.queue()["d1"] - ok(job and job.attempts == 1 and job.next_try_at and job.next_try_at > os.time(), "kept with a backoff") - eob.fail = 404 - E.EOB.drain(ui.bookorbit, true) - ok(E.EOB.queue()["d1"] == nil, "dropped on 404") - eob.fail = nil -end) - -test("end of book: Download and open, offline -> Couldn't connect, Get it at the next sync", function() - eobModules() - local ui = bookUI() - ui.status:onEndOfBook() - W.wifi, W.vpn = false, false - W.companion = false - sheetRow("card", "Titan's Curse").action() - run(60) - ok(sheetRow("notice", "Couldn't connect"), "the card says so") - sheetRow("button", "Get it at the next sync").action() - ok(E.EOB.downloads()["43"], "remembered for the next sync") - W.wifi, W.vpn, W.companion = true, true, true - E.EOB.wants_download = {} - E.EOB.save() -end) -test("end of book: Download and open sends the finish first, downloads through the plugin, opens it", function() - eobModules() - local DCat = {} - DCat.__index = DCat - function DCat:downloadDefaultFile(detail, file) self:checkDownloadFile("/books/titan.epub", detail, file) end - function DCat:downloadFile(path, detail, file, rep) - ok(self.client and self.bookMode == false, "headless, the plugin's client") - table.insert(eob.calls, "download:" .. detail.id) - rep.progress(512, 1024) - rep.finished(true, nil, path) - end - function DCat:loadBooks() end - package.loaded["bookorbit_catalog"] = DCat - local ui = bookUI() - ui.status:onEndOfBook() - eob.calls, W.opened = {}, nil - sheetRow("card", "Titan's Curse").action() - run(60) - local c = table.concat(eob.calls, ",") - ok(c:find("status:42:read", 1, true) and c:find("download:43", 1, true) - and c:find("status:42:read", 1, true) < c:find("download:43", 1, true), "finish, then download: " .. c) - ok(W.opened == "/books/titan.epub", "opened: " .. tostring(W.opened)) - ok(E.EOB.sheet == nil, "sheet closed") - package.loaded["bookorbit_catalog"] = nil -end) -test("end of book: Download and open uses the reader's delivery variant and a supported file (hash_mismatch on M8C)", function() - eobModules() - local JSON = dofile(here .. "/json_mini.lua") - -- @fixture bookorbit/catalog-book.delivery-variants.json - local fx = JSON.fixture(here, "bookorbit/catalog-book.delivery-variants.json") - local DCat = {} - DCat.__index = DCat - function DCat:fetchDeliveryBook(id) table.insert(eob.calls, "delivery:" .. id); return fx.with_variant end - function DCat:supportedFiles(detail) - local out = {} - for _, f in ipairs(detail.files) do if f.format == "epub" then table.insert(out, f) end end - return out - end - function DCat:downloadDefaultFile(detail, file) self:checkDownloadFile("/books/titan.epub", detail, file) end - function DCat:downloadFile(path, detail, file, rep) - eob.file = file - rep.finished(true, nil, path) - end - function DCat:loadBooks() end - package.loaded["bookorbit_catalog"] = DCat - local ui = bookUI() - ui.status:onEndOfBook() - eob.calls, eob.file = {}, nil - sheetRow("card", "Titan's Curse").action() - run(60) - local c = table.concat(eob.calls, ",") - ok(c:find("delivery:43", 1, true) and not c:find("book:43", 1, true), "the plugin's delivery detail: " .. c) - ok(eob.file and eob.file.id == 902 and eob.file.selection == "sel-902", "the EPUB with its selection") - ok(eob.file.fileHash == "hash-audioless-artifact", "checked against the artifact's hash") - package.loaded["bookorbit_catalog"] = nil -end) + + -- Keep book copies current: BookOrbit rewrote the library files (tags), every copy is -- position-incompatible; each is downloaded again in place, one at a time, never while reading. @@ -3321,26 +2869,6 @@ test("background notices: start and wake pulls are silent, including delayed cal restore() end) -test("background notices: copy replacements and their completion callbacks are silent", function() - copiesSetup(copyBooks(), { ["/books/a.epub"] = "old1", ["/books/b.epub"] = "old2", ["/books/c.epub"] = "cur3" }) - local burst, restore = noticeFixture() - copiesUI(false) - local Cat = package.loaded["bookorbit_catalog"] - local download = Cat.downloadFile - function Cat:downloadFile(path, detail, file, rep) - burst("copy download") - UIManager:nextTick(function() burst("copy completion"); download(self, path, detail, file, rep) end) - end - W.shown, W.presented = {}, {} - E.Copies.tick("background") - run(10) - eq(#W.presented, 0, "background copies show zero notices") - eq(#E.Copies.state().queue, 0, "copy replacements still finish") - eq(#copies.repaired, 2, "both copies carried their identity") - ok(noticeLog("copy download: Loading book...") and noticeLog("copy completion: Trapper"), "copy notice texts logged") - restore() - copiesTeardown() -end) test("background notices: yielding scope is isolated, error safe, and timers still cancel", function() local burst, restore, Trapper = noticeFixture() @@ -3369,135 +2897,12 @@ test("background notices: yielding scope is isolated, error safe, and timers sti restore() end) -test("copies: changed copies are replaced in place, one at a time, and their hashes move on", function() - copiesSetup(copyBooks(), { ["/books/a.epub"] = "old1", ["/books/b.epub"] = "old2", ["/books/c.epub"] = "cur3" }) - copiesUI(false) - E.Copies.tick("test") - run(10) - local c = table.concat(copies.calls, ",") - ok(c == "delivery:1,download:/books/a.epub,delivery:2,download:/books/b.epub", "one at a time: " .. c) - ok(table.concat(copies.repaired, ",") == "/books/a.epub:old1>new1,/books/b.epub:old2>new2", "state re-keyed: " .. table.concat(copies.repaired, ",")) - ok(#E.Copies.state().queue == 0, "queue done") - copiesTeardown() -end) - -test("copies: never while reading; the queue waits on disk and goes once the book closes", function() - copiesSetup(copyBooks(), { ["/books/a.epub"] = "old1", ["/books/b.epub"] = "old2" }) - local _ui, m = copiesUI(true) - E.Copies.tick("test") - E.Copies.ask("test") - run(5) - ok(#copies.calls == 0, "nothing while reading") - eq(#E.Copies.state().queue,0,"durable companion event waits until reading ends") - m:onCloseWidget() - copiesUI(false) - run(10) - ok(#copies.calls == 4, "replaced after the close: " .. table.concat(copies.calls, ",")) - copiesTeardown() -end) -test("copies: offline or turned off, nothing is downloaded; a copy already current is left alone", function() - copiesSetup(copyBooks(), { ["/books/a.epub"] = "new1", ["/books/b.epub"] = "old2" }) - copiesUI(false) - store.orbit_android.keep_copies_current = false - E.Copies.tick("test") - run(5) - ok(#copies.calls == 0, "off") - store.orbit_android.keep_copies_current = true - W.wifi = false - E.Copies.tick("test") - run(5) - ok(#copies.calls == 0, "offline") - W.wifi = true - E.Copies.scanned_at = nil - E.Copies.tick("test") - run(10) - local c = table.concat(copies.calls, ",") - ok(not c:find("download:/books/a.epub", 1, true), "a already matches the library: " .. c) - ok(c:find("download:/books/b.epub", 1, true), "b replaced") - copiesTeardown() -end) - -test("copies: BookSync Companion finds the changed copies; the UI thread reads no saved detail and checks no file", function() - copiesSetup(copyBooks(), { ["/books/a.epub"] = "old1", ["/books/b.epub"] = "old2", ["/books/c.epub"] = "cur3" }) - copiesUI(false) - local reads, exists = 0, 0 - local get, lfs = E.OC.get, require("libs/libkoreader-lfs") - local attributes = lfs.attributes - E.OC.get = function(...) reads = reads + 1; return get(...) end - lfs.attributes = function(f, ...) if not W.in_companion and tostring(f):find("^/books/") then exists = exists + 1 end return attributes(f, ...) end - W.broadcasts = {} - E.Copies.tick("test") - local b = lastBroadcast(".COPIES") - ok(b and b.extras.reason == "test" and b.extras.userkey == nil, "asked the companion, no login") - local ask = E.Cache.decode(b.extras.ask or "") - ok(ask and #ask.books == 3, "the ask lists the books from memory") - run(10) - E.OC.get, lfs.attributes = get, attributes - ok(copies.fc.copies_asks == 1, "the companion looked") - ok(reads == 0 and exists == 0, "no detail read, no file checked on the UI thread: " .. reads .. " " .. exists) - ok(#copies.calls == 4, "the two changed copies replaced: " .. table.concat(copies.calls, ",")) - -- Without the companion of this version nothing is checked. - copies.problem = "BookSync Companion needed" - E.Copies.scanned_at = nil - E.Copies.tick("test"); run(5) - ok(copies.fc.copies_asks == 1, "not asked") - copies.problem = nil - copiesTeardown() -end) - -test("end of book: Home from the companion with the sheet open closes it, opens library home, sends the finish", function() - eobModules() - local ui, m = bookUI() - ui.status:onEndOfBook() - ok(E.EOB.sheet and W.shown[#W.shown] == E.EOB.sheet, "sheet on top") - eob.calls = {} - m:onSuspend(); W.clock = W.clock + 0.5 - command(m, "home") - m:onResume() - run(30) - ok(E.EOB.sheet == nil, "sheet closed") - local cb = ui.bookorbit.catalog_browser - ok(cb and W.shown[#W.shown] == cb, "library home on top: " .. tostring(W.shown[#W.shown] and W.shown[#W.shown].name)) - ok(table.concat(eob.calls, ","):find("status:42:read", 1, true), "finish sent: " .. table.concat(eob.calls, ",")) - cb.close_callback() - W.intent_extras["net.fledgewing.orbitcompanion.extra.COMMAND"] = nil -end) -test("end of book: the sheet's Home opens library home (never its menu) and sends the finish", function() - eobModules() - local ui, m = bookUI() - ui.status:onEndOfBook() - eob.calls = {} - sheetRow("footer", "Home").action() - run(30) - local top = W.shown[#W.shown] - ok(ui.bookorbit.catalog_browser and top == ui.bookorbit.catalog_browser, "library home on top: " .. tostring(top and top.name)) - ok(not has(ui.bookorbit.calls, "menu_sheet"), "no menu sheet") - local noted = E.LocalState.load().books["d1"] - ok(noted and noted.pending and noted.status == "complete", "the open book noted for Home's first paint") - ok(table.concat(eob.calls, ","):find("status:42:read", 1, true), "finish sent: " .. table.concat(eob.calls, ",")) - -- Home again with library home already on top: it stays, no menu sheet. - m:onOrbitGoHome() - run(5) - ok(not has(ui.bookorbit.calls, "menu_sheet") and W.shown[#W.shown] == ui.bookorbit.catalog_browser, "still Home, no menu") - ui.bookorbit.catalog_browser.close_callback() -end) -test("end of book: a finish marked here leaves Continue reading at once (plugin ids as strings)", function() - eobModules() - package.loaded["bookorbit_state_manager"].getBook = function(d) return d == "d1" and { bookId = "42" } or nil end - local ui = bookUI() - ui.status:onEndOfBook() - E.EOB.actions.back() - local body = { continueReading = { { id = 42, title = "Sea of Monsters", readStatus = "reading", progressPercentage = 99 }, - { id = 8, title = "Dare", readStatus = "reading" } }, readingGoal = { goalBooks = 10, completedBooks = 2 } } - local out = E.LocalFirst.overlay(body, E.LocalState.view()) - ok(#out.continueReading == 1 and out.continueReading[1].id == 8, "dropped from Continue reading") - ok(out.readingGoal.completedBooks == 3, "counted toward the goal") - ui.status:markBook(false) - E.LocalState.data.books["d1"] = nil -end) + + + test("outbox: completion releases the native sync lease without polling upstream diagnostics", function() local ui,m=newUI(true); run(30); W.sync_commands={} @@ -3509,23 +2914,6 @@ test("outbox: completion releases the native sync lease without polling upstream ok(not has(ui.bookorbit.calls,"fetch")) end) -test("end of book: a finished book's stale position is held", function() - eobModules() - local PCls = {} - PCls.__index = PCls - function PCls:enqueueLifecycleSnapshot(snap) eob.snap = snap end - function PCls:updateProgress() eob.live_push = true end - local ui, m = bookUI({ status = "complete" }) - setmetatable(ui.bookorbit, PCls) - E.EOB.installPluginHooks(ui.bookorbit) - E.EOB.queue()["d1"] = E.Finish.newJob({ hash = "d1", book_id = 42, final_pos = { percentage = 1 }, now = os.time() }) - E.EOB.session["d1"] = { forward = 0 } - ui.bookorbit:enqueueLifecycleSnapshot({ digest = "d1", percentage = 0.5, progress = "x", status = "complete" }, "close") - ok(eob.snap and eob.snap.percentage == nil, "position held") - ui.bookorbit:enqueueLifecycleSnapshot({ digest = "d1", percentage = 0.95, status = "complete" }, "close") - ok(eob.snap.percentage == 0.95, "near the end: sent") - E.EOB.queue()["d1"] = nil -end) ---------------------------------------------------------------- local-first Home (ROADMAP 3) @@ -4115,40 +3503,6 @@ end) ---------------------------------------------------------------- v0.11.2 (M8C test of v0.11.1) -test("lists: All books and Recently updated offer By series and By author; read in 100-book pages, grouped once (v0.11.2)", function() - package.loaded["bookorbit_catalog"], package.loaded["bookorbit_api"] = LCat, LApi - newUI(false) - for _, params in ipairs({ { sort = "title" }, { sort = "recently_updated", order = "desc" } }) do - lists_server.urls = {} - W.logs = {} - local cat = newCatalog(LCat, LApi, { kind = "books", title = params.sort == "title" and "All books" or "Recently updated", params = params }) - local m = cat:listSortSheetModel({}) - ok(m.rows[1].key == "orbit-series" and m.rows[2].key == "orbit-authors", params.sort .. ": the rows are offered") - cat:listRun({ kind = "orbit-group", section = "series" }) - run(1) - ok(#lists_server.urls == 3, params.sort .. ": three pages of two: " .. #lists_server.urls) - for _, u in ipairs(lists_server.urls) do - ok(u:find("size=100", 1, true) and u:find("sort=title", 1, true) and not u:find("recently", 1, true), "the paged read: " .. u) - end - local ctx = cat.current_context - ok(ctx.section == "series" and ctx.orbit_group and ctx.total == 3, "the Series view of the whole library") - local grouped, read - for _, l in ipairs(W.logs) do - if l:find("lists: grouped 5 books of all by series in", 1, true) then grouped = (grouped or 0) + 1 end - if l:find("lists: read 5 books of all", 1, true) and l:find(" ms (3 page(s))", 1, true) then read = true end - end - ok(grouped == 1 and read, "timed in the log: " .. table.concat(W.logs, " | ")) - -- Page 2 of the view reuses the groups. - cat:loadSection("series", { replace = true, offset = 2 }) - grouped = 0 - for _, l in ipairs(W.logs) do if l:find("lists: grouped", 1, true) then grouped = grouped + 1 end end - ok(grouped == 1 and #lists_server.urls == 3, "built once per list") - -- A row: the server's series page with the list's filters (no ids). - cat:listRun({ kind = "open-series", entry = cat.current_context.entries[1] }) - ok(cat.loaded.params.ids == nil and cat.loaded.params.orbitGroup, "a series of the library, from the server") - end - package.loaded["bookorbit_catalog"], package.loaded["bookorbit_api"] = nil, nil -end) test("reading gate: BookOrbit over the book is not reading, whatever floats on top; Wi-Fi agrees (v0.11.2)", function() RE.Gate.queue = {} @@ -4954,19 +4308,17 @@ test("reading: a locked cache cannot delay page turns or cold/warm cache reads", st:close() end) -test("reading: finish sync skips catalog calls and file writes, then completes outside reading", function() - local reading, usable = RE.reading, RE.EOB.usable - local done, touched = 0, 0 - RE.reading = function() return true end - RE.EOB.usable = function() touched = touched + 1; return false end - RE.EOB.drain({}, false, function() done = done + 1 end) - eq(touched, 0, "reading returns before any finish/detail work") - eq(done, 1, "the outbox callback is not held") - RE.reading = function() return false end - RE.EOB.drain({}, false, function() done = done + 1 end) - eq(touched, 1, "the next sync outside reading can do the deferred work") - eq(done, 2) - RE.reading, RE.EOB.usable = reading, usable +test("reading: finish sync returns immediately and dispatches only outside reading", function() + local reading,action=RE.reading,RE.Library.catalogAction + local done,calls=0,0 + RE.Library.catalogAction=function(op,args,cb) eq(op,"finish.drain");calls=calls+1;cb({ok=true}) end + RE.reading=function() return true end + RE.FinishUI.drain({},false,function() done=done+1 end) + eq(calls,0);eq(done,1) + RE.reading=function() return false end + RE.FinishUI.drain({},false,function() done=done+1 end) + eq(calls,1);eq(done,2) + RE.reading,RE.Library.catalogAction=reading,action end) test("network: native preparation never probes a server or starts a subprocess", function() @@ -5457,6 +4809,7 @@ if os.getenv("ORBIT_REQUIRE_READER_FLOWS") then assert(executed[name], "required reader flow did not run: " .. name) end end +dofile(here .. "/catalog_actions_flows.lua")({E=RE,W=W,test=test,eq=eq,ok=ok,newUI=newUI,UIManager=UIManager,store=store}) print(string.format("%d passed, %d failed", passed, failed)) if failed > 0 then for _, l in ipairs(W.logs) do print(l) end diff --git a/docs/FEATURES.md b/docs/FEATURES.md index ddd054c9..88801c62 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -30,7 +30,7 @@ Counts include settings exposure as separate rows; they are not feature quality | Feature / behaviour | Android (M8C / Boox) | X4 Pro | X4 classic | X3 | |---|---|---|---|---| | Catalog lists, search and detail through the BookOrbit integration | ✅ (v0.11.3-rc.17) Cached catalog adapter. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt:20](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt#L20) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Catalog cache and facet queries. [xteink/orbify/CatalogRefresh.inc:31](../xteink/orbify/CatalogRefresh.inc#L31) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Catalog cache and facet queries. [xteink/orbify/CatalogRefresh.inc:31](../xteink/orbify/CatalogRefresh.inc#L31) | 🟡 Online catalog; no BookSync offline cache; **hardware: cache uses PSRAM; X3 flash cuts**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | -| Group every catalog list by series or author | ✅ (v0.11.3-rc.17) Series/author chips and grouped rows. [android/koreader/orbit.koplugin/ko/server/bookorbit/grouping.lua:40](../android/koreader/orbit.koplugin/ko/server/bookorbit/grouping.lua#L40) | ❌ Facet lists exist; no group-every-list control; **deliberately deferred: ROADMAP Next 6a**. [xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch:6](../xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch#L6) | ❌ Facet lists exist; no group-every-list control; **deliberately deferred: ROADMAP Next 6a**. [xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch:6](../xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch#L6) | ❌ No grouping control; **hardware: current cached implementation excluded on X3; ROADMAP Next 6a**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | +| Group every catalog list by series or author | ✅ (v0.11.3-rc.17) Series/author chips and grouped rows. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt:40](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt#L40) | ❌ Facet lists exist; no group-every-list control; **deliberately deferred: ROADMAP Next 6a**. [xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch:6](../xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch#L6) | ❌ Facet lists exist; no group-every-list control; **deliberately deferred: ROADMAP Next 6a**. [xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch:6](../xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch#L6) | ❌ No grouping control; **hardware: current cached implementation excluded on X3; ROADMAP Next 6a**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | | Offline catalog pages and retained book details | ✅ (v0.11.3-rc.17) SQLite cache via companion. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CacheStore.kt:17](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CacheStore.kt#L17) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) SD cache; retained replies. [xteink/orbify/CacheStore.cpp:396](../xteink/orbify/CacheStore.cpp#L396) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) SD cache; retained replies. [xteink/orbify/CacheStore.cpp:396](../xteink/orbify/CacheStore.cpp#L396) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | | Explicit resumable Full refresh; monotone percentage | ✅ (v0.11.3-rc.17) Refresh tap expands running Full refresh progress; otherwise refreshes normally; hold offers Full refresh. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/AdapterWorker.kt:62](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/AdapterWorker.kt#L62) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Persistent checkpoint and worker with native refresh progress controls. [xteink/orbify/RefreshRunner.cpp:32](../xteink/orbify/RefreshRunner.cpp#L32) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Persistent checkpoint and worker with native refresh progress controls. [xteink/orbify/RefreshRunner.cpp:32](../xteink/orbify/RefreshRunner.cpp#L32) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate and no PSRAM exclude the Full refresh worker and its progress controls**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | | Bulk manifest, derived lists and batched state reconciliation | ✅ (v0.11.3-rc.17) Bulk catalog plan. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BulkWork.kt:10](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BulkWork.kt#L10) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Bulk catalog derived author/series lists. [xteink/orbify/BulkCatalog.cpp:22](../xteink/orbify/BulkCatalog.cpp#L22) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Bulk catalog derived author/series lists. [xteink/orbify/BulkCatalog.cpp:22](../xteink/orbify/BulkCatalog.cpp#L22) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | @@ -38,15 +38,15 @@ Counts include settings exposure as separate rows; they are not feature quality | Saved pages retained indefinitely; silent incremental refresh | ✅ (v0.11.3-rc.17) Companion reconciliation. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/AdapterWorker.kt:62](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/AdapterWorker.kt#L62), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt:20](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt#L20) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Opening does not evict/revalidate; worker incremental requests. [xteink/orbify/CacheStore.cpp:496](../xteink/orbify/CacheStore.cpp#L496), [xteink/orbify/RefreshRunner.cpp:36](../xteink/orbify/RefreshRunner.cpp#L36) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Opening does not evict/revalidate; worker incremental requests. [xteink/orbify/CacheStore.cpp:496](../xteink/orbify/CacheStore.cpp#L496), [xteink/orbify/RefreshRunner.cpp:36](../xteink/orbify/RefreshRunner.cpp#L36) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | | One storage budget: 250 MB default, 100 MB through 10 GB or unlimited | ✅ (v0.11.3-rc.17) Companion eviction plan; protected entries can prevent fitting. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/StorageLogic.kt:9](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/StorageLogic.kt#L9), [shared/settings/schema.json:824](../shared/settings/schema.json#L824) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Shared 64-bit budget on SD catalog. [xteink/orbify/Settings.cpp:68](../xteink/orbify/Settings.cpp#L68), [xteink/orbify/CacheStore.cpp:26](../xteink/orbify/CacheStore.cpp#L26) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Shared 64-bit budget on SD catalog. [xteink/orbify/Settings.cpp:68](../xteink/orbify/Settings.cpp#L68), [xteink/orbify/CacheStore.cpp:26](../xteink/orbify/CacheStore.cpp#L26) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | | Lazy covers and repair on Full refresh | ✅ (v0.11.3-rc.17) Thumbnail cache and ETag-aware fetch. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ThumbnailCache.kt:8](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ThumbnailCache.kt#L8) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Cache plus mirror. [xteink/orbify/Mirror.cpp:26](../xteink/orbify/Mirror.cpp#L26), [xteink/orbify/CacheStore.cpp:26](../xteink/orbify/CacheStore.cpp#L26) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Cache plus mirror. [xteink/orbify/Mirror.cpp:26](../xteink/orbify/Mirror.cpp#L26), [xteink/orbify/CacheStore.cpp:26](../xteink/orbify/CacheStore.cpp#L26) | 🟡 Live catalog covers; no retained BookSync cache/repair; **hardware: cached cover path cut for flash/PSRAM**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | -| Download progress and return to catalog | ✅ (v0.11.3-rc.17) BookOrbit download integration; companion copy worker. [android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua:18](../android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua#L18) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Return-to-catalog patch; native progress on S3. [xteink/tailnet/tailnet_build.py:239](../xteink/tailnet/tailnet_build.py#L239) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Return-to-catalog patch; native progress on S3. [xteink/tailnet/tailnet_build.py:239](../xteink/tailnet/tailnet_build.py#L239) | 🟡 Progress bar only if largest free block fits framebuffer plus 40,000-byte margin; otherwise static Downloading screen; **hardware: conditional framebuffer restoration to preserve TLS heap**. [xteink/tailnet/tailnet_build.py:247](../xteink/tailnet/tailnet_build.py#L247), [xteink/tailnet/tailnet_build.py:248](../xteink/tailnet/tailnet_build.py#L248), [xteink/overlay/patches/v2.0/0013-download-progress-ui.patch:13](../xteink/overlay/patches/v2.0/0013-download-progress-ui.patch#L13) | -| Replace changed library copies; preserve reading state | ✅ (v0.11.3-rc.17) Companion copy refresh. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesLogic.kt:10](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesLogic.kt#L10), [android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua:18](../android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua#L18) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Copy check and refresh on sync. [xteink/orbify/CopyRefresh.cpp:31](../xteink/orbify/CopyRefresh.cpp#L31), [xteink/tailnet/tailnet_build.py:281](../xteink/tailnet/tailnet_build.py#L281) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Copy check and refresh on sync. [xteink/orbify/CopyRefresh.cpp:31](../xteink/orbify/CopyRefresh.cpp#L31), [xteink/tailnet/tailnet_build.py:281](../xteink/tailnet/tailnet_build.py#L281) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Copy check and refresh on sync. [xteink/orbify/CopyRefresh.cpp:31](../xteink/orbify/CopyRefresh.cpp#L31), [xteink/tailnet/tailnet_build.py:281](../xteink/tailnet/tailnet_build.py#L281) | +| Download progress and return to catalog | ✅ (v0.11.3-rc.17) BookOrbit download integration; companion copy worker. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflow.kt:18](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflow.kt#L18) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Return-to-catalog patch; native progress on S3. [xteink/tailnet/tailnet_build.py:239](../xteink/tailnet/tailnet_build.py#L239) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Return-to-catalog patch; native progress on S3. [xteink/tailnet/tailnet_build.py:239](../xteink/tailnet/tailnet_build.py#L239) | 🟡 Progress bar only if largest free block fits framebuffer plus 40,000-byte margin; otherwise static Downloading screen; **hardware: conditional framebuffer restoration to preserve TLS heap**. [xteink/tailnet/tailnet_build.py:247](../xteink/tailnet/tailnet_build.py#L247), [xteink/tailnet/tailnet_build.py:248](../xteink/tailnet/tailnet_build.py#L248), [xteink/overlay/patches/v2.0/0013-download-progress-ui.patch:13](../xteink/overlay/patches/v2.0/0013-download-progress-ui.patch#L13) | +| Replace changed library copies; preserve reading state | ✅ (v0.11.3-rc.17) Companion copy refresh. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesLogic.kt:10](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesLogic.kt#L10), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflow.kt:18](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflow.kt#L18) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Copy check and refresh on sync. [xteink/orbify/CopyRefresh.cpp:31](../xteink/orbify/CopyRefresh.cpp#L31), [xteink/tailnet/tailnet_build.py:281](../xteink/tailnet/tailnet_build.py#L281) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Copy check and refresh on sync. [xteink/orbify/CopyRefresh.cpp:31](../xteink/orbify/CopyRefresh.cpp#L31), [xteink/tailnet/tailnet_build.py:281](../xteink/tailnet/tailnet_build.py#L281) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Copy check and refresh on sync. [xteink/orbify/CopyRefresh.cpp:31](../xteink/orbify/CopyRefresh.cpp#L31), [xteink/tailnet/tailnet_build.py:281](../xteink/tailnet/tailnet_build.py#L281) | | Furthest-place position sync, behind hold and explicit Yes/No | ✅ (0.12 (feature branch; device acceptance pending)) BookSync position sync pull/drain and prompt; 0.12 sync runs through the companion single owner with durable lifecycle replay. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt:66](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt#L66) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) BookSync position sync state and reader prompt. [xteink/orbify/OrbiSmartSync.cpp:31](../xteink/orbify/OrbiSmartSync.cpp#L31), [xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch:5](../xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch#L5) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) BookSync position sync state and reader prompt. [xteink/orbify/OrbiSmartSync.cpp:31](../xteink/orbify/OrbiSmartSync.cpp#L31), [xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch:5](../xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch#L5) | 🟡 Sleep/foreground sync; no in-reader pause/wake background transport; **hardware: TLS cannot coexist with open book on X3**. [xteink/orbify/OrbiSmartSync.cpp:31](../xteink/orbify/OrbiSmartSync.cpp#L31), [xteink/tailnet/tailnet_build.py:268](../xteink/tailnet/tailnet_build.py#L268) | | Read from here everywhere; offline queued override | ✅ (0.12 (feature branch; device acceptance pending)) BookSync position sync override; 0.12 sync runs through the companion single owner with durable lifecycle replay. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt:66](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt#L66) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable override drain. [xteink/orbify/OrbiSmartSync.cpp:333](../xteink/orbify/OrbiSmartSync.cpp#L333) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable override drain. [xteink/orbify/OrbiSmartSync.cpp:333](../xteink/orbify/OrbiSmartSync.cpp#L333) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable override drain. [xteink/orbify/OrbiSmartSync.cpp:333](../xteink/orbify/OrbiSmartSync.cpp#L333) | | Sync at sleep, with bounded time and wake cancellation | ✅ (v0.11.3-rc.17) Sleep flow and configurable cap. [android/koreader/orbit.koplugin/ko/sleep.lua:9](../android/koreader/orbit.koplugin/ko/sleep.lua#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Deadline/watchdog overlay. [xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch:9](../xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Deadline/watchdog overlay. [xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch:9](../xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Deadline/watchdog overlay. [xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch:9](../xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch#L9) | | Periodic/page/chapter sync or pause sync while book stays open | ✅ (0.12 (feature branch; device acceptance pending)) Reading schedule and BookSync position sync pause; 0.12 sync runs through the companion single owner with durable lifecycle replay. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt:66](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt#L66), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt:66](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt#L66) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Background sync task. [xteink/orbify/BookOrbitBackgroundSync.cpp:42](../xteink/orbify/BookOrbitBackgroundSync.cpp#L42) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Background sync task. [xteink/orbify/BookOrbitBackgroundSync.cpp:42](../xteink/orbify/BookOrbitBackgroundSync.cpp#L42) | ❌ TLS session does not fit beside an open book; no PSRAM; **hardware: TLS session does not fit beside an open book; no PSRAM**. [xteink/tailnet/tailnet_build.py:268](../xteink/tailnet/tailnet_build.py#L268) | | Highlight and bookmark sync carried through lifecycle sync | ✅ (0.12 (feature branch; device acceptance pending)) Drains BookOrbit lifecycle outbox; 0.12 sync runs through the companion single owner with durable lifecycle replay. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt:127](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt#L127) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Full sync; background reading defers annotation work. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Full sync; background reading defers annotation work. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sleep/foreground full sync; background unavailable. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392), [xteink/tailnet/tailnet_build.py:268](../xteink/tailnet/tailnet_build.py#L268) | | Reading sessions uploaded in full sync | ✅ (0.12 (feature branch; device acceptance pending)) Lifecycle outbox integration; 0.12 sync runs through the companion single owner with durable lifecycle replay. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt:127](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt#L127) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sessions deferred to full sync while book open. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sessions deferred to full sync while book open. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sessions deferred to full sync while book open. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | -| Final progress before durable read-status; Undo | ✅ (v0.11.3-rc.17) Finish queue and sheet. [android/koreader/orbit.koplugin/ko/server/bookorbit/endofbook.lua:39](../android/koreader/orbit.koplugin/ko/server/bookorbit/endofbook.lua#L39), [android/koreader/orbit.koplugin/ko/endsheet.lua:15](../android/koreader/orbit.koplugin/ko/endsheet.lua#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable finish queue. [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37), [xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch:9](../xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable finish queue. [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37), [xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch:9](../xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable finish queue. [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37), [xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch:9](../xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch#L9) | +| Final progress before durable read-status; Undo | ✅ (v0.11.3-rc.17) Finish queue and sheet. [android/koreader/orbit.koplugin/ko/finish.lua:39](../android/koreader/orbit.koplugin/ko/finish.lua#L39), [android/koreader/orbit.koplugin/ko/endsheet.lua:15](../android/koreader/orbit.koplugin/ko/endsheet.lua#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable finish queue. [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37), [xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch:9](../xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable finish queue. [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37), [xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch:9](../xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable finish queue. [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37), [xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch:9](../xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch#L9) | | End-of-book sheet: next series book, suggestion, author books | ✅ (v0.11.3-rc.17) End sheet. [android/koreader/orbit.koplugin/ko/endsheet.lua:15](../android/koreader/orbit.koplugin/ko/endsheet.lua#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) End page; two suggestions configured. [xteink/orbify/EndPage.cpp:27](../xteink/orbify/EndPage.cpp#L27), [xteink/tailnet/tailnet_build.py:288](../xteink/tailnet/tailnet_build.py#L288) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) End page; two suggestions configured. [xteink/orbify/EndPage.cpp:27](../xteink/orbify/EndPage.cpp#L27), [xteink/tailnet/tailnet_build.py:288](../xteink/tailnet/tailnet_build.py#L288) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) End page; two suggestions configured. [xteink/orbify/EndPage.cpp:27](../xteink/orbify/EndPage.cpp#L27), [xteink/tailnet/tailnet_build.py:288](../xteink/tailnet/tailnet_build.py#L288) | | End-of-book stars and rating upload | ✅ (v0.11.3-rc.17) Stars on end sheet. [android/koreader/orbit.koplugin/ko/endsheet.lua:15](../android/koreader/orbit.koplugin/ko/endsheet.lua#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Rating enabled. [xteink/tailnet/tailnet_build.py:285](../xteink/tailnet/tailnet_build.py#L285), [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Rating enabled. [xteink/tailnet/tailnet_build.py:285](../xteink/tailnet/tailnet_build.py#L285), [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37) | ❌ X3 rating code/strings excluded to preserve flash gate; **hardware: X3 rating code/strings excluded to preserve flash gate**. [xteink/tailnet/tailnet_build.py:285](../xteink/tailnet/tailnet_build.py#L285) | | Next-in-series cover on end sheet | ✅ (v0.11.3-rc.17) Cover on end sheet. [android/koreader/orbit.koplugin/ko/endsheet.lua:15](../android/koreader/orbit.koplugin/ko/endsheet.lua#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Cached cover drawn offline. [xteink/orbify/EndPage.cpp:8](../xteink/orbify/EndPage.cpp#L8) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Cached cover drawn offline. [xteink/orbify/EndPage.cpp:8](../xteink/orbify/EndPage.cpp#L8) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:298](../xteink/tailnet/tailnet_build.py#L298) | @@ -72,7 +72,7 @@ Counts include settings exposure as separate rows; they are not feature quality | Record/export orbit-battery-stats/1 | ✅ (v0.11.3-rc.17) Battery stats/export. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/StatsLogic.kt:20](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/StatsLogic.kt#L20) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Record and export on USB mode. [xteink/tailnet/tailnet_build.py:276](../xteink/tailnet/tailnet_build.py#L276), [xteink/orbify/BatteryStats.cpp:29](../xteink/orbify/BatteryStats.cpp#L29) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Record and export on USB mode. [xteink/tailnet/tailnet_build.py:276](../xteink/tailnet/tailnet_build.py#L276), [xteink/orbify/BatteryStats.cpp:29](../xteink/orbify/BatteryStats.cpp#L29) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Record; Settings writes JSON export. [xteink/tailnet/tailnet_build.py:276](../xteink/tailnet/tailnet_build.py#L276), [xteink/orbify/BatteryStats.cpp:29](../xteink/orbify/BatteryStats.cpp#L29) | | Battery rates and cross-reader comparison UI | ✅ (v0.11.3-rc.17) Compare stats. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/StatsLogic.kt:20](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/StatsLogic.kt#L20) | ➖ Rates page and export remain available; **not applicable: Android-only by design (screen size); a future BookSync server could serve the data to other devices.**. [xteink/orbify/BatteryStatsActivity.cpp:18](../xteink/orbify/BatteryStatsActivity.cpp#L18) | ➖ Rates page and export remain available; **not applicable: Android-only by design (screen size); a future BookSync server could serve the data to other devices.**. [xteink/orbify/BatteryStatsActivity.cpp:18](../xteink/orbify/BatteryStatsActivity.cpp#L18) | ➖ Export remains available; numeric rates display cut for flash; **not applicable: Android-only by design (screen size); a future BookSync server could serve the data to other devices.**. [xteink/tailnet/tailnet_build.py:276](../xteink/tailnet/tailnet_build.py#L276) | | Optional BookSync installer for Bitter and Literata | ✅ (v0.11.3-rc.17) Off by default; worker install. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/FontInstaller.kt:17](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/FontInstaller.kt#L17) | ➖ Fonts are CrossInk-owned, not an BookSync installer; **not applicable: Fonts are CrossInk-owned, not an BookSync installer**. [xteink/orbify/EndPage.cpp:54](../xteink/orbify/EndPage.cpp#L54) | ➖ Fonts are CrossInk-owned, not an BookSync installer; **not applicable: Fonts are CrossInk-owned, not an BookSync installer**. [xteink/orbify/EndPage.cpp:54](../xteink/orbify/EndPage.cpp#L54) | ➖ Built-in fonts/SD files are CrossInk-owned; no BookSync installer; **not applicable: Built-in fonts/SD files are CrossInk-owned; no BookSync installer**. [xteink/tailnet/tailnet_build.py:261](../xteink/tailnet/tailnet_build.py#L261) | -| Install/update KOReader, plugins; full/add-on mode; recommended defaults with Undo | ✅ (v0.11.3-rc.17) Installers, mode and recommendations. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Installers.kt:25](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Installers.kt#L25), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Mode.kt:25](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Mode.kt#L25), [android/koreader/orbit.koplugin/ko/server/bookorbit/recommended.lua:14](../android/koreader/orbit.koplugin/ko/server/bookorbit/recommended.lua#L14) | ➖ Firmware image; no Android app/launcher setup; **not applicable: Firmware image; no Android app/launcher setup**. [xteink/scripts/apply.sh:1](../xteink/scripts/apply.sh#L1) | ➖ Firmware image; no Android app/launcher setup; **not applicable: Firmware image; no Android app/launcher setup**. [xteink/scripts/apply.sh:1](../xteink/scripts/apply.sh#L1) | ➖ Firmware image; no Android app/launcher setup; **not applicable: Firmware image; no Android app/launcher setup**. [xteink/scripts/apply.sh:1](../xteink/scripts/apply.sh#L1) | +| Install/update KOReader, plugins; full/add-on mode; recommended defaults with Undo | ✅ (v0.11.3-rc.17) Installers, mode and recommendations. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Installers.kt:25](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Installers.kt#L25), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Mode.kt:25](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Mode.kt#L25), [android/koreader/orbit.koplugin/ko/recommendations.lua:14](../android/koreader/orbit.koplugin/ko/recommendations.lua#L14) | ➖ Firmware image; no Android app/launcher setup; **not applicable: Firmware image; no Android app/launcher setup**. [xteink/scripts/apply.sh:1](../xteink/scripts/apply.sh#L1) | ➖ Firmware image; no Android app/launcher setup; **not applicable: Firmware image; no Android app/launcher setup**. [xteink/scripts/apply.sh:1](../xteink/scripts/apply.sh#L1) | ➖ Firmware image; no Android app/launcher setup; **not applicable: Firmware image; no Android app/launcher setup**. [xteink/scripts/apply.sh:1](../xteink/scripts/apply.sh#L1) | | Reapply frontlight after first boot paint | ➖ Android firmware controls frontlight; **not applicable: Android firmware controls frontlight**. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Vendor.kt:19](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Vendor.kt#L19) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Boot repaint patch enabled. [xteink/tailnet/tailnet_build.py:251](../xteink/tailnet/tailnet_build.py#L251), [xteink/overlay/patches/v2.0/0024-frontlight-reapply.patch:102](../xteink/overlay/patches/v2.0/0024-frontlight-reapply.patch#L102) | ➖ No frontlight on this hardware; **not applicable: no frontlight**. [platformio.ini:603](https://github.com/agosez/CrossInk-Bookorbit/blob/87e2e1984481e8a3d996f12b34b50a383f9013b8/platformio.ini#L603) | ➖ No frontlight on this hardware; **not applicable: no frontlight**. [libs/hardware/BoardConfig/include/BoardConfig.h:1091](https://github.com/Free-Ink/freeink-sdk/blob/9d5bba3ef02a1c35363ecadbb50ad0e1ac279653/libs/hardware/BoardConfig/include/BoardConfig.h#L1091) | | Persist crash summary and deduplicate diagnostic report at boot | ❌ Logs exist; no BookSync persisted crash-record equivalent; **gap — no reason**. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ReadingLogic.kt:11](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ReadingLogic.kt#L11), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Pages.kt:18](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Pages.kt#L18) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Core-dump summary logged; not automatic remote upload. [xteink/orbify/CrashRecord.cpp:19](../xteink/orbify/CrashRecord.cpp#L19) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Core-dump summary logged; not automatic remote upload. [xteink/orbify/CrashRecord.cpp:19](../xteink/orbify/CrashRecord.cpp#L19) | ❌ Crash summary implementation is S3-only; **hardware: firmware core-dump implementation gated to S3**. [xteink/orbify/CrashRecord.cpp:6](../xteink/orbify/CrashRecord.cpp#L6) | | In-product project credit and licence notices | ✅ (v0.11.3-rc.17) Public About ships notice asset. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/AboutActivity.kt:9](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/AboutActivity.kt#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) About credit enabled. [xteink/tailnet/tailnet_build.py:270](../xteink/tailnet/tailnet_build.py#L270) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) About credit enabled. [xteink/tailnet/tailnet_build.py:270](../xteink/tailnet/tailnet_build.py#L270) | ❌ In-product BookSync About credit omitted; **hardware: About strings excluded for flash; distribution licences still shipped**. [xteink/tailnet/tailnet_build.py:270](../xteink/tailnet/tailnet_build.py#L270) | diff --git a/docs/design/backend-independence.md b/docs/design/backend-independence.md index cdd21e86..3011412b 100644 --- a/docs/design/backend-independence.md +++ b/docs/design/backend-independence.md @@ -178,17 +178,24 @@ Cover acquisition and refresh now use neutral companion commands; the plugin rea bounded local references. The former cover downloader and thumbnail child scanner are removed. Mirror planning and catalog refresh now run in the companion; the neutral library reads bounded snapshots and dispatches `catalog.control`. The Lua mirror, catalog interpreter -and old library binding are deleted. The parallel F12-Q2 slice owns remaining grouping, -copies, recommendations and end-of-book transport. Until that slice lands, the **whole -plugin** is not yet server-free. Its cached catalog display helpers are extracted into +and old library binding are deleted. The F12-Q2 catalog slice now owns grouping, +copies, recommendations and end-of-book commands as well. Its cached catalog display helpers are extracted into `ko/server/bookorbit/local_view.lua`; existing non-sync jobs receive neutral lifecycle signals through the library binding. The named middleware (`wifi`, `sleep`, `module`, `net`, `shared`, `main_loop`) no longer accesses the server facade for sync. The remaining reviewed compatibility facade consumers are Home, notices, sleepscreen and endsheet; only `main.lua` loads implementation files. No new Lua transport is permitted. +Catalog-side copies, grouping, recommendations and end-of-book are also companion-owned +(F12-Q2 step 4). The four legacy Lua modules are deleted; `ko/library.lua` dispatches neutral +`catalog.action` and `settings.recommendations` commands and reads bounded snapshots. +`CopiesLogic`, `CacheWorker`, `BookOrbitProjection` and the existing read model own catalog +work. Account-scoped copy/finish queues checkpoint legacy sources and acknowledge identity +and writeback phases. Finishes follow SyncOwner delivery; no retired native writer is called. +Temporary catalog display/native-setting bindings remain in the private Lua compatibility root. + Every screen/widget keeps its budget. Consent and bounded native verification add named -one-row / 16 KiB budgets; commands, drains and paints log timing spans. No sync is added -to Home paint. Heavy capture, sidecar processing and statistics stay on the companion. -Device acceptance targets remain pending maintainer confirmation. Firmware adapter -enforcement is deferred under the Android-first instruction. +one-row / 16 KiB budgets; finish has three rows and recommendation review has eight. +Commands, drains and paints log timing spans. No sync is added to Home paint. Heavy capture, +sidecar processing and statistics stay on the companion. Device targets remain pending +maintainer confirmation. Firmware enforcement is deferred under the Android-first ruling. diff --git a/docs/design/booksync-home/F12-Q2-NOTES.md b/docs/design/booksync-home/F12-Q2-NOTES.md index b0a49d0c..b65c0fc4 100644 --- a/docs/design/booksync-home/F12-Q2-NOTES.md +++ b/docs/design/booksync-home/F12-Q2-NOTES.md @@ -126,3 +126,71 @@ model bytes to/from UTF-8 exactly once; byte limits charge UTF-8 bytes. A real J stand-in and companion codec tests cover non-ASCII owner/query/path round-trips. The package gate asserts the protocol inventory is absent from the plugin zip; its companion copy remains checked against the shared inventory fixture. + + +## Step 4: copies, grouped lists, recommendations and finish + +Android-only maintainer ruling continues. Deleted the four catalog-side Lua adapter modules: +`copies.lua`, `grouping.lua`, `recommended.lua` and `endofbook.lua`. The plugin dispatches +neutral commands through `ko/library.lua`; local native settings/reader hooks remain behind +that interface. Catalog HTTP, backend JSON, file sampling, downloads, comparisons, grouping, +next-book/suggestion selection, counts and review labels now run in the companion. + +Reuse evidence (current paths/lines): + +- `server/bookorbit/CacheWorker.kt:318` extends its saved-detail lookup as `changedCopies`; + `:338` retains sidecar/statistics migration. `CopiesLogic.kt:35` retains candidate rules and + now also selects readable delivery files; `HashSidecar` retains hash-keyed folder migration. +- `LibraryReadModel.kt:26` retains bounded publication and owner checks; `BookOrbitProjection.kt:249` + extends its existing membership boundary with neutral native-list selection scope, then reuses + its group projection at `:330`. No second catalog or full-list cache is added in Lua. +- `BookOrbitLibrary.kt:36` retains the account-scoped local file ledger; the worker now refreshes + it from persisted native state, including account-specific filenames. No Lua catalog scan is sent. +- `ko/endsheet.lua` retains the approved sheet renderer; `ko/home_host.lua` retains owned list and + Series navigation. `ko/library.lua` retains existing bounded paints, commands and batched reads. + `ko/base.lua` now owns the common native-hook chain previously hidden in grouping. + +`CatalogWorkflow` uses the existing sole cache writer, `ConnectorHttp`, `CopiesLogic` and +read model. It persists account-scoped workflow files outside cache ownership resets. Legacy +copy, finish and deferred-download queues remain intact; a source-owner claim and durable +migration checkpoint prevent cross-account replay and resurrection after acknowledgement. +Replacement bytes are sampled/verified before atomic rename; an interrupted rename/identity +handoff resumes from its saved phase. Identity and finish writeback are idempotent, acknowledged +phases. Finish event tokens reject older events after a newer mark. The owned lifecycle journal remains the sole position writer. The temporary `EOB` handle +retains cached display/session compatibility without retaining a second finish sender. + +`RecommendationPlan` supplies at most eight native-setting descriptors, decisions, review rows, +labels/counts and backups; only observed native settings are written on the reader, with a +compare-before-write check. Review JSON is written by the companion. Use/Keep/Undo and bulk +review retain capability-aware Wi-Fi handling. Backups are saved before native actions. + +Budgets: finish screen/widget three rows (summary plus two cards), recommendation screen/widget +eight rows, copies state one local row; each snapshot <=16 KiB. Zero plugin network/forks, +one batched read per paint, and info spans for calls/paints/draws. Queue checkpoints remain +available while reading; background transfers pause. Device timing targets remain unconfirmed. + +Tests move the retired network/interpreter assertions into companion workflow/projection tests, +including the recorded delivery-variant fixture (registry reader moves from Lua to Kotlin). +Lua tests exercise neutral dispatch, bounded sheets, stale-push holds, gated copy commands, +callback visibility and budgets. Existing native sync/reading/SQLite-lock/owned UI tests remain. +The boundary guard rejects copy/finish transport even inside a Lua adapter and checks all four +retired paths stay absent. F12-Q is integrated; remaining root/display cleanup belongs to step 5. + +Pinned upstream evidence at `c1dd6b4f1947ff50843a155e12e70f1e7d15f0c7`: +`koreader-plugin/bookorbit.koplugin/bookorbit_api.lua:705`/`:709` define status/rating writes; +`:737`/`:741` define delivery detail/file acquisition. `bookorbit_delivery.lua:32` defines +variant precedence; `bookorbit_state_manager.lua:233` defines private account identity; +`bookorbit_state.lua:34` selects the native account filename. These bindings are now private +companion adapter concerns. No devices, releases, tags or firmware changes are involved. + +## Integration with the merged F12-Q writer + +The owned sync writer now precedes finish delivery; pending native-sidecar application does +not block completed position transport, but a transport error prevents finish delivery. +Adopting a proven native login preserves its catalog namespace and pending workflow files; +existing managed login namespaces stay intact. A completed match forwards its local identity +to the existing catalog ledger, without a second lifecycle writer. Local-only finish preparation +warms one identity row while reading. Native catalog downloads use the companion command; +verified cache hits reuse the file and native cache linking is replayable after a restart. +Saved recommendation choices feed the owned sync settings source. Tests cover the ownership +handoff, offline match/finish identity, pending native links and native download suppression. diff --git a/shared/contract/companion.json b/shared/contract/companion.json index 2b40adf1..942e726f 100644 --- a/shared/contract/companion.json +++ b/shared/contract/companion.json @@ -135,20 +135,6 @@ ], "does": "count what BookSync stores and remove the oldest over the limit" }, - { - "name": "COPIES", - "method": "net.fledgewing.orbitcompanion.action.COPIES", - "extras": [ - "reason", - "ask", - "prepare", - "template", - "server", - "user", - "userkey" - ], - "does": "find changed copies from an in-memory ask, or prepare one replacement in the companion" - }, { "name": "SLEEP_REFRESH", "method": "net.fledgewing.orbitcompanion.action.SLEEP_REFRESH", @@ -182,14 +168,9 @@ "reason", "drain_events", "events_ack", - "old_hash", - "new_hash", "board_year", "board_key", - "board_now", - "remember_id", - "copy_path", - "plugin_state" + "board_now" ], "does": "a write the plugin made, patched into orbit.db (or a wipe)" }, @@ -401,7 +382,7 @@ }, { "path": "koreader/settings/orbit-recommended.json", - "writer": "plugin", + "writer": "companion", "reader": "companion", "format": "json", "what": "the recommended settings' rows" @@ -524,9 +505,9 @@ { "path": "koreader/settings/orbit-cache/plugin-state.lua", "writer": "companion", - "reader": "plugin", + "reader": "companion", "format": "lua", - "what": "detail variant and copies queue snapshot" + "what": "legacy snapshot retained intact until account-scoped catalog workflow migration checkpoints its copies queue" } ], "db": { diff --git a/shared/features.json b/shared/features.json index f7adb2bf..1dd87512 100644 --- a/shared/features.json +++ b/shared/features.json @@ -91,7 +91,7 @@ "reason": null, "evidence": [ { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/grouping.lua", + "path": "android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitProjection.kt", "line": 40 } ], @@ -563,7 +563,7 @@ "reason": null, "evidence": [ { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua", + "path": "android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflow.kt", "line": 18 } ], @@ -630,7 +630,7 @@ "line": 10 }, { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua", + "path": "android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CatalogWorkflow.kt", "line": 18 } ], @@ -1047,7 +1047,7 @@ "reason": null, "evidence": [ { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/endofbook.lua", + "path": "android/koreader/orbit.koplugin/ko/finish.lua", "line": 39 }, { @@ -2731,7 +2731,7 @@ "line": 25 }, { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/recommended.lua", + "path": "android/koreader/orbit.koplugin/ko/recommendations.lua", "line": 14 } ], diff --git a/shared/fixtures/REGISTRY.json b/shared/fixtures/REGISTRY.json index 27d0e2c0..e668dd15 100644 --- a/shared/fixtures/REGISTRY.json +++ b/shared/fixtures/REGISTRY.json @@ -335,7 +335,7 @@ "rule": "Recorded book detail with and without a delivery variant", "owner": "server", "readers": [ - "lua" + "kt" ] }, { diff --git a/tools/test/test-server-boundary.py b/tools/test/test-server-boundary.py index 33665461..34076191 100644 --- a/tools/test/test-server-boundary.py +++ b/tools/test/test-server-boundary.py @@ -74,6 +74,8 @@ def violations(path, source): cover_errors.append(f'{path}: plugin cover transport is companion-owned; use the neutral library command') if re.search(r'\b(?:Store[.:](?:read|search)|Server[.:]bulkList)\s*\(|\bCompanion\.ACTION\.(?:MIRROR|CHECK)\b|\b(?:FROM|JOIN)\s+(?:bulk_\w+|list_items|books)\b', code, re.I): cover_errors.append(f'{path}: catalog interpretation/transport is companion-owned; consume a bounded library snapshot') + if re.search(r'\bCompanion\.ACTION\.COPIES\b|[:.]catalogSet(?:ReadStatus|Rating)\s*\(|[:.]downloadCatalogFile\s*\(|[\"\']/koreader/plugin/catalog/(?:files|books)/', code): + cover_errors.append(f'{path}: catalog copy/finish transport is companion-owned; use Library commands/snapshots') if kotlin_adapter or lua_adapter: if kotlin_adapter and path.suffix in ('.kt', '.java'): expected = '.'.join(path.relative_to(source_root).parent.parts) @@ -198,6 +200,19 @@ def test_catalog_interpreter_cannot_be_reintroduced_in_any_lua_adapter(self): self.assertFalse(violations(LUA / 'ko/library.lua','Store.library(owner,request)')) self.assertTrue(violations(LUA / 'ko/library.lua','Store.rows(conn,sql)')) + def test_copy_and_finish_transport_cannot_hide_in_any_lua_adapter(self): + for path in (LUA / 'ko/library.lua',LUA / 'ko/server/bookorbit/other.lua'): + for source in ('Companion.send(Companion.ACTION.COPIES,{})','client:catalogSetReadStatus(id,status)', + 'client:catalogSetRating(id,rating)','client:downloadCatalogFile(id,path)', + 'local route="/koreader/plugin/catalog/files/7/download"'): + self.assertTrue(violations(path,source),(path,source)) + for name in ('copies','grouping','recommended','endofbook'): + retired=LUA / 'ko/server/bookorbit' / (name+'.lua') + self.assertFalse((ROOT / retired).exists()) + self.assertNotIn(str(retired.relative_to(LUA)),(ROOT / LUA_REGISTRY).read_text()) + for name in ('finish','recommendations'): + self.assertFalse(violations(LUA / 'ko' / (name+'.lua'),(ROOT / LUA / 'ko' / (name+'.lua')).read_text())) + def test_entire_production_tree(self): errors = [] for root in (COMPANION, LUA, *RESOURCE_ROOTS):