diff --git a/AGENTS.md b/AGENTS.md index d7931640..dc1bd78b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,9 +53,9 @@ CrossInk 2.x bridge and the later stable BookSync releases become available (`xt The interface is introduced in 0.12 ([BookSync Home's owned-client design](docs/design/backend-independence.md#1-owned-android-client-and-ledger)). - **Server adapters own protocol.** Android endpoint paths, authentication, upstream transport primitives, backend JSON and - backend terms live only in `server/bookorbit` (Kotlin) and `ko/server/bookorbit` / - `logic/server/bookorbit` (Lua compatibility). Only `ServerAdapters.kt` and the plugin loader - wire implementations. Direct legacy Lua globals are not an interface: use Library or the + backend terms live only in the companion's `server/bookorbit` package (Kotlin). + Android plugin Lua has no server adapter exemption. `ServerAdapters.kt` wires protocol + implementations; the plugin loader binds only neutral local retirement metadata. Direct legacy Lua globals are not an interface: use Library or the reviewed Server facade; local file IO belongs to generic Store. UI uses the neutral library/read model and capability flags. Run `python3 tools/test/test-server-boundary.py`; no baseline, suppression or skip list is allowed. @@ -321,3 +321,9 @@ Device-local library projections use their own reserved owner without changing c ownership. They inherit the same screen/widget row, byte and one-batch limits; folder and sidecar work stays on the companion. Login adoption checkpoints secrets and its migration marker together in the existing encrypted vault; never activate a second lifecycle writer. + +Android plugin Lua has no adapter-directory or composition-root exemption: no server routes, +HTTP clients or vendor identifiers. Legacy class retirement uses one bounded local Library +bootstrap descriptor (one row, 16 KiB, one round-trip, zero network/subprocesses) before instances +start; a missing, late or mismatched companion never claims sync ownership. Retirement metadata +and native setting/gesture identifiers are supplied by the companion adapter, never encoded in Lua. diff --git a/ROADMAP.md b/ROADMAP.md index 94d6dd60..aef24cf9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -16,7 +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) | +| 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) | implemented on feature/0.12 (F12-Q2 step 5; device acceptance pending) | |---|---|---| | Word of the day, local Reading buddy, hardware Light, Highlight and A year ago picker widgets through companion projections and a source-aggregating personal-data interface. | 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 63f25301..6edc11e2 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 @@ -33,6 +33,7 @@ class CommandProvider : ContentProvider() { /** The plugin's key and the companion's proof for one `GET /clicks` (ClickChannel). */ const val CLICKS = "${Contract.PACKAGE}.call.CLICKS" + const val LIBRARY_BOOTSTRAP = "${Contract.PACKAGE}.call.LIBRARY_BOOTSTRAP" const val DEVICE_SETTINGS = "${Contract.PACKAGE}.call.DEVICE_SETTINGS" /** USB only: the shell (adb, tools/sideload-android.sh) asks for KOReader's restart. */ @@ -80,6 +81,14 @@ class CommandProvider : ContentProvider() { if(body.size>16384) return answer(false,"budget") return answer(true).apply { putString("body",String(body,Charsets.UTF_8)) } } + if (method == LIBRARY_BOOTSTRAP) { + if(extras?.getString("patch_version")!=BuildConfig.VERSION_NAME) return answer(false,"version") + val start=System.nanoTime() + val body=LuaValue.transportText(ServerAdapters.connector.retirementPlan()) + OLog.i("library.bootstrap ms=${(System.nanoTime()-start)/1_000_000}") + if(body.toByteArray().size>16384) return answer(false,"budget") + return answer(true).apply { putString("body",body) } + } if (method == DEVICE_SETTINGS) { DeviceSettings.refreshAsync() return answer(true).apply { putString("body",LuaValue.transportText(DeviceSettings.snapshot())) } 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 fc64f5a3..8bb9f85f 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 @@ -77,6 +77,8 @@ interface ProjectionStore : AutoCloseable { } interface ConnectorInstaller { + /** Bounded local retirement metadata; no network, credentials or catalog data. */ + fun retirementPlan(): Map = emptyMap() val minimumVersion: String val homeModeKey: String fun coverCacheDir(root: File): File 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 7a6defd9..24fab7e8 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 @@ -242,10 +242,12 @@ object AdapterWorker : ServerRuntime { } private fun creds(i: Intent): CacheWorker.Creds? { - val server = i.getStringExtra("server")?.takeIf { it.isNotEmpty() } ?: return null - val user = i.getStringExtra("user") ?: return null - val key = i.getStringExtra("userkey") ?: return null - return CacheWorker.Creds(server, user, key) + val ctx=app ?: return null + val credentials=ServerCredentials(EncryptedAccountVault.android(ctx)) + val login=credentials.login("sync") + if(login!=null) return CacheWorker.Creds(login.server,login.user,login.secret) + if(credentials.legacyImported()) return null + return LegacyCoverSource.read(File(Environment.getExternalStorageDirectory(),"koreader/settings.reader.lua"))?.credentials } override fun onIntent(ctx: Context, i: Intent) { 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 index b06a1563..ee1dd98d 100644 --- 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 @@ -86,7 +86,7 @@ internal class CatalogWorkflow(private val worker: CacheWorker, private val cred 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(row["owned_sync"]!=true && 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"])) @@ -157,6 +157,8 @@ internal class CatalogWorkflow(private val worker: CacheWorker, private val cred "final_pos" to mapOf("percentage" to args["percentage"]),"status_seen" to status,"rating" to jobs[hash]?.get("rating")) } else jobs.remove(hash) save() + id(args)?.let { book -> worker.patch(book,mapOf("readStatus" to if(args["complete"]==true) "read" else "reading", + "progressPercentage" to ((args["percentage"] as? Number)?.toDouble()?.times(100))),true,false) } } "finish.rate" -> { jobs[hash]?.set("rating", args["rating"] ?: "clear"); save() } "finish.leave" -> { jobs[hash]?.set("ready",true); save() } @@ -279,7 +281,7 @@ internal class CatalogWorkflow(private val worker: CacheWorker, private val cred 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) { + private fun recordLocal(book:Long,fileReference:Any?,path:String,hash:String,ownedSync:Boolean=true) { 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() diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ConnectorPlugin.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ConnectorPlugin.kt index 9d15f045..7147a08f 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ConnectorPlugin.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ConnectorPlugin.kt @@ -6,6 +6,13 @@ import org.json.JSONArray import org.json.JSONObject object ConnectorPlugin : ConnectorInstaller { + override fun retirementPlan(): Map = mapOf( + "plugins" to listOf("bookorbit"), "modules" to listOf("bookorbit_api"), + "settings_key" to "bookorbit", "home_key" to "bookorbit", "row_count" to 1, + "preference_overlay" to mapOf("record" to "osm_saved_plugin","guard" to mapOf("sync_forward" to 3,"sync_backward" to 3), + "keys" to listOf("sync_forward","sync_backward","auto_sync")), + "actions" to listOf(mapOf("id" to "bookorbit_sync_now","event" to "LibrarySyncAll","title" to "BookSync: Sync all books"), + mapOf("id" to "bookorbit_this_book","event" to "LibraryThisBook","title" to "BookSync: This book"))) override val minimumVersion = PluginRelease.MIN_VERSION override val homeModeKey = "bookorbit" override fun coverCacheDir(root: File) = File(root, "koreader/cache/bookorbit") 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 index 6cad4a9c..522576a5 100644 --- 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 @@ -65,6 +65,13 @@ class CatalogWorkflowTest { catch(_:IllegalArgumentException) { } } finally { outside.delete() } } + @Test fun offlineFinishAndUndoImmediatelyPatchTheOwnedCatalogWithoutNetwork()=World().use { w -> + w.reading=true;w.mark() + assertEquals("read",(w.worker.store.detail(7)!!.first as Map<*,*>)["readStatus"]) + w.run("finish.mark",mapOf("path" to w.old.path,"document" to CatalogWorkflow.partial(w.old),"complete" to false,"percentage" to .9)) + assertEquals("reading",(w.worker.store.detail(7)!!.first as Map<*,*>)["readStatus"]) + assertTrue(w.calls.isEmpty());assertTrue(w.jobs().isEmpty()) + } @Test fun nativeRecommendationLabelsAreProjectedAndAllEightRowsFitTheBudget() { val definitions=RecommendedSettings.items val observations=definitions.associate { it["id"] as String to mapOf("available" to true,"current" to it["ours"]) } diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/ContractTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/ContractTest.kt index 9a08439e..38f224d7 100644 --- a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/ContractTest.kt +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/ContractTest.kt @@ -49,7 +49,7 @@ class ContractTest { "RESTART_KOREADER" to CommandProvider.RESTART_KOREADER, "SERVER_STATE" to LibraryAccount.STATE, "SERVER_COMMAND" to ServerCommands.START, "SERVER_RESULT" to ServerCommands.RESULT, "ACCOUNT_OPEN" to LibraryAccount.OPEN, - "DEVICE_SETTINGS" to CommandProvider.DEVICE_SETTINGS), calls.mapValues { it.value.getString("method") }) + "DEVICE_SETTINGS" to CommandProvider.DEVICE_SETTINGS,"LIBRARY_BOOTSTRAP" to CommandProvider.LIBRARY_BOOTSTRAP), calls.mapValues { it.value.getString("method") }) assertEquals("shell", calls.getValue("RESTART_KOREADER").getString("caller")) calls.values.forEach { o -> (o.getJSONArray("extras").strings() + o.getJSONArray("answer").strings()).forEach { used(it, "call field") } } c.getJSONArray("answer").strings().forEach { used(it, "answer field") } diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/RetiredCatalogFixtureTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/RetiredCatalogFixtureTest.kt new file mode 100644 index 00000000..bde5ec1a --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/RetiredCatalogFixtureTest.kt @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import org.junit.Assert.* +import org.junit.Test +import java.io.File +import java.nio.file.Files + +/** Historical Lua catalog fixtures now exercise the existing companion implementation. */ +class RetiredCatalogFixtureTest { + private val fixtures=File("../../../shared/fixtures") + private fun fixture(name:String)=LuaValue.fromJson(File(fixtures,name).readText()) as Map<*,*> + private fun num(v:Any?)=(v as Number).toInt() + // @fixture cache/cases.json#mirror.windows + @Test fun windowIdentityIsIndependentOfDisplayPaging() { + val rows=((fixture("cache/cases.json")["mirror"] as Map<*,*>)["windows"] as List<*>).map { it as Map<*,*> } + for(r in rows) { + val actual=MirrorLogic.listWindow(r["path"] as String) + if(r["list"]==false) assertNull(actual) + else assertEquals(r["same"],actual?.identity==MirrorLogic.listWindow(r["identity_of"] as String)?.identity) + } + } + // @fixture cache/cases.json#mirror.slices + // @fixture cache/cases.json#mirror.small_pages + @Test fun savedPagesAnswerSmallDisplayWindowsAndMissingPagesStayMissing() { + val mirror=fixture("cache/cases.json")["mirror"] as Map<*,*> + for(raw in (mirror["slices"] as List<*>)+(mirror["small_pages"] as List<*>)) { + val r=raw as Map<*,*>;val window=r["window"] as Map<*,*> + val root=Files.createTempDirectory("retired-window").toFile() + try { CacheStore(root,{}, {JdbcSql(it)}).use { store -> + store.own("fixture") + val total=num(r["total"]);val size=(r["page_size"] as? Number)?.toInt() ?: 100 + val base=if(window["kind"]=="books") "/koreader/plugin/catalog/books" else "/koreader/plugin/catalog/sections/series" + for(page in r["saved_pages"] as List<*>) { + val offset=(num(page)-1)*size + val items=(offset+1..minOf(offset+size,total)).map { mapOf("id" to it.toLong(),"title" to "Book $it") } + val path="$base?page=${num(page)}&size=$size" + store.save(MirrorLogic.key("fixture","https://library.example",path),path,mapOf("items" to items,"total" to total.toLong(),"page" to num(page).toLong(),"size" to size.toLong()),1,null) + } + val q=window.filterKeys { it!="kind" }.entries.joinToString("&") { "${it.key}=${it.value}" } + val path="$base?$q" + val result=store.read(MirrorLogic.key("fixture","https://library.example",path),path,null) + if(r["items"]==null) assertNull(r["name"].toString(),result) + else { + val body=result!!.body as Map<*,*>;val items=body["items"] as List<*> + val expected=r["items"] as List<*> + assertEquals(r["name"].toString(),num(expected.first()),num((items.first() as Map<*,*>)["id"])) + assertEquals(r["name"].toString(),num(expected.last()),num((items.last() as Map<*,*>)["id"])) + assertTrue(items.size<=num(window["size"])) + } + } } finally { root.deleteRecursively() } + } + } + // @fixture bookorbit/catalog-sections.collections.json + // @fixture bookorbit/catalog-sections.smart-scopes.json + @Test fun recordedNativeSectionsRemainReadableFromTheCompanionStore() { + for(kind in listOf("collections","smart-scopes")) { + val body=fixture("bookorbit/catalog-sections.$kind.json") + val items=body["items"] as List<*> + val root=Files.createTempDirectory("retired-sections").toFile() + try { CacheStore(root,{}, {JdbcSql(it)}).use { store -> + store.own("fixture") + val path="/koreader/plugin/catalog/sections/$kind" + store.save("fixture:$kind",path,body+mapOf("total" to items.size.toLong()),1,null) + val result=store.read("fixture:$kind",path,null)!!.body as Map<*,*> + assertEquals(items.size,(result["items"] as List<*>).size) + assertEquals((items.first() as Map<*,*>)["title"],((result["items"] as List<*>).first() as Map<*,*>)["title"]) + } } finally { root.deleteRecursively() } + } + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/RetirementPlanTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/RetirementPlanTest.kt new file mode 100644 index 00000000..645d0cfb --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/RetirementPlanTest.kt @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MIT +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import org.junit.Assert.* +import org.junit.Test + +class RetirementPlanTest { + @Test fun bootstrapIsOneSmallStaticRowWithoutCredentialsOrCatalogData() { + val plan=ConnectorPlugin.retirementPlan() + assertEquals(1,plan["row_count"]) + assertTrue(LuaValue.encode(plan).size<=16384) + assertEquals(setOf("plugins","modules","settings_key","home_key","row_count","actions","preference_overlay"),plan.keys) + assertEquals(listOf("bookorbit"),plan["plugins"]) + assertEquals(listOf("bookorbit_api"),plan["modules"]) + assertEquals(2,(plan["actions"] as List<*>).size) + } +} diff --git a/android/docs/INTERFACE.md b/android/docs/INTERFACE.md index 4880a4fb..cc51843e 100644 --- a/android/docs/INTERFACE.md +++ b/android/docs/INTERFACE.md @@ -591,3 +591,13 @@ contains decisions, compare-before-write operations, backup/Undo state, labels a 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. + +### Local startup retirement (0.12, F12-Q2 step 5) + +`LIBRARY_BOOTSTRAP` is a trusted, local provider read before plugin instances start. It accepts +`patch_version` and refuses a different companion version. Its one static row is at most 16 KiB; +no network, file scans or subprocesses run. The adapter supplies opaque legacy class/module, +setting and gesture identifiers. Lua only disables old methods and preserves native scalar +settings. A late, absent or malformed descriptor cannot authorize the owned sync writer. +Home/account/catalog UI uses the owned Library surfaces. `SLEEP_REFRESH` carries neutral +settings only; the companion adapter resolves its login and preserves explicit login removal. diff --git a/android/koreader/orbit.koplugin/ko/base.lua b/android/koreader/orbit.koplugin/ko/base.lua index 53ec3e8b..f060c452 100644 --- a/android/koreader/orbit.koplugin/ko/base.lua +++ b/android/koreader/orbit.koplugin/ko/base.lua @@ -51,3 +51,8 @@ function wrap(Cls,name,make,feature) if stock[key] then return end stock[key]=Cls[name];Cls[name]=make(stock[key]) end + +function liveUI() + return require("apps/reader/readerui").instance or require("apps/filemanager/filemanager").instance +end +function inBook() local ui=liveUI();return ui~=nil and ui.document~=nil end diff --git a/android/koreader/orbit.koplugin/ko/companion.lua b/android/koreader/orbit.koplugin/ko/companion.lua index 0e06f532..caeab898 100644 --- a/android/koreader/orbit.koplugin/ko/companion.lua +++ b/android/koreader/orbit.koplugin/ko/companion.lua @@ -217,7 +217,6 @@ end -- nothing heavy runs in KOReader either (no mirror, no background checks). -- The plugin and the companion ship together (docs/design/companion-worker.md "Required -- companion"): nil when the companion of this plugin's own version is there, else what to do. --- purpose: what it is needed for (default "to save BookOrbit for offline"). function Companion.workerProblem(purpose) purpose = purpose or _("to save library for offline") local st = Companion.state() @@ -250,7 +249,6 @@ request_seq = 0 -- One command, through the companion's caller-checked call (android/docs/INTERFACE.md). Only -- to the companion signed by BookSync's release key (Companion.state), so a look-alike app never --- gets a command or the BookOrbit login some carry. function Companion.send(action, extras) extras = extras or {} local short = action:match("[^.]+$") @@ -330,3 +328,5 @@ function Companion.status() end --------------------------------------------------------------------------------------------- + +Companion.LIBRARY_BOOTSTRAP=Companion.PACKAGE..".call.LIBRARY_BOOTSTRAP" diff --git a/android/koreader/orbit.koplugin/ko/companion_ui.lua b/android/koreader/orbit.koplugin/ko/companion_ui.lua index 43e2720b..6566cffa 100644 --- a/android/koreader/orbit.koplugin/ko/companion_ui.lua +++ b/android/koreader/orbit.koplugin/ko/companion_ui.lua @@ -21,10 +21,8 @@ function OrbitAndroid:onOrbitOpenCompanion() return true end --- Home from BookOrbit home: the companion's launcher page (as on a double Home). A companion -- older than 0.2.1 has no SHOW_LAUNCHER; its apps page stands in. function OrbitAndroid:openCompanionHome() - -- Without the companion as Home (Add-on, plugin only): BookOrbit home is the top; Android's -- Home key goes to the reader's own launcher (docs/design/addon-mode.md §6.4). if not Companion.has("home") then log("home: the companion isn't Home here; staying on library home") diff --git a/android/koreader/orbit.koplugin/ko/db.lua b/android/koreader/orbit.koplugin/ko/db.lua index 1fda316b..33a3c99b 100644 --- a/android/koreader/orbit.koplugin/ko/db.lua +++ b/android/koreader/orbit.koplugin/ko/db.lua @@ -9,7 +9,6 @@ -- timeout) and never sees half of one. -- -- A connection belongs to the process that opened it: SQLite connections must not cross fork(), --- and the BookOrbit plugin reads its catalog in forked children. A child opens its own and leaves -- the inherited one alone. A file replaced under us (the companion recreated it, or the swap -- fallback renamed a new one in) has another inode: the next read reopens. --------------------------------------------------------------------------------------------- diff --git a/android/koreader/orbit.koplugin/ko/finish.lua b/android/koreader/orbit.koplugin/ko/finish.lua index 6db21b3b..c52805f3 100644 --- a/android/koreader/orbit.koplugin/ko/finish.lua +++ b/android/koreader/orbit.koplugin/ko/finish.lua @@ -33,12 +33,6 @@ function FinishUI.leaveForHome(ui) 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 diff --git a/android/koreader/orbit.koplugin/ko/home.lua b/android/koreader/orbit.koplugin/ko/home.lua index 7e699c79..847f8d42 100644 --- a/android/koreader/orbit.koplugin/ko/home.lua +++ b/android/koreader/orbit.koplugin/ko/home.lua @@ -29,7 +29,6 @@ function OrbitAndroid:checkCommand(source) self:reopenAfterRestart(source) return true end - -- The companion's Setup rows (docs/design/addon-mode.md §4.2): BookOrbit's sign-in, and the -- recommended settings' review page. if cmd == "signin" then UIManager:scheduleIn(0.5, function() self:openSignIn(source) end) @@ -42,7 +41,7 @@ function OrbitAndroid:checkCommand(source) -- The companion's Settings buttons (docs/design/companion-settings.md §3.2, A2, A4, A5): the work -- happens here in KOReader, which the command brought to the front. if cmd == "full_refresh" then - UIManager:scheduleIn(0.5, function() Server.refreshLibrary() end) + UIManager:scheduleIn(0.5, function() Library.fullRefresh() end) return true end if cmd == "sync_sleep" then @@ -57,21 +56,8 @@ function OrbitAndroid:checkCommand(source) return false end --- BookOrbit's own sign-in page (promptLogin opens it, main.lua:967-974). function OrbitAndroid:openSignIn(source) - local p = serverPlugin(self.ui) - if not p then - UIManager:show(InfoMessage:new{ text = _("The library plugin isn't loaded."), timeout = 3 }) -- gate: user action (Setup's sign-in) - return - end - if Server.signedIn(p) then - log("sign in (" .. tostring(source) .. "): already signed in") - UIManager:show(InfoMessage:new{ text = _("Signed in to library."), timeout = 2 }) -- gate: user action (Setup's sign-in) - pcall(Server.reportRecommended, "signin", true, self.ui) - return - end - local okc, err = pcall(function() Server.openLogin(p) end) - log("sign in (" .. tostring(source) .. "): library's sign-in", okc and "opened" or ("FAILED: " .. tostring(err))) + return AccountView.open("account") end -- COMMAND=restart (android/docs/INTERFACE.md): the companion installed a newer patch file; a restart @@ -93,8 +79,7 @@ function OrbitAndroid:restartForCompanion(source, quit_only) -- The quit closes the reader (which clears open_book_at_exit): remember the book apart, so -- the next start reopens it where it was (v0.5.5). S.restart_book = ui and ui.document and ui.document.file or nil - -- The screen the reader was on comes back too: BookOrbit Home over the book. - S.restart_screen = catalogOnTop(serverPlugin(ui)) and HomePlan.SERVER_HOME or nil + S.restart_screen = HomeHost.foreground() and HomePlan.SERVER_HOME or nil saveSettings() pcall(function() G_reader_settings:flush() end) Stats.send("restart", nil, false) @@ -169,9 +154,7 @@ function OrbitAndroid:maybeRestart(event) return act end --- The plugin's BookOrbit home is the top widget: its catalog widget (main.lua:1207-1230) is -- topmost (the plugin's own test, main.lua:1384) and shows its dashboard context --- (BookOrbitCatalog:dashboardMode, bookorbit_catalog.lua:1875-1877). Its other views -- (book details, lists, sheets over it) don't count. -- The topmost screen: notes (KOReader's toasts, Orbit's own notes) float over it and never count. function topWidget() @@ -190,7 +173,6 @@ end -- Nothing interrupts reading (docs/design/reading-gate.md): while a book is open in front, -- nothing from BookSync shows, restarts or takes focus. reading() is the one gate; every note and -- message goes through Gate.show, which holds it until the next moment nobody is reading --- (BookOrbit Home or a list over the book, the book closed, KOReader back after another app) -- and drops it when it has gone stale. Exceptions are only what the reader does in the book: -- menus they open, the end-of-book sheet. function reading() @@ -200,16 +182,16 @@ function reading() local ui = liveUI() if not (ui and ui.document) then return false end if Wifi and Wifi.state and Wifi.state().foreground == false then return false end - if serverOverBook(serverPlugin(ui)) then return false end + if ui.menu and ui.menu.menu_container then return false end -- a menu the reader opened - if Server.endSheetOpen() then return false end -- the reader reached the end + if (FinishUI and FinishUI.sheet~=nil) then return false end -- the reader reached the end return true end Gate = { queue = {}, MAX_AGE_S = 600 } function Gate.refreshNotice(what) - local full = Server.fullRefreshNotice() + local full = Library.catalog_active log((full and "Full refresh" or "background") .. ": suppressed notice: " .. tostring(what)) if full and Badge and Badge.notice then Badge.notice(what) end end @@ -232,7 +214,7 @@ function Gate.show(what, fn, max_age_s) end function Gate.drain(why) - if Gate.inBackground() and not (Server.fullRefreshNotice()) then return end + if Gate.inBackground() and not (Library.catalog_active) then return end if Gate.silent() then for _, q in ipairs(Gate.queue) do Gate.refreshNotice(q.what) end Gate.queue = {} @@ -251,12 +233,11 @@ function Gate.drain(why) end end --- BookOrbit's own toasts (sync results and the like) wait too: bookorbit_toast.show/error. function Gate.installToast() -- The final boundary also catches direct KOReader and Trapper messages. -- Dialogs (including position-sync choices) are unaffected. wrap(UIManager, "show", function(stock) return function(self, w, ...) - local notice = w and (Server.notice(w) or w.is_infomessage or w.orbit_note) + local notice = w and (false or w.is_infomessage or w.orbit_note) local m = w and getmetatable(w) while m and not notice do notice = m == InfoMessage or m == package.loaded["ui/widget/notification"] @@ -285,27 +266,8 @@ function Gate.installToast() end end, "refresh_notices") Gate.installCatalog() Gate.installTrapper() - Gate.installPlugin(serverPlugin(liveUI())) - local okt, Toast = pcall(Server.require, "toast") - if not okt or type(Toast) ~= "table" then return end - for _, name in ipairs({ "show", "error", "loading" }) do - if type(Toast[name]) == "function" then - wrap(Toast, name, function(stock) return function(...) - local args = { n = select("#", ...), ... } - if Gate.silent() then - Gate.refreshNotice("library " .. name .. ": " .. tostring(args[1])) - -- Loading callers close the returned handle, including withLoading. - if name == "loading" then return { close = function() end, closed = false } end - return - end - if name == "loading" then - log("notice: shown: library loading: " .. tostring(args[1])) - return stock(unpack(args, 1, args.n)) - end - return Gate.show("library " .. name .. ": " .. tostring(args[1]), function() return stock(unpack(args, 1, args.n)) end, 120) - end end, "gate") - end - end + + end -- A short note that never sits in the way: KOReader's Notification is a toast (it lets every @@ -328,60 +290,9 @@ function orbitNote(text, timeout, refresh_popup) return Gate.show("note: " .. tostring(text), show) end --- BookOrbit is in front of the open book: its catalog (Home or any list), or one of its own --- views, menus or dialogs (widgets named bookorbit_*, e.g. bookorbit_book_sheet, --- bookorbit_menu_sheet, bookorbit_confirm), anywhere above the ReaderUI in the window stack. --- Not just the topmost widget: BookOrbit's loading and error pills (bookorbit_toast, not marked -- as toasts) and KOReader's widgets float over Home while the reader browses it (v0.11.1 on the -- M8C held Full refresh's progress "while reading" with Home on screen). The pills alone, over -- the book, don't count. Shared by reading() and the Wi-Fi plan's "browsing". -function serverOverBook(p) - local cb = p and p.catalog_browser - local okr, RUI = pcall(require, "apps/reader/readerui") - local reader = okr and type(RUI) == "table" and RUI.instance or nil - for _, w in ipairs(visibleStack()) do - if reader ~= nil and w == reader then return false end - if cb ~= nil and w == cb then return true end - local name = type(w) == "table" and rawget(w, "name") or nil - if name == nil and type(w) == "table" then - local okn, n = pcall(function() return w.name end) - name = okn and n or nil - end - if Server.ownsView(name) and not Server.notice(w) then return true end - end - return false -end - --- What is really showing, by identity with the plugin's catalog widget (never its flag alone: --- plugin.catalog_browser stays set while the file browser or a book covers it). -function catalogOnTop(p) - local cb = p and p.catalog_browser - return cb ~= nil and topWidget() == cb -end - --- The topmost widget, named for the log: KOReader's own screens by identity, else its name, --- title or (for a class instance) its class's name. -function widgetName(w, p) - if w == nil then return "nothing" end - if p and w == p.catalog_browser then return "library catalog" end - local okr, RUI = pcall(require, "apps/reader/readerui") - if okr and type(RUI) == "table" and w == RUI.instance then return "ReaderUI (book)" end - local okf, FM = pcall(require, "apps/filemanager/filemanager") - if okf and type(FM) == "table" and w == FM.instance then return "FileManager (file browser)" end - local okn, n = pcall(function() - local v = w.name or w.title - if v == nil then - local mt = getmetatable(w) - local cls = mt and (rawget(mt, "__index") or mt) - v = type(cls) == "table" and (rawget(cls, "name") or rawget(cls, "title")) or nil - end - return v - end) - if okn and n ~= nil and (type(n) == "string" or type(n) == "number") then return tostring(n) end - return "unnamed widget" -end - --- Visible widgets, topmost first (uimanager.lua:858-866 skips invisible ones the same way). function visibleStack() local out = {} local okw, stack = pcall(function() return UIManager._window_stack end) @@ -397,92 +308,10 @@ function visibleStack() return out end --- Which BookOrbit screen is showing (plugin 2.3.0), from the real window stack: -- "main": the catalog (main.lua:1207-1229) is the topmost widget, in dashboard mode --- (bookorbit_catalog.lua:1875-1877: current_context.kind == "dashboard"). --- "sub": BookOrbit, but not its main page: the catalog in another mode (books, detail, lists, --- search, board, ... switched in place, bookorbit_catalog.lua:1350 showBookPage, :1288 -- showRecentSearches; detail_sheet/list_sheet live in that context, :2451-2462), or --- widgets over the catalog: its dialogs (bookorbit_catalog.lua:1439, :1534, :1559, :1598, --- :1792), the book sheet (bookorbit_book_sheet.lua:385, :410), settings --- (bookorbit_settings_page.lua:952), menu pages and dialogs (bookorbit_dialog_ui.lua:91), --- the main menu sheet (bookorbit_main_menu.lua:380 openMenuSheet). -- nil: no catalog showing (none, or KOReader's file browser or a book over it). -- Returns kind, the widgets over the catalog (topmost first), and a description for the log. -function serverScreen(p) - local cb = p and p.catalog_browser - if cb == nil then return nil, {}, "no library view" end - -- Without dashboardMode the main page can't be told apart: the pre-0.4.9 behaviour. - if not Compat.callable(cb.dashboardMode) then return nil, {}, "library catalog without dashboardMode" end - local above, found = {}, false - local okr, RUI = pcall(require, "apps/reader/readerui") - local okf, FM = pcall(require, "apps/filemanager/filemanager") - for _, w in ipairs(visibleStack()) do - if w == cb then found = true break end - if (okr and type(RUI) == "table" and w == RUI.instance) or (okf and type(FM) == "table" and w == FM.instance) then - return nil, {}, "library covered by " .. widgetName(w, p) - end - table.insert(above, w) - end - if not found then return nil, {}, "library view not in the window stack" end - local okk, kind = pcall(function() return cb.current_context and cb.current_context.kind end) - kind = okk and kind or nil - local dash = Compat.callable(cb.dashboardMode) and select(2, pcall(function() return cb:dashboardMode() end)) == true - if #above == 0 and dash then return "main", above, "library main page" end - local names = {} - for _, w in ipairs(above) do table.insert(names, widgetName(w, p)) end - local desc = "library " .. tostring(kind or "?") .. " view" - if #names > 0 then desc = desc .. " under " .. table.concat(names, ", ") end - return "sub", above, desc -end - --- The catalog's page past the first, with nothing over it: page, how to go to page 1, what. --- nil on page 1, with something over the catalog, or a plugin without the paging hooks. -function catalogPage(cb) - if cb == nil then return nil end - local missing = Compat.missingOn(cb, Compat.PAGING) - if #missing > 0 then - if not compat_logged.paging then - compat_logged.paging = true - log("compat: paging unavailable: missing " .. table.concat(missing, ", ") .. " -> Home leaves any page") - end - return nil - end - local okp, page, go, what = pcall(function() - if cb:dashboardMode() then - local n = tonumber(cb:boardPage()) - return n, function() cb:boardFlip(1 - n) end, "dashboard" - end - if cb:listMode() then - local pg = cb:listPaging() - return tonumber(type(pg) == "table" and pg.page), function() cb:listGoPage(1) end, "list" - end - end) - if not okp then log("home: paging check failed:", tostring(page)); return nil end - if page and page > 1 then return page, go, what end - return nil -end - -function onDashboard(p) - local cb = p and p.catalog_browser - if cb == nil then return false end - if topWidget() ~= cb then return false end - if not Compat.callable(cb.dashboardMode) then - if not compat_logged.catalog then - compat_logged.catalog = true - log("compat: catalog unavailable (plugin " .. pluginVersion(p) .. "): missing dashboardMode -> Home on library home goes back to the book") - end - return false - end - if not Compat.callable(cb.dashboardMode) then return false end - local okd, dash = pcall(function() return cb:dashboardMode() end) - return okd and dash == true -end - --- Home keeps the rotation the device is held in (HomePlan.rotation): KOReader's own file browser --- may have turned it (its start, a book close). Through the file browser's own handler --- (FileManager:onSetRotationMode, filemanager.lua:71-79, as KOReader's rotation menu does by --- event, screen_rotation_menu_table.lua:18), which also lays it out again. function keepHeldRotation(action, held, in_reader, source) if held == nil then return end -- KOReader's start already kept the held rotation (patches/1-orbit-start-rotation.lua). @@ -509,8 +338,6 @@ function keepHeldRotation(action, held, in_reader, source) end -- A book closing opens a new file browser, which turns the device to the file browser's rotation --- (filemanager.lua:63-69 via :1321; readerui.lua:594), and BookOrbit Home then shows in it. Keep --- the book's rotation instead: the file browser here is only ever under BookOrbit Home. KOReader's -- start sets it before plugins load (reader.lua:291); the companion's ROTATION corrects that one. function keepRotationOnFileBrowser(why) local okf, FM = pcall(require, "apps/filemanager/filemanager") @@ -561,150 +388,27 @@ end -- Home (android/docs/INTERFACE.md "go home"): HomePlan decides. mode: "smart" (home_smart) or -- HomePlan.SERVER_HOME (home). -function OrbitAndroid:smartHome(source, from_extra, mode, held) - if S.home_screen == "booksync" then - if (mode == nil or mode == "smart") and HomeHost.active and topWidget() == HomeHost.active and liveUI() and liveUI().document then - return HomeHost.active:onClose() - end +function OrbitAndroid:smartHome(source,from_extra,mode,held) + local host=HomeHost.active + local ui=liveUI() + -- Preserve the owned Home's established toggle and Back behavior. + if S.home_screen=="booksync" then + if (mode==nil or mode=="smart") and host and topWidget()==host and ui and ui.document then return host:onClose() end return HomeHost.show() end - mode = mode or "smart" - -- Orbit's own sheets close first: they are not BookOrbit, and they'd cover whatever Home opens. - if Server.leaveEndSheet(liveUI()) then log("home: closed the end-of-book sheet") end - local ui = liveUI() - local in_reader = ui ~= nil and ui.document ~= nil - local p = serverPlugin(ui) - local menu_open = in_reader and ui.menu ~= nil and ui.menu.menu_container ~= nil - local view_open = p ~= nil and p.catalog_browser ~= nil - local screen, over, screen_desc = serverScreen(p) - local on_dash = screen == "main" or (screen == nil and onDashboard(p)) - local page, first_page, page_what - if screen == "main" or (screen == "sub" and #over == 0) then - page, first_page, page_what = catalogPage(p.catalog_browser) - end - -- Reopen only the current book: one Home closed, or one KOReader was killed with (first - -- command of this process). Never history. - local last = nil - if not in_reader then - last = S.home_book or (source == "start" and killed_with_book) or nil - end - local reopen = false - if type(last) == "string" then - local okl, lfs = pcall(require, "libs/libkoreader-lfs") - reopen = okl and lfs.attributes(last, "mode") == "file" - if not reopen and last == S.home_book then S.home_book = nil; saveSettings() end - end - if source == "start" then killed_with_book = nil end - local paused = source == "start" and nil or state.paused_for - local from_other = HomePlan.cameFromOtherApp(from_extra, paused) - local action = HomePlan.decide{ - mode = mode, in_reader = in_reader, covered = menu_open or view_open, on_dashboard = on_dash, - library_sub = screen == "sub", page_above_1 = page ~= nil, - from_other = from_other, reopen = reopen, - } - log("home (" .. mode .. "):", action, "| in reader", tostring(in_reader), "menu", tostring(menu_open), "library view", - tostring(view_open), "dashboard on top", tostring(on_dash), "(top: " .. widgetName(topWidget(), p) .. ")", - "from other app", tostring(from_other), - "(paused", paused and fmt(paused) or "-", ")", "reopen current book", reopen and tostring(last) or "no") - log("home: screen:", screen_desc) - keepHeldRotation(action, held, in_reader, source) - if action == "first_page" then - log("home: library " .. page_what .. " page " .. page .. " -> page 1") - local okg, err = pcall(first_page) - if not okg then log("home: going to page 1 failed:", tostring(err)) end - return true - end - if action == "library_main" then return self:serverMain(p, over, screen_desc) end - if action == "companion" then return self:openCompanionHome() end - if action == "dashboard" then return self:onOrbitGoHome() end - -- Back to the book: close what covers it, or open the last one. - if menu_open then pcall(function() ui.menu:onCloseReaderMenu() end) end - if view_open then - -- The plugin's own close (close_callback, main.lua:1225-1228; used by the catalog itself, - -- bookorbit_catalog_download.lua:359-362) also clears plugin.catalog_browser, without - -- which openCatalogBrowser (main.lua:1207) never opens it again. - local cb = p.catalog_browser - local okc, err = pcall(function() - if cb.close_callback then cb.close_callback() else UIManager:close(cb); p.catalog_browser = nil end - end) - log("home (smart): closed the library view", okc and "" or tostring(err)) - end - if not in_reader then - log("home (smart): reopening the current book", tostring(last)) - UIManager:nextTick(function() - local ReaderUI = require("apps/reader/readerui") - if ReaderUI.instance then log("orbit: closing reader because Smart Home is reopening the current book") end - ReaderUI:showReader(last) - end) - end - return true -end - --- BookOrbit home. With a book open, the plugin's dashboard opens on top of the reader without --- closing it (onBookOrbitOpenDashboard, main.lua:1381-1389 -> browseCatalog, main.lua:1235-1241 --- -> openCatalogBrowser, main.lua:1206-1230: UIManager:show of its catalog widget; its own menu --- does the same from a book, bookorbit_main_menu.lua:307). Fallback (no plugin, signed out): --- close the book (the reader saves it; the plugin syncs it as on any close, main.lua:1292-1312) --- and remember it as the current book (home_book), so Home elsewhere goes back to it. --- The plugin has some BookOrbitOpenDashboard handler. Advisory: anything there counts (a --- KOReader HandlerSandbox or a future wrapper); only a plugin without it is "missing". -function hasHandler(p, event) - if p == nil then return false end - local okv, v = pcall(function() return p["on" .. event] end) - return okv and v ~= nil -end - --- Send a plugin event the way KOReader's dispatcher does (the plugin's public actions, e.g. --- bookorbit_open_dashboard -> BookOrbitOpenDashboard, main.lua:987-988): through the live UI, --- which passes it to its plugin modules. Without a UI that takes it, call the handler. -function pluginEvent(host, p, event, ...) - if not can(p, PLUGIN_EVENT_FEATURE[event] or "core") then - log("compat: the method check doesn't see on" .. event .. "; sending the event anyway") - end - host = host or liveUI() - if host and host.handleEvent then - local okh, err = pcall(host.handleEvent, host, Event:new(event, ...)) - if okh then return true end - log("plugin event", event, "failed:", tostring(err)) - end - local okv, h = pcall(function() return p and p["on" .. event] end) - if okv and Compat.callable(h) then - local okc, err = pcall(h, p, ...) - if not okc then log("plugin handler on" .. event, "failed:", tostring(err)) end - return okc - end - local okb = pcall(UIManager.broadcastEvent, UIManager, Event:new(event, ...)) - return okb -end - --- After opening BookOrbit home: say so if it isn't on top a second later. -function checkDashboardOpened(p, why) - UIManager:scheduleIn(1, function() - local q = serverPlugin(liveUI()) or p - if catalogOnTop(q) then - log("home: library home is on top (" .. why .. ")") - Gate.drain("library Home") - Server.resumeCache("Home") - else - log("home: library home did NOT open (" .. why .. "); top:", widgetName(topWidget(), q)) + -- The older Home choice retains its book -> Home -> companion cycle using owned UI. + if host and HomeHost.foreground() then + if from_extra=="other_app" then + if ui and ui.document then UIManager:close(host);return true end + return HomeHost.show() end - end) -end - --- Close one widget the plugin's way: its close_callback (the catalog, main.lua:1225-1228), --- else UIManager:close, which runs its onCloseWidget / on_close (MenuPage sheets). -function closeWidget(w) - local okc, err = pcall(function() - if Compat.callable(w.close_callback) then w.close_callback() else UIManager:close(w) end - end) - if not okc then log("home: closing", widgetName(w), "failed:", tostring(err)) end + if host.list_layout or host.series_key then return host:onClose() end + return self:openCompanionHome() + end + if from_extra=="other_app" and ui and ui.document and (mode==nil or mode=="smart") then return true end + return HomeHost.show() end --- After a restart that quit with a book open: that book again, at its saved place (the reader --- saved it before the quit; showReader opens at the last position). The book: the one this --- patch remembered (restart_book), else KOReader's last file (a restart by an older patch, --- which the companion follows with COMMAND=reopen_book). BookOrbit home opened by the start --- (the plugin's open mode) is closed so the book is on top. function OrbitAndroid:reopenAfterRestart(source) local file = S.restart_book if file ~= nil then S.restart_book = nil; saveSettings() end @@ -717,8 +421,7 @@ function OrbitAndroid:reopenAfterRestart(source) if ui and ui.document then log("restart: a book is already open; not reopening", file); return end local okl, lfs = pcall(require, "libs/libkoreader-lfs") if not (okl and lfs.attributes(file, "mode") == "file") then log("restart: the book is gone:", file); return end - local p = serverPlugin(ui) - if p and p.catalog_browser then closeWidget(p.catalog_browser) end + if HomeHost.active then UIManager:close(HomeHost.active) end log("restart: reopening the book at its place (" .. source .. "):", file) local screen = S.restart_screen if screen then S.restart_screen = nil; saveSettings() end @@ -735,121 +438,15 @@ function OrbitAndroid:reopenAfterRestart(source) end) end --- Home on a BookOrbit screen that isn't its main page: close what is over the catalog, then --- the catalog's own Home (goDashboard, bookorbit_catalog.lua:530-537; also its hold-Return, -- :2521-2525). If anything is left over it, or the plugin lacks goDashboard: close the catalog --- and open BookOrbit home fresh (the plugin's event), so no half-closed stack is left. -function OrbitAndroid:serverMain(p, over, desc) - log("home: on", desc, "-> library main page") - for _, w in ipairs(over or {}) do - log("home: closing", widgetName(w, p)) - closeWidget(w) - end - local cb = p.catalog_browser - local screen = serverScreen(p) - if cb and screen ~= nil and topWidget() == cb and Compat.callable(cb.goDashboard) then - if screen ~= "main" then - local okg, err = pcall(function() cb:goDashboard() end) - if okg then - log("home: library catalog back to its main page (goDashboard)") - checkDashboardOpened(p, "back to main") - return true - end - log("home: goDashboard failed:", tostring(err)) - else - log("home: library main page showing") - return true - end - end - log("home: reopening library home fresh (top:", widgetName(topWidget(), p) .. ")") - if p.catalog_browser then closeWidget(p.catalog_browser) end - p.catalog_browser = nil - pluginEvent(liveUI(), p, Server.events.home) - checkDashboardOpened(p, "reopened") - return true -end - -function OrbitAndroid:onOrbitGoHome() - if S.home_screen == "booksync" then return HomeHost.show() end - if Server.leaveEndSheet(liveUI()) then log("home: closed the end-of-book sheet") end - local ui = liveUI() - local p = serverPlugin(ui) - -- BookOrbit home already open: bring it up ourselves. The plugin's open action on an open - -- catalog opens its menu sheet instead (main.lua:1381-1385). - if p and p.catalog_browser then - local screen, over, desc = serverScreen(p) - if screen ~= nil then return self:serverMain(p, over, desc) end - log("home: library home is open but not showing (" .. tostring(desc) .. "); reopening it") - closeWidget(p.catalog_browser) - p.catalog_browser = nil - end - if ui and ui.document and hasHandler(p, Server.events.home) and Server.signedIn(p) then - log("home: library home over the open book") - -- The plugin's public action bookorbit_open_dashboard (event BookOrbitOpenDashboard, - -- main.lua:987-988). - UIManager:nextTick(function() - pluginEvent(ui, p, Server.events.home) - checkDashboardOpened(p, "over the book") - end) - UIManager:scheduleIn(1, function() self:maybeSetupPrompt("home") end) - return true - end - state.pending_home = os.time() - if ui and ui.document then - log("home: closing book, then library home (it stays the current book)") - state.closing_for_home = ui.document.file - UIManager:nextTick(function() - log("orbit: closing reader because Home requested the file browser") - ui:onHome() - end) - else - self:finishHome() - end - -- Also when finishHome stays put (BookOrbit home already open, no plugin): once off the book. - UIManager:scheduleIn(2.5, function() self:maybeSetupPrompt("home") end) - return true -end - +function OrbitAndroid:onOrbitGoHome() return HomeHost.show() end function OrbitAndroid:finishHome() - if not state.pending_home then return end - if os.time() - state.pending_home > 15 then state.pending_home = nil return end - state.pending_home = nil - local p = serverPlugin(self.ui) - if not p then - log("home: library plugin missing; staying in the file browser") - return - end - -- With "Make BookOrbit home" the plugin opens itself when the book closes (main.lua:1404-1412). - if p.catalog_browser and catalogOnTop(p) then - log("home: library home already showing") - return - end - if not hasHandler(p, Server.events.home) then - -- Advisory: the live UI may still route the event to a plugin module we can't see. - log("home: this plugin instance shows no library home handler; sending the event anyway") - end - if p.catalog_browser then - -- Open but covered (the file browser on top): the plugin's open action does nothing while - -- catalog_browser is set (main.lua:1381-1385), so close it the plugin's way, then reopen. - log("home: library home is open but not showing (top: " .. widgetName(topWidget(), p) .. "); bringing it to the top") - local cb = p.catalog_browser - local okc, err = pcall(function() - if cb.close_callback then cb.close_callback() else UIManager:close(cb); p.catalog_browser = nil end - end) - if not okc then log("home: closing the covered library view failed:", tostring(err)) end - p.catalog_browser = nil - end - log("home: opening library home") - pluginEvent(liveUI() or self.ui, p, Server.events.home) - checkDashboardOpened(p, "from the file browser") - UIManager:scheduleIn(1, function() self:maybeSetupPrompt("home") end) + if state.pending_home then state.pending_home=nil;return HomeHost.show() end end --- Where the reader is now, for the setup box: a book on screen, BookOrbit home, the file browser. function OrbitAndroid:whereNow() local ui = liveUI() or self.ui - local p = serverPlugin(ui) - if catalogOnTop(p) then return HomePlan.SERVER_HOME end + if HomeHost.foreground() then return HomePlan.SERVER_HOME end if ui and ui.document then return "reader" end return "browser" end @@ -883,21 +480,3 @@ function OrbitAndroid:maybeSetupPrompt(why, where) end --------------------------------------------------------------------------------------------- - --- Catalog fetches use their subprocess path only inside a Trapper context. Home --- actions (including scheduled opens) must enter it before invoking upstream UI. -local function homeJob(fn) - local okt, Trapper = pcall(require, "ui/trapper") - if okt and Trapper.wrap then return Trapper:wrap(fn) end - return fn() -end -local directPluginEvent = pluginEvent -function pluginEvent(...) - local args = pack(...) - return homeJob(function() return directPluginEvent(unpack(args, 1, args.n)) end) -end -local directServerMain = OrbitAndroid.serverMain -function OrbitAndroid:serverMain(...) - local args = pack(...) - return homeJob(function() return directServerMain(self, unpack(args, 1, args.n)) end) -end diff --git a/android/koreader/orbit.koplugin/ko/library.lua b/android/koreader/orbit.koplugin/ko/library.lua index 796a9a87..9e9ad91f 100644 --- a/android/koreader/orbit.koplugin/ko/library.lua +++ b/android/koreader/orbit.koplugin/ko/library.lua @@ -459,7 +459,7 @@ function Library.pollEvents() UIManager:unschedule(Library.pollEvents) UIManager:scheduleIn(.5,Library.pollEvents) if Companion.workerProblem() or reading() then return end - if Library.compatTick then Library.compatTick(Store.now()) end + if Library.compatTick then Library.compatTick(now_s()) end local encoded=Store.readFile(Store.dir().."/events-batch.lua",65537) if not encoded or #encoded>65536 then return end local batch=Cache.decode(encoded) @@ -607,3 +607,97 @@ end function Library.catalogDownload(reference,destination,file_reference,done) return Library.catalogAction("finish.download",{reference=reference,destination=destination,file_reference=file_reference},done) end + +-- Local reader/settings bindings; protocol objects never enter the plugin. +function Library.nativeReader(ui) + 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" then return end + 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,book_id=prepared and prepared.reference, + percentage=LibraryAdapter.readerPosition(ui.document.file),summary=ui.doc_settings:readSetting("summary") or {},doc_settings=ui.doc_settings} +end +local function connectorSettings() + local key=NativeRetirement and NativeRetirement.plan and NativeRetirement.plan.settings_key + return key and G_reader_settings:readSetting(key) +end +local function preferenceSource(settings,key) + local rule=NativeRetirement and NativeRetirement.plan and NativeRetirement.plan.preference_overlay + local record=rule and S[rule.record] + if type(record)=="table" and next(record) and type(rule.guard)=="table" and type(rule.keys)=="table" then + local n=0 + for name,value in pairs(rule.guard) do + n=n+1;if n>8 or settings[name]~=value then return settings,false end + end + for i,name in ipairs(rule.keys) do if i>8 then break end;if name==key then return record,true end end + end + return settings,false +end +function Library.observeSetting(item) + local settings=connectorSettings();local defaults=NativeRetirement and NativeRetirement.defaults + if type(settings)~="table" or type(defaults)~="table" then return {available=false,reason="Connector defaults unavailable"} end + local source=preferenceSource(settings,item.key) + return {available=true,current=source[item.key],default=defaults[item.key]} +end +function Library.writeSetting(item,value) + local settings=connectorSettings();if type(settings)~="table" then return false end + local source,overlay=preferenceSource(settings,item.key) + source[item.key]=value + if overlay then saveSettings() else G_reader_settings:flush() end + return true +end +function Library.sleepRefresh(extras) + Companion.send(Companion.ACTION.SLEEP_REFRESH,extras);Library.watchEvents() +end +function Library.localBookReference(path) + local row=FinishUI and FinishUI.reader_key + return row and row.owner==LibraryAdapter.owner() and row.path==path and row.reference or nil +end +function Library.storageRecount(why) + Companion.send(Companion.ACTION.STORAGE,{reason=tostring(why),limit=tostring((tonumber(S.storage_limit_mb) or 512)*1048576),mirror_covers=S.mirror_covers and "1" or "0"}) + Library.watchEvents() +end +LibraryAdapter.idle=function() + Library.copiesTick("book closed") + if FinishUI and not reading() and not FinishUI.sending then + FinishUI.sending=true;Library.finishCurrent(function() FinishUI.sending=nil end) + end +end +LibraryAdapter.networkRestored=function() return Library.refreshCatalog("resume",false) end +LibraryAdapter.backgroundBusy=function() return Library.catalog_active and "saving the catalog for offline" or nil end +LibraryAdapter.backgroundCommand=function(op,...) + local hooks={ ["views.install"]=function() end,["cache.resume"]=LibraryAdapter.networkRestored, + ["storage.recount"]=Library.storageRecount,["covers.refresh"]=function() return Library.refreshCatalog("covers",false) end, + ["preferences.report"]=function(...) return Recommendations.report(...) end,["preferences.apply"]=function(...) return Recommendations.applyChoices(...) end, + ["capabilities.lost"]=function() return Recommendations.pass("caps lost",nil,true) end,["capabilities.gained"]=function() return Recommendations.pass("capabilities gained") end } + return assert(hooks[op],"Unknown lifecycle operation")(...) +end +Library.connectorReady=function() Library.watchEvents() end +Library.compatTick=Library.compatTick or function(t) if Sleep and Sleep.waited then Sleep.waited(t) end end +Library.catalogFinished=Library.catalogFinished or function() Library.copiesTick("catalog refresh") end +Library.compatEvent=function(ev) + if ev.kind=="sleep_pool" and Sleep then Sleep.landed(ev) + elseif ev.kind=="native_footer_repair" and type(ev.token)=="string" and S.native_footer_repair~=ev.token then + local before=tonumber(ev.before);local after=tonumber(ev.after) + if (before or ev.before=="nil") and (after or ev.after=="nil") then + if G_reader_settings:readSetting("reader_footer_mode")==before then G_reader_settings:saveSetting("reader_footer_mode",after) end + S.native_footer_repair=ev.token;saveSettings() + end + elseif (ev.kind=="copy.identity" or ev.kind=="finish.applied" or ev.kind=="download.saved") and ev.owner==LibraryAdapter.owner() then + if ev.kind=="copy.identity" then + -- The companion already repaired sidecars/statistics and its owned file ledger. + Library.catalogAction("copies.ack",{token=ev.token}) + 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 result.apply and ev.owner==LibraryAdapter.owner() and epoch==(FinishUI.intent[ev.document] or 0) then + FinishUI.jobs[ev.document]=nil + Library.catalogAction("finish.ack",{document=ev.document,token=ev.token}) + end + end) + elseif ev.kind=="download.saved" and ev.deferred then Gate.show("downloaded book",function() + UIManager:show(InfoMessage:new{text="Downloaded: "..tostring(ev.title or "Book"),timeout=3}) -- gate: Gate.show + end) end + end +end diff --git a/android/koreader/orbit.koplugin/ko/library_bootstrap.lua b/android/koreader/orbit.koplugin/ko/library_bootstrap.lua new file mode 100644 index 00000000..21c5816f --- /dev/null +++ b/android/koreader/orbit.koplugin/ko/library_bootstrap.lua @@ -0,0 +1,11 @@ +-- SPDX-License-Identifier: AGPL-3.0-or-later +-- One bounded local call at class-load time. Never used by a paint or background timer. +Library={} +function Library.bootstrap() + local finish=Budgets.span("library.bootstrap",now_s,log) + if Companion.state()~="ok" then finish();return {ok="0",why="unavailable"} end + local result=Jni.call(Companion.AUTHORITY,Companion.LIBRARY_BOOTSTRAP,{patch_version=PATCH_VERSION}) + local bytes=result and type(result.body)=="string" and #result.body or 0 + local within=Budgets.check(Budgets.libraryBootstrap,{rows=bytes>0 and 1 or 0,bytes=bytes,spawns=0,roundTrips=1,network=0,snapshotBytes=bytes}) + finish();return within and result or {ok="0",why="budget"} +end diff --git a/android/koreader/orbit.koplugin/ko/module.lua b/android/koreader/orbit.koplugin/ko/module.lua index 6deef0cc..f1dd9dd2 100644 --- a/android/koreader/orbit.koplugin/ko/module.lua +++ b/android/koreader/orbit.koplugin/ko/module.lua @@ -47,7 +47,6 @@ function OrbitAndroid:init() self:maybeRestart("check") end) UIManager:scheduleIn(1.5, function() self:wakeFlow("start") end) - -- Recommended settings: after the BookOrbit plugin's init (and its next-tick fallback). UIManager:scheduleIn(1.2, function() self:recommendedPass("start") end) UIManager:scheduleIn(Stats.INTERVAL, statsTick) elseif state.pending_home and not in_reader then @@ -56,6 +55,9 @@ function OrbitAndroid:init() end function OrbitAndroid:onDispatcherRegisterActions() + for i,action in ipairs((NativeRetirement.plan or {}).actions or {}) do + if i<=8 then Dispatcher:registerAction(action.id,{category="none",event=action.event,title=_(action.title),general=true}) end + end Dispatcher:registerAction("orbit_sync_and_sleep", { category = "none", event = "OrbitSyncAndSleep", title = _("BookSync: sync and sleep"), general = true }) Dispatcher:registerAction("orbit_go_home", @@ -65,3 +67,6 @@ function OrbitAndroid:onDispatcherRegisterActions() Dispatcher:registerAction("orbit_open_apps", { category = "none", event = "OrbitOpenApps", title = _("BookSync Companion: apps"), general = true, separator = true }) end + +function OrbitAndroid:onLibrarySyncAll() return Library.syncCurrent(function() end) end +function OrbitAndroid:onLibraryThisBook() return ReaderPanel.show(self.ui,"reader-top-panel") end diff --git a/android/koreader/orbit.koplugin/ko/notices.lua b/android/koreader/orbit.koplugin/ko/notices.lua index e2bfac4c..3ce8cd4a 100644 --- a/android/koreader/orbit.koplugin/ko/notices.lua +++ b/android/koreader/orbit.koplugin/ko/notices.lua @@ -7,7 +7,7 @@ function Gate.inBackground() return Gate.backgrounds[coroutine.running() or main] == true end function Gate.silent() - return Gate.inBackground() or (Server.fullRefreshNotice()) + return Gate.inBackground() or Library.catalog_active end function Gate.withBackground(background, fn, ...) local key = coroutine.running() or main @@ -89,14 +89,6 @@ local function quietMethods(t, names) end end quietMethods(OrbitAndroid, { "init", "onResume", "onReaderReady", "onSuspend", "wakeFlow", "showWakeBanner", "bookOpenFlow", "readingSync", "onNetworkConnected" }) -Server.quietLegacy(quietMethods) -function Gate.installCatalog() - local Catalog = Server.loaded("catalog") - if type(Catalog) ~= "table" then return end - for _, name in ipairs({ "scheduleThumbnailDownloads", "downloadThumbnailBatch", "boardRefreshClock" }) do - if type(Catalog[name]) == "function" then - wrap(Catalog, name, function(stock) return Gate.bind(stock) end, "background_notices") - end - end -end + +function Gate.installCatalog() end diff --git a/android/koreader/orbit.koplugin/ko/retirement.lua b/android/koreader/orbit.koplugin/ko/retirement.lua new file mode 100644 index 00000000..d23fc63d --- /dev/null +++ b/android/koreader/orbit.koplugin/ko/retirement.lua @@ -0,0 +1,40 @@ +-- SPDX-License-Identifier: AGPL-3.0-or-later +-- Local migration metadata only. Retire complete legacy classes before instance startup; +-- no original method is invoked, and a late/missing handshake never activates our writer. +NativeRetirement={} +SyncRetirement={safe=false} +local result=Library.bootstrap() +if result and result.ok=="1" and type(result.body)=="string" and #result.body<=16384 then + local plan=Cache.decode(result.body) + if type(plan)=="table" and type(plan.plugins)=="table" and #plan.plugins<=4 and type(plan.modules)=="table" and #plan.modules<=8 then + NativeRetirement.plan=plan + HomePlan.SERVER_HOME=plan.home_key or HomePlan.SERVER_HOME + local function retired() return nil,"companion_owned" end + local function disable(target,keep_constructor) + if type(target)~="table" then return end + for name,value in pairs(target) do + if type(value)=="function" and (not keep_constructor or name~="new") then target[name]=retired end + end + end + local function disarm(plugin) + for _,id in ipairs(plan.plugins) do + if plugin and plugin.name==id then + NativeRetirement.defaults=plugin.default_settings + disable(plugin,true) + end + end + for _,id in ipairs(plan.modules) do disable(package.loaded[id],false) end + end + local late=false + for _,id in ipairs(plan.plugins) do if PluginLoader.loaded_plugins and PluginLoader.loaded_plugins[id] then late=true end end + for _,plugin in ipairs(PluginLoader.enabled_plugins or {}) do disarm(plugin) end + if type(PluginLoader.createPluginInstance)=="function" then + local stock=PluginLoader.createPluginInstance + function PluginLoader:createPluginInstance(plugin,...) + disarm(plugin) + return stock(self,plugin,...) + end + SyncRetirement.safe=not late + end + end +end diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit.lua deleted file mode 100644 index 655288f8..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit.lua +++ /dev/null @@ -1,662 +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"). - --- The BookOrbit plugin ---------------------------------------------------------------------------------------------- - --- The reader or file browser on screen now. Flows outlive the module that started them --- (a book can close mid-flow), so they look the UI up again when they need it. -function liveUI() - local ReaderUI = require("apps/reader/readerui") - if ReaderUI.instance then return ReaderUI.instance end - return require("apps/filemanager/filemanager").instance -end - -compat_seen = setmetatable({}, { __mode = "k" }) -compat_logged = {} -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) - local okv, v = pcall(function() return p.PLUGIN_VERSION end) - return (okv and type(v) == "string") and v or "unknown" -end - --- Unavailable features for this plugin instance, logged once per feature. Only a full pass is --- cached (per live instance): a check that finds something missing, e.g. one made before the --- plugin finished init, is made again next time. -function compatOf(p) - if not p then return {} end - local m = compat_seen[p] - if m then return m end - m = Compat.check(p) - if next(m) == nil then compat_seen[p] = m end - for id, missing in pairs(m) do - if not compat_logged[id] then - compat_logged[id] = true - log("compat:", id, "unavailable (plugin " .. pluginVersion(p) .. "): missing", - table.concat(missing, ", "), "->", Compat.fallback(id)) - end - end - return m -end - --- Can the patch use this plugin feature? -function can(p, id) - return p ~= nil and compatOf(p)[id] == nil -end - -function serverPlugin(ui) - ui = liveUI() or ui - local p = ui and ui.bookorbit - if not p then - local ok, inst = pcall(PluginLoader.getPluginInstance, PluginLoader, "bookorbit") - p = ok and inst or nil - end - -- Without isLoggedIn/settings nothing else is safe: behave as without the plugin. - if p and not can(p, "core") then return nil end - if Server and Server.installCovers then Server.installCovers(Server.loaded("api"),Server.loaded("catalog")) end - return p -end - --- Status lines for the menu and Test sync path; {} when the plugin is fully supported. -function compatLines(p) - if not p then return {} end - return Compat.lines(compatOf(p), pluginVersion(p)) -end - -function inBook() - local ui = liveUI() - return ui ~= nil and ui.document ~= nil -end - ---------------------------------------------------------------------------------------------- - --- One compatibility entry point. Only main.lua loads this implementation. -Server = {} -Server.events = { home = "BookOrbitOpenDashboard", sync = "BookOrbitSyncBook", auto = "BookOrbitToggleAutoSync" } -function Server.loaded(name) return package.loaded["bookorbit_" .. name] end -function Server.require(name) return require("bookorbit_" .. name) end -function Server.ownsView(name) return type(name) == "string" and name:find("^bookorbit") ~= nil end -function Server.notice(w) return w and w.name == "bookorbit_toast" end -function Server.credentials(client, extras) - extras.server, extras.user, extras.userkey = client.server_url, client.username, client.userkey - return extras -end - -function Server.signedIn(p) return p ~= nil and p:isLoggedIn() end -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 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 -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 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 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(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({"OC","LF","Mirror"}) do - wrap(getfenv(1)[name],name) - end -end - --- Temporary non-transport compatibility for the finish adapter while its parallel cutover lands. - --- 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. -function Server.installCovers(Api,Catalog) - if type(Api)~="table" then return false end - if not Api._booksync_covers then - Api._booksync_covers=true - for _,name in ipairs({"downloadCatalogThumbnail","downloadCatalogAuthorPhoto"}) do - Api[name]=function(_,_,path) - return Library.cachedCover(path) and true or nil,"companion-owned" - end - end - end - if type(Catalog)~="table" then return false end - if Catalog._booksync_covers then return true end - Catalog._booksync_covers=true - -- The upstream batch entry point no longer forks. Its timer calls this parent-side - -- asynchronous worker instead; a direct legacy call can only inspect local snapshots. - Catalog.downloadThumbnailBatch=function(self,batch) - local result={} - for _,book in ipairs(batch or {}) do - local entry=self:thumbnailEntry(book) - if entry then result[entry.reference:match("([^/]+)%.jpg$")]=entry.exists end - end - return result - end - local entry=Catalog.thumbnailEntry - if type(entry)=="function" then - Catalog.thumbnailEntry=function(self,book) - local row=entry(self,book) - if row then - row.reference=row.reference or row.path - local path=Library.cachedCover(row.reference) - row.path,row.exists=path or row.reference,path~=nil - end - return row - end - end - Catalog.runThumbnailWorker=function(self,generation) - local function valid() return not self.catalog_closed and self.thumbnail_generation==generation end - if not valid() then return self:stopThumbnailWorker(generation) end - local visible=true - local books=CoverQueue.take(self.thumbnail_queue) - if #books==0 then visible=false; books=CoverQueue.take(self.thumbnail_prefetch_queue) end - if #books==0 then self:stopThumbnailWorker(generation); return end - local rows={} - for _,book in ipairs(books) do - local row=self:thumbnailEntry(book) - if row then rows[#rows+1]={reference=row.reference,entry=row,key=row.reference:match("([^/]+)%.jpg$")} end - end - local written=false - CoverQueue.acquire(rows,false,valid,function(row,result) - if result.local_path then - row.entry.path,row.entry.exists=result.local_path,true - written=true - if self.thumbnail_failures then self.thumbnail_failures[row.key]=nil end - elseif self.thumbnail_failures then self.thumbnail_failures[row.key]=true end - end,function(ok) - if not ok then return self:stopThumbnailWorker(generation) end - if visible and written and not reading() and valid() then self:updateItems(nil,true) end - UIManager:scheduleIn(0.05,function() self:runThumbnailWorker(generation) end) - end) - end - -- These old maintenance paths enumerate/delete files. The companion owns storage policy. - for _,name in ipairs({"sweepThumbnailTemp","cleanLegacyThumbnails","maybePruneThumbnailCache","pruneThumbnailCache"}) do - Catalog[name]=function() end - end - return true -end - --- Transitional lifecycle contracts used by the parallel sync/copies cutovers. All catalog --- transport and projection work is companion-owned; these never read upstream replies. -OC={now=os.time} -function OC.dir() return OC._dir or Store.defaultDirectory() end --- Existing test/diagnostic directory providers remain supported. - -function OC.readFile(...) return Store.readFile(...) end -function OC.writeFile(...) return Store.writeFile(...) end -function OC.on() return S.offline_cache~=false end -function OC.owner(value) return tostring(value.username or "").."|"..tostring(value.server_url or ""):lower() end -function OC.client() - local p=serverPlugin(liveUI()) - 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.watchChecks() return Library.watchEvents() end -function OC.drainEvents() return Library.pollEvents() end -function OC.applyEvents(events) return Library.applyEvents(events) end -function OC.busy() return Library.catalog_active and "saving the catalog for offline" or nil end -function OC.refresh() return Library.refreshCatalog("refresh",true) end -function OC.fullRefresh() return Library.fullRefresh() end -function OC.menuFullRefresh() return Library.fullRefresh() end -function OC.storageCount(why) - local now=Store.now() - if why=="over the limit" and OC.storage_last and now-OC.storage_last<60 then return end - if OC.storage_asked and now-OC.storage_asked<60 then OC.storage_again=why;return end - if not Companion.workerProblem() then - OC.storage_asked,OC.storage_last=now,now Companion.send(Companion.ACTION.STORAGE,{reason=tostring(why), - limit=tostring((tonumber(S.storage_limit_mb) or 512)*1048576),mirror_covers=S.mirror_covers and "1" or "0"}) end - OC.watchChecks() -end -function OC.storageCounted(event) - OC.storage=event.totals;OC.storage_asked=nil - local again=OC.storage_again;OC.storage_again=nil - if again and again~="over the limit" then OC.storageCount(again) end -end -function OC.storageTotals() return OC.storage end -function OC.storageText() return string.format("Using %.1f MB",((OC.storage or {}).used or 0)/1048576) end -function OC.install() - local api,cat=Server.loaded("api"),Server.loaded("catalog") - Server.installCovers(api,cat) - OC.installed=Server.installCatalogApi(api,cat) - return OC.installed -end -Mirror={SENTINEL="987654321"} -function Mirror.catalog() - local p=serverPlugin(liveUI()) - return p and p.catalog_browser or Mirror.cat -end -function Mirror.status() return Library.catalog_status or {} end -function Mirror.fullRunning() return Library.catalog_active==true end -function Mirror.running() return Library.catalog_active==true end -function Mirror.savedText() return Companion.workerProblem() or Mirror.status().saved_label or _("Not saved for offline yet") end -function Mirror.coverPass() return Library.refreshCatalog("covers",false) end -function Mirror.tick(why) - if not reading() and NetworkMgr:isConnected() then return Library.refreshCatalog("incremental",false) end -end -function Mirror.kick(why) - if Sleep and Sleep.kick then Sleep.kick(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. --- Only the companion owns conditional image transport and publication. -OC.RECHECK_WAIT_S = 120 -function OC.recheckCovers(cat, jobs) - local generation=cat.thumbnail_generation - local rows={} - for _,job in ipairs(jobs) do rows[#rows+1]={reference=job.path} end - local index=1 - local changed=0 - local function nextBatch() - if cat.catalog_closed or cat.thumbnail_generation~=generation then return end - local batch={} - for _=1,CoverQueue.MAX_BATCH do - if rows[index] then batch[#batch+1]=rows[index]; index=index+1 end - end - if #batch==0 then return OC.rechecked({checked=#jobs,changed=changed>0 and {true} or {}}) end - CoverQueue.acquire(batch,true,function() return not cat.catalog_closed and cat.thumbnail_generation==generation end, - function(_,result) if result.local_path then changed=changed+1 end end,function(ok) if ok then nextBatch() end end) - end - OC.recheck={at=Store.now(),cat=cat,n=#jobs} - nextBatch() -end - -function OC.rechecked(ev) - local r = OC.recheck - OC.recheck = nil - if not r then return end - if ev.err then log("cache: covers not re-asked:", tostring(ev.err)) end - local changed = type(ev.changed) == "table" and ev.changed or {} - log("cache: covers re-asked:", tonumber(ev.checked) or 0, "checked,", #changed, "replaced") - local cat = r.cat - if #changed > 0 and cat and not cat.catalog_closed and not reading() then - if Compat.callable(cat.resetThumbnailMemo) then cat:resetThumbnailMemo() end - if Compat.callable(cat.updateItems) then cat:updateItems(nil, true) end - end -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 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 - Library.compatEvent=function(ev) - if ev.kind=="library" or ev.kind=="library_source" or ev.kind=="account" then Server.catalogChanged(ev) end - if ev.kind == "board_year" and LF then - LF.yearLanded(ev) - elseif ev.kind == "native_footer_repair" then - -- G_reader_settings is already loaded. Correct its matching scalar - -- too, or KOReader's next native flush would undo the disk repair. - -- This does not touch an open ReaderFooter or reflow the document. - if type(ev.token) == "string" and S.native_footer_repair ~= ev.token then - local function scalar(text) - if text == "nil" then return nil, true end - local n = tonumber(text) - return n, n ~= nil and n == n and n ~= math.huge and n ~= -math.huge - end - local before, valid_before = scalar(ev.before) - local after, valid_after = scalar(ev.after) - if valid_before and valid_after then - if G_reader_settings:readSetting("reader_footer_mode") == before then - G_reader_settings:saveSetting("reader_footer_mode", after) - log("status repair: native global footer mode " .. tostring(before) .. "->" .. tostring(after)) - end - S.native_footer_repair = ev.token - saveSettings() - end - end - elseif ev.kind == "storage" then - OC.storageCounted(ev) - elseif ev.kind == "sleep_pool" and Sleep then - Sleep.landed(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() - local p=serverPlugin(liveUI()) - local cat=p and p.catalog_browser - if not cat or cat.catalog_closed or reading() or not catalogOnTop(p) then return end - local context=cat.current_context or {} - local books=context.books or {} - if context.kind=="dashboard" and Compat.callable(cat.dashboardBooks) then books=cat.dashboardBooks(context.dashboard) end - if context.kind=="detail" and Compat.callable(cat.detailThumbnailBooks) then books=cat:detailThumbnailBooks(context.detail) end - local generation=cat.thumbnail_generation - UIManager:nextTick(function() - if cat.catalog_closed or cat.thumbnail_generation~=generation or reading() or not catalogOnTop(p) then return end - local jobs={} - for i=1,math.min(24,#books) do - local book=books[i] - if book.hasCover~=false and Compat.callable(cat.thumbnailPath) then - local path=cat:thumbnailPath(book) - if path then jobs[#jobs+1]={path=path} end - end - end - if #jobs>0 then OC.recheckCovers(cat,jobs) end - end) - end - Library.catalogFinished=function(status) - Server.catalogChanged({owner=LibraryAdapter.owner()}) - 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 --- 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 - if not Library.compatEvent then Server.installCatalogRuntime() end - if not Api._booksync_catalog then - Api._booksync_catalog=true - local function row(book) - local files={} - for _,f in ipairs(book.files or {}) do files[#files+1]={id=f.reference,format=f.format,size=f.bytes, - md5=f.digest,fileHash=f.digest,sizeBytes=f.bytes,contentVersion=f.revision,role=f.role,filename=f.filename, - downloadVariant=f.delivery,requestedVariant=f.requested_delivery,devicePath=f.local_path} end - return {id=book.reference,title=book.title,authors=book.authors,seriesName=(book.series or {})[1], - seriesId=book.series_reference,seriesIndex=book.series_position,readStatus=book.status_raw, - progressPercentage=book.progress,lastReadAt=book.last_read,updatedAt=book.cover_revision, - hasCover=book.cover_available,rating=book.rating,pageCount=book.pages,formats=book.formats, - description=book.description,files=files} - end - Server.catalogRow=row - local function read(view,params,extra) - params=params or {} - local limit=math.max(1,math.min(24,tonumber(params.size) or 24)) - local names={libraryId="library",collectionId="collection",smartScopeId="list",seriesId="series", - series="series_name",author="author",format="format",readStatus="status",ids="ids",q="search",order="direction",filter="section_filter"} - local selection={} - for field,name in pairs(names) do if params[field]~=nil then selection[name]=tostring(params[field]) end end - if params.sort then selection.sort=({recently_added="added",recently_updated="updated",recently_read="last"})[params.sort] or params.sort end - local args={view=view,selection=selection,offset=tonumber(params.offset) or math.max(0,(tonumber(params.page) or 1)-1)*limit,limit=limit} - for k,v in pairs(extra or {}) do args[k]=v end - local paint=Library.paint("library") - local result=paint:read("connector.catalog",args); paint:flush() - if result.pending or result.error then return nil,"cancelled" end - local items={} - for _,item in ipairs(result.items or {}) do items[#items+1]=view=="index" and - {id=item.reference,title=item.title,name=item.title,bookCount=item.count,count=item.count,seriesId=item.series_reference, - readingCount=item.reading,finishedCount=item.finished} or row(item) end - if view=="book" then return items[1],items[1] and nil or "cancelled" end - return {items=items,total=result.total,page=tonumber(params.page) or 1,size=limit,offset=args.offset,hasNext=result.more,hasPrevious=args.offset>0} - end - Api.catalogBooks=function(_,params) return read("books",params) end - Api.catalogRoot=function() - local paint=Library.paint("library") - local snapshot=paint:read("connector.root",{limit=24});paint:flush() - if snapshot.pending or snapshot.error then return nil,"cancelled" end - local sections={} - for _,category in ipairs(snapshot.items or {}) do sections[#sections+1]={section=category.kind=="lists" and "smart-scopes" or category.kind,title=category.title,count=category.count} end - return {sections=sections} - end - Api.catalogBook=function(_,id) return read("book",{size=1},{reference=id}) end - Api.catalogSection=function(_,category,params) - return read("index",params,{category=category=="smart-scopes" and "lists" or category}) - end - -- The owned Home supplies these surfaces. Opening a native Home redirects to its host; - -- no native dashboard/root request is permitted to fall back to upstream transport. - for _,name in ipairs({"catalogDashboard","catalogDiscover","catalogDashboardSection","catalogManifest"}) do - Api[name]=function() return nil,"cancelled" end - 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. - 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,...) - if Server.catalog_paint then return nil,"cancelled" end - return stock(self,...) - end end,"catalog-local") - end - 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 - local result={pcall(function(...) - if LF and LF.primeOnDevice then LF.primeOnDevice(self) end - return stock(self,...) - end,...)} - Library.catalog_opening=before - if not result[1] then error(result[2],0) end - return unpack(result,2) - - end end,"catalog-local") - end - if Compat.callable(Catalog.runConnected) then - wrap(Catalog,"runConnected",function(stock) return function(self,fn) - if NetworkMgr:isConnected() then return stock(self,fn) end - local before=Server.catalog_paint;Server.catalog_paint=true - local result={pcall(fn)} - Server.catalog_paint=before - if not result[1] then error(result[2],0) end - return unpack(result,2) - end end,"catalog-local") - end - if Compat.callable(Catalog.fetch) then - Catalog.fetch=function(_,_,fn) - local previous=Server.catalog_paint; Server.catalog_paint=true - local ok,a,b,c=pcall(fn) - Server.catalog_paint=previous - if not ok then error(a,0) end - return a,b,c - end - end - if Compat.callable(Catalog.dashboardRootFetch) then - Catalog.dashboardRootFetch=function(self) - local sources,names={},{} - if Compat.callable(self.boardSources) then sources,names=self:boardSources() end - local shelves,labels={},{} - for slot,props in pairs(sources) do - if #shelves<6 then - local params=props.params or {} - local select={} - local fields={libraryId="library",collectionId="collection",smartScopeId="list",seriesId="series",series="series_name",author="author"} - for field,target in pairs(fields) do if params[field] then select[target]=tostring(params[field]) end end - local source=props.source or slot - if source=="in-progress" or source=="pick-back-up" then select.status,select.sort="reading","last" - elseif source=="finished" then select.status,select.sort="finished","last" - elseif source=="recently-added" then select.sort="added" - elseif source=="want-to-read" then select.status="want_to_read" - else select.sort="title" end - if source=="pick-back-up" then select.direction="asc" end - shelves[#shelves+1]={slot=slot,selection=select} - end - end - for name in pairs(names) do if #labels<2 then labels[#labels+1]=name=="scopes" and "lists" or name end end - local paint=Library.paint("home") - local snapshot=paint:read("connector.home",{shelves=shelves,names=labels,limit=24});paint:flush() - if snapshot.pending or snapshot.error then return self:dashboardContext(nil,{stale=true,unavailable=true}) end - local body={boardShelves={},boardNames={},continueReading={},finishedThisYear={},discover={}, - displayName=snapshot.greeting,username=snapshot.account_label,totalBooks=snapshot.total,bookCount=snapshot.total} - for slot,items in pairs(snapshot.shelves or {}) do - local books={} - for _,book in ipairs(items) do books[#books+1]=Server.catalogRow(book) end - body.boardShelves[slot]=books - if slot=="in-progress" then body.continueReading=books end - if slot=="finished" then body.finishedThisYear=books end - if slot=="random" then body.discover=books end - end - for category,titles in pairs(snapshot.names or {}) do body.boardNames[category=="lists" and "scopes" or category]=titles end - local goal,streak,activity=snapshot.goal or {},snapshot.streak or {},snapshot.activity or {} - body.readingGoal={year=goal.year,goalBooks=goal.target,completedBooks=goal.completed} - body.readingStreak={currentStreak=streak.current,longestStreak=streak.best} - body.readingYear={startDate=activity.start_date,minutes=activity.minutes} - return self:dashboardContext(body,{stale=not (snapshot.freshness and snapshot.freshness.saved)}) - end - end - - end - return true -end - -Library={connectorReady=function() Server.installCatalogRuntime(); OC.install() end, - bindLifecycle=function() - LibraryAdapter.idle=Server.readerIdle - LibraryAdapter.networkRestored=function() return Library.refreshCatalog("resume",false) end - LibraryAdapter.backgroundBusy=Server.cacheBusy - LibraryAdapter.backgroundCommand=function(op,...) - local hooks={ ["views.install"]=Server.installGrouping,["cache.resume"]=LibraryAdapter.networkRestored, - ["storage.recount"]=Server.countStorage,["covers.refresh"]=function() return Library.refreshCatalog("covers",false) end, - ["preferences.report"]=Server.reportRecommended,["preferences.apply"]=Server.applyRecommended, - ["capabilities.lost"]=Server.capabilitiesLost,["capabilities.gained"]=Server.capabilitiesGained } - return assert(hooks[op],"Unknown lifecycle operation")(...) - end - end} - -function Server.catalogChanged(event) - local p=serverPlugin(liveUI()) - local cat=p and p.catalog_browser - if not cat or cat.catalog_closed or reading() or not catalogOnTop(p) or cat._booksync_redraw then return end - local context=cat.current_context - cat._booksync_redraw=true - UIManager:scheduleIn(.3,function() - cat._booksync_redraw=nil - if cat.catalog_closed or cat.current_context~=context or reading() or not catalogOnTop(p) then return end - if event.owner and event.owner~=LibraryAdapter.owner() then return end - 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/local_view.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/local_view.lua deleted file mode 100644 index 9095b5c7..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/local_view.lua +++ /dev/null @@ -1,747 +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"). - --- Legacy catalog display compatibility, retained for the separate catalog cutover. --- No sync/outbox ownership lives in this module. --- Local-first Home on Android (docs/design/local-first/DESIGN.md "Item 3"; ROADMAP 3). --- BookOrbit Home paints once, from data on the device that already shows what this device --- knows; a refresh then repaints only the header stamp and the tiles that changed. --- * LocalState (settings/orbit_local_state.lua, disposable): per book, this device's percent --- and status, when it changed, and whether the upload still waits. Fed by the plugin's --- close/suspend snapshot (BookOrbit:enqueueLifecycleSnapshot, main.lua:394, hooked in --- endofbook.lua), our own finish marks, the outbox (bookorbit_lifecycle_outbox.lua :225 --- listMetadata, :247 isBlocked) and changed sidecars (bookorbit_sidecar.lua :87 sidecarMtime). --- * Hooks on the catalog class and the board modules (bookorbit_board_data.lua :628 build; --- bookorbit_catalog_dashboard.lua :113 dashboardRootFetch; bookorbit_catalog.lua :847 --- switchTo, :592 refreshOnDevice, :2056 updateItems, :475 refreshCurrent; --- bookorbit_catalog_board.lua :151 boardHeader (its statusCluster upvalue, :149), :882 --- boardRun, :811 boardRefreshTile, :846 boardRefreshClock; bookorbit_catalog_lists.lua :739 --- listRun, :1155 listHeader; bookorbit_list_view.lua :162 header (its region upvalue, :93)). --- If any is missing, nothing installs and the board is stock (one log line). --- The server body upstream saves (settings.catalog_dashboard_cache) is never modified: the --- overlay works on a copy. ---------------------------------------------------------------------------------------------- - -LocalState = { data = nil, gen = 0, failed = false } -LocalState.FILE = "orbit_local_state.lua" -LocalState.VERSION = 1 -LocalState.MAX = 200 - -local function lsStore() - local okd, DataStorage = pcall(require, "datastorage") - local dir = okd and DataStorage:getSettingsDir() or "." - return require("luasettings"):open(dir .. "/" .. LocalState.FILE) -end - -function LocalState.load() - if LocalState.data then return LocalState.data end - local okl, d = pcall(function() return lsStore():readSetting("state") end) - if not okl or type(d) ~= "table" or d.v ~= LocalState.VERSION then - d = { v = LocalState.VERSION, books = {}, fetchedAt = {} } -- missing, corrupt or old: rebuilt - end - d.books, d.fetchedAt = d.books or {}, d.fetchedAt or {} - LocalState.data = d - return d -end - -function LocalState.save() - local d = LocalState.load() - -- At most MAX books: the oldest change goes first. - local list = {} - for k, v in pairs(d.books) do table.insert(list, { k = k, at = v.changedAt or 0 }) end - if #list > LocalState.MAX then - table.sort(list, function(a, b) return a.at > b.at end) - for i = LocalState.MAX + 1, #list do d.books[list[i].k] = nil end - end - pcall(function() - local st = lsStore() - st:saveSetting("state", d) - st:flush() - end) -end - -function LocalState.bump() - LocalState.gen = LocalState.gen + 1 -end - -local function bookIdOf(digest) - local sm = package.loaded["bookorbit_state_manager"] - if type(sm) ~= "table" or type(sm.getBook) ~= "function" then return nil end - local okb, book = pcall(sm.getBook, digest) - return okb and type(book) == "table" and book.bookId or nil -end - -function LocalState.put(digest, fields) - if type(digest) ~= "string" then return end - local d = LocalState.load() - local e = d.books[digest] or {} - for k, v in pairs(fields) do e[k] = v end - e.bookId = e.bookId or bookIdOf(digest) - e.changedAt = fields.changedAt or os.time() - d.books[digest] = e - LocalState.bump() - LocalState.save() -end - --- The plugin's close/suspend snapshot (percentage 0-1, KOReader's summary.status). -function LocalState.noteSnapshot(snap) - local fields = { pending = true } - if type(snap.percentage) == "number" then fields.percent = math.floor(snap.percentage * 1000 + 0.5) / 10 end - if type(snap.status) == "string" then fields.status = snap.status end - LocalState.put(snap.digest, fields) -end - --- A finish mark (or unmark) on this device, before any snapshot. -function LocalState.noteMark(b, status) - LocalState.put(b.digest, { status = status, bookId = b.book_id, pending = true, - percent = status == "complete" and 100 or nil }) -end - -function LocalState.noteSent(digest) - local e = LocalState.load().books[digest] - if e then e.finish_sent = true; LocalState.save() end -end - --- Sidecars of the board's books on this device, only those whose mtime moved (read in another app --- or with auto-sync off). Up to 5 now; the rest in later steps, each followed by a quiet update. -function LocalState.scanSidecars(cat, ids) - local sc = package.loaded["bookorbit_sidecar"] - local sm = package.loaded["bookorbit_state_manager"] - if type(sc) ~= "table" or type(sc.sidecarMtime) ~= "function" or type(sm) ~= "table" then return end - local okm, maps = pcall(sm.onDeviceMaps) - if not okm or type(maps) ~= "table" or type(maps.byBookId) ~= "table" then return end - local todo = {} - local by_id = {} - for digest, e in pairs(LocalState.load().books) do if e.bookId then by_id[e.bookId] = { digest = digest, e = e } end end - for _, id in ipairs(ids) do - local rec = maps.byBookId[id] - local file = type(rec) == "table" and (rec.file or rec.path) or (type(rec) == "string" and rec) or nil - if file then - local okt, mtime = pcall(sc.sidecarMtime, file) - local known = by_id[id] - if okt and mtime and (not known or known.e.sidecarMtime ~= mtime) then - table.insert(todo, { id = id, file = file, mtime = mtime, digest = known and known.digest }) - end - end - end - local function readOne(t) - local okr, err = pcall(function() - local ds = require("docsettings"):open(t.file) - local pct = ds:readSetting("percent_finished") - local summary = ds:readSetting("summary") or {} - local digest = t.digest or ds:readSetting("partial_md5_checksum") - if type(digest) ~= "string" then return end - LocalState.put(digest, { bookId = t.id, sidecarMtime = t.mtime, - percent = type(pct) == "number" and math.floor(pct * 1000 + 0.5) / 10 or nil, - status = summary.status, changedAt = t.mtime }) - end) - if not okr and not LocalState.sidecar_logged then - LocalState.sidecar_logged = true - log("local-first: a sidecar read failed (that book keeps the server's value):", err) - end - end - for i = 1, math.min(5, #todo) do readOne(todo[i]) end - local i = 6 - local function step() - if not todo[i] then return end - readOne(todo[i]); i = i + 1 - if cat then LF.quiet(cat) end - UIManager:scheduleIn(0.2, step) - end - if todo[i] then UIManager:scheduleIn(0.2, step) end -end - --- { byBookId = { [id] = entry } } for the overlay. -function LocalState.view() - local by = {} - for _, e in pairs(LocalState.load().books) do - if e.bookId then - local cur = by[e.bookId] - if not cur or (e.changedAt or 0) > (cur.changedAt or 0) then by[e.bookId] = e end - end - end - return { byBookId = by } -end - ----------------------------------------------------------------- hooks - -LF = { installed = false, memo = setmetatable({}, { __mode = "k" }) } -LF.BOARD_DATA = { build = "function" } -LF.CATALOG = { switchTo = "function", refreshOnDevice = "function", updateItems = "function", - refreshCurrent = "function", dashboardRootFetch = "function", boardHeader = "function", - boardRun = "function", boardRefreshTile = "function", boardRefreshClock = "function", - listRun = "function", listHeader = "function" } -LF.LIST_VIEW = { header = "function" } -LF.BOARD_UI = { statusCluster = "function", hit = "function", icon = "function", hstack = "function" } - -local function upvalue(fn, name) - for i = 1, 200 do - local n, v = debug.getupvalue(fn, i) - if n == nil then return nil end - if n == name then return v, i end - end -end - --- The overlaid body for a dashboard context, memoised on (body, local-state generation), so --- the minute clock's rebuilds get the same table back. -function LF.overlaid(body) - if type(body) ~= "table" then return body end - local m = LF.memo[body] - if m and m.gen == LocalState.gen then return m.out end - local out = LocalFirst.overlay(body, LocalState.view()) - LF.memo[body] = { gen = LocalState.gen, out = out } - return out -end - -function LF.stampText(view, online) - local d = LocalState.load() - return LocalFirst.stamp({ online = online, fetched_at = d.fetchedAt[view], now = os.time(), - failed = LF.failed and LF.failed[view] }) -end - --- Quiet update of the open board after local state changed (sidecar steps, a sync). -function LF.quiet(cat) - if not (cat and cat._board_ctx and cat._board_tiles and cat.current_context - and cat.current_context.kind == "dashboard") or cat.catalog_closed then return 0 end - local BoardData = package.loaded["bookorbit_board_data"] - local old_d = cat._board_ctx.d - local new_d = BoardData.build(cat, cat.current_context, os.time()) - local tiles = LF.tilesOf(cat) - local changed = LocalFirst.changedTiles(tiles, tiles, old_d, new_d) or {} - LF.logChanged(tiles, changed, old_d, new_d) - cat._board_ctx.d = new_d - LF.paintTiles(cat, changed) - return #changed -end - --- Each tile gets its own turn; abandon stale repaints when the view changes. -function LF.paintTiles(cat, changed) - cat._orbit_paint_pending = cat._orbit_paint_pending or {} - for _i, index in ipairs(changed) do cat._orbit_paint_pending[index] = cat.current_context end - if cat._orbit_painting then return end - cat._orbit_painting = true - local function paint() - local index, context = next(cat._orbit_paint_pending) - if not index then cat._orbit_painting = nil; return end - cat._orbit_paint_pending[index] = nil - if not reading() and not cat.catalog_closed and cat.current_context == context then - local tile = cat._board_tiles and cat._board_tiles[index] - if tile then pcall(cat.boardRefreshTile, cat, tile) end - end - UIManager:scheduleIn(0.01, paint) - end - UIManager:scheduleIn(0.01, paint) -end - --- One small answer replaces a 364-day date/SQLite pass on every board rebuild. -LF.year = { values = {}, start = 0, today = 0 } -function LF.yearMinutes(now, year) - if LF.year.today == 0 then - -- A correctly dated empty calendar while the first worker snapshot is in flight. - local day = os.date("*t", now); day.hour, day.min, day.sec = 0, 0, 0 - local today = os.time(day) - local dow = tonumber(os.date("%w", now)) - local values = {}; for i=1,364-(6-dow) do values[i]=0 end - LF.year = { values = values, start = today + (6-dow-363)*86400 + 43200, today = today } - end - local key = tostring(year) .. ":" .. os.date("%Y-%m-%d", now) .. ":" .. tostring(math.floor(now / 120)) - if LF.year_key ~= key and not Companion.workerProblem() then - LF.year_key = key - Companion.send(Companion.ACTION.PATCH, { reason = "Home calendar", board_year = ServerCache.encode(year or {}), - board_key = key, board_now = tostring(now) }) - LF.year_waiting = os.time() - OC.watchChecks() - end - return LF.year.values, LF.year.start, LF.year.today -end -function LF.yearLanded(ev) - if ev.key ~= LF.year_key or type(ev.data) ~= "table" then return end - LF.year_waiting = nil - LF.year = ev.data - local cat = Mirror.catalog() - if cat then - if not reading() then LF.quiet(cat) end - end -end - --- One line per changed tile: which one and what in it changed (why a quiet repaint happened). -function LF.logChanged(tiles, changed, old_d, new_d) - for _, i in ipairs(changed or {}) do - local t = tiles[i] or {} - local okd, what = pcall(LocalFirst.tileDiff, t.kind, old_d, new_d, t.source) - log("local-first: tile", tostring(i), tostring(t.kind) .. (t.source and ("/" .. tostring(t.source)) or ""), - "changed:", okd and tostring(what) or ("? " .. tostring(what))) - end -end - --- The on-device marks for Home's first paint. The catalog is built with none --- (bookorbit_catalog.lua:322 on_device = {}) and paints Home (initialDashboardContext, :332) --- before it reads them (:353 hydrateOnDeviceMaps, next tick): every book on the reader drew --- "Download", then "Resume" once the refresh landed (v0.11.1 on the M8C, every Home open). The --- plugin's maps when it has them (BookOrbitStateManager.onDeviceMaps, what refreshOnDevice --- :592-611 adopts), else the ones kept from the last start. -function LF.primeOnDevice(cat) - if type(cat) ~= "table" then return 0 end - if type(cat.on_device) == "table" and next(cat.on_device) ~= nil then return 0 end - local sm = package.loaded["bookorbit_state_manager"] - if type(sm) == "table" and Compat.callable(sm.hasOnDeviceMaps) and Compat.callable(sm.onDeviceMaps) then - local okh, has = pcall(sm.hasOnDeviceMaps) - local okm, maps = false, nil - if okh and has then okm, maps = pcall(sm.onDeviceMaps) end - if okm and type(maps) == "table" and type(maps.byBookId) == "table" then - cat.on_device, cat.on_device_files = maps.byBookId, maps.byFileId or cat.on_device_files - cat.on_device_generation = maps.generation - local n = 0 - for _ in pairs(maps.byBookId) do n = n + 1 end - log("local-first: first paint with BookOrbit's on-device marks for", n, "book(s)") - return n - end - end - return LF.seedOnDevice(cat) -end - -function LF.tilesOf(cat) - local out = {} - for i, e in ipairs(cat._board_tiles or {}) do - local item = e.item or {} - table.insert(out, { key = i, kind = item.type, source = item.source or (item.props and item.props.source) }) - end - return out -end - -local function boardBookIds(body) - local ids, seen = {}, {} - local function add(list) - for _, b in ipairs(type(list) == "table" and list or {}) do - if type(b) == "table" and b.id and not seen[b.id] then seen[b.id] = true; table.insert(ids, b.id) end - end - end - if type(body) == "table" then - add(body.continueReading); add(body.finishedThisYear) - for _, l in pairs(type(body.boardShelves) == "table" and body.boardShelves or {}) do add(l) end - end - return ids -end - -function LF.install(why) - if LF.installed then return true end - local Catalog = package.loaded["bookorbit_catalog"] - local BoardData = package.loaded["bookorbit_board_data"] - local ListView = package.loaded["bookorbit_list_view"] - local BoardUI = package.loaded["bookorbit_board_ui"] - if type(Catalog) ~= "table" or type(BoardData) ~= "table" or type(ListView) ~= "table" or type(BoardUI) ~= "table" then - return false - end - local missing = {} - for _, m in ipairs(Compat.missingOn(Catalog, LF.CATALOG)) do table.insert(missing, m) end - for _, m in ipairs(Compat.missingOn(BoardData, LF.BOARD_DATA)) do table.insert(missing, "BoardData." .. m) end - for _, m in ipairs(Compat.missingOn(ListView, LF.LIST_VIEW)) do table.insert(missing, "ListView." .. m) end - for _, m in ipairs(Compat.missingOn(BoardUI, LF.BOARD_UI)) do table.insert(missing, "BoardUI." .. m) end - local board_status = type(Catalog.boardHeader) == "function" and select(2, upvalue(Catalog.boardHeader, "statusCluster")) - local list_region = type(ListView.header) == "function" and upvalue(ListView.header, "region") - if not board_status then table.insert(missing, "boardHeader.statusCluster") end - if type(list_region) ~= "function" then table.insert(missing, "ListView.header.region") end - if #missing > 0 then - if not compat_logged.local_first then - compat_logged.local_first = true - log("compat: local-first Home off (plugin changed): missing " .. table.concat(missing, ", ")) - end - return false - end - if type(BoardData.yearMinutes) == "function" then BoardData.yearMinutes = LF.yearMinutes end - LF.installed = true - LF.failed = {} - log("local-first: installed (" .. tostring(why) .. ")") - - -- The overlay: every board build sees an overlaid copy of the body. - wrap(BoardData, "build", function(stock) return function(catalog, context, now) - if type(context) == "table" and type(context.dashboard) == "table" then - local c = {} - for k, v in pairs(context) do c[k] = v end - c.dashboard = LF.overlaid(context.dashboard) - local d = stock(catalog, c, now) - if type(d) == "table" then d.orbit_board = true end - return d - end - return stock(catalog, context, now) - end end, "lf") - - -- The header ⟳ (left of the device status) and the freshness stamp. - local function refreshIcon(d) - local okm, px = pcall(function() return require("bookorbit_board_metrics").px end) - local size = okm and type(px) == "function" and px(18) or 18 - return BoardUI.icon("refresh-cw", size, { sw = 2 }) - end - local function withRefresh(stock_cluster, d, make) - local cluster = stock_cluster(d) - local okw, w = pcall(function() - return BoardUI.hstack({ gap = 8 }, { make(refreshIcon(d)), cluster }) - end) - return okw and w or cluster - end - local stock_cluster = BoardUI.statusCluster - debug.setupvalue(Catalog.boardHeader, board_status, function(d) - if type(d) == "table" and d.orbit_board then - return withRefresh(stock_cluster, d, function(icon) return BoardUI.hit(LF.holdable(icon), { kind = "orbit-refresh" }) end) - end - return stock_cluster(d) - end) - wrap(BoardUI, "statusCluster", function(stock) return function(d) - if LF.list_header then - return withRefresh(stock, d, function(icon) - return list_region(icon, { kind = "orbit-refresh" }, "header", "orbit-refresh") - end) - end - return stock(d) - end end, "lf") - wrap(ListView, "header", function(stock) return function(w, o) - if type(o) ~= "table" or not o.orbit_refresh then return stock(w, o) end - LF.list_header = true - local okh, r1, r2, r3 = pcall(stock, w, o) - LF.list_header = nil - if not okh then error(r1, 0) end - return r1, r2, r3 - end end, "lf") - wrap(Catalog, "boardHeader", function(stock) return function(self, d, w, mode, page_name) - if type(d) == "table" and d.orbit_board and mode ~= "edit" and not (not d.online and d.stale) then - local stamp = LF.stampText("dashboard", d.online) - if stamp then - local c = {} - for k, v in pairs(d) do c[k] = v end - c.date_long = (d.date_long or "") .. " · " .. stamp - return stock(self, c, w, mode, page_name) - end - end - return stock(self, d, w, mode, page_name) - end end, "lf") - wrap(Catalog, "listHeader", function(stock) return function(self, kind, context) - local h = stock(self, kind, context) - if type(h) == "table" and not h.select then - h.orbit_refresh = true - local key = LF.viewKey(context) - local stamp = key and LF.stampText(key, require("ui/network/manager"):isConnected()) - if stamp and type(h.sub) == "string" then h.sub = h.sub .. " · " .. stamp - elseif stamp and h.sub == nil then h.sub = stamp end - end - return h - end end, "lf") - wrap(Catalog, "boardRun", function(stock) return function(self, action, tile) - if type(action) == "table" and action.kind == "orbit-refresh" then - log("local-first: ⟳ on Home") - return LF.refreshTap(self) - end - return stock(self, action, tile) - end end, "lf") - wrap(Catalog, "listRun", function(stock) return function(self, action, region, hold) - if type(action) == "table" and action.kind == "orbit-refresh" then - log("local-first: ⟳ on a list" .. (hold and " (held)" or "")) - if hold then return LF.refreshHold(self) end - return LF.refreshTap(self) - end - return stock(self, action, region, hold) - end end, "lf") - - -- Covers are keyed by book id + cover version (plugin thumbnailPath), so a changed cover - -- arrives under a new name: our refresh never deletes them (plugin refreshCurrent, - -- bookorbit_catalog.lua:475-490, evicts every cover on screen). Failed ones retry. - if Compat.callable(Catalog.evictCachedCovers) then - wrap(Catalog, "evictCachedCovers", function(stock) return function(self, books) - if not self._orbit_keep_covers then return stock(self, books) end - if type(self.thumbnail_failures) == "table" then self.thumbnail_failures = {} end - end end, "lf") - end - - -- A server refresh: tag it and stamp it; a failure marks "Not updated". - wrap(Catalog, "dashboardRootFetch", function(stock) return function(self, opts) - local items, context = stock(self, opts) - if type(context) == "table" and type(context.dashboard) == "table" and not context.stale - and not (OC and OC.cache_only) then - context.orbit_refresh = true - LocalState.load().fetchedAt.dashboard = os.time() - LF.failed.dashboard = nil - LocalState.save() - elseif type(context) == "table" and context.unavailable and require("ui/network/manager"):isConnected() then - LF.failed.dashboard = true - end - return items, context - end end, "lf") - - -- One paint, then quiet updates (design "One paint, then quiet updates"). - wrap(Catalog, "switchTo", function(stock) return function(self, title, item_table, context, push) - if type(context) == "table" and context.kind == "books" then - LocalState.load().fetchedAt[LF.viewKey(context) or "books"] = os.time() - end - local function full(why) - if type(context) == "table" then - log("paint:", tostring(context.kind), "full (" .. why .. ") from", tostring(self._orbit_paint_source or "the plugin") - .. (context.stale and (context.orbit_first and ", first paint" or ", saved body") or "")) - end - return stock(self, title, item_table, context, push) - end - local old = self.current_context - -- A saved body coming back over the Home on screen (a refresh that couldn't reach the - -- server) only updates what differs; it never repaints every tile. - local saved_over_home = type(context) == "table" and context.kind == "dashboard" and context.stale - and old and old.kind == "dashboard" and self._board_ctx ~= nil - if push or type(context) ~= "table" or context.kind ~= "dashboard" or not (context.orbit_refresh or saved_over_home) then - return full(push and "opened" or "new view") - end - if not (old and old.kind == "dashboard" and self._board_ctx and self._board_tiles) or self.board_edit then - return full("first paint") - end - local okq, done = pcall(LF.quietSwitch, self, old, item_table, context) - log("paint: Home", (okq and done) and "quiet (changed tiles only)" or "full", "from", tostring(self._orbit_paint_source or "the plugin")) - if okq and done then - -- The stock switchTo would cancel the cover jobs and queue this body's covers; the - -- quiet path keeps the jobs running and queues the covers it doesn't have yet. - if Compat.callable(self.scheduleThumbnailDownloads) and Compat.callable(self.dashboardBooks) then - pcall(self.scheduleThumbnailDownloads, self, self.dashboardBooks(context.dashboard)) - end - return - end - if not okq then log("local-first: quiet update failed, full repaint:", done) end - return stock(self, title, item_table, context, push) - end end, "lf") - - -- Hydration: when the on-device marks didn't change, the repaint after it is skipped. - -- Every change to the plugin's state file drops its on-device maps (bookorbit_state_manager - -- .lua:107-111 publish), and a new catalog starts with none (bookorbit_catalog.lua:322): - -- until the child process rebuilds them (:612), every book would draw "Download". The last - -- maps seen are kept here and stand in meanwhile, so a book on the reader shows "Resume" - -- on the first paint. - if Compat.callable(Catalog.hydrateOnDeviceMaps) then - wrap(Catalog, "hydrateOnDeviceMaps", function(stock) return function(self, ...) - pcall(LF.seedOnDevice, self) - return stock(self, ...) - end end, "lf") - end - wrap(Catalog, "refreshOnDevice", function(stock) return function(self, ...) - local before = LF.onDeviceKey(self) - local r = stock(self, ...) - if r then pcall(LF.keepOnDevice, self) else pcall(LF.seedOnDevice, self) end - if self.current_context and self.current_context.kind == "dashboard" and before ~= nil - and before == LF.onDeviceKey(self) then - self._orbit_skip_repaint = true - UIManager:nextTick(function() self._orbit_skip_repaint = nil end) - end - return r - end end, "lf") - wrap(Catalog, "updateItems", function(stock) return function(self, ...) - if self._orbit_skip_repaint and self.current_context and self.current_context.kind == "dashboard" then - self._orbit_skip_repaint = nil - -- Skipped as a full repaint, but whatever did change (a cover that just landed) - -- still repaints its own tile. - local okq, n = pcall(LF.quiet, self) - if okq and (n or 0) > 0 then log("covers: late cover(s) landed;", n, "tile(s) redrawn") end - return - end - return stock(self, ...) - end end, "lf") - return true -end - -local function deviceOwner(cat) - local c = cat and cat.client - return c and (tostring(c.server_url) .. "|" .. tostring(c.username)) or nil -end - --- The plugin's current on-device map, kept for the next start (only when it changed). -function LF.keepOnDevice(cat) - if type(cat.on_device) ~= "table" then return end - local map, n = {}, 0 - for id, path in pairs(cat.on_device) do - if type(path) == "string" then map[tostring(id)] = path; n = n + 1 end - end - local saved = S.orbit_on_device - local sig = ServerCache.encode(map) - if saved and saved.owner == deviceOwner(cat) and saved.sig == sig then return end - S.orbit_on_device = { owner = deviceOwner(cat), map = map, sig = sig } - saveSettings() -end - --- A book this reader has open is on it, whatever the maps say (noted on the way to Home). -function LF.noteOnDevice(book_id, path) - if not (book_id and type(path) == "string") then return end - local saved = S.orbit_on_device - if not saved then return end - if saved.map[tostring(book_id)] == path then return end - saved.map[tostring(book_id)] = path - saved.sig = nil - saveSettings() -end - --- While the plugin's maps are missing: the kept ones, for files that are still there. -function LF.seedOnDevice(cat) - local saved = S.orbit_on_device - if not (saved and saved.owner == deviceOwner(cat) and type(saved.map) == "table") then return 0 end - cat.on_device = type(cat.on_device) == "table" and cat.on_device or {} - local n = 0 - for id, path in pairs(saved.map) do - local nid = tonumber(id) - if nid and cat.on_device[nid] == nil and require("libs/libkoreader-lfs").attributes(path, "mode") == "file" then - cat.on_device[nid] = path - n = n + 1 - end - end - if n > 0 then log("local-first: on-device marks from the last start for", n, "book(s) while BookOrbit rebuilds its own") end - return n -end - --- The board's ⟳ with its own hold: a hold on it is a Full refresh, not the tile's board editing --- (the tile's HoldSelect, bookorbit_catalog_board.lua:75, sees it only if this one doesn't). -function LF.holdable(icon) - local okw, wdg = pcall(function() - local InputContainer = require("ui/widget/container/inputcontainer") - local GestureRange = require("ui/gesturerange") - local area = InputContainer:new{ icon } - area.ges_events = { OrbitHold = { GestureRange:new{ ges = "hold", range = function() return area.dimen end } } } - area.onOrbitHold = function() - local p = serverPlugin(liveUI()) - local cat = p and p.catalog_browser - if cat then log("local-first: ⟳ on Home (held)"); LF.refreshHold(cat) end - return true - end - return area - end) - return okw and wdg or icon -end - --- Tap ⟳ = Refresh, hold ⟳ = Full refresh (docs/design/write-through-cache.md); without the --- cache, both are the plugin's refresh with the covers kept. -function LF.refreshTap(cat) - if OC and OC.installed then return OC.refresh(cat) end - return LF.refreshKeepingCovers(cat) -end - -function LF.refreshHold(cat) - if OC and OC.installed then return OC.fullRefresh(cat) end - return LF.refreshKeepingCovers(cat) -end - --- ⟳: the plugin's refresh of the current view, keeping the covers on disk. -function LF.refreshKeepingCovers(cat) - cat._orbit_keep_covers = true - local okr, r = pcall(cat.refreshCurrent, cat) - cat._orbit_keep_covers = nil - if not okr then error(r, 0) end - return r -end - --- The view key for list stamps: the list's kind and its main filter. -function LF.viewKey(context) - if type(context) ~= "table" then return nil end - local p = context.params or {} - return table.concat({ tostring(context.kind), tostring(context.section or ""), tostring(p.libraryId or p.collectionId - or p.smartScopeId or p.author or p.seriesId or ""), tostring(p.sort or "") }, "|") -end - -function LF.onDeviceKey(cat) - local body = cat.current_context and cat.current_context.dashboard - if type(body) ~= "table" or type(cat.on_device) ~= "table" then return nil end - local parts = {} - for _, id in ipairs(boardBookIds(body)) do table.insert(parts, cat.on_device[id] and "1" or "0") end - return table.concat(parts) -end - --- A refreshed dashboard replacing the one on screen: adopt it, repaint the header (stamp) and --- the tiles whose content changed; a different tile set or page set -> false (full repaint). -function LF.quietSwitch(cat, old, item_table, context) - local BoardData = package.loaded["bookorbit_board_data"] - local ob, nb = old.dashboard or {}, context.dashboard or {} - if LocalFirst.serialize(ob.boardNames) ~= LocalFirst.serialize(nb.boardNames) then return false end - local ok_keys, nk_keys = {}, {} - for k in pairs(type(ob.boardShelves) == "table" and ob.boardShelves or {}) do table.insert(ok_keys, k) end - for k in pairs(type(nb.boardShelves) == "table" and nb.boardShelves or {}) do table.insert(nk_keys, k) end - table.sort(ok_keys); table.sort(nk_keys) - if table.concat(ok_keys, ",") ~= table.concat(nk_keys, ",") then return false end - context.board_page = context.board_page or old.board_page - local old_d = cat._board_ctx.d - cat.current_context = context - cat.item_table = item_table - local new_d = BoardData.build(cat, context, os.time()) - local tiles = LF.tilesOf(cat) - local changed = LocalFirst.changedTiles(tiles, tiles, old_d, new_d) - if not changed then return false end - LF.logChanged(tiles, changed, old_d, new_d) - cat._board_ctx.d = new_d - cat:boardRefreshClock() -- the header: "updated just now" - LF.paintTiles(cat, changed) - log("local-first: refresh landed;", #changed, "tile(s) changed") - LocalState.scanSidecars(cat, boardBookIds(nb)) - return true -end - --- Wiring: install with grouping at init; outbox state and sidecars on open and resume. -do - local base_init = OrbitAndroid.init - function OrbitAndroid:init(...) - local r = base_init(self, ...) - if S.local_first ~= false then pcall(LF.install, "init") end - pcall(LF.installRemove) - pcall(Gate.installToast) - local p = serverPlugin(self.ui) - if p then - pcall(EOB.installPluginHooks, p) - end - return r - end - local base_resume = OrbitAndroid.onResume - function OrbitAndroid:onResume(...) - local p = serverPlugin(self.ui) - local cat = p and p.catalog_browser - if cat and cat.current_context and cat.current_context.kind == "dashboard" then - pcall(LocalState.scanSidecars, cat, boardBookIds(cat.current_context.dashboard)) - pcall(LF.quiet, cat) - end - if base_resume then return base_resume(self, ...) end - end -end - ----------------------------------------------------------------- remove from this reader - --- BookOrbit removes a book's file through the file browser's delete (which asks first and --- clears the sidecar, history and collections: filemanager.lua:1120-1191), and without a file --- browser it only says "Open the file browser to remove this book." (bookorbit_catalog_board.lua --- :955-966, bookorbit_catalog_detail.lua:764-776, bookorbit_book_peek.lua:155-167). With a book --- open there is no file browser: Home opens over the book. The same delete runs from KOReader's --- FileManager class (its file delete uses no file-browser state), with the same confirmation. --- The book that is open stays: removing it under the reader would break its sidecar. -function LF.withFileManager(path, run) - local okf, FM = pcall(require, "apps/filemanager/filemanager") - if not okf or type(FM) ~= "table" or FM.instance or type(FM.showDeleteFileDialog) ~= "function" then return run() end - local okr, RUI = pcall(require, "apps/reader/readerui") - local open = okr and type(RUI) == "table" and RUI.instance and RUI.instance.document and RUI.instance.document.file - if open and path and open == path then - log("remove: the book is open; not removed") - pcall(function() require("bookorbit_toast").error(_("This book is open. Close it, then remove it.")) end) -- gate: user action (Remove) - return - end - log("remove: no file browser open; KOReader's delete (it asks first)") - FM.instance = setmetatable({}, { __index = FM }) - local okc, err = pcall(run) - FM.instance = nil - if not okc then error(err, 0) end -end - -function LF.installRemove() - local Catalog = package.loaded["bookorbit_catalog"] - if type(Catalog) == "table" and Compat.callable(Catalog.boardDustRemove) then - wrap(Catalog, "boardDustRemove", function(stock) return function(self, book) - local path = book and Compat.callable(self.onDeviceBookPath) and self:onDeviceBookPath(book) - return LF.withFileManager(path, function() return stock(self, book) end) - end end, "remove") - end - if type(Catalog) == "table" and Compat.callable(Catalog.detailRemoveFromDevice) then - wrap(Catalog, "detailRemoveFromDevice", function(stock) return function(self, d) - return LF.withFileManager(d and d.read_path, function() return stock(self, d) end) - end end, "remove") - end - local okp, Peek = pcall(require, "bookorbit_book_peek") - if okp and type(Peek) == "table" and Compat.callable(Peek.remove) then - wrap(Peek, "remove", function(stock) return function(catalog, path) - return LF.withFileManager(path, function() return stock(catalog, path) end) - end end, "remove") - end -end diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit/quiesce.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/quiesce.lua deleted file mode 100644 index b176a772..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/quiesce.lua +++ /dev/null @@ -1,33 +0,0 @@ --- SPDX-License-Identifier: AGPL-3.0-or-later --- Migration-only retirement gate: this module never calls the retired transport. --- Installed while PluginLoader is still loading classes, before any instances start. -SyncRetirement = { safe = not (PluginLoader.loaded_plugins and PluginLoader.loaded_plugins.bookorbit) } -local function retired() return nil, "sync_owned_by_companion" end -local function disarm(plugin) - if plugin and plugin.name == "bookorbit" then - for _,name in ipairs({"requestLifecycleOutboxDrain","requestProgressPull","requestProgressPush", - "fetchRemoteProgress","enqueueLifecycleSnapshot","startSweep","onBookOrbitSyncBook","onStart","_onSuspend","_onCloseDocument","_onPageUpdate","_onResume","_onNetworkConnected","_onNetworkDisconnecting", - "onReaderReady","registerEvents","schedulePeriodicPush","requestAnnotationExchange","requestOpenBookMatch", - "requestSweep","requestManualBookSync","scheduleOpenAnnotationSync","submitSyncJob","startMatchRecheck"}) do - plugin[name] = retired - end - end - local api = package.loaded.bookorbit_api - if type(api) == "table" then - -- This closes even bypasses from a legacy scheduled job. No original method is invoked. - for _,name in ipairs({"request","requestBlocking","getProgress","updateProgress","matchCheck","uploadPageStats", - "uploadAnnotations","exchangeAnnotations","exchangeAck","exchangeBookmarks","exchangeBookmarksAck", - "uploadBookStates","bulkProgress","sweepComplete"}) do api[name] = retired end - end -end -for _,plugin in ipairs(PluginLoader.enabled_plugins or {}) do disarm(plugin) end -if type(PluginLoader.createPluginInstance) == "function" then - local stock = PluginLoader.createPluginInstance - function PluginLoader:createPluginInstance(plugin, ...) - disarm(plugin) - return stock(self, plugin, ...) - end -else - -- No known startup seam: retain all source data and refuse companion ownership. - SyncRetirement.safe = false -end diff --git a/android/koreader/orbit.koplugin/ko/shared.lua b/android/koreader/orbit.koplugin/ko/shared.lua index d42ce1ad..5d1d1966 100644 --- a/android/koreader/orbit.koplugin/ko/shared.lua +++ b/android/koreader/orbit.koplugin/ko/shared.lua @@ -37,7 +37,6 @@ function Shared.refresh(why) end local st = Companion.status(1) Shared.capsChanged(why, Companion.updateCaps(st, why)) - -- Signed in to BookOrbit changed since the last report (a sign-in on BookOrbit's page). if why ~= "start" then pcall(Library.backgroundCommand,"preferences.report", "refresh " .. why) end -- Clicker buttons: the companion's key map (an empty map turns ours off). if st then diff --git a/android/koreader/orbit.koplugin/ko/sleepscreen.lua b/android/koreader/orbit.koplugin/ko/sleepscreen.lua index a25ed6a6..745c491e 100644 --- a/android/koreader/orbit.koplugin/ko/sleepscreen.lua +++ b/android/koreader/orbit.koplugin/ko/sleepscreen.lua @@ -121,8 +121,7 @@ local function readJson(path) return (okd and type(v) == "table") and v or nil end --- The BookOrbit id of a book file on this reader (the plugin's on-device map), or nil. -function Sleep.bookId(path) return Server.localBookId(path) end +function Sleep.bookId(path) return Library.localBookReference(path) end ---------------------------------------------------------------- Current book (R9) @@ -181,11 +180,7 @@ function Sleep.kick(why) end -- The login travels only in the caller-checked call to the verified companion (Companion.send), never in a file. -local function ask(client, extras) - Server.credentials(client, extras) - Companion.send(Companion.ACTION.SLEEP_REFRESH, extras) - Server.watchCache() -end +local function ask(extras) return Library.sleepRefresh(extras) end function Sleep.refresh(why) local s = Sleep.settings() @@ -199,15 +194,15 @@ function Sleep.refresh(why) return false end Sleep.problem = nil - local client = Server.cacheClient() - if not (client and Sleep.dir()) then + local available=(Library.cachedAccountState().catalog or {}).canRefresh==true + if not (available and Sleep.dir()) then log("sleep screen: no library client yet; the pool waits (" .. tostring(why) .. ")") return false end Sleep.asked, Sleep.refreshed_at = Store.now(), t Wifi.acquire("sleep screen") log("sleep screen: the companion refreshes the pool from", s.sleep_from, "(" .. tostring(why) .. ")") - ask(client, { reason = tostring(why), from = s.sleep_from, rules = SleepPool.encodeRules(s.sleep_leave_out), + ask({ reason = tostring(why), from = s.sleep_from, rules = SleepPool.encodeRules(s.sleep_leave_out), open_id = tostring(Sleep.bookId(S.sleep_current_file) or ""), every = s.sleep_hours == SleepPool.EVERY_SLEEP and "1" or "0", storage_limit_mb = tostring(tonumber(S.storage_limit_mb) or Cache.STORAGE_DEFAULT_MB) }) return true @@ -291,15 +286,15 @@ end -- The companion lists both again when online; done(v or nil) after. function Sleep.refreshScopes(why, done) - local client = Server.cacheClient() + local available=(Library.cachedAccountState().catalog or {}).canRefresh==true local t = os.time() - if Sleep.scopes_asked or not client or not NetworkMgr:isConnected() or Companion.workerProblem() + if Sleep.scopes_asked or not available or not NetworkMgr:isConnected() or Companion.workerProblem() or (Sleep.scopes_at and t >= Sleep.scopes_at and t - Sleep.scopes_at < Sleep.SCOPES_EVERY_S) then if done then done(nil) end return false end Sleep.scopes_asked, Sleep.scopes_at, Sleep.scopes_done = Store.now(), t, done - ask(client, { reason = tostring(why), scopes_only = "1" }) + ask({ reason = tostring(why), scopes_only = "1" }) return true end diff --git a/android/koreader/orbit.koplugin/ko/start.lua b/android/koreader/orbit.koplugin/ko/start.lua index 4739a35a..4d2a0f3f 100644 --- a/android/koreader/orbit.koplugin/ko/start.lua +++ b/android/koreader/orbit.koplugin/ko/start.lua @@ -21,7 +21,6 @@ function OrbitAndroid:onResume() end log("resume", state.paused_for and ("after " .. fmt(state.paused_for) .. " in the background") or "") Clicks.install("resume") - -- Back in front and not in a book (file browser, BookOrbit Home): what waited shows now. UIManager:scheduleIn(2, function() Gate.drain("resume") end) UIManager:scheduleIn(0.3, function() if Library then Library.accountReturned() end @@ -29,7 +28,6 @@ function OrbitAndroid:onResume() Wifi.applySettings("resume") self:checkCommand("resume") self:maybeRestart("check") - -- After checkCommand: a Home command moves to BookOrbit home first (finishHome checks too). self:maybeSetupPrompt("resume") -- Also after "home": the closed book's sync needs the network. self:wakeFlow("wake") diff --git a/android/koreader/orbit.koplugin/ko/wifi.lua b/android/koreader/orbit.koplugin/ko/wifi.lua index 6ade4762..98102ff0 100644 --- a/android/koreader/orbit.koplugin/ko/wifi.lua +++ b/android/koreader/orbit.koplugin/ko/wifi.lua @@ -141,20 +141,6 @@ end -- http.request at call time (all of KOReader's) are covered. function pack(...) return { n = select("#", ...), ... } end -function wrapRequests(modname) - local okm, mod = pcall(require, modname) - if not okm or type(mod) ~= "table" or type(mod.request) ~= "function" or mod._orbit_wrapped then return end - local orig = mod.request - mod._orbit_wrapped = true - mod.request = function(...) - Wifi.inflight_http = Wifi.inflight_http + 1 - if Wifi.plan then WifiPlan.activity(Wifi.plan, now_s()) end - local r = pack(pcall(orig, ...)) - Wifi.inflight_http = Wifi.inflight_http - 1 - if Wifi.plan then WifiPlan.activity(Wifi.plan, now_s()) end - if not r[1] then error(r[2], 0) end - return unpack(r, 2, r.n) - end -end + --------------------------------------------------------------------------------------------- diff --git a/android/koreader/orbit.koplugin/ko/wifi_backend.lua b/android/koreader/orbit.koplugin/ko/wifi_backend.lua index 96561911..1d097ba8 100644 --- a/android/koreader/orbit.koplugin/ko/wifi_backend.lua +++ b/android/koreader/orbit.koplugin/ko/wifi_backend.lua @@ -60,7 +60,14 @@ end stock_beforeWifiAction = NetworkMgr.beforeWifiAction function NetworkMgr:beforeWifiAction(callback) Wifi.activity("KOReader needs the network") - return stock_beforeWifiAction(self, callback) + if type(callback)~="function" then return stock_beforeWifiAction(self,callback) end + return stock_beforeWifiAction(self,function(...) + Wifi.inflight_http=Wifi.inflight_http+1;Wifi.activity("native network job") + local result=pack(pcall(callback,...)) + Wifi.inflight_http=Wifi.inflight_http-1;Wifi.activity("native network job finished") + if not result[1] then error(result[2],0) end + return unpack(result,2,result.n) + end) end -- No "Turn on Wi-Fi?" prompt, in every Wi-Fi mode, when the companion can switch Wi-Fi: @@ -70,8 +77,6 @@ end -- connection is up (frontend/ui/network/manager.lua:539-541, closed at :110-113 or replaced by -- "Error connecting to the network" at :88-92). It runs for every beforeWifiAction -- (manager.lua:605-619), e.g. the plugin's resume pull, which asks for the network 1 s after --- each wake (bookorbit.koplugin main.lua:1329-1337 -> requestProgressPull(true, ...) -> --- willRerunWhenConnected, bookorbit_progress_sync.lua:389). With Wi-Fi off after a sleep -- sync or "just in time", that flashed on every wake. With the companion, the same steps run -- without the message: ask for Wi-Fi (requestToTurnOnWifi, manager.lua:67-78), then the -- stock connectivity check with no widget (:82-133), which shows nothing on success and @@ -107,7 +112,5 @@ end -- (ko/recommended.lua silentWifiOn): only at KOReader's default, with a backup. silentWifiOn() -wrapRequests("socket.http") -wrapRequests("ssl.https") --------------------------------------------------------------------------------------------- diff --git a/android/koreader/orbit.koplugin/logic/budgets.lua b/android/koreader/orbit.koplugin/logic/budgets.lua index 7138f1e6..9f612975 100644 --- a/android/koreader/orbit.koplugin/logic/budgets.lua +++ b/android/koreader/orbit.koplugin/logic/budgets.lua @@ -26,6 +26,7 @@ Budgets.screens["editor-picker"].roundTrips = 0 Budgets.screens["editor-picker"].drawNodes = 24 -- Picker pages inherit the same filter screen limits, including one worker round-trip. Budgets.screens["filter-picker"] = budget(24, 16384, 50) +Budgets.libraryBootstrap = budget(1,16384,50) Budgets.libraryWindow = budget(32, 32768, 30) for _, id in ipairs({"continue-reading", "booklist", "lists", "library", "battery", "this-week", "year-in-reading", "when-you-read", "reading-records", "clock", "word", "light", "buddy", "highlight", "yearago"}) do diff --git a/android/koreader/orbit.koplugin/logic/cache.lua b/android/koreader/orbit.koplugin/logic/cache.lua index 411733cb..aea539da 100644 --- a/android/koreader/orbit.koplugin/logic/cache.lua +++ b/android/koreader/orbit.koplugin/logic/cache.lua @@ -4,7 +4,6 @@ -- order main.lua lists (docs/design/orbit-plugin.md "Module layout"). -- Generic literal serialization, hashing, URL utilities, display counts and local quota/image --- helpers. Legacy server cache policy lives only in logic/server/bookorbit/cache.lua. --------------------------------------------------------------------------------------------- Cache = {} diff --git a/android/koreader/orbit.koplugin/logic/copies.lua b/android/koreader/orbit.koplugin/logic/copies.lua index 50fbb74e..92a1e7e6 100644 --- a/android/koreader/orbit.koplugin/logic/copies.lua +++ b/android/koreader/orbit.koplugin/logic/copies.lua @@ -3,7 +3,6 @@ -- 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). BookOrbit writes -- metadata into the library file (tags, series), so its partial MD5 moves and every copy on a -- reader stops matching it: the server marks those copies position-incompatible and progress, -- highlights and bookmarks stop syncing. These are the pure rules: which copies changed, which diff --git a/android/koreader/orbit.koplugin/logic/home_plan.lua b/android/koreader/orbit.koplugin/logic/home_plan.lua index c53209d2..413e85bc 100644 --- a/android/koreader/orbit.koplugin/logic/home_plan.lua +++ b/android/koreader/orbit.koplugin/logic/home_plan.lua @@ -5,23 +5,16 @@ -- Smart Home (android/docs/INTERFACE.md "go home"). What Home does in KOReader. -- mode: "smart" | HomePlan.SERVER_HOME; in_reader: a book is open; covered: a menu or the --- plugin's views are over it; on_dashboard: the plugin's BookOrbit home (dashboard) is the -- top widget; from_other: Home came from another app (or KOReader was just started); -- reopen: a current book that isn't open now and still exists: the book Home itself closed -- (home_book), or the one KOReader was killed with (cold start, open_book_at_exit). A book -- the user closed is never reopened from history. --- bookorbit_sub: a BookOrbit screen that isn't its main page is on top (BookOrbit.screen). --- Returns "bookorbit_main" (that BookOrbit main page), "companion" (the companion's launcher page), "dashboard" (close any book, --- BookOrbit home) or "book" (show the book: close what covers it, or open the last one). --- Presses in KOReader step book -> BookOrbit home -> companion; Home from another app (the -- companion included) goes back to the book, so the steps never loop. HomePlan = {} function HomePlan.decide(o) - -- A BookOrbit page past its first (the dashboard's page 2, a list's page 3), nothing over -- it: page 1 first; only page 1 leaves (v0.5.4). if o.page_above_1 and not o.from_other then return "first_page" end - -- Any BookOrbit screen other than its main page (a detail, list, search, board, settings, -- a sheet or dialog over the catalog): back to the main page (v0.4.9). if o.library_sub then return "library_main" end if o.on_dashboard and not o.from_other then return "companion" end @@ -44,13 +37,11 @@ function HomePlan.cameFromOtherApp(from_extra, suspended_s) return suspended_s == nil or suspended_s >= HomePlan.OTHER_APP_S end --- The rotation Home keeps (BookOrbit Home must never turn the device from how it is held). -- On Android, KOReader's rotation is the activity's requestedOrientation (koreader-base -- ffi/framebuffer_android.lua:78-91: mode 0-3 -> PORTRAIT, LANDSCAPE, REVERSE_PORTRAIT, -- REVERSE_LANDSCAPE), which turns the whole display. Every new file browser forces its own -- rotation, fm_rotation_mode or upright (filemanager.lua:63-69, from showFiles :1321: KOReader's -- start, reader.lua:291, and every book close, readerui.lua:594, since opening a book closes the --- file browser, readerui.lua:787-788), and BookOrbit Home sits over it. -- held: the companion's ROTATION extra, the display's orientation when Home was pressed. HomePlan.ROTATIONS = { portrait = 0, landscape = 1, reverse_portrait = 2, reverse_landscape = 3 } diff --git a/android/koreader/orbit.koplugin/logic/native.lua b/android/koreader/orbit.koplugin/logic/native.lua new file mode 100644 index 00000000..de9464c2 --- /dev/null +++ b/android/koreader/orbit.koplugin/logic/native.lua @@ -0,0 +1,8 @@ +-- SPDX-License-Identifier: AGPL-3.0-or-later +Compat={PAGING={boardPage="function",boardFlip="function",listMode="function",listPaging="function",listGoPage="function"}} +function Compat.callable(v) return type(v)=="function" end +function Compat.missingOn(obj,needs) + local out={};for key,kind in pairs(needs) do if type((obj or {})[key])~=kind then out[#out+1]=key end end + table.sort(out);return out +end +HomePlan.SERVER_HOME="server-home" diff --git a/android/koreader/orbit.koplugin/logic/plan.lua b/android/koreader/orbit.koplugin/logic/plan.lua index 1283fbdf..d72ae645 100644 --- a/android/koreader/orbit.koplugin/logic/plan.lua +++ b/android/koreader/orbit.koplugin/logic/plan.lua @@ -6,7 +6,6 @@ -- Decisions taken on plugin state, kept pure so they can be tested. Plan = {} --- Strategy values from bookorbit main.lua:56-60. Plan.STRATEGY = { PROMPT = 1, SILENT = 2, DISABLE = 3 } -- While waiting for the plugin's lifecycle outbox after a sleep sync. @@ -22,11 +21,8 @@ function Plan.outboxVerdict(o) return "wait" end --- Sync while reading: what to do once the plugin has refreshed BookOrbit's position -- (fetchRemoteProgress, which never moves the reader or prompts). --- has_remote: BookOrbit has a position for this book -- same_place / remote_newer: the plugin's own isSamePlace / remoteProgressIsNewer --- forward: the plugin's "BookOrbit is further ahead" strategy -- Returns "push", "pull" or "none". Never "prompt": a PROMPT strategy waits for the next -- wake or book open, so nothing interrupts the page. function Plan.readingAction(o) diff --git a/android/koreader/orbit.koplugin/logic/prompts.lua b/android/koreader/orbit.koplugin/logic/prompts.lua index 0dc8807d..cb509667 100644 --- a/android/koreader/orbit.koplugin/logic/prompts.lua +++ b/android/koreader/orbit.koplugin/logic/prompts.lua @@ -5,7 +5,6 @@ -- "Setup needs you" box (companion 0.4.1+): /status carries setup_prompt = { key, rows } only -- while rows need the user and they didn't say Later (the companion's snooze). Shown once per --- key, never with a book on screen: the file browser, BookOrbit home or a menu. --------------------------------------------------------------------------------------------- SetupPrompt = {} @@ -66,7 +65,6 @@ end -- An update the reader asked for restarts at once: the book is saved through KOReader's own close -- and reopens where it was (v0.11.1). An automatic one only when KOReader is out of the way: the -- screen off (restart), or another app in front ("quit": save and quit, the new plugin loads at --- the next start). A closed book or BookOrbit Home is not enough: the reader is still using it. function RestartPlan.decide(want, running, tried, reading, event) if not want then return "none" end if Update.compare(want, running) ~= 1 then return tried and "done" or "none" end diff --git a/android/koreader/orbit.koplugin/logic/server/bookorbit/cache.lua b/android/koreader/orbit.koplugin/logic/server/bookorbit/cache.lua deleted file mode 100644 index d8e8a00f..00000000 --- a/android/koreader/orbit.koplugin/logic/server/bookorbit/cache.lua +++ /dev/null @@ -1,233 +0,0 @@ --- SPDX-License-Identifier: AGPL-3.0-or-later --- Legacy cache policy and response shapes are private to this adapter. -ServerCache=setmetatable({ - FRESH_S = 60, -- a read within this of the last check is not checked again - VERSION = 1, - MIRROR_PAGE = 100, -- the server's largest page (koreader-catalog-query.dto.ts:87, :284) - MIRROR_TTL_DAYS = 7, -- an automatic Full refresh once the mirror is older than this -},{__index=Cache}) --- Legacy protocol classification and cached-field normalization. No IO. -function ServerCache.cacheable(method, path) - if tostring(method or ""):upper() ~= "GET" then return false end - local p = ServerCache.splitPath(path) - if not (p:find("^/koreader/plugin/catalog/") or p:find("^/plugin/catalog/")) then return false end - if p:find("/thumbnail$") or p:find("/photo$") or p:find("/download") or p:find("/files/") then return false end - return true -end - -function ServerCache.listWindow(path) - local p, q = ServerCache.splitPath(path) - local books = p:find("/catalog/books$") ~= nil - local section = p:match("/catalog/sections/([%w%-]+)$") - if not books and not section then return nil end - local query = ServerCache.parseQuery(q) - if query.q and query.q ~= "" then return nil end -- search stays online - local w = { page = tonumber(query.page), size = tonumber(query.size), offset = tonumber(query.offset), - kind = books and "books" or "section", section = section } - query.page, query.size, query.offset = nil, nil, nil - local rest = ServerCache.encQuery(query) - w.identity = p .. (rest ~= "" and ("?" .. rest) or "") - return w -end - -function ServerCache.writeEffect(method, path, body) - if tostring(method or ""):upper() == "GET" then return nil end - local p = ServerCache.splitPath(path) - local id, what = p:match("/catalog/books/(%d+)/([%w%-]+)$") - id = tonumber(id) - if not id then return { stale_home = p:find("/catalog/") ~= nil or p:find("/sync") ~= nil or p:find("/progress") ~= nil } end - body = type(body) == "table" and body or {} - if what == "read-status" then return { id = id, fields = { readStatus = body.status }, stale_home = true } end - if what == "rating" then - local r = body.rating - if type(r) ~= "number" then r = ServerCache.NULL end - return { id = id, fields = { rating = r }, stale_home = true } - end - return { stale_home = true } -end - -ServerCache.VOLATILE = { generatedAt = true } -ServerCache.KEEP_SAVED = { discover = true } - -function ServerCache.normalize(body) - if type(body) ~= "table" then return body end - local out = {} - for k, v in pairs(body) do - if not ServerCache.VOLATILE[k] and not ServerCache.KEEP_SAVED[k] then out[k] = v end - end - return out -end - -local splitPath=ServerCache.splitPath -local function normQuery(query) - local keys = {} - for k, v in pairs(query or {}) do - if v ~= nil and tostring(v) ~= "" then table.insert(keys, tostring(k)) end - end - table.sort(keys) - local parts = {} - for _, k in ipairs(keys) do table.insert(parts, k .. "=" .. tostring(query[k])) end - return table.concat(parts, "&") -end -local function normServer(s) - return (tostring(s or ""):lower():gsub("/+$", "")) -end - -function ServerCache.key(r) - local path, q = splitPath(r.path) - local query = ServerCache.parseQuery(q) - for k, v in pairs(r.query or {}) do query[k] = v end - return table.concat({ tostring(r.account or ""), normServer(r.server), tostring(r.method or "GET"):upper(), - path, normQuery(query) }, "|") -end - --- Catalog reads only; never covers, downloads, auth, version or sync. - ----------------------------------------------------------------- reads - --- entry: nil or { validated_at }; mode: "open" | "refresh" | "full". -> serve, fetch. --- entry.stale: a write since may have changed it (served, checked at once). -function ServerCache.readPlan(entry, now, mode, offline) - if mode == "full" then - if offline then return entry ~= nil, false end - return false, true - end - if not entry then return false, not offline end - if offline then return true, false end - if mode == "refresh" or entry.stale then return true, true end - return true, (now - (entry.validated_at or 0)) >= ServerCache.FRESH_S -end - --- Fields that differ on every request and say nothing about the data: generatedAt is the --- server's clock (koreader-catalog.service.ts:279); discover is a fresh random pick each time --- (:417-433, getRandomBooks), so a check never counts it and the saved pick is kept until a --- Full refresh. - --- -> changed, stored -function ServerCache.revalidate(cached, reply, status) - if type(status) ~= "number" or status < 200 or status >= 300 or reply == nil then return false, false end - return ServerCache.encode(ServerCache.normalize(cached)) ~= ServerCache.encode(ServerCache.normalize(reply)), true -end - ----------------------------------------------------------------- the offline mirror - --- A list read (a books page or a section page): its identity (the path without page, size and --- offset) and the window it asks for. nil for anything else (a book, the dashboard, a search). - --- A search: never mirrored; offline it says it needs a connection. -function ServerCache.isSearch(path) - local _, q = splitPath(path) - local query = ServerCache.parseQuery(q) - return query.q ~= nil and query.q ~= "" -end - -function ServerCache.pageCount(total, size) - total = tonumber(total) or 0 - if total <= 0 then return 1 end - return math.ceil(total / (size or ServerCache.MIRROR_PAGE)) -end - --- One list page answered from the mirror's pages. --- w: Cache.listWindow; pages: { [n] = body of mirror page n }; -> body, or nil when a page it --- needs isn't saved. -local PAGING = { items = true, page = true, size = true, offset = true, hasNext = true, hasPrevious = true, - nextUrl = true, previousUrl = true } -function ServerCache.slice(w, pages, page_size) - local per = page_size or ServerCache.MIRROR_PAGE - local first = pages[1] - if type(first) ~= "table" or type(first.items) ~= "table" then return nil end - local total = tonumber(first.total) or #first.items - local size = w.size or (w.kind == "books" and 20 or total) - if size < 1 then size = 1 end - local start = w.offset or ((w.page or 1) - 1) * size - local stop = math.min(total, start + size) - local items = {} - for i = start + 1, stop do - local n = math.floor((i - 1) / per) + 1 - local page = pages[n] - if type(page) ~= "table" or type(page.items) ~= "table" then return nil end - local item = page.items[i - (n - 1) * per] - if item == nil then return nil end - table.insert(items, item) - end - local out = {} - for k, v in pairs(first) do if not PAGING[k] then out[k] = v end end - out.items, out.total, out.size = items, total, size - out.page = math.floor(start / size) + 1 - if w.offset then out.offset = w.offset end - out.hasNext, out.hasPrevious = stop < total, start > 0 - return out -end - --- The positions a list read asks for (docs/design/sqlite-cache.md "How KOReader reads"; the --- companion's CacheStore.windowOf). kind: "books" | "section"; page, size, offset: the read's own. --- -> start (0-based), stop (exclusive), size -function ServerCache.window(kind, total, page, size, offset) - total = tonumber(total) or 0 - size = tonumber(size) or (kind == "books" and 20 or total) - if size < 1 then size = 1 end - local start = tonumber(offset) or ((tonumber(page) or 1) - 1) * size - return start, math.max(start, math.min(total, start + size)), size -end - --- A list page from its saved head (the first page's other fields) and the items at start..stop-1. -function ServerCache.assemble(head, items, total, start, stop, size, offset) - local out = {} - for k, v in pairs(type(head) == "table" and head or {}) do if not PAGING[k] then out[k] = v end end - out.items, out.total, out.size = items, total, size - out.page = math.floor(start / size) + 1 - if offset then out.offset = tonumber(offset) end - out.hasNext, out.hasPrevious = stop < total, start > 0 - return out -end - --- The book id when path is the detail template (the plugin's detail request with the sentinel id) --- filled with an id; the companion's CacheStore.detailId. -function ServerCache.detailId(path, template, sentinel) - if type(template) ~= "string" or type(path) ~= "string" then return nil end - local i, j = template:find(sentinel, 1, true) - if not i then return nil end - local pre, post = template:sub(1, i - 1), template:sub(j + 1) - if #path <= #pre + #post or path:sub(1, #pre) ~= pre or (post ~= "" and path:sub(-#post) ~= post) then return nil end - local mid = path:sub(#pre + 1, #path - #post) - if not mid:match("^%d+$") or #mid > 12 then return nil end - return tonumber(mid) -end - --- An offline search's words, each as a LIKE pattern (% and _ escaped with \). -function ServerCache.searchWords(q) - local out = {} - for w in tostring(q or ""):gmatch("%S+") do - table.insert(out, "%" .. w:gsub("[\\%%_]", "\\%0") .. "%") - end - return out -end - --- Whether the mirror needs an automatic Full refresh. --- m: { at (last complete Full refresh), lib_version }; lib_version: the plugin's current one. --- -> reason ("never" | "ttl" | "library") or nil -function ServerCache.mirrorDue(m, now, ttl_days, lib_version) - if type(m) ~= "table" or not m.at then return "never" end - if now - m.at >= (ttl_days or ServerCache.MIRROR_TTL_DAYS) * 86400 then return "ttl" end - if lib_version and m.lib_version and lib_version ~= m.lib_version then return "library" end - return nil -end - ----------------------------------------------------------------- writes - --- The book id and the fields a write sets, or nil when the write patches nothing. - -ServerCache.NULL = {} -- a field the write clears - --- The book ids a body lists (for finding the entries a write touches). -function ServerCache.ids(body, out, depth) - out = out or {} - depth = depth or 0 - if type(body) ~= "table" or depth > 30 then return out end - local id = tonumber(body.id) - if id then out[id] = true end - for _, v in pairs(body) do - if type(v) == "table" then ServerCache.ids(v, out, depth + 1) end - end - return out -end diff --git a/android/koreader/orbit.koplugin/logic/server/bookorbit/compat.lua b/android/koreader/orbit.koplugin/logic/server/bookorbit/compat.lua deleted file mode 100644 index ee8bdc06..00000000 --- a/android/koreader/orbit.koplugin/logic/server/bookorbit/compat.lua +++ /dev/null @@ -1,143 +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"). - --- Plugin compatibility (survive BookOrbit plugin updates). Every plugin internal the patch --- calls, grouped by the feature that needs it. A missing one turns off only that feature, which --- then falls back to the plugin's own behaviour. Definitions (bookorbit.koplugin 2.3.0): --- main.lua:283 isLoggedIn, :287 errorLabel, :361 getSyncCoordinator, :374 getLifecycleOutbox, --- :414 requestLifecycleOutboxDrain, :717 requestProgressPush, :730 requestProgressPull, --- :1246 startSweep, :1269 onBookOrbitSyncBook, :1340 _onSuspend, :1381 onBookOrbitOpenDashboard, --- :1416 onBookOrbitToggleAutoSync; bookorbit_progress_sync.lua:63 getLastPercent, :71 --- getLastProgress, :81 getDocumentDigest, :145 isSamePlace, :157 remoteProgressIsNewer, :521 --- fetchRemoteProgress; the catalog widget: main.lua:1207-1230 --- (catalog_browser, close_callback), bookorbit_catalog.lua:1875 dashboardMode. --- test/plugin_compat.lua checks the same list against the latest plugin source (CI, weekly). -Compat = {} -Compat.FEATURES = { - { id = "core", needs = { isLoggedIn = "function", settings = "table" }, - fallback = "the patch leaves syncing to the plugin" }, - { id = "outbox", needs = { requestLifecycleOutboxDrain = "function", getLifecycleOutbox = "function", - getSyncCoordinator = "function" }, - fallback = "wake and sleep syncs use the plugin's own sync" }, - { id = "wake_pull", needs = { requestProgressPull = "function" }, - fallback = "wake and open pulls use the plugin's own timing" }, - { id = "sleep_snapshot", needs = { _onSuspend = "function" }, - fallback = "Sync and sleep sends what the plugin already queued" }, - { id = "reading_sync", needs = { fetchRemoteProgress = "function", isSamePlace = "function", - remoteProgressIsNewer = "function", getLastPercent = "function", getLastProgress = "function", - getDocumentDigest = "function", requestProgressPush = "function", requestProgressPull = "function", - requestLifecycleOutboxDrain = "function" }, - fallback = "Sync while reading is off" }, - { id = "dashboard", needs = { onBookOrbitOpenDashboard = "function" }, - fallback = "Home closes the book, then the plugin opens BookOrbit home" }, - { id = "test_sync", needs = { onBookOrbitSyncBook = "function", startSweep = "function", errorLabel = "function" }, - fallback = "Test sync path skips the plugin step" }, - { id = "recommended", needs = { onBookOrbitToggleAutoSync = "function" }, - fallback = "Recommended settings can't turn on Auto-sync" }, - { id = "signin", needs = { promptLogin = "function" }, - fallback = "BookSync Companion's \"Sign in\" opens KOReader without BookOrbit's sign-in page" }, -} --- The feature that names each plugin event (advisory logging in pluginEvent). -PLUGIN_EVENT_FEATURE = { BookOrbitOpenDashboard = "dashboard", BookOrbitSyncBook = "test_sync", - BookOrbitToggleAutoSync = "recommended" } --- Plugin settings the patch writes, with the values the plugin accepts. catalog_auto_open is the --- plugin's open mode (2.3.0 bookorbit_settings_page.lua:205-209 "Make BookOrbit home" = "home"; --- read by main.lua:940-960 onStart/maybeAutoOpenCatalog; the plugin saves it by setting the --- field and flushing G_reader_settings, bookorbit_settings_page.lua:822-825). -Compat.SETTINGS = { catalog_auto_open = { off = true, filemanager = true, home = true } } - --- The setting can be written: the plugin's settings table, and the current value unset or one --- the plugin knows (a value we don't know means the plugin changed the setting: leave it alone). -function Compat.settable(settings, key, value) - local known = Compat.SETTINGS[key] - if type(settings) ~= "table" or not known or not known[value] then return false end - local cur = settings[key] - return cur == nil or (type(cur) == "string" and known[cur] == true) -end - --- On the catalog widget, checked when it is open. -Compat.CATALOG = { dashboardMode = "function", close_callback = "function", goDashboard = "function" } - --- Lists by series and by author (v0.6.0, Grouping): the catalog class's methods it wraps or --- calls (bookorbit_catalog.lua :847 switchTo, :881 fetch, :974 loadSection, :1111 --- paramsForEntry, :1181 loadBooks, :924 runConnected, :970 showRetry; the list methods copied --- onto it by CatalogLists.install, bookorbit_catalog_lists.lua :45 listKind, :246 --- listSectionParams, :659 listSortSheetModel, :739 listRun, :1115 listToolbar, :1155 --- listHeader), and the API class's (bookorbit_api.lua :386 query, :714 catalogBooks, :720 --- catalogManifest). A missing one turns off only this feature (logged once). -Compat.CATALOG_CLASS = { switchTo = "function", fetch = "function", loadSection = "function", - paramsForEntry = "function", loadBooks = "function", runConnected = "function", showRetry = "function", - listKind = "function", listSectionParams = "function", listSortSheetModel = "function", listRun = "function", - listToolbar = "function", listHeader = "function" } -Compat.API_CLASS = { query = "function", catalogBooks = "function", catalogManifest = "function" } - --- Paging on the catalog, for Home's "page 1 first" (v0.5.4): the dashboard's page --- (bookorbit_catalog_board.lua:119-123 boardPage, :968-976 boardFlip) and a list's page --- (bookorbit_catalog_lists.lua:64-66 listMode, :390-411 listPaging, :421-446 listGoPage). -Compat.PAGING = { boardPage = "function", boardFlip = "function", listMode = "function", - listPaging = "function", listGoPage = "function" } - --- "function" means callable: KOReader 2025.10+ wraps every plugin on* handler in a --- HandlerSandbox, a table with __call (frontend/pluginloader.lua v2026.07.1:117-128, :158-164, --- applied at :263); up to 2025.08 the wrapper was a plain function. A type() check alone saw --- 2.3.0's handlers as missing on 2025.10+ (11-21 Boox Page, KOReader 2026.07.1). -function Compat.callable(v) - if type(v) == "function" then return true end - if type(v) ~= "table" and type(v) ~= "userdata" then return false end - local okm, mt = pcall(getmetatable, v) - return okm and type(mt) == "table" and mt.__call ~= nil -end - -function hasKind(v, kind) - if kind == "function" then return Compat.callable(v) end - return type(v) == kind -end - --- { [id] = missing symbols (sorted list) } for one plugin instance; {} when all is there. -function Compat.check(p) - local out = {} - for _, f in ipairs(Compat.FEATURES) do - local missing = {} - for name, kind in pairs(f.needs) do - local okv, v = pcall(function() return p[name] end) - if not okv or not hasKind(v, kind) then table.insert(missing, name) end - end - if #missing > 0 then table.sort(missing); out[f.id] = missing end - end - return out -end - --- The names in needs that obj lacks (sorted); {} when all are there. -function Compat.missingOn(obj, needs) - local missing = {} - for name, kind in pairs(needs) do - local okv, v = pcall(function() return obj[name] end) - if not okv or not hasKind(v, kind) then table.insert(missing, name) end - end - table.sort(missing) - return missing -end - -function Compat.fallback(id) - for _, f in ipairs(Compat.FEATURES) do if f.id == id then return f.fallback end end - return id -end - --- One line per unavailable feature, e.g. "BookOrbit 2.4.0 changed: sleep sync uses ...". -function Compat.lines(missing, version) - local ids = {} - for id in pairs(missing) do table.insert(ids, id) end - table.sort(ids) - local out = {} - for _, id in ipairs(ids) do - table.insert(out, string.format("BookOrbit %s changed: %s", version or "?", Compat.fallback(id))) - end - return out -end - ---------------------------------------------------------------------------------------------- - --- Preserve the historical shared-setting wire value behind the compatibility adapter. -HomePlan.SERVER_HOME = "bookorbit" diff --git a/android/koreader/orbit.koplugin/logic/server/bookorbit/finish.lua b/android/koreader/orbit.koplugin/logic/server/bookorbit/finish.lua deleted file mode 100644 index 773f74ab..00000000 --- a/android/koreader/orbit.koplugin/logic/server/bookorbit/finish.lua +++ /dev/null @@ -1,205 +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 (docs/design/end-of-book/DESIGN.md, ROADMAP 1 and 2): the FinishJob queue and its --- drain decisions, the "next in series" / suggestion / author picker, and the stale-push hold. --- Pure: no KOReader modules. Table-tested from shared/fixtures/bookorbit/ (test_logic.lua). ---------------------------------------------------------------------------------------------- - -Finish = { - MAX_ATTEMPTS = 5, -- then the job is parked until a manual sync (design §3 "Errors") - BACKOFF_FIRST = 60, -- seconds, doubling... - BACKOFF_MAX = 3600, -- ...up to an hour - HOLD_POINTS = 10, -- a push this many points below the finish is held (§7, server S3) - HOLD_RELEASE_PAGES = 10, -- unless the reader turned this many pages forward in the session - SUGGEST_ANDROID = 1, -} - --- The statuses someone chose elsewhere on purpose; the drain doesn't fight them (G4). -Finish.DELIBERATE = { rereading = true, on_hold = true, abandoned = true } - --- A new job. f: { hash, book_id?, file?, finished_on? (YYYY-MM-DD), final_pos? {percentage, --- xpointer}, rating? (1..5 | "clear"), status_seen?, now }. -function Finish.newJob(f) - return { - hash = f.hash, book_id = f.book_id, file = f.file, finished_on = f.finished_on, - final_pos = f.final_pos, rating = f.rating, status_seen = f.status_seen, - created_at = f.now or 0, attempts = 0, next_try_at = 0, parked = false, - } -end - --- One job per book, the newest local intent wins (§3): a new job replaces the book's old one, --- keeping a rating given earlier unless the new one carries its own. -function Finish.put(queue, job) - local old = queue[job.hash] - if old and job.rating == nil then job.rating = old.rating end - queue[job.hash] = job - return job -end - --- Undo, "Mark as reading" or a reread deletes the unsent job. -function Finish.cancel(queue, hash) - local had = queue[hash] ~= nil - queue[hash] = nil - return had -end - --- A rating on the end screen: 1..5, the same star again clears it ("clear"), nil leaves it. -function Finish.setRating(job, stars, current) - if stars == nil then return job.rating end - if current == stars then job.rating = "clear" else job.rating = stars end - return job.rating -end - --- Jobs to send now, oldest first. manual: a sync the reader asked for also retries parked jobs. -function Finish.due(queue, now, manual) - local out = {} - for _, job in pairs(queue) do - if (manual or not job.parked) and (manual or (job.next_try_at or 0) <= now) then - table.insert(out, job) - end - end - table.sort(out, function(a, b) - if a.created_at == b.created_at then return tostring(a.hash) < tostring(b.hash) end - return a.created_at < b.created_at - end) - return out -end - --- Steps 4 and 5 from the guard read (step 3, `GET catalog/books/:id`, server S9/S11): --- { read_status = bool, rating = nil | 1..5 | "clear", reason = text }. -function Finish.plan(job, server_status) - local p = { read_status = true, rating = job.rating, reason = "send" } - if server_status == "read" then - p.read_status, p.reason = false, "already read" - elseif Finish.DELIBERATE[server_status] and server_status ~= job.status_seen then - p.read_status, p.reason = false, "changed elsewhere to " .. server_status - end - return p -end - --- What to do after a failed request: "retry" (backoff, parked after MAX_ATTEMPTS), "auth" --- (keep it, ask to sign in) or "drop" (the server refused it for good). code: HTTP status or nil --- (network error, timeout). -function Finish.onError(job, code, now) - code = tonumber(code) - if code == 401 then return "auth" end - if code == 400 or code == 403 or code == 404 then return "drop" end - job.attempts = (job.attempts or 0) + 1 - local wait = math.min(Finish.BACKOFF_MAX, Finish.BACKOFF_FIRST * 2 ^ (job.attempts - 1)) - job.next_try_at = now + wait - if job.attempts >= Finish.MAX_ATTEMPTS then job.parked = true end - return "retry" -end - --- The day a finish happened, or nil when the clock can't be trusted (G19). -function Finish.day(t, date_fn) - if type(t) ~= "number" or t < 1577836800 then return nil end -- before 2020: unset clock - return (date_fn or os.date)("%Y-%m-%d", t) -end - ----------------------------------------------------------------- next, suggestions, author (§6) - -local function num(v) - if type(v) == "number" then return v end - if type(v) == "string" then return tonumber(v) end - return nil -end - --- The book after this one in its series (detail = `GET catalog/books/:id`, server S13/S14): --- { kind = "next", book = member, read = bool } --- { kind = "gap", number = n } "Book n isn't in your library" (D3: no skip ahead) --- { kind = "series_done" } "You've finished the series" --- { kind = "last_unread", book = m } "Last book · not read yet: Book n" --- nil not in a series -function Finish.next(detail) - if type(detail) ~= "table" then return nil end - local c = num(detail.seriesIndex) - if detail.seriesId == nil or c == nil then return nil end - local after, all_read, first_unread = {}, true, nil - for _, m in ipairs(detail.seriesMembers or {}) do - local i = num(m.seriesIndex) - if m.id ~= detail.id and i ~= nil then - if i > c then table.insert(after, { m = m, i = i }) end - if m.readStatus ~= "read" then - all_read = false - if not first_unread or i < first_unread.i or (i == first_unread.i and m.id < first_unread.m.id) then - first_unread = { m = m, i = i } - end - end - end - end - table.sort(after, function(a, b) if a.i == b.i then return a.m.id < b.m.id end return a.i < b.i end) - local nxt = after[1] - if not nxt then - if all_read or not first_unread then return { kind = "series_done" } end - return { kind = "last_unread", book = first_unread.m, number = first_unread.i } - end - local whole = math.floor(c) + 1 - if nxt.i > whole then return { kind = "gap", number = whole } end - return { kind = "next", book = nxt.m, number = nxt.i, read = nxt.m.readStatus == "read" } -end - --- Suggestions: the first books of relatedSections "author", then "similar", skipping this book, --- the next one and anything read (the related books carry no status, so read is known only from --- seriesMembers). limit: 1 on Android, 2 on Xteink. Each: { book, source = "author"|"similar" }. -function Finish.suggestions(detail, limit, next_id) - local out, skip = {}, { [detail and detail.id or -1] = true } - if next_id then skip[next_id] = true end - for _, m in ipairs(detail and detail.seriesMembers or {}) do - if m.readStatus == "read" then skip[m.id] = true end - end - local by = {} - for _, s in ipairs(detail and detail.relatedSections or {}) do by[s.id] = s end - for _, src in ipairs({ "author", "similar" }) do - for _, b in ipairs(by[src] and by[src].books or {}) do - if #out >= (limit or 1) then return out end - if not skip[b.id] and b.readStatus ~= "read" then - skip[b.id] = true - table.insert(out, { book = b, source = src }) - end - end - end - return out -end - --- The author link (S16: the author list takes a name): authors[1], or nil. -function Finish.author(detail) - local a = detail and detail.authors and detail.authors[1] - if type(a) == "string" and a ~= "" then return a end - return nil -end - --- The words on the card for a picker result. on_device: is that book on this device. -function Finish.nextCard(n, on_device) - if not n then return nil end - if n.kind == "gap" then - return { line = string.format("Book %s isn't in your library", Finish.fmtNum(n.number)) } - elseif n.kind == "series_done" then - return { line = "You've finished the series" } - end - local b = n.book - local head = n.kind == "last_unread" - and string.format("Last book · not read yet: Book %s", Finish.fmtNum(n.number)) - or string.format("Next in series · Book %s%s", Finish.fmtNum(n.number), n.read and " · Read" or "") - return { line = head, title = b.title, book_id = b.id, action = on_device and "open" or "download" } -end - -function Finish.fmtNum(v) - if v == nil then return "?" end - if v == math.floor(v) then return string.format("%d", v) end - return (string.format("%.2f", v):gsub("0+$", "")) -end - ----------------------------------------------------------------- stale-push hold (§7) - --- Hold a progress push for a book finished on this device? final: the finish position (%), --- push: the position about to be sent (%), forward: page turns forward this session, --- released: the reader pressed Undo / Read again. -function Finish.holdPush(final, push, forward, released) - if released or type(final) ~= "number" or type(push) ~= "number" then return false end - if (forward or 0) >= Finish.HOLD_RELEASE_PAGES then return false end - return push <= final - Finish.HOLD_POINTS -end diff --git a/android/koreader/orbit.koplugin/logic/server/bookorbit/group.lua b/android/koreader/orbit.koplugin/logic/server/bookorbit/group.lua deleted file mode 100644 index 4c2b2df1..00000000 --- a/android/koreader/orbit.koplugin/logic/server/bookorbit/group.lua +++ /dev/null @@ -1,385 +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, android/docs/DESIGN.md "Lists by series and by author"). --- BookOrbit's Series and Authors views are server-wide: its sections endpoint takes no list --- (KoreaderCatalogSectionQueryDto whitelists q, page, offset, size, sort, filter). So the --- patch reads a list's books once and groups them here, in the section shape the plugin draws --- (bookorbit_list_data.lua:195-225: count, readingCount, finishedCount, memberStates, --- authorNames, previewBooks, letter), with the server's semantics copied from --- opds-book.service.ts: read buckets (:115-118, readStatusBucket :193-198), the series and --- author filters (:711, :793-797), the name and "most books" orders (:211-231), the A-Z letter --- (latinJumpBucketExpr :200-205) and buckets (first row of each letter, :865-877), series --- members in series order with the first author of each (:965-1035, 40 states, 2 names, --- 3 previews), author previews reading, then finished, then newest (:899-960) and an author's --- series line (their series with the most books, :885-897). Pure (tested). ---------------------------------------------------------------------------------------------- -Group = { PAGE = 100, IDS_MAX = 200, MANIFEST_IDS_MAX = 500, PREVIEWS = 3, MEMBER_STATES = 40, - AUTHOR_NAMES = 2, SECTION_SIZE = 60, STANDALONE = "orbit:standalone", SNAPSHOTS = 6 } - -READING_STATUS = { reading = true, rereading = true, on_hold = true } -FINISHED_STATUS = { read = true, skimmed = true, abandoned = true } - -function Group.bucket(status) - if READING_STATUS[status] then return "reading" end - if FINISHED_STATUS[status] then return "finished" end - return "unread" -end - --- Latin-1 letters with accents, folded (UTF-8 pairs), as bookorbit_unaccent does for these. -FOLD = {} -for from, to in pairs({ A = "ÀÁÂÃÄÅàáâãäå", C = "Çç", E = "ÈÉÊËèéêë", I = "ÌÍÎÏìíîï", N = "Ññ", - O = "ÒÓÔÕÖØòóôõöø", U = "ÙÚÛÜùúûü", Y = "Ýýÿ" }) do - for ch in to:gmatch("[\192-\223][\128-\191]") do FOLD[ch] = to:find(ch, 1, true) and from end -end --- Lower case, accents folded, spaces trimmed: the key names compare and match by. -function Group.fold(s) - s = tostring(s or ""):gsub("^%s+", ""):gsub("%s+$", "") - s = s:gsub("[\192-\223][\128-\191]", function(ch) return FOLD[ch] or ch end) - return s:lower() -end - --- "A".."Z" for a name starting with a (folded) letter, else "#". -function Group.letter(name) - local c = Group.fold(name):sub(1, 1) - if c:match("^[a-z]$") then return c:upper() end - return "#" -end - --- A book's series: its id, or (an older server sends no seriesId) its name. nil: no series. -function Group.seriesKey(book) - if book.seriesId ~= nil then return "id:" .. tostring(book.seriesId) end - local name = book.seriesName - if type(name) == "string" and name:match("%S") then return "name:" .. Group.fold(name) end - return nil -end - --- Series order: the index as a number, then as text, missing last; then title, then id. -function Group.bySeriesIndex(a, b) - local ia, ib = tonumber(a.seriesIndex), tonumber(b.seriesIndex) - if ia ~= ib then - if ia == nil then return false end - if ib == nil then return true end - return ia < ib - end - local sa, sb = tostring(a.seriesIndex or ""), tostring(b.seriesIndex or "") - if sa ~= sb then return sa < sb end - local ta, tb = Group.fold(a.title), Group.fold(b.title) - if ta ~= tb then return ta < tb end - return (tonumber(a.id) or 0) < (tonumber(b.id) or 0) -end - -function counts(books) - local reading, finished = 0, 0 - for _, b in ipairs(books) do - local k = Group.bucket(b.readStatus) - if k == "reading" then reading = reading + 1 elseif k == "finished" then finished = finished + 1 end - end - return reading, finished -end - -function firstN(list, n) - local out = {} - for i = 1, math.min(n, #list) do out[i] = list[i] end - return out -end - --- Books grouped by key(book) (nil: left out), in first-seen order: { key, books }. -function groupBy(books, key) - local groups, by = {}, {} - for _, b in ipairs(books or {}) do - for _, k in ipairs(key(b)) do - local g = by[k] - if not g then g = { key = k, books = {} }; by[k] = g; table.insert(groups, g) end - table.insert(g.books, b) - end - end - return groups -end - --- One series row per series among the books (each book under its primary series only). -function Group.series(books) - local out = {} - for _, g in ipairs(groupBy(books, function(b) local k = Group.seriesKey(b); return k and { k } or {} end)) do - local members = firstN(g.books, #g.books) - table.sort(members, Group.bySeriesIndex) - local first = members[1] - local name = first.seriesName or "" - for _, b in ipairs(members) do if type(b.seriesName) == "string" and b.seriesName ~= "" then name = b.seriesName break end end - local reading, finished = counts(members) - local states, names, seen = {}, {}, {} - for i, b in ipairs(members) do - if i <= Group.MEMBER_STATES then states[i] = Group.bucket(b.readStatus) end - local who = b.authors and b.authors[1] - if who and not seen[who] and #names < Group.AUTHOR_NAMES then seen[who] = true; table.insert(names, who) end - end - local sid = tonumber(first.seriesId) - table.insert(out, { - id = sid and ("series:" .. sid) or name, title = name, section = "series", seriesId = sid, - count = #members, readingCount = reading, finishedCount = finished, - memberStates = states, authorNames = names, previewBooks = firstN(members, Group.PREVIEWS), - letter = Group.letter(name), orbitKey = g.key, - }) - end - return out -end - --- The time a preview orders by: reading by last read, finished by last read, others by added. -function previewTier(b) - local k = Group.bucket(b.readStatus) - if k == "reading" then return 0, b.lastReadAt or "" end - if k == "finished" then return 1, b.lastReadAt or "" end - return 2, b.addedAt or "" -end - -function Group.byPreview(a, b) - local ta, ra = previewTier(a) - local tb, rb = previewTier(b) - if ta ~= tb then return ta < tb end - if ra ~= rb then return ra > rb end - return (tonumber(a.id) or 0) > (tonumber(b.id) or 0) -end - --- One author row per author among the books (a book counts for each of its authors). -function Group.authors(books) - local out = {} - local groups = groupBy(books, function(b) - local keys, seen = {}, {} - for _, a in ipairs(b.authors or {}) do - if type(a) == "string" and a ~= "" and not seen[a] then seen[a] = true; table.insert(keys, a) end - end - return keys - end) - for _, g in ipairs(groups) do - local reading, finished = counts(g.books) - local previews = firstN(g.books, #g.books) - table.sort(previews, Group.byPreview) - -- Their series with the most books here; a tie goes to the name first A-Z. - local top, top_n, top_fold - for _, s in ipairs(groupBy(g.books, function(b) local k = Group.seriesKey(b); return k and { k } or {} end)) do - local name = s.books[1].seriesName or "" - local f = Group.fold(name) - if not top or #s.books > top_n or (#s.books == top_n and f < top_fold) then top, top_n, top_fold = name, #s.books, f end - end - table.insert(out, { - id = g.key, title = g.key, section = "authors", count = #g.books, - readingCount = reading, finishedCount = finished, seriesName = top, - previewBooks = firstN(previews, Group.PREVIEWS), letter = Group.letter(g.key), orbitKey = "author:" .. g.key, - }) - end - return out -end - --- The "Not in a series" row of an author's books by series: always last. -function Group.standalone(books) - local alone = {} - for _, b in ipairs(books or {}) do if Group.seriesKey(b) == nil then table.insert(alone, b) end end - if #alone == 0 then return nil end - local reading, finished = counts(alone) - local states = {} - for i, b in ipairs(alone) do if i <= Group.MEMBER_STATES then states[i] = Group.bucket(b.readStatus) end end - return { id = Group.STANDALONE, title = "Not in a series", section = "series", count = #alone, - readingCount = reading, finishedCount = finished, memberStates = states, authorNames = {}, - previewBooks = firstN(alone, Group.PREVIEWS), letter = "", orbitKey = Group.STANDALONE } -end - --- The server's Reading / Finished filters: a series under way (a book in progress, or some but --- not all finished) or all finished; an author with a book in progress, or one finished. -function Group.keep(e, section, filter) - local n, r, f = e.count or 0, e.readingCount or 0, e.finishedCount or 0 - if filter == "reading" then - if section == "authors" then return r > 0 end - return r > 0 or (f > 0 and f < n) - elseif filter == "finished" then - if section == "authors" then return f > 0 end - return f == n - end - return true -end - --- Name A-Z (or Z-A), or most books first then name A-Z; ties by id. -function Group.sort(entries, sort) - table.sort(entries, function(a, b) - local fa, fb = Group.fold(a.title), Group.fold(b.title) - if sort == "books" and a.count ~= b.count then return a.count > b.count end - if fa ~= fb then - if sort == "name_desc" then return fa > fb end - return fa < fb - end - return tostring(a.id) < tostring(b.id) - end) - return entries -end - --- One page of rows, as the sections endpoint answers it. params: the plugin's section --- request (q, sort, filter, size, offset or page; bookorbit_catalog_lists.lua:246-260). --- A section of an author's books adds the "Not in a series" row last. -function Group.sectionBody(rows, section, params, extra_last) - params = params or {} - local sort = params.sort or "name" - local q = params.q and Group.fold(params.q) or "" - local list = {} - for _, e in ipairs(rows) do - if (q == "" or Group.fold(e.title):find(q, 1, true)) and Group.keep(e, section, params.filter) then - table.insert(list, e) - end - end - Group.sort(list, sort) - local buckets - if sort ~= "books" then - buckets = {} - local seen = {} - for i, e in ipairs(list) do - if not seen[e.letter] then seen[e.letter] = true; table.insert(buckets, { key = e.letter, index = i - 1 }) end - end - end - if extra_last and q == "" and Group.keep(extra_last, "series", params.filter) then table.insert(list, extra_last) end - local size = tonumber(params.size) or Group.SECTION_SIZE - local offset = tonumber(params.offset) or ((tonumber(params.page) or 1) - 1) * size - local items = {} - for i = offset + 1, math.min(#list, offset + size) do table.insert(items, list[i]) end - return { - items = items, total = #list, size = size, sort = sort, filter = params.filter, buckets = buckets, - page = math.floor(offset / size) + 1, offset = params.offset ~= nil and offset or nil, - hasNext = offset + size < #list, hasPrevious = offset > 0, query = params.q, - } -end - --- The books of one row: an author's, a series', or (STANDALONE) an author's outside a series. -function Group.select(books, author, key) - local out = {} - for _, b in ipairs(books or {}) do - local by = author == nil - if not by then for _, a in ipairs(b.authors or {}) do if a == author then by = true break end end end - local sk = Group.seriesKey(b) - local in_key = key == nil or (key == Group.STANDALONE and sk == nil) or (key ~= Group.STANDALONE and sk == key) - if by and in_key then table.insert(out, b) end - end - return out -end - --- Which list a book list is: { section, id } from its params, or nil (a search, a series or an --- author page, a list by id). Every other book list is the whole library with its filters --- (All books, Recently updated, Recently added...): { section = "all" } (v0.11.2). -function Group.listOf(params) - params = params or {} - if params.smartScopeId then return { section = "smart-scopes", id = tonumber(params.smartScopeId) } end - if params.collectionId then return { section = "collections", id = tonumber(params.collectionId) } end - if params.libraryId then return { section = "libraries", id = tonumber(params.libraryId) } end - -- On device: the plugin's list of this reader's books by id (bookorbit_catalog.lua:1187-1206, - -- ids capped at 200 by the server, koreader-catalog-query.dto.ts:114). Its rows drill by id. - if params.on_device_filter and params.ids and params.ids ~= "" then return { section = "on-device" } end - local function set(v) return v ~= nil and tostring(v) ~= "" end - if set(params.q) or set(params.ids) or set(params.seriesId) or set(params.series) or set(params.author) then return nil end - return { section = "all" } -end - --- The request for every book of the list, page by page: its params with the list's filters. -FETCH_DROP = { page = true, size = true, offset = true, sort = true, order = true, buckets = true, on_device_filter = true } -function Group.fetchParams(params, page) - local q = {} - for k, v in pairs(params or {}) do - if not FETCH_DROP[k] and not tostring(k):match("^orbit") then q[k] = v end - end - q.sort, q.size, q.page = "title", Group.PAGE, page or 1 - return q -end - --- Book ids, ascending, joined for the ids parameter. -function Group.ids(books, max) - local ids = {} - for _, b in ipairs(books) do table.insert(ids, tonumber(b.id)) end - table.sort(ids) - if max and #ids > max then for i = #ids, max + 1, -1 do ids[i] = nil end end - return table.concat(ids, ",") -end - --- The request for some of a list's books (a row tapped in the grouped view). --- list: { section, id }; list_params: the list's own params (its filters); books: those books; --- target: what the page is (seriesId/series, author, sort); marks: orbit* keys to carry. --- A library or collection: the server ANDs libraryId / collectionId with the target --- (opds-book.service.ts:378-395), with the list's filters. A smart scope: the server drops --- every other filter when smartScopeId is set (:368-375), so the books go by id instead (ids --- caps at 200, koreader-catalog-query.dto.ts:114); past that the patch serves them from the --- books it holds (orbitLocal). flat: always by id (a flat book list, not the author page). -function Group.drill(list, list_params, books, target, marks, flat) - local p = {} - for k, v in pairs(target or {}) do p[k] = v end - for k, v in pairs(marks or {}) do p[k] = v end - if not flat and list.section ~= "smart-scopes" and list.section ~= "on-device" then - for _, k in ipairs({ "libraryId", "collectionId", "readStatus", "format", "ids" }) do - if list_params[k] ~= nil then p[k] = list_params[k] end - end - return p, "server" - end - if #books <= Group.IDS_MAX then - p.ids = Group.ids(books) - return p, "ids" - end - p.orbitLocal = "1" - return p, "held" -end - --- A page of the held books (orbitLocal), as the books endpoint answers it. -SORT_KEY = { - title = function(b) return Group.fold(b.title) end, - author = function(b) return Group.fold(b.authors and b.authors[1]) end, - series = function(b) return Group.fold(b.seriesName) end, - recently_added = function(b) return b.addedAt or "" end, - recently_read = function(b) return b.lastReadAt or "" end, -} -NATURAL = { recently_added = "desc", recently_read = "desc", recently_updated = "desc", published = "desc" } -function Group.booksBody(books, params) - params = params or {} - local list = {} - for _, b in ipairs(books or {}) do - local k = Group.bucket(b.readStatus) - if params.readStatus == nil or k == params.readStatus then table.insert(list, b) end - end - local sort = SORT_KEY[params.sort] and params.sort or "series" - local desc = (params.order or NATURAL[params.sort] or "asc") == "desc" - table.sort(list, function(a, b) - local ka, kb = SORT_KEY[sort](a), SORT_KEY[sort](b) - if ka ~= kb then if desc then return ka > kb end return ka < kb end - return Group.bySeriesIndex(a, b) - end) - local size = tonumber(params.size) or 20 - local offset = tonumber(params.offset) or ((tonumber(params.page) or 1) - 1) * size - local items = {} - for i = offset + 1, math.min(#list, offset + size) do table.insert(items, list[i]) end - return { items = items, total = #list, size = size, page = math.floor(offset / size) + 1, - offset = params.offset ~= nil and offset or nil, hasNext = offset + size < #list, hasPrevious = offset > 0 } -end - --- Lists read for the grouped views, by token: { list, params, title, books }. A few at a time --- (the oldest goes); the token rides in the request params (orbitGroup), never to the server. -Group.held, Group.order, Group.next = {}, {}, 0 -function Group.remember(snap) - Group.next = Group.next + 1 - local token = "g" .. Group.next - Group.held[token] = snap - table.insert(Group.order, token) - while #Group.order > Group.SNAPSHOTS do Group.held[table.remove(Group.order, 1)] = nil end - return token -end - --- Request params never sent: the patch's own marks. -function Group.strip(params) - if type(params) ~= "table" then return params end - local has = false - for k in pairs(params) do if tostring(k):match("^orbit") then has = true break end end - if not has then return params end - local out = {} - for k, v in pairs(params) do if not tostring(k):match("^orbit") then out[k] = v end end - return out -end - --- The books a request with orbitLocal means: the held list, narrowed by its marks. -function Group.localBooks(params) - local snap = Group.held[params.orbitGroup or ""] - if not snap then return nil end - local key = params.orbitSeries - return Group.select(snap.books, params.orbitAuthor, key ~= "" and key or nil) -end diff --git a/android/koreader/orbit.koplugin/logic/server/bookorbit/localfirst.lua b/android/koreader/orbit.koplugin/logic/server/bookorbit/localfirst.lua deleted file mode 100644 index 6a352eab..00000000 --- a/android/koreader/orbit.koplugin/logic/server/bookorbit/localfirst.lua +++ /dev/null @@ -1,349 +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"). - --- Local-first Home (docs/design/local-first/DESIGN.md, ROADMAP 3): the overlay of this device's --- reading state on a copy of the dashboard body, the freshness stamp, and the per-tile content --- keys that decide what a refresh repaints. Pure: no KOReader modules. Table-tested from --- shared/fixtures/localfirst/ (test_logic.lua). Display only: nothing here writes to the server. ---------------------------------------------------------------------------------------------- - -LocalFirst = {} - --- "2026-11-20T19:02:11.000Z" -> epoch seconds (UTC), or nil. -function LocalFirst.parseIso(s) - if type(s) ~= "string" then return nil end - local y, mo, d, h, mi, se = s:match("^(%d%d%d%d)-(%d%d)-(%d%d)[T ](%d%d):(%d%d):(%d%d)") - if not y then - y, mo, d = s:match("^(%d%d%d%d)-(%d%d)-(%d%d)$") - if not y then return nil end - h, mi, se = 0, 0, 0 - end - y, mo, d = tonumber(y), tonumber(mo), tonumber(d) - -- Days from civil (H. Hinnant), so no os.time() and no local time zone. - local yy = mo <= 2 and y - 1 or y - local era = math.floor(yy / 400) - local yoe = yy - era * 400 - local mp = (mo + 9) % 12 - local doy = math.floor((153 * mp + 2) / 5) + d - 1 - local doe = yoe * 365 + math.floor(yoe / 4) - math.floor(yoe / 100) + doy - local days = era * 146097 + doe - 719468 - return days * 86400 + tonumber(h) * 3600 + tonumber(mi) * 60 + tonumber(se) -end - --- KOReader's summary.status -> the server's readStatus. -LocalFirst.STATUS = { complete = "read", reading = "reading", abandoned = "abandoned" } - --- Book ids reach us as numbers (the server body) or strings (the plugin's state): one key each. -local function idKey(id) return id ~= nil and tostring(id) or nil end - --- "Device wins while newer" (design "Shared concepts"): the device's value is shown when its --- change is newer than the server's lastReadAt, or still waits to upload. -function LocalFirst.deviceWins(server_book, loc) - if type(loc) ~= "table" then return false end - if loc.pending then return true end - local srv = LocalFirst.parseIso(server_book and server_book.lastReadAt) or 0 - return (loc.changedAt or 0) > srv -end - -local function copy(t) - local o = {} - for k, v in pairs(t) do o[k] = v end - return o -end - --- One book, overlaid when the device wins. Returns the copy and whether it changed. -function LocalFirst.overlayBook(book, loc) - if type(book) ~= "table" or not LocalFirst.deviceWins(book, loc) then return book, false end - local b = copy(book) - if type(loc.percent) == "number" then b.progressPercentage = loc.percent end - local st = LocalFirst.STATUS[loc.status] - if st then b.readStatus = st end - b.orbit_local = true - return b, true -end - -local function overlayList(list, by_id) - if type(list) ~= "table" then return list end - local out = {} - for i, b in ipairs(list) do - out[i] = (type(b) == "table" and b.id ~= nil) and (LocalFirst.overlayBook(b, by_id[b.id])) or b - end - return out -end - --- Every saved record of a book in the body (any list), so a book started here that the server's --- Continue reading lacks can be added without inventing a title or cover. -local function records(body) - local out = {} - local function add(list) - for _, b in ipairs(type(list) == "table" and list or {}) do - if type(b) == "table" and b.id ~= nil and not out[idKey(b.id)] then out[idKey(b.id)] = b end - end - end - add(body.continueReading); add(body.finishedThisYear); add(body.discover) - for _, list in pairs(type(body.boardShelves) == "table" and body.boardShelves or {}) do add(list) end - if type(body.yearAgo) == "table" then add({ body.yearAgo.book }) end - return out -end - --- The overlaid copy of a dashboard body. state.byBookId: { [bookId] = { percent (0-100), --- status ("reading"|"complete"|"abandoned"), changedAt (epoch s), pending, blocked, retrying } }. --- extra: more saved records (list pages) by id. Never modifies body. --- Shelves that list books being read: a book finished (or put down) here leaves them at once. -LocalFirst.READING_SHELVES = { ["in-progress"] = true, ["pick-back-up"] = true } - -local function byKey(by_id) - local out = setmetatable({}, { __index = function(t, k) - if type(k) ~= "string" and k ~= nil then return rawget(t, tostring(k)) end - end }) - for k, v in pairs(by_id or {}) do out[tostring(k)] = v end - return out -end - -function LocalFirst.overlay(body, state, extra) - if type(body) ~= "table" then return body end - local by_id = byKey(state and state.byBookId) - local out = copy(body) - local known = records(body) - for id, b in pairs(extra or {}) do if not known[idKey(id)] then known[idKey(id)] = b end end - - -- Continue reading: overlay; a book finished here leaves; one read here more recently than - -- the head moves to the front; a book started here joins only with a saved record. - local cr, seen = {}, {} - for _, b in ipairs(type(body.continueReading) == "table" and body.continueReading or {}) do - local o = LocalFirst.overlayBook(b, by_id[b.id]) - seen[idKey(b.id)] = true - if o.readStatus ~= "read" and o.readStatus ~= "abandoned" then table.insert(cr, o) end - end - for id, loc in pairs(by_id) do - if not seen[id] and loc.status == "reading" and known[id] then - local o = LocalFirst.overlayBook(known[id], loc) - if o ~= known[id] then table.insert(cr, o) end - end - end - local function recent(b) - local loc = by_id[b.id] - local srv = LocalFirst.parseIso(b.lastReadAt) or 0 - if b.orbit_local and loc then return math.max(loc.changedAt or 0, srv) end - return srv - end - local order = {} - for i, b in ipairs(cr) do order[b] = i end - table.sort(cr, function(a, b) - local ra, rb = recent(a), recent(b) - if a.orbit_local or b.orbit_local then - if ra ~= rb then return ra > rb end - end - return order[a] < order[b] - end) - out.continueReading = cr - - -- Finished: pending local finishes join the front and count toward the goal until the - -- server knows (the Xteink Home's localFinishedAtFetch rule). - local finished = overlayList(body.finishedThisYear, by_id) - local in_finished = {} - for _, b in ipairs(finished or {}) do if type(b) == "table" then in_finished[idKey(b.id)] = true end end - local added, front = 0, {} - local ids = {} - for id in pairs(by_id) do table.insert(ids, id) end - table.sort(ids, function(a, b) return (by_id[a].changedAt or 0) > (by_id[b].changedAt or 0) end) - for _, id in ipairs(ids) do - local loc = by_id[id] - if loc.status == "complete" and loc.pending and not in_finished[id] then - local srv = known[id] - if not (srv and srv.readStatus == "read") then - added = added + 1 - if srv then table.insert(front, (LocalFirst.overlayBook(srv, loc))) end - end - end - end - if finished then - for i = #front, 1, -1 do table.insert(finished, 1, front[i]) end - out.finishedThisYear = finished - end - if added > 0 and type(body.readingGoal) == "table" then - out.readingGoal = copy(body.readingGoal) - out.readingGoal.completedBooks = (tonumber(body.readingGoal.completedBooks) or 0) + added - end - - out.discover = overlayList(body.discover, by_id) - if type(body.boardShelves) == "table" then - out.boardShelves = {} - for k, list in pairs(body.boardShelves) do - local o = overlayList(list, by_id) - if LocalFirst.READING_SHELVES[k] and type(o) == "table" then - local kept = {} - for _, b in ipairs(o) do - if not (type(b) == "table" and b.orbit_local and (b.readStatus == "read" or b.readStatus == "abandoned")) then - table.insert(kept, b) - end - end - o = kept - end - out.boardShelves[k] = o - end - end - if type(body.yearAgo) == "table" and type(body.yearAgo.book) == "table" then - out.yearAgo = copy(body.yearAgo) - out.yearAgo.book = LocalFirst.overlayBook(body.yearAgo.book, by_id[body.yearAgo.book.id]) - end - out.orbit_overlay = true - return out -end - --- The "not synced" mark (lists only): with auto-sync on, only while the upload is blocked or --- retrying; with it off, whenever the change waits. -function LocalFirst.notSynced(loc, auto_sync) - if type(loc) ~= "table" then return false end - if loc.blocked or loc.retrying then return true end - return (not auto_sync) and loc.pending == true -end - ----------------------------------------------------------------- freshness stamp - --- "just now", "12 min ago", "3 h ago", "2 d ago" (ages in min, h and d, as the Xteink Home tile). -function LocalFirst.age(seconds) - seconds = math.max(0, seconds or 0) - if seconds < 60 then return "just now" end - if seconds < 3600 then return string.format("%d min ago", math.floor(seconds / 60)) end - if seconds < 86400 then return string.format("%d h ago", math.floor(seconds / 3600)) end - return string.format("%d d ago", math.floor(seconds / 86400)) -end - --- s: { online, fetched_at (epoch s or nil), now, failed (the last refresh got no answer) }. -function LocalFirst.stamp(s) - if not s.fetched_at then - if not s.online then return "Offline" end - return s.failed and "Not updated" or nil - end - local age = LocalFirst.age((s.now or 0) - s.fetched_at) - if not s.online then return "Offline, saved " .. age end - if s.failed then return "Not updated · saved " .. age end - return "updated " .. age -end - ----------------------------------------------------------------- what a refresh repaints - --- A stable string for a Lua value (sorted keys; functions and widgets skipped). -function LocalFirst.serialize(v, depth) - depth = depth or 0 - local t = type(v) - if t == "string" then return string.format("%q", v) end - if t == "number" or t == "boolean" or t == "nil" then return tostring(v) end - if t ~= "table" or depth > 6 then return "?" end - local keys = {} - for k in pairs(v) do - if type(k) ~= "table" and type(v[k]) ~= "function" then table.insert(keys, k) end - end - table.sort(keys, function(a, b) return tostring(a) < tostring(b) end) - local parts = {} - for _, k in ipairs(keys) do - table.insert(parts, tostring(k) .. "=" .. LocalFirst.serialize(v[k], depth + 1)) - end - return "{" .. table.concat(parts, ",") .. "}" -end - -local function booksKey(list) - local parts = {} - for _, b in ipairs(type(list) == "table" and list or {}) do - local pct = tonumber(b.progressPercentage) - table.insert(parts, table.concat({ tostring(b.id), pct and tostring(math.floor(pct + 0.5)) or "-", - tostring(b.readStatus), b.on_device and "d" or "", tostring(b.cover_state) }, ":")) - end - return table.concat(parts, ",") -end - --- Tile types that repaint on their own timers: no content key (they never repaint for a refresh). -LocalFirst.TIMER_TILES = { clock = true, light = true, word = true } - --- The content key of one tile: the data that tile draws, from the board data d (overlaid). Any --- type not listed keys on the whole of d, so a new upstream widget is never left stale. -function LocalFirst.tileKey(kind, d, source) - if LocalFirst.TIMER_TILES[kind] then return "" end - if kind == "hero" or kind == "also" or kind == "forecast" then - return booksKey(d.continue_reading) - elseif kind == "shelf" then - return booksKey(d.shelves and d.shelves[source or ""]) - elseif kind == "goalpace" then - local g = d.goal or {} - return table.concat({ tostring(g.books), tostring(g.done), tostring(g.year) }, ":") - elseif kind == "streak" or kind == "week" or kind == "today" or kind == "heatmap" or kind == "calendar" then - return table.concat({ tostring(d.streak and d.streak.current), tostring(d.week_min), tostring(d.today_min) }, ":") - elseif kind == "sync" then - return tostring(d.last_sync_at) .. ":" .. tostring(d.online) - elseif kind == "link" then - return LocalFirst.serialize(d.counts) - elseif kind == "highlight" then - return LocalFirst.serialize(d.highlight) - elseif kind == "yearago" then - return LocalFirst.serialize(d.year_ago) - elseif kind == "records" or kind == "hours" then - return LocalFirst.serialize({ d.streak, d.heatmap }) - end - local stripped = {} - for k, v in pairs(d) do - if k ~= "now" and k ~= "clock" and k ~= "fingerprint" and k ~= "greeting" and k ~= "updated" then stripped[k] = v end - end - return LocalFirst.serialize(stripped) -end - --- What changed in one tile, for the log: per book "book -> " (percent, --- status, on device, cover), books added or removed, the order; else "content". -local BOOK_FIELDS = { "id", "percent", "status", "on device", "cover" } -local function split(s, sep) - local out = {} - if s == "" then return out end - for part in (s .. sep):gmatch("(.-)" .. sep) do table.insert(out, part) end - return out -end -function LocalFirst.tileDiff(kind, old_d, new_d, source) - local a, b = LocalFirst.tileKey(kind, old_d, source), LocalFirst.tileKey(kind, new_d, source) - if a == b then return nil end - if not (kind == "hero" or kind == "also" or kind == "forecast" or kind == "shelf") then return "content" end - local old_by, old_order, new_order, out = {}, {}, {}, {} - for _, part in ipairs(split(a, ",")) do - local f = split(part, ":") - old_by[f[1]] = f - table.insert(old_order, f[1]) - end - local seen = {} - for _, part in ipairs(split(b, ",")) do - local f = split(part, ":") - seen[f[1]] = true - table.insert(new_order, f[1]) - local o = old_by[f[1]] - if not o then - table.insert(out, "book " .. f[1] .. " added") - else - for j = 2, #BOOK_FIELDS do - if o[j] ~= f[j] then - local function show(v) - if j == 4 then return v == "d" and "yes" or "no" end - return (v == nil or v == "") and "-" or v - end - table.insert(out, string.format("book %s %s %s -> %s", f[1], BOOK_FIELDS[j], show(o[j]), show(f[j]))) - end - end - end - end - for _, id in ipairs(old_order) do if not seen[id] then table.insert(out, "book " .. id .. " removed") end end - if #out == 0 and table.concat(old_order, ",") ~= table.concat(new_order, ",") then table.insert(out, "order") end - return #out > 0 and table.concat(out, "; ") or "content" -end - --- Which tiles changed between two boards. tiles: { { key = id, kind, source } } (the same set on --- both). Returns the changed ids, or nil when the tile set itself differs (a full repaint). -function LocalFirst.changedTiles(old_tiles, new_tiles, old_d, new_d) - if #old_tiles ~= #new_tiles then return nil end - local changed = {} - for i, t in ipairs(new_tiles) do - local o = old_tiles[i] - if o.key ~= t.key or o.kind ~= t.kind or o.source ~= t.source then return nil end - if LocalFirst.tileKey(t.kind, old_d, t.source) ~= LocalFirst.tileKey(t.kind, new_d, t.source) then - table.insert(changed, t.key) - end - end - return changed -end diff --git a/android/koreader/orbit.koplugin/logic/server/bookorbit/recommended.lua b/android/koreader/orbit.koplugin/logic/server/bookorbit/recommended.lua deleted file mode 100644 index 9d47ec9a..00000000 --- a/android/koreader/orbit.koplugin/logic/server/bookorbit/recommended.lua +++ /dev/null @@ -1,209 +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 (docs/design/addon-mode.md §5). Pure: the KOReader side --- (ko/server/bookorbit/recommended.lua) observes each item and writes it; this file decides. --- --- The rule, the same in every mode: an item still at its stock default is applied (with a --- backup); an item the user changed is never overwritten, only listed for review; an item whose --- plugin or capability is missing waits. A pass looks only at items no earlier pass settled --- (new ids in a later release, or items that were unavailable), so a setting the user changes --- by hand later is never changed back. ---------------------------------------------------------------------------------------------- - -Recommended = { REV = 1 } - --- kind: "bo" (the BookOrbit plugin's settings), "ko" (a KOReader global setting), "gesture" (a --- KOReader gesture in books). needs: a companion capability (docs/design/addon-mode.md §6.1). --- untouched_only: at default only when the pass finds KOReader untouched (no conflicts at all). --- required_by: the capability that can't work without it (its conflict offers to turn that off). -Recommended.ITEMS = { - { id = "bo.auto_sync", kind = "bo", key = "auto_sync", ours = true, label = "BookOrbit › Auto-sync" }, - { id = "bo.sync_forward", kind = "bo", key = "sync_forward", ours = Plan.STRATEGY.SILENT, - label = "BookOrbit › When BookOrbit is further ahead" }, - { id = "bo.home", kind = "bo", key = "catalog_auto_open", ours = "home", label = "BookOrbit › Make BookOrbit home" }, - { id = "ko.wifi_on", kind = "ko", key = "wifi_enable_action", ours = "turn_on", stock = "prompt", - needs = "wifi", required_by = "wifi", label = "KOReader › Action when Wi-Fi is off" }, - { id = "g.sync_sleep", kind = "gesture", key = "hold_top_right_corner", ours = { orbit_sync_and_sleep = true }, - label = "Gesture in books: hold top-right corner" }, - { id = "g.sync_all", kind = "gesture", key = "hold_top_left_corner", ours = { bookorbit_sync_now = true }, - label = "Gesture in books: hold top-left corner" }, - -- KOReader has no one-finger "swipe up from the bottom"; this bottom-edge swipe is the nearest. - { id = "g.this_book", kind = "gesture", key = "one_finger_swipe_bottom_edge_right", ours = { bookorbit_this_book = true }, - label = "Gesture in books: swipe right along the bottom edge" }, - -- KOReader's default here is "brighter frontlight" on devices with a light (gestures defaults.lua:62). - { id = "g.apps", kind = "gesture", key = "two_finger_swipe_north", ours = { orbit_open_apps = true }, needs = "apps", - label = "Gesture in books: two-finger swipe up" }, -} - -function Recommended.item(id) - for _, it in ipairs(Recommended.ITEMS) do if it.id == id then return it end end -end - --- Deep equality, nil-safe (util.tableEquals semantics, gestures.koplugin main.lua:310-312). -function Recommended.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 Recommended.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 - -function Recommended.copy(v) - if type(v) ~= "table" then return v end - local out = {} - for k, x in pairs(v) do out[k] = Recommended.copy(x) end - return out -end - --- obs: { current, default, stock } (stock: another value KOReader treats as its default). --- Returns "already" | "at_default" | "conflict". -function Recommended.classify(item, obs) - if Recommended.equal(obs.current, item.ours) then return "already" end - if Recommended.equal(obs.current, obs.default) then return "at_default" end - if item.stock ~= nil and Recommended.equal(obs.current, item.stock) then return "at_default" end - return "conflict" -end - --- Items a pass looks at: never settled, or unavailable last time. only: { [id] = true } or nil. -function Recommended.candidates(items, record, only) - local seen = type(record) == "table" and type(record.items) == "table" and record.items or {} - local out = {} - for _, it in ipairs(items) do - local st = seen[it.id] - if (st == nil or st == "unavailable") and (not only or only[it.id]) then table.insert(out, it) end - end - return out -end - --- observe(item) -> { available = bool, reason, current, default }. Returns --- { decisions = { { item, state, obs } }, applied = n, conflicts = n, unavailable = n }. --- The mode is not an input: the same KOReader gives the same plan in every mode. -function Recommended.plan(items, record, observe, only) - local out = { decisions = {}, applied = 0, conflicts = 0, unavailable = 0 } - local later = {} - local function decide(it, state, obs) - table.insert(out.decisions, { item = it, state = state, obs = obs }) - if state == "at_default" then out.applied = out.applied + 1 - elseif state == "conflict" then out.conflicts = out.conflicts + 1 - elseif state == "unavailable" then out.unavailable = out.unavailable + 1 end - end - for _, it in ipairs(Recommended.candidates(items, record, only)) do - local obs = observe(it) or { available = false, reason = "unknown" } - if not obs.available then decide(it, "unavailable", obs) - else - local state = Recommended.classify(it, obs) - if it.untouched_only and state == "at_default" then table.insert(later, { it, obs }) - else decide(it, state, obs) end - end - end - -- An item with no stock default of its own: at default only on a KOReader with no changed - -- values at all (this pass's conflicts, or any the user kept before). - local touched = out.conflicts > 0 - local seen = type(record) == "table" and type(record.items) == "table" and record.items or {} - for _, st in pairs(seen) do if st == "conflict" or st == "kept" then touched = true end end - for _, l in ipairs(later) do decide(l[1], touched and "conflict" or "at_default", l[2]) end - return out -end - -local STATUS = { at_default = "applied", already = "already", conflict = "conflict", unavailable = "unavailable" } - --- The record after a plan: S.recommended = { rev, at, items = { [id] = status }, unseen }. --- applied_ok: { [id] = false } for an apply that failed (it stays unavailable). -function Recommended.record(record, plan, now, applied_ok) - record = type(record) == "table" and record or {} - record.items = type(record.items) == "table" and record.items or {} - record.rev, record.at = Recommended.REV, now - local applied = 0 - for _, d in ipairs(plan.decisions) do - local st = STATUS[d.state] - if d.state == "at_default" and applied_ok and applied_ok[d.item.id] == false then st = "unavailable" - elseif d.state == "at_default" then applied = applied + 1 end - record.items[d.item.id] = st - end - record.unseen = (record.unseen or 0) + applied - return record, applied -end - --- The backup kept before an apply (S.recommended_backup[id]). -function Recommended.backup(obs, item, now) - return { had = obs.current ~= nil, prior = Recommended.copy(obs.current), ours = Recommended.copy(item.ours), at = now } -end - --- Undo restores the prior value only while the current one is still ours. -function Recommended.undoable(entry, current) - return type(entry) == "table" and Recommended.equal(current, entry.ours) -end - --- Counts of each status in the record. -function Recommended.counts(record) - local c = { applied = 0, already = 0, conflict = 0, kept = 0, unavailable = 0 } - local items = type(record) == "table" and type(record.items) == "table" and record.items or {} - for _, st in pairs(items) do c[st] = (c[st] or 0) + 1 end - return c -end - --- For the companion's row (REPORT recommended=): none (no pass yet), partial (conflicts to --- review), reviewed (the user kept some of theirs), applied. -function Recommended.reportState(record) - if type(record) ~= "table" or type(record.items) ~= "table" or next(record.items) == nil then return "none" end - local c = Recommended.counts(record) - if c.conflict > 0 then return "partial" end - if c.kept > 0 then return "reviewed" end - return "applied" -end - --- The one line: "Applied 7 recommended settings · Review", "Applied 4 · 2 to review", --- "Review 2 recommended settings", or nil (nothing to say). -function Recommended.lineText(applied, conflicts) - applied, conflicts = applied or 0, conflicts or 0 - if applied > 0 and conflicts > 0 then return string.format("Applied %d · %d to review", applied, conflicts) end - if applied > 0 then - return string.format(applied == 1 and "Applied %d recommended setting · Review" or "Applied %d recommended settings · Review", applied) - end - if conflicts > 0 then - return string.format(conflicts == 1 and "Review %d recommended setting" or "Review %d recommended settings", conflicts) - end - return nil -end - --- Items to undo when capabilities go away (Full → Add-on): applied by Orbit, needing a cap now lost. -function Recommended.lostCaps(record, has) - local out = {} - local items = type(record) == "table" and type(record.items) == "table" and record.items or {} - for _, it in ipairs(Recommended.ITEMS) do - if it.needs and items[it.id] == "applied" and not has(it.needs) then table.insert(out, it) end - end - return out -end - --- Plain words for a value (the review page). -local LABELS = { - auto_sync = function(v) return v and "On" or "Off" end, - sync_forward = function(v) return ({ [1] = "Ask", [2] = "Silent", [3] = "Don't sync" })[v] or tostring(v) end, - catalog_auto_open = function(v) - return ({ off = "Off", filemanager = "File browser", home = "BookOrbit home" })[v] or tostring(v) - end, - wifi_enable_action = function(v) return ({ turn_on = "Turn on", prompt = "Ask", ignore = "Ignore" })[v or "prompt"] or tostring(v) end, -} -local ACTIONS = { - orbit_sync_and_sleep = "BookSync: Sync and sleep", bookorbit_sync_now = "BookOrbit: sync all books", - bookorbit_this_book = "BookOrbit: this book", orbit_open_apps = "BookSync: other apps", - increase_frontlight = "Brighter frontlight", toggle_page_flipping = "Page flipping", -} -function Recommended.valueLabel(item, v) - if item.kind == "gesture" then - if type(v) ~= "table" or next(v) == nil then return "Nothing" end - local names = {} - for k in pairs(v) do table.insert(names, ACTIONS[k] or k) end - table.sort(names) - return table.concat(names, " + ") - end - local f = LABELS[item.key] - if f then return f(v) end - return tostring(v) -end - ---------------------------------------------------------------------------------------------- diff --git a/android/koreader/orbit.koplugin/logic/wifi_plan.lua b/android/koreader/orbit.koplugin/logic/wifi_plan.lua index f1bdfe8f..3ac8e5a7 100644 --- a/android/koreader/orbit.koplugin/logic/wifi_plan.lua +++ b/android/koreader/orbit.koplugin/logic/wifi_plan.lua @@ -100,7 +100,6 @@ function WifiPlan.wifiOff(st) end -- ctx = { now, wifi_on, busy, screen_off, browsing }. Returns action ("off" | nil), reason, force. --- browsing: BookOrbit's catalog is on top (Home opens over the book): not reading, so the -- "done in a book" offs wait; just in time's idle rule still applies. -- force: off_reading's book-open off, which applies even to Wi-Fi turned on by hand. -- Never off while a flow holds the network, the plugin or a download is busy, or (except diff --git a/android/koreader/orbit.koplugin/main.lua b/android/koreader/orbit.koplugin/main.lua index 9604b3c6..1777b32f 100644 --- a/android/koreader/orbit.koplugin/main.lua +++ b/android/koreader/orbit.koplugin/main.lua @@ -24,20 +24,19 @@ local PATCH_VERSION = "0.0.0-dev" local LOGIC = { "logic/schedule.lua", "logic/plan.lua", "logic/update.lua", "logic/wifi_plan.lua", - "logic/home_plan.lua", "logic/server/bookorbit/compat.lua", "logic/stats.lua", "logic/clicks.lua", - "logic/prompts.lua", "logic/server/bookorbit/group.lua", "logic/server/bookorbit/finish.lua", "logic/server/bookorbit/localfirst.lua", "logic/sheet_layout.lua", "logic/cache.lua", "logic/server/bookorbit/cache.lua", - "logic/server/bookorbit/recommended.lua", "logic/caps.lua", "logic/copies.lua", "logic/sleep_pool.lua", "logic/settings_sync.lua", + "logic/home_plan.lua", "logic/native.lua", "logic/stats.lua", "logic/clicks.lua", + "logic/prompts.lua", "logic/sheet_layout.lua", "logic/cache.lua", "logic/caps.lua", "logic/copies.lua", "logic/sleep_pool.lua", "logic/settings_sync.lua", "logic/orbismart.lua", "logic/status_layout.lua", "logic/reading_style.lua", "logic/account.lua", "logic/settings_ui.lua", "logic/reader_panel.lua", "logic/budgets.lua", "logic/widget_registry.lua", "logic/layout.lua", "logic/filter_sheet.lua", "logic/reading_stats.lua", "logic/local_widgets.lua", "logic/storage.lua", "logic/battery_widget.lua", "logic/home_host.lua", "logic/home_editor.lua", "logic/booklist.lua", "logic/series.lua", } local KO = { - "ko/base.lua", "ko/settings.lua", "ko/jni.lua", "ko/companion.lua", "ko/shared.lua", - "ko/server/bookorbit/quiesce.lua", "ko/server/bookorbit.lua", "ko/net.lua", "ko/wifi.lua", "ko/updater.lua", + "ko/base.lua", "ko/jni.lua", "ko/companion.lua", "ko/library_bootstrap.lua", "ko/retirement.lua", "ko/settings.lua", "ko/shared.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/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/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", } @@ -70,7 +69,7 @@ if rawget(_G, "ORBIT_ANDROID_TEST") then return { Schedule = env.Schedule, Plan = env.Plan, Update = env.Update, WifiPlan = env.WifiPlan, HomePlan = env.HomePlan, disabledText = env.disabledText, Compat = env.Compat, Stats = env.Stats, Clicks = env.Clicks, SetupPrompt = env.SetupPrompt, MenuLock = env.MenuLock, - SeriesPlan = env.SeriesPlan, ReadingStyle = env.ReadingStyle, BookList = env.BookList, HomeEditorPlan = env.HomeEditorPlan, Layout = env.Layout, WidgetRegistry = env.WidgetRegistry, Budgets = env.Budgets, FilterSheet = env.FilterSheet, RestartPlan = env.RestartPlan, Group = env.Group, Finish = env.Finish, LocalFirst = env.LocalFirst, Cache = env.Cache, ServerCache = env.ServerCache, SheetLayout = env.SheetLayout, Recommended = env.Recommended, Caps = env.Caps, CopiesPlan = env.CopiesPlan, SleepPool = env.SleepPool, SettingsSync = env.SettingsSync, OrbiSmart = env.OrbiSmart, StatusLayout = env.StatusLayout, BatteryGlyph = env.BatteryGlyph, PATCH_VERSION = PATCH_VERSION } + SeriesPlan = env.SeriesPlan, ReadingStyle = env.ReadingStyle, BookList = env.BookList, HomeEditorPlan = env.HomeEditorPlan, Layout = env.Layout, WidgetRegistry = env.WidgetRegistry, Budgets = env.Budgets, FilterSheet = env.FilterSheet, RestartPlan = env.RestartPlan, Cache = env.Cache, SheetLayout = env.SheetLayout, Caps = env.Caps, CopiesPlan = env.CopiesPlan, SleepPool = env.SleepPool, SettingsSync = env.SettingsSync, OrbiSmart = env.OrbiSmart, StatusLayout = env.StatusLayout, BatteryGlyph = env.BatteryGlyph, PATCH_VERSION = PATCH_VERSION } end -- The old user patch still loaded (koreader/patches/2-orbit-android.lua; it hooks PluginLoader at diff --git a/android/koreader/test/catalog_actions_flows.lua b/android/koreader/test/catalog_actions_flows.lua index 5fb66978..4040c6e0 100644 --- a/android/koreader/test/catalog_actions_flows.lua +++ b/android/koreader/test/catalog_actions_flows.lua @@ -68,18 +68,7 @@ test("catalog actions: queued copies dispatch once outside reading with open pat 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 @@ -93,6 +82,9 @@ test("catalog actions: recommendation observation unwraps the saved native value 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} + local retirement=E.NativeRetirement + E.NativeRetirement={plan={settings_key="fixture-connector",preference_overlay={record="osm_saved_plugin",guard={sync_forward=3,sync_backward=3},keys={"sync_forward","sync_backward","auto_sync"}}},defaults=p.default_settings} + E.G_reader_settings:saveSetting("fixture-connector",p.settings) 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() @@ -100,8 +92,9 @@ test("catalog actions: recommendation observation unwraps the saved native value 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) + E.NativeRetirement.defaults=nil;eq(E.Library.observeSetting({key="sync_forward"}).available,false) end) + E.NativeRetirement=retirement E.S.osm_saved_plugin,E.S.sync_mode=saved,mode if not success then error(why) end end) @@ -119,22 +112,7 @@ test("catalog actions: finish follows the owned writer even with pending closed- 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 @@ -163,22 +141,7 @@ test("catalog actions: a saved next book opens offline without a network command 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 diff --git a/android/koreader/test/home_host_flows.lua b/android/koreader/test/home_host_flows.lua index c85d8563..9c9fd5f6 100644 --- a/android/koreader/test/home_host_flows.lua +++ b/android/koreader/test/home_host_flows.lua @@ -2,7 +2,7 @@ return function(test,eq,ok,E,W,Widget) local function withHost(fn) local saved={adapter=E.LibraryAdapter,ui=E.HomeWidgets._ui,layout=E.S.home_layout,screen=E.S.home_screen, - problem=E.Companion.workerProblem,scale=E.Device.screen.scaleBySize,shown=W.shown,free=Widget.free,paint=Widget.paintTo,require=E.require,codec=E.HomeEditor.codec,path=E.HomeEditor.path,loaded=E.HomeEditor.loaded,save=E.HomeEditor.save,liveUI=E.liveUI,pin=E.Shared.pin_locked,refresh=E.Shared.refresh,wifiState=E.Wifi.state,eobSheet=E.EOB.sheet,open=E.Library.open,panel=E.ReaderPanel,readFile=E.Store.readFile,writeFile=E.Store.writeFile} + problem=E.Companion.workerProblem,scale=E.Device.screen.scaleBySize,shown=W.shown,free=Widget.free,paint=Widget.paintTo,require=E.require,codec=E.HomeEditor.codec,news=E.S.news_012_pending,path=E.HomeEditor.path,loaded=E.HomeEditor.loaded,save=E.HomeEditor.save,liveUI=E.liveUI,pin=E.Shared.pin_locked,refresh=E.Shared.refresh,wifiState=E.Wifi.state,eobSheet=E.FinishUI.sheet,open=E.Library.open,panel=E.ReaderPanel,readFile=E.Store.readFile,writeFile=E.Store.writeFile} local batches,reads={},{} E.Device.screen.scaleBySize=function(_,n) return n end E.Companion.workerProblem=function() end @@ -61,20 +61,50 @@ return function(test,eq,ok,E,W,Widget) end,decode=function(raw) return E.Layout.copy(records[raw]) end} end E.Store.readFile=function(path) return files[path] end E.Store.writeFile=function(path,raw) files[path]=raw; return true end - W.shown={} + W.shown={};E.S.news_012_pending=false local success,err=pcall(fn,batches,reads,U) if E.HomeHost.active then E.HomeHost.active:onCloseWidget() end E.LibraryAdapter,E.HomeWidgets._ui,E.S.home_layout,E.S.home_screen=saved.adapter,saved.ui,saved.layout,saved.screen E.Device.screen.scaleBySize,W.shown,Widget.free,Widget.paintTo,E.require=saved.scale,saved.shown,saved.free,saved.paint,saved.require E.HomeEditor.codec,E.HomeEditor.path,E.HomeEditor.loaded=saved.codec,saved.path,saved.loaded E.Library.open,E.ReaderPanel=saved.open,saved.panel - E.HomeEditor.save=saved.save - E.liveUI,E.Wifi.state,E.EOB.sheet=saved.liveUI,saved.wifiState,saved.eobSheet + E.HomeEditor.save=saved.save;E.S.news_012_pending=saved.news + E.liveUI,E.Wifi.state,E.FinishUI.sheet=saved.liveUI,saved.wifiState,saved.eobSheet E.Shared.pin_locked,E.Shared.refresh=saved.pin,saved.refresh E.Store.readFile,E.Store.writeFile=saved.readFile,saved.writeFile E.Companion.workerProblem=saved.problem ok(success,err) end + test("owned Home: the default repeated Home returns to the open book",function() withHost(function() + E.S.home_screen="booksync" + local ui={document={file="/fixture/current.epub"}};E.liveUI=function() return ui end + local controller=setmetatable({ui=ui,openCompanionHome=function() error("default Home opened the companion") end},{__index=E.OrbitAndroid}) + controller:smartHome("command",nil,"smart");local host=E.HomeHost.active + eq(W.shown[#W.shown],host) + controller:smartHome("command",nil,"smart") + for _,w in ipairs(W.shown) do ok(w~=host,"Home closed back to the current book") end + eq(ui.document.file,"/fixture/current.epub");eq(E.reading(),true) + end) end) + test("owned Home: legacy choice cycles Home, companion and the current book",function() withHost(function() + E.S.home_screen="server-home" + local ui={document={file="/fixture/current.epub"}} + E.liveUI=function() return ui end + local opened=0 + local controller=setmetatable({ui=ui,openCompanionHome=function() opened=opened+1;return true end},{__index=E.OrbitAndroid}) + ok(controller:smartHome("command",nil,"smart"));local host=E.HomeHost.active + ok(host);eq(E.reading(),false) + ok(controller:smartHome("command",nil,"smart"));eq(opened,1) + ok(controller:smartHome("command","other_app","smart"));eq(W.shown[#W.shown],nil) + eq(ui.document.file,"/fixture/current.epub");eq(E.reading(),true) + end) end) + test("owned Home: list and Series return through the owned host with no native catalog",function() withHost(function() + local ui={document={file="/fixture/current.epub"}};E.liveUI=function() return ui end + local controller=setmetatable({ui=ui},{__index=E.OrbitAndroid}) + controller:onOrbitGoHome();local host=E.HomeHost.active + host:showList("All books","all",{});ok(host.list_layout) + controller:smartHome("command",nil,"smart");eq(host.list_layout,nil) + eq(E.HomeHost.active,host);eq(ui.document.file,"/fixture/current.epub") + end) end) dofile((arg[0]:match("^(.*)/") or ".").."/series_flows.lua")(test,eq,ok,E,W,withHost) dofile((arg[0]:match("^(.*)/") or ".").."/booklist_flows.lua")(test,eq,ok,E,W,Widget,withHost) dofile((arg[0]:match("^(.*)/") or ".").."/home_editor_flows.lua")(test,eq,ok,E,W,Widget,withHost) @@ -429,7 +459,7 @@ return function(test,eq,ok,E,W,Widget) local reader={document={}} E.liveUI=function() return reader end E.Wifi.state=function() return {foreground=true} end - E.EOB.sheet=nil + E.FinishUI.sheet=nil W.shown={reader,h} eq(E.reading(),false) local read=E.LibraryAdapter.read @@ -460,7 +490,7 @@ return function(test,eq,ok,E,W,Widget) local reader={document={}} E.liveUI=function() return reader end E.Wifi.state=function() return {foreground=true} end - E.EOB.sheet=nil + E.FinishUI.sheet=nil W.shown={reader,h} E.Library.open=function() return false end E.ReaderPanel={details=function(key) diff --git a/android/koreader/test/plugin_compat.lua b/android/koreader/test/plugin_compat.lua index d57146ef..23edc33a 100644 --- a/android/koreader/test/plugin_compat.lua +++ b/android/koreader/test/plugin_compat.lua @@ -1,160 +1,23 @@ --- Checks that every BookOrbit plugin internal Orbit uses (Compat, orbit.koplugin/logic/compat.lua) --- is still defined in a plugin checkout. Static: looks for each definition in the source. --- luajit plugin_compat.lua --- Prints the plugin version and any missing symbols; exits 1 when something is missing. -local here = arg[0]:match("^(.*)/[^/]*$") or "." -local dir = arg[1] or error("usage: plugin_compat.lua ") -_G.ORBIT_ANDROID_TEST = true -local M = dofile(here .. "/../orbit.koplugin/main.lua") - -local function list(d) - local p = io.popen('ls "' .. d .. '"') - local out = {} - for f in p:lines() do if f:match("%.lua$") then table.insert(out, d .. "/" .. f) end end - p:close() - return out -end -local src = {} -for _, f in ipairs(list(dir)) do - local h = io.open(f, "rb"); src[f] = h:read("*a"); h:close() -end -local function any(pattern) - for _, text in pairs(src) do if text:find(pattern) then return true end end - return false -end -local function esc(s) return (s:gsub("[%-%.%+%[%]%(%)%$%^%%%?%*]", "%%%0")) end - -local version = (src[dir .. "/main.lua"] or ""):match('local PLUGIN_VERSION = "([^"]+)"') or "unknown" -local missing, seen = {}, {} -local function need(name, kind) - if seen[name] then return end - seen[name] = true - local ok - if kind == "function" then - -- function X:name( / function X.name( / name = function - ok = any("function%s+[%w_%.]+[:%.]" .. esc(name) .. "%s*%(") or any("[%.%s]" .. esc(name) .. "%s*=%s*function") - else - ok = any("[%.%s]" .. esc(name) .. "%s*=") - end - if not ok then table.insert(missing, name) end -end -for _, f in ipairs(M.Compat.FEATURES) do - for name, kind in pairs(f.needs) do need(name, kind) end -end -for name, kind in pairs(M.Compat.CATALOG) do need(name, kind) end -need("submitSyncJob", "function") -- background notice scope follows native queued jobs -need("preference", "function") -- cached delivery variant for companion copy preparation -need("effectiveGridDimensions", "function") -- Mirror thumbnail bounds --- Recommended settings (ko/recommended.lua): the plugin's own defaults, read at run time. -need("default_settings", "field") -for name, kind in pairs(M.Compat.PAGING) do need(name, kind) end --- Lists by series and by author (Grouping): the class methods it wraps or calls. -for name, kind in pairs(M.Compat.CATALOG_CLASS) do need(name, kind) end -for name, kind in pairs(M.Compat.API_CLASS) do need(name, kind) end -local lists = src[dir .. "/bookorbit_catalog_lists.lua"] or "" -local catalog = src[dir .. "/bookorbit_catalog.lua"] or "" -local function has(text, plain, what) if not text:find(plain, 1, true) then table.insert(missing, what) end end --- The list methods are copied onto the catalog class (so the patch wraps that class). -has(lists, "function CatalogLists.install(Catalog)", "CatalogLists.install") -has(catalog, "CatalogLists.install(BookOrbitCatalog)", "CatalogLists.install(BookOrbitCatalog)") --- The row actions it takes over inside a grouped view, and the sheet rows it adds to. -has(lists, 'kind == "open-series"', 'action kind "open-series"') -has(lists, 'kind == "open-author"', 'action kind "open-author"') -local sheet = lists:match("function CatalogLists:listSortSheetModel%(sheet%)(.-)\nend\n") or "" -has(sheet, "rows = {", "rows = { in listSortSheetModel") --- The section body and context fields its answer and wrappers rely on. -for _, f in ipairs({ "body.items", "body.total", "body.size", "body.buckets", "body.hasNext", "body.offset", "body.sort", "body.filter" }) do - has(catalog, f, "loadSection reads " .. f) -end -for _, f in ipairs({ "list_sheet", "dashboard_source_index", "series_summary" }) do need(f, "field") end -has(lists, "params.q = opts.q", "listSectionParams sends q") --- End of book (ko/endofbook.lua EOB.COMPAT, EOB.CATALOG) and local-first Home (ko/localfirst.lua --- LF.*): the plugin functions they wrap or call. -for _, name in ipairs({ "newClient", "getDocumentDigest", "getLastPercent", "enqueueLifecycleSnapshot", - "updateProgress", "pushProgressAfterBookSync", "catalogBook", "catalogSetReadStatus", "catalogSetRating", "getBook", "mutate", - "onDeviceMaps", "rememberServerState", "applyServerStateLive", "applyServerStateSidecar", "sidecarMtime", - "downloadDefaultFile", "downloadFile", "checkDownloadFile", "loadBooks", "switchTo", "refreshOnDevice", - "updateItems", "refreshCurrent", "dashboardRootFetch", "boardHeader", "boardRun", "boardRefreshTile", - "boardRefreshClock", "listRun", "listHeader", "build", "statusCluster", "hit", "icon", "hstack", - "header", "listMetadata", "isBlocked", "getLifecycleOutbox", "evictCachedCovers", - "scheduleThumbnailDownloads", "dashboardBooks", "thumbnailDisplay", - -- v0.11.1: first paint from the cache, the on-device seed, the offline mirror's list paths, - -- cover logging, Remove without a file browser, the suspend snapshot skip. - "initialDashboardContext", "hydrateOnDeviceMaps", "paramsForEntry", "effectiveOrder", - "listDecorateBookQuery", "listSectionParams", "loadOnDevice", "fetchBookPage", "cancelThumbnailJobs", - "downloadThumbnailBatch", "boardDustRemove", "detailRemoveFromDevice", "_onSuspend", - -- Keep book copies current: the state's own repair for a file whose bytes changed. - "repairFileIdentity", "linkDownloadedFile", - -- v0.11.2: the first paint's on-device marks; mirrored covers outside the plugin's cover cap. - "hasOnDeviceMaps", "pruneThumbnailCache" }) do need(name, "function") end --- OrbiSmart sync (ko/orbismart.lua): every pull and push goes through the API client it wraps; the --- This book sheet's row it adds and the action it handles; the reader moves it makes. -for name, kind in pairs(M.Compat.ORBISMART_API or {}) do need(name, kind) end -for _, name in ipairs({ "syncToProgress", "noteProgressCompared", "fetchRemoteProgress", "requestProgressPush", - "row", "divider", "runAction", "vstack" }) do need(name, "function") end -need("last_page_turn_timestamp", "field") -has(src[dir .. "/bookorbit_api.lua"] or "", "function BookOrbitApi:getProgress(digest)", "BookOrbitApi:getProgress") -has(src[dir .. "/bookorbit_api.lua"] or "", "function BookOrbitApi:updateProgress(digest, percentage, progress, timestamp)", "BookOrbitApi:updateProgress") -has(src[dir .. "/bookorbit_book_sync.lua"] or "", "ctx.client:updateProgress(", "the outbox pushes through the API client") -has(src[dir .. "/bookorbit_book_sheet.lua"] or "", 'action = { kind = "auto" }', "This book sheet's Auto-sync row") --- The cover pruner removes files with the global os.remove (Mirror.guardPrune skips mirrored ones). -has(src[dir .. "/bookorbit_catalog_thumbnails.lua"] or "", "os.remove(removed.path)", "pruneThumbnailCache removes with os.remove") --- Our ⟳ keeps covers by wrapping evictCachedCovers, which refreshCurrent must still go through; --- Wi-Fi holds count only drainable outbox entries. -has(catalog, "self:evictCachedCovers(", "refreshCurrent evicts through evictCachedCovers") -has(src[dir .. "/bookorbit_lifecycle_outbox.lua"] or "", "drainable =", "outbox diagnostics() drainable") --- The cache (ko/cache.lua): the catalog request paths test_flows.lua's PLUGIN_PATHS copies, and the --- calls it wraps or uses; end of book downloads through the detail page's delivery path. -local api = src[dir .. "/bookorbit_api.lua"] or "" -for _, p in ipairs({ '"/koreader/plugin/catalog/root"', '"/koreader/plugin/catalog/dashboard"', - '"/koreader/plugin/catalog/dashboard/discover"', '"/koreader/plugin/catalog/dashboard/sections/"', - '"/koreader/plugin/catalog/sections/"', '"/koreader/plugin/catalog/books"', '"/koreader/plugin/catalog/manifest"', - '"/koreader/plugin/catalog/books/" .. tostring(book_id), { deviceId = self.device_id, variant = variant }' }) do - has(api, p, "catalog path " .. p) -end -for _, name in ipairs({ "thumbnailEntry", "runThumbnailWorker", "stopThumbnailWorker", "runConnected", "download", "fetchDeliveryBook", "supportedFiles", "requestBlocking", "runInSubprocess" }) do - need(name, "function") -end -has(api, '"subprocess_no_result"', "runInSubprocess reports a child without a result") -local board = src[dir .. "/bookorbit_catalog_board.lua"] or "" -local list_view = src[dir .. "/bookorbit_list_view.lua"] or "" --- Upvalues local-first swaps or calls: the header's status cluster and the list view's region. -has(board, "local statusCluster = BoardUI.statusCluster", "boardHeader's statusCluster upvalue") -has(list_view, "local function region(", "ListView region upvalue") --- Snapshot and detail fields they read. -for _, f in ipairs({ "percentage =", "seriesMembers", "relatedSections", "readStatus" }) do - if not any(esc(f)) then table.insert(missing, "field " .. f) end -end --- Fields and events the patch reads or writes directly. -for _, name in ipairs({ "catalog_browser", "pull_timestamp", "push_timestamp", "pages_before_update", - "last_remote_progress", "PLUGIN_VERSION", "last_error", "sync_forward", "sync_backward", - "catalog_auto_open", "auto_sync", "current_context" }) do need(name, "field") end --- Public actions the patch sends as events. -local main = src[dir .. "/main.lua"] or "" -if not main:find('registerAction%("bookorbit_open_dashboard"') then table.insert(missing, "action bookorbit_open_dashboard") end --- Setting values the patch writes (Compat.SETTINGS): the plugin still offers each one. -for key, values in pairs(M.Compat.SETTINGS) do - for v in pairs(values) do - if v ~= "off" and not any('"' .. esc(v) .. '"') then table.insert(missing, key .. " = " .. v) end - end -end - -table.sort(missing) -print("BookOrbit plugin " .. version) --- The companion's cache worker (docs/design/companion-worker.md) asks with the client's login and --- saves covers under the plugin's own cover names (CacheWorker.coverName). -local api = src[dir .. "/bookorbit_api.lua"] or "" -has(api, '["x-auth-user"] = self.username', "client.username as x-auth-user") -has(api, '["x-auth-key"] = self.userkey', "client.userkey as x-auth-key") -has(api, "server_url = forkSafeServerUrl(opts.server_url)", "client.server_url") -local thumbs = src[dir .. "/bookorbit_catalog_thumbnails.lua"] or "" -has(thumbs, 'local token = tostring(value):gsub("%D", "")', "coverToken: updatedAt's digits") -has(thumbs, 'token = token:sub(1, 16) .. token:sub(-16)', "coverToken: 16 + 16 digits") -has(thumbs, 'return (book.author_photo and "a" or "") .. id .. "_" .. coverToken(book)', "memoKey") -has(src[dir .. "/bookorbit_toast.lua"] or "", "function Toast.dismiss()", "Toast.dismiss") -if #missing == 0 then - print("all hooked symbols present") - os.exit(0) -end -print("missing: " .. table.concat(missing, ", ")) -os.exit(1) +-- BookSync retires the legacy plugin instead of calling its UI or transport methods. +-- Check only the pinned metadata/settings that the companion migration still consumes. +-- Run: luajit plugin_compat.lua +local dir=assert(arg[1],"plugin directory required") +local function read(name) + local f=assert(io.open(dir.."/"..name,"rb"),name);local s=f:read("*a");f:close();return s +end +local main=read("main.lua") +assert(main:match('name%s*=%s*["\']bookorbit["\']'),"legacy class identity changed: update the companion retirement descriptor") +assert(main:find("default_settings",1,true),"native setting defaults no longer available") +for _,key in ipairs({"auto_sync","sync_forward","sync_backward","catalog_auto_open"}) do + assert(main:find(key,1,true),"native setting changed: "..key) +end +for _,entry in ipairs({{"PROMPT",1},{"SILENT",2},{"DISABLE",3}}) do + assert(main:match(entry[1].."%s*=%s*"..entry[2]),"native direction value changed: "..entry[1]) +end +read("bookorbit_api.lua") -- the companion retirement descriptor disables this complete module +local state=read("bookorbit_state.lua") +assert(state:find("bookorbit_sync_state",1,true),"native import source filename changed") +local outbox=read("bookorbit_lifecycle_outbox.lua") +assert(outbox:find("payload_generation",1,true),"native lifecycle generation format changed") +assert(outbox:find("acknowledged",1,true),"native lifecycle checkpoint format changed") +print("legacy retirement metadata and migration formats match the pinned plugin; no UI/transport dependency") diff --git a/android/koreader/test/position_sync_flows.lua b/android/koreader/test/position_sync_flows.lua index de5e026d..ad16ee1f 100644 --- a/android/koreader/test/position_sync_flows.lua +++ b/android/koreader/test/position_sync_flows.lua @@ -45,8 +45,8 @@ return function(test,eq,ok,E,W,UIManager,run,newUI,ReaderUI,FileManager) local loader={enabled_plugins={legacy},loaded_plugins={},createPluginInstance=function(_,plugin) plugin:requestProgressPull(); plugin:enqueueLifecycleSnapshot(); api:updateProgress(); return plugin end} - local env=setmetatable({PluginLoader=loader,package={loaded={bookorbit_api=api}}},{__index=_G}) - local chunk=assert(loadfile(E.SOURCE_DIR.."/ko/server/bookorbit/quiesce.lua")); setfenv(chunk,env); chunk() + local env=setmetatable({PluginLoader=loader,package={loaded={bookorbit_api=api}},Library={bootstrap=function() return {ok="1",body="fixture"} end},Cache={decode=function() return {plugins={"bookorbit"},modules={"bookorbit_api"}} end},HomePlan={}},{__index=_G}) + local chunk=assert(loadfile(E.SOURCE_DIR.."/ko/retirement.lua")); setfenv(chunk,env); chunk() ok(env.SyncRetirement.safe); loader:createPluginInstance(legacy); eq(writes,0) loader.loaded_plugins.bookorbit=legacy chunk(); eq(env.SyncRetirement.safe,false,"late activation retains source and refuses a second writer") diff --git a/android/koreader/test/retirement_flows.lua b/android/koreader/test/retirement_flows.lua new file mode 100644 index 00000000..0141a250 --- /dev/null +++ b/android/koreader/test/retirement_flows.lua @@ -0,0 +1,44 @@ +-- SPDX-License-Identifier: AGPL-3.0-or-later +return function(test,eq,ok,E) + local function load(plan,late,constructor) + local invoked=0 + local function old() invoked=invoked+1 end + local legacy={name="retired-fixture",init=old,onStart=old,onReaderReady=old,download=old,default_settings={sync_forward=1}} + local client={request=old,download=old} + local loader={enabled_plugins={legacy},loaded_plugins=late and {[legacy.name]=legacy} or {},createPluginInstance=constructor and function(_,p) p:init();p:onStart();return p end or nil} + local env=setmetatable({Library={bootstrap=function() return plan and {ok="1",body="fixture"} or {ok="0"} end}, + Cache={decode=function() return plan end},HomePlan={},PluginLoader=loader,package={loaded={fixture_client=client}}},{__index=_G}) + local chunk=assert(loadfile(E.SOURCE_DIR.."/ko/retirement.lua"));setfenv(chunk,env);chunk() + return env,legacy,client,loader,function() return invoked end + end + test("retirement: a neutral descriptor disables complete classes before any constructor",function() + local e,p,client,loader,count=load({plugins={"retired-fixture"},modules={"fixture_client"},settings_key="fixture"},false,true) + ok(e.SyncRetirement.safe);loader:createPluginInstance(p);p:onReaderReady();p:download();client:request();client:download();eq(count(),0) + eq(e.NativeRetirement.defaults.sync_forward,1) + end) + test("retirement: missing, late and unknown startup seams never activate the owned writer",function() + eq(load(nil,false,true).SyncRetirement.safe,false) + eq(load({plugins={"retired-fixture"},modules={"fixture_client"}},true,true).SyncRetirement.safe,false) + eq(load({plugins={"retired-fixture"},modules={}},false,false).SyncRetirement.safe,false) + end) + test("retirement: malformed descriptor does not claim safety",function() + eq(load({plugins="invalid",modules={}},false,true).SyncRetirement.safe,false) + end) + test("library bootstrap: one local row has a deterministic byte and round-trip budget",function() + local b=E.Budgets.libraryBootstrap + ok(E.Budgets.check(b,{rows=1,bytes=100,spawns=0,network=0,roundTrips=1,snapshotBytes=100})) + ok(not E.Budgets.check(b,{rows=1,bytes=16385,spawns=0,network=0,roundTrips=1,snapshotBytes=16385})) + eq(b.network,0);eq(b.spawns,0) + end) + test("library bootstrap: untrusted companion sends nothing and oversized metadata fails closed",function() + local calls=0 + local env=setmetatable({Budgets=E.Budgets,now_s=function() return 1 end,log=function() end, + Companion={state=function() return "untrusted" end,LIBRARY_BOOTSTRAP="bootstrap",AUTHORITY="fixture"}, + Jni={call=function() calls=calls+1;return {ok="1",body=string.rep("x",16385)} end}},{__index=_G}) + setfenv(assert(loadfile(E.SOURCE_DIR.."/ko/library_bootstrap.lua")),env)() + eq(env.Library.bootstrap().ok,"0");eq(calls,0) + env.Companion.state=function() return "ok" end + eq(env.Library.bootstrap().why,"budget");eq(calls,1) + end) + +end diff --git a/android/koreader/test/test_flows.lua b/android/koreader/test/test_flows.lua index 3e781fb8..5c8b823d 100644 --- a/android/koreader/test/test_flows.lua +++ b/android/koreader/test/test_flows.lua @@ -248,6 +248,9 @@ end -- ContentResolver.call to the companion (Jni.call): the status, or a command. function W.companionCall(method, extras) local function answer(t) return { kind = "bundle", extras = t } end + if method:match("%.call%.LIBRARY_BOOTSTRAP$") then + return answer({ok="1",body='{plugins={"bookorbit"},modules={"bookorbit_api"},settings_key="bookorbit",home_key="bookorbit",row_count=1}'}) + end if method:match("%.call%.STATUS$") then W.last_status = extras local body = W.web[STATUS_KEY] @@ -856,20 +859,7 @@ test("sync while reading: chapter cadence never invokes the retired client", fun store.orbit_android.reading_schedule="off" end) -test("home from the companion: library home opens over the book, which stays open", function() - local ui = newUI(true) - run(30) - W.home_called = false - W.shown = {} - W.intent_extras["net.fledgewing.orbitcompanion.extra.COMMAND"] = "home" - ui.menu.registered[1]:onResume() - run(1) - ok(not W.home_called, "reader not closed") - ok(has(ui.bookorbit.calls, "dashboard"), "dashboard opened") - ok(W.shown[#W.shown] == ui.bookorbit.catalog_browser, "dashboard on top") - ui.bookorbit.catalog_browser.close_callback() - ok(W.intent_extras["net.fledgewing.orbitcompanion.extra.COMMAND"] == nil, "extra consumed") -end) + test("menu is its own Tools entry, not inside the plugin's menu, and builds", function() local ui, m = newUI(true) @@ -940,7 +930,7 @@ test("wifi: just in time turns Wi-Fi off after the idle time, and not while a do run(30) W.broadcasts = {} -- A download that blocks for a while: activity, so the timer restarts. - require("socket.http").request({ url = "https://dl.test/none", method = "GET" }) + NetworkMgr:beforeWifiAction(function() require("socket.http").request({url="https://dl.test/none",method="GET"}) end) run(50) ok(#wifiOffs() == 0, "not idle yet") run(40) @@ -1197,8 +1187,8 @@ test("restart with a book open (an update you started): the next start reopens t W.opened = nil local ui2, m2 = newUI(false) local cb = {} - cb.close_callback = function() ui2.bookorbit.catalog_browser = nil; W.catalog_closed = true end - ui2.bookorbit.catalog_browser = cb + cb.dismiss_callback = function() getfenv(Orbit.onSuspend).HomeHost.active=nil; W.catalog_closed=true end + getfenv(Orbit.onSuspend).HomeHost.active=cb W.catalog_closed = false m2:reopenAfterRestart("start") -- what init schedules 1 s after a start with restart_book set run(1) @@ -1334,6 +1324,8 @@ test("contract: every command, call, page, launch command, status key, file and 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() + local installer=assert(io.open(here.."/../../companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ConnectorPlugin.kt","rb")) + mailbox_source=mailbox_source..installer:read("*a");installer: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 @@ -1479,20 +1471,7 @@ test("caps: plugin only, a newer plugin on disk: asks to reopen KOReader, never end) -test("commands: signin opens BookOrbit's sign-in; recommended opens the review page", function() - local ui, m, p = recWorld(false) - p.signed_out = true - W.intent_extras[RE.Companion.EXTRA_COMMAND] = "signin" - ok(m:checkCommand("resume"), "handled") - run(1) - ok(has(p.calls, "promptLogin"), "BookOrbit's sign-in") - p.signed_out = nil - W.intent_extras[RE.Companion.EXTRA_COMMAND] = "recommended" - ok(m:checkCommand("resume"), "handled") - run(1) - ok(m.rec_menu and m.rec_menu.title == "Recommended settings", "review page") - run(1) -end) + test("add-on: a restart starts the companion's relaunch window, never at screen-off", function() capsReset() @@ -1746,106 +1725,17 @@ local function command(m, cmd, from) W.intent_extras["net.fledgewing.orbitcompanion.extra.FROM"] = from end -test("smart home: pressed in a book -> library home", function() - local ui, m = newUI(true) - run(5) - W.home_called = false - m:onSuspend(); W.clock = W.clock + 0.5 - command(m, "home_smart") - m:onResume() - run(1) - ok(has(ui.bookorbit.calls, "dashboard") and not W.home_called, "library home over the book") - ui.bookorbit.catalog_browser.close_callback() -end) -test("smart home: from another app with a book open -> stay in the book", function() - local ui, m = newUI(true) - run(5) - W.home_called = false - m:onSuspend(); W.clock = W.clock + 60 - command(m, "home_smart") - m:onResume() - run(1) - ok(not W.home_called, "stayed in the book") -end) -test("smart home: cold start after KOReader was killed with a book open -> that book", function() - W.files["/books/killed.epub"] = true - W.opened = nil - local ui, m = newUI(false) - command(nil, "home_smart", "other_app") - m:checkCommand("start") -- what init schedules 1 s after a cold start - run(5) - ok(W.opened == "/books/killed.epub", "reopened the book it was killed with") -end) -test("smart home: from the file browser with no book open -> library home, not history", function() - store.lastfile = "/books/last.epub" - W.files["/books/last.epub"] = true - W.opened = nil - local ui, m = newUI(false) - run(5) - m:onSuspend(); W.clock = W.clock + 0.5 - command(m, "home_smart") - m:onResume() - run(1) - ok(W.opened == nil, "no book reopened from history") - ok(has(ui.bookorbit.calls, "dashboard"), "library home") -end) -test("smart home: book -> library home -> companion -> back to the book", function() - local ui, m = newUI(true) - run(5) - W.shown, W.activities, W.home_called = {}, {}, false - local function press(from, pause) - m:onSuspend(); W.clock = W.clock + (pause or 0.5) - command(m, "home_smart", from) - m:onResume() - run(1) - end - press() - ok(ui.bookorbit.catalog_browser ~= nil and W.shown[#W.shown] == ui.bookorbit.catalog_browser, "1: library home") - press() - local a = W.activities[#W.activities] - ok(a and a.action:match("%.SHOW_LAUNCHER$"), "2: companion") - press("other_app", 30) - ok(ui.bookorbit.catalog_browser == nil and #W.shown == 0, "3: dashboard closed, back in the book") - ok(not W.home_called, "the book was never closed") -end) -test("smart home: fallback close by Home keeps the book current; elsewhere goes back to it", function() - store.orbit_android.home_book = nil - W.files["/b.epub"] = true - local ui, m = newUI(true) - m:onReaderReady() - run(5) - -- A plugin without the dashboard action (compat fallback): Home closes the book instead. - local q = newPlugin(); q.onBookOrbitOpenDashboard = nil - ui.bookorbit = q - local before = #W.logs - m:onOrbitGoHome() - run(1) - ok(W.home_called, "closed by Home") - local logged = false - for i = before + 1, #W.logs do - if W.logs[i]:find("compat: dashboard unavailable (plugin", 1, true) then logged = true end - end - ok(logged, "compat logged") - m:onCloseWidget() - ok(store.orbit_android.home_book == "/b.epub", "still the current book") - local fm, m2 = newUI(false) - run(5) - W.opened = nil - command(m2, "home_smart", "other_app") - m2:onResume() - run(1) - ok(W.opened == "/b.epub", "back to the book Home closed") - -- A user close clears it. - local ui3, m3 = newUI(true) - m3:onReaderReady() - m3:onCloseWidget() - ok(store.orbit_android.home_book == nil, "user close clears it") -end) + + + + + + -- Like KOReader 2025.10+ (frontend/pluginloader.lua v2026.07.1:117-164): on* handlers become -- callable tables. @@ -1858,42 +1748,9 @@ local function sandboxed(p) return p end -test("home: plugin handlers wrapped by KOReader 2026.07 -> Home on the file browser opens library home", function() - store.lastfile = nil - local ui, m = newUI(false) - sandboxed(ui.bookorbit) - run(5) - W.shown, W.activities = { { name = "filemanager" } }, {} - command(m, "home_smart", "other_app") - m:onResume() - run(2) - ok(has(ui.bookorbit.calls, "dashboard"), "dashboard handler ran") - ok(W.shown[#W.shown] == ui.bookorbit.catalog_browser, "library home on top") - ok(#W.activities == 0, "no companion page") - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) -test("home: the instance shows no handler but the UI routes the event -> library home opens", function() - store.lastfile = nil - local ui, m = newUI(false) - local real = ui.bookorbit - local seen = newPlugin() - seen.onBookOrbitOpenDashboard = nil -- what the patch sees; the UI still has the real module - ui.bookorbit = seen - function ui:handleEvent(ev) - local h = real["on" .. ev.name] - if h then return h(real, unpack(ev.args)) end - end - run(5) - W.shown, W.activities = { { name = "filemanager" } }, {} - command(m, "home_smart", "other_app") - m:onResume() - run(2) - ok(has(real.calls, "dashboard"), "event reached the plugin") - ok(W.shown[#W.shown] == real.catalog_browser, "library home on top") - W.shown = {} -end) + + test("storage menu: all sizes and fractional GB labels", function() local E = getfenv(Orbit.onSuspend) @@ -1998,20 +1855,7 @@ test("compat: reading sync does not require an upstream progress API", function( ok(not has(ui.bookorbit.calls,"fetch")) end) -test("compat: a catalog without dashboardMode -> not treated as library home", function() - local ui, m = newUI(true) - run(5) - local cb = {} - cb.close_callback = function() UIManager:close(cb); ui.bookorbit.catalog_browser = nil end - ui.bookorbit.catalog_browser = cb - W.shown, W.activities = { cb }, {} - m:onSuspend(); W.clock = W.clock + 0.5 - command(m, "home_smart") - m:onResume() - run(1) - ok(#W.activities == 0, "no companion page") - ok(ui.bookorbit.catalog_browser == nil, "back to the book") -end) + test("open book at exit: set when a book opens, cleared when it is closed", function() local ui, m = newUI(true) @@ -2022,15 +1866,7 @@ test("open book at exit: set when a book opens, cleared when it is closed", func ok(store.orbit_android.open_book_at_exit == nil, "cleared") end) -test("smart home: no last book -> library home", function() - store.lastfile = nil - local ui, m = newUI(false) - run(5) - command(m, "home_smart", "other_app") - m:onResume() - run(5) - ok(has(ui.bookorbit.calls, "dashboard"), "dashboard") -end) + local function dashboardOnTop(ui, kind) local cb = { dashboardMode = function() return kind == "dashboard" end } @@ -2039,87 +1875,16 @@ local function dashboardOnTop(ui, kind) end for _, cmd in ipairs({ "home_smart", "home" }) do - test("home (" .. cmd .. "): pressed on library home -> the companion's launcher page", function() - store.lastfile = "/books/last.epub" - W.files["/books/last.epub"] = true - local ui, m = newUI(false) - run(5) - dashboardOnTop(ui, "dashboard") - W.activities, W.opened = {}, nil - m:onSuspend(); W.clock = W.clock + 0.5 - command(m, cmd) - m:onResume() - run(1) - local a = W.activities[#W.activities] - ok(a and a.action:match("%.SHOW_LAUNCHER$"), "launcher page started") - ok(W.opened == nil, "no book opened") - ui.bookorbit.catalog_browser = nil - W.shown = {} - end) + end -test("home: from the companion page while library home is on top, no book -> library home", function() - store.lastfile = "/books/last.epub" - W.files["/books/last.epub"] = true - local ui, m = newUI(false) - run(5) - dashboardOnTop(ui, "dashboard") - W.activities, W.opened = {}, nil - command(m, "home_smart", "other_app") - m:onResume() - run(1) - ok(#W.activities == 0, "no companion page") - ok(W.opened == nil, "no book reopened") - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) + -- Held left-handed (upside down) in another app; KOReader's file browser had forced upright -- (filemanager.lua:63-69). Home: BookOrbit Home turns back to how the device is held. -test("home from another app with no book: BookOrbit Home keeps the held rotation", function() - store.lastfile = nil - local ui, m = newUI(false) - run(5) - local screen = preload.device.screen - local rot = 0 - screen.getRotationMode = function() return rot end - local set = {} - function ui:onSetRotationMode(mode) table.insert(set, mode); rot = mode end - command(m, "home_smart", "other_app") - W.intent_extras["net.fledgewing.orbitcompanion.extra.ROTATION"] = "reverse_portrait" - m:onResume() - run(2) - ok(#set == 1, "one turn"); ok(set[1] == 2, "upside down, as held") - ok(W.intent_extras["net.fledgewing.orbitcompanion.extra.ROTATION"] == nil, "extra consumed") - -- Already as held: nothing turns. - command(m, "home_smart", "other_app") - W.intent_extras["net.fledgewing.orbitcompanion.extra.ROTATION"] = "reverse_portrait" - ui.bookorbit.catalog_browser = nil - m:onResume() - run(2) - ok(#set == 1, "no second turn") - screen.getRotationMode, ui.onSetRotationMode = nil, nil - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) -test("home from another app back to the open book: the book's rotation stays", function() - local ui, m = newUI(true) - run(5) - local screen = preload.device.screen - screen.getRotationMode = function() return 0 end - local turned = false - screen.setRotationMode = function() turned = true end - m:onSuspend(); W.clock = W.clock + 30 - command(m, "home_smart", "other_app") - W.intent_extras["net.fledgewing.orbitcompanion.extra.ROTATION"] = "reverse_portrait" - m:onResume() - run(2) - ok(not turned, "a book keeps its own rotation") - screen.getRotationMode, screen.setRotationMode = nil, nil - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) + + test("a book closing: the new file browser keeps the book's rotation", function() local calls = 0 @@ -2157,45 +1922,9 @@ test("start patch: installed into koreader/patches once, kept current", function ok(got == src, "the plugin's copy") end) -test("home at KOReader's start after the start patch: no second turn", function() - store.lastfile = nil - local ui, m = newUI(false) - run(5) - local screen = preload.device.screen - screen.getRotationMode = function() return 2 end - local set = {} - function ui:onSetRotationMode(mode) table.insert(set, mode) end - ORBIT_START_ROTATION = 2 - m:smartHome("start", "other_app", "smart", "landscape") - run(2) - ORBIT_START_ROTATION = nil - ok(#set == 0, "the start kept the held rotation") - screen.getRotationMode, ui.onSetRotationMode = nil, nil - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) -test("home: file browser on top of a stale library home -> library home brought to the top", function() - store.lastfile = nil - local ui, m = newUI(false) - run(5) - local stale = { dashboardMode = function() return true end } - stale.close_callback = function() UIManager:close(stale); ui.bookorbit.catalog_browser = nil end - ui.bookorbit.catalog_browser = stale - local browser = { name = "filemanager" } - W.shown = { stale, browser } - W.activities, W.opened = {}, nil - command(m, "home_smart", "other_app") - m:onResume() - run(2) - local top = W.shown[#W.shown] - ok(#W.activities == 0, "no companion page") - ok(ui.bookorbit.catalog_browser ~= nil and ui.bookorbit.catalog_browser ~= stale, "reopened") - ok(top == ui.bookorbit.catalog_browser, "library home is on top") - ok(m:whereNow() == "bookorbit", "where: bookorbit") - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) + + -- A catalog like plugin 2.3.0's: modes switched in place, goDashboard back to the main page. local function catalogIn(ui, kind) @@ -2217,37 +1946,9 @@ local function homePress(m) run(2) end -test("home: BookOrbit detail view over an open book -> BookOrbit main page, book stays", function() - store.lastfile = "/books/last.epub" - W.files["/books/last.epub"] = true - local ui, m = newUI(true) - run(5) - local cb = catalogIn(ui, "detail") - homePress(m) - ok(#W.activities == 0, "no companion page") - ok(not W.home_called, "the book stays open") - ok(W.went_dashboard and cb:dashboardMode(), "catalog back to its main page") - ok(W.shown[#W.shown] == cb, "same catalog on top") - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) -test("home: a sheet over BookOrbit's main page -> the sheet closed, main page", function() - store.lastfile = nil - local ui, m = newUI(false) - run(5) - local cb = catalogIn(ui, "dashboard") - local closed = false - local sheet = { name = "bookorbit_menu_sheet", onCloseWidget = function() closed = true end } - sheet.dismiss_callback = function() closed = true end - table.insert(W.shown, sheet) - homePress(m) - ok(#W.activities == 0, "no companion page") - ok(closed and W.shown[#W.shown] == cb, "sheet closed, catalog on top") - ok(cb:dashboardMode(), "main page") - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) + + -- Plugin 2.3.0's paging: the dashboard's board_page (boardPage/boardFlip), a list's page -- (listMode/listPaging/listGoPage). @@ -2262,70 +1963,15 @@ local function withPaging(cb, page) return cb end -test("home: library home on page 2 -> page 1, not the companion", function() - store.lastfile = nil - local ui, m = newUI(false) - run(5) - local cb = withPaging(catalogIn(ui, "dashboard"), 2) - homePress(m) - ok(#W.activities == 0, "no companion page") - ok(cb:boardPage() == 1, "page 1") - ok(W.shown[#W.shown] == cb and cb:dashboardMode(), "same catalog, main page") - homePress(m) - local a = W.activities[#W.activities] - ok(a and a.action:match("%.SHOW_LAUNCHER$"), "page 1: the launcher page") - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) -test("home: a BookOrbit list on page 3 -> its page 1, then the main page", function() - store.lastfile = nil - local ui, m = newUI(false) - run(5) - local cb = withPaging(catalogIn(ui, "books"), 3) - W.list_went = nil - homePress(m) - ok(W.list_went == 1, "list page 1") - ok(not W.went_dashboard and #W.activities == 0, "stayed on the list") - homePress(m) - ok(W.went_dashboard and cb:dashboardMode(), "then the main page") - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) -test("home: catalog in a list mode, plugin without goDashboard -> reopened on its main page", function() - store.lastfile = nil - local ui, m = newUI(false) - run(5) - local cb = catalogIn(ui, "books") - cb.goDashboard = nil - homePress(m) - local now = ui.bookorbit.catalog_browser - ok(now ~= nil and now ~= cb, "a fresh catalog") - ok(W.shown[#W.shown] == now and now:dashboardMode(), "on its main page") - ok(#W.shown == 1, "the old one closed: " .. #W.shown) - ok(#W.activities == 0, "no companion page") - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) -test("home: BookOrbit's true main page -> the companion's launcher page", function() - local ui, m = newUI(false) - run(5) - catalogIn(ui, "dashboard") - homePress(m) - local a = W.activities[#W.activities] - ok(a and a.action:match("%.SHOW_LAUNCHER$"), "launcher page") - ok(not W.went_dashboard, "no reset") - ui.bookorbit.catalog_browser = nil - W.shown = {} -end) -test("apps gesture: registered and in the recommended set", function() - ok(actions.orbit_open_apps and actions.orbit_open_apps.title == "BookSync Companion: apps", "action title") - local R = getfenv(Orbit.onSuspend).Recommended - ok(R.item("g.apps").ours.orbit_open_apps and R.item("g.apps").key == "two_finger_swipe_north", "two-finger swipe up") -end) + + + + + ---------------------------------------------------------------- updates (BookSync Companion) -- The plugin and the companion ship together: the menu's check asks the companion (UPDATE), and @@ -2541,43 +2187,7 @@ W.screen_on = false sh("rm -rf", ORBIT_ANDROID_PLUGIN_DIR) os.remove(SELF) -test("settings PIN: a locked companion makes the BookSync menu read-only, with the keypad one tap away; unreachable stays usable", function() - local url = STATUS_KEY - local ui, m = newUI(true) - local items = {} - m:addToMainMenu(items) - W.web[url] = "STATUS" - W.json.STATUS = { version = "0.4.4", pin_locked = true } - W.activities = {} - local sub = items.orbit_android.sub_item_table_func() - ok(sub[1].text:find("PIN", 1, true), "first row asks for the PIN") - -- Every value is still there to read; nothing that changes something is enabled. - local all = menuAll(sub) - ok(#all > 20, "the whole menu, read-only " .. #all) - local enabled = 0 - for i, it in ipairs(all) do - if i > 1 and it.callback and not it.settings_group and not it.sub_item_table and not it.keep_menu_open and not it.read_only and not (it.enabled_func and it.enabled_func() == false) then - enabled = enabled + 1 - end - end - eq(enabled, 0, "no control enabled while locked") - local wifi = RE.S.sync_on_wake - for _, it in ipairs(all) do if it.text == "Sync when it wakes" then it.callback() end end - eq(RE.S.sync_on_wake, wifi, "a tap changes nothing") - run(1) - for _, a in ipairs(W.activities) do ok(not a.action:match("SHOW_PIN$"), "no keypad until asked") end - W.activities = {} - sub[1].callback() - ok(W.activities[1] and W.activities[1].action:match("SHOW_PIN$"), "the first row opens the keypad") - W.json.STATUS = { version = "0.4.4", pin_locked = false } - local open = items.orbit_android.sub_item_table_func() - ok(not open[1].text:find("PIN", 1, true), "unlocked: the usual menu") - W.web[url], W.json.STATUS = nil, nil - W.activities = {} - ok(#items.orbit_android.sub_item_table_func() >= 9, "companion unreachable: full menu") - run(1) - for _, a in ipairs(W.activities) do ok(not a.action:match("SHOW_PIN$"), "no keypad without the companion") end -end) + ---------------------------------------------------------------- lists by series and by author -- A catalog class like plugin 2.3.0's (bookorbit_catalog.lua with CatalogLists mixed in), cut @@ -2973,100 +2583,11 @@ local function lfModules(drop) return Cat, BD, LV, BUI end -test("local-first: a plugin without a hook -> Home stays the plugin's", function() - local Cat, BD = lfModules("listRun") - local build = BD.build - newUI(false) - ok(not E.LF.installed and BD.build == build and not (rawget(Cat, "__orbit_stock") or {})["lf:boardRun"], "no local-first hooks installed") -end) -test("local-first: Home paints this device's state; ⟳ refreshes; a refresh repaints changed tiles only", function() - local Cat, BD, LV, BUI = lfModules() - package.loaded["bookorbit_state_manager"] = { getBook = function(d) return d == "d7" and { bookId = 7 } or nil end } - newUI(false) - ok(E.LF.installed, "installed") - -- Finished here, not yet sent: Home shows it finished before the server knows. - E.LocalState.put("d7", { status = "complete", percent = 100, pending = true }) - local body = { continueReading = { { id = 7, title = "A", progressPercentage = 40 }, { id = 8, title = "B", progressPercentage = 10 } } } - local cat = setmetatable({ current_context = { kind = "dashboard", dashboard = body } }, Cat) - local d = BD.build(cat, cat.current_context, os.time()) - ok(lf.built ~= body and lf.built.orbit_overlay, "an overlaid copy") - ok(#body.continueReading == 2, "the saved body untouched") - ok(d.orbit_board, "marked for the header") - -- Header: ⟳ next to the device status, and the stamp. - E.LocalState.load().fetchedAt.dashboard = os.time() - 120 - local h = cat:boardHeader(d) - ok(h.status.items and h.status.items[1].action.kind == "orbit-refresh", "⟳ in the header") - ok(h.date_long:find("Sunday · updated", 1, true), "stamp: " .. tostring(h.date_long)) - cat:boardRun({ kind = "orbit-refresh" }) - ok(lf.refreshed, "⟳ refreshes") - cat:boardRun({ kind = "menu" }) - ok(lf.stock_run == "menu", "other actions: the plugin's") - -- List header: ⟳ and its stamp. - local lh = cat:listHeader("books", { kind = "books", params = {} }) - local lv = LV.header(500, lh) - ok(lv.status.items and lv.status.items[1].region.kind == "orbit-refresh", "⟳ on lists") - lf.refreshed = nil - cat:listRun({ kind = "orbit-refresh" }) - ok(lf.refreshed, "list ⟳ refreshes") - -- A refresh lands: one tile changed -> only it repaints, plus the header stamp. - cat._board_ctx = { d = d } - cat._board_tiles = { { item = { type = "hero" } }, { item = { type = "clock" } }, { item = { type = "shelf", source = "x" } } } - lf.repainted, lf.stock_switch, lf.header = {}, 0, 0 - local fresh = { continueReading = { { id = 8, title = "B", progressPercentage = 30 } } } - lf.next_context = { kind = "dashboard", dashboard = fresh } - local items, ctx = cat:dashboardRootFetch({}) - cat:switchTo("Home", items, ctx, false) - ok(lf.stock_switch == 0 and lf.header == 1, "no full repaint; header stamped") - W.shown = { cat }; run(0.1) - ok(#lf.repainted == 1 and lf.repainted[1] == "hero", "only the hero tile: " .. table.concat(lf.repainted, ",")) - ok(cat.current_context == ctx, "the new body adopted") - -- A different board (shelf set changed) -> the plugin's full repaint. - local other = { kind = "dashboard", dashboard = { continueReading = {}, boardShelves = { y = {} } }, orbit_refresh = true } - cat:switchTo("Home", {}, other, false) - ok(lf.stock_switch == 1, "full repaint") - for _, k in ipairs({ "bookorbit_catalog", "bookorbit_board_data", "bookorbit_list_view", "bookorbit_board_ui", "bookorbit_state_manager" }) do - package.loaded[k] = nil - end -end) -test("local-first: ⟳ keeps covers; a quiet refresh keeps cover jobs; a late cover redraws its tile", function() - local Cat, BD = lfModules() - E.LF.installed = nil -- install again, onto this test's catalog - newUI(false) - lf.evicted, lf.scheduled, lf.cancelled, lf.covers, lf.refreshed = {}, {}, 0, {}, nil - local body = { continueReading = { { id = 7, title = "A", progressPercentage = 40 } } } - local cat = setmetatable({ current_context = { kind = "dashboard", dashboard = body } }, Cat) - local d = BD.build(cat, cat.current_context, os.time()) - -- ⟳: the data refreshes, the covers stay (they are keyed by cover version). - cat:boardRun({ kind = "orbit-refresh" }) - ok(lf.refreshed, "⟳ refreshes") - ok(#lf.evicted == 0, "no cover deleted: " .. table.concat(lf.evicted, ",")) - -- The plugin's own refresh paths still evict, as before. - cat:refreshCurrent() - ok(#lf.evicted == 1, "the plugin's own refresh unchanged") - lf.evicted = {} - -- A refresh lands quietly: no cancelled cover jobs, and the new book's cover is fetched. - cat._board_ctx = { d = d } - cat._board_tiles = { { item = { type = "hero" } } } - lf.repainted, lf.stock_switch, lf.header = {}, 0, 0 - lf.next_context = { kind = "dashboard", dashboard = { continueReading = { { id = 7, title = "A", progressPercentage = 40 }, { id = 9, title = "C", progressPercentage = 5 } } } } - local items, ctx = cat:dashboardRootFetch({}) - cat:switchTo("Home", items, ctx, false) - ok(lf.stock_switch == 0 and lf.cancelled == 0, "quiet: cover jobs kept") - ok(table.concat(lf.scheduled, ",") == "7,9", "covers scheduled: " .. table.concat(lf.scheduled, ",")) - -- A cover lands while a hydration repaint skip is pending: its tile still redraws. - lf.repainted, lf.full_paint = {}, 0 - lf.covers[9] = "ready" - cat._orbit_skip_repaint = true - cat:updateItems(nil, true) - W.shown = { cat }; run(0.1) - ok(lf.full_paint == 0, "no full repaint") - ok(#lf.repainted == 1 and lf.repainted[1] == "hero", "the cover's tile redrew: " .. table.concat(lf.repainted, ",")) - for _, k in ipairs({ "bookorbit_catalog", "bookorbit_board_data", "bookorbit_list_view", "bookorbit_board_ui" }) do - package.loaded[k] = nil - end -end) + + + ---------------------------------------------------------------- write-through cache local cache = {} @@ -3219,18 +2740,7 @@ local DASH = "/koreader/plugin/catalog/dashboard" -test("covers: low-level legacy calls are local only even with caching disabled", function() - local client = cacheSetup() - local saved=E.Library.cachedCover - E.Library.cachedCover=function(path) return path=="/fixture/cached.jpg" and path or nil end - E.S.offline_cache=false - eq(client:downloadCatalogThumbnail(7,"/fixture/cached.jpg"),true) - eq(client:downloadCatalogThumbnail(7,"/fixture/missing.jpg"),nil) - eq(client:downloadCatalogAuthorPhoto(7,"/fixture/missing.jpg"),nil) - eq(cache.stock_cover,nil); eq(#cache.calls,0) - E.Library.cachedCover=saved; E.S.offline_cache=true - cacheTeardown() -end) + -- The request paths the pinned plugin builds (bookorbit_api.lua:676-738; query() sorts and drops -- empty parameters, :386). plugin_compat.lua checks these strings are still in the plugin. @@ -3351,106 +2861,13 @@ end -test("covers: companion batches never fork and stale results cannot redraw", function() - local function prep(Cat) - function Cat:thumbnailEntry(book) - self.thumbnail_memo=self.thumbnail_memo or {} - local key=tostring(book.id) - self.thumbnail_memo[key]=self.thumbnail_memo[key] or {path=cache.dir.."/covers/"..key.."_100.jpg"} - return self.thumbnail_memo[key] - end - function Cat:stopThumbnailWorker() self.stopped=true end - function Cat:updateItems() self.redraws=(self.redraws or 0)+1 end - end - local client,Cat=cacheSetup(prep) - local commands={}; local paths={} - local cached,command=E.Library.cachedCover,E.LibraryAdapter.command - E.Library.cachedCover=function(ref) return paths[ref] end - E.LibraryAdapter.command=function(op,args,done) - eq(op,"covers.acquire"); ok(not W.in_child,"parent-side dispatch") - commands[#commands+1]=args - UIManager:scheduleIn(0.1,function() paths[args.reference]=args.reference; done({local_path=args.reference}) end) - return true - end - local cat=setmetatable({client=client,thumbnail_generation=1,thumbnail_queue={head=1,tail=2,{id=1},{id=2}}, - thumbnail_prefetch_queue={head=1,tail=0}},Cat) - cat:runThumbnailWorker(1); run(0.5) - eq(#commands,2); eq(cat.redraws,1); ok(cat.stopped); eq(cache.stock_cover,nil); eq(cache.child_crash,nil) - cat.thumbnail_queue={head=1,tail=1,{id=3}}; cat.stopped=false - cat:runThumbnailWorker(1); cat.thumbnail_generation=2; run(0.5) - eq(cat.redraws,1,"departed generation cannot redraw") - E.Library.cachedCover,E.LibraryAdapter.command=cached,command - cacheTeardown() -end) -test("covers: forced recheck dispatches neutral references and never redraws while reading", function() - local _,Cat=cacheSetup() - local command=E.LibraryAdapter.command - local requests={} - E.LibraryAdapter.command=function(op,args,done) - eq(op,"covers.acquire"); eq(args.refresh,true); ok(args.server==nil and args.userkey==nil) - requests[#requests+1]=args.reference - UIManager:scheduleIn(0.1,function() done({local_path=args.reference}) end) - return true - end - local cat=setmetatable({thumbnail_generation=1},Cat) - local redraw=0 - function cat:updateItems() redraw=redraw+1 end - E.OC.recheckCovers(cat,{{path="/fixture/one.jpg"},{path="/fixture/two.jpg"}}) - run(0.5); eq(#requests,2); eq(redraw,1) - local reading=E.reading; E.reading=function() return true end - E.OC.recheckCovers(cat,{{path="/fixture/one.jpg"}}) - run(0.5); eq(redraw,1,"reading is never interrupted by a cover completion") - E.reading=reading; E.LibraryAdapter.command=command - cacheTeardown() -end) -test("covers: saved local references stay drawable offline while refresh waits", function() - local function prep(Cat) - function Cat:thumbnailEntry(book) - self.thumbnail_memo=self.thumbnail_memo or {} - self.thumbnail_memo[book.id]=self.thumbnail_memo[book.id] or {path=cache.dir.."/covers/"..book.id.."_200.jpg"} - return self.thumbnail_memo[book.id] - end - function Cat:stopThumbnailWorker() end - function Cat:updateItems() end - end - local _,Cat=cacheSetup(prep) - local cached,command=E.Library.cachedCover,E.LibraryAdapter.command - local old=cache.dir.."/covers/1_100.jpg" - local f=assert(io.open(old,"wb")); f:write("\255\216\255\224cached"); f:close() - E.Library.cachedCover=function() return old end - local calls=0 - E.LibraryAdapter.command=function(op,args,done) - calls=calls+1; eq(op,"covers.acquire") - UIManager:scheduleIn(0.1,function() done({local_path=old,stale=true}) end) - return true - end - local cat=setmetatable({thumbnail_generation=1,thumbnail_queue={head=1,tail=1,{id=1}},thumbnail_prefetch_queue={head=1,tail=0}},Cat) - W.wifi=false - local row=cat:thumbnailEntry({id=1}); eq(row.path,old); eq(row.exists,true); eq(calls,0,"paint is local-only") - cat:runThumbnailWorker(1) - eq(cat:thumbnailEntry({id=1}).path,old,"pending acquisition keeps the saved cover") - run(0.5); eq(cat:thumbnailEntry({id=1}).path,old); eq(#cache.calls,0) - E.Library.cachedCover,E.LibraryAdapter.command=cached,command - cacheTeardown() -end) -test("wifi: just in time keeps Wi-Fi on while BookOrbit's Home is over the book, and while the cache works", function() - local WP = E.WifiPlan - local st = WP.new("jit", 2, 0) - st.mode, st.foreground, st.in_book, st.last_flow, st.release_at, st.last_activity = "jit", true, true, "wake", 10, 100 - local a, why = WP.decide(st, { now = 20, wifi_on = true, browsing = false }) - ok(a == "off" and why:find("done in a book"), "reading: off after the wake (" .. tostring(why) .. ")") - a, why = WP.decide(st, { now = 20, wifi_on = true, browsing = true }) - ok(a == nil, "BookOrbit's Home over the book: kept (" .. tostring(why) .. ")") - a = WP.decide(st, { now = 100 + 121, wifi_on = true, browsing = true }) - ok(a == "off", "idle there for the just-in-time time: off") - E.Library.catalog_active=true - local busy, bwhy = E.Wifi.busy() - ok(busy and bwhy:find("catalog"), "a cache check out at the companion keeps it: " .. tostring(bwhy)) - E.Library.catalog_active=nil -end) + + + + test("suspend: unchanged app switches coalesce native captures; real sleep always captures", function() local ui,m=newUI(true); run(30) @@ -3466,37 +2883,7 @@ test("suspend: unchanged app switches coalesce native captures; real sleep alway env.Jni.isInteractive=interactive end) -test("remove: with a book open (no file browser) BookOrbit's remove asks through KOReader's delete; the open book stays", function() - local asked, deleted = {}, {} - local FM = { instance = nil } - function FM:showDeleteFileDialog(path, after) table.insert(asked, path); if self:deleteFile(path, true) and after then after() end end - function FM:deleteFile(path) table.insert(deleted, path); return true end - local RUI = { instance = { document = { file = "/books/open.epub" } } } - local saved_fm, saved_rui = package.loaded["apps/filemanager/filemanager"], package.loaded["apps/reader/readerui"] - package.loaded["apps/filemanager/filemanager"], package.loaded["apps/reader/readerui"] = FM, RUI - local errors = {} - package.loaded["bookorbit_toast"] = { error = function(t) table.insert(errors, t) end, show = function() end } - local Peek = {} - -- As bookorbit_book_peek.lua:156-167. - function Peek.remove(catalog, path) - local fm = require("apps/filemanager/filemanager").instance - if not fm or not fm.showDeleteFileDialog then - require("bookorbit_toast").error("Open the file browser to remove this book.") - return - end - fm:showDeleteFileDialog(path, function() catalog.refreshed = true end) - end - package.loaded["bookorbit_book_peek"] = Peek - E.LF.installRemove() - local cat = {} - Peek.remove(cat, "/books/other.epub") - ok(asked[1] == "/books/other.epub" and deleted[1] == "/books/other.epub" and cat.refreshed, "asked, deleted, refreshed") - ok(#errors == 0 and FM.instance == nil, "no 'open the file browser'; no file browser left behind") - Peek.remove(cat, "/books/open.epub") - ok(#deleted == 1 and errors[1]:find("This book is open"), "the open book stays: " .. tostring(errors[1])) - package.loaded["apps/filemanager/filemanager"], package.loaded["apps/reader/readerui"] = saved_fm, saved_rui - package.loaded["bookorbit_toast"], package.loaded["bookorbit_book_peek"] = nil, nil -end) + @@ -3504,39 +2891,7 @@ end) ---------------------------------------------------------------- v0.11.2 (M8C test of v0.11.1) -test("reading gate: BookOrbit over the book is not reading, whatever floats on top; Wi-Fi agrees (v0.11.2)", function() - RE.Gate.queue = {} - local ui = newUI(true) - local cat = { name = "catalog" } - ui.bookorbit.catalog_browser = cat - W.shown = {} - ok(RE.reading(), "the book alone: reading") - -- Home over the book, under BookOrbit's loading pill (not a toast) and a KOReader message. - W.shown = { ui, cat, { name = "bookorbit_toast" }, { name = "InfoMessage" } } - ok(not RE.reading(), "Home over the book with a pill and a message on top: not reading") - local shown - RE.Gate.show("BookOrbit show: Full refresh · saving for offline 1/146", function() shown = true end) - ok(shown and #RE.Gate.queue == 0, "the Full refresh progress shows at once") - W.shown = { ui, { name = "bookorbit_book_sheet" } } - ok(not RE.reading(), "a BookOrbit sheet over the book") - W.shown = { ui, { name = "bookorbit_menu_sheet" }, { name = "bookorbit_confirm" } } - ok(not RE.reading(), "a BookOrbit menu and dialog over the book") - W.shown = { ui, { name = "bookorbit_toast" } } - ok(RE.reading(), "a BookOrbit pill alone over the book: still reading") - W.shown = { cat, ui } - ok(RE.reading(), "the book over the catalog: reading") - -- The Wi-Fi plan's "browsing" is the same test: no "done in a book" off with Home over it. - W.shown = { ui, cat, { name = "bookorbit_toast" } } - local hosts = RE.serverPlugin - RE.serverPlugin = function() return ui.bookorbit end - ok(RE.serverOverBook(RE.serverPlugin()), "browsing for the Wi-Fi plan") - local st = RE.WifiPlan.new("jit", 2, 0) - st.in_book, st.last_flow, st.release_at, st.last_activity = true, "wake", W.clock - 1, W.clock - local a = RE.WifiPlan.decide(st, { now = W.clock, wifi_on = true, browsing = RE.serverOverBook(RE.serverPlugin()) }) - ok(a == nil, "kept on while paging BookOrbit lists over the book") - RE.serverPlugin = hosts - W.shown = {} -end) + @@ -3570,32 +2925,7 @@ end) -test("local-first: Home's first paint has the on-device marks; a changed tile names what changed (v0.11.2)", function() - local client, Cat = cacheSetup(function(Cat) - function Cat:initialDashboardContext() return {}, { kind = "dashboard", dashboard = {}, stale = true } end - function Cat:dashboardRootFetch() return {}, { kind = "dashboard", dashboard = self.client:request("GET", DASH) } end - end) - W.wifi = true - cache.server[DASH] = { continueReading = { { id = 7, progressPercentage = 40 } } } - client:request("GET", DASH) - local sm = package.loaded["bookorbit_state_manager"] - package.loaded["bookorbit_state_manager"] = { - hasOnDeviceMaps = function() return true end, - onDeviceMaps = function() return { byBookId = { [7] = "/books/seven.epub" }, byFileId = {}, generation = 3 } end, - } - local cat = setmetatable({ client = client, on_device = {} }, Cat) - W.logs = {} - cat:initialDashboardContext() - ok(cat.on_device[7] == "/books/seven.epub", "BookOrbit's marks before the first paint (Resume, not Download)") - ok(table.concat(W.logs, "\n"):find("first paint with BookOrbit's on-device marks for 1 book(s)", 1, true), "logged") - package.loaded["bookorbit_state_manager"] = sm - W.logs = {} - E.LF.logChanged({ { key = 1, kind = "hero" } }, { 1 }, - { continue_reading = { { id = 7, progressPercentage = 40 } } }, - { continue_reading = { { id = 7, progressPercentage = 40, on_device = true } } }) - ok(W.logs[1] and W.logs[1]:find("local-first: tile 1 hero changed: book 7 on device no -> yes", 1, true), "the tile and field: " .. tostring(W.logs[1])) - cacheTeardown() -end) + @@ -3638,33 +2968,7 @@ end -test("sleep screen: back from a real sleep the plugin tells the companion (no service needed); an app switch doesn't", function() - local on = RE.Sleep.on - RE.Sleep.on = function() return true end - local function wakes() - return count(W.broadcasts, function(x) return x.action:sub(-11) == ".SLEEP_POOL" and x.extras.wake == "1" end) - end - local _ui, m = newUI(false) - run(5) - W.broadcasts = {} - W.screen_on = false - m:onSuspend() - run(2) - W.screen_on = true - m:onResume() - run(1) - ok(wakes() == 1, "one wake: " .. wakes()) - local b = lastBroadcast(".SLEEP_POOL") - ok(b.package == "net.fledgewing.orbitcompanion" and b.extras.reason == "wake", "to the companion") - -- Another app in front and back, the screen on throughout: no wake. - m:onSuspend() - run(2) - m:onResume() - run(1) - ok(wakes() == 1, "an app switch is no wake: " .. wakes()) - RE.Sleep.on = on - W.screen_on = false -end) + -- BookSync Companion refreshes the sleep screen's pool (fake_companion.lua plays SleepPoolBuilder). local function sleepCompanion() @@ -3685,134 +2989,7 @@ local function sleepCompanion() return fc end -test("sleep screen: the menu, SETTINGS to the companion, a pool from Up next through Leave out, the current cover", function() - local JSON = dofile(here .. "/json_mini.lua") - capsReset() - local caps = {} - for _, c in ipairs(FULL) do table.insert(caps, c) end - table.insert(caps, "sleep_screen") - W.web[STATUS_KEY] = "STATUS" - W.json.STATUS = { version = "0.12.0", mode = "full", caps = caps, sleep = { shown_by = "BookSync screen saver ✓" } } - local dir = os.tmpname(); os.remove(dir); sh("mkdir -p", dir .. "/covers") - local lfs = require("libs/libkoreader-lfs") - local saved = { attributes = lfs.attributes, dir = lfs.dir } - lfs.attributes = function(f, k) - local d = os.execute('test -d "' .. f .. '"') - if d == 0 or d == true then return "directory" end - local h = io.open(f, "rb"); if h then h:close(); return "file" end - return saved.attributes(f, k) - end - lfs.dir = function(d) - local h = io.popen('ls -1 "' .. d .. '" 2>/dev/null'); local names = {} - for n in h:lines() do table.insert(names, n) end - h:close(); local i = 0 - return function() i = i + 1; return names[i] end - end - local S, Sleep = RE.S, RE.Sleep - Sleep.base_dir = dir - local ui, m = newUI(false) - RE.Shared.refresh("test") - ok(RE.Companion.has("sleep_screen"), "the companion offers it") - local item - item = RE.Sleep.menuItem(m, function(fn) return fn end) - ok(item, "Tools › BookSync › Sleep screen") - local rows = item.sub_item_table_func() - ok(rows[1].text_func() == "Sleep screen: The reader's own", "off by default: " .. rows[1].text_func()) - ok(rows[2].enabled_func() == false, "Pick from waits for Recommended") - ok(rows[#rows - 1].text_func() == "Shown by: BookSync screen saver ✓", "how the companion shows it") - -- Recommended on: saved, and the companion gets every sleep extra. - W.broadcasts = {} - rows[1].sub_item_table[2].callback() - ok(S.sleep_mode == "recommended", "saved") - local b = lastBroadcast(".SETTINGS") - ok(b and b.extras.sleep_mode == "recommended" and b.extras.sleep_hours == "6" and b.extras.sleep_style == "bar" - and b.extras.sleep_battery == "0" and b.extras.sleep_from == "up_next", "SETTINGS extras") - Sleep.set("sleep_leave_out", { "tag:age:18" }) - ok(lastBroadcast(".SETTINGS").extras.sleep_leave_out == "tag:age:18", "rules, one per line") - -- The pool: Up next is empty, so Want to read; one read, one without a cover, one left out by tag. - local calls = {} - local client = {} - function client:query(path, q) - local keys = {} - for k in pairs(q) do table.insert(keys, k) end - table.sort(keys) - local parts = {} - for _, k in ipairs(keys) do table.insert(parts, k .. "=" .. tostring(q[k])) end - return path .. "?" .. table.concat(parts, "&") - end - local ui_calls = 0 - function client:requestBlocking(method, path) - table.insert(calls, path) - if not W.in_companion then ui_calls = ui_calls + 1 end - if path:find("sections/up%-next%-in%-series") then return { section = { books = {} } } end - if path:find("sections/want%-to%-read") then - return { section = { books = { - { id = 1, title = "Read One", hasCover = true, readStatus = "read" }, - { id = 2, title = "Tagged", hasCover = true }, - { id = 3, title = "Kept", hasCover = true }, - { id = 4, title = "No Cover", hasCover = false }, - } } } - end - local id = tonumber(path:match("/catalog/books/(%d+)$")) - if id == 2 then return { id = 2, title = "Tagged", hasCover = true, tags = { "Age:18" } } end - if id == 3 then return { id = 3, title = "Kept", hasCover = true, tags = { "cosy" } } end - return nil, 404 - end - local oc_client = RE.OC.client - RE.OC.client = function() return client end - local fc = sleepCompanion() - fc.sleepDownload = function(_, id, path) local f = io.open(path, "wb"); f:write("jpg" .. id); f:close(); return true end - io.open(dir .. "/covers/99.jpg", "wb"):close() -- a cover from an earlier pool - W.broadcasts = {} - Sleep.refreshed_at = nil - Sleep.kick("test") - run(60) - local f = io.open(dir .. "/pool.json", "rb") - ok(f, "pool.json written") - local pool = JSON.decode(f:read("*a")); f:close() - ok(#pool.items == 1 and pool.items[1].id == 3 and pool.items[1].file == "covers/3.jpg", "only the kept book: " .. tostring(#pool.items)) - ok(io.open(dir .. "/covers/3.jpg", "rb"), "its cover") - ok(not io.open(dir .. "/covers/99.jpg", "rb"), "the old cover went") - local ask = lastBroadcast(".SLEEP_REFRESH") - ok(ask and ask.extras.from == "up_next" and ask.extras.rules == "tag:age:18" and ask.extras.every == "0", "the companion is asked") - ok(ui_calls == 0 and fc.sleep_asks == 1, "the companion lists, checks and fetches; KOReader asks nothing: " .. ui_calls) - -- Without the right companion nothing is asked. - local at = Sleep.refreshed_at - fc.problem = "Update BookSync Companion" - Sleep.refreshed_at = nil - ok(Sleep.refresh("old companion") == false and fc.sleep_asks == 1, "an older companion: not asked") - fc.problem, Sleep.refreshed_at = nil, at - local log = table.concat(W.logs, "\n") - ok(log:find("sleep screen: pool 1 cover(s)", 1, true) and log:find("from want-to-read (the chosen list was empty)", 1, true), "logged") - -- Not again within REFRESH_EVERY_S; never in a book. - local n = #calls - Sleep.kick("again"); run(10) - ok(#calls == n, "not again so soon") - -- The current book's cover, once per book. - package.loaded["apps/filemanager/filemanagerbookinfo"] = { getCoverImage = function() - return { writeToFile = function(_, path) local g = io.open(path, "wb"); g:write("png"); g:close(); return true end, free = function() end } - end } - local book = { document = { file = "/books/made-up.epub" }, doc_props = { display_title = "A Made-Up Book", authors = "Ann Example" } } - ok(Sleep.writeCurrent(book, "test") == true, "written") - ok(Sleep.writeCurrent(book, "test") == false, "once per book") - f = io.open(dir .. "/current.json", "rb") - local cur = JSON.decode(f:read("*a")); f:close() - ok(cur.title == "A Made-Up Book" and cur.file == "current.png" and cur.authors == "Ann Example", "current.json") - ok(io.open(dir .. "/current.png", "rb"), "current.png") - -- Off again: nothing more is written. - rows[1].sub_item_table[1].callback() - S.sleep_current_file = nil - ok(Sleep.writeCurrent(book, "off") == false, "off writes nothing") - package.loaded["apps/filemanager/filemanagerbookinfo"] = nil - RE.OC.client = oc_client - fc.done() - lfs.attributes, lfs.dir = saved.attributes, saved.dir - Sleep.base_dir = nil - S.sleep_leave_out = {} - sh("rm -rf", dir) - capsReset() - run(5) -end) + test("sleep screen: settings changed in the companion are applied; an older companion changes nothing", function() capsReset() @@ -3835,259 +3012,11 @@ test("sleep screen: settings changed in the companion are applied; an older comp run(5) end) -test("sleep screen: Pick from and Leave out list every list and collection, all pages, with counts, saved for offline", function() - local JSON = dofile(here .. "/json_mini.lua") - local function fixture(name) - local f = assert(io.open(here .. "/../../../shared/fixtures/bookorbit/" .. name, "rb")) - local v = JSON.decode(f:read("*a")); f:close(); return v - end - -- @fixture bookorbit/catalog-sections.smart-scopes.json @fixture bookorbit/catalog-sections.collections.json - local scopes, collections = fixture("catalog-sections.smart-scopes.json"), fixture("catalog-sections.collections.json") - -- scopes.json is read back with KOReader's json module: the real decoder here. - local jm = require("json") - local stub_decode = jm.decode - jm.decode = function(str) return W.json[str] or JSON.decode(str) end - capsReset() - local caps = {} - for _, c in ipairs(FULL) do table.insert(caps, c) end - table.insert(caps, "sleep_screen") - W.web[STATUS_KEY] = "STATUS" - W.json.STATUS = { version = "0.12.0", mode = "full", caps = caps } - local dir = os.tmpname(); os.remove(dir); sh("mkdir -p", dir .. "/covers") - local S, Sleep = RE.S, RE.Sleep - Sleep.base_dir, Sleep.scopes_cache, Sleep.scope_names, Sleep.scopes_at = dir, nil, nil, nil - S.sleep_mode = "recommended" - local ui, m = newUI(false) - RE.Shared.refresh("test") - -- Lists come in two pages (hasNext), collections whole, as the server sends them. - local calls, down = {}, false - local client = {} - function client:query(path, q) return string.format("%s?page=%d&size=%d", path, q.page, q.size) end - function client:requestBlocking(_, path) - table.insert(calls, path) - if down then return nil, "offline" end - if path:find("/sections/smart%-scopes%?page=1&size=100") then - local items = {} - for i = 1, 7 do items[i] = scopes.items[i] end - return { section = "smart-scopes", items = items, hasNext = true } - end - if path:find("/sections/smart%-scopes%?page=2&size=100") then - local items = {} - for i = 8, #scopes.items do table.insert(items, scopes.items[i]) end - return { section = "smart-scopes", items = items, hasNext = false } - end - if path:find("/sections/collections%?page=1") then return collections end - return nil, 404 - end - local oc_client = RE.OC.client - RE.OC.client = function() return client end - local fc = sleepCompanion() - W.wifi = true - local item - item = RE.Sleep.menuItem(m, function(fn) return fn end) - local rows = item.sub_item_table_func() - local from = rows[2].sub_item_table - local picker = from[#from] - -- First open: nothing saved yet, fetched behind the menu. - local first = picker.sub_item_table_func() - ok(#first == 1 and first[1].text_func():find("Loading", 1, true), "loading: " .. first[1].text_func()) - run(10) - ok(#calls == 3, "two pages of scopes, one of collections: " .. table.concat(calls, " ")) - local f = io.open(dir .. "/scopes.json", "rb") - ok(f, "scopes.json saved"); if f then f:close() end - local function texts(list) - local out = {} - for _, r in ipairs(list) do table.insert(out, r.text or (r.text_func and r.text_func())) end - return out - end - local got = texts(picker.sub_item_table_func()) - ok(#got == 15, "2 headers, 12 scopes, 1 collection: " .. #got) - ok(got[1] == "Lists" and got[2] == "Cosy Mysteries · 5" and got[13] == "Holiday Picks", "scopes with counts, the last without: " .. tostring(got[13])) - ok(got[14] == "Collections" and got[15] == "ToRead · 23", "the collection: " .. tostring(got[15])) - -- Tapping one ticks it beside Up next (Pick from is a set, R1c), and both names show. - local tapped = picker.sub_item_table_func() - ok(tapped[15].checked_func and not tapped[15].checked_func(), "a tick box, not ticked yet") - tapped[15].callback() - ok(S.sleep_from == "up_next\ncollection:7" and Sleep.fromLabel(S.sleep_from) == "Up next in series, ToRead", "picked: " .. tostring(S.sleep_from)) - ok(picker.sub_item_table_func()[15].checked_func(), "ticked") - -- Library stands alone: ticking it clears the others; ticking a list clears it. - from[1].callback() - ok(S.sleep_from == "library" and Sleep.fromLabel(S.sleep_from) == "Whole library", "library: " .. tostring(S.sleep_from)) - from[3].callback() - ok(S.sleep_from == "want_to_read", "a list clears Library: " .. tostring(S.sleep_from)) - from[3].callback() - ok(S.sleep_from == "want_to_read", "the last one stays ticked") - tapped[15].callback() - -- Offline, after a restart: the same lists from scopes.json, in Leave out too. - down, W.wifi = true, false - Sleep.scopes_cache, Sleep.scope_names, Sleep.scopes_at = nil, nil, nil - local leave = rows[3].sub_item_table_func() - local add - for _, r in ipairs(leave) do if r.text == "Add a rule: Library, list or collection…" then add = r end end - local lo = texts(add.sub_item_table_func()) - ok(#lo == 15 and lo[3] == "Space Opera · 8", "Leave out lists them offline: " .. #lo) - add.sub_item_table_func()[4].callback() - ok(S.sleep_leave_out[1] == "scope:103" and Sleep.ruleLabel("scope:103") == "Short Reads (list)", "rule added: " .. tostring(S.sleep_leave_out[1])) - RE.OC.client, jm.decode = oc_client, stub_decode - fc.done() - Sleep.base_dir, Sleep.scopes_cache, Sleep.scope_names, Sleep.scopes_at = nil, nil, nil, nil - S.sleep_mode, S.sleep_from, S.sleep_leave_out = "off", "up_next", {} - sh("rm -rf", dir) - capsReset() - run(5) -end) -test("sleep screen: the tag picker opens from the companion's tags.json; KOReader reads no saved detail", function() - capsReset() - local caps = {} - for _, c in ipairs(FULL) do table.insert(caps, c) end - table.insert(caps, "sleep_screen") - W.web[STATUS_KEY] = "STATUS" - W.json.STATUS = { version = "0.12.0", mode = "full", caps = caps } - local jm = require("json") - local JSON = dofile(here .. "/json_mini.lua") - local stub_decode = jm.decode - jm.decode = function(str) return W.json[str] or JSON.decode(str) end - local sdir = os.tmpname(); os.remove(sdir); sh("mkdir -p", sdir .. "/covers") - local S, Sleep = RE.S, RE.Sleep - Sleep.base_dir, Sleep.tags_cache, Sleep.scopes_cache, Sleep.scope_names, Sleep.scopes_at = sdir, nil, nil, nil, nil - S.sleep_mode, S.sleep_leave_out = "recommended", {} - newUI(false) - RE.Shared.refresh("test") - local client = {} - function client:query(path, q) return path .. "?page=" .. q.page end - function client:requestBlocking(_, path) - if path:find("/sections/") then return { items = {}, hasNext = false } end - return nil, 404 - end - local oc_client = RE.OC.client - RE.OC.client = function() return client end - local fc = sleepCompanion() - -- 400 saved details in the database, each with tags, and one more. - local cdir = RE.OC.dir() - local st = fc.db() - st:begin() - for i = 1, 400 do st:putDetail(i, { id = i, tags = { i % 2 == 0 and "Age:18" or "cosy", "Fantasy" } }, 1) end - st:putDetail(900, { id = 900, tags = { "Space" } }, 1) - st:commit() - -- Every file KOReader's UI thread opens in the cache folder while the picker opens. - local reads, open = 0, io.open - io.open = function(path, ...) - -- The companion's small answers (events/) are read; no saved detail or index is. - if not W.in_companion and tostring(path):find(cdir, 1, true) and not tostring(path):find("/events/", 1, true) and not tostring(path):find("/events-batch.lua", 1, true) then reads = reads + 1 end - return open(path, ...) - end - W.wifi = true - local item - item = RE.Sleep.menuItem(select(2, newUI(false)), function(fn) return fn end) - local leave = item.sub_item_table_func()[3].sub_item_table_func() - local tagItem - for _, r in ipairs(leave) do if r.text == "Add a rule: Tag…" then tagItem = r end end - -- First open: nothing counted yet; the companion counts behind it. - local first = tagItem.sub_item_table_func() - ok(#first == 2 and first[2].text_func():find("Counting", 1, true), "counting: " .. tostring(first[2] and first[2].text_func and first[2].text_func())) - run(10) - ok(fc.sleep_asks == 1 and fc.sleep_last.scopes_only == "1", "the companion was asked for the pickers' lists") - local rows = tagItem.sub_item_table_func() - local texts = {} - for _, r in ipairs(rows) do table.insert(texts, r.text or "") end - ok(texts[2] == "Fantasy · 400" and texts[3] == "Age:18 · 200" and texts[4] == "cosy · 200" and texts[5] == "Space · 1", "counted by the companion: " .. table.concat(texts, " | ")) - ok(reads == 0, "KOReader read no saved detail: " .. reads) - rows[3].callback() - ok(S.sleep_leave_out[1] == "tag:age:18", "picked: " .. tostring(S.sleep_leave_out[1])) - io.open = open - RE.OC.client, jm.decode = oc_client, stub_decode - fc.done() - Sleep.base_dir, Sleep.tags_cache, Sleep.scopes_cache, Sleep.scope_names, Sleep.scopes_at = nil, nil, nil, nil, nil - S.sleep_mode, S.sleep_leave_out = "off", {} - sh("rm -rf", sdir) - capsReset() - run(5) -end) -test("sleep screen: 24 covers ready whatever the source; Every sleep retires the used-up and tops up", function() - local JSON = dofile(here .. "/json_mini.lua") - local jm = require("json") - local stub_decode = jm.decode - jm.decode = function(str) return W.json[str] or JSON.decode(str) end - capsReset() - local caps = {} - for _, c in ipairs(FULL) do table.insert(caps, c) end - table.insert(caps, "sleep_screen") - W.web[STATUS_KEY] = "STATUS" - W.json.STATUS = { version = "0.12.0", mode = "full", caps = caps } - local dir = os.tmpname(); os.remove(dir); sh("mkdir -p", dir .. "/covers") - local lfs = require("libs/libkoreader-lfs") - local saved = { attributes = lfs.attributes, dir = lfs.dir } - lfs.attributes = function(f, k) - local d = os.execute('test -d "' .. f .. '"') - if d == 0 or d == true then return "directory" end - local h = io.open(f, "rb"); if h then h:close(); return "file" end - return saved.attributes(f, k) - end - lfs.dir = function(d) - local h = io.popen('ls -1 "' .. d .. '" 2>/dev/null'); local names = {} - for n in h:lines() do table.insert(names, n) end - h:close(); local i = 0 - return function() i = i + 1; return names[i] end - end - local S, Sleep = RE.S, RE.Sleep - Sleep.base_dir = dir - newUI(false) - RE.Shared.refresh("test") - S.sleep_mode, S.sleep_from, S.sleep_hours, S.sleep_leave_out = "recommended", "up_next", 6, {} - local books = {} - for i = 1, 30 do books[i] = { id = i, title = "Book " .. i, hasCover = true } end - local client = {} - function client:query(path) return path end - function client:requestBlocking(_, path) - if path:find("sections/up%-next%-in%-series") then return { section = { books = books } } end - return nil, 404 - end - local oc_client = RE.OC.client - RE.OC.client = function() return client end - local fc = sleepCompanion() - fc.sleepDownload = function(_, id, path) local f = io.open(path, "wb"); f:write("jpg" .. id); f:close(); return true end - W.wifi = true - local function build() - Sleep.refreshed_at = nil - Sleep.kick("test"); run(60) - local ids, f = {}, io.open(dir .. "/pool.json", "rb") - for _, it in ipairs(JSON.decode(f:read("*a")).items) do table.insert(ids, it.id) end - f:close() - return ids - end - local function has(ids, id) for _, x in ipairs(ids) do if x == id then return true end end return false end - local function state(shows) - local f = io.open(dir .. "/state.json", "wb"); f:write(shows); f:close() - end - -- 30 in the source: the batch is 24, with hours too. - local ids = build() - ok(#ids == 24 and ids[1] == 1 and ids[24] == 24, "24 of 30: " .. #ids) - -- Every sleep: 1 and 2 were shown 3 times; they go, 25 and 26 come in; the rest stay. - S.sleep_hours = 0 - state('{"v":1,"shown":3,"changed_at":1,"shows":{"1":3,"2":3,"3":1}}') - ids = build() - ok(#ids == 24 and not has(ids, 1) and not has(ids, 2) and has(ids, 3) and has(ids, 25) and has(ids, 26), "retired and topped up: " .. table.concat(ids, ",")) - ok(not io.open(dir .. "/covers/1.jpg", "rb"), "a retired cover's file goes") - ok(table.concat(W.logs, "\n"):find("every sleep: 22 kept, 2 retired", 1, true), "logged") - -- A one-book source: fewer than 24 is fine, and a used-up last cover stays rather than nothing. - books = { { id = 40, title = "Only", hasCover = true } } - state('{"v":1,"shown":0,"changed_at":1,"shows":{}}') - ids = build() - ok(#ids == 1 and ids[1] == 40, "one book: " .. table.concat(ids, ",")) - state('{"v":1,"shown":40,"changed_at":1,"shows":{"40":3}}') - ids = build() - ok(#ids == 1 and ids[1] == 40, "kept cycling: " .. table.concat(ids, ",")) - RE.OC.client, jm.decode = oc_client, stub_decode - fc.done() - lfs.attributes, lfs.dir = saved.attributes, saved.dir - Sleep.base_dir = nil - S.sleep_mode, S.sleep_from, S.sleep_hours, S.sleep_leave_out = "off", "up_next", 6, {} - sh("rm -rf", dir) - capsReset() - run(5) -end) + + + test("settings v2: a change queued in the companion while KOReader was off applies, then is echoed", function() @@ -4183,51 +3112,35 @@ test("sqlite stress: the reader sees whole pages through lua-ljsqlite3, read-onl w:close(); os.remove(path) end) -test("sqlite stress: a torn page and a locked file are caught and counted", function() - local path, w = stressDb() - for gen = 1, 50 do stressWrite(w, gen, { torn = gen == 17 }) end - local r = RE.SqliteStress.read(path, 2, tickClock()) - ok(r.errors > 0 and tostring(r.first_error):find("torn page") ~= nil, "torn: " .. tostring(r.first_error)) - -- A writer holding the commit lock: the reader waits (busy) and goes on once it's released. - local path2, w2 = stressDb() - for gen = 1, 50 do stressWrite(w2, gen) end - w2:exec("BEGIN EXCLUSIVE") - local n, release = 0, nil - local clock = function() n = n + 1; if n == 30 then w2:exec("COMMIT") end; return n * 0.01 end - local r2 = RE.SqliteStress.read(path2, 1, clock) - eq(r2.errors, 0, "errors after the wait: " .. tostring(r2.first_error)) - ok(r2.busy >= 1, "the wait is counted") - ok(r2.reads > 0, "reads after the lock went") - w:close(); w2:close(); os.remove(path); os.remove(path2) -end) + -- The offline cache's database, as CacheStoreTest reads it: the same fixture, the plugin's reads. local JSONF = dofile(here .. "/json_mini.lua") -- @fixture cache/db.json @fixture cache/schema.sql local DBFX = JSONF.decode(io.open(here .. "/../../../shared/fixtures/cache/db.json", "rb"):read("*a")) -local FakeStore = dofile(here .. "/fake_store.lua")(RE.ServerCache, SQ3, here .. "/../../../shared/fixtures/cache/schema.sql") - local function fixtureStore() - local dir = os.tmpname() .. "-store" - os.execute("mkdir -p '" .. dir .. "'") - local st = FakeStore.open(dir .. "/orbit.db") - st:own(DBFX.owner) - for i, sv in ipairs(DBFX.saves) do - local key = sv.key or RE.ServerCache.key({ account = DBFX.owner:match("^([^|]*)"), server = DBFX.owner:match("|(.*)$"), method = "GET", path = sv.path }) - st:save(key, sv.path, sv.reply, 1000 + i, DBFX.detail_template) + local dir=os.tmpname().."-store";os.execute("mkdir -p '"..dir.."'") + local sql=SQ3.open(dir.."/orbit.db","rwc") + local st={conn=sql} + function st:run(query,...) + local q=self.conn:prepare(query);if select("#",...)>0 then q:bind(...) end + local out={};while true do local row=q:step();if not row then break end;out[#out+1]=row end;q:close();return out + end + function st:close() self.conn:close() end + for line in io.lines(here.."/../../../shared/fixtures/cache/schema.sql") do + if line~="" and not line:match("^%-%-") then sql:exec(line) end end - return dir, st + sql:exec("PRAGMA user_version=1") + st:run("INSERT OR REPLACE INTO meta(k,v) VALUES('owner',?)",DBFX.owner) + return dir,st end - -local function withStore(dir, fn) - local saved = RE.OC._dir - RE.OC._dir = dir - local okf, err = pcall(fn) - RE.Db.close(dir .. "/orbit.db") - RE.OC._dir = saved - if not okf then error(err, 0) end +local function withStore(dir,fn) + local saved,ready=RE.Store.directory,RE.Store.directoryReady;RE.Store.directory=function() return dir end;RE.Store.directoryReady=function() return true end + local worked,why=pcall(fn);RE.Db.close(dir.."/orbit.db");RE.Store.directory=saved;RE.Store.directoryReady=ready + if not worked then error(why,0) end end + test("library device owner: local SQLite rows survive sign-out without adopting the catalog", function() local dir, st = fixtureStore() st:run("CREATE TABLE library_views(owner TEXT,request TEXT,body BLOB,at INTEGER,PRIMARY KEY(owner,request))") @@ -4272,41 +3185,7 @@ end) -test("reading: a locked cache cannot delay page turns or cold/warm cache reads", function() - local dir, st = fixtureStore() - withStore(dir, function() - local path = DBFX.reads[1].path - local reading, conn = RE.reading, RE.Db.conn - RE.reading = function() return false end - st.conn:exec("CREATE TABLE IF NOT EXISTS library_views (owner TEXT,request TEXT,body BLOB,at INTEGER,PRIMARY KEY(owner,request))") - st.conn:exec("INSERT INTO library_views VALUES ('"..DBFX.owner.."','tap-warm','{items={}}',1)") - local warm = RE.Store.library(DBFX.owner, "tap-warm") - ok(warm ~= nil, "prime the decoded cache before reading") - local ui, m = newUI(true) - RE.EOB.page_digests[ui] = { file = ui.document.file, digest = "tap-regression" } - local bookOf = RE.EOB.bookOf - RE.EOB.bookOf = function() error("page turn read plugin state") end - RE.reading = function() return true end - local opens = 0 - RE.Db.conn = function(...) opens = opens + 1; return conn(...) end - st.conn:exec("BEGIN EXCLUSIVE") - local okf, err = pcall(function() - uiWorkBudget(function() - for page = 2, 26 do - m:onPageUpdate(page) - eq(RE.Store.library(DBFX.owner,"tap-warm"), warm, "memory hit") - eq(RE.Store.library(DBFX.owner,"tap-cold"), nil, "cold miss skips SQL") - end - end, { opens = 0, reads = 0, walks = 0, entries = 0, intents = 0 }) - end) - st.conn:exec("COMMIT") - RE.reading, RE.Db.conn, RE.EOB.bookOf = reading, conn, bookOf - if not okf then error(err) end - eq(RE.EOB.session["tap-regression"].forward, 24, "forward turns still release the stale-push hold") - eq(opens, 0, "no SQLite access on a page turn, even under an exclusive lock") - end) - st:close() -end) + test("reading: finish sync returns immediately and dispatches only outside reading", function() local reading,action=RE.reading,RE.Library.catalogAction @@ -4628,64 +3507,7 @@ test("main loop: yielding work is attributed to each resume rather than a combin W.logs=logs end) -test("Home calendar: worker snapshots replace a correctly dated empty calendar", function() - local LF, C, OC = E.LF, E.Companion, E.OC - local saved={year=LF.year,key=LF.year_key,waiting=LF.year_waiting,send=C.send,problem=C.workerProblem,watch=OC.watchChecks,catalog=E.Mirror.catalog} - local asks={} - C.send=function(action, extras) asks[#asks+1]=extras; return true end - C.workerProblem=function() return nil end - OC.watchChecks=function() end - E.Mirror.catalog=function() return nil end - LF.year={values={},start=0,today=0}; LF.year_key=nil - local now=os.time(); local body={} - local values,start,today=LF.yearMinutes(now,body) - ok(start>now-365*86400 and today<=now and now-today<86400,"current calendar dates before first answer") - ok(#values>=358 and #values<=364); eq(#asks,1) - LF.yearMinutes(now,body); eq(#asks,1,"pending ask coalesced") - LF.yearLanded({key=asks[1].board_key,data={values={10,20},start=start,today=today}}) - eq(select(1,LF.yearMinutes(now,body))[2],20,"worker answer used") - LF.year,LF.year_key,LF.year_waiting=saved.year,saved.key,saved.waiting - C.send,C.workerProblem,OC.watchChecks,E.Mirror.catalog=saved.send,saved.problem,saved.watch,saved.catalog -end) -test("startup: 7000 cover files keep each UI callback within a fixed IO/intent budget", function() - local client = cacheSetup() - local lfs = require("libs/libkoreader-lfs") - local cdir = cache.dir .. "/covers" - for i=1,7000 do local f=assert(io.open(cdir .. "/" .. i .. ".jpg.etag", "wb")); f:write("etag"); f:close() end - E.OC.cover_dir = cdir - FC.coverDirectory=cdir - local checked = 0 - local items = FC.storageItems - -- The fake worker walks the real directory; companion tests cover its actual cleanup/count. - FC.storageItems = function(folder) - ok(W.in_companion, "storage runs in companion") - local count=0; for name in lfs.dir(folder) do if name:match("%.etag$") then count=count+1 end end - eq(count,7000) - return {} - end - W.main_loop_guard = function(fn,args) - uiWorkBudget(function() fn(unpack(args)) end) - if getfenv(fn)==E then checked=checked+1 end - end - local passed_guard, err=pcall(function() - uiWorkBudget(function() - E.OC.storageCount("orphan ETags") - eq(E.OC.olderCover,nil,"older-cover enumeration is companion-only") - end) - run(12) - local reader={document={file="/books/reading.epub"}} - ReaderUI.instance=reader; W.shown={reader} - uiWorkBudget(function() E.OC.storageCount("orphan ETags") end) - run(12) - ReaderUI.instance=nil; W.shown={} - ok(checked > 0, "guard measured production callbacks") - end) - W.main_loop_guard=nil; FC.storageItems=items - ReaderUI.instance=nil; W.shown={} - cacheTeardown() - ok(passed_guard,err) -end) @@ -4701,6 +3523,12 @@ end) + + +-- This case is also in the emulated release gate (ORBIT_TEST_ONLY=startup). +-- With a pinned checkout it executes KOReader's actual opening coroutine. + + -- This case is also in the emulated release gate (ORBIT_TEST_ONLY=startup). -- With a pinned checkout it executes KOReader's actual opening coroutine. test("startup smoke: Home, history and file browser open during Full refresh with repair pending", function() @@ -4708,7 +3536,7 @@ test("startup smoke: Home, history and file browser open during Full refresh wit eq(Reader.showReader, stockShowReader, "book opening is never intercepted for repair") local show = Reader.showReader local old_do, old_co = Reader.doShowReader, Reader.showReaderCoroutine - local old_notices, old_busy, old_active = E.Mirror.notices, E.Mirror.busy, E.Mirror.active + local active=RE.Library.catalog_active local Info = require("ui/widget/infomessage") local source = [[ function Reader:showReaderCoroutine(file, provider, seamless) @@ -4733,7 +3561,7 @@ end for _, origin in ipairs({ "Home", "history", "file browser" }) do W.queue, W.shown = {}, {} ReaderUI.instance = nil - E.Mirror.notices, E.Mirror.busy, E.Mirror.active = true, true, true + RE.Library.catalog_active=true -- No companion repair answer is delivered. Opening cannot wait for one. local before, quits = #W.broadcasts, W.quits or 0 local reader = { document={file="/books/synthetic.epub"}, name="reader" } @@ -4755,7 +3583,7 @@ end package.loaded["ui/widget/trapwidget"] = old end) Reader.showReader, Reader.doShowReader, Reader.showReaderCoroutine = show, old_do, old_co - E.Mirror.notices, E.Mirror.busy, E.Mirror.active = old_notices, old_busy, old_active + RE.Library.catalog_active=active ReaderUI.instance = nil; W.shown = {} ok(success, err) end) @@ -4810,6 +3638,7 @@ if os.getenv("ORBIT_REQUIRE_READER_FLOWS") then end end dofile(here .. "/catalog_actions_flows.lua")({E=RE,W=W,test=test,eq=eq,ok=ok,newUI=newUI,UIManager=UIManager,store=store}) +dofile(here.."/retirement_flows.lua")(test,eq,ok,RE) 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/android/koreader/test/test_library.lua b/android/koreader/test/test_library.lua index 4d81e64f..5bc4a125 100644 --- a/android/koreader/test/test_library.lua +++ b/android/koreader/test/test_library.lua @@ -290,7 +290,7 @@ return function(test, eq, ok, here, Cache) local commands,expanded,started,finished,released=0,0,0,0,0 local nextPoll,owner,status owner="opaque";status={row_count=1,running=true,pct=0,beat=1} - local e=setmetatable({Cache=Cache,now_s=function() return 1 end,log=function() end,reading=function() return false end, + local e=setmetatable({S={keep_copies_current=false},Cache=Cache,now_s=function() return 1 end,log=function() end,reading=function() return false end, Store={now=function() return 1 end},Wifi={acquire=function() end,release=function() released=released+1 end}, UIManager={scheduleIn=function(_,delay,fn) eq(delay,3);nextPoll=fn end}, Badge={start=function() started=started+1 end,expand=function() expanded=expanded+1 end,update=function() end,finish=function() finished=finished+1 end}, @@ -336,35 +336,6 @@ return function(test, eq, ok, here, Cache) reading=true;e.Library.pollEvents();eq(reads,3) reading=false;body=string.rep("x",65537);e.Library.pollEvents();eq(acks,2);eq(changes,1) end) - test("catalog: native getters use neutral windows and fetch never forks or calls HTTP",function() - local calls,flushes,stock=0,0,0 - local last - local e=setmetatable({Compat={callable=function(v) return type(v)=="function" end,missingOn=function(obj,required) - local missing={};for k,v in pairs(required) do if type(obj[k])~=v then missing[#missing+1]=k end end;return missing - end},wrap=function(obj,key,factory) obj[key]=factory(obj[key]) end}, {__index=_G}) - setfenv(assert(loadfile(root.."ko/server/bookorbit.lua")),e)() - e.Library={compatEvent=function() end,paint=function(screen) - return {read=function(_,op,args) - calls=calls+1;last=args - if op=="connector.home" then return {shelves={reading={{reference=7,title="Ready",authors={}}}},row_count=2} end - eq(op,"connector.catalog");eq(screen,"library") - return {items={{reference=7,title="Ready",authors={"Fixture"},cover_available=true}},total=100,more=true} - end,flush=function() flushes=flushes+1 end} - end} - local Api={request=function() stock=stock+1;error("HTTP called") end,requestBlocking=function() error("HTTP called") end, - runInSubprocess=function() error("fork called") end,query=function() error("route constructed") end} - local Catalog={fetch=function() error("stock fetch called") end,dashboardRootFetch=function() error("stock dashboard called") end, - dashboardContext=function(_,body) return body end} - eq(e.Server.installCatalogApi(Api,Catalog),true) - local client=setmetatable({},{__index=Api}) - local cat=setmetatable({boardSources=function() return {reading={source="in-progress"}},{} end},{__index=Catalog}) - local body=cat:fetch("Catalog",function() return client:catalogBooks({size=999,page=2,author="Fixture"}) end) - eq(calls,1);eq(flushes,1);eq(last.limit,24);eq(last.offset,24);eq(last.selection.author,"Fixture") - eq(body.items[1].id,7);eq(body.items[1].title,"Ready");eq(body.size,24);eq(stock,0) - local value,err=cat:fetch("Catalog",function() return client:request("GET","forbidden") end) - eq(value,nil);eq(err,"cancelled");eq(stock,0);eq(e.Server.catalog_paint,nil) - local home=cat:dashboardRootFetch();eq(home.boardShelves.reading[1].id,7) - eq(calls,2);eq(flushes,2,"one batched Home read") - end) + end diff --git a/android/koreader/test/test_logic.lua b/android/koreader/test/test_logic.lua index b8b27715..77b95b0b 100644 --- a/android/koreader/test/test_logic.lua +++ b/android/koreader/test/test_logic.lua @@ -351,13 +351,7 @@ test("home: a BookOrbit page past the first -> page 1 first (M8C 11-22)", functi eq(H{ mode = "smart", on_dashboard = true, page_above_1 = true, from_other = true }, "dashboard", "from another app: the usual rule") end) -test("compat: missingOn names what an object lacks", function() - local Compat = M.Compat - eq(#Compat.missingOn({ boardPage = function() end, boardFlip = function() end, listMode = function() end, - listPaging = function() end, listGoPage = function() end }, Compat.PAGING), 0) - eq(table.concat(Compat.missingOn({ boardPage = function() end }, Compat.PAGING), ","), - "boardFlip,listGoPage,listMode,listPaging") -end) + test("home: cold start after KOReader was killed with a book open -> that book", function() eq(H{ mode = "smart", in_reader = false, from_other = true, reopen = true }, "book") end) @@ -465,42 +459,9 @@ test("disabled text names the disabler at run time, or stays neutral", function( eq(M.disabledText("BookSync Companion", nil, nil), "BookSync Companion is disabled by the system: re-enable it in Settings › Apps.") end) -test("compat: KOReader 2025.10+ HandlerSandbox (a callable table) counts as a function", function() - local C = M.Compat - local sandbox = setmetatable({}, { __call = function(_, module, ...) return true end }) - eq(C.callable(function() end), true) - eq(C.callable(sandbox), true, "callable table") - eq(C.callable({}), false, "plain table") - eq(C.callable("x"), false) - eq(C.callable(nil), false) - local p = { settings = {} } - for _, f in ipairs(C.FEATURES) do - for name, kind in pairs(f.needs) do - if kind == "function" then p[name] = name:sub(1, 2) == "on" and sandbox or function() end end - end - end - eq(next(C.check(p)), nil, "2.3.0 on KOReader 2026.07.1: nothing missing") -end) -test("compat: missing or mistyped plugin symbols turn off only their feature", function() - local C = M.Compat - local full = { settings = {} } - for _, f in ipairs(C.FEATURES) do - for name, kind in pairs(f.needs) do - if kind == "function" then full[name] = function() end end - end - end - eq(next(C.check(full)), nil, "complete plugin") - full._onSuspend = nil - full.fetchRemoteProgress = "not a function" - local m = C.check(full) - eq(m.sleep_snapshot[1], "_onSuspend") - eq(m.reading_sync[1], "fetchRemoteProgress") - eq(m.outbox, nil, "others unaffected") - local lines = C.lines(m, "2.4.0") - eq(#lines, 2) - eq(lines[1], "BookOrbit 2.4.0 changed: Sync while reading is off") -end) + + local Stats = M.Stats @@ -652,438 +613,7 @@ test("restart plan: a newer file loads now, or after the book; one try per versi eq(R.doneText("0.5.0"), "Updated to v0.5.0") end) -test("compat: Make BookOrbit home is written only where the plugin knows the setting", function() - local C = M.Compat - eq(C.settable({}, "catalog_auto_open", "home"), true, "unset (the plugin's default, off)") - eq(C.settable({ catalog_auto_open = "filemanager" }, "catalog_auto_open", "home"), true, "a known mode") - eq(C.settable({ catalog_auto_open = "always" }, "catalog_auto_open", "home"), false, "a mode we don't know") - eq(C.settable({ catalog_auto_open = 3 }, "catalog_auto_open", "home"), false, "not a string") - eq(C.settable(nil, "catalog_auto_open", "home"), false, "no settings table") - eq(C.settable({}, "catalog_auto_open", "bogus"), false, "a value the plugin doesn't take") -end) - --- Lists by series and by author (Group) -local G = M.Group -local function bk(id, t) - t.id = id - t.title = t.title or ("Book " .. id) - t.authors = t.authors or { "Rick Riordan" } - return t -end --- A shelf: Percy Jackson (ids, one missing from the shelf), Skyward by name only (an older --- server), two standalones, one book by two authors. -local shelf = { - bk(1, { seriesId = 7, seriesName = "Percy Jackson", seriesIndex = "2", readStatus = "read" }), - bk(2, { seriesId = 7, seriesName = "Percy Jackson", seriesIndex = "1", readStatus = "read" }), - bk(3, { seriesId = 7, seriesName = "Percy Jackson", seriesIndex = "5", readStatus = "reading", lastReadAt = "2026-11-20" }), - bk(4, { seriesId = 7, seriesName = "Percy Jackson", seriesIndex = "5.5" }), - bk(5, { seriesName = "Skyward", seriesIndex = "1", authors = { "Brandon Sanderson" }, readStatus = "rereading" }), - bk(6, { seriesName = "skyward", seriesIndex = "2", authors = { "Brandon Sanderson" } }), - bk(7, { authors = { "Brandon Sanderson" }, title = "Tress", addedAt = "2026-01-02" }), - bk(8, { authors = { "Nnedi Okorafor", "Brandon Sanderson" }, title = "Akata Witch", readStatus = "skimmed" }), - bk(9, { seriesId = 9, seriesName = "Émile's Tales", seriesIndex = "1", authors = { "Émile Zola" } }), -} - -test("lists: series rows from the list's books, in the plugin's section shape", function() - local rows = G.series(shelf) - eq(#rows, 3, "Percy, Skyward (by name), Émile") - local pj = rows[1] - eq(pj.title, "Percy Jackson"); eq(pj.id, "series:7"); eq(pj.seriesId, 7); eq(pj.count, 4) - eq(pj.readingCount, 1); eq(pj.finishedCount, 2); eq(pj.letter, "P") - eq(table.concat(pj.memberStates, ","), "finished,finished,reading,unread", "series order") - eq(pj.previewBooks[1].id, 2, "first by series index"); eq(#pj.previewBooks, 3) - eq(table.concat(pj.authorNames, ","), "Rick Riordan") - local sky = rows[2] - eq(sky.seriesId, nil, "no seriesId: grouped by name"); eq(sky.count, 2, "names fold case"); eq(sky.id, "Skyward") - eq(sky.readingCount, 1, "rereading counts as reading") - eq(rows[3].letter, "E", "accents fold for the letter") - eq(G.bucket("on_hold"), "reading"); eq(G.bucket("abandoned"), "finished"); eq(G.bucket("want_to_read"), "unread"); eq(G.bucket(nil), "unread") -end) - -test("lists: author rows count a book for each of its authors", function() - local rows = G.sectionBody(G.authors(shelf), "authors", {}).items - eq(#rows, 4) - local bs = rows[1] - eq(bs.title, "Brandon Sanderson"); eq(bs.id, "Brandon Sanderson"); eq(bs.count, 4) - eq(bs.readingCount, 1); eq(bs.finishedCount, 1); eq(bs.seriesName, "Skyward", "their series with the most books") - eq(bs.previewBooks[1].id, 5, "reading first"); eq(bs.previewBooks[2].id, 8, "then finished") - eq(rows[2].title, "Émile Zola", "A-Z with accents folded") -end) - -test("lists: sort, filter, q, buckets and offset slicing copy the server", function() - local rows = G.series(shelf) - local b = G.sectionBody(rows, "series", {}) - eq(b.total, 3); eq(b.items[1].title, "Émile's Tales"); eq(b.items[3].title, "Skyward") - eq(b.buckets[1].key, "E"); eq(b.buckets[1].index, 0); eq(b.buckets[3].key, "S"); eq(b.buckets[3].index, 2) - b = G.sectionBody(rows, "series", { sort = "name_desc" }) - eq(b.items[1].title, "Skyward") - b = G.sectionBody(rows, "series", { sort = "books" }) - eq(b.items[1].title, "Percy Jackson"); eq(b.buckets, nil, "no buckets by most books") - eq(G.sectionBody(rows, "series", { filter = "reading" }).total, 2, "under way: Percy (reading) and Skyward (rereading)") - eq(G.sectionBody(rows, "series", { filter = "finished" }).total, 0, "all finished") - local done = G.series({ bk(20, { seriesId = 1, seriesName = "Done", readStatus = "read" }), bk(21, { seriesId = 1, seriesName = "Done", readStatus = "read" }), - bk(22, { seriesId = 2, seriesName = "Half", readStatus = "read" }), bk(23, { seriesId = 2, seriesName = "Half" }) }) - eq(G.sectionBody(done, "series", { filter = "finished" }).items[1].title, "Done") - eq(G.sectionBody(done, "series", { filter = "reading" }).items[1].title, "Half", "some but not all finished is under way") - local authors = G.authors(shelf) - eq(G.sectionBody(authors, "authors", { filter = "finished" }).total, 3, "an author with one book finished") - eq(G.sectionBody(rows, "series", { q = "emile" }).items[1].title, "Émile's Tales", "q folds accents") - eq(G.sectionBody(rows, "series", { q = "JACK" }).total, 1) - local p2 = G.sectionBody(rows, "series", { size = 2, offset = 2 }) - eq(#p2.items, 1); eq(p2.items[1].title, "Skyward"); eq(p2.page, 2); eq(p2.offset, 2); eq(p2.hasNext, false); eq(p2.hasPrevious, true) - local pg = G.sectionBody(rows, "series", { size = 2, page = 1 }) - eq(#pg.items, 2); eq(pg.hasNext, true); eq(pg.offset, nil) -end) - -test("lists: an author's books by series, with Not in a series last", function() - local mine = G.select(shelf, "Brandon Sanderson", nil) - eq(#mine, 4) - local b = G.sectionBody(G.series(mine), "series", { sort = "books" }, G.standalone(mine)) - eq(b.total, 2); eq(b.items[1].title, "Skyward"); eq(b.items[2].title, "Not in a series"); eq(b.items[2].count, 2) - eq(b.items[2].id, G.STANDALONE) - eq(G.sectionBody(G.series(mine), "series", { q = "sky" }, G.standalone(mine)).total, 1, "a name filter leaves it out") - eq(#G.select(shelf, "Brandon Sanderson", G.STANDALONE), 2, "its books") - eq(#G.select(shelf, "Brandon Sanderson", "name:skyward"), 2) -end) - -test("lists: which list a book list is, and the request that reads it all", function() - eq(G.listOf({ collectionId = 4, libraryId = 2 }).section, "collections") - eq(G.listOf({ smartScopeId = "3" }).id, 3) - eq(G.listOf({ libraryId = 2 }).section, "libraries") - -- v0.11.2: the whole library's lists group too (All books, Recently updated); a search, a - -- series or author page and a list by id don't. - eq(G.listOf({ sort = "title" }).section, "all", "All books") - eq(G.listOf({ sort = "recently_updated", order = "desc" }).section, "all", "Recently updated") - eq(G.listOf({ sort = "title", q = "dune" }), nil, "a search") - eq(G.listOf({ seriesId = 7, sort = "series" }), nil, "a series page") - eq(G.listOf({ author = "A", sort = "series" }), nil, "an author page") - eq(G.listOf({ ids = "1,2", sort = "title" }), nil, "a list by id") - local all = G.fetchParams({ sort = "recently_updated", order = "desc", readStatus = "unread", page = 4, size = 12 }, 1) - eq(all.readStatus, "unread", "its filter"); eq(all.sort, "title"); eq(all.order, nil); eq(all.size, 100) - local dp, dhow = G.drill({ section = "all" }, { readStatus = "unread", sort = "title" }, { { id = 1 } }, { seriesId = 4 }, {}) - eq(dhow, "server", "a row of All books: the server's series page"); eq(dp.seriesId, 4); eq(dp.readStatus, "unread") - local q = G.fetchParams({ collectionId = 4, readStatus = "unread", sort = "author", page = 3, size = 12, offset = 24, on_device_filter = true, orbitGroup = "g1" }, 2) - eq(q.collectionId, 4); eq(q.readStatus, "unread", "the shelf's filters"); eq(q.size, 100); eq(q.page, 2); eq(q.sort, "title") - eq(q.offset, nil); eq(q.on_device_filter, nil); eq(q.orbitGroup, nil) -end) - -test("lists: drill-down params per list kind", function() - local some = { shelf[1], shelf[2] } - local p, how = G.drill({ section = "libraries", id = 2 }, { libraryId = 2, readStatus = "unread", sort = "title" }, some, - { sort = "series", seriesId = 7 }, { orbitGroup = "g1" }) - eq(how, "server"); eq(p.libraryId, 2); eq(p.seriesId, 7); eq(p.readStatus, "unread"); eq(p.sort, "series"); eq(p.ids, nil); eq(p.orbitGroup, "g1") - p = G.drill({ section = "collections", id = 4 }, { collectionId = 4 }, some, { series = "Skyward", author = "B" }, {}) - eq(p.collectionId, 4); eq(p.series, "Skyward"); eq(p.author, "B") - p, how = G.drill({ section = "smart-scopes", id = 3 }, { smartScopeId = 3 }, some, { sort = "series", seriesId = 7 }, {}) - eq(how, "ids"); eq(p.ids, "1,2"); eq(p.smartScopeId, nil, "the server would drop the other filters"); eq(p.seriesId, 7) - local many = {} - for i = 1, 201 do many[i] = { id = i } end - p, how = G.drill({ section = "smart-scopes", id = 3 }, { smartScopeId = 3 }, many, { sort = "title" }, { orbitGroup = "g1" }) - eq(how, "held", "past the ids cap: the books held here"); eq(p.ids, nil); eq(p.orbitLocal, "1") - p, how = G.drill({ section = "collections", id = 4 }, { collectionId = 4 }, some, { sort = "title" }, {}, true) - eq(how, "ids", "flat: by id in any list"); eq(p.collectionId, nil) -end) - -test("lists: held books answer a request the way the server pages it", function() - local token = G.remember({ list = { section = "smart-scopes", id = 3 }, params = {}, title = "Unread fantasy", books = shelf }) - local params = { orbitGroup = token, orbitLocal = "1", orbitAuthor = "Rick Riordan", orbitSeries = "id:7", sort = "series", size = 2, page = 2 } - local books = G.localBooks(params) - eq(#books, 4) - local b = G.booksBody(books, params) - eq(b.total, 4); eq(#b.items, 2); eq(b.items[1].id, 3, "series order, page 2"); eq(b.page, 2); eq(b.hasNext, false) - eq(G.booksBody(books, { readStatus = "finished", sort = "title" }).total, 2) - eq(G.booksBody(G.localBooks({ orbitGroup = token }), { sort = "recently_added", size = 1 }).items[1].id, 7, "newest first") - eq(G.localBooks({ orbitGroup = "gone" }), nil) - local s = G.strip({ orbitGroup = token, orbitLocal = "1", ids = "1,2", sort = "title" }) - eq(s.orbitGroup, nil); eq(s.orbitLocal, nil); eq(s.ids, "1,2") - local plain = { sort = "title" } - eq(G.strip(plain), plain, "nothing to strip: the same table") - for _ = 1, G.SNAPSHOTS do G.remember({ books = {} }) end - eq(G.held[token], nil, "the oldest held list goes") -end) - ----------------------------------------------------------------- end of book (Finish) -local F = M.Finish -local FC = JSON.fixture(here, "bookorbit/finish-cases.json") - -test("end of book: next in series, suggestions and author from the shared fixtures", function() - -- @fixture bookorbit/finish-cases.json#picker @fixture bookorbit/catalog-book.no-author.json @fixture bookorbit/catalog-book.no-series.json @fixture bookorbit/catalog-book.series-fractional.json @fixture bookorbit/catalog-book.series-gap.json @fixture bookorbit/catalog-book.series-last-all-read.json @fixture bookorbit/catalog-book.series-last-unread-earlier.json @fixture bookorbit/catalog-book.series-middle.json - for _, c in ipairs(FC.picker) do - local d = JSON.fixture(here, "bookorbit/" .. c.fixture) - local n = F.next(d) - if c.next == nil then eq(n, nil, c.fixture .. " no next card") - else - eq(n.kind, c.next.kind, c.fixture) - if c.next.id then eq(n.book.id, c.next.id, c.fixture .. " book") end - if c.next.number then eq(n.number, c.next.number, c.fixture .. " number") end - if c.next.read ~= nil then eq(n.read, c.next.read, c.fixture .. " read") end - end - local nid = n and n.book and n.book.id - for limit, want in pairs({ [1] = c.suggest1, [2] = c.suggest2 }) do - local got = F.suggestions(d, limit, nid) - eq(#got, #want, c.fixture .. " suggestions " .. limit) - for i, id in ipairs(want) do eq(got[i].book.id, id, c.fixture .. " suggestion " .. i) end - end - eq(F.author(d), c.author, c.fixture .. " author") - end -end) -test("end of book: the card's words", function() - local d = JSON.fixture(here, "bookorbit/catalog-book.series-gap.json") - eq(F.nextCard(F.next(d)).line, "Book 3 isn't in your library") - local m = F.nextCard(F.next(JSON.fixture(here, "bookorbit/catalog-book.series-middle.json")), true) - eq(m.line, "Next in series · Book 3"); eq(m.title, "Wayfarer Three"); eq(m.action, "open") - local f = F.nextCard(F.next(JSON.fixture(here, "bookorbit/catalog-book.series-fractional.json")), false) - eq(f.line, "Next in series · Book 2.5 · Read"); eq(f.action, "download") - eq(F.nextCard(F.next(JSON.fixture(here, "bookorbit/catalog-book.series-last-all-read.json"))).line, "You've finished the series") - eq(F.nextCard(F.next(JSON.fixture(here, "bookorbit/catalog-book.series-last-unread-earlier.json"))).line, - "Last book · not read yet: Book 2") -end) - -test("end of book: drain plan, errors and the stale-push hold from the shared table", function() - -- @fixture bookorbit/finish-cases.json#drain - for _, c in ipairs(FC.drain) do - local p = F.plan(F.newJob({ hash = "h", rating = c.job.rating, status_seen = c.job.status_seen }), c.server) - eq(p.read_status, c.expect.read_status, c.name) - eq(p.rating, c.expect.rating, c.name .. " rating") - end - -- @fixture bookorbit/finish-cases.json#errors - for _, c in ipairs(FC.errors) do - local job = F.newJob({ hash = "h" }); job.attempts = c.attempts_before - eq(F.onError(job, c.code, 1000), c.expect, tostring(c.code)) - if c.next_try_in then eq(job.next_try_at, 1000 + c.next_try_in, tostring(c.code) .. " backoff"); eq(job.parked, c.parked) end - end - -- @fixture bookorbit/finish-cases.json#hold - for i, c in ipairs(FC.hold) do eq(F.holdPush(c.final, c.push, c.forward, c.released), c.expect, "hold " .. i) end -end) - -test("end of book: one job per book; Undo deletes it; ratings toggle", function() - local q = {} - local a = F.put(q, F.newJob({ hash = "x", now = 5, finished_on = "2026-11-22" })) - F.setRating(a, 4, nil); eq(a.rating, 4) - F.setRating(a, 4, 4); eq(a.rating, "clear", "the same star again clears") - F.setRating(a, 3, nil) - local b = F.put(q, F.newJob({ hash = "x", now = 9 })) - eq(b.rating, 3, "the newer job keeps the rating"); eq(q.x, b) - F.put(q, F.newJob({ hash = "y", now = 7 })) - local due = F.due(q, 100) - eq(#due, 2); eq(due[1].hash, "y", "oldest first") - q.y.parked = true - eq(#F.due(q, 100), 1, "parked waits"); eq(#F.due(q, 100, true), 2, "a manual sync retries it") - q.x.next_try_at = 200 - eq(#F.due(q, 100), 0, "backing off") - ok(F.cancel(q, "x")); eq(q.x, nil); ok(not F.cancel(q, "x")) - eq(F.day(0), nil, "an unset clock gives no day"); eq(F.day(1795000000, function() return "2026-11-18" end), "2026-11-18") -end) - ----------------------------------------------------------------- local-first Home (LocalFirst) -local LF = M.LocalFirst - -local function localState(t, keys) - local by = {} - for k, v in pairs(t or {}) do by[keys == "string" and tostring(k) or tonumber(k)] = v end - return { byBookId = by } -end - -test("local-first: overlay cases from the shared fixture", function() - -- @fixture localfirst/overlay-cases.json - for _, c in ipairs(JSON.fixture(here, "localfirst/overlay-cases.json").cases) do - local body = c.body - local before = LF.serialize(body) - local out = LF.overlay(body, localState(c["local"], c.localKeys)) - eq(LF.serialize(body), before, c.name .. ": the server body is never modified") - for list, want in pairs(c.expect) do - if list == "goalDone" then - eq(out.readingGoal.completedBooks, want, c.name .. " goal") - else - local shelf = list:match("^shelf:(.+)$") - local got = (shelf and (out.boardShelves or {})[shelf] or out[list]) or {} - eq(#got, #want, c.name .. " " .. list .. " length") - for i, w in ipairs(want) do - for k, v in pairs(w) do eq(got[i][k], v, c.name .. " " .. list .. "[" .. i .. "]." .. k) end - end - end - end - for id, want in pairs(c.notSynced or {}) do - eq(LF.notSynced(localState(c["local"]).byBookId[tonumber(id)], c.autoSync), want, c.name .. " not synced") - end - end -end) - -test("local-first: freshness stamp cases from the shared fixture", function() - -- @fixture localfirst/stamp-cases.json - for i, c in ipairs(JSON.fixture(here, "localfirst/stamp-cases.json").cases) do - eq(LF.stamp(c), c.expect, "stamp " .. i) - end -end) - -test("local-first: ISO times, content keys and changed tiles", function() - eq(LF.parseIso("1970-01-02T00:00:00.000Z"), 86400) - eq(LF.parseIso("2026-11-22T10:00:00Z") - LF.parseIso("2026-11-22"), 36000) - eq(LF.parseIso(nil), nil) - local d1 = { continue_reading = { { id = 1, progressPercentage = 40.2, readStatus = "reading" } }, shelves = { a = {} }, - goal = { books = 24, done = 6, year = 2026 }, streak = { current = 3 }, week_min = 90, today_min = 10, now = 1 } - local d2 = { continue_reading = { { id = 1, progressPercentage = 39.8, readStatus = "reading" } }, shelves = { a = {} }, - goal = { books = 24, done = 7, year = 2026 }, streak = { current = 3 }, week_min = 90, today_min = 10, now = 2 } - local tiles = { { key = "t1", kind = "hero" }, { key = "t2", kind = "goalpace" }, { key = "t3", kind = "clock" }, - { key = "t4", kind = "shelf", source = "a" } } - local ch = LF.changedTiles(tiles, tiles, d1, d2) - eq(#ch, 1, "rounded % unchanged; only the goal"); eq(ch[1], "t2") - eq(#LF.changedTiles(tiles, tiles, d1, d1), 0, "an identical refresh changes no tile") - eq(LF.changedTiles(tiles, { tiles[1] }, d1, d2), nil, "a different tile set: full repaint") - ok(LF.tileKey("newwidget", d1) ~= LF.tileKey("newwidget", d2), "unknown types key on all of d") - eq(LF.tileKey("newwidget", d1), LF.tileKey("newwidget", (function() local c = {} for k, v in pairs(d1) do c[k] = v end c.now = 99 return c end)()), - "the clock alone changes nothing") -end) - ----------------------------------------------------------------- write-through cache (shared cases) -local C = M.ServerCache --- The companion's rules as the fake companion plays them (test/companion_rules.lua): checked here --- against the tables the companion's tests read, so the fake cannot drift from the real worker. -local CR = dofile(here .. "/companion_rules.lua")(C) -local CC = JSON.fixture(here, "cache/cases.json") -local function set(list) local t = {} for _, v in ipairs(list or {}) do t[tostring(v)] = true end return t end -local function sameSet(a, b, what) - local sa, sb = set(a), set(b) - for k in pairs(sa) do ok(sb[k], what .. ": unexpected " .. k) end - for k in pairs(sb) do ok(sa[k], what .. ": missing " .. k) end -end - -test("cache: keys (shared cases)", function() - -- @fixture cache/cases.json#keys - for _, c in ipairs(CC.keys) do eq(C.key(c.a) == C.key(c.b), c.same, c.name) end -end) - -test("cache: what is cached (shared cases)", function() - -- @fixture cache/cases.json#cacheable - for _, c in ipairs(CC.cacheable) do eq(C.cacheable(c.method, c.path), c.cached, c.method .. " " .. c.path) end -end) - -test("cache: reads (shared cases)", function() - -- @fixture cache/cases.json#reads - for _, c in ipairs(CC.reads) do - local serve, fetch = C.readPlan(c.entry, c.now, c.mode, c.offline) - eq(serve, c.serve, c.name .. " serve"); eq(fetch, c.fetch, c.name .. " fetch") - end -end) - -test("cache: revalidation (shared cases)", function() - -- @fixture cache/cases.json#revalidate - for _, c in ipairs(CC.revalidate) do - local changed, stored = C.revalidate(c.cached, c.reply, c.status) - eq(changed, c.changed, c.name .. " changed"); eq(stored, c.stored, c.name .. " stored") - end -end) - -test("cache: writes patch what they change (shared cases)", function() - -- @fixture cache/cases.json#writes - for _, c in ipairs(CC.writes) do - local entries = C.copy(c.entries) - local stale = {} - if c.write.status >= 200 and c.write.status < 300 then - local eff = C.writeEffect(c.write.method, c.write.path, c.write.body) - -- What the companion is sent (CacheStore.patched applies it; CacheStoreTest reads the same cases). - eq(eff.id, c.effect.id, c.name .. " effect id"); eq(eff.stale_home, c.effect.stale_home, c.name .. " effect stale_home") - for k, v in pairs(c.effect.fields) do eq(C.encode(eff.fields[k]), C.encode(v), c.name .. " effect " .. k) end - for k, v in pairs(eff.fields) do ok(c.effect.fields[k] ~= nil or v == C.NULL, c.name .. " effect sets " .. k) end - for _, body in pairs(entries) do if eff.id then CR.patch(body, eff.id, eff.fields) end end - if eff.stale_home then stale = { "dashboard" } end - else - eq(c.effect, nil, c.name .. ": a failed write sends nothing") - end - for k, want in pairs(c.expect) do eq(C.encode(entries[k]), C.encode(want), c.name .. " " .. k) end - sameSet(stale, c.stale, c.name .. " stale") - end -end) - -test("companion rules: a check keeps the saved random pick; a Full refresh takes the new one (shared cases)", function() - -- @fixture cache/cases.json#settle - for _, c in ipairs(CC.settle) do eq(C.encode(CR.settle(c.cached, c.reply, c.mode)), C.encode(c.expect), c.name) end -end) - -test("cache: the offline mirror's list identities, pages, re-paging and TTL (shared cases)", function() - -- @fixture cache/cases.json#mirror.windows - for _, c in ipairs(CC.mirror.windows) do - local w = C.listWindow(c.path) - if c.list == false then - eq(w, nil, c.path .. " is not a mirrored list") - else - local o = C.listWindow(c.identity_of) - eq(C.key({ path = w.identity }) == C.key({ path = o.identity }), c.same, c.path) - eq(C.listWindow(CR.mirrorPage(w.identity, 2)).identity, w.identity, "a mirror page keeps the identity") - end - end - -- @fixture cache/cases.json#mirror.slices - for _, c in ipairs(CC.mirror.slices) do - local pages = {} - for _, n in ipairs(c.saved_pages) do - local items = {} - for i = (n - 1) * C.MIRROR_PAGE + 1, math.min(c.total, n * C.MIRROR_PAGE) do table.insert(items, { id = i }) end - pages[n] = { items = items, total = c.total, page = n, size = C.MIRROR_PAGE, seriesSummary = { total = c.total } } - end - local b = C.slice(c.window, pages) - if c.items == nil then - eq(b, nil, c.name) - else - ok(b, c.name .. ": answered") - eq(b.items[1].id, c.items[1], c.name .. " first"); eq(b.items[#b.items].id, c.items[2], c.name .. " last") - eq(b.total, c.total, c.name .. " total"); eq(b.hasNext, c.hasNext, c.name .. " hasNext"); eq(b.hasPrevious, c.hasPrevious, c.name .. " hasPrevious") - eq(b.seriesSummary.total, c.total, c.name .. " keeps the list's other fields") - end - end - -- @fixture cache/cases.json#mirror.due - for _, c in ipairs(CC.mirror.due) do eq(C.mirrorDue(c.mirror, c.now, c.ttl_days, c.lib_version), c.due, c.name) end - ok(C.isSearch("/koreader/plugin/catalog/books?q=dune") and not C.isSearch("/koreader/plugin/catalog/books?page=1"), "search") -end) - -test("lists: On device groups by series and author, its rows by id", function() - local G = M.Group - local list = G.listOf({ ids = "3,5,9", sort = "title", on_device_filter = true }) - ok(list and list.section == "on-device", "On device is a list") - eq(G.listOf({ ids = "3,5" }), nil, "ids alone (a grouped row) is not") - local q = G.fetchParams({ ids = "3,5,9", sort = "title", on_device_filter = true, page = 2 }, 1) - eq(q.ids, "3,5,9", "reads by its ids"); eq(q.on_device_filter, nil, "never sends the plugin's mark") - local p, how = G.drill(list, { ids = "3,5,9" }, { { id = 9 }, { id = 3 } }, { seriesId = 4 }, {}) - eq(how, "ids", "a row drills by id"); eq(p.ids, "3,9", "its books") -end) - -test("cache: encode is canonical and round-trips", function() - local v = { b = { 1, 2, { z = "x\n" } }, a = 1.5, c = true, [10] = "ten" } - eq(C.encode(C.decode(C.encode(v))), C.encode(v)) - eq(C.encode({ a = 1, b = 2 }), C.encode({ b = 2, a = 1 })) -end) - -test("companion rules: the mirror's stop note (shared cases; the eviction order is StorageLogic's)", function() - -- @fixture cache/cases.json#storage.notes - for _, c in ipairs(CC.storage.notes) do eq(CR.limitText(c.what, c.done, c.total), c.text, c.text) end - eq(C.STORAGE_DEFAULT_MB, 250, "250 MB by default") -end) - -test("cache: a mirror request with no answer is retried, smaller pages, then skipped (shared cases)", function() - -- @fixture cache/cases.json#mirror.retry - for _, c in ipairs(CC.mirror.retry) do - local r = CR.mirrorRetry(c.tries, c.size, c.page) - eq(r.skip == true, c.skip == true, c.name .. " skip") - if not c.skip then eq(r.wait_s, c.wait_s, c.name .. " wait"); eq(r.size, c.size_next, c.name .. " size") end - end - -- @fixture cache/cases.json#mirror.small_pages - for _, c in ipairs(CC.mirror.small_pages) do - local pages = {} - for _, n in ipairs(c.saved_pages) do - local items = {} - for i = (n - 1) * c.page_size + 1, math.min(c.total, n * c.page_size) do table.insert(items, { id = i }) end - pages[n] = { items = items, total = c.total, page = n, size = c.page_size } - end - eq(C.pageCount(c.total, c.page_size), c.pages, c.name .. " pages") - local w = C.listWindow(CR.mirrorPage("/koreader/plugin/catalog/sections/series", 3, c.page_size)) - eq(w.size, c.page_size, c.name .. " asks that size") - local b = C.slice(c.window, pages, c.page_size) - if c.items == nil then eq(b, nil, c.name) else - eq(b.items[1].id, c.items[1], c.name .. " first"); eq(b.items[#b.items].id, c.items[2], c.name .. " last") - eq(b.hasNext, c.hasNext, c.name .. " hasNext") - end - end -end) ---------------------------------------------------------------- end-of-book sheet layout local SL = M.SheetLayout @@ -1156,148 +686,6 @@ test("end-of-book sheet: rows never overlap, widths are symmetric, rows fit thei end end) ----------------------------------------------------------------- recommended settings (addon-mode §5) -local R = M.Recommended --- A fake KOReader: values by item id, defaults by item id, unavailable ids. -local function world(cur, opts) - opts = opts or {} - return function(it) - if opts.missing and opts.missing[it.id] then return { available = false, reason = "missing" } end - local defaults = opts.defaults or {} - local d = defaults[it.id] - if d == nil and it.kind == "gesture" then d = nil end - return { available = true, current = cur[it.id], default = d } - end -end -local BO_DEFAULTS = { ["bo.auto_sync"] = false, ["bo.sync_forward"] = 1, ["bo.home"] = "off" } -local function fresh() - return { ["bo.auto_sync"] = false, ["bo.sync_forward"] = 1, ["bo.home"] = "off" } -end -local function states(plan) - local out = {} - for _, d in ipairs(plan.decisions) do out[d.item.id] = d.state end - return out -end - -test("recommended: an item's state (BookOrbit key, gesture table, KOReader global)", function() - local bo = R.item("bo.sync_forward") - eq(R.classify(bo, { current = 2, default = 1 }), "already") - eq(R.classify(bo, { current = 1, default = 1 }), "at_default") - eq(R.classify(bo, { current = 3, default = 1 }), "conflict") - local g = R.item("g.apps") - eq(R.classify(g, { current = { increase_frontlight = 0 }, default = { increase_frontlight = 0 } }), "at_default", "table equal by value") - eq(R.classify(g, { current = nil, default = nil }), "at_default", "no light: nothing is the default") - eq(R.classify(g, { current = { orbit_open_apps = true }, default = nil }), "already") - eq(R.classify(g, { current = { toc = true }, default = { increase_frontlight = 0 } }), "conflict") - local ko = R.item("ko.wifi_on") - eq(R.classify(ko, { current = nil }), "at_default", "unset is the default") - eq(R.classify(ko, { current = "prompt" }), "at_default", "KOReader's own default value") - eq(R.classify(ko, { current = "ignore" }), "conflict") - eq(R.classify(ko, { current = "turn_on" }), "already") -end) - -test("recommended: a fresh KOReader gets every available item, and one line saying how many", function() - local plan = R.plan(R.ITEMS, nil, world(fresh(), { defaults = BO_DEFAULTS })) - eq(plan.applied, #R.ITEMS, "all applied") - eq(plan.conflicts, 0) - local rec, n = R.record(nil, plan, 100) - eq(n, 8) - eq(R.lineText(n, plan.conflicts), "Applied 8 recommended settings · Review") - eq(R.reportState(rec), "applied") - eq(rec.unseen, 8) -end) - -test("recommended: a customised KOReader keeps every changed value; those are listed for review", function() - local cur = fresh() - cur["bo.sync_forward"] = 3 -- the user picked Don't sync - cur["g.sync_all"] = { toc = true } -- the user's own gesture - local plan = R.plan(R.ITEMS, nil, world(cur, { defaults = BO_DEFAULTS })) - local st = states(plan) - eq(st["bo.sync_forward"], "conflict") - eq(st["g.sync_all"], "conflict") - eq(st["bo.auto_sync"], "at_default") - eq(plan.applied, 6); eq(plan.conflicts, 2) - eq(R.lineText(plan.applied, plan.conflicts), "Applied 6 · 2 to review") - local rec = R.record(nil, plan, 1) - eq(rec.items["bo.sync_forward"], "conflict") - eq(R.reportState(rec), "partial") - eq(R.lineText(0, 2), "Review 2 recommended settings") - eq(R.lineText(0, 0), nil, "silent when nothing changed") -end) - -test("recommended: an untouched-only item is at default only when nothing was changed", function() - local items = { { id = "o.x", kind = "orbit", ours = true, untouched_only = true }, R.item("bo.sync_forward") } - local w = function(cur) return function(it) return { available = true, current = cur[it.id], default = it.id == "bo.sync_forward" and 1 or nil } end end - eq(states(R.plan(items, nil, w({ ["bo.sync_forward"] = 1 })))["o.x"], "at_default", "untouched") - eq(states(R.plan(items, nil, w({ ["bo.sync_forward"] = 3 })))["o.x"], "conflict", "customised") - eq(states(R.plan(items, { items = { ["bo.sync_forward"] = "kept" } }, w({})))["o.x"], "conflict", "kept earlier counts") -end) - -test("recommended: a later release adds an id: only that one is evaluated; kept and applied stay", function() - local rec = { items = { ["bo.auto_sync"] = "applied", ["bo.sync_forward"] = "kept", ["bo.home"] = "already", - ["ko.wifi_on"] = "applied", ["g.sync_sleep"] = "applied", ["g.sync_all"] = "conflict", ["g.this_book"] = "applied" } } - local looked = {} - local plan = R.plan(R.ITEMS, rec, function(it) looked[it.id] = true; return { available = true, current = nil, default = nil } end) - eq(#plan.decisions, 1, "one item") - ok(looked["g.apps"] and not looked["bo.sync_forward"], "only the new id") - eq(R.candidates(R.ITEMS, rec, nil)[1].id, "g.apps") -end) - -test("recommended: a capability appears: only the unblocked items are evaluated", function() - local plan = R.plan(R.ITEMS, nil, world(fresh(), { defaults = BO_DEFAULTS, missing = { ["ko.wifi_on"] = true, ["g.apps"] = true } })) - eq(plan.unavailable, 2) - local rec = R.record(nil, plan, 1) - eq(rec.items["g.apps"], "unavailable") - eq(R.reportState(rec), "applied", "unavailable items don't hold the row") - local plan2 = R.plan(R.ITEMS, rec, world({}, {})) - eq(#plan2.decisions, 2, "only the two that were unavailable") - eq(plan2.applied, 2) - rec = R.record(rec, plan2, 2) - eq(rec.items["g.apps"], "applied") - eq(rec.unseen, 8) -end) - -test("recommended: a failed apply stays unavailable, and isn't counted", function() - local plan = R.plan({ R.item("bo.home") }, nil, world(fresh(), { defaults = BO_DEFAULTS })) - local rec, n = R.record(nil, plan, 1, { ["bo.home"] = false }) - eq(n, 0); eq(rec.items["bo.home"], "unavailable") -end) - -test("recommended: backup and undo round trip; undo leaves a value the user changed since", function() - local it = R.item("g.apps") - local prior = { increase_frontlight = 0 } - local b = R.backup({ current = prior }, it, 5) - ok(b.had and R.equal(b.prior, prior) and b.prior ~= prior, "a copy of the prior value") - ok(R.undoable(b, { orbit_open_apps = true }), "still ours: undo") - ok(not R.undoable(b, { toc = true }), "changed since: left as is") - local b2 = R.backup({ current = nil }, R.item("ko.wifi_on"), 5) - ok(not b2.had and b2.prior == nil, "unset before") -end) - -test("recommended: the same results with mode full, addon and no companion (the mode is not an input)", function() - local cur = fresh(); cur["bo.home"] = "filemanager" - local a = states(R.plan(R.ITEMS, nil, world(cur, { defaults = BO_DEFAULTS }))) - for _, mode in ipairs({ "full", "addon", "none" }) do - local b = states(R.plan(R.ITEMS, nil, world(cur, { defaults = BO_DEFAULTS }))) - for id, s in pairs(a) do eq(b[id], s, mode .. " " .. id) end - end -end) - -test("recommended: lost capabilities undo only BookSync's applied items that need them", function() - local rec = { items = { ["ko.wifi_on"] = "applied", ["g.apps"] = "already", ["g.sync_all"] = "applied" } } - local lost = R.lostCaps(rec, function(cap) return cap ~= "wifi" and cap ~= "apps" end) - eq(#lost, 1); eq(lost[1].id, "ko.wifi_on") -end) - -test("recommended: values in plain words", function() - eq(R.valueLabel(R.item("bo.sync_forward"), 1), "Ask") - eq(R.valueLabel(R.item("ko.wifi_on"), nil), "Ask") - eq(R.valueLabel(R.item("g.apps"), nil), "Nothing") - eq(R.valueLabel(R.item("g.apps"), { orbit_open_apps = true }), "BookSync: other apps") - eq(R.reportState(nil), "none") - eq(R.reportState({ items = { a = "kept", b = "applied" } }), "reviewed") -end) - ---------------------------------------------------------------- companion caps (addon-mode §6) local Caps = M.Caps test("caps: from the file only, the status only, both (the status wins), none", function() @@ -1436,34 +824,6 @@ test("reading gate: every show, toast, activity start and restart names its gate eq(table.concat(missing, " "), "", "ungated show paths") end) --- shared/fixtures/cache/worker.json: the cache's keys, file names, list pages, cover names and --- entry format, which the companion's cache worker must match byte for byte (CacheWorkerTest --- reads the same file). Regenerate only when the plugin's rules change, then fix the companion. -test("cache worker fixture: the plugin's keys, hashes, pages, cover names and entry format", function() - local Cache = M.ServerCache - -- @fixture cache/worker.json - local fx = JSON.fixture(here, "cache/worker.json") - for _, k in ipairs(fx.keys) do - local key = Cache.key({ account = k.account, server = k.server, method = "GET", path = k.path }) - eq((key:gsub(".", function(c) return string.format("%02x", c:byte()) end)), k.key_hex, "key of " .. k.path) - eq(Cache.hash(key), k.hash, "hash of " .. k.path) - end - for _, w in ipairs(fx.windows) do - local got = Cache.listWindow(w.path) - eq(got and got.identity, w.identity, "identity of " .. w.path) - if got then - eq(got.kind, w.kind, "kind"); eq(got.section, w.section, "section") - eq(CR.mirrorPage(got.identity, 2, nil), w.page2, "page 2"); eq(CR.mirrorPage(got.identity, 1, 50), w.page1_50, "page 1 of 50") - end - end - for _, c in ipairs(fx.covers) do - eq(CR.coverName({ id = c.id, updatedAt = c.updatedAt, author_photo = c.author_photo or nil }), c.name, "cover of " .. c.id) - end - local e = fx.entry - local body = JSON.decode(e.body_json) - eq(Cache.encode({ key = e.key, body = body, fetched_at = e.fetched_at, validated_at = e.validated_at, path = e.path }), e.lua, "entry") -end) - test("sleep screen, Every sleep: a setting value", function() eq(SP.normalize({ sleep_hours = 0 }).sleep_hours, 0, "Every sleep is a value") eq(SP.normalize({ sleep_hours = "0" }).sleep_hours, 0) @@ -1537,16 +897,17 @@ end) -- @fixture settings/merge.json local MERGE = JSON.fixture(here, "settings/merge.json") +local MERGE_INDEX=SettingsSync.index(SettingsSync.decodeJson(schemaText),{["server-home"]="bookorbit"}) for _, c in ipairs(MERGE.cases) do test("settings merge: " .. c.name, function() local vals, at, remote = {}, {}, {} - for k, e in pairs(c["local"]) do vals[k] = SettingsSync.fromWire(SIDX.byKey[k], e.v); at[k] = e.at end + for k, e in pairs(c["local"]) do vals[k] = SettingsSync.fromWire(MERGE_INDEX.byKey[k], e.v); at[k] = e.at end for k, e in pairs(c.remote) do remote[k] = { v = e.v, at = e.at } end - local taken = SettingsSync.merge(SIDX, vals, at, remote, c.now, c.remote_wins_tie) + local taken = SettingsSync.merge(MERGE_INDEX, vals, at, remote, c.now, c.remote_wins_tie) local keys = {} for _, t in ipairs(taken) do table.insert(keys, t.key); vals[t.key] = t.value; at[t.key] = t.at end eq(table.concat(keys, ","), table.concat(c.taken, ","), "taken") - for k, v in pairs(c.expect) do eq(SettingsSync.toWire(SIDX.byKey[k], vals[k]), v, k) end + for k, v in pairs(c.expect) do eq(SettingsSync.toWire(MERGE_INDEX.byKey[k], vals[k]), v, k) end end) end diff --git a/docs/FEATURES.md b/docs/FEATURES.md index eaed2208..d16c6c9a 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -51,7 +51,7 @@ Counts include settings exposure as separate rows; they are not feature quality | 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) | | No unsolicited overlays or focus changes while reading | ✅ (v0.11.3-rc.17) Gate and companion Reading. [android/koreader/orbit.koplugin/ko/notices.lua:6](../android/koreader/orbit.koplugin/ko/notices.lua#L6), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ReadingLogic.kt:11](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ReadingLogic.kt#L11) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Reader activity gate. [xteink/orbify/Quiet.cpp:9](../xteink/orbify/Quiet.cpp#L9), [xteink/overlay/patches/v2.0/0031-orbify-reading-quiet.patch:9](../xteink/overlay/patches/v2.0/0031-orbify-reading-quiet.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Reader activity gate. [xteink/orbify/Quiet.cpp:9](../xteink/orbify/Quiet.cpp#L9), [xteink/overlay/patches/v2.0/0031-orbify-reading-quiet.patch:9](../xteink/overlay/patches/v2.0/0031-orbify-reading-quiet.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Reader activity gate. [xteink/orbify/Quiet.cpp:9](../xteink/orbify/Quiet.cpp#L9), [xteink/overlay/patches/v2.0/0031-orbify-reading-quiet.patch:9](../xteink/overlay/patches/v2.0/0031-orbify-reading-quiet.patch#L9) | -| Local reading first; return to book then library home | ✅ (v0.11.3-rc.17) Smart Home and local state hooks. [android/koreader/orbit.koplugin/ko/home.lua:9](../android/koreader/orbit.koplugin/ko/home.lua#L9), [android/koreader/orbit.koplugin/ko/server/bookorbit/local_view.lua:30](../android/koreader/orbit.koplugin/ko/server/bookorbit/local_view.lua#L30) | 🟡 Cached native Home and sync tile; no Android smart Home-button policy; **deliberately deferred: ROADMAP Next release BookSync Home**. [xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch:9](../xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch#L9) | 🟡 Cached native Home and sync tile; no Android smart Home-button policy; **deliberately deferred: ROADMAP Next release BookSync Home**. [xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch:9](../xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch#L9) | 🟡 Cached native Home and sync tile; no Android smart Home-button policy; **deliberately deferred: ROADMAP Next release BookSync Home**. [xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch:9](../xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch#L9) | +| Local reading first; return to book then library home | ✅ (v0.11.3-rc.17) Owned Smart Home and companion-materialized local state. [android/koreader/orbit.koplugin/ko/home.lua:9](../android/koreader/orbit.koplugin/ko/home.lua#L9), [android/koreader/orbit.koplugin/ko/library.lua:163](../android/koreader/orbit.koplugin/ko/library.lua#L163) | 🟡 Cached native Home and sync tile; no Android smart Home-button policy; **deliberately deferred: ROADMAP Next release BookSync Home**. [xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch:9](../xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch#L9) | 🟡 Cached native Home and sync tile; no Android smart Home-button policy; **deliberately deferred: ROADMAP Next release BookSync Home**. [xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch:9](../xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch#L9) | 🟡 Cached native Home and sync tile; no Android smart Home-button policy; **deliberately deferred: ROADMAP Next release BookSync Home**. [xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch:9](../xteink/overlay/patches/v2.0/0037g-orbify-home-sync-tile.patch#L9) | | BookSync reading layout: top clock, bottom battery/chapter/progress | ✅ (v0.11.3-rc.17) Paint inside existing margins; optional size caps. [android/koreader/orbit.koplugin/ko/status_layout.lua:5](../android/koreader/orbit.koplugin/ko/status_layout.lua#L5) | 🟡 Native configurable clock/battery/chapter/progress slots plus BookSync spacing; no single BookSync preset; **gap — no reason**. [xteink/tailnet/tailnet_build.py:284](../xteink/tailnet/tailnet_build.py#L284), [xteink/orbify/core/StatusFormat.h:6](../xteink/orbify/core/StatusFormat.h#L6), [src/util/ReaderStatusBarConfig.h:15](https://github.com/agosez/CrossInk-Bookorbit/blob/87e2e1984481e8a3d996f12b34b50a383f9013b8/src/util/ReaderStatusBarConfig.h#L15) | 🟡 Native configurable clock/battery/chapter/progress slots plus BookSync spacing; no single BookSync preset; **gap — no reason**. [xteink/tailnet/tailnet_build.py:284](../xteink/tailnet/tailnet_build.py#L284), [xteink/orbify/core/StatusFormat.h:6](../xteink/orbify/core/StatusFormat.h#L6), [src/util/ReaderStatusBarConfig.h:15](https://github.com/agosez/CrossInk-Bookorbit/blob/87e2e1984481e8a3d996f12b34b50a383f9013b8/src/util/ReaderStatusBarConfig.h#L15) | 🟡 Native configurable status bars remain; BookSync spaced page format cut; **hardware: X3 status formatting excluded for flash**. [xteink/tailnet/tailnet_build.py:284](../xteink/tailnet/tailnet_build.py#L284), [src/util/ReaderStatusBarConfig.h:15](https://github.com/agosez/CrossInk-Bookorbit/blob/87e2e1984481e8a3d996f12b34b50a383f9013b8/src/util/ReaderStatusBarConfig.h#L15) | | Recommended/current sleep cover with offline pool | ✅ (v0.11.3-rc.17) Companion pool and sleep screen. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/SleepPoolBuilder.kt:18](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/SleepPoolBuilder.kt#L18), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SleepScreen.kt:30](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SleepScreen.kt#L30) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) SD cover pool; native current-cover mode. [xteink/orbify/SleepScreen.cpp:34](../xteink/orbify/SleepScreen.cpp#L34), [xteink/orbify/SleepSettings.cpp:281](../xteink/orbify/SleepSettings.cpp#L281) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) SD cover pool; native current-cover mode. [xteink/orbify/SleepScreen.cpp:34](../xteink/orbify/SleepScreen.cpp#L34), [xteink/orbify/SleepSettings.cpp:281](../xteink/orbify/SleepSettings.cpp#L281) | ❌ No BookSync pool; native current-cover screen remains; flash/PSRAM cut; **hardware: No BookSync pool; native current-cover screen remains; flash/PSRAM cut**. [xteink/tailnet/tailnet_build.py:302](../xteink/tailnet/tailnet_build.py#L302) | | Sleep text, battery, bar/overlay and placement | ✅ (v0.11.3-rc.17) Sleep rendering. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SleepScreen.kt:30](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SleepScreen.kt#L30) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sleep row controls and renderer. [xteink/orbify/SleepSettings.cpp:312](../xteink/orbify/SleepSettings.cpp#L312), [xteink/orbify/SleepScreen.cpp:34](../xteink/orbify/SleepScreen.cpp#L34) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sleep row controls and renderer. [xteink/orbify/SleepSettings.cpp:312](../xteink/orbify/SleepSettings.cpp#L312), [xteink/orbify/SleepScreen.cpp:34](../xteink/orbify/SleepScreen.cpp#L34) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:302](../xteink/tailnet/tailnet_build.py#L302) | diff --git a/docs/design/backend-independence.md b/docs/design/backend-independence.md index 3011412b..8be0d6b3 100644 --- a/docs/design/backend-independence.md +++ b/docs/design/backend-independence.md @@ -179,12 +179,9 @@ bounded local references. The former cover downloader and thumbnail child scanne 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 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. +copies, recommendations and end-of-book commands as well. The native catalog display bridge is now retired, and the +owned Home/Library surfaces consume the bounded read model. Neutral lifecycle signals route +non-sync jobs through Library. No Lua facade consumer or adapter-directory exemption remains. 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 @@ -192,10 +189,22 @@ Catalog-side copies, grouping, recommendations and end-of-book are also companio `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. +Native scalar settings and gesture aliases use bounded companion-supplied metadata; the private Lua compatibility root is deleted. Every screen/widget keeps its budget. Consent and bounded native verification add named 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. + +### Final Android Lua guard (F12-Q2 step 5) + +The catalog compatibility root and local native catalog display bridge are retired. All +plugin Lua paths now receive the same protocol/vendor/transport guard, including adapter +directories and composition roots; there are no Lua exemptions. Owned Home/Library surfaces +consume neutral windows. The companion owns protocol and sends one bounded local retirement +descriptor before legacy classes instantiate; the native bridge only disables methods. +Signer/version mismatch, late loading or an unknown startup seam never authorizes the owned +sync writer. Settings/gesture bindings are opaque native metadata, not server JSON. Sleep +requests carry no credentials. See [Q2 notes](booksync-home/F12-Q2-NOTES.md#step-5-enforce-every-lua-path) +for migration boundaries, reuse evidence and deterministic startup/render budgets. diff --git a/docs/design/booksync-home/F12-Q2-NOTES.md b/docs/design/booksync-home/F12-Q2-NOTES.md index b65c0fc4..4996ed0c 100644 --- a/docs/design/booksync-home/F12-Q2-NOTES.md +++ b/docs/design/booksync-home/F12-Q2-NOTES.md @@ -1,9 +1,9 @@ # F12-Q2 catalog transport migration -Status: **covers and mirror/store cutovers implemented; remaining catalog cutover incomplete**. The legacy -Lua catalog adapter and its callers are still present. The maintainer authorised -merging this prerequisite as step 1 of 5; it does not complete the server-free -plugin slice. +Status: **Android catalog cutover implemented, including the final Lua boundary guard**. +The five staged PRs move cover, mirror/store, copy, grouping, recommendation and finish work +behind Library and the companion. No plugin Lua adapter or composition root is exempt. +Xteink enforcement remains deferred under the maintainer's Android-first ruling. The library now exposes an explicit `acquireCover(key, callback)` command and a one-row `cover(key)` snapshot. `ServerAdapter.acquireCover` resolves an opaque key @@ -194,3 +194,48 @@ warms one identity row while reading. Native catalog downloads use the companion 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. + +## Step 5: enforce every Lua path + +`tools/test/test-server-boundary.py` checks every production plugin Lua file, including +nested `ko/server/`, `logic/server/`, the loader and the former sync paths. There is no file +skip list, baseline, suppression annotation or vendor-name masking for Lua. The guard's +negative matrix covers both vendor names, routes, HTTP imports/clients and subprocess +entry points under invented adapter paths. The five F12-Q files already retired, so they +need no exception. Comments remain documentation, not executable protocol. + +The former root facade and `local_view.lua` are deleted, along with unused Lua catalog +policy modules. No vendor-shaped display records are reconstructed in Lua. Home, lists, +Details, group navigation and account setup use the existing owned UI and bounded library +snapshots. Native KOReader opening, rotation, reading gates and the owned single sync writer +remain in place. The release test still executes the pinned native opening coroutine while +Full refresh is active; it never intercepts book opening for repair. + +Retirement is necessary before any old client instance starts. `ConnectorPlugin` supplies +one static, credential-free descriptor through the trusted `LIBRARY_BOOTSTRAP` provider. +`ko/library_bootstrap.lua` verifies the companion signer, version handshake and one-row / +16 KiB / one-round-trip budget; `ko/retirement.lua` replaces complete legacy class/API methods +without invoking them. Missing metadata, a late instance or an unknown startup seam leaves +`SyncRetirement.safe=false`, preserving the existing five-phase import gate. Native defaults, +setting keys and old gesture aliases are opaque adapter metadata; configured gestures now +reach owned Library sync and ReaderPanel actions. No encoding or concatenation hides vendor +names in Lua source. + +Sleep refresh sends neutral settings only. Its existing adapter worker resolves the encrypted +login itself and does not resurrect a removed adopted login. Copy sidecar/statistics repair +and the local ledger already commit in the companion before the native event is acknowledged; +finish intent is already in native reader settings and the owned journal. No retired native +cache or state writer is reactivated merely to acknowledge an event. + +Reuse evidence: `ko/home_host.lua:339` (owned Home), `ko/library.lua:163` (Library command/read +boundary), `ko/store.lua:66` (bounded local persistence), `ko/base.lua:48` (native hook chain), +`MirrorLogic.kt:116` (window identities), `CacheStore.kt:240` (saved window reads), and +`CatalogWorkflow.kt:268` (owned file identity). Historical mirror slicing and section fixtures +now exercise those companion implementations in `RetiredCatalogFixtureTest.kt`; existing +workflow/projection tests own catalog policy. Retired native UI tests are replaced by owned +Home, generic retirement, bounded SQLite and companion tests, rather than testing dead code. + +Every screen/widget retains its budget; no new screen is introduced. Bootstrap has its own +startup-call budget and timing span. The plugin observes native network work at KOReader's +NetworkMgr seam and imports no HTTP client. Device timing targets still require maintainer +confirmation. No devices, adb, releases, tags or firmware source changes are part of this slice. diff --git a/shared/contract/companion.json b/shared/contract/companion.json index 942e726f..3924e6c2 100644 --- a/shared/contract/companion.json +++ b/shared/contract/companion.json @@ -145,13 +145,10 @@ "open_id", "every", "storage_limit_mb", - "scopes_only", - "server", - "user", - "userkey" + "scopes_only" ], - "does": "refresh the sleep screen's pool, or only the pickers' lists", - "login": true + "does": "refresh the sleep pool or pickers through the companion-owned login; no plugin credentials", + "login": false }, { "name": "SQLITE_STRESS", @@ -167,12 +164,9 @@ "extras": [ "reason", "drain_events", - "events_ack", - "board_year", - "board_key", - "board_now" + "events_ack" ], - "does": "a write the plugin made, patched into orbit.db (or a wipe)" + "does": "publish bounded read-model requests and acknowledge durable event batches" }, { "name": "UPDATE", @@ -282,6 +276,18 @@ "body" ], "does": "one cached neutral device-settings record" + }, + { + "name": "LIBRARY_BOOTSTRAP", + "method": "net.fledgewing.orbitcompanion.call.LIBRARY_BOOTSTRAP", + "caller": "koreader", + "extras": [ + "patch_version" + ], + "answer": [ + "body" + ], + "does": "one bounded local legacy retirement descriptor before plugin instances start" } ], "activities": [ @@ -476,7 +482,7 @@ "path": "koreader/cache/bookorbit/", "pattern": "_.jpg and matching .etag", "writer": "plugin, companion", - "reader": "plugin, companion", + "reader": "companion", "format": "jpeg, etag", "what": "BookOrbit thumbnails and mirror covers" }, diff --git a/shared/features.json b/shared/features.json index f2fe4cb1..6617df3b 100644 --- a/shared/features.json +++ b/shared/features.json @@ -1370,7 +1370,7 @@ "platforms": { "android": { "status": "supported", - "note": "Smart Home and local state hooks", + "note": "Owned Smart Home and companion-materialized local state", "reason": null, "evidence": [ { @@ -1378,8 +1378,8 @@ "line": 9 }, { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/local_view.lua", - "line": 30 + "path": "android/koreader/orbit.koplugin/ko/library.lua", + "line": 163 } ], "version": "v0.11.3-rc.17" diff --git a/shared/fixtures/REGISTRY.json b/shared/fixtures/REGISTRY.json index e668dd15..546b9a32 100644 --- a/shared/fixtures/REGISTRY.json +++ b/shared/fixtures/REGISTRY.json @@ -7,7 +7,6 @@ "rule": "What makes two requests one cache entry", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, @@ -17,7 +16,6 @@ "rule": "Which requests are cached", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, @@ -27,7 +25,6 @@ "rule": "When a read is served from the cache and when it is checked", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, @@ -37,7 +34,6 @@ "rule": "Whether a check changed the saved reply", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, @@ -48,7 +44,6 @@ "owner": "plugin, companion, xteink", "readers": [ "kt", - "lua", "cpp" ], "note": "lua also checks the fake companion's copy of the patch (android/koreader/test/companion_rules.lua)" @@ -79,8 +74,7 @@ "rule": "A check keeps the saved random pick; a Full refresh takes the new one", "owner": "companion", "readers": [ - "kt", - "lua" + "kt" ], "note": "lua: the fake companion's copy (android/koreader/test/companion_rules.lua)" }, @@ -88,18 +82,18 @@ "file": "cache/cases.json", "section": "mirror.windows", "rule": "The offline mirror's list identities", - "owner": "plugin", + "owner": "companion", "readers": [ - "lua" + "kt" ] }, { "file": "cache/cases.json", "section": "mirror.slices", "rule": "A read cut from the mirror's saved pages", - "owner": "plugin", + "owner": "companion", "readers": [ - "lua" + "kt" ] }, { @@ -117,7 +111,6 @@ "rule": "When the automatic Full refresh is due", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, @@ -127,8 +120,7 @@ "rule": "A mirror request with no answer is retried with smaller pages, then skipped", "owner": "companion", "readers": [ - "kt", - "lua" + "kt" ], "note": "lua: the fake companion's copy (android/koreader/test/companion_rules.lua)" }, @@ -136,9 +128,9 @@ "file": "cache/cases.json", "section": "mirror.small_pages", "rule": "A list saved in a smaller page size", - "owner": "plugin", + "owner": "companion", "readers": [ - "lua" + "kt" ] }, { @@ -156,8 +148,7 @@ "rule": "The note when the mirror stops at the limit", "owner": "companion", "readers": [ - "kt", - "lua" + "kt" ], "note": "lua: the fake companion's copy (android/koreader/test/companion_rules.lua)" }, @@ -166,8 +157,7 @@ "rule": "The plugin's cache keys, hashes, list pages, cover names and entry format, which the companion's worker matches byte for byte", "owner": "companion", "readers": [ - "kt", - "lua" + "kt" ] }, { @@ -225,7 +215,6 @@ "rule": "End of book: next in series, suggestions and author", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, @@ -235,7 +224,6 @@ "rule": "End of book: the finish queue's drain guard", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, @@ -245,7 +233,6 @@ "rule": "End of book: error backoff", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, @@ -255,7 +242,6 @@ "rule": "End of book: the stale-push hold", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, @@ -272,7 +258,6 @@ "rule": "Recorded book detail for the end-of-book picker", "owner": "server", "readers": [ - "lua", "cpp" ] }, @@ -281,7 +266,6 @@ "rule": "Recorded book detail for the end-of-book picker", "owner": "server", "readers": [ - "lua", "cpp" ] }, @@ -290,7 +274,6 @@ "rule": "Recorded book detail for the end-of-book picker", "owner": "server", "readers": [ - "lua", "cpp" ] }, @@ -299,7 +282,6 @@ "rule": "Recorded book detail for the end-of-book picker", "owner": "server", "readers": [ - "lua", "cpp" ] }, @@ -308,7 +290,6 @@ "rule": "Recorded book detail for the end-of-book picker", "owner": "server", "readers": [ - "lua", "cpp" ] }, @@ -317,7 +298,6 @@ "rule": "Recorded book detail for the end-of-book picker", "owner": "server", "readers": [ - "lua", "cpp" ] }, @@ -326,7 +306,6 @@ "rule": "Recorded book detail for the end-of-book picker", "owner": "server", "readers": [ - "lua", "cpp" ] }, @@ -349,17 +328,17 @@ { "file": "bookorbit/catalog-sections.smart-scopes.json", "rule": "Smart scopes in the server's shape, for the sleep screen's pickers", - "owner": "server", + "owner": "companion", "readers": [ - "lua" + "kt" ] }, { "file": "bookorbit/catalog-sections.collections.json", "rule": "Collections in the server's shape, for the sleep screen's pickers", - "owner": "server", + "owner": "companion", "readers": [ - "lua" + "kt" ] }, { @@ -385,7 +364,6 @@ "rule": "Local-first: this device's reading over the server's", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, @@ -394,7 +372,6 @@ "rule": "Local-first: the reading stamp", "owner": "plugin, xteink", "readers": [ - "lua", "cpp" ] }, diff --git a/tools/test/test-server-boundary.py b/tools/test/test-server-boundary.py index 34076191..08f334dd 100644 --- a/tools/test/test-server-boundary.py +++ b/tools/test/test-server-boundary.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Android adapter boundary. No baselines, annotations, environment switches or per-file skips. -Only composition roots may name implementations; protocol belongs to adapter directories. +Only the companion composition root may name implementations; no Android Lua adapter exemption. """ from pathlib import Path import re @@ -26,14 +26,8 @@ r'/api/v1|/?koreader/plugin\b|\bcatalog/(?:books|sections|dashboard)|\b(?:' + '|'.join(FIELDS) + r')\b|smart[ _-]?scopes?|x-auth-user|x-auth-key|/koreader/(?:users|syncs|credentials)|' r'/auth/(?:login|refresh|logout)|/opds(?:-users\b|[/?\"\']|$)', re.I) -PROTOCOL = re.compile(WIRE_PROTOCOL.pattern + r'|bookorbit', re.I) +PROTOCOL = re.compile(WIRE_PROTOCOL.pattern + r'|bookorbit|grimmory', re.I) IMPLEMENTATION = re.compile(r'(?:net\.fledgewing\.orbitcompanion\.server\.[a-z]+|(?:ko|logic)[/.]server[/.]|[\"\']bookorbit_|\bServerCache\b)') -# Reviewed legacy facade consumers: permissions to call the facade, never protocol exemptions. -# main.lua is the only implementation loader; owned Home/Details/widget modules are absent. -LUA_COMPAT_CONSUMERS = frozenset(LUA / 'ko' / name for name in ( - 'home.lua', 'notices.lua', 'sleepscreen.lua', - 'endsheet.lua', -)) LEGACY_GLOBALS = r'OC|Mirror|OSM|Copies|LF|Grouping|Rec|EOB|Sync' LUA_STRINGS = re.compile(r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|\[(=*)\[.*?\]\1\]', re.S) @@ -66,7 +60,6 @@ def violations(path, source): relative = path.relative_to(COMPANION) if path.is_relative_to(COMPANION) else None source_root = COMPANION / relative.parts[0] / relative.parts[1] if relative and len(relative.parts) > 2 and relative.parts[1] in ('java', 'kotlin') else None kotlin_adapter = source_root is not None and path.is_relative_to(source_root / 'net/fledgewing/orbitcompanion/server') - lua_adapter = any(path.is_relative_to(LUA / family / 'server') for family in ('ko', 'logic')) cover_errors = [] if path.is_relative_to(LUA) and path.suffix == '.lua': code = code_only(source, True) @@ -76,7 +69,7 @@ def violations(path, source): 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: if kotlin_adapter and path.suffix in ('.kt', '.java'): expected = '.'.join(path.relative_to(source_root).parent.parts) if not re.search(r'^package ' + re.escape(expected) + r'\s*$', source, re.M): @@ -86,13 +79,15 @@ def violations(path, source): if path.suffix in ('.xml', '.html'): source = re.sub(r'', lambda m: re.sub(r'[^\n]', ' ', m[0]), source, flags=re.S) code = code_only(source, lua) - wiring = path in (REGISTRY, LUA_REGISTRY) + wiring = path == REGISTRY errors = list(cover_errors) + if lua and re.search(r'\b(?:https?|socket|ssl)[.:]\s*(?:request|connect)\s*[(\{]|\b(?:requestBlocking|downloadBlocking|runInSubprocess|httpGet|httpPost)\s*\(|[\"\'](?:socket[./]http|ssl[./]https|socket[./]url|https?|httpclient|requests|curl)[\"\']',code): + errors.append(f'{path}: HTTP client/subprocess in plugin; use Library companion commands') if lua and re.search(r'(?:require\s*\(?|pcall\s*\(\s*require\s*,)\s*["\'](?:socket\.http|bookorbit)["\']|\bhttp\.request\s*[({]', code): errors.append(f'{path}: direct server transport/import outside the adapter') if lua and re.search(r'\bLibraryAdapter[.:]', code) and path != LUA / 'ko/library.lua': errors.append(f'{path}: only the library interface may call its adapter binding') - if lua and re.search(r'\bServer[.:]|\b(?:serverPlugin|serverOverBook|serverScreen)\s*\(', code) and path not in LUA_COMPAT_CONSUMERS: + if lua and re.search(r'\bServer[.:]|\b(?:serverPlugin|serverOverBook|serverScreen)\s*\(', code): errors.append(f'{path}: unreviewed legacy adapter facade consumer; owned UI must use Library') if lua: # These are implementation objects exported by old shared-environment modules, @@ -110,7 +105,7 @@ def violations(path, source): for n, line in enumerate(code.splitlines(), 1): # About's shared credits are data, not a protocol call. The literal credit is the sole # permitted brand use, not an exception for the About source file. - line = line.replace('"bookorbit-credit"', '"credit"') + if not lua: line = line.replace('"bookorbit-credit"', '"credit"') protocol_line = line if wiring: # Remove only implementation identifiers/imports and quoted module paths. Endpoint @@ -139,11 +134,11 @@ def test_rejects_protocol_and_imports_even_with_suppression_comments(self): self.assertTrue(violations(path, '// skip boundary\n-- allow-server\n' + value), value) self.assertTrue(violations(KOTLIN / 'Widget.kt', 'import net.fledgewing.orbitcompanion.server.bookorbit.Hidden')) self.assertTrue(violations(COMPANION / 'debug/kotlin/Widget.kt', 'val path="/api/v1"')) - def test_only_reviewed_legacy_modules_can_call_the_lua_facade(self): + def test_no_ui_module_can_call_a_legacy_lua_facade(self): self.assertTrue(violations(LUA / 'ko/home_widgets.lua', 'Server.loaded("api")')) self.assertTrue(violations(LUA / 'ko/home_widgets.lua', 'LibraryAdapter.read("x")')) self.assertTrue(violations(LUA / 'ko/home_widgets.lua', 'serverPlugin()')) - self.assertFalse(violations(LUA / 'ko/home.lua', 'Server.loaded("toast")')) + self.assertTrue(violations(LUA / 'ko/home.lua', 'Server.loaded("toast")')) # Reviewed facade consumers still cannot contain protocol data or direct imports. self.assertTrue(violations(LUA / 'ko/home.lua', 'local field="readStatus"')) self.assertTrue(violations(LUA / 'ko/home.lua', 'require("bookorbit_api")')) @@ -213,6 +208,18 @@ def test_copy_and_finish_transport_cannot_hide_in_any_lua_adapter(self): for name in ('finish','recommendations'): self.assertFalse(violations(LUA / 'ko' / (name+'.lua'),(ROOT / LUA / 'ko' / (name+'.lua')).read_text())) + def test_every_lua_path_has_the_same_boundary(self): + # Invented nested adapters and composition roots receive exactly the UI rules. + for name in ('main.lua','ko/server/bookorbit.lua','ko/server/other/deep.lua', + 'logic/server/other.lua','ko/sync.lua','ko/reading_sync.lua', + 'ko/lifecycle.lua','ko/orbismart.lua','ko/localfirst.lua'): + for source in ('local x="BookOrbit"','local x="bookorbit-credit"','local x="Grimmory"','local x="/api/v1/books"', + 'require("socket.http")','require("ssl.https")','require("http")','require("curl")','http.request{}', + 'client:requestBlocking("GET",path)','client:runInSubprocess(fn)'): + self.assertTrue(violations(LUA/name,source),(name,source)) + self.assertFalse(violations(LUA/'ko/retirement.lua','target[name]=retired')) + self.assertFalse(violations(LUA/'ko/library.lua','Library.catalogAction("copies.check",{})')) + def test_entire_production_tree(self): errors = [] for root in (COMPANION, LUA, *RESOURCE_ROOTS):