Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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())) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ interface ProjectionStore : AutoCloseable {
}

interface ConnectorInstaller {
/** Bounded local retirement metadata; no network, credentials or catalog data. */
fun retirementPlan(): Map<String,Any?> = emptyMap()
val minimumVersion: String
val homeModeKey: String
fun coverCacheDir(root: File): File
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"]))
Expand Down Expand Up @@ -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() }
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ import org.json.JSONArray
import org.json.JSONObject

object ConnectorPlugin : ConnectorInstaller {
override fun retirementPlan(): Map<String,Any?> = 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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"]) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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") }
Expand Down
Original file line number Diff line number Diff line change
@@ -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() }
}
}
}
Original file line number Diff line number Diff line change
@@ -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)
}
}
10 changes: 10 additions & 0 deletions android/docs/INTERFACE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
5 changes: 5 additions & 0 deletions android/koreader/orbit.koplugin/ko/base.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 2 additions & 2 deletions android/koreader/orbit.koplugin/ko/companion.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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("[^.]+$")
Expand Down Expand Up @@ -330,3 +328,5 @@ function Companion.status()
end

---------------------------------------------------------------------------------------------

Companion.LIBRARY_BOOTSTRAP=Companion.PACKAGE..".call.LIBRARY_BOOTSTRAP"
2 changes: 0 additions & 2 deletions android/koreader/orbit.koplugin/ko/companion_ui.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
1 change: 0 additions & 1 deletion android/koreader/orbit.koplugin/ko/db.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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.
---------------------------------------------------------------------------------------------
Expand Down
Loading