diff --git a/AGENTS.md b/AGENTS.md index 0cdc3b21..0521d31f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,7 +57,8 @@ CrossInk 2.x bridge and the later stable BookSync releases become available (`xt The guard scans production resources and shared Settings/UI data too; About credit prose may name its credited project. See `docs/design/backend-independence.md` for adapter registration and legacy follow-ups. A transport cutover must checkpoint every unacknowledged lifecycle phase before retiring - its source queue. Never activate a replacement position writer while the legacy writer + its source queue. Android sync now uses only neutral Library companion commands; keep policy, + durable decision state and all five lifecycle phases in the companion single owner. Never activate a replacement position writer while the legacy writer can still drain that document; a durable position queue alone is not a lifecycle migration. - **Nothing interrupts reading.** While a book is open in the foreground, nothing from BookSync, diff --git a/README.md b/README.md index 546f3bc4..43d544b4 100644 --- a/README.md +++ b/README.md @@ -18,10 +18,10 @@ Generated support counts (settings included): ✅ supported, 🟡 partial, ❌ m | Platform | ✅ | 🟡 | ❌ | ➖ | |---|---:|---:|---:|---:| -| Android (M8C / Boox) | 75 | 13 | 1 | 3 | -| X4 Pro | 55 | 12 | 13 | 12 | -| X4 classic | 54 | 12 | 13 | 13 | -| X3 | 20 | 16 | 43 | 13 | +| Android (M8C / Boox) | 76 | 13 | 1 | 3 | +| X4 Pro | 55 | 12 | 14 | 12 | +| X4 classic | 54 | 12 | 14 | 13 | +| X3 | 20 | 16 | 44 | 13 | ## Releases diff --git a/ROADMAP.md b/ROADMAP.md index 482d8892..9fd639f8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -54,7 +54,7 @@ design and mockup approval still apply. | **Reusable filter sheet**: nine picker rows, companion-counted facets, removable chips and a local Home Book list action. | Android building; X4 Pro, X4, X3 after | building (maintainer-authorised Android F12-G) | | **Reading statistics and Stats widgets**: server-first cross-device days, streaks, finish counts and goal targets, with labeled local hourly/session fallback and overlap-safe today totals; Home integration is implemented; local completion/goal settings follow. | Android building (approved 2026-11-25); X4 Pro, X4, X3 deferred to firmware implementation | building | | **BookSync library interface**: all platform UIs use one interface with BookOrbit/Grimmory adapters, capability-gated features and neutral filters with cached-catalog fallback ([BookSync Home owned-client design](docs/design/backend-independence.md#1-owned-android-client-and-ledger)); maintainer rule 2026-11-26. | Android (KOReader plugin + companion), X4 Pro, X4, X3 | building (Android F12-A foundation and F12-L adapter enforcement; X4 Pro, X4, X3 planned) | -| **Server-free Android plugin**: move remaining cover, lifecycle, mirror, copies and finish requests into companion-owned adapter commands without losing queued work ([F12-Q checkpoints](docs/design/booksync-home/F12-Q-NOTES.md)). | Android first; X4 Pro, X4, X3 deferred under the maintainer's Android-first ruling | building (durable position queue prerequisite; transport cutover and migration still pending) | +| **Server-free Android plugin**: move remaining cover, lifecycle, mirror, copies and finish requests into companion-owned adapter commands without losing queued work ([F12-Q checkpoints](docs/design/booksync-home/F12-Q-NOTES.md)). | Android first; X4 Pro, X4, X3 deferred under the maintainer's Android-first ruling | building (companion-owned sync and durable lifecycle migration implemented on feature/0.12; parallel catalog/cover/finish cutover pending) | | **Grouped BookSync settings on the reader**, with visible sync/power controls, three mode presets, companion battery estimates and one update-channel picker. | Android first (maintainer-authorised 2026-11-25); X4 Pro, X4, X3 later | building (F12-D; measured battery and reading-preset integration follow their slices) | | **Equivalent settings controls**: expose the [parity gap 1](docs/FEATURES.md#prioritised-parity-bugs) controls, including a sleep sync budget aligned with Android's 10/15/20 s choices. | X4 Pro, X4 | planned (0.12) | | **BookSync status-bar preset**: add one preset over the existing native controls ([parity gap 2](docs/FEATURES.md#prioritised-parity-bugs)). | X4 Pro, X4 | planned (0.12) | 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 7eaba53e..c9e99212 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 @@ -71,6 +71,15 @@ class CommandProvider : ContentProvider() { return answer(true) } if (!KoreaderTrust.check(ctx, uid)) return answer(false, "caller") + if (method == "${Contract.PACKAGE}.call.SYNC_PREVIEW") { + val encoded=extras?.getString("args")?.takeIf { it.length<=8192 } ?: return answer(false,"budget") + val args=LuaValue.parseTransport(encoded) as? Map<*, *> ?: return answer(false,"invalid") + val start=System.nanoTime() + val body=LuaValue.encode(LibraryAccount.positionPreview(args)) + OLog.i("sync.preview ms=${(System.nanoTime()-start)/1_000_000}") + if(body.size>16384) return answer(false,"budget") + return answer(true).apply { putString("body",String(body,Charsets.UTF_8)) } + } if (method == DEVICE_SETTINGS) { DeviceSettings.refreshAsync() return answer(true).apply { putString("body",LuaValue.transportText(DeviceSettings.snapshot())) } @@ -79,7 +88,8 @@ class CommandProvider : ContentProvider() { val encoded = extras?.getString("args")?.takeIf { it.length <= 8192 } ?: return answer(false,"budget") val op = extras.getString("op") ?: return answer(false,"missing") return try { - val args = LuaValue.parseTransport(encoded) as? Map<*, *> ?: return answer(false,"invalid") + val parsed=LuaValue.parseTransport(encoded) + val args=when(parsed) { is Map<*, *> -> parsed; emptyList() -> emptyMap(); else -> return answer(false,"invalid") } answer(true).apply { putString("id",ServerCommands.start(ctx,op,args)) } } catch (_: Exception) { answer(false,"invalid") } } diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt index 252b5aea..9921e118 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt @@ -13,7 +13,27 @@ object LibraryAccount { private val queue = Executors.newSingleThreadExecutor { r -> Thread(r, "booksync-server").apply { isDaemon = true } } private val main = Handler(Looper.getMainLooper()) private var adapter: ServerAdapter? = null - private class Published(val state: Map = emptyMap(), val owner: String? = null, val stats: Map<*, *>? = null, val fallback: RemoteReadingStats? = null) + @Volatile private var syncOwner: SyncOwner? = null + private var syncRetryScheduled=false + private fun syncOwner(ctx: Context): SyncOwner = syncOwner ?: SyncOwner( + LifecycleQueue(AndroidSql(File(ctx.filesDir,"sync-journal.db"))), + File(android.os.Environment.getExternalStorageDirectory(),"koreader/settings")).also { syncOwner=it } + private fun retrySync(ctx: Context) { + val owner=syncOwner ?: return + val a=adapter ?: return + if(syncRetryScheduled || !owner.needsRetry(a)) return + syncRetryScheduled=true + main.postDelayed({ queue.execute { + syncRetryScheduled=false + runCatching { if(owner.needsRetry(a)) owner.drain(a) } + retrySync(ctx) + } },60000) + } + fun positionPreview(args: Map<*, *>): Map { + val a=adapter ?: return mapOf("pending" to true) + return syncOwner?.preview(a.id,published.positionOwner,args) ?: mapOf("pending" to true) + } + private class Published(val state: Map = emptyMap(), val owner: String? = null, val stats: Map<*, *>? = null, val fallback: RemoteReadingStats? = null, val positionOwner: String? = null) @Volatile private var published = Published() @Volatile private var loaded = false private var nextRefreshAt = 0L @@ -29,7 +49,7 @@ object LibraryAccount { if (loaded) { main.post(done); return } val app = ctx.applicationContext queue.execute { - try { if (!loaded) { publish(adapter(app)); loaded = true } } + try { if (!loaded) { publish(adapter(app)); syncOwner(app).restorePreviews(adapter(app)); loaded = true } } catch (_: Exception) { published = Published() } finally { main.post(done) } } @@ -45,7 +65,7 @@ object LibraryAccount { private fun publish(a: ServerAdapter) { val state = a.state(); val owner = a.owner() require(LuaValue.encode(state).size <= 16384) - published = Published(state, owner, owner?.let(a::stats),a.fallbackReadingStats()) + published = Published(state, owner, owner?.let(a::stats),a.fallbackReadingStats(),a.positionOwner()) } private fun command(ctx: Context, work: (ServerAdapter) -> Unit, done: (String?) -> Unit, cleanup: () -> Unit = {}, invalidate: Boolean = true) { val app = ctx.applicationContext @@ -54,7 +74,7 @@ object LibraryAccount { var error: String? = null try { work(adapter(app)) } catch (e: ServerFailure) { error = e.kind } catch (_: Exception) { error = "unavailable" } - finally { cleanup() } + finally { cleanup(); runCatching { retrySync(app) } } runCatching { adapter?.let(::publish) }.onFailure { published = Published(); error = "unavailable" } if (invalidate) Worker.accountChanged(app) OLog.i("server.command ms=${(System.nanoTime()-start)/1_000_000}") @@ -70,7 +90,12 @@ object LibraryAccount { fun useAccountLogin(ctx: Context, kind: String, done: (String?) -> Unit) = command(ctx, { it.useAccountLogin(kind) }, done) fun position(ctx: Context, document: String, update: Map? = null, done: (Map?,String?) -> Unit) { var result: Map? = null - command(ctx, { result = it.position(document,update) }, { done(result,it) }, invalidate = false) + // Writes go through the same owner/policy journal as lifecycle captures. + command(ctx, { result = if(update==null) it.position(document,null) else syncOwner(ctx.applicationContext).write(it,document,update) }, { done(result,it) }, invalidate = false) + } + fun sync(ctx: Context, op: String, args: Map<*, *>, done: (Map?,String?)->Unit) { + var result: Map?=null + command(ctx,{ result=syncOwner(ctx.applicationContext).command(it,op,args) },{ done(result,it) },invalidate=false) } fun catalog(ctx: Context, page: Int = 1, limit: Int = 24, done: (Map?,String?) -> Unit) { var result: Map? = null diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LifecycleQueue.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LifecycleQueue.kt new file mode 100644 index 00000000..ddef5cd3 --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LifecycleQueue.kt @@ -0,0 +1,83 @@ +package net.fledgewing.orbitcompanion + +/** Sole worker's durable five-phase journal. Payloads/checkpoints belong to the adapter and + * never enter the UI read model. Every phase commits separately, including remote-pending data. */ +class LifecycleQueue(val sql: Sql) { + companion object { + val PHASES = listOf("match","stats","annotations","state","progress") + const val WINDOW = 24 + const val MAX_BYTES = 200 * 1024 * 1024 + } + data class Entry(val id: String, val adapter: String, val owner: String, val document: String, + val payload: ByteArray, val acknowledged: Set, val checkpoint: ByteArray, + val source: String?, val retired: Boolean) + init { + sql.exec("CREATE TABLE IF NOT EXISTS lifecycle_jobs (sequence INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT NOT NULL UNIQUE,adapter TEXT NOT NULL,owner TEXT NOT NULL,document TEXT NOT NULL,payload BLOB NOT NULL,checkpoint BLOB NOT NULL,source TEXT,retired INTEGER NOT NULL DEFAULT 0,done INTEGER NOT NULL DEFAULT 0)") + sql.exec("CREATE UNIQUE INDEX IF NOT EXISTS lifecycle_source ON lifecycle_jobs(adapter,source) WHERE source IS NOT NULL") + sql.exec("CREATE INDEX IF NOT EXISTS lifecycle_owner ON lifecycle_jobs(adapter,owner,done,sequence)") + sql.exec("CREATE TABLE IF NOT EXISTS lifecycle_acks (id TEXT NOT NULL,phase TEXT NOT NULL,PRIMARY KEY(id,phase))") + sql.exec("CREATE TABLE IF NOT EXISTS sync_records (adapter TEXT NOT NULL,owner TEXT NOT NULL,document TEXT NOT NULL,body BLOB NOT NULL,PRIMARY KEY(adapter,owner,document))") + sql.exec("CREATE TABLE IF NOT EXISTS sync_imports (adapter TEXT NOT NULL,source TEXT NOT NULL,job TEXT NOT NULL,proof BLOB NOT NULL,retired INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(adapter,source))") + } + fun enqueue(adapter: String, owner: String, document: String, payload: ByteArray, + acknowledged: Set = emptySet(), checkpoint: ByteArray = LuaValue.encode(emptyMap()), + source: String? = null, proof: ByteArray = byteArrayOf()): String = sql.transaction { + require(adapter.isNotBlank() && owner.isNotBlank() && document.isNotBlank()) + require(acknowledged.all { it in PHASES } && payload.size <= MAX_BYTES && checkpoint.size <= MAX_BYTES) + if (source != null) imported(adapter,source)?.let { return@transaction it } + check(sql.query("SELECT COUNT(*) FROM lifecycle_jobs WHERE done=0") { it.long(0)!! }.single()<1000) { "lifecycle queue full" } + check(sql.query("SELECT COALESCE(SUM(length(payload)+length(checkpoint)),0) FROM lifecycle_jobs WHERE done=0") { it.long(0)!! }.single()+payload.size+checkpoint.size<=MAX_BYTES) { "lifecycle byte limit" } + val id = java.util.UUID.randomUUID().toString() + sql.exec("INSERT INTO lifecycle_jobs(id,adapter,owner,document,payload,checkpoint,source) VALUES (?,?,?,?,?,?,?)",id,adapter,owner,document,payload,checkpoint,source) + for (phase in acknowledged) sql.exec("INSERT INTO lifecycle_acks VALUES (?,?)",id,phase) + if (source != null) sql.exec("INSERT INTO sync_imports(adapter,source,job,proof) VALUES (?,?,?,?)",adapter,source,id,proof) + id + } + fun imported(adapter: String, source: String): String? = sql.query("SELECT job FROM sync_imports WHERE adapter=? AND source=?",adapter,source) { it.text(0) }.firstOrNull() + fun importProof(adapter: String, source: String): ByteArray? = sql.query("SELECT proof FROM sync_imports WHERE adapter=? AND source=?",adapter,source) { it.bytes(0) }.firstOrNull() + fun imports(adapter: String): List> = sql.query("SELECT source,proof FROM sync_imports WHERE adapter=? AND retired=0",adapter) { it.text(0)!! to it.bytes(1)!! } + fun retired(adapter: String, source: String) = sql.transaction { + sql.exec("UPDATE sync_imports SET retired=1 WHERE adapter=? AND source=?",adapter,source) + sql.exec("UPDATE lifecycle_jobs SET retired=1 WHERE adapter=? AND source=?",adapter,source) + } + fun window(adapter: String, owner: String): List = sql.query( + "SELECT id,document,payload,checkpoint,source,retired FROM lifecycle_jobs WHERE adapter=? AND owner=? AND done=0 ORDER BY sequence LIMIT ?",adapter,owner,WINDOW) { row -> + val id=row.text(0)!! + Entry(id,adapter,owner,row.text(1)!!,row.bytes(2)!!, + sql.query("SELECT phase FROM lifecycle_acks WHERE id=?",id) { it.text(0)!! }.toSet(),row.bytes(3)!!,row.text(4),row.long(5)==1L) + } + fun acknowledge(id: String, phase: String, checkpoint: ByteArray) = sql.transaction { + require(phase in PHASES && checkpoint.size <= MAX_BYTES) + sql.exec("UPDATE lifecycle_jobs SET checkpoint=? WHERE id=?",checkpoint,id) + sql.exec("INSERT OR IGNORE INTO lifecycle_acks VALUES (?,?)",id,phase) + } + fun checkpoint(id: String, checkpoint: ByteArray) { + require(checkpoint.size <= MAX_BYTES) + sql.exec("UPDATE lifecycle_jobs SET checkpoint=? WHERE id=?",checkpoint,id) + } + fun finish(id: String) { + check(sql.query("SELECT COUNT(*) FROM lifecycle_acks WHERE id=?",id) { it.long(0)!! }.single()==PHASES.size.toLong()) + // Imported payloads and provenance remain as a migration backup after delivery. + sql.transaction { + val imported=sql.query("SELECT source FROM lifecycle_jobs WHERE id=?",id) { it.text(0) }.firstOrNull()!=null + if(imported) sql.exec("UPDATE lifecycle_jobs SET done=1 WHERE id=?",id) + else { sql.exec("DELETE FROM lifecycle_acks WHERE id=?",id); sql.exec("DELETE FROM lifecycle_jobs WHERE id=?",id) } + } + } + fun pending(adapter: String, owner: String): Int = sql.query("SELECT COUNT(*) FROM lifecycle_jobs WHERE adapter=? AND owner=? AND done=0",adapter,owner) { it.long(0)!!.toInt() }.single() + fun pending(): Int = sql.query("SELECT COUNT(*) FROM lifecycle_jobs WHERE done=0") { it.long(0)!!.toInt() }.single() + fun contains(id: String): Boolean = sql.query("SELECT 1 FROM lifecycle_jobs WHERE id=? AND done=0",id) { true }.isNotEmpty() + fun records(adapter: String, owner: String): List>> = sql.query("SELECT document,body FROM sync_records WHERE adapter=? AND owner=? ORDER BY rowid DESC LIMIT 300",adapter,owner) { + val raw=LuaValue.parse(it.bytes(1)!!) as? Map<*, *> + it.text(0)!! to raw.orEmpty().entries.associate { e -> e.key.toString() to e.value } + } + fun record(adapter: String, owner: String, document: String): Map<*, *> = sql.query( + "SELECT body FROM sync_records WHERE adapter=? AND owner=? AND document=?",adapter,owner,document) { LuaValue.parse(it.bytes(0)!!) as? Map<*, *> }.firstOrNull().orEmpty() + fun record(adapter: String, owner: String, document: String, record: Map) { + val body=LuaValue.encode(record); require(body.size <= 65536) + sql.exec("INSERT OR REPLACE INTO sync_records VALUES (?,?,?,?)",adapter,owner,document,body) + } +} + +/** Opaque adapter checkpoint returned after one phase. A deferred phase remains unacknowledged. */ +data class SyncPhaseResult(val checkpoint: ByteArray, val complete: Boolean = true) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/PositionPolicy.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/PositionPolicy.kt new file mode 100644 index 00000000..c7edb7f4 --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/PositionPolicy.kt @@ -0,0 +1,44 @@ +package net.fledgewing.orbitcompanion + +import kotlin.math.abs + +/** Position policy shared with logic/orbismart.lua and the cross-platform recorded cases. + * Pages/chapters are local locator captures; adapter resets and redates arrive normalized. */ +object PositionPolicy { + const val SKEW_SECONDS = 600 + data class Marker(val at: Long, val place: Double) + data class Input(val local: Double, val remote: Double? = null, val tolerance: Double = 1.0, + val remoteAt: Long = 0, val marker: Marker? = null, val turnAt: Long = 0, + val reset: Boolean = false, val redated: Boolean = false, val finished: Boolean = false, + val released: Boolean = false, val declinedAt: Long = 0, val overrideAt: Long? = null, + val percentOnly: Boolean = false) + data class Decision(val decision: String, val rule: String, val dropped: Boolean = false) + fun decide(i: Input): Decision { + val remote = i.remote + val moved = i.marker != null && remote != null && i.remoteAt != i.marker.at && !i.redated + val dropped = i.overrideAt != null && moved && i.remoteAt > i.overrideAt + fun result(decision: String, rule: String) = Decision(decision,rule,dropped) + fun move(decision: String, rule: String) = if (i.declinedAt != 0L && i.declinedAt == i.remoteAt) + result("stay","declined") else result(decision,rule) + if (i.overrideAt != null && !dropped) return result("override","override") + if (remote == null) return result("push","no-server") + if (abs(i.local-remote) <= i.tolerance) return result("same","rule1") + if (i.reset) return move("follow","rule2") + if (i.finished && i.local < remote) return result(if (i.released) "push" else "hold","rule7") + if (remote > i.local) return move("take","rule3") + if (!moved) return result("push","rule4") + if (i.percentOnly) return result("push","percent") + if (abs(i.local-(i.marker?.place ?: 0.0)) <= i.tolerance) return move("follow","rule5") + if (i.remoteAt > i.turnAt + SKEW_SECONDS) return move("follow","rule6") + return result("push","rule6") + } + fun apply(decision: String, moment: String): String = when { + decision !in setOf("take","follow") -> "no" + moment == "prerender" -> "now" + moment == "sleep" -> "wake" + moment == "close" -> "no" + else -> "ask" + } + fun mayPush(place: Double?, remote: Double?, tolerance: Double = 1.0, exempt: Boolean = false) = + exempt || remote == null || place == null || place >= remote-tolerance +} diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ProgressOutbox.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ProgressOutbox.kt index 3f581824..4b1cadb4 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ProgressOutbox.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ProgressOutbox.kt @@ -1,70 +1,27 @@ package net.fledgewing.orbitcompanion -/** Companion-owned, account-scoped position writes. Enqueue commits before transport starts; - * a process death after delivery but before acknowledgment replays the same captured write. - * Call only on LibraryAccount's serial worker. This is not a render/read-model operation. */ -class ProgressOutbox(private val sql: Sql, private val log: (String) -> Unit = OLog::i, - private val now: () -> Long = { System.currentTimeMillis()/1000 }) { +/** Position-only convenience over the five-phase journal, retained from the prerequisite. + * Runtime writes are authorized and drained exclusively by SyncOwner. There is one journal, + * not a second position database/writer. Commit precedes transport; failed acks replay. */ +class ProgressOutbox(sql: Sql, private val now: ()->Long = { System.currentTimeMillis()/1000 }) { companion object { - const val MAX_PENDING = 1000 - const val MAX_POSITION_BYTES = 4096 - const val MAX_BATCH = 24 + const val MAX_PENDING=1000 + const val MAX_POSITION_BYTES=4096 + const val MAX_BATCH=LifecycleQueue.WINDOW } - init { - sql.exec("CREATE TABLE IF NOT EXISTS position_outbox (sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, adapter TEXT NOT NULL, owner TEXT NOT NULL, document TEXT NOT NULL, body BLOB NOT NULL)") - sql.exec("CREATE INDEX IF NOT EXISTS position_outbox_owner ON position_outbox(adapter,owner,sequence)") - } - data class Entry(val id: String, val document: String, val update: Map) - data class Drain(val sent: Int, val pending: Int, val error: String?) - - fun enqueue(adapter: String, owner: String, document: String, update: Map): String { - require(adapter.isNotBlank() && adapter.length <= 100 && owner.isNotBlank() && owner.length <= 1024) - require(document.isNotBlank() && document.length <= 1024) - val fraction = (update["percentage"] as? Number)?.toDouble() ?: throw IllegalArgumentException("percentage") + private val journal=LifecycleQueue(sql) + fun enqueue(adapter: String,owner: String,document: String,update: Map): String { + require(adapter.isNotBlank() && adapter.length<=100 && owner.isNotBlank() && owner.length<=1024) + require(document.isNotBlank() && document.length<=1024) + val fraction=(update["percentage"] as? Number)?.toDouble() ?: throw IllegalArgumentException("percentage") require(fraction.isFinite() && fraction in 0.0..1.0) - val position = update["position"] - require(position == null || position is String && position.length <= MAX_POSITION_BYTES && position.all { it.code <= 255 }) - // Never persist arbitrary command inputs: credentials and unrelated fields cannot enter the queue. - val body = LuaValue.encode(mapOf("percentage" to fraction, "position" to position, "capturedAt" to now())) - require(body.size <= 16384) - val id = java.util.UUID.randomUUID().toString() - sql.transaction { - check(count() < MAX_PENDING) { "position queue full" } - sql.exec("INSERT INTO position_outbox(id,adapter,owner,document,body) VALUES (?,?,?,?,?)", id,adapter,owner,document,body) - } - return id - } - fun count(): Int = sql.query("SELECT COUNT(*) FROM position_outbox") { it.long(0)!!.toInt() }.single() - fun count(adapter: String, owner: String): Int = sql.query("SELECT COUNT(*) FROM position_outbox WHERE adapter=? AND owner=?",adapter,owner) { it.long(0)!!.toInt() }.single() - fun contains(id: String): Boolean = sql.query("SELECT 1 FROM position_outbox WHERE id=?",id) { true }.isNotEmpty() - private fun window(adapter: String, owner: String): List = - sql.query("SELECT id,document,body FROM position_outbox WHERE adapter=? AND owner=? ORDER BY sequence LIMIT ?",adapter,owner,MAX_BATCH) { row -> - val raw = LuaValue.parse(row.bytes(2)!!) as Map<*, *> - Entry(row.text(0)!!,row.text(1)!!,raw.entries.associate { it.key as String to it.value }) - } - - /** FIFO, bounded per drain. Stop at failure so a later override cannot overtake an earlier - * write. Only an explicit successful response acknowledges a row; unsupported is retained. */ - fun drain(adapter: ServerAdapter): Drain { - val start = System.nanoTime() - try { return deliver(adapter) } - finally { log("position.outbox.drain ms=${(System.nanoTime()-start)/1_000_000}") } - } - private fun deliver(adapter: ServerAdapter): Drain { - val owner = adapter.positionOwner() ?: return Drain(0,0,"unauthorized") - var sent = 0 - var error: String? = null - for (entry in window(adapter.id,owner)) { - try { - check(adapter.positionOwner() == owner) { "position owner changed" } - val result = adapter.position(entry.document,entry.update) - val failure = result["error"] as? String - if (failure != null) { error = failure; break } - sql.exec("DELETE FROM position_outbox WHERE id=? AND adapter=? AND owner=?",entry.id,adapter.id,owner) - sent++ - } catch (e: ServerFailure) { error = e.kind; break } - catch (_: Exception) { error = "unavailable"; break } - } - return Drain(sent,count(adapter.id,owner),error) + val position=update["position"] + require(position==null || position is String && position.length<=MAX_POSITION_BYTES && position.all { it.code<=255 }) + val body=LuaValue.encode(mapOf("percentage" to fraction,"position" to position,"capturedAt" to now())) + require(body.size<=16384) + return journal.enqueue(adapter,owner,document,body,LifecycleQueue.PHASES.take(4).toSet()) } + fun count()=journal.pending() + fun count(adapter: String,owner: String)=journal.pending(adapter,owner) + fun contains(id: String)=journal.contains(id) } 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 ba2755e8..4d24d40a 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 @@ -41,8 +41,22 @@ interface ServerAdapter { fun owner(): String? = null /** Position credentials may belong to a different account from the catalog login. */ fun positionOwner(): String? = owner() + fun positionDirections(): PositionDirections = PositionDirections() fun stats(owner: String): Map<*, *>? = null fun position(document: String, update: Map? = null): Map = unsupported() + /** Companion's sole sync owner invokes these on its serial worker, never from rendering. */ + fun importLifecycle(queue: LifecycleQueue, settings: File, quiesced: Boolean): Int = 0 + fun captureLifecycle(capture: Map<*, *>): Pair = throw ServerFailure("unsupported") + fun positionIntent(document: String, update: Map): ByteArray = LuaValue.encode(update) + fun lifecyclePosition(payload: ByteArray): CapturedPosition { + val raw=LuaValue.parse(payload) as? Map<*, *> ?: throw ServerFailure("invalid") + return CapturedPosition((raw["percentage"] as? Number)?.toDouble(),raw["position"] as? String, + (raw["capturedAt"] as? Number)?.toLong() ?: 0L,raw["finished"]==true) + } + fun lifecyclePhase(entry: LifecycleQueue.Entry, phase: String, checkpoint: ByteArray, openPath: String?): SyncPhaseResult = throw ServerFailure("unsupported") + fun lifecycleComplete(checkpoint: ByteArray): Boolean = true + fun nextSyncVerification(owner: String, document: String): Map = emptyMap() + fun syncVerification(owner: String, document: String, key: String, valid: Boolean, page: Int?) {} fun catalog(page: Int = 1, limit: Int = 24): Map = unsupported() fun download(key: String, destination: File): Boolean = false fun setupCredentials(values: Map): Map = unsupported() @@ -76,3 +90,8 @@ interface CachedListProjection { /** Neutral, credential-free failure surfaced by any adapter. */ open class ServerFailure(val kind: String) : Exception(kind) + +data class CapturedPosition(val percentage: Double?, val position: String?, val capturedAt: Long, val finished: Boolean = false) + +/** Owned position policy options, translated by adapters from any legacy preference format. */ +data class PositionDirections(val automatic: Boolean=true,val ahead: String="ask",val behind: String="keep") diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerCommands.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerCommands.kt index 3a49bfae..a680fe21 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerCommands.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ServerCommands.kt @@ -10,7 +10,7 @@ object ServerCommands { private class Pending(val at: Long, var body: Map? = null) private val jobs = linkedMapOf() @Synchronized fun start(ctx: Context, op: String, args: Map<*, *>): String { - require(op in setOf("device.sleep","storage.free","storage.folder","sync.read","sync.write","catalog.window","catalog.control","covers.acquire","downloads.start","account.signIn","account.signOut","login.save","login.remove","login.replace")) + require(op in setOf("device.sleep","storage.free","storage.folder","sync.verify.next","sync.verify.result","sync.activate","sync.capture","sync.pull","sync.decide","sync.answer","sync.override","sync.drain","sync.read","sync.write","catalog.window","catalog.control","covers.acquire","downloads.start","account.signIn","account.signOut","login.save","login.remove","login.replace")) val now = System.currentTimeMillis() jobs.entries.removeAll { now - it.value.at > 120000 } require(jobs.size < 32) @@ -23,6 +23,7 @@ object ServerCommands { fun accountDone(error: String?) = finish(mapOf("state" to LibraryAccount.state()),error) fun text(key: String) = LuaValue.utf8(args[key] as? String ?: throw IllegalArgumentException("missing")) try { when (op) { + "sync.verify.next","sync.verify.result","sync.activate","sync.capture","sync.pull","sync.decide","sync.answer","sync.override","sync.drain" -> LibraryAccount.sync(ctx,op,args,::finish) "storage.free", "storage.folder" -> Worker.localCommand(ctx,op,args,::finish) "device.sleep" -> DeviceSettings.sleep(ctx,(args["ms"] as? Number)?.toInt() ?: 600000) { finish(mapOf("device" to DeviceSettings.snapshot()),it) } diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt new file mode 100644 index 00000000..c2118bbc --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt @@ -0,0 +1,268 @@ +package net.fledgewing.orbitcompanion + +import java.io.File +import java.security.MessageDigest + +/** One serial owner for capture, policy state, consent, migration and every server write. + * Native captures contain a locator and bounded geometry only; heavy sidecar/stat work stays here. */ +class SyncOwner(private val journal: LifecycleQueue, private val settings: File, + private val log: (String)->Unit = OLog::i, private val now: ()->Long = { System.currentTimeMillis()/1000 }) { + private var active=false + private var activatedOwner: String?=null + private var readerEpoch: String?=null + private var openPath: String?=null + @Volatile private var previews: Map> = emptyMap() + private fun map(value: Any?) = (value as? Map<*, *>)?.entries?.associate { it.key.toString() to it.value }.orEmpty() + private fun number(value: Any?) = (value as? Number)?.toDouble() + private fun time(value: Any?) = (value as? Number)?.toLong() ?: 0L + private fun scope(a: ServerAdapter) = a.positionOwner() ?: throw ServerFailure("unauthorized") + private fun record(a: ServerAdapter, document: String) = map(journal.record(a.id,scope(a),document)) + private fun projection(document: String, owner: String, record: Map): Map = + record.filterKeys { it in setOf("path","marker","remote","token","pending") }+mapOf("document" to document,"owner" to owner) + private fun save(a: ServerAdapter, document: String, record: Map) { + journal.record(a.id,scope(a),document,record) + val path=record["path"] as? String ?: return + val snapshot=record+mapOf("document" to document,"owner" to scope(a)) + previews=(previews.filterValues { it["document"]!=document || it["owner"]!=scope(a) }+((a.id+"|"+scope(a)+"|"+path) to snapshot)).entries.toList().takeLast(300).associate { it.toPair() } + val bytes=LuaValue.encode(projection(document,scope(a),record)) + if(bytes.size>16384) return // Keep the complete private record; oversized snapshots never reach Lua. + val dir=File(settings,"orbit-cache/position").also { it.mkdirs() } + val file=File(dir,MessageDigest.getInstance("MD5").digest(path.toByteArray(Charsets.ISO_8859_1)).joinToString("") { "%02x".format(it) }+".lua") + val temp=File(dir,file.name+".tmp") + temp.writeBytes(bytes); check(temp.renameTo(file)) + } + fun restorePreviews(a: ServerAdapter, publish: Boolean=false) { + val owner=a.positionOwner() ?: return + for ((document,record) in journal.records(a.id,owner)) { + val path=record["path"] as? String ?: continue + previews=previews+((a.id+"|"+owner+"|"+path) to (record+mapOf("document" to document,"owner" to owner))) + if(publish) save(a,document,record) + } + } + fun activate(a: ServerAdapter, quiesced: Boolean, epoch: String="fixture"): Map { + check(quiesced) + if(active && activatedOwner==a.positionOwner() && epoch==readerEpoch) return mapOf("ok" to true,"imported" to 0) + if(readerEpoch!=epoch) openPath=null + readerEpoch=epoch + val count=a.importLifecycle(journal,settings,true) + active=true + activatedOwner=a.positionOwner() + restorePreviews(a,true) + return mapOf("ok" to true,"imported" to count) + } + private fun ensure() { if (!active) throw ServerFailure("writer-active") } + fun needsRetry(a: ServerAdapter) = active && a.positionOwner()?.let { journal.pending(a.id,it)>0 }==true + fun write(a: ServerAdapter, document: String, update: Map): Map { + ensure() + val fraction=number(update["percentage"]) ?: throw IllegalArgumentException("percentage") + require(fraction.isFinite() && fraction in 0.0..1.0) + val position=update["position"] as? String + require(position==null || position.length<=4096) + val intent=mapOf("percentage" to fraction,"position" to position,"capturedAt" to now()) + journal.enqueue(a.id,scope(a),document,a.positionIntent(document,intent),LifecycleQueue.PHASES.take(4).toSet()) + return drain(a) + } + fun command(a: ServerAdapter, op: String, args: Map<*, *>): Map { + val started=System.nanoTime() + try { + if (op=="sync.activate") { + val result=activate(a,args["quiesced"]==true,args["epoch"] as? String ?: "unknown") + openPath=args["path"] as? String + return result + } + ensure() + val owner=scope(a) + if (op=="sync.drain") { + if(args["closed_path"]==openPath && openPath!=null) openPath=null + if(args["online"]==false) return mapOf("remaining" to journal.pending(a.id,owner)) + return drain(a) + } + val path=args["path"] as? String + if (path!=null && args["current"]!=false) openPath=path + val capture=if (path!=null && op in setOf("sync.capture","sync.override","sync.pull")) a.captureLifecycle(args) else null + val document=capture?.first ?: args["document"] as? String ?: throw IllegalArgumentException("document") + var rec=record(a,document).toMutableMap() + if (path!=null) rec["path"]=path + if(capture!=null) { + val directions=a.positionDirections() + rec["automatic"]=args["automatic"] as? Boolean ?: directions.automatic + rec["directions"]=mapOf("ahead" to directions.ahead,"behind" to directions.behind) + if(args["moment"]=="open") rec["compared"]=false + } + val local=mapOf("percentage" to args["percentage"],"position" to args["position"],"at" to time(args["captured_at"]).takeIf { it>0 }.let { it ?: now() },"page" to args["page"],"turnAt" to args["turn_at"],"finished" to args["finished"],"released" to args["released"],"moment" to args["moment"]) + when (op) { + "sync.verify.next" -> return a.nextSyncVerification(owner,document) + "sync.verify.result" -> { + a.syncVerification(owner,document,args["key"] as? String ?: throw IllegalArgumentException("key"),args["valid"]==true,(args["page"] as? Number)?.toInt()) + return mapOf("ok" to true) + } + "sync.capture", "sync.override" -> { + requireNotNull(capture) + rec["local"]=local + if (op=="sync.override") { rec["override"]=local; rec.remove("declinedAt"); rec.remove("declinedReset") } + // Durable before any transport, also while offline. Sidecar work is done by the adapter. + journal.enqueue(a.id,owner,document,capture.second) + save(a,document,rec) + if (args["online"]==false) return mapOf("queued" to true,"document" to document) + return pull(a,document,rec)+mapOf("queued" to true) + } + "sync.pull" -> { rec["local"]=local; save(a,document,rec); return pull(a,document,rec) } + "sync.decide" -> return decide(a,document,rec,args) + "sync.answer" -> { + val remote=map(rec["remote"]) + if (args["token"]!=rec["token"]) return mapOf("stale" to true) + if (args["yes"]==true) { + rec["allowPush"]=false; rec["policyToken"]=rec["token"] + rec["marker"]=remote; rec.remove("pending") + } else { + rec["allowPush"]=false; rec["policyToken"]=rec["token"] + rec["declinedAt"]=remote["at"]; rec["declinedReset"]=remote["reset"]==true + rec.remove("pending") + } + save(a,document,rec) + return mapOf("move" to (args["yes"]==true),"remote" to remote,"token" to rec["token"]) + } + else -> throw IllegalArgumentException("sync operation") + } + } finally { log("sync.owner.$op ms=${(System.nanoTime()-started)/1_000_000}") } + } + private fun pull(a: ServerAdapter, document: String, rec: MutableMap): Map { + val reply=a.position(document) + (reply["error"] as? String)?.let { throw ServerFailure(it) } + val remote=mapOf("percentage" to reply["percentage"],"position" to reply["position"],"at" to reply["timestamp"], + "reset" to (reply["reset"]==true),"web" to (reply["web"]==true),"label" to reply["label"]).filterValues { it!=null } + if (remote["reset"]!=true) rec.remove("declinedReset") + if (map(rec["remote"])!=remote) rec["token"]=java.util.UUID.randomUUID().toString() + rec["remote"]=remote + save(a,document,rec) + return mapOf("document" to document,"snapshot" to projection(document,scope(a),rec)) + } + /** Read-only preview runs on an immutable publication: no SQL, network, writes or worker wait. + * It is the only synchronous bridge, allowing an already-known move before the first draw. */ + fun preview(adapter: String, owner: String?, args: Map<*, *>): Map { + val rec=previews[adapter+"|"+owner+"|"+args["path"]] ?: return mapOf("pending" to true) + if (args["token"]!=rec["token"]) return mapOf("stale" to true) + val out=decision(rec,args) + return mapOf("decision" to out.decision,"applied" to presentation(rec,args,out,"prerender"),"remote" to rec["remote"],"token" to rec["token"],"document" to rec["document"]) + } + private fun decision(rec: Map, args: Map<*, *>): PositionPolicy.Decision { + val remote=map(rec["remote"]); val marker=map(rec["marker"]); val local=map(rec["local"]) + val percentOnly=args["percent_only"]==true + if((args["automatic"] ?: rec["automatic"])==false && map(rec["override"]).isEmpty()) { + val here=number(args["page"]) ?: 0.0; val there=number(args["remote_page"]) + val tolerance=number(args["tolerance"]) ?: 1.0 + if(there==null) return PositionPolicy.Decision("push","custom-empty") + if(kotlin.math.abs(here-there)<=tolerance) return PositionPolicy.Decision("same","custom-same") + val turn=time(args["turn_at"] ?: local["turnAt"]) + val newer=if(turn>0) time(remote["at"])>turn || there>here && rec["compared"]!=true else there>here + val strategy=map(rec["directions"])[if(newer) "ahead" else "behind"] ?: if(newer) "ask" else "keep" + if(strategy=="keep") return PositionPolicy.Decision(if(newer) "hold" else "push","custom-keep") + if(time(rec["declinedAt"])!=0L && rec["declinedAt"]==remote["at"]) return PositionPolicy.Decision(if(newer) "stay" else "push","custom-declined") + return PositionPolicy.Decision(if(newer) "take" else "follow","custom-$strategy") + } + return PositionPolicy.decide(PositionPolicy.Input(number(args["page"]) ?: 0.0,number(args["remote_page"]), + number(args["tolerance"]) ?: 1.0,time(remote["at"]), + number(args["marker_page"])?.let { PositionPolicy.Marker(time(marker["at"]),it) }, + time(args["turn_at"] ?: local["turnAt"]),remote["reset"]==true, + remote["web"]==true && args["same_chapter"]==true && (number(args["remote_page"]) ?: 0.0)-(number(args["marker_page"]) ?: 0.0)<=1, + args["finished"]==true,args["released"]==true, + if (remote["reset"]==true && rec["declinedReset"]==true) time(remote["at"]) else time(rec["declinedAt"]), + map(rec["override"])["at"]?.let(::time),percentOnly)) + } + private fun presentation(rec: Map, args: Map<*, *>, out: PositionPolicy.Decision, moment: String): String { + if((args["automatic"] ?: rec["automatic"])==false && out.rule.startsWith("custom-")) { + // A prompt strategy never interrupts a scheduled reading pause. Cached silent + // placement is safe before draw; after draw, use the approved one-draw consent. + if(moment=="prerender" && out.rule!="custom-follow") return "no" + if(moment=="pause" && out.rule=="custom-ask") return "no" + } + return PositionPolicy.apply(out.decision,moment) + } + private fun decide(a: ServerAdapter, document: String, rec: MutableMap, args: Map<*, *>): Map { + if (args["token"]!=rec["token"]) return mapOf("stale" to true) + val out=decision(rec,args); val moment=args["moment"] as? String ?: "reading" + rec["compared"]=true + if (out.dropped) rec.remove("override") + if (out.rule=="rule7" && out.decision=="push") rec["rereadAt"]=map(rec["remote"])["at"] + if (out.decision=="same") { rec["marker"]=rec["remote"]; rec.remove("pending") } + val applied=presentation(rec,args,out,if(moment=="wake-local") "wake" else moment) + if (applied=="wake") rec["pending"]=true + rec["allowPush"]=out.decision in setOf("push","override") + rec["policyToken"]=rec["token"] + save(a,document,rec) + val result=mapOf("decision" to out.decision,"applied" to applied,"remote" to rec["remote"],"token" to rec["token"],"document" to document) + if(moment=="wake-local") return result + val delivered=drain(a) + return result+delivered+if(record(a,document)["token"]!=result["token"]) mapOf("stale" to true) else emptyMap() + } + fun drain(a: ServerAdapter): Map { + val started=System.nanoTime() + try { return drainWindow(a,started) } + finally { log("sync.owner.drain ms=${(System.nanoTime()-started)/1_000_000}") } + } + private fun drainWindow(a: ServerAdapter, started: Long): Map { + ensure(); val owner=scope(a) + var error: String?=null + val defaultAutomatic=a.positionDirections().automatic + for (entry in journal.window(a.id,owner)) { + if (entry.source!=null && !entry.retired) continue + var checkpoint=entry.checkpoint + try { pull(a,entry.document,record(a,entry.document).toMutableMap()) } + catch(e: ServerFailure) { error=e.kind; break } + for (phase in LifecycleQueue.PHASES) { + if((System.nanoTime()-started)/1_000_000>20000) { error="retryable"; break } + if (phase in entry.acknowledged) continue + try { + check(a.positionOwner()==owner) + if (phase=="progress") { + val rec=record(a,entry.document) + val remote=map(rec["remote"]) + val capture=a.lifecyclePosition(entry.payload) + val override=map(rec["override"]) + val remoteFraction=number(remote["percentage"]) + val staleOverride=override.isNotEmpty() && time(remote["at"])>time(override["at"]) && time(remote["at"])!=time(map(rec["marker"])["at"]) + if (staleOverride) { val changed=rec.toMutableMap(); changed.remove("override"); save(a,entry.document,changed) } + val fraction=if(staleOverride) capture.percentage else number(override["percentage"]) ?: capture.percentage + val exempt=override.isNotEmpty() && !staleOverride || rec["rereadAt"]==remote["at"] && remote["at"]!=null + val fallback=PositionPolicy.decide(PositionPolicy.Input((fraction ?: 0.0)*100,remoteFraction?.times(100),1.0, + time(remote["at"]),number(map(rec["marker"])["percentage"])?.let { PositionPolicy.Marker(time(map(rec["marker"])["at"]),it*100) }, + time(map(rec["local"])["turnAt"]),remote["reset"]==true,finished=capture.finished,released=exempt, + overrideAt=if(exempt) time(override["at"]) else null,percentOnly=true)) + val custom=(rec["automatic"] ?: defaultAutomatic)==false + val lifecycle=map(rec["local"])["moment"] in setOf("close","sleep","suspend") + val allowed=if(custom && lifecycle) true else if(rec["policyToken"]==rec["token"] && number(map(rec["local"])["percentage"])==fraction) rec["allowPush"]==true + else custom || fallback.decision in setOf("push","override") + val olderThanOverride=capture.capturedAt? = null private val artifacts = linkedMapOf() + private var sync: BookOrbitSync? = null + override fun importLifecycle(queue: LifecycleQueue, settings: File, quiesced: Boolean): Int { + check(quiesced) + sync = BookOrbitSync(settings, { path, body -> + val c=login("sync") + fun native(value: Any?): Any? = when(value) { + is String -> LuaValue.utf8(value) + is Map<*, *> -> value.entries.associate { it.key.toString() to native(it.value) } + is List<*> -> value.map { native(it) } + else -> value + } + @Suppress("UNCHECKED_CAST") + val reply=transport.request(c.server,path,"POST",native(body) as Map,headers(c,"sync")) + check(reply); reply.value as? Map<*, *> ?: throw ServerFailure("invalid-response") + },queue.sql) + var legacyOwner: String? = null + val stateFiles=settings.listFiles().orEmpty().filter { it.name.matches(Regex("bookorbit_sync_state(?:_[a-f0-9]{32})?\\.lua")) } + require(stateFiles.size<=128 && stateFiles.sumOf { it.length() }<=LifecycleQueue.MAX_BYTES) + val states=stateFiles.mapNotNull { f -> LegacyLifecycleImport.literal(f)?.let { f to it } } + fun namespace(identity: String): String? { + val server=identity.substringBeforeLast('|',""); val user=identity.substringAfterLast('|',"") + if(server.isBlank() || user.isBlank()) return null + val normalized=runCatching { BookOrbitAccount.normalizeServer(LuaValue.utf8(server)) }.getOrNull() ?: return null + val current=credentials.login("sync") + return if(current?.server==normalized && current.user==LuaValue.utf8(user)) current.owner() + else ServerCredentials.Login(normalized,LuaValue.utf8(user),"","user").owner() + } + val count=LegacyLifecycleImport(queue,settings,{ old -> + val server=(old["server_url"] as? String)?.let { runCatching { BookOrbitAccount.normalizeServer(LuaValue.utf8(it)) }.getOrNull() } + val user=(old["username"] as? String)?.let(LuaValue::utf8) + if(server==null || user.isNullOrBlank()) null else { + val current=credentials.login("sync") + if(current==null) { + val key=(old["userkey"] as? String)?.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) } + if(key!=null) credentials.set("sync",ServerCredentials.Login(server,user,key,"user")) + } + val selected=credentials.login("sync") + val fallback=if(selected?.server==server && selected.user==user) selected.owner() + else ServerCredentials.Login(server,user,"","user").owner() + val snapshot=old["_snapshot"] as? Map<*, *> + if(snapshot==null) { legacyOwner=fallback; fallback } + else { + val identity=(old["server_url"] as String).trimEnd('/')+"|"+(old["username"] as String) + val namedHash=MessageDigest.getInstance("MD5").digest(identity.toByteArray(Charsets.ISO_8859_1)).joinToString("") { "%02x".format(it) } + val matches=states.filter { (_,state) -> + val book=(state["books"] as? Map<*, *>)?.get(snapshot["digest"]) as? Map<*, *> + book!=null && (book["file"]==null || book["file"]==snapshot["file"]) + } + val proven=matches.map { (file,state) -> (state["account_identity"] as? String) + ?: identity.takeIf { file.name=="bookorbit_sync_state_$namedHash.lua" } }.distinct() + when { + matches.size==1 && proven.singleOrNull()!=null -> namespace(proven.single()!!) + matches.isEmpty() && (states.isEmpty() || states.size==1 && states.single().second["account_identity"]==identity) -> fallback + else -> null // Multiple editions/accounts in the legacy store: never guess current credentials. + } + } + } + }).run(true) + // This local decision state never contains credentials. Import once; later companion state wins. + val root=LegacyLifecycleImport.literal(File(settings.parentFile,"settings.reader.lua")) + val old=(root?.get("orbit_android") as? Map<*, *>)?.get("orbismart") as? Map<*, *> + val bound=legacyOwner + if(bound!=null) queue.sql.transaction { + val configured=(root?.get("bookorbit") as? Map<*, *>).orEmpty() + val identity=(configured["server_url"] as? String)?.trimEnd('/')+"|"+configured["username"] + val namedHash=MessageDigest.getInstance("MD5").digest(identity.toByteArray(Charsets.ISO_8859_1)).joinToString("") { "%02x".format(it) } + val selected=states.firstOrNull { it.second["account_identity"]==identity || it.first.name=="bookorbit_sync_state_$namedHash.lua" }?.second + val books=(selected?.get("books") as? Map<*, *>).orEmpty() + // Queued snapshots can belong to an older account. Preserve its known state too: + // null rating/review captures mean explicit clears only with that account's history. + for((file,state) in states) { + val proven=(state["account_identity"] as? String) + ?: identity.takeIf { file.name=="bookorbit_sync_state_$namedHash.lua" } + val stateOwner=proven?.let(::namespace) ?: continue + for((doc,book) in (state["books"] as? Map<*, *>).orEmpty()) if(doc is String && book is Map<*, *>) { + queue.sql.exec("INSERT OR IGNORE INTO adapter_sync_books VALUES (?,?,?)",stateOwner,doc,LuaValue.encode(book)) + } + } + for((document,value) in old.orEmpty()) { + if(document !is String || value !is Map<*, *> || queue.record(id,bound,document).isNotEmpty()) continue + if(states.isNotEmpty() && document !in books) continue + fun remote(raw: Any?): Map { + val r=raw as? Map<*, *> ?: return emptyMap() + return mapOf("at" to r["at"],"percentage" to r["pct"],"position" to r["progress"], + "reset" to (r["device_id"]=="bookorbit-web" && (r["pct"] as? Number)?.toDouble()==0.0),"web" to (r["device"]=="web"),"label" to (r["device_name"] ?: r["device"])) + } + queue.record(id,bound,document,mapOf("marker" to remote(value["m"]),"remote" to remote(value["server"]), + "override" to remote(value["override"]),"declinedAt" to value["declined_at"],"declinedReset" to value["declined_reset"], + "path" to ((books[document] as? Map<*, *>)?.get("file")),"pending" to value["pending"],"rereadAt" to value["reread_at"],"token" to java.util.UUID.randomUUID().toString())) + } + } + return count + } + override fun positionDirections() = sync?.directions() ?: PositionDirections() + override fun captureLifecycle(capture: Map<*, *>) = (sync ?: throw ServerFailure("writer-active")).capture(capture) + override fun positionIntent(document: String, update: Map) = LuaValue.encode(mapOf( + "digest" to document,"percentage" to update["percentage"],"progress" to update["position"],"ts" to update["capturedAt"])) + override fun lifecyclePosition(payload: ByteArray): CapturedPosition { + val raw=LuaValue.parse(payload) as? Map<*, *> ?: throw ServerFailure("invalid") + return CapturedPosition((raw["percentage"] as? Number)?.toDouble(),raw["progress"] as? String, + (raw["ts"] as? Number)?.toLong() ?: 0L,raw["status"]=="complete") + } + override fun lifecyclePhase(entry: LifecycleQueue.Entry, phase: String, checkpoint: ByteArray, openPath: String?) = + (sync ?: throw ServerFailure("writer-active")).phase(entry,phase,checkpoint,openPath) + override fun lifecycleComplete(checkpoint: ByteArray): Boolean = + ((LuaValue.parse(checkpoint) as? Map<*, *>)?.get("remote_pending") as? Map<*, *>).isNullOrEmpty() + override fun nextSyncVerification(owner: String, document: String) = + (sync ?: throw ServerFailure("writer-active")).nextVerification(owner,document) + override fun syncVerification(owner: String, document: String, key: String, valid: Boolean, page: Int?) = + (sync ?: throw ServerFailure("writer-active")).verification(owner,document,key,valid,page) private fun login(kind: String): ServerCredentials.Login { val c = credentials.login(kind) ?: throw BookOrbitAccount.Failure("unauthorized") if (c.origin == "account" && account.state()["signedIn"] != true) throw BookOrbitAccount.Failure("unauthorized") @@ -113,15 +223,18 @@ internal class BookOrbitServerAdapter(private val credentials: ServerCredentials require(position == null || position.length <= 4096) val capturedAt = (it["capturedAt"] as? Number)?.toLong() require(capturedAt == null || capturedAt > 0) - mapOf("document" to document, "percentage" to percentage, "progress" to position?.let(LuaValue::utf8), "device" to "BookSync") + + mapOf("document" to document, "percentage" to percentage, "progress" to position?.let(LuaValue::utf8), "device" to "BookSync", "device_id" to sync?.deviceId()) + (if (capturedAt != null) mapOf("timestamp" to capturedAt) else emptyMap()) } val reply = transport.request(c.server, path, if (body == null) "GET" else "PUT", body, headers(c,"sync")) + if(update==null && reply.code==404) return emptyMap() check(reply) val raw = reply.value as? Map<*, *> ?: emptyMap() val position = raw["progress"] as? String require(position == null || position.length <= 4096) - return mapOf("position" to position, "percentage" to (raw["percentage"] as? Number), "timestamp" to (raw["timestamp"] as? Number)) + return mapOf("position" to position, "percentage" to (raw["percentage"] as? Number), "timestamp" to (raw["timestamp"] as? Number), + "reset" to (raw["device_id"]=="bookorbit-web" && (raw["percentage"] as? Number)?.toDouble()==0.0), + "web" to (raw["device"]=="web"),"label" to ((raw["device_name"] ?: raw["device"]) as? String)?.let { LuaValue.boundedText(LuaValue.utf8(it),100) }) } override fun catalog(page: Int, limit: Int): Map { require(page in 1..10000 && limit in 1..24) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt new file mode 100644 index 00000000..eeff7509 --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt @@ -0,0 +1,304 @@ +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import java.io.File +import java.io.RandomAccessFile +import java.security.MessageDigest +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +/** The sync protocol's only transport owner. Source snapshots/checkpoints stay private here. */ +internal class BookOrbitSync(private val settings: File, + private val request: (String,Map)->Map<*, *>, + private val journal: Sql, + private val openSql: (File)->Sql = { AndroidSql(it,readOnly=true) }, + private val allowed: (File)->Boolean = { Places.inside(it,Places.roots())!=null }) { + private fun map(value: Any?) = (value as? Map<*, *>)?.entries?.associate { it.key.toString() to it.value }.orEmpty() + private fun list(value: Any?) = value as? List<*> ?: emptyList() + private fun text(value: Any?) = value as? String + private fun bounded(value: Any?, bytes: Int): String? = (value as? String)?.let { LuaValue.boundedText(LuaValue.utf8(it),bytes) } + private fun locator(value: Any?): String? = when(value) { + is String -> value + is Number -> value.toString() + is Map<*, *> -> LuaValue.str(org.json.JSONObject(value).toString()) + else -> null + } + private fun md5(value: ByteArray) = MessageDigest.getInstance("MD5").digest(value).joinToString("") { "%02x".format(it) } + private val hashes=mutableMapOf() + private val global=LegacyLifecycleImport.literal(File(settings.parentFile,"settings.reader.lua")).orEmpty() + init { + journal.exec("CREATE TABLE IF NOT EXISTS adapter_sync_books (owner TEXT NOT NULL,document TEXT NOT NULL,body BLOB NOT NULL,PRIMARY KEY(owner,document))") + journal.exec("CREATE TABLE IF NOT EXISTS adapter_sync_verifications (owner TEXT NOT NULL,document TEXT NOT NULL,k TEXT NOT NULL,body BLOB NOT NULL,ready INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(owner,document,k))") + } + private fun file(snapshot: Map<*, *>) = (snapshot["file"] as? String)?.let { File(LuaValue.utf8(it)) }?.also { + require(allowed(it)); (snapshot["digest"] as? String)?.let { hash -> hashes[it.path]=hash } + } + private fun sidecar(book: File): File { + val name="metadata.${book.extension.ifEmpty { "_" }}.lua" + val doc=File(book.parentFile,"${book.nameWithoutExtension}.sdr/$name") + val dir=File(settings.parentFile,"docsettings${book.path.substringBeforeLast('.')}.sdr/$name") + val hash=hashes[book.path] + val hashed=hash?.let { File(settings.parentFile,"hashdocsettings/${it.take(2)}/$it.sdr/$name") } + val candidates=when(global["document_metadata_folder"]) { + "hash" -> listOfNotNull(hashed,doc,dir) + "dir" -> listOfNotNull(dir,doc,hashed) + else -> listOfNotNull(doc,dir,hashed) + } + return (candidates.firstOrNull { it.isFile } ?: candidates.first()).also { require(allowed(it)) } + } + private fun readSidecar(book: File): Map { + val source=sidecar(book) + if(!source.isFile) return emptyMap() + val parsed=LegacyLifecycleImport.literal(source) ?: throw ServerFailure("invalid-sidecar") + return map(parsed) + } + private fun writeSidecar(book: File, data: Map) { + val dest=sidecar(book); require(allowed(dest)); dest.parentFile?.mkdirs() + val temp=File(dest.parentFile,dest.name+".booksync.tmp") + temp.writeBytes("return ".toByteArray()+LuaValue.encode(data)); check(temp.renameTo(dest)) + } + fun directions(): PositionDirections { + val root=LegacyLifecycleImport.literal(File(settings.parentFile,"settings.reader.lua")).orEmpty() + val owned=map(root["orbit_android"]); val legacy=map(root["bookorbit"]) + val saved=map(owned["osm_saved_plugin"]) + val source=if(legacy["sync_forward"]==3L && legacy["sync_backward"]==3L && saved.isNotEmpty()) saved else legacy + fun strategy(key: String, fallback: String)=when((source[key] as? Number)?.toInt()) { 1->"ask"; 2->"follow"; 3->"keep"; else->fallback } + return PositionDirections(owned["sync_mode"]!="custom",strategy("sync_forward","ask"),strategy("sync_backward","keep")) + } + fun capture(args: Map<*, *>): Pair { + val percentage=(args["percentage"] as? Number)?.toDouble() + require(percentage==null || percentage.isFinite() && percentage in 0.0..1.0) + val position=locator(args["position"]) + require(position==null || position.length<=4096) + val book=File(LuaValue.utf8(args["path"] as? String ?: throw IllegalArgumentException("path"))) + require(allowed(book)) + val hash=MessageDigest.getInstance("MD5") + if(book.isFile) RandomAccessFile(book,"r").use { input -> + val bytes=ByteArray(1024) + for (i in -1..10) { val offset=if(i<0) 0L else 1024L shl (2*i) + input.seek(offset); val n=input.read(bytes); if(n<0) break; hash.update(bytes,0,n) } + } + val digest=if(book.isFile) hash.digest().joinToString("") { "%02x".format(it) } + else (args["document"] as? String)?.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) } ?: throw ServerFailure("missing") + hashes[book.path]=digest + val data=readSidecar(book); val summary=map(data["summary"])+map(args["summary"]) + val statsId=(args["stats_id"] as? Number)?.toLong() + val ids=if(statsId!=null) listOf(statsId) else if(File(settings,"statistics.sqlite3").isFile) + openSql(File(settings,"statistics.sqlite3")).use { sql -> sql.query("SELECT id FROM book WHERE md5=?",digest) { it.long(0)!! } } else emptyList() + val snapshot=mapOf("digest" to digest,"file" to LuaValue.str(book.path),"percentage" to percentage, + "progress" to position,"status" to summary["status"],"status_modified" to summary["modified"], + "rating" to (summary["rating"] as? Number)?.toInt()?.takeIf { it in 1..5 },"review_note" to bounded(summary["note"],10000),"ts" to args["captured_at"], + "title" to (data["doc_props"] as? Map<*, *>)?.get("title"),"authors" to (data["doc_props"] as? Map<*, *>)?.get("authors"), + "stats_ids" to ids,"annotations" to annotations(data,false),"bookmarks" to annotations(data,true),"native_capture" to true, + "annotation_sync" to ((LegacyLifecycleImport.literal(File(settings.parentFile,"settings.reader.lua"))?.get("bookorbit") as? Map<*, *>)?.get("annotation_sync")!=false)) + return digest to LuaValue.encode(snapshot) + } + private fun annotations(data: Map<*, *>, bookmarks: Boolean): List> = list(data["annotations"]).mapNotNull { raw -> + val a=map(raw); val date=(a["datetime"] as? String)?.takeIf { it.matches(Regex("\\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d")) } ?: return@mapNotNull null + val start=a[if(bookmarks) "page" else "pos0"] ?: return@mapNotNull null + if ((a["drawer"]==null)!=bookmarks) return@mapNotNull null + if (a["bookorbit_pending_verification"]==true || a["booksync_pending_verification"]==true) return@mapNotNull null + if (bookmarks && start !is String) return@mapNotNull null + if (!bookmarks && locator(start)==null) return@mapNotNull null + if (bookmarks) mapOf("datetime" to date,"datetimeUpdated" to a["datetime_updated"],"pos" to bounded(start,4000), + "pageno" to a["pageno"],"chapter" to bounded(a["chapter"],500),"note" to bounded(a["note"],500)) + else mapOf("datetime" to date,"datetimeUpdated" to a["datetime_updated"],"pos0" to bounded(locator(start),4000),"pos1" to bounded(locator(a["pos1"]),4000), + "posFormat" to if(start is String) "xpointer" else "page","drawer" to a["drawer"],"color" to a["color"], + "text" to bounded(a["text"],10000),"note" to bounded(a["note"],5000),"chapter" to bounded(a["chapter"],500),"pageno" to a["pageno"]) + } + private fun result(body: Map<*, *>, digest: String): Map { + if (digest in list(body["unmatched"])) throw ServerFailure("missing") + if (digest in list(body["positionIncompatible"])) throw ServerFailure("incompatible") + return map(list(body["results"]).firstOrNull()) + } + private fun device(body: Map) = body+mapOf("deviceId" to deviceId(),"deviceModel" to "BookSync", + "deviceTime" to LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))) + fun deviceId(): String { + val path=File(settings,"booksync-sync-device") + if(path.isFile) return path.readText().also { require(it.matches(Regex("[A-Za-z0-9-]{1,100}"))) } + settings.mkdirs(); val id=(global["device_id"] as? String)?.takeIf { it.matches(Regex("[A-Za-z0-9-]{1,100}")) } ?: java.util.UUID.randomUUID().toString() + val temp=File(settings,path.name+".tmp"); temp.writeText(id); check(temp.renameTo(path)); return id + } + fun phase(entry: LifecycleQueue.Entry, phase: String, encoded: ByteArray, openPath: String?): SyncPhaseResult { + val snap=map(LuaValue.parse(entry.payload)); val checkpoint=map(LuaValue.parse(encoded)).toMutableMap() + val book=file(snap); val isOpen=snap["file"]==openPath + fun done(complete: Boolean=true) = SyncPhaseResult(LuaValue.encode(checkpoint),complete) + when(phase) { + "match" -> { + val match=request("/koreader/plugin/match-check",device(mapOf("hashes" to listOf(entry.document),"books" to listOf(mapOf( + "hash" to entry.document,"title" to snap["title"],"authors" to snap["authors"],"lastOpen" to snap["last_open"],"source" to "current_file"))))) + val found=list(match["matches"]).map(::map).firstOrNull { it["hash"]==entry.document } ?: throw ServerFailure("missing") + checkpoint["match"]=found + return done() + } + "stats" -> { + if (snap["stats_metadata_ambiguous"]==true) return done() + val db=File(settings,"statistics.sqlite3"); if(!db.isFile) return done() + val cursor=list(checkpoint["stats_cursor"]).map { (it as Number).toLong() } + val at=cursor.getOrElse(0) { 0 }; val page=cursor.getOrElse(1) { -1 }; val row=cursor.getOrElse(2) { -1 } + val captured=(snap["ts"] as? Number)?.toLong() ?: Long.MAX_VALUE + val events=openSql(db).use { sql -> + val ids=list(snap["stats_ids"]).mapNotNull { (it as? Number)?.toLong() }.ifEmpty { + sql.query("SELECT id FROM book WHERE md5=?",entry.document) { it.long(0)!! } + } + if(ids.isEmpty()) emptyList() else { + val marks=ids.joinToString(",") { "?" } + sql.query("SELECT page,start_time,duration,total_pages,id_book FROM page_stat_data WHERE id_book IN ($marks) AND total_pages>0 AND start_time<=? AND (start_time>? OR (start_time=? AND page>?) OR (start_time=? AND page=? AND id_book>?)) ORDER BY start_time,page,id_book LIMIT 256", + *(ids+listOf(captured,at,at,page,at,page,row)).toTypedArray()) { r -> mapOf("page" to r.long(0),"startTime" to r.long(1), + "durationSeconds" to (r.long(2) ?: 0).coerceIn(0,86400),"totalPages" to r.long(3),"row" to r.long(4)) } + } + } + if(events.isEmpty()) return done() + val upload=mutableMapOf("hash" to entry.document,"events" to events.map { it-"row" }) + if(snap["stats_row_ambiguous"]==true) { + var match=map(checkpoint["match"]) + if(match["bookFileId"]==null) { + val reply=request("/koreader/plugin/match-check",device(mapOf("hashes" to listOf(entry.document),"books" to listOf(mapOf("hash" to entry.document,"title" to snap["title"],"authors" to snap["authors"]))))) + match=list(reply["matches"]).map(::map).firstOrNull { it["hash"]==entry.document } ?: throw ServerFailure("missing") + checkpoint["match"]=match + } + upload["bookFileId"]=match["bookFileId"] ?: throw ServerFailure("missing") + } + result(request("/koreader/plugin/page-stats",device(mapOf("books" to listOf(upload)))),entry.document) + val last=events.last(); checkpoint["stats_cursor"]=listOf(last["startTime"],last["page"],last["row"]) + return done(events.size<256) + } + "annotations" -> { + if(map(checkpoint["match"])["positionCompatible"]==false) return done() + val pending=map(checkpoint["remote_pending"]).toMutableMap() + val enabled=map(checkpoint["legacy"])["annotation_sync"]!=false && snap["annotation_sync"]!=false + if(!enabled && pending["annotations"]==null && pending["bookmarks"]==null) return done() + var incomplete=false + if(!isOpen && book!=null && book.isFile) cleanVerified(entry.owner,entry.document,book) + for ((kind,bookmark) in listOf("annotations" to false,"bookmarks" to true)) { + val key="exchange_$kind" + val progress=map(checkpoint[key]).toMutableMap() + if(progress["done"]==true && pending[kind]==null) continue + val existing=map(pending[kind]) + if(existing.isNotEmpty()) { + if(book==null || !book.isFile || isOpen) { incomplete=true; continue } + val ack=applyRemote(entry,book,kind,map(existing["to_apply"])) + request("/koreader/plugin/$kind/exchange-ack",device(mapOf("books" to listOf(mapOf("hash" to entry.document)+ack)))) + pending.remove(kind) + if(progress["done"]==true && existing["more"]!=true) { checkpoint[key]=progress; continue } + } + if(!enabled) continue // Complete imported pending applications, but do not restart disabled exchanges. + val changes=if(progress.containsKey("changes")) list(progress["changes"]).map(::map) else { + val captured=if(snap["native_capture"]==true && !isOpen && book!=null) annotations(readSidecar(book),bookmark) else list(snap[kind]).map(::map) + progress["changes"]=captured; captured + } + val cursor=(progress["cursor"] as? Number)?.toInt() ?: 0 + val chunk=changes.drop(cursor).take(16) + // A historical queued snapshot never establishes absence/deletion of newer notes. + val completeKeys=snap["native_capture"]==true && !isOpen && book!=null && readSidecar(book)["booksync_sync_known"]==true + val keys=if(cursor==0 && completeKeys) changes.map { a -> mapOf("k" to md5(((a["datetime"] as String)+"|"+a[if(bookmark) "pos" else "pos0"]).toByteArray(Charsets.ISO_8859_1)),"dt" to a["datetime"]) } else emptyList() + val response=result(request("/koreader/plugin/$kind/exchange",device(mapOf("books" to listOf(mapOf("hash" to entry.document, + "keys" to keys,"keysComplete" to completeKeys,"changes" to chunk))))),entry.document) + val toApply=map(response["toApply"]) + if(toApply.values.any { list(it).isNotEmpty() }) { + pending[kind]=mapOf("to_apply" to toApply,"more" to response["more"]) + incomplete=true + } + progress["cursor"]=cursor+chunk.size + progress["done"]=cursor+chunk.size>=changes.size && response["more"]!=true + if(progress["done"]!=true) incomplete=true + checkpoint[key]=progress + } + checkpoint["remote_pending"]=pending + if(enabled && !incomplete && !isOpen && book!=null && book.isFile) writeSidecar(book,readSidecar(book)+("booksync_sync_known" to true)) + return done(!incomplete) + } + "state" -> { + val pending=map(checkpoint["remote_pending"]).toMutableMap() + var state=map(pending["state"]) + if(state.isEmpty()) { + val known=journal.query("SELECT body FROM adapter_sync_books WHERE owner=? AND document=?",entry.owner,entry.document) { map(LuaValue.parse(it.bytes(0)!!)) }.firstOrNull().orEmpty() + val sent=mutableMapOf("hash" to entry.document) + if(snap["status"]!=null) { sent["status"]=snap["status"]; if(snap["status_modified"]!=null) sent["statusModified"]=snap["status_modified"] } + if(snap["rating"]!=null) sent["rating"]=snap["rating"] + else if(known["ratingSyncedKnown"]==true && known["ratingSynced"]!=null) sent["ratingCleared"]=true + if(snap["review_note"]!=null) sent["reviewNote"]=snap["review_note"] + else if(known["reviewSyncedKnown"]==true && known["reviewSyncedNote"]!=null) sent["reviewCleared"]=true + if(snap["review_modified"]!=null || snap["status_modified"]!=null) sent["reviewModified"]=snap["review_modified"] ?: snap["status_modified"] + val reply=result(request("/koreader/plugin/book-states",device(mapOf("books" to listOf(sent)))),entry.document) + state=mapOf("status_known" to (reply["statusSet"]==true),"status" to reply["status"],"status_modified" to (reply["statusUpdatedAt"] as? String)?.take(10), + "rating_known" to (reply["ratingSet"] is Boolean),"rating" to reply["rating"].takeIf { reply["ratingSet"]==true }, + "review_known" to (reply["reviewNoteSet"] is Boolean),"review_note" to reply["reviewNote"].takeIf { reply["reviewNoteSet"]==true }) + if(state.values.all { it==null || it==false }) return done() + journal.exec("INSERT OR REPLACE INTO adapter_sync_books VALUES (?,?,?)",entry.owner,entry.document,LuaValue.encode(known+mapOf( + "ratingSyncedKnown" to state["rating_known"],"ratingSynced" to state["rating"],"reviewSyncedKnown" to state["review_known"],"reviewSyncedNote" to state["review_note"]))) + pending["state"]=state; checkpoint["remote_pending"]=pending + } + if(book==null || !book.isFile || isOpen) return done(false) + val data=readSidecar(book); val summary=map(data["summary"]).toMutableMap() + if(state["status_known"]==true) { summary["status"]=state["status"]; summary["modified"]=state["status_modified"] } + if(state["rating_known"]==true) summary["rating"]=state["rating"] + if(state["review_known"]==true) summary["note"]=state["review_note"] + writeSidecar(book,data+("summary" to summary)); pending.remove("state"); checkpoint["remote_pending"]=pending + return done() + } + else -> throw IllegalArgumentException("phase") + } + } + fun nextVerification(owner: String, document: String): Map { + val found=journal.query("SELECT k,body FROM adapter_sync_verifications WHERE owner=? AND document=? AND ready=0 LIMIT 1",owner,document) { + it.text(0)!! to map(LuaValue.parse(it.bytes(1)!!)) + }.firstOrNull() ?: return emptyMap() + return mapOf("row" to mapOf("key" to found.first,"start" to found.second["pos0"],"end" to found.second["pos1"])) + } + fun verification(owner: String, document: String, key: String, valid: Boolean, page: Int?) { + val raw=journal.query("SELECT body FROM adapter_sync_verifications WHERE owner=? AND document=? AND k=? AND ready=0",owner,document,key) { map(LuaValue.parse(it.bytes(0)!!)) }.firstOrNull() ?: return + val ack=mapOf("serverId" to raw["serverId"],"version" to raw["version"],"status" to if(valid) "applied" else "failed", + "verified" to valid,"pos0" to raw["pos0"],"pos1" to raw["pos1"],"pageno" to page,"datetimeUpdated" to raw["datetimeUpdated"]) + request("/koreader/plugin/annotations/exchange-ack",device(mapOf("books" to listOf(mapOf("hash" to document,"applied" to listOf(ack),"deleted" to emptyList()))))) + journal.exec("UPDATE adapter_sync_verifications SET ready=? WHERE owner=? AND document=? AND k=?",if(valid) 1 else 2,owner,document,key) + } + private fun cleanVerified(owner: String, document: String, book: File) { + val keys=journal.query("SELECT k FROM adapter_sync_verifications WHERE owner=? AND document=? AND ready=1 LIMIT 1024",owner,document) { it.text(0)!! }.toSet() + if(keys.isEmpty()) return + val data=readSidecar(book) + val annotations=list(data["annotations"]).map { a -> + val row=map(a) + if(row["booksync_verification"] in keys) row-filterOfPending else row + } + writeSidecar(book,data+("annotations" to annotations)) + for(key in keys) journal.exec("DELETE FROM adapter_sync_verifications WHERE owner=? AND document=? AND k=?",owner,document,key) + } + private val filterOfPending=setOf("booksync_verification","booksync_pending_verification","bookorbit_pending_verification") + private fun applyRemote(job: LifecycleQueue.Entry, book: File, kind: String, changes: Map): Map { + val data=readSidecar(book); val entries=list(data["annotations"]).map { map(it).toMutableMap() }.toMutableList() + val applied=mutableListOf>() + val deleted=mutableListOf>() + val verification=mutableMapOf>() + val bookmark=kind=="bookmarks" + fun find(change: Map) = entries.indexOfFirst { a -> + val position=a[if(bookmark) "page" else "pos0"] + (a["drawer"]==null)==bookmark && (a["booksync_remote_id"]==change["serverId"] && change["serverId"]!=null || + a["datetime"]==change["datetime"] && locator(position)==change[if(bookmark) "pos" else "pos0"] || + (change["key"] ?: change["k"])==md5(("${a["datetime"]}|${locator(position)}").toByteArray(Charsets.ISO_8859_1))) } + for(op in listOf("add","edit","delete")) for(raw in list(changes[op])) { + val change=map(raw); val index=find(change) + if(op=="delete") { if(index>=0) entries.removeAt(index); deleted+=mapOf("serverId" to change["serverId"],"status" to "applied"); continue } + val position=change[if(bookmark) "pos" else "pos0"] + if(!bookmark && change["posFormat"]!="xpointer" && index<0) { + applied+=mapOf("serverId" to change["serverId"],"version" to change["version"],"status" to "failed"); continue + } + val annotation=if(index>=0) entries[index] else mutableMapOf().also { entries+=it } + for(key in listOf("datetime","drawer","color","text","note","chapter","pageno","pos0","pos1")) if(change.containsKey(key) && !(key=="text" && change[key]=="")) annotation[key]=change[key] + annotation["note"]=change["note"] + if(change["datetimeUpdated"]!=null) annotation["datetime_updated"]=change["datetimeUpdated"] + annotation["page"]=position; annotation["booksync_remote_id"]=change["serverId"] + if(bookmark) { annotation.remove("drawer"); annotation["note"]=change["title"] ?: change["note"] } + else { + val key=md5("${job.owner}|${job.document}|${change["serverId"]}|${change["version"]}".toByteArray(Charsets.UTF_8)) + annotation["booksync_verification"]=key; annotation["booksync_pending_verification"]=true + verification[key]=change + } + applied+=if(bookmark) mapOf("serverId" to change["serverId"],"status" to "applied","key" to md5(((annotation["datetime"] as? String ?: "")+"|"+position).toByteArray(Charsets.ISO_8859_1)),"datetime" to annotation["datetime"],"pos" to position) + else mapOf("serverId" to change["serverId"],"version" to change["version"],"status" to "applied","verified" to false,"pos0" to position,"pos1" to change["pos1"],"datetimeUpdated" to change["datetimeUpdated"]) + } + writeSidecar(book,data+mapOf("annotations" to entries,"annotations_externally_modified" to true)) + for((key,body) in verification) journal.exec("INSERT OR IGNORE INTO adapter_sync_verifications(owner,document,k,body) VALUES (?,?,?,?)",job.owner,job.document,key,LuaValue.encode(body)) + return mapOf("applied" to applied,"deleted" to deleted) + } +} diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ConnectorHttp.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ConnectorHttp.kt index a57f44b5..5bb7ee9d 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ConnectorHttp.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/ConnectorHttp.kt @@ -18,7 +18,8 @@ internal object ConnectorHttp : BookOrbitServerAdapter.ConnectorTransport { if (body != null) { c.doOutput = true; c.setRequestProperty("Content-Type", "application/json") val bytes = JSONObject(body).toString().toByteArray(Charsets.UTF_8) - try { require(bytes.size <= 16384); c.outputStream.use { it.write(bytes) } } finally { bytes.fill(0) } + // Worker batches have a transport cap; screen snapshots retain their 16 KiB cap. + try { require(bytes.size <= 1048576); c.outputStream.use { it.write(bytes) } } finally { bytes.fill(0) } } val code = c.responseCode if (code !in 200..299) return BookOrbitAccount.Reply(code) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLifecycleImport.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLifecycleImport.kt new file mode 100644 index 00000000..7f1b812e --- /dev/null +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLifecycleImport.kt @@ -0,0 +1,107 @@ +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import java.io.File +import java.security.MessageDigest + +/** Read-only parsing until the journal/checkpoint commit; then atomic per-entry retirement. + * Originals stay in a non-writer archive. No Lua is executed, even for corrupt input. */ +internal class LegacyLifecycleImport(private val queue: LifecycleQueue, private val root: File, + private val owner: (Map<*, *>) -> String?, private val crash: (String) -> Unit = {}) { + companion object { + private val NAME=Regex("^(entry_[a-fA-F0-9]+_[0-9]+_[0-9]+)_g([0-9]+)\\.lua$") + fun literal(file: File, max: Int = LifecycleQueue.MAX_BYTES): Map<*, *>? { + if (!file.isFile || file.length()>max) return null + val text=String(file.readBytes(),Charsets.ISO_8859_1) + .replaceFirst(Regex("\\A(?:\\s*--[^\\n]*\\n)*\\s*(?:return\\s+)?"),"") + return LuaValue.parse(text.toByteArray(Charsets.ISO_8859_1)) as? Map<*, *> + } + private fun hash(file: File): String { + val digest=MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> val bytes=ByteArray(8192) + while (true) { val n=input.read(bytes); if (n<0) break; digest.update(bytes,0,n) } } + return digest.digest().joinToString("") { "%02x".format(it) } + } + } + fun run(quiesced: Boolean): Int { + check(quiesced) { "legacy writer still active" } + val source=File(root,"bookorbit-lifecycle-outbox") + val archive=File(root,"booksync-retired-lifecycle") + // Resume a crash between individual renames even when its metadata has already moved. + for ((id,encoded) in queue.imports("bookorbit")) { + val proof=LuaValue.parse(encoded) as? Map<*, *> ?: continue + val dest=File(archive,id) + check(dest.isDirectory || dest.mkdirs()) + for ((name,digest) in proof) { + require(name is String && name.matches(Regex(Regex.escape(id)+"(?:_payload)?_g[0-9]+\\.lua"))) + val from=File(source,name); val to=File(dest,name) + if (to.isFile) { check(hash(to)==digest); if (from.isFile) check(hash(from)==digest && from.delete()) } + else { check(from.isFile && hash(from)==digest); check(from.renameTo(to)) } + crash("retire-file") + } + queue.retired("bookorbit",id) + } + val login=literal(File(root.parentFile,"settings.reader.lua"))?.get("bookorbit") as? Map<*, *> ?: emptyMap() + owner(login) // Initialize credential/provenance lookup, even when the source is empty. + val files=source.listFiles().orEmpty().filter { NAME.matches(it.name) } + require(files.size<=10000) + var imported=0 + val selectedEntries=files.groupBy { NAME.matchEntire(it.name)!!.groupValues[1] }.mapNotNull { (id,generations) -> + val selected=generations.sortedByDescending { NAME.matchEntire(it.name)!!.groupValues[2].toLongOrNull() ?: 0L } + .firstNotNullOfOrNull { metadata -> + val generation=NAME.matchEntire(metadata.name)!!.groupValues[2].toLongOrNull() + val m=literal(metadata) ?: return@firstNotNullOfOrNull null + if (m["version"]!=1L || m["id"]!=id || m["generation"]!=generation || (m["acknowledged"] !is Map<*, *> && m["acknowledged"] != emptyList())) return@firstNotNullOfOrNull null + val digest=m["digest"] as? String ?: return@firstNotNullOfOrNull null + if (!digest.matches(Regex("[a-fA-F0-9]+"))) return@firstNotNullOfOrNull null + val pg=(m["payload_generation"] as? Number)?.toLong()?.takeIf { it>=1 } ?: return@firstNotNullOfOrNull null + val payload=File(source,"${id}_payload_g$pg.lua") + val p=literal(payload) ?: return@firstNotNullOfOrNull null + if (p["version"]!=1L || p["id"]!=id || p["digest"]!=digest || p["snapshot"] !is Map<*, *>) return@firstNotNullOfOrNull null + Triple(m,payload,metadata) + } ?: return@mapNotNull null // Damaged entries remain untouched for recovery. + id to selected + }.sortedWith(compareBy,File,File>>> { + (it.second.first["enqueued_at"] as? Number)?.toLong() ?: 0L + }.thenBy { it.first }) + for ((id,selected) in selectedEntries) { + val m=selected.first + val payload=literal(selected.second)!!["snapshot"] as Map<*, *> + val bound=owner(login+mapOf("_entry" to m,"_snapshot" to payload)) ?: continue // Unproven ownership stays in source. + val entryFiles=source.listFiles().orEmpty().filter { it.name.matches(Regex(Regex.escape(id)+"(?:_payload)?_g[0-9]+\\.lua")) } + if (entryFiles.sumOf { it.length() }>LifecycleQueue.MAX_BYTES) continue + val proof=LuaValue.encode(entryFiles.associate { it.name to hash(it) }) + val key=id // Immutable after quiescence; dedup spans crashes, not account switches. + val acks=(m["acknowledged"] as? Map<*, *>).orEmpty() + val pending=(m["remote_pending"] as? Map<*, *>).orEmpty() + val outstanding=buildSet { + if(pending.containsKey("annotations") || pending.containsKey("bookmarks")) add("annotations") + if(pending.containsKey("state")) add("state") + } + crash("before-checkpoint") + queue.enqueue("bookorbit",bound,m["digest"] as String,LuaValue.encode(payload), + LifecycleQueue.PHASES.filter { acks[it]==true && it !in outstanding }.toSet(), + LuaValue.encode(mapOf("legacy" to m,"remote_pending" to m["remote_pending"])),key,proof) + crash("after-checkpoint") + check(queue.importProof("bookorbit",key)?.contentEquals(proof)==true) { "legacy source changed after checkpoint" } + check(entryFiles.all { it.isFile && hash(it)==(LuaValue.parse(proof) as Map<*, *>)[it.name] }) + val dest=File(archive,id) + check(dest.isDirectory || dest.mkdirs()) + for (f in entryFiles) { + val target=File(dest,f.name) + if (target.exists()) check(hash(target)==hash(f) && f.delete()) + else check(f.renameTo(target)) + crash("retire-file") + } + crash("after-retire") + queue.retired("bookorbit",key) + imported++ + } + // Crash after the atomic retirement but before its marker: the committed proof is enough. + for (dir in archive.listFiles().orEmpty().filter { it.isDirectory }) { + val proof=queue.importProof("bookorbit",dir.name)?.let(LuaValue::parse) as? Map<*, *> ?: continue + if (proof.all { (name,digest) -> name is String && File(dir,name).isFile && hash(File(dir,name))==digest }) queue.retired("bookorbit",dir.name) + } + return imported + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/PositionPolicyTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/PositionPolicyTest.kt new file mode 100644 index 00000000..22d8924a --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/PositionPolicyTest.kt @@ -0,0 +1,34 @@ +package net.fledgewing.orbitcompanion + +import java.io.File +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Test + +class PositionPolicyTest { + private val cases=JSONObject(File("../../../shared/fixtures/orbismart/cases.json").readText()) + @Test fun everySharedDecisionCase() { + val rows=cases.getJSONArray("decide") + for (n in 0 until rows.length()) { + val row=rows.getJSONObject(n); val i=row.getJSONObject("in"); val want=row.getJSONObject("want") + val marker=i.optJSONObject("marker") + val input=PositionPolicy.Input(i.optDouble("local",0.0),if (i.has("server")&&!i.isNull("server")) i.getDouble("server") else null, + i.optDouble("tolerance",1.0),i.optLong("server_at"),marker?.let { PositionPolicy.Marker(it.optLong("at"),it.optDouble("place")) }, + i.optLong("turn_at"),i.optBoolean("reset"),i.optBoolean("redated"),i.optBoolean("finished"),i.optBoolean("released"), + i.optLong("declined_at"),i.optJSONObject("override")?.optLong("at"),i.optBoolean("percent_only")) + val result=PositionPolicy.decide(input) + assertEquals(row.getString("name"),want.getString("decision"),result.decision) + assertEquals(row.getString("name"),want.getString("rule"),result.rule) + assertEquals(row.getString("name"),want.optBoolean("dropped"),result.dropped) + } + } + @Test fun everySharedPresentationAndBehindHoldCase() { + val applied=cases.getJSONArray("apply") + for (n in 0 until applied.length()) { val c=applied.getJSONObject(n) + assertEquals(c.getString("applied"),PositionPolicy.apply(c.getString("decision"),c.getString("moment"))) } + val push=cases.getJSONArray("push") + for (n in 0 until push.length()) { val c=push.getJSONObject(n) + assertEquals(c.getString("name"),c.getBoolean("allowed"),PositionPolicy.mayPush(c.optDouble("place"), + if (c.isNull("server")) null else c.getDouble("server"),c.optDouble("tolerance",1.0),c.has("exempt"))) } + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/ProgressOutboxTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/ProgressOutboxTest.kt index ab4c102a..9cfa1c98 100644 --- a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/ProgressOutboxTest.kt +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/ProgressOutboxTest.kt @@ -6,6 +6,24 @@ import org.junit.Assert.* import org.junit.Test class ProgressOutboxTest { + private data class Drain(val sent: Int,val pending: Int,val error: String?) + /** Test convenience only: production has no queue-side transport or second drainer. */ + private class Queue(sql: Sql, root: File, now: ()->Long) { + private val capture=ProgressOutbox(sql,now) + private val journal=LifecycleQueue(sql) + private val owner=SyncOwner(journal,root,{},now) + fun enqueue(adapter: String,account: String,document: String,update: Map)=capture.enqueue(adapter,account,document,update) + fun count()=capture.count() + fun contains(id: String)=capture.contains(id) + fun drain(adapter: ServerAdapter): Drain { + val account=adapter.positionOwner() ?: return Drain(0,0,"unauthorized") + owner.activate(adapter,true) + val before=journal.pending(adapter.id,account) + val result=owner.drain(adapter) + val after=journal.pending(adapter.id,account) + return Drain(before-after,after,result["error"] as? String) + } + } private class Toy : ServerAdapter { override val id = "toy" var account: String? = "sync:one" @@ -15,7 +33,8 @@ class ProgressOutboxTest { override fun positionOwner() = account override fun position(document: String, update: Map?): Map { if (offline) throw ServerFailure("unavailable") - delivered += document to requireNotNull(update) + if(update==null) return emptyMap() + delivered += document to update return mapOf("ok" to true) } } @@ -28,17 +47,17 @@ class ProgressOutboxTest { val toy = Toy().also { it.offline = true } val locator = LuaValue.str("opaque:位置/one") val id = JdbcSql(file).use { sql -> - val queue = ProgressOutbox(sql, {}) { 100L } + val queue = Queue(sql,file.parentFile!!) { 100L } val id = queue.enqueue(toy.id,toy.positionOwner()!!,"urn:book:one",write(locator)) - assertEquals(ProgressOutbox.Drain(0,1,"unavailable"),queue.drain(toy)) + assertEquals(Drain(0,1,"unavailable"),queue.drain(toy)) assertTrue(queue.contains(id)) id } JdbcSql(file).use { sql -> - val queue = ProgressOutbox(sql, {}) { 900L } + val queue = Queue(sql,file.parentFile!!) { 900L } assertTrue(queue.contains(id)) toy.offline = false - assertEquals(ProgressOutbox.Drain(1,0,null),queue.drain(toy)) + assertEquals(Drain(1,0,null),queue.drain(toy)) assertEquals("urn:book:one",toy.delivered.single().first) assertEquals(locator,toy.delivered.single().second["position"]) assertEquals(100L,toy.delivered.single().second["capturedAt"]) @@ -48,13 +67,13 @@ class ProgressOutboxTest { } @Test fun accountsAdaptersAndCatalogOwnershipCannotCrossDeliver() = database { file -> JdbcSql(file).use { sql -> - val queue = ProgressOutbox(sql, {}) { 100L } + val queue = Queue(sql,file.parentFile!!) { 100L } val toy = Toy() queue.enqueue("other","sync:one","book:other-adapter",write()) queue.enqueue("toy","sync:two","book:other-account",write()) queue.enqueue("toy","catalog:other","book:catalog-account",write()) queue.enqueue("toy","sync:one","book:current",write()) - assertEquals(ProgressOutbox.Drain(1,0,null),queue.drain(toy)) + assertEquals(Drain(1,0,null),queue.drain(toy)) assertEquals("book:current",toy.delivered.single().first) assertEquals(3,queue.count()) toy.account = null @@ -67,28 +86,28 @@ class ProgressOutboxTest { } @Test fun fifoStopsAtFailureAndDrainReadsOnlyOneBoundedWindow() = database { file -> JdbcSql(file).use { sql -> - val queue = ProgressOutbox(sql, {}) { 100L } + val queue = Queue(sql,file.parentFile!!) { 100L } val toy = Toy().also { it.offline = true } repeat(ProgressOutbox.MAX_BATCH+1) { queue.enqueue("toy","sync:one","book:$it",write()) } - assertEquals(ProgressOutbox.Drain(0,25,"unavailable"),queue.drain(toy)) + assertEquals(Drain(0,25,"unavailable"),queue.drain(toy)) toy.offline = false - assertEquals(ProgressOutbox.Drain(24,1,null),queue.drain(toy)) + assertEquals(Drain(24,1,null),queue.drain(toy)) assertEquals((0..23).map { "book:$it" },toy.delivered.map { it.first }) - assertEquals(ProgressOutbox.Drain(1,0,null),queue.drain(toy)) + assertEquals(Drain(1,0,null),queue.drain(toy)) } } @Test fun unsuccessfulRepliesAreNeverAcknowledged() = database { file -> JdbcSql(file).use { sql -> - val queue = ProgressOutbox(sql, {}) { 100L } + val queue = Queue(sql,file.parentFile!!) { 100L } val adapter = object : ServerAdapter { override val id = "unsupported"; override fun owner() = "account" } queue.enqueue(adapter.id,adapter.owner(),"book",write()) - assertEquals(ProgressOutbox.Drain(0,1,"unsupported"),queue.drain(adapter)) + assertEquals(Drain(0,1,"unsupported"),queue.drain(adapter)) assertEquals(1,queue.count()) } } @Test fun validationAndCapacityFailureLeaveEarlierWritesIntact() = database { file -> JdbcSql(file).use { sql -> - val queue = ProgressOutbox(sql, {}) { 100L } + val queue = Queue(sql,file.parentFile!!) { 100L } for (bad in listOf(write("x".repeat(4097)),write("位置"),mapOf("percentage" to Double.NaN),mapOf("percentage" to -1),mapOf("percentage" to 2))) { assertThrows(IllegalArgumentException::class.java) { queue.enqueue("toy","sync:one","book",bad) } } @@ -100,9 +119,9 @@ class ProgressOutboxTest { } @Test fun queuePersistsOnlyReviewedFields() = database { file -> JdbcSql(file).use { sql -> - val queue = ProgressOutbox(sql, {}) { 100L } + val queue = Queue(sql,file.parentFile!!) { 100L } queue.enqueue("toy","sync:one","book",write()+mapOf("password" to "fixture-secret","unrelated" to listOf(1,2))) - val body = LuaValue.parse(sql.query("SELECT body FROM position_outbox") { it.bytes(0)!! }.single()) as Map<*, *> + val body = LuaValue.parse(sql.query("SELECT payload FROM lifecycle_jobs") { it.bytes(0)!! }.single()) as Map<*, *> assertEquals(setOf("percentage","position","capturedAt"),body.keys) } } @@ -111,18 +130,18 @@ class ProgressOutboxTest { JdbcSql(file).use { database -> val failing = object : Sql by database { override fun exec(sql: String, vararg args: Any?) { - if (sql.startsWith("DELETE FROM position_outbox")) throw IllegalStateException("fixture disk error") + if (sql.startsWith("INSERT OR IGNORE INTO lifecycle_acks") && args.getOrNull(1)=="progress") throw IllegalStateException("fixture disk error") database.exec(sql,*args) } } - val queue = ProgressOutbox(failing, {}) { 100L } + val queue = Queue(failing,file.parentFile!!) { 100L } queue.enqueue("toy","sync:one","book",write()) - assertEquals(ProgressOutbox.Drain(0,1,"unavailable"),queue.drain(toy)) + assertEquals(Drain(0,1,"unavailable"),queue.drain(toy)) assertEquals(1,toy.delivered.size) } JdbcSql(file).use { sql -> - val queue = ProgressOutbox(sql, {}) { 900L } - assertEquals(ProgressOutbox.Drain(1,0,null),queue.drain(toy)) + val queue = Queue(sql,file.parentFile!!) { 900L } + assertEquals(Drain(1,0,null),queue.drain(toy)) assertEquals(2,toy.delivered.size) assertEquals(toy.delivered[0],toy.delivered[1]) } diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/SyncOwnerTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/SyncOwnerTest.kt new file mode 100644 index 00000000..e3e87575 --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/SyncOwnerTest.kt @@ -0,0 +1,176 @@ +package net.fledgewing.orbitcompanion + +import java.io.File +import java.nio.file.Files +import org.junit.Assert.* +import org.junit.Test + +/** End-to-end journal/policy/consent tests deliberately use an unrelated opaque-key adapter. */ +class SyncOwnerTest { + private class Toy : ServerAdapter { + override val id="toy" + var account="account/one" + var offline=false + var directions=PositionDirections() + override fun positionDirections()=directions + var remote: Map = emptyMap() + val writes=mutableListOf>() + val phases=mutableListOf() + val leases=mutableListOf() + override fun positionOwner()=account + override fun position(document: String, update: Map?): Map { + if(offline) throw ServerFailure("offline") + if(update!=null) { writes+=update; remote=mapOf("percentage" to update["percentage"],"position" to update["position"],"timestamp" to update["capturedAt"]) } + return remote + } + override fun captureLifecycle(capture: Map<*, *>): Pair = "urn:toy:book" to LuaValue.encode(mapOf( + "percentage" to capture["percentage"],"position" to capture["position"],"capturedAt" to capture["captured_at"],"finished" to capture["finished"])) + override fun lifecyclePhase(entry: LifecycleQueue.Entry,phase: String,checkpoint: ByteArray,openPath: String?): SyncPhaseResult { + phases+=phase; leases+=openPath; return SyncPhaseResult(checkpoint) + } + } + private fun args(fraction: Double=.4,at: Long=1000,moment: String="open",online: Boolean=true) = mapOf( + "path" to "/fixture/book.epub","percentage" to fraction,"position" to "locator:$fraction","page" to fraction*300, + "captured_at" to at,"turn_at" to at,"moment" to moment,"online" to online) + private fun fixture(test: (File,LifecycleQueue,SyncOwner,Toy)->Unit) { + val root=Files.createTempDirectory("sync-owner").toFile() + try { JdbcSql(File(root,"journal.db")).use { sql -> + val q=LifecycleQueue(sql); val a=Toy(); val owner=SyncOwner(q,root,{}, { 1000L }) + owner.activate(a,true); test(root,q,owner,a) + } } finally { root.deleteRecursively() } + } + @Test fun quiescenceIsRequiredAndOfflineSnapshotsSurviveCompanionRestart() = fixture { root,q,owner,a -> + assertThrows(IllegalStateException::class.java) { SyncOwner(q,root,{}).activate(a,false) } + a.offline=true + assertEquals(true,owner.command(a,"sync.capture",args(online=false))["queued"]) + assertEquals(1,q.pending(a.id,a.account)); assertTrue(a.writes.isEmpty()) + val restarted=SyncOwner(q,root,{},{ 2000L }); restarted.activate(a,true) + assertEquals("offline",restarted.command(a,"sync.drain",emptyMap())["error"]) + assertEquals(1,q.pending(a.id,a.account)) + a.offline=false + assertEquals(0,restarted.command(a,"sync.drain",emptyMap())["remaining"]) + assertEquals(listOf("match","stats","annotations","state"),a.phases) + assertEquals(1000L,a.writes.single()["capturedAt"]) + } + @Test fun sidecarLeaseSurvivesCloseCaptureAndCompanionRestartUntilNativeClosure() = fixture { root,q,owner,a -> + owner.command(a,"sync.capture",args(moment="close",online=false)) + owner.command(a,"sync.drain",emptyMap()) + assertTrue(a.leases.all { it=="/fixture/book.epub" }) + a.leases.clear() + val restarted=SyncOwner(q,root,{}, {2000L}) + restarted.command(a,"sync.activate",mapOf("quiesced" to true,"epoch" to "same-reader","path" to "/fixture/book.epub")) + restarted.command(a,"sync.capture",args(online=false)) + restarted.command(a,"sync.drain",emptyMap()) + assertTrue(a.leases.isNotEmpty()); assertTrue(a.leases.all { it=="/fixture/book.epub" }) + a.leases.clear() + restarted.command(a,"sync.capture",args(online=false)) + restarted.command(a,"sync.drain",mapOf("closed_path" to "/fixture/book.epub","online" to false)) + assertTrue("offline closure only releases the lease",a.leases.isEmpty()) + restarted.command(a,"sync.drain",emptyMap()) + assertTrue(a.leases.isNotEmpty()); assertTrue(a.leases.all { it==null }) + } + @Test fun staleCaptureCannotReplaceCurrentSidecarLeaseOrKeepAnOldPathPreview() = fixture { _,_,owner,a -> + a.remote=mapOf("percentage" to .8,"position" to "remote:240","timestamp" to 900L) + val current=owner.command(a,"sync.capture",args()+mapOf("path" to "/fixture/current.epub")) + val snapshot=current["snapshot"] as Map<*, *> + owner.command(a,"sync.capture",args(online=false)+mapOf("current" to false)) + owner.command(a,"sync.drain",emptyMap()) + assertTrue(a.leases.isNotEmpty()); assertTrue(a.leases.all { it=="/fixture/current.epub" }) + assertEquals(true,owner.preview(a.id,a.account,mapOf("path" to "/fixture/current.epub","token" to snapshot["token"],"page" to 120,"remote_page" to 240))["pending"]) + } + @Test fun declineAndMarkerStatePersistAndStaleConsentCannotMoveAnotherPlace() = fixture { root,q,owner,a -> + a.remote=mapOf("percentage" to .8,"position" to "remote:240","timestamp" to 900L) + val pulled=owner.command(a,"sync.capture",args()) + val snapshot=pulled["snapshot"] as Map<*, *> + val mapped=mapOf("document" to "urn:toy:book","token" to snapshot["token"],"page" to 120,"remote_page" to 240,"moment" to "open") + val decision=owner.command(a,"sync.decide",mapped) + assertEquals("take",decision["decision"]); assertEquals("ask",decision["applied"]); assertTrue(a.writes.isEmpty()) + owner.command(a,"sync.answer",mapped+mapOf("yes" to false)) + val restarted=SyncOwner(q,root,{}); restarted.activate(a,true) + assertEquals("stay",restarted.command(a,"sync.decide",mapped)["decision"]) + a.remote=a.remote+("timestamp" to 1100L) + restarted.command(a,"sync.pull",args()) + assertEquals(true,restarted.command(a,"sync.answer",mapped+mapOf("yes" to true))["stale"]) + assertEquals(900L,q.record(a.id,a.account,"urn:toy:book")["declinedAt"]) + } + @Test fun overrideGoesBeforeOlderSnapshotsAndIsConsumedOnce() = fixture { _,q,owner,a -> + a.remote=mapOf("percentage" to .8,"position" to "remote:240","timestamp" to 900L) + owner.command(a,"sync.capture",args(.5,500,online=false)) + owner.command(a,"sync.override",args(.1,1000,online=false)) + owner.command(a,"sync.drain",emptyMap()) + assertEquals(1,a.writes.size) + assertEquals(.1,a.writes.single()["percentage"]) + assertEquals("locator:0.1",a.writes.single()["position"]) + assertNull(q.record(a.id,a.account,"urn:toy:book")["override"]) + owner.command(a,"sync.capture",args(.05,1200,online=false)) + owner.command(a,"sync.drain",emptyMap()) + assertEquals(1,a.writes.size) + } + @Test fun newerRemoteMovementDropsAnOfflineOverrideInsteadOfReplayingIt() = fixture { root,q,owner,a -> + a.remote=mapOf("percentage" to .8,"position" to "remote:240","timestamp" to 900L) + owner.command(a,"sync.pull",args()) + // A busy worker must retain the time the reader chose, not its later dispatch time. + val delayed=SyncOwner(q,root,{}, {9000L}) + delayed.activate(a,true) + delayed.command(a,"sync.override",args(.1,1000,online=false)) + a.remote=a.remote+("timestamp" to 1200L) + owner.command(a,"sync.drain",emptyMap()) + assertTrue(a.writes.isEmpty()); assertNull(q.record(a.id,a.account,"urn:toy:book")["override"]) + } + @Test fun customKeepAndLifecyclePushRemainOwnedByCompanion() = fixture { _,_,owner,a -> + a.directions=PositionDirections(false,"keep","keep") + a.remote=mapOf("percentage" to .8,"position" to "remote:240","timestamp" to 900L) + val pulled=owner.command(a,"sync.capture",args()+mapOf("automatic" to false)) + val snapshot=pulled["snapshot"] as Map<*, *> + val mapped=mapOf("document" to "urn:toy:book","token" to snapshot["token"],"page" to 120,"remote_page" to 240,"turn_at" to 1000,"moment" to "open","automatic" to false) + assertEquals("hold",owner.command(a,"sync.decide",mapped)["decision"]) + assertTrue(a.writes.isEmpty()) + owner.command(a,"sync.capture",args(moment="close",online=false)+mapOf("automatic" to false)) + owner.command(a,"sync.drain",emptyMap()) + assertEquals(.4,a.writes.last()["percentage"]) + } + @Test fun customPromptIsQuietDuringScheduledPauseAndReadingAfterDeclineCanPush() = fixture { _,_,owner,a -> + a.directions=PositionDirections(false,"ask","keep") + a.remote=mapOf("percentage" to .8,"position" to "remote:240","timestamp" to 900L) + val snapshot=owner.command(a,"sync.capture",args()+mapOf("automatic" to false))["snapshot"] as Map<*, *> + val mapped=mapOf("document" to "urn:toy:book","token" to snapshot["token"],"page" to 120,"remote_page" to 240,"moment" to "pause","automatic" to false) + assertEquals("no",owner.command(a,"sync.decide",mapped)["applied"]) + assertEquals("ask",owner.command(a,"sync.decide",mapped+mapOf("moment" to "open","turn_at" to 0))["applied"]) + owner.command(a,"sync.answer",mapped+mapOf("yes" to false)) + owner.command(a,"sync.capture",args(.45,1100,moment="pause")+mapOf("automatic" to false)) + val result=owner.command(a,"sync.decide",mapped+mapOf("page" to 135,"turn_at" to 1100)) + assertEquals("push",result["decision"]); assertEquals(.45,a.writes.last()["percentage"]) + } + @Test fun customSilentKnownPlacementUsesPurePrerenderPreviewAndConsentAfterDraw() = fixture { _,_,owner,a -> + a.directions=PositionDirections(false,"follow","keep") + a.remote=mapOf("percentage" to .8,"position" to "remote:240","timestamp" to 900L) + val snapshot=owner.command(a,"sync.capture",args()+mapOf("automatic" to false))["snapshot"] as Map<*, *> + val mapped=mapOf("path" to "/fixture/book.epub","document" to "urn:toy:book","token" to snapshot["token"],"page" to 120,"remote_page" to 240,"turn_at" to 0,"moment" to "open","automatic" to false) + assertEquals("now",owner.preview(a.id,a.account,mapped)["applied"]) + assertTrue(a.writes.isEmpty()) + assertEquals("ask",owner.command(a,"sync.decide",mapped)["applied"]) + } + @Test fun successfulDeliveryPublishesTheCommittedPlaceAndClearsDeferredConsent() = fixture { root,q,owner,a -> + a.directions=PositionDirections(false,"ask","keep") + a.remote=mapOf("percentage" to .8,"position" to "remote:240","timestamp" to 900L) + val snapshot=owner.command(a,"sync.capture",args()+mapOf("automatic" to false))["snapshot"] as Map<*, *> + owner.command(a,"sync.decide",mapOf("document" to "urn:toy:book","token" to snapshot["token"],"page" to 120,"remote_page" to 240,"moment" to "sleep","automatic" to false)) + owner.command(a,"sync.capture",args(moment="close",online=false)+mapOf("automatic" to false)) + owner.command(a,"sync.drain",emptyMap()) + val record=q.record(a.id,a.account,"urn:toy:book") + assertEquals(.4,(record["remote"] as Map<*, *>)["percentage"]) + assertNull(record["pending"]); assertNotEquals(snapshot["token"],record["token"]) + assertEquals(true,owner.command(a,"sync.answer",mapOf("document" to "urn:toy:book","token" to snapshot["token"],"yes" to true))["stale"]) + val cached=File(root,"orbit-cache/position").listFiles()!!.single() + assertEquals(.4,((LuaValue.parse(cached.readBytes()) as Map<*, *>)["remote"] as Map<*, *>)["percentage"]) + } + @Test fun ownerSwitchNeverSendsAnotherAccountsQueueAndPreviewHasNoTransport() = fixture { _,q,owner,a -> + owner.command(a,"sync.capture",args(online=false)) + a.account="account/two" + assertEquals(0,owner.command(a,"sync.drain",emptyMap())["remaining"]) + assertEquals(1,q.pending(a.id,"account/one")); assertTrue(a.writes.isEmpty()) + a.offline=true + assertEquals(true,owner.preview(a.id,a.account,args())["pending"]) + assertTrue(a.writes.isEmpty()) + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSyncTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSyncTest.kt new file mode 100644 index 00000000..dcda2173 --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSyncTest.kt @@ -0,0 +1,124 @@ +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import java.io.File +import java.nio.file.Files +import org.junit.Assert.* +import org.junit.Test + +class BookOrbitSyncTest { + private class Kit(val root: File) : AutoCloseable { + val sql=JdbcSql(File(root,"journal.db")); val q=LifecycleQueue(sql) + val book=File(root,"fixture.epub").apply { writeText("fixture book bytes") } + val sidecar=File(root,"fixture.sdr/metadata.epub.lua").apply { parentFile!!.mkdirs(); writeBytes(LuaValue.encode(mapOf("summary" to mapOf("status" to "reading"),"unrelated" to "keep"))) } + val calls=mutableListOf>>() + var response: ((String,Map)->Map<*, *>)?=null + val sync=BookOrbitSync(root,{ path,body -> + calls+=path to body + response?.invoke(path,body) ?: if(path.endsWith("match-check")) mapOf("matches" to listOf(mapOf("hash" to document,"bookFileId" to 4,"positionCompatible" to true))) + else mapOf("results" to listOf(emptyMap())) + },sql,::JdbcSql,{true}) + var document="a".repeat(32) + fun job(snapshot: Map,checkpoint: Map = emptyMap()): LifecycleQueue.Entry { + val payload=mapOf("digest" to document,"file" to book.path,"percentage" to .5,"progress" to "/p50","ts" to 1000L)+snapshot + val id=q.enqueue("fixture","account",document,LuaValue.encode(payload),checkpoint=LuaValue.encode(checkpoint)) + return q.window("fixture","account").first { it.id==id } + } + override fun close()=sql.close() + } + private fun fixture(test: (Kit)->Unit) { + val root=Files.createTempDirectory("sync-protocol").toFile() + try { Kit(root).use(test) } finally { root.deleteRecursively() } + } + @Test fun phaseRequestsAreAdapterOwnedAndStatsCursorDoesNotLoseEqualTimestampRows() = fixture { k -> + JdbcSql(File(k.root,"statistics.sqlite3")).use { db -> + db.exec("CREATE TABLE book (id INTEGER PRIMARY KEY,md5 TEXT)") + db.exec("CREATE TABLE page_stat_data (id_book INTEGER,page INTEGER,start_time INTEGER,duration INTEGER,total_pages INTEGER)") + db.exec("INSERT INTO book VALUES (1,?)",k.document) + db.transaction { repeat(300) { db.exec("INSERT INTO page_stat_data VALUES (1,?,1000,10,400)",it+1) } } + } + val job=k.job(mapOf("stats_ids" to listOf(1))) + var cp=k.sync.phase(job,"match",job.checkpoint,null).checkpoint + val first=k.sync.phase(job,"stats",cp,null); assertFalse(first.complete); cp=first.checkpoint + val second=k.sync.phase(job,"stats",cp,null); assertTrue(second.complete) + val uploaded=k.calls.filter { it.first.endsWith("page-stats") }.flatMap { + val books=it.second["books"] as List<*>; (books.single() as Map<*, *>)["events"] as List<*> + } + assertEquals(300,uploaded.size) + assertEquals((1L..300L).toList(),uploaded.map { (it as Map<*, *>)["page"] }) + } + @Test fun remotePendingWaitsForCloseThenPersistsSidecarBeforeAcknowledgmentAndVerifiesOneLocator() = fixture { k -> + val remote=mapOf("serverId" to 10L,"version" to 2L,"datetime" to "2026-11-25 10:00:00","posFormat" to "xpointer", + "pos0" to "/p10","pos1" to "/p11","drawer" to "lighten","text" to "fixture") + val job=k.job(mapOf("annotations" to emptyList(),"bookmarks" to emptyList()), + mapOf("remote_pending" to mapOf("annotations" to mapOf("to_apply" to mapOf("add" to listOf(remote)))), + "exchange_annotations" to mapOf("done" to true),"exchange_bookmarks" to mapOf("done" to true))) + val held=k.sync.phase(job,"annotations",job.checkpoint,k.book.path) + assertFalse(held.complete); assertTrue(k.calls.isEmpty()) + k.response={path,_ -> + if(path.endsWith("exchange-ack")) { + val data=LegacyLifecycleImport.literal(k.sidecar)!! + assertEquals("keep",data["unrelated"]) + assertEquals(1,(data["annotations"] as List<*>).size) + } + mapOf("results" to listOf(emptyMap())) + } + val closed=k.sync.phase(job,"annotations",held.checkpoint,null) + assertTrue(closed.complete) + val row=k.sync.nextVerification("account",k.document)["row"] as Map<*, *> + assertEquals("/p10",row["start"]); assertEquals("/p11",row["end"]) + assertFalse(row.containsKey("serverId")); assertFalse(row.containsKey("version")) + val capture=k.sync.capture(mapOf("path" to k.book.path,"percentage" to .5,"position" to "/p50","captured_at" to 1001L)) + val captured=LuaValue.parse(capture.second) as Map<*, *> + assertEquals("unverified sidecar rows must not become local uploads",emptyList(),captured["annotations"]) + k.sync.verification("account",k.document,row["key"] as String,true,10) + assertTrue(k.sync.nextVerification("account",k.document).isEmpty()) + assertEquals(true,(((k.calls.last().second["books"] as List<*>).single() as Map<*, *>)["applied"] as List<*>).let { (it.single() as Map<*, *>)["verified"] }) + } + @Test fun unknownRatingAndReviewNeverBecomeAccidentalClearsAndOpenSidecarsAreNotWritten() = fixture { k -> + val original=k.sidecar.readBytes() + k.response={path,body -> + if(path.endsWith("book-states")) { + val sent=(body["books"] as List<*>).single() as Map<*, *> + assertFalse(sent.containsKey("rating")); assertFalse(sent.containsKey("reviewNote")) + assertFalse(sent.containsKey("ratingCleared")); assertFalse(sent.containsKey("reviewCleared")) + mapOf("results" to listOf(mapOf("statusSet" to true,"status" to "complete","ratingSet" to true,"rating" to 4,"reviewNoteSet" to false))) + } else emptyMap() + } + val job=k.job(mapOf("status" to "reading")) + val held=k.sync.phase(job,"state",job.checkpoint,k.book.path) + assertFalse(held.complete); assertArrayEquals(original,k.sidecar.readBytes()) + k.sync.phase(job,"state",held.checkpoint,null) + val summary=LegacyLifecycleImport.literal(k.sidecar)!!["summary"] as Map<*, *> + assertEquals("complete",summary["status"]); assertEquals(4L,summary["rating"]) + } + @Test fun knownAccountHistoryPreservesExplicitRatingAndReviewClears() = fixture { k -> + k.sql.exec("INSERT INTO adapter_sync_books VALUES (?,?,?)","account",k.document,LuaValue.encode(mapOf( + "ratingSyncedKnown" to true,"ratingSynced" to 4,"reviewSyncedKnown" to true,"reviewSyncedNote" to "old review"))) + k.sync.phase(k.job(emptyMap()),"state",LuaValue.encode(emptyMap()),k.book.path) + val sent=(k.calls.single().second["books"] as List<*>).single() as Map<*, *> + assertEquals(true,sent["ratingCleared"]); assertEquals(true,sent["reviewCleared"]) + } + @Test fun disabledAnnotationSyncDoesNotStartExchangesOrChangeSidecars() = fixture { k -> + val original=k.sidecar.readBytes() + for(job in listOf(k.job(mapOf("annotation_sync" to false)),k.job(emptyMap(),mapOf("legacy" to mapOf("annotation_sync" to false))))) { + assertTrue(k.sync.phase(job,"annotations",job.checkpoint,null).complete) + } + assertTrue(k.calls.isEmpty()); assertArrayEquals(original,k.sidecar.readBytes()) + } + @Test fun customDirectionsTranslateSavedPresetAndRespectLaterPreferenceChanges() = fixture { k -> + val settings=File(k.root,"settings").also { it.mkdirs() } + val config=File(k.root,"settings.reader.lua") + fun write(ahead: Int,behind: Int) { config.writeBytes(LuaValue.encode(mapOf("orbit_android" to mapOf("sync_mode" to "custom", + "osm_saved_plugin" to mapOf("sync_forward" to 2,"sync_backward" to 1)),"bookorbit" to mapOf("sync_forward" to ahead,"sync_backward" to behind)))) } + val sync=BookOrbitSync(settings,{_,_->error("preferences never use network")},k.sql,::JdbcSql,{true}) + write(3,3); assertEquals(PositionDirections(false,"follow","ask"),sync.directions()) + write(1,2); assertEquals(PositionDirections(false,"ask","follow"),sync.directions()) + } + @Test fun malformedSidecarIsPreservedInsteadOfBeingOverwritten() = fixture { k -> + k.sidecar.writeText("return os.execute('not evaluated')") + val job=k.job(emptyMap(),mapOf("remote_pending" to mapOf("state" to mapOf("status_known" to true,"status" to "complete")))) + assertThrows(ServerFailure::class.java) { k.sync.phase(job,"state",job.checkpoint,null) } + assertEquals("return os.execute('not evaluated')",k.sidecar.readText()) + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyAdapterMigrationTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyAdapterMigrationTest.kt new file mode 100644 index 00000000..25abc703 --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyAdapterMigrationTest.kt @@ -0,0 +1,50 @@ +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import java.io.File +import java.nio.file.Files +import org.junit.Assert.* +import org.junit.Test + +class LegacyAdapterMigrationTest { + private class Vault : AccountVault { + var value: Map?=null + override fun load()=value + override fun save(value: Map?) { this.value=value } + } + @Test fun entryProvenanceUsesItsOldAccountWithoutRebindingCurrentLogin() { + val root=Files.createTempDirectory("sync-provenance").toFile() + try { + val settings=File(root,"settings").also { it.mkdirs() } + val old=ServerCredentials.Login("https://old.invalid/api/v1","old-reader","a".repeat(32),"user") + val current=ServerCredentials.Login("https://new.invalid/api/v1","new-reader","b".repeat(32),"user") + val credentials=ServerCredentials(Vault()).also { it.set("sync",current) } + val account=BookOrbitAccount(credentials.accountVault,object : BookOrbitAccount.Http { + override fun request(server: String,path: String,method: String,body: Map?,bearer: String?): BookOrbitAccount.Reply = error("migration must not use network") + },setupOnSignIn={false}) + val adapter=BookOrbitServerAdapter(credentials,account,object : BookOrbitServerAdapter.ConnectorTransport { + override fun request(server: String,path: String,method: String,body: Map?,headers: Map): BookOrbitAccount.Reply = error("migration must not use network") + override fun download(server: String,path: String,headers: Map,destination: File): Boolean = error("migration must not download") + }) + val digest="a".repeat(32); val id="entry_${digest}_100_1" + fun literal(file: File,value: Map) { file.parentFile!!.mkdirs(); file.writeBytes("return ".toByteArray()+LuaValue.encode(value)) } + literal(File(root,"settings.reader.lua"),mapOf("bookorbit" to mapOf("server_url" to current.server,"username" to current.user))) + literal(File(settings,"bookorbit_sync_state.lua"),mapOf("account_identity" to "${old.server}|${old.user}","books" to mapOf(digest to mapOf("file" to "/fixture/one.epub","ratingSyncedKnown" to true,"ratingSynced" to 4,"reviewSyncedKnown" to true,"reviewSyncedNote" to "old review")))) + literal(File(settings,"bookorbit-lifecycle-outbox/${id}_g1.lua"),mapOf("version" to 1,"id" to id,"generation" to 1,"payload_generation" to 1,"digest" to digest,"acknowledged" to emptyMap())) + literal(File(settings,"bookorbit-lifecycle-outbox/${id}_payload_g1.lua"),mapOf("version" to 1,"id" to id,"digest" to digest,"snapshot" to mapOf("digest" to digest,"file" to "/fixture/one.epub","ts" to 100,"percentage" to .5))) + JdbcSql(File(root,"journal.db")).use { sql -> + val queue=LifecycleQueue(sql) + assertEquals(1,adapter.importLifecycle(queue,settings,true)) + assertEquals(1,queue.pending(adapter.id,old.owner())) + assertEquals(0,queue.pending(adapter.id,current.owner())) + assertEquals(current.owner(),credentials.login("sync")!!.owner()) + assertEquals(current.secret,credentials.login("sync")!!.secret) + assertTrue(queue.window(adapter.id,old.owner()).single().retired) + val known=sql.query("SELECT body FROM adapter_sync_books WHERE owner=? AND document=?",old.owner(),digest) { LuaValue.parse(it.bytes(0)!!) as Map<*, *> }.single() + assertEquals(4L,known["ratingSynced"]); assertEquals("old review",known["reviewSyncedNote"]) + assertEquals(true,known["ratingSyncedKnown"]); assertEquals(true,known["reviewSyncedKnown"]) + assertTrue(sql.query("SELECT body FROM adapter_sync_books WHERE owner=?",current.owner()) { it.bytes(0)!! }.isEmpty()) + } + } finally { root.deleteRecursively() } + } +} diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLifecycleImportTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLifecycleImportTest.kt new file mode 100644 index 00000000..0d657fae --- /dev/null +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/server/bookorbit/LegacyLifecycleImportTest.kt @@ -0,0 +1,77 @@ +package net.fledgewing.orbitcompanion.server.bookorbit + +import net.fledgewing.orbitcompanion.* +import java.io.File +import java.nio.file.Files +import org.junit.Assert.* +import org.junit.Test + +class LegacyLifecycleImportTest { + private val id="entry_${"a".repeat(32)}_100_1" + private val digest="a".repeat(32) + private fun entry(root: File, generation: Long=1, payloadGeneration: Long=generation, ack: Map = emptyMap(), id: String=this.id, at: Long=100) { + val dir=File(root,"bookorbit-lifecycle-outbox").also { it.mkdirs() } + File(dir,"${id}_g$generation.lua").writeBytes("return ".toByteArray()+LuaValue.encode(mapOf("version" to 1L,"id" to id,"generation" to generation, + "enqueued_at" to at,"payload_generation" to payloadGeneration,"digest" to digest,"acknowledged" to ack,"remote_pending" to mapOf("annotations" to mapOf("to_apply" to listOf("pending")))))) + File(dir,"${id}_payload_g$payloadGeneration.lua").writeBytes("return ".toByteArray()+LuaValue.encode(mapOf("version" to 1L,"id" to id,"digest" to digest, + "snapshot" to mapOf("digest" to digest,"percentage" to 0.5,"annotations" to listOf(mapOf("text" to "fixture")),"stats_ids" to listOf(7L),"status" to "reading")))) + } + private fun fixture(test: (File,LifecycleQueue)->Unit) { + val root=Files.createTempDirectory("legacy-import").toFile() + try { JdbcSql(File(root,"journal.db")).use { test(root,LifecycleQueue(it)) } } finally { root.deleteRecursively() } + } + @Test fun importsAllPhasesAndPendingPayloadWithProvenanceAndGenerationFallback() = fixture { root,q -> + entry(root,ack=mapOf("match" to true,"stats" to false,"annotations" to false,"state" to true,"progress" to false)) + entry(root,2); File(root,"bookorbit-lifecycle-outbox/${id}_payload_g2.lua").writeText("corrupt") + val import=LegacyLifecycleImport(q,root,{ "old-account" }) + assertEquals(1,import.run(true)) + val e=q.window("bookorbit","old-account").single() + assertEquals(setOf("match","state"),e.acknowledged) + val payload=LuaValue.parse(e.payload) as Map<*, *> + assertEquals(listOf(7L),payload["stats_ids"]) + assertEquals("reading",payload["status"]) + assertNotNull((LuaValue.parse(e.checkpoint) as Map<*, *>)["remote_pending"]) + assertTrue(e.retired) + assertEquals(0,q.pending("bookorbit","new-account")) + assertEquals(0,import.run(true)) + assertEquals(1,q.pending("bookorbit","old-account")) + } + @Test fun crashesOnBothSidesOfCheckpointAndRetirementNeverLoseOrDuplicate() { + for (boundary in listOf("before-checkpoint","after-checkpoint","retire-file","after-retire")) fixture { root,q -> + entry(root) + assertThrows(IllegalStateException::class.java) { + LegacyLifecycleImport(q,root,{ "owner" }) { if (it==boundary) error("fixture crash") }.run(true) + } + assertEquals(if (boundary=="before-checkpoint") 0 else 1,q.pending("bookorbit","owner")) + LegacyLifecycleImport(q,root,{ "owner" }).run(true) + val job=q.window("bookorbit","owner").single() + assertTrue(job.retired) + assertEquals(emptySet(),job.acknowledged) + assertEquals(0,LegacyLifecycleImport(q,root,{ "owner" }).run(true)) + assertEquals(1,q.pending("bookorbit","owner")) + } + } + @Test fun importPreservesLegacyFifoRatherThanDirectoryEnumerationOrder() = fixture { root,q -> + val second="entry_${digest}_200_2"; val first="entry_${digest}_100_3" + entry(root,id=id,at=300); entry(root,id=first,at=100); entry(root,id=second,at=200) + LegacyLifecycleImport(q,root,{"owner"}).run(true) + assertEquals(listOf(first,second,id),q.window("bookorbit","owner").map { it.source }) + } + @Test fun acknowledgedExchangeStillImportsItsPendingRemoteApplication() = fixture { root,q -> + entry(root,ack=LifecycleQueue.PHASES.associateWith { true }) + LegacyLifecycleImport(q,root,{ "owner" }).run(true) + val job=q.window("bookorbit","owner").single() + assertFalse("pending remote work must not be skipped",job.acknowledged.contains("annotations")) + assertEquals(LifecycleQueue.PHASES.toSet()-"annotations",job.acknowledged) + assertNotNull((LuaValue.parse(job.checkpoint) as Map<*, *>)["remote_pending"]) + } + @Test fun corruptAndUnknownOwnerEntriesStayInSourceAndLiveWriterIsRejected() = fixture { root,q -> + entry(root) + val source=File(root,"bookorbit-lifecycle-outbox/${id}_g1.lua") + assertThrows(IllegalStateException::class.java) { LegacyLifecycleImport(q,root,{ "owner" }).run(false) } + assertEquals(0,LegacyLifecycleImport(q,root,{ null }).run(true)); assertTrue(source.isFile) + source.writeText("return os.execute('never run')") + assertEquals(0,LegacyLifecycleImport(q,root,{ "owner" }).run(true)); assertTrue(source.isFile) + assertEquals(0,q.pending("bookorbit","owner")) + } +} diff --git a/android/docs/INTERFACE.md b/android/docs/INTERFACE.md index 2453cf25..7e16a2bf 100644 --- a/android/docs/INTERFACE.md +++ b/android/docs/INTERFACE.md @@ -461,7 +461,7 @@ time-left fields remain absent until its evidence thresholds are met). The `book `days_start_to_finish`. Joins and SQLite aggregation run in the companion; no metadata file or statistics database is parsed by the reader UI. The `progress.syncCurrent` capability advertises the existing explicit Sync action -behind the library adapter, with no new sync writer. See +through the companion’s sole sync owner (the legacy writer is retired). See [reader progress notes](../../docs/design/booksync-home/F12-H-NOTES.md). The owned Home host also uses `lists(limit)` on the library context. Its materialized @@ -472,6 +472,37 @@ worker-checked file ledger. The plugin opens only that local file through publication emits `library`; catalog publication emits `library_source`. These reuse the acknowledged event queue. They invalidate an already visible Home, never show it. + +### 0.12 companion-owned sync (F12-Q) + +The library dispatches `sync.activate`, `sync.capture`, `sync.pull`, `sync.decide`, +`sync.answer`, `sync.override`, `sync.drain`, `sync.verify.next` and `sync.verify.result` +through the existing serial command worker. Activation requires a successful native +retirement handshake and reader process epoch. A restarted companion repeats that +handshake before retrying. Native captures carry a path, optional cached document ID, +locator/fraction, page geometry, capture time, small summary, selected automatic/Custom +mode and lifecycle moment. Direction preferences are translated privately by the +companion adapter. A post-close drain releases the open-sidecar lease by `closed_path` +only after native closure; offline closure does not initiate transport. Captures +from a no-longer-current document carry `current=false`, preserving the active lease. +The companion owns catalog/statistics/sidecar work and all server protocol. Secrets +and backend response fields never return to the plugin. + +Responses contain a bounded neutral document/token/remote/marker/pending projection. +The public cached position snapshot is at most 16 KiB; the reader rejects larger files. +`SYNC_PREVIEW` evaluates only an immutable in-memory projection with caller-supplied +native geometry, returning decision/applied/remote/token/document. It performs no SQL, +network or writes. Token-checked `sync.answer` commits consent or decline; native code +moves only the still-open initiating document. Native verification reads one row with +key/start/end and returns valid/page through a separate command. No annotation list +or backend JSON is decoded by the reader. + +Library `idle` and `networkRestored` hooks route remaining background jobs through the +neutral binding. Home paint does not trigger sync. Consent/verification use the named +budgets in `logic/budgets.lua`; commands and drains emit info-level timing spans. +Migration journal details and crash guarantees are in +[F12-Q notes](../../docs/design/booksync-home/F12-Q-NOTES.md). + ### Owned cover acquisition (0.12 catalog prerequisite) The trusted `SERVER_COMMAND` operation `covers.acquire` accepts either one opaque diff --git a/android/koreader/orbit.koplugin/ko/library.lua b/android/koreader/orbit.koplugin/ko/library.lua index a6b9f8c8..d435a95d 100644 --- a/android/koreader/orbit.koplugin/ko/library.lua +++ b/android/koreader/orbit.koplugin/ko/library.lua @@ -64,7 +64,9 @@ end function LibraryAdapter.fullRefresh() return Library.refreshCatalog("full",true) end function LibraryAdapter.syncNow(reader) return reader:onOrbitSyncAndSleep(true) end -function LibraryAdapter.syncCurrent(done) done(false,"Sync unavailable"); return false end +function LibraryAdapter.syncCurrent(done) + return ReadingSync.run("manual",function(ok,why) done(ok,why or (ok and "Synced" or "Saved · delivery pending")) end) +end -- KOReader already computes this on page/position updates, even with its footer hidden. -- No document scan, sidecar read or second progress writer on a panel paint. function LibraryAdapter.readerPosition(path) @@ -146,6 +148,7 @@ end end Library = rawget(getfenv(1),"Library") or {} +if Library.bindLifecycle then Library.bindLifecycle() end -- Explicit user command; the existing adapter/worker owns the full-refresh job. local function command(id, run) local finish = Budgets.span("library." .. id .. ".enqueue", now_s, log) @@ -302,6 +305,43 @@ function Library:sources(category, offset, limit, caps) allow_wtr=not (caps and caps.wantToRead==false),allow_device=not (caps and caps.onDevice==false)}) end +-- Position sync owns one local row and a bounded pure preview; all writes remain worker commands. +function Library.nativeReaderPosition(path) return LibraryAdapter.readerPosition(path) end +function Library.idle() if LibraryAdapter.idle then return LibraryAdapter.idle() end end +function Library.networkRestored() if LibraryAdapter.networkRestored then return LibraryAdapter.networkRestored() end end +function Library.positionCommand(op,args,done) + return command(op,function() return LibraryAdapter.command(op,args,done or function() end) end) +end +function Library.positionCached(path) + local finish=Budgets.span("library.position.cached",now_s,log) + local b=Budgets.get("screens","position-consent") + local root=require("datastorage"):getSettingsDir() .. "/orbit-cache" + local body=Store.readFile(root .. "/position/" .. require("ffi/sha2").md5(path) .. ".lua",b.bytes+1) + local value=type(body)=="string" and #body<=16384 and Cache.decode(body) or nil + finish() + return type(value)=="table" and value.path==path and value or nil +end +function Library.positionPreview(args) + local finish=Budgets.span("library.position.preview",now_s,log) + local encoded=Cache.encode(args); assert(#encoded<=Budgets.MAX_REQUEST,"Position preview exceeds budget") + local result=Jni.call(Companion.AUTHORITY,Companion.PACKAGE .. ".call.SYNC_PREVIEW",{args=encoded}) + local body=result and result.body + local value=type(body)=="string" and #body<=16384 and Cache.decode(body) or nil + finish() + return value +end + +-- Neutral lifecycle hooks shared with the independently migrating catalog/finish adapter. +function Library.backgroundCommand(op,...) + local args={...} + return command(op,function() return LibraryAdapter.backgroundCommand(op,unpack(args)) end) +end +function Library.backgroundBusy() + local finish=Budgets.span("library.background.busy",now_s,log) + local busy=LibraryAdapter.backgroundBusy and LibraryAdapter.backgroundBusy() + finish(); return busy +end + local function storagePath() local ui=liveUI and liveUI() return ui and ui.document and ui.document.file or nil diff --git a/android/koreader/orbit.koplugin/ko/main_loop.lua b/android/koreader/orbit.koplugin/ko/main_loop.lua index 9488f5d2..2e61a567 100644 --- a/android/koreader/orbit.koplugin/ko/main_loop.lua +++ b/android/koreader/orbit.koplugin/ko/main_loop.lua @@ -57,7 +57,6 @@ local function wrapTable(t,name) end end end -for _,name in ipairs({"OrbitAndroid","ReadingStatus","Store","Companion","Jni","Shared","Clicks","Channel","Wifi","Net","Sleep","Stats"}) do +for _,name in ipairs({"OrbitAndroid","ReadingStatus","Store","Companion","Jni","Shared","Clicks","Channel","Wifi","Net","Sleep","Stats","ReadingSync","Library"}) do wrapTable(plugin_env[name],name) end -Server.timeLegacy(wrapTable) diff --git a/android/koreader/orbit.koplugin/ko/menu.lua b/android/koreader/orbit.koplugin/ko/menu.lua index fa4cae9a..890fe174 100644 --- a/android/koreader/orbit.koplugin/ko/menu.lua +++ b/android/koreader/orbit.koplugin/ko/menu.lua @@ -85,7 +85,6 @@ function OrbitAndroid:statusText() end local need = Shared.setupNeededText() if need then table.insert(parts, need) end - for _i, l in ipairs(compatLines(serverPlugin(self.ui))) do table.insert(parts, l) end return _("Status: ") .. table.concat(parts, " · ") end @@ -304,8 +303,8 @@ function OrbitAndroid:menuItems() out[#out+1]=sleep out[#out+1] = action("Battery ›", function() BatteryUI.show() end) out[#out+1] = action("Sync and sleep now", function() self:onOrbitSyncAndSleep() end) - if Server.positionOn() and self.ui and self.ui.document then - out[#out+1] = action("Read from here everywhere", function() Server.readFromHere("menu") end) + if ReadingSync.on() and self.ui and self.ui.document then + out[#out+1] = action("Read from here everywhere", function() ReadingSync.readFromHere("menu") end) end return out end), diff --git a/android/koreader/orbit.koplugin/ko/module.lua b/android/koreader/orbit.koplugin/ko/module.lua index 17196e8b..6deef0cc 100644 --- a/android/koreader/orbit.koplugin/ko/module.lua +++ b/android/koreader/orbit.koplugin/ko/module.lua @@ -11,7 +11,7 @@ OrbitAndroid = WidgetContainer:extend{ function OrbitAndroid:init() state.module = self - Server.installGrouping("init") + Library.backgroundCommand("views.install","init") Clicks.install("init") keepRotationOnFileBrowser("init") if not state.start_patch_checked then @@ -22,18 +22,13 @@ function OrbitAndroid:init() if self.ui and self.ui.menu then self.ui.menu:registerToMainMenu(self) end local in_reader = self.ui ~= nil and self.ui.document ~= nil self.schedule = Schedule.new(S.reading_schedule, now_s()) - if in_reader then - -- The BookOrbit plugin's instance comes first when both sit in one plugins folder - -- (PluginLoader sorts by path); elsewhere it may come later: hook it once it exists. - if serverPlugin(self.ui) then self:hookPluginPagePush() - else UIManager:nextTick(function() self:hookPluginPagePush() end) end - end -- A Sync while reading change from the companion (Shared.refresh) restarts this counter. Shared.onSchedule = function(id) self.schedule = Schedule.new(id, now_s()) - if self.ui and self.ui.document then self:hookPluginPagePush() end + end + ReadingSync.activate() if not state.started then state.started = true log("start: KOReader started (treated as a wake)", in_reader and "in reader" or "in file browser") diff --git a/android/koreader/orbit.koplugin/ko/net.lua b/android/koreader/orbit.koplugin/ko/net.lua index 4c96d1c2..6093b057 100644 --- a/android/koreader/orbit.koplugin/ko/net.lua +++ b/android/koreader/orbit.koplugin/ko/net.lua @@ -26,18 +26,18 @@ function Net.up(p, opts, cb) -- The companion takes part when it switches Wi-Fi or holds the wake lock for sleep syncs; -- otherwise the plugin wakes Tailscale itself (docs/design/addon-mode.md §3). local res = { companion = Companion.has("wifi") or Companion.has("sleep_sync"), wifi_switch = Companion.has("wifi") } - local url = opts.need_server and serverUrl(p) or nil + -- Server reachability/authentication is decided by the companion sync command. + local url = nil log("network up: start", opts.reason, "cap", cap .. "s", "companion", res.companion and "yes" or "no", "server", url and "set" or "none") - local next_probe = 0 local ts_resent = false local function finish(ok, failed_at, detail) res.elapsed = now_s() - t0 res.failed_at = failed_at res.detail = detail Net.inflight = nil - if ok then Server.resumeCache("network up") end + if ok then Library.networkRestored() end log("network up:", ok and "ok" or ("FAILED at " .. tostring(failed_at)), opts.reason, "wifi", res.wifi_s and fmt(res.wifi_s) or "-", "vpn", res.vpn_s and fmt(res.vpn_s) or "-", "server", res.server_s and fmt(res.server_s) or "-", "total", fmt(res.elapsed), detail or "") @@ -90,34 +90,7 @@ function Net.up(p, opts, cb) res.vpn_s = el log("network: VPN up after", fmt(el)) end - if not url then return finish(true) end - if el < cap and el >= next_probe then - local remaining = cap - el - -- A HEAD can wait on DNS/connect/read for seconds. Scheduling tick does not - -- make that I/O asynchronous: run it in a child, including while reading. - Background.run("network probe", function() - local answered, code = probeServer(url, math.max(0.05, math.min(1.5, remaining))) - return answered and tostring(code) or "" - end, math.min(2, remaining), function(result) - local after = now_s() - t0 - local code = tonumber(result) - if code then - res.server_s = after - log("network: server answered", code, "after", fmt(after)) - return finish(true) - end - log("network: server not answering yet at", fmt(after)) - next_probe = after + 1 - tick() - end) - return - end - if el >= cap then - local stage = (S.wake_tailscale and not res.vpn_s) and "tailscale" or "server" - return finish(false, stage, stage == "tailscale" and ("Tailscale didn't connect in " .. cap .. " s") - or ("library didn't answer in " .. cap .. " s")) - end - UIManager:scheduleIn(0.5, tick) + return finish(true) end tick() end diff --git a/android/koreader/orbit.koplugin/ko/position_sync.lua b/android/koreader/orbit.koplugin/ko/position_sync.lua new file mode 100644 index 00000000..2b4fb9b3 --- /dev/null +++ b/android/koreader/orbit.koplugin/ko/position_sync.lua @@ -0,0 +1,218 @@ +-- SPDX-License-Identifier: AGPL-3.0-or-later +-- Only native locator/geometry captures and consent UI. Policy and durable state are companion-owned. +ReadingSync = { ready=false, busy=false, turn_at=0, generation=0 } +function ReadingSync.on() return S.sync_mode ~= "custom" end +function ReadingSync.closePrompt() + if ReadingSync.prompt then + ReadingSync.prompt.answered=true + UIManager:close(ReadingSync.prompt.widget) + ReadingSync.prompt=nil + end +end +function ReadingSync.capture(ui, moment) + ui=ui or liveUI() + if not (ui and ui.document) then return {moment=moment,online=NetworkMgr:isConnected()} end + local doc=ui.document + local fraction=Library.nativeReaderPosition(doc.file) + if fraction==nil then + local engine=doc.info and doc.info.has_pages and ui.paging or ui.rolling + if engine and engine.getLastPercent then local ok,p=pcall(engine.getLastPercent,engine); if ok then fraction=p end end + end + local engine=doc.info and doc.info.has_pages and ui.paging or ui.rolling + local ok,position=pcall(function() return engine:getLastProgress() end) + local _,page=pcall(function() return doc:getCurrentPage() end) + local summary=ui.doc_settings and ui.doc_settings:readSetting("summary") or {} + if type(summary)~="table" then summary={} end + return {automatic=ReadingSync.on(),path=doc.file,document=ui.doc_settings and ui.doc_settings:readSetting("partial_md5_checksum"),position=ok and position or nil,percentage=fraction,page=type(page)=="number" and page or nil, + summary={status=summary.status,rating=summary.rating,modified=summary.modified}, + finished=summary.status=="complete",released=(ReadingSync.forward or 0)>=10,turn_at=ReadingSync.turn_at, + stats_id=ui.statistics and ui.statistics.id_curr_book,captured_at=os.time(),moment=moment,online=NetworkMgr:isConnected()} +end +function ReadingSync.geometry(snapshot, ui, moment) + local args=ReadingSync.capture(ui,moment) + local doc=ui.document + local ok,n=pcall(doc.getPageCount,doc) + local pages=ok and tonumber(n) or 100 + local function place(record) + record=record or {} + local pos=record.position + if type(pos)=="string" and pos~="" then + if doc.info and doc.info.has_pages then local p=tonumber(pos); if p then return p,false end + else local success,p=pcall(doc.getPageFromXPointer,doc,pos); if success and type(p)=="number" then return p,false end end + end + if type(record.percentage)=="number" then return math.floor(record.percentage*pages+0.5),true end + end + args.remote_page,args.percent_only=place(snapshot.remote) + args.marker_page=place(snapshot.marker) + args.tolerance=args.percent_only and math.max(1,pages*0.02) or 1 + local toc=ui.toc + local function chapter(page) + if not (toc and page) then return nil end + local success,c=pcall(function() return toc:isChapterStart(page) and page or toc:getPreviousChapter(page) end) + return success and c or nil + end + local a,b=chapter(args.remote_page),chapter(args.marker_page) + args.same_chapter=a~=nil and a==b + args.document,args.token=snapshot.document,snapshot.token + return args +end +local function jump(ui,remote) + local doc=ui.document + if remote.position and remote.position~="" then + ui:handleEvent(Event:new(doc.info and doc.info.has_pages and "GotoPage" or "GotoXPointer", + doc.info and doc.info.has_pages and tonumber(remote.position) or remote.position)) + elseif type(remote.percentage)=="number" then + ui:handleEvent(Event:new("GotoPercent",remote.percentage*100)) + end +end +function ReadingSync.present(result,ui) + if not result or result.stale or not (ui and ui.document) or liveUI()~=ui then return end + if result.applied~="ask" then return end + local remote=result.remote or {} + if ReadingSync.prompt and ReadingSync.prompt.token==result.token then return end + ReadingSync.closePrompt() + local span=Budgets.span("position-consent.paint",now_s,log) + local entry={token=result.token,ui=ui,document=ui.document} + local function answer(yes) + if entry.answered then return end + entry.answered=true + if ReadingSync.prompt==entry then ReadingSync.prompt=nil end + ReadingSync.command("sync.answer",{document=result.document,token=result.token,yes=yes},function(reply) + if yes and reply.move and not reply.stale and liveUI()==ui and ui.document==entry.document then jump(ui,reply.remote or {}) end + end) + end + local args=ReadingSync.geometry({remote=remote},ui,"reading") + local label=type(remote.label)=="string" and remote.label or _("another reader") + entry.widget=ConfirmBox:new{text=string.format(_("Continue from %s, p. %s?"),label,tostring(args.remote_page or "?")), + ok_text=_("Yes"),cancel_text=_("No"),ok_callback=function() answer(true) end,cancel_callback=function() answer(false) end} + ReadingSync.prompt=entry + UIManager:show(entry.widget) -- gate: BookSync position sync's one-draw consent, maintainer exception + span() +end +function ReadingSync.activate(done) + if Companion.workerProblem() or not (SyncRetirement and SyncRetirement.safe) then if done then done(false) end; return false end + local ui=liveUI() + Library.positionCommand("sync.activate",{quiesced=true,epoch=tostring(Db.pid()),path=ui and ui.document and ui.document.file},function(result) + ReadingSync.ready=not result.error + if done then done(ReadingSync.ready) end + end) + return true +end +-- A companion process restart loses only the activation handshake, never its journal. +function ReadingSync.command(op,args,done) + done=done or function() end + local function send(callback) + if args.path then + local current=liveUI() + args.current=not not (current and current.document and current.document.file==args.path) + end + return Library.positionCommand(op,args,callback) + end + return send(function(result) + if result.error=="writer-active" then + ReadingSync.ready=false + return ReadingSync.activate(function(ok) + if ok then send(done) else done({error="unavailable"}) end + end) + end + done(result) + end) +end +function ReadingSync.run(moment,done,override) + done=done or function() end + local ui=liveUI() + local args=ReadingSync.capture(ui,moment) + local native=ui and ui.document + local function run() + ReadingSync.running=(ReadingSync.running or 0)+1 + ReadingSync.busy=true + local finished=false + local function finish(ok,why) if finished then return end; finished=true; ReadingSync.running=math.max(0,(ReadingSync.running or 1)-1); ReadingSync.busy=ReadingSync.running>0; done(ok,why) end + UIManager:scheduleIn(S.sleep_cap or 20,function() finish(false,"Saved · delivery still pending") end) + if not args.path then + return ReadingSync.command("sync.drain",{},function(r) finish(not r.error and (r.remaining or 0)==0,r.error) end) + end + ReadingSync.command(override and "sync.override" or "sync.capture",args,function(r) + if r.error then return finish(false,r.error) end + if not args.online then return finish(false,"Offline · saved on this device") end + if not r.snapshot then return finish(false,"Saved · awaiting remote place") end + r.snapshot.document=r.document + -- The worker sees geometry only while it still belongs to this native document. + if liveUI()~=ui or ui.document~=native or not ui.document or ui.document.file~=args.path then + return ReadingSync.command("sync.drain",{},function(d) finish(not d.error and (d.remaining or 0)==0,d.error) end) + end + local mapped=ReadingSync.geometry(r.snapshot,ui,moment) + ReadingSync.command("sync.decide",mapped,function(d) + local current=liveUI()==ui and ui.document==native and args.automatic==ReadingSync.on() + if current and moment~="close" and moment~="sleep" then ReadingSync.present(d,ui) end + if current and moment~="sleep" and moment~="close" then ReadingSync.verify(ui,r.document) end + finish(not d.error and (d.remaining or 0)==0,d.error) + end) + end) + end + if ReadingSync.ready then run() else ReadingSync.activate(function(ok) if ok then run() else done(false,"Companion sync unavailable") end end) end +end +function ReadingSync.readFromHere(why) return ReadingSync.run("manual",nil,true) end +function ReadingSync.preview(ui) + if not (SyncRetirement and SyncRetirement.safe) or not (ui and ui.document) then return end + local snapshot=Library.positionCached(ui.document.file) + if not snapshot or not snapshot.remote then return end + local args=ReadingSync.geometry(snapshot,ui,"prerender") + local result=Library.positionPreview(args) + if result and result.applied=="now" and result.remote and liveUI()==ui then + jump(ui,result.remote) + ReadingSync.command("sync.answer",{document=result.document,token=result.token,yes=true},function() end) + end +end +function ReadingSync.modeChanged() ReadingSync.closePrompt() end + +function ReadingSync.queue(moment,ui) + local args=ReadingSync.capture(ui,moment) + if not args.path then return end + args.online=false + local annotations=ui and ui.annotation and ui.annotation.annotations + local signature=table.concat({args.path,tostring(args.position),tostring(args.percentage),tostring(ReadingSync.last_page),tostring(annotations and #annotations or 0),tostring(args.summary and args.summary.status)},"|") + if moment=="suspend" and Jni.isInteractive()==true and signature==ReadingSync.last_snapshot then return end + ReadingSync.last_snapshot=signature + local function enqueue() + ReadingSync.command("sync.capture",args,function(r) if r.error=="writer-active" then ReadingSync.ready=false end end) + end + if ReadingSync.ready then enqueue() else ReadingSync.activate(function(ok) if ok then enqueue() end end) end +end + +function ReadingSync.resume(ui) + if not ReadingSync.on() or not (ui and ui.document) then return end + local snapshot=Library.positionCached(ui.document.file) + if not (snapshot and snapshot.pending and snapshot.remote) then return end + local function decide() + ReadingSync.command("sync.decide",ReadingSync.geometry(snapshot,ui,"wake-local"),function(result) ReadingSync.present(result,ui) end) + end + if ReadingSync.ready then decide() else ReadingSync.activate(function(ok) if ok then decide() end end) end +end + +-- One bounded native locator-verification capture per callback. The companion stores the +-- work and performs acknowledgments; no sidecar, server JSON or annotation scan enters Lua. +function ReadingSync.verify(ui,document,left) + left=left or 8 + if left<=0 or liveUI()~=ui or not ui.document then return end + local native=ui.document + ReadingSync.command("sync.verify.next",{document=document,path=native.file},function(result) + if liveUI()~=ui or ui.document~=native or not result.row then return end + local row=result.row + local finish=Budgets.span("position-verification.capture",now_s,log) + local budget=Budgets.get("screens","position-verification") + local bytes=#Cache.encode(row) + assert(Budgets.check(budget,{rows=1,bytes=bytes,spawns=0,network=0,roundTrips=0,snapshotBytes=bytes})) + local function page(position) + if type(position)~="string" or #position>4096 then return nil end + if native.info and native.info.has_pages then return tonumber(position) end + local success,p=pcall(native.getPageFromXPointer,native,position) + return success and type(p)=="number" and p>0 and p or nil + end + local a,b=page(row.start),page(row["end"]) + finish() + ReadingSync.command("sync.verify.result",{document=document,path=native.file,key=row.key,valid=a~=nil and b~=nil and b>=a,page=a},function() + UIManager:scheduleIn(0.2,function() if ui.document==native then ReadingSync.verify(ui,document,left-1) end end) + end) + end) +end diff --git a/android/koreader/orbit.koplugin/ko/reading_sync.lua b/android/koreader/orbit.koplugin/ko/reading_sync.lua new file mode 100644 index 00000000..6de6825a --- /dev/null +++ b/android/koreader/orbit.koplugin/ko/reading_sync.lua @@ -0,0 +1,138 @@ +-- 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"). + +-- Sync while reading +--------------------------------------------------------------------------------------------- + +function OrbitAndroid:chapterKey(page) + local toc = self.ui and self.ui.toc + if not toc or type(page) ~= "number" then return nil end + local ok, key = pcall(function() + if toc:isChapterStart(page) then return page end + return toc:getPreviousChapter(page) + end) + return ok and key or nil +end + +function OrbitAndroid:onCloseDocument() + if not (self.ui and self.ui.document) then return end + self.closed_file=self.ui.document.file + self.closed_content=contentOfUI(self.ui) + self.closed_capture=true + ReadingSync.queue("close",self.ui) + ReadingSync.closePrompt() + local file=self.closed_file + UIManager:nextTick(function() + ReadingSync.command("sync.drain",{closed_path=file,online=NetworkMgr:isConnected()},function() Library.idle() end) + end) +end + +function OrbitAndroid:onCloseWidget() + if self.ui and (self.ui.document or self.closed_file) then + if not self.closed_capture then ReadingSync.queue("close",self.ui) end + ReadingSync.closePrompt() + Stats.send("close", self.closed_content or contentOfUI(self.ui), false) + end + -- A patch update waiting for the book: once nothing is open (another book may be opening). + if self.ui and (self.ui.document or self.closed_file) and state.restart_waiting then + UIManager:scheduleIn(1.5, function() OrbitAndroid.maybeRestart(self, "check") end) + end + -- The book closed: what waited for the reader shows now (another book may be opening). + if self.ui and (self.ui.document or self.closed_file) then + UIManager:scheduleIn(1.5, function() + Gate.drain("book closed") + Library.idle() + end) + end + -- A close (Back to file browser, Exit) runs this; a kill or suspend doesn't. A close Home + -- started keeps the book as the current one (home_book); the user's own close clears it. + if self.ui and (self.ui.document or self.closed_file) then + local file = self.closed_file or self.ui.document.file + if state.closing_for_home and state.closing_for_home == file then + S.home_book = file + log("home: book closed by Home; it stays the current book") + else + S.home_book = nil + end + state.closing_for_home = nil + S.open_book_at_exit = nil + saveSettings() + pcall(function() G_reader_settings:flush() end) + end + if self.reading_task then + UIManager:unschedule(self.reading_task) + self.reading_task = nil + end + if self.ui and (self.ui.document or self.closed_file) and self.book_tracked then + self.book_tracked = false + local st = Wifi.state() + local restore = WifiPlan.bookClosed(st) + log("wifi: book closed | mode", st.mode, restore == "on" and "| Wi-Fi was on before the book: turning it back on" or "") + if restore == "on" and Companion.has("wifi") then + Companion.netUp("book_closed", { owner = "auto" }) + end + end +end + +function OrbitAndroid:onReaderReady() + -- "Open book at exit": survives a kill (flushed now), cleared when the book is closed. + -- Another book opening replaces Home's current book. + local file = self.ui and self.ui.document and self.ui.document.file + if file and (S.open_book_at_exit ~= file or S.home_book) then + S.open_book_at_exit = file + S.home_book = nil + saveSettings() + pcall(function() G_reader_settings:flush() end) + end + self.schedule = Schedule.new(S.reading_schedule, now_s()) + ReadingSync.forward=0 + ReadingSync.turn_at=0; ReadingSync.last_page=nil + ReadingSync.preview(self.ui) + Stats.send("open", contentOfUI(self.ui), true) + self:bookOpenFlow() +end + +function OrbitAndroid:bookOpenFlow() + local st=Wifi.state() + WifiPlan.bookOpened(st,Wifi.radioOn()) + self.book_tracked=true + Wifi.acquire("open") + Net.up(nil,{reason="open",cap=20},function() + ReadingSync.run("open",function() Wifi.release("open") end) + end) +end +function OrbitAndroid:onNetworkConnected() + Wifi.kick() + Library.networkRestored() + ReadingSync.run(inBook() and "wake" or "close") +end +function OrbitAndroid:onPageUpdate(page) + if self.ui and (self.ui.document or self.closed_file) then Stats.page(stats_acc) end + ReadingSync.turn_at=os.time() + if ReadingSync.last_page and page>ReadingSync.last_page then ReadingSync.forward=(ReadingSync.forward or 0)+1 end + ReadingSync.last_page=page + -- The power settings choose cadence; the position rule chooses safe pull/push behavior. + if S.reading_schedule == "off" or not (self.ui and self.ui.document) then return end + local t = now_s() + Schedule.onPage(self.schedule, self:chapterKey(page), t) + if Schedule.isDue(self.schedule, t) then + -- Run once the reader settles on a page, never in the middle of turning. + if self.reading_task then UIManager:unschedule(self.reading_task) end + self.reading_task = function() + self.reading_task = nil + self:readingSync() + end + UIManager:scheduleIn(3, self.reading_task) + end +end + +function OrbitAndroid:readingSync() + if not inBook() then return end + Schedule.markSynced(self.schedule,now_s()) + Wifi.acquire("reading") + Net.up(nil,{reason="reading",cap=20},function() + ReadingSync.run("pause",function() Wifi.release("reading") end) + end) +end diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit.lua index 9c0a60e9..7c2dd7af 100644 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit.lua +++ b/android/koreader/orbit.koplugin/ko/server/bookorbit.lua @@ -72,26 +72,6 @@ function inBook() return ui ~= nil and ui.document ~= nil end -function serverUrl(p) - local settings = p and p.settings or G_reader_settings:readSetting("bookorbit") - return settings and settings.server_url or nil -end - --- Any HTTP status from the base URL counts: it proves the route and the server, with no login. --- Blocking primitive: only called by Net.up's background child. Socket timeouts --- do not bound DNS resolution; Background.run also caps the child's lifetime. -function probeServer(url, timeout) - local http = require("socket.http") - local socket = require("socket") - local socketutil = require("socketutil") - local ltn12 = require("ltn12") - timeout = math.min(1.5, timeout) - socketutil:set_timeout(timeout, timeout) - local code = socket.skip(1, http.request{ url = url, method = "HEAD", sink = ltn12.sink.null() }) - socketutil:reset_timeout() - return type(code) == "number", code -end - --------------------------------------------------------------------------------------------- -- One compatibility entry point. Only main.lua loads this implementation. @@ -108,40 +88,23 @@ end function Server.signedIn(p) return p ~= nil and p:isLoggedIn() end function Server.openLogin(p) return p:promptLogin() end -function Server.drain(p, ...) return p:requestLifecycleOutboxDrain(...) end -function Server.pull(p, reason) return p:requestProgressPull(false, false, reason) end -function Server.snapshot(p) return pcall(p._onSuspend, p) end -function Server.syncBusy(p) - local c = p:getSyncCoordinator() - if c:isBusy() or c:queuedCount() > 0 then return true end - return outboxPending(p:getLifecycleOutbox():diagnostics()) > 0 -end -function Server.testReady(p) - return hasHandler(p, Server.events.sync) and Compat.callable(p.startSweep) and Compat.callable(p.errorLabel) -end -function Server.testError(p, err) return p:errorLabel(err) end -function Server.testSync(p, reader, done) - if reader then pluginEvent(liveUI(), p, Server.events.sync, {quiet=true, on_done=done}) - else p:startSweep({quiet=true, on_progress=function() end, on_done=done}) end -end - -- Legacy service bridge. Only reviewed lifecycle/sheet modules use this facade. function Server.cacheClient() return OC.client() end +function Server.readerIdle() + if Copies and Copies.tick then pcall(Copies.tick,"book closed") end + if EOB and EOB.drain and not reading() then + local p=serverPlugin() + if p then EOB.drain(p,false,function() end) end + 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 Grouping.install(...) end -function Server.positionOn() return OSM and OSM.on() end -function Server.positionWakeMinimum() return OSM.WAKE_MIN_S end -function Server.pullThenDrain(...) return OSM.pullThenDrain(...) end -function Server.readFromHere(...) return OSM.readFromHere(...) end -function Server.waitOutbox(...) return Sync.waitOutbox(...) end -function Server.clearPullDebounce(...) return Sync.clearPullDebounce(...) 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.positionModeChanged(...) if OSM and OSM.modeChanged then return OSM.modeChanged(...) end end function Server.reportRecommended(...) if Rec then return Rec.report(...) end end function Server.applyRecommended(...) if Rec then return Rec.applyChoices(...) end end function Server.capabilitiesLost(...) if Rec then return Rec.capsLost(...) end end @@ -159,14 +122,16 @@ 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"}) - quiet(OSM,{"pause","pullThenDrain"}) end function Server.timeLegacy(wrap) - for _,name in ipairs({"EOB","OSM","OC","LF","Sync","Mirror","Copies"}) do + for _,name in ipairs({"EOB","OC","LF","Mirror","Copies"}) do wrap(getfenv(1)[name],name) end end +-- Temporary non-transport compatibility for the finish adapter while its parallel cutover lands. +Sync = { waitOutbox=function(_,_,done) return ReadingSync.run("close",done) end } + -- Covers have one owner even with legacy catalog caching disabled. Never call the upstream -- downloader: these low-level methods can be reached inside an upstream subprocess. function Server.installCovers(Api,Catalog) @@ -419,43 +384,8 @@ function Server.installCatalogRuntime() Server.catalogChanged({owner=LibraryAdapter.owner()}) if Copies and Copies.tick then pcall(Copies.tick,"catalog refresh") end end - LibraryAdapter.syncCurrent=Server.syncCurrent Library.watchEvents() end -function Server.syncCurrent(done) - local ui = liveUI() - local p = serverPlugin(ui) - if not (p and ui and ui.document and hasHandler(p, "BookOrbitSyncBook")) then - done(false, "Sync unavailable") - return false - end - local document = ui.document - Wifi.acquire("reader-panel") - Net.up(p, {reason="reader-panel", cap=20, need_server=true}, function(ok) - if not ok then - Wifi.release("reader-panel") - done(false, "Offline · will sync when connected") - return - end - if liveUI() ~= ui or ui.document ~= document then - Wifi.release("reader-panel") - done(false, "Book closed · your place stays saved") - return - end - local completed = false - local function finish(err) - if completed then return end - completed = true - Wifi.release("reader-panel") - done(err == nil, err and "Sync failed · your place stays saved" or "Synced") - end - pluginEvent(ui, p, "BookOrbitSyncBook", {quiet=true, on_done=finish}) - UIManager:scheduleIn(30, function() finish("timeout") end) - end) - return true -end - - -- Compatibility shapes are assembled from BookSync display records, never HTTP/JSON. The -- remaining copies/EOB slice still uses native identifiers; catalog queries are worker-owned. function Server.installCatalogApi(Api,Catalog) @@ -611,7 +541,19 @@ function Server.installCatalogApi(Api,Catalog) return true end -Library={connectorReady=function() Server.installCatalogRuntime(); OC.install() 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()) diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit/lifecycle.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/lifecycle.lua deleted file mode 100644 index c8813359..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/lifecycle.lua +++ /dev/null @@ -1,65 +0,0 @@ --- SPDX-License-Identifier: AGPL-3.0-or-later --- Copyright (c) 2026 Fledgewing. Part of BookSync. --- Legacy upstream lifecycle/settings bindings, loaded after ko/module.lua. - --- "Sync while reading" replaces the plugin's every-few-pages push while it is on. --- The plugin's every-few-pages push is its user setting "Push while reading" --- (settings.pages_before_update, bookorbit_settings_page.lua:259-260; read by _onPageUpdate, --- main.lua:1322-1324; 0 = off). While our Sync while reading is on we set it to 0 and keep the --- reader's value; when it goes off we put that value back (unless they changed it meanwhile). -function OrbitAndroid:hookPluginPagePush() - local p = serverPlugin(self.ui) - if not p or type(p.settings) ~= "table" then return end - local cur = p.settings.pages_before_update - -- OrbiSmart pushes at a pause instead (docs/design/position-sync.md §3.3). - if S.reading_schedule ~= "off" or (OSM and OSM.on()) then - if S.saved_pages_before_update == nil and (cur or 0) > 0 then - S.saved_pages_before_update = cur - p.settings.pages_before_update = 0 - saveSettings() - log("page push: plugin's Push while reading", cur, "-> off while Sync while reading is on") - end - elseif S.saved_pages_before_update ~= nil then - if (cur or 0) == 0 then - p.settings.pages_before_update = S.saved_pages_before_update - log("page push: plugin's Push while reading restored to", S.saved_pages_before_update) - end - S.saved_pages_before_update = nil - saveSettings() - end -end - ---------------------------------------------------------------------------------------------- - --- BookOrbit snapshots the open book into its outbox on every Suspend (main.lua:1340-1351), and --- Android sends Suspend on every app switch: each press of the Home key bounces through the --- companion's launcher and back (logged "home press: START_KOREADER"), so every press synced the --- book again ("book sync done reason=recovery", the label every outbox drain carries, --- bookorbit_book_sync.lua:169). With the screen on, a snapshot of a book that hasn't moved since --- its last one is skipped; a real sleep, a close and Sync and sleep always snapshot. -function snapshotKey(p, ui) - local okd, digest = pcall(p.getDocumentDigest, p) - if not okd or not digest then return nil end - local okp, pct = pcall(p.getLastPercent, p) - local ann = ui and ui.annotation and ui.annotation.annotations - local okst, status = pcall(function() return ui.doc_settings:readSetting("summary").status end) - return table.concat({ tostring(digest), tostring(okp and pct or "?"), tostring(p.last_page or "?"), - tostring(type(ann) == "table" and #ann or "?"), tostring(okst and status or "?") }, "|") -end - -function OrbitAndroid:hookSuspendSnapshot() - local p = serverPlugin(self.ui) - if not p or type(p._onSuspend) ~= "function" or rawget(p, "_orbit_snapshot_hooked") then return end - local orig = p._onSuspend - p._orbit_snapshot_hooked = true - p._onSuspend = function(plugin, ...) - local key = snapshotKey(plugin, self.ui) - if not state.force_snapshot and key and key == state.last_snapshot_key and Jni.isInteractive() == true then - log("suspend: app switch and the book hasn't moved since its last snapshot; library's snapshot skipped") - return - end - state.last_snapshot_key = key - return orig(plugin, ...) - end - if p.onSuspend == orig then p.onSuspend = p._onSuspend end -end diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit/localfirst.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/local_view.lua similarity index 95% rename from android/koreader/orbit.koplugin/ko/server/bookorbit/localfirst.lua rename to android/koreader/orbit.koplugin/ko/server/bookorbit/local_view.lua index 31519cce..9095b5c7 100644 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/localfirst.lua +++ b/android/koreader/orbit.koplugin/ko/server/bookorbit/local_view.lua @@ -3,6 +3,8 @@ -- 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. @@ -102,38 +104,6 @@ function LocalState.noteSent(digest) if e then e.finish_sent = true; LocalState.save() end end --- The outbox decides "pending": an entry still waiting for a book keeps it; once gone (acknowledged) --- pending clears, unless a finish waits in our own queue. Blocked or retrying -> not synced. -function LocalState.fromOutbox(p) - local okm, list, outbox = pcall(function() - local o = p:getLifecycleOutbox() - return o:listMetadata(), o - end) - if not okm or type(list) ~= "table" then return end - local waiting = {} - local now = os.time() - for _, e in ipairs(list) do - if type(e) == "table" and e.digest then - local okb, blocked = pcall(outbox.isBlocked, outbox, e) - waiting[e.digest] = { blocked = okb and blocked or false, - retrying = e.next_attempt_at ~= nil and e.next_attempt_at > now } - end - end - local changed = false - for digest, e in pairs(LocalState.load().books) do - local w = waiting[digest] - local finish_waits = EOB and EOB.jobs and EOB.jobs[digest] ~= nil - local pending = w ~= nil or finish_waits or false - local blocked = w and w.blocked or false - local retrying = w and w.retrying or false - if e.pending ~= pending or (e.blocked or false) ~= blocked or (e.retrying or false) ~= retrying then - e.pending, e.blocked, e.retrying = pending, blocked, retrying - changed = true - end - end - if changed then LocalState.bump(); 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) @@ -713,7 +683,6 @@ do pcall(Gate.installToast) local p = serverPlugin(self.ui) if p then - pcall(LocalState.fromOutbox, p) pcall(EOB.installPluginHooks, p) end return r @@ -721,7 +690,6 @@ do local base_resume = OrbitAndroid.onResume function OrbitAndroid:onResume(...) local p = serverPlugin(self.ui) - if p then pcall(LocalState.fromOutbox, p) end 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)) diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua deleted file mode 100644 index 754cd35d..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua +++ /dev/null @@ -1,645 +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"). - --- OrbiSmart sync on Android (docs/design/position-sync.md §3.3): the "Sync: OrbiSmart" setting's --- runtime. The decision is logic/orbismart.lua (the shared table); this file feeds it and acts. --- * Every pull and push of the BookOrbit plugin goes through its API client --- (bookorbit_api.lua :578 getProgress, :582 updateProgress; the live push --- bookorbit_progress_sync.lua :325, the outbox's bookorbit_book_sync.lua :858). Both are --- wrapped: a pull records the server's place and runs the decision for the open book; a push --- behind the last known server place is held (the behind-hold) and answered as done, so the --- outbox entry completes without sending it. --- * The plugin's own "further ahead" / "further behind" are Don't sync under OrbiSmart (kept --- and given back under Custom): its pulls never move the reader. Orbit moves it: silently --- before the page renders (ReaderReady, with a place already known), otherwise by asking --- ("Continue from Boox, p. 214? Yes / No"), at open, wake, a pause or a pull while reading. --- * A pause (120 s without a turn, moved more than a page) pulls and pushes. --- * "Read from here everywhere" (Orbit menu, This book sheet) queues an override for the book, --- sent now when the network comes up, else first at the next sync. --- Per book (S.orbismart[digest]): m (the marker: server time and place of the last sync), server --- (the last server place pulled), declined_at / declined_reset (the reader's No), override, --- pending (a move found at sleep, asked at wake), pushed (the place of the last push). ---------------------------------------------------------------------------------------------- - -OSM = { PAUSE_S = 120, WAKE_MIN_S = 300, MAX_BOOKS = 300, MOMENT_S = 40, logged = {} } - --- The stock plugin's strategy for "Don't sync" (main.lua:56-60, Plan.STRATEGY). -local DONT = Plan.STRATEGY.DISABLE --- BookOrbit's reset is served as the start of the book by this device id (koreader.service.ts:44-45). -local RESET_DEVICE_ID = "bookorbit-web" - -function OSM.on() return S.sync_mode ~= "custom" end - -local function once(key, ...) - if OSM.logged[key] then return end - OSM.logged[key] = true - log(...) -end - --- The first run of a build with this setting: OrbiSmart, unless the reader changed a sync --- setting it would override (docs/design/position-sync.md §6, the recommended-settings rule). --- S.sync_mode already holds the schema's default (ko/settings.lua); a value chosen on either side --- has a real time in S.settings_at (more than the 1 ms seed) and is left alone. -function OSM.migrate() - if S.orbismart_migrated then return end - S.orbismart_migrated = true - local chosen = (tonumber(S.settings_at and S.settings_at.sync_mode) or 0) > 1 - local bo = G_reader_settings:readSetting("bookorbit") - bo = type(bo) == "table" and bo or {} - local custom = (S.reading_schedule or "off") ~= "off" or S.sync_on_wake == false or S.sync_on_sleep == false - or bo.sync_forward == DONT or (bo.sync_backward ~= nil and bo.sync_backward ~= DONT) - if custom and not chosen then - S.sync_mode = "custom" - S.settings_at.sync_mode = os.time() * 1000 - log("orbismart: this reader's sync settings were changed by hand; Sync stays Custom") - end - saveSettings() -end - ----------------------------------------------------------------- per-book record - -function OSM.rec(digest, create) - if not digest then return nil end - if type(S.orbismart) ~= "table" then S.orbismart = {} end - local r = S.orbismart[digest] - if not r and create then - r = {} - S.orbismart[digest] = r - OSM.trim() - end - if r then r.seen = os.time() end - return r -end - -function OSM.trim() - local list = {} - for k, v in pairs(S.orbismart) do table.insert(list, { k = k, seen = type(v) == "table" and v.seen or 0 }) end - if #list <= OSM.MAX_BOOKS then return end - table.sort(list, function(a, b) return a.seen < b.seen end) - for i = 1, #list - OSM.MAX_BOOKS do S.orbismart[list[i].k] = nil end -end - ----------------------------------------------------------------- places (local pages) - -local function openDigest(p) - local okd, d = pcall(p.getDocumentDigest, p) - return okd and d or nil -end - -function OSM.pages(ui) - local doc = ui and ui.document - if not doc then return nil end - local okn, n = pcall(function() return doc:getPageCount() end) - return okn and type(n) == "number" and n > 0 and n or nil -end - --- A place in this layout's pages: the exact position when there is one (an xpointer, or a page --- number for paged formats), else the percentage. -> page, percent_only. -function OSM.place(ui, pct, progress) - local doc = ui and ui.document - if doc and type(progress) == "string" and progress ~= "" then - if doc.info and doc.info.has_pages then - local n = tonumber(progress) - if n then return n, false end - else - local okp, pg = pcall(function() return doc:getPageFromXPointer(progress) end) - if okp and type(pg) == "number" then return pg, false end - end - end - local n = OSM.pages(ui) - if type(pct) == "number" and n then return math.floor(pct * n + 0.5), true end - return nil, true -end - -function OSM.localPlace(p, ui) - local doc = ui and ui.document - local okc, pg = pcall(function() return doc:getCurrentPage() end) - if okc and type(pg) == "number" then return pg end - if type(OSM.page) == "number" then return OSM.page end - local okp, pct = pcall(p.getLastPercent, p) - local n = OSM.pages(ui) - if okp and type(pct) == "number" and n then return math.floor(pct * n + 0.5) end - return nil -end - -local function chapterOf(ui, page) - local toc = ui and ui.toc - if not toc or type(page) ~= "number" then return nil end - local okk, key = pcall(function() - if toc:isChapterStart(page) then return page end - return toc:getPreviousChapter(page) - end) - return okk and key or nil -end - -local function finished(ui) - local okst, status = pcall(function() return ui.doc_settings:readSetting("summary").status end) - return okst and status == "complete" -end - -local function released(digest) - local s = EOB and EOB.session and EOB.session[digest] - return s ~= nil and (s.released == true or (s.forward or 0) >= Finish.HOLD_RELEASE_PAGES) -end - --- The decision's input (logic/orbismart.lua) for the open book against server place R. -function OSM.input(p, ui, digest, R, rec) - local L = OSM.localPlace(p, ui) - if not L then return nil end - local i = { ["local"] = L, turn_at = p.last_page_turn_timestamp or 0, finished = finished(ui), - released = released(digest), override = rec.override } - local pages = OSM.pages(ui) or 100 - if R then - local rp, pct_only = OSM.place(ui, R.pct, R.progress) - i.server, i.server_at = rp, tonumber(R.at) or 0 - i.percent_only = pct_only and rp ~= nil - if i.percent_only then i.tolerance = math.max(1, 0.02 * pages) end - i.reset = R.device_id == RESET_DEVICE_ID and (R.pct or 0) == 0 - i.declined_at = (i.reset and rec.declined_reset) and i.server_at or rec.declined_at - end - if rec.m then - local mp = OSM.place(ui, rec.m.pct, rec.m.progress) - if mp then i.marker = { at = tonumber(rec.m.at) or 0, place = mp } end - end - -- BookOrbit's web reader re-dates the place it opens at: the start of a page or a chapter in - -- the chapter last synced, at or before it (BookOrbitSmartSync::onlyRedated, design §5). - if R and R.device == "web" and not i.reset and i.marker and i.server then - local chapter = chapterOf(ui, i.server) - i.redated = chapter ~= nil and chapter == chapterOf(ui, i.marker.place) and i.server - i.marker.place <= 1 - end - return i -end - -local function remoteOf(body) - return { at = body.timestamp, pct = body.percentage, progress = body.progress, device = body.device, - device_name = body.device_name, device_id = body.device_id } -end - ----------------------------------------------------------------- the moment - --- What the next decision is for: set by the flows (open, wake, pause, sleep) for their pull; --- otherwise a pull while a book is open is "reading". -function OSM.setMoment(m) OSM.moment, OSM.moment_until = m, now_s() + OSM.MOMENT_S end -function OSM.currentMoment() - if OSM.moment and now_s() <= (OSM.moment_until or 0) then return OSM.moment end - return "reading" -end - ----------------------------------------------------------------- decide and act - -function OSM.mark(rec, R) rec.m = { at = R.at, pct = R.pct, progress = R.progress } end - --- Decide for the open book against R (nil: the last server place known) at moment. -function OSM.decide(moment, R) - if not OSM.on() then return nil end - local ui = liveUI and liveUI() or nil - local p = serverPlugin(ui) - if not p or not ui or not ui.document then return nil end - local digest = openDigest(p) - local rec = OSM.rec(digest, true) - if not rec then return nil end - R = R or rec.server - local i = OSM.input(p, ui, digest, R, rec) - if not i then return nil end - local out = OrbiSmart.decide(i) - local applied = OrbiSmart.apply(out.decision, moment) - log(OrbiSmart.line(i, out, moment)) - if out.dropped then - rec.override = nil - log("orbismart: override dropped (newer reading elsewhere)") - end - local d = out.decision - -- A released reread may replace the completed read's place once, even when that read - -- finished short of 100%. A successful push consumes this exemption. - if out.rule == "rule7" and d == "push" then rec.reread_at = i.server_at end - if d == "same" and R then - OSM.mark(rec, R) - rec.pending = nil - elseif d == "take" or d == "follow" then - if applied == "now" then OSM.jump(p, digest, R, rec, i) - elseif applied == "ask" then OSM.ask(p, ui, digest, R, i, d) - elseif applied == "wake" then rec.pending = true end - elseif d == "push" or d == "override" then - -- Before render nothing is sent (the open flow follows); at sleep the plugin's snapshot - -- carries the place, held or not by the behind-hold. - if moment ~= "prerender" and moment ~= "sleep" and moment ~= "close" then OSM.push(p, d) end - end - saveSettings() - return out, applied -end - -function OSM.jump(p, digest, R, rec, i) - rec.pending = nil - OSM.mark(rec, R) - pcall(p.noteProgressCompared, p, digest) - local okj, err = pcall(p.syncToProgress, p, R.progress, R.pct) - log("orbismart: moved", tostring(i["local"]) .. "->" .. tostring(i.server), okj and "" or ("FAILED: " .. tostring(err))) -end - -function OSM.push(p, kind) - if not NetworkMgr:isConnected() then return end - p.push_timestamp = 0 -- the plugin's 25 s debounce (bookorbit_progress_sync.lua:26) - p:requestProgressPush(false, false, kind == "override" and "orbismart_override" or "orbismart") -end - -local function deviceLabel(R) - local okn, Names = pcall(require, "bookorbit_device_names") - if okn and type(Names) == "table" and type(Names.label) == "function" then - local okl, l = pcall(Names.label, R.device, R.device_name) - if okl and l then return l end - end - return R.device_name or R.device or _("another reader") -end - --- Closes the open popup without answering it (a newer place, or the book closed). -function OSM.closePopup() - local cur = OSM.popup - if not cur then return end - cur.answered = true - OSM.popup = nil - pcall(UIManager.close, UIManager, cur.widget) -end - --- The Yes / No popup (ruling 1): one draw, no animation; one at a time, a newer place replaces it. -function OSM.ask(p, ui, digest, R, i, decision) - local cur = OSM.popup - if cur and cur.digest == digest and cur.at == R.at then return end - OSM.closePopup() - local t0 = now_s() - local entry = { digest = digest, at = R.at } - local function answer(yes) - if entry.answered then return end - entry.answered = true - if OSM.popup == entry then OSM.popup = nil end - local rec = OSM.rec(digest, true) - log(string.format("orbismart: popup %s->%s %s after %d s", tostring(i["local"]), tostring(i.server), - yes and "yes" or "no", math.floor(now_s() - t0))) - if yes then - local live = serverPlugin(liveUI and liveUI() or ui) - if live and openDigest(live) == digest then OSM.jump(live, digest, R, rec, i) end - else - rec.pending = nil - if i.reset then rec.declined_reset = true else rec.declined_at = R.at end - end - saveSettings() - end - entry.widget = ConfirmBox:new{ - text = OrbiSmart.question(deviceLabel(R), i.server, decision), - ok_text = _("Yes"), - cancel_text = _("No"), - ok_callback = function() answer(true) end, - -- Back or a tap outside is No too (ConfirmBox:onClose calls cancel_callback, confirmbox.lua:242-244). - cancel_callback = function() answer(false) end, - } - OSM.popup = entry - UIManager:show(entry.widget) -- gate: OrbiSmart's Yes / No popup, shown while reading by the user's ruling (docs/design/position-sync.md ruling 1) -end - ----------------------------------------------------------------- the plugin's API client - --- A pull of any book: remember the server's place; for the open book, decide. -function OSM.onPulled(digest, body) - if type(body) ~= "table" or body.percentage == nil then return end - local rec = OSM.rec(digest, true) - rec.server = remoteOf(body) - -- A standing reset is re-dated on each GET (pinned koreader.service.ts:579-589), so No - -- covers that standing place until normal progress returns, not every future reset. - if body.device_id ~= RESET_DEVICE_ID or body.percentage ~= 0 then rec.declined_reset = nil end - saveSettings() - local ui = liveUI and liveUI() or nil - local p = serverPlugin(ui) - if not p or not ui or not ui.document or openDigest(p) ~= digest then return end - -- The This book sheet shows BookOrbit's place itself, with its own Jump / Stay. - if p.book_sheet then return end - local moment = OSM.currentMoment() - local remote = rec.server - UIManager:nextTick(function() - local current = liveUI and liveUI() or nil - local live = serverPlugin(current) - if OSM.on() and current == ui and live == p and openDigest(live) == digest and rec.server == remote then - OSM.decide(moment, remote) - end - end) -end - --- The behind-hold: a push behind the last server place this reader knows waits, except an --- override or a released reread. -> true when held. -function OSM.holdPush(digest, pct, progress) - local rec = OSM.rec(digest) - if not rec or not rec.server or type(pct) ~= "number" then return false end - if rec.override or (rec.reread_at ~= nil and rec.reread_at == (tonumber(rec.server.at) or 0)) then return false end - local ui = liveUI and liveUI() or nil - local p = serverPlugin(ui) - local L, R, tol - if ui and ui.document and p and openDigest(p) == digest then - local pct_only - L = OSM.place(ui, pct, progress) - R, pct_only = OSM.place(ui, rec.server.pct, rec.server.progress) - tol = pct_only and math.max(1, 0.02 * (OSM.pages(ui) or 100)) or 1 - else - -- A closed book: percent, a point either way. - L, R, tol = pct * 100, (rec.server.pct or 0) * 100, 1 - end - if L == nil or R == nil or OrbiSmart.mayPush(L, R, tol, false) then return false end - log(string.format("orbismart: push held L=%s R=%s (behind the server)", tostring(L), tostring(R))) - return true -end - -function OSM.onPushed(digest, pct, progress, ts) - local rec = OSM.rec(digest, true) - rec.m = { at = ts, pct = pct, progress = progress } - rec.server = rec.server or {} - rec.server.at, rec.server.pct, rec.server.progress = ts, pct, progress - rec.server.device_id = nil - rec.pushed, rec.reread_at = pct, nil - if rec.override then - rec.override = nil - log("orbismart: override sent") - end - saveSettings() -end - -function OSM.installApi() - if OSM.api_hooked then return true end - local oka, Api = pcall(require, "bookorbit_api") - if not oka or type(Api) ~= "table" then return false end - local missing = Compat.missingOn(Api, Compat.ORBISMART_API) - if #missing > 0 then - once("api", "compat: BookSync's behind-hold and decisions off (plugin changed): missing api." .. table.concat(missing, ", api.")) - return false - end - OSM.api_hooked = true - wrap(Api, "getProgress", function(stock) return function(self, digest, ...) - local body, err = stock(self, digest, ...) - if OSM.on() and type(body) == "table" then - local okp, e = pcall(OSM.onPulled, digest, body) - if not okp then log("orbismart: pull follow-up failed:", tostring(e)) end - end - return body, err - end end, "orbismart") - wrap(Api, "updateProgress", function(stock) return function(self, digest, pct, progress, ts, ...) - if OSM.on() then - -- An outbox snapshot may predate the override, or reading may have moved on while - -- offline. The explicit action sends the place chosen then, before any snapshot. - local rec = OSM.rec(digest) - if rec and rec.override and type(rec.override.pct) == "number" then - pct, progress, ts = rec.override.pct, rec.override.progress, os.time() - end - local okh, held = pcall(OSM.holdPush, digest, pct, progress) - if not okh then return nil, "BookSync could not check the server place" end - -- Answered as sent: the outbox entry completes, the server keeps its further place. - if okh and held then return { document = digest, timestamp = ts, orbit_held = true } end - end - local body, err = stock(self, digest, pct, progress, ts, ...) - if OSM.on() and body then pcall(OSM.onPushed, digest, pct, progress, ts) end - return body, err - end end, "orbismart") - return true -end - ----------------------------------------------------------------- the plugin's settings - --- Under OrbiSmart the plugin never moves the reader by itself: "further ahead" and "further --- behind" are Don't sync (its settings page, bookorbit_settings_page.lua sync strategies). Its --- own values are kept and given back under Custom, unless the reader changed them meanwhile. -function OSM.preset(p) - if not p or type(p.settings) ~= "table" then return end - local st = p.settings - if OSM.on() then - if st.sync_forward ~= DONT or st.sync_backward ~= DONT or st.auto_sync ~= true then - if S.osm_saved_plugin == nil then - S.osm_saved_plugin = { sync_forward = st.sync_forward, sync_backward = st.sync_backward, auto_sync = st.auto_sync } - end - st.sync_forward, st.sync_backward = DONT, DONT - if st.auto_sync ~= true then pluginEvent(liveUI(), p, "BookOrbitToggleAutoSync", true, true, true) end - saveSettings() - log("orbismart: the plugin's further ahead / behind -> Don't sync (Orbit decides)") - end - elseif S.osm_saved_plugin then - if st.sync_forward == DONT and st.sync_backward == DONT then - st.sync_forward = S.osm_saved_plugin.sync_forward - st.sync_backward = S.osm_saved_plugin.sync_backward - if st.auto_sync == true and S.osm_saved_plugin.auto_sync ~= true then - pluginEvent(liveUI(), p, "BookOrbitToggleAutoSync", false, true, true) - end - log("orbismart: Custom; the plugin's further ahead / behind given back") - end - S.osm_saved_plugin = nil - saveSettings() - end -end - --- The plugin's own value of a setting OrbiSmart presets, kept for Custom: { value } or nil when --- OrbiSmart holds none (Recommended settings read and write this one, ko/server/bookorbit/recommended.lua). -function OSM.savedPluginSetting(key) - if not OSM.on() or type(S.osm_saved_plugin) ~= "table" then return nil end - if key ~= "sync_forward" and key ~= "sync_backward" and key ~= "auto_sync" then return nil end - return { value = S.osm_saved_plugin[key] } -end - -function OSM.setSavedPluginSetting(key, value) - if not OSM.savedPluginSetting(key) then return false end - S.osm_saved_plugin[key] = value - saveSettings() - return true -end - -function OSM.modeChanged(why) - if not OSM.on() then OSM.closePopup() end - log("orbismart: Sync =", OSM.on() and "OrbiSmart" or "Custom", "(" .. tostring(why) .. ")") - local ui = liveUI and liveUI() or nil - local p = serverPlugin(ui) - if p then OSM.preset(p) end - local m = state.module - if m and m.ui and m.ui.document then pcall(m.hookPluginPagePush, m) end -end - ----------------------------------------------------------------- flows - --- ReaderReady runs before the first paint (ReaderUI:init ends with it; showReader paints after), --- so a further place already known opens straight there (ruling 1: silent before render). -function OSM.onReaderReady(m) - local p = serverPlugin(m.ui) - if not p then return end - OSM.installApi() - OSM.installSheet() - OSM.preset(p) - if not OSM.on() then return end - OSM.page = nil - local digest = openDigest(p) - local rec = OSM.rec(digest) - local R = rec and rec.server - local live = p.last_remote_progress - if type(live) == "table" and live.digest == digest and live.percentage ~= nil and (not R or (live.timestamp or 0) > (R.at or 0)) then - R = remoteOf({ timestamp = live.timestamp, percentage = live.percentage, progress = live.progress, - device = live.device, device_name = live.device_name }) - end - if R then OSM.decide("prerender", R) end - OSM.setMoment("open") -end - --- Resume: a move found at sleep is asked now, before any network. -function OSM.onResume() - if not OSM.on() or not inBook() then return end - local ui = liveUI() - local p = serverPlugin(ui) - local rec = p and OSM.rec(openDigest(p)) - OSM.setMoment("wake") - if rec and rec.pending and rec.server then OSM.decide("wake", rec.server) end -end - --- Pull, then the outbox (the behind-hold needs the server's place first), then done(). -function OSM.pullThenDrain(p, moment, source, done) - OSM.setMoment(moment) - local digest = openDigest(p) - p:fetchRemoteProgress(digest, function() - -- onPulled's queued decision runs first, including sending or dropping an override. - UIManager:nextTick(function() - OSM.setMoment(moment) - if can(p, "outbox") then p:requestLifecycleOutboxDrain(source) end - done() - end) - end, true) -end - -function OSM.onPage(m, page) - OSM.page = page - if OSM.pause_task then UIManager:unschedule(OSM.pause_task) end - OSM.pause_task = function() - OSM.pause_task = nil - OSM.pause(m) - end - UIManager:scheduleIn(OSM.PAUSE_S, OSM.pause_task) -end - --- A pause: 120 s without a turn, and the place moved more than a page since the last push. -function OSM.pause(m) - if not OSM.on() or not inBook() or OSM.pausing then return end - local ui = liveUI() - local p = serverPlugin(ui) - if not p or not p:isLoggedIn() or not can(p, "reading_sync") then return end - local digest = openDigest(p) - local rec = OSM.rec(digest, true) - local L = OSM.localPlace(p, ui) - local last = rec.pushed and OSM.place(ui, rec.pushed, nil) or (rec.m and OSM.place(ui, rec.m.pct, rec.m.progress)) - if L == nil or (last and math.abs(L - last) <= 1) then return end - OSM.pausing = true - Wifi.acquire("pause") - Net.up(p, { reason = "pause", cap = 20, need_server = true }, function(ok, res) - if not ok then - OSM.pausing = false - Wifi.release("pause") - log("orbismart: pause sync skipped, network not ready:", res and res.detail or "") - return - end - OSM.pullThenDrain(p, "pause", "orbismart_pause", function() - OSM.pausing = false - UIManager:scheduleIn(1, function() Sync.waitOutbox(p, 20, function() Wifi.release("pause") end) end) - end) - end) -end - --- "Read from here everywhere": pushes this place now, skipping the behind-hold once; queued for --- the next sync when offline (design §3.5). On a finished book it starts a reread (ruling 2). -function OSM.readFromHere(why) - local ui = liveUI() - local p = serverPlugin(ui) - if not p or not ui or not ui.document then return end - local digest = openDigest(p) - local rec = OSM.rec(digest, true) - local okp, pct = pcall(p.getLastPercent, p) - local okx, progress = pcall(p.getLastProgress, p) - if not okp or type(pct) ~= "number" or not okx then return end - rec.override = { at = os.time(), pct = pct, progress = progress } - rec.declined_at, rec.declined_reset, rec.pending = nil, nil, nil - if finished(ui) and EOB and EOB.session and digest then - EOB.session[digest] = EOB.session[digest] or { forward = 0 } - EOB.session[digest].released = true - end - saveSettings() - log("orbismart: override queued (" .. tostring(why) .. ")") - if not p:isLoggedIn() then return end - Wifi.acquire("override") - Net.up(p, { reason = "override", cap = 20, need_server = true }, function(ok) - if not ok then - Wifi.release("override") - log("orbismart: override queued (offline); sent first at the next sync") - return - end - OSM.push(p, "override") - UIManager:scheduleIn(1, function() Sync.waitOutbox(p, 20, function() Wifi.release("override") end) end) - end) -end - ----------------------------------------------------------------- the This book sheet - --- One row under Auto-sync in the plugin's This book sheet (bookorbit_book_sheet.lua :241-243, --- built through bookorbit_menu_ui.lua :217 MenuUI.row, :71 MenuUI.divider), and its action --- (bookorbit_menu_page.lua :189 MenuPage:runAction). Missing: the Orbit menu still has it. -function OSM.installSheet() - if OSM.sheet_hooked then return true end - local oku, MenuUI = pcall(require, "bookorbit_menu_ui") - local okp, MenuPage = pcall(require, "bookorbit_menu_page") - local okb, BoardUI = pcall(require, "bookorbit_board_ui") - if not (oku and okp and okb) or type(MenuUI) ~= "table" or type(MenuPage) ~= "table" or type(BoardUI) ~= "table" then return false end - local missing = {} - for _, n in ipairs(Compat.missingOn(MenuUI, { row = "function", divider = "function" })) do table.insert(missing, "MenuUI." .. n) end - for _, n in ipairs(Compat.missingOn(MenuPage, { runAction = "function" })) do table.insert(missing, "MenuPage." .. n) end - for _, n in ipairs(Compat.missingOn(BoardUI, { vstack = "function" })) do table.insert(missing, "BoardUI." .. n) end - if #missing > 0 then - once("sheet", "compat: \"Read from here everywhere\" in This book off (plugin changed): missing " .. table.concat(missing, ", ")) - return false - end - OSM.sheet_hooked = true - wrap(MenuUI, "row", function(stock) return function(w, o, ...) - local row = stock(w, o, ...) - if type(o) == "table" and type(o.action) == "table" and o.action.kind == "auto" and OSM.on() and inBook() then - local here = stock(w, { icon = "arrow-right", label = _("Read from here everywhere"), - sub = _("Your other readers move here at their next sync"), action = { kind = "orbit_read_here" } }) - return BoardUI.vstack({ w = w }, { row, MenuUI.divider(w), here }) - end - return row - end end, "orbismart") - wrap(MenuPage, "runAction", function(stock) return function(page, action, ...) - if type(action) == "table" and action.kind == "orbit_read_here" then - pcall(page.close, page) - UIManager:nextTick(function() OSM.readFromHere("This book") end) - return - end - return stock(page, action, ...) - end end, "orbismart") - return true -end - ----------------------------------------------------------------- wiring - -Compat.ORBISMART_API = { getProgress = "function", updateProgress = "function" } - -OSM.migrate() --- Cover closed-book startup outbox drains too; ReaderReady retries if BookOrbit loads later. -OSM.installApi() - -do - local base_ready = OrbitAndroid.onReaderReady - function OrbitAndroid:onReaderReady(...) - -- Before the rest: a known further place opens before the first paint. - local okr, err = pcall(OSM.onReaderReady, self) - if not okr then log("orbismart: open failed:", tostring(err)) end - return base_ready(self, ...) - end - -- 0.12: Sync, Wi-Fi & power controls cadence, including Off. Scheduled - -- pulls retain the safe position decision without a second pause timer. - local base_resume = OrbitAndroid.onResume - function OrbitAndroid:onResume(...) - pcall(OSM.onResume) - return base_resume(self, ...) - end - local base_close = OrbitAndroid.onCloseWidget - function OrbitAndroid:onCloseWidget(...) - if OSM.pause_task then UIManager:unschedule(OSM.pause_task); OSM.pause_task = nil end - OSM.closePopup() - return base_close(self, ...) - end -end diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit/quiesce.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/quiesce.lua new file mode 100644 index 00000000..b176a772 --- /dev/null +++ b/android/koreader/orbit.koplugin/ko/server/bookorbit/quiesce.lua @@ -0,0 +1,33 @@ +-- 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/server/bookorbit/reading_sync.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/reading_sync.lua deleted file mode 100644 index eec74cca..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/reading_sync.lua +++ /dev/null @@ -1,195 +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"). - --- Sync while reading ---------------------------------------------------------------------------------------------- - -function OrbitAndroid:chapterKey(page) - local toc = self.ui and self.ui.toc - if not toc or type(page) ~= "number" then return nil end - local ok, key = pcall(function() - if toc:isChapterStart(page) then return page end - return toc:getPreviousChapter(page) - end) - return ok and key or nil -end - -function OrbitAndroid:onCloseWidget() - if self.ui and self.ui.document then Stats.send("close", contentOfUI(self.ui), false) end - -- A patch update waiting for the book: once nothing is open (another book may be opening). - if self.ui and self.ui.document and state.restart_waiting then - UIManager:scheduleIn(1.5, function() OrbitAndroid.maybeRestart(self, "check") end) - end - -- The book closed: what waited for the reader shows now (another book may be opening). - if self.ui and self.ui.document then - UIManager:scheduleIn(1.5, function() - Gate.drain("book closed") - if Copies and Copies.tick then pcall(Copies.tick, "book closed") end - end) - end - -- A close (Back to file browser, Exit) runs this; a kill or suspend doesn't. A close Home - -- started keeps the book as the current one (home_book); the user's own close clears it. - if self.ui and self.ui.document then - local file = self.ui.document.file - if state.closing_for_home and state.closing_for_home == file then - S.home_book = file - log("home: book closed by Home; it stays the current book") - else - S.home_book = nil - end - state.closing_for_home = nil - S.open_book_at_exit = nil - saveSettings() - pcall(function() G_reader_settings:flush() end) - end - if self.reading_task then - UIManager:unschedule(self.reading_task) - self.reading_task = nil - end - if self.ui and self.ui.document and self.book_tracked then - self.book_tracked = false - local st = Wifi.state() - local restore = WifiPlan.bookClosed(st) - log("wifi: book closed | mode", st.mode, restore == "on" and "| Wi-Fi was on before the book: turning it back on" or "") - if restore == "on" and Companion.has("wifi") then - Companion.netUp("book_closed", { owner = "auto" }) - end - end -end - -function OrbitAndroid:onReaderReady() - -- "Open book at exit": survives a kill (flushed now), cleared when the book is closed. - -- Another book opening replaces Home's current book. - local file = self.ui and self.ui.document and self.ui.document.file - if file and (S.open_book_at_exit ~= file or S.home_book) then - S.open_book_at_exit = file - S.home_book = nil - saveSettings() - pcall(function() G_reader_settings:flush() end) - end - self.schedule = Schedule.new(S.reading_schedule, now_s()) - self:hookPluginPagePush() - pcall(self.hookSuspendSnapshot, self) - Stats.send("open", contentOfUI(self.ui), true) - self:bookOpenFlow() -end - --- A book opened: remember Wi-Fi for off while reading; in the off-while-reading and just-in-time --- modes, bring the network up for the plugin's open-time pull, then let Wi-Fi go off. -function OrbitAndroid:bookOpenFlow() - if not Companion.has("wifi") then return end - local st = Wifi.state() - local on = Wifi.radioOn() - WifiPlan.bookOpened(st, on) - self.book_tracked = true - log("wifi: book opened (Wi-Fi", on == false and "off" or "on", ") mode", st.mode) - if st.mode == "always_on" then return end - local p = serverPlugin(self.ui) - if not p or not p:isLoggedIn() then return Wifi.kick() end - Wifi.acquire("open") - Net.up(p, { reason = "open", cap = 20, need_server = true }, function(ok) - if not ok then return Wifi.release("open") end - -- OrbiSmart: pull, decide, then the outbox under the behind-hold. - if OSM and OSM.on() and can(p, "reading_sync") then - -- ReaderReady runs inside doShowReader's construction coroutine, before - -- UIManager:show(reader). BookOrbit reuses that coroutine for its yielding - -- background GET; yielding here leaves no window and UIManager exits. - -- Start the pull from the UI loop, after construction has shown the reader. - local ui = self.ui - return UIManager:nextTick(function() - if liveUI() ~= ui or not ui.document then return Wifi.release("open") end - OSM.pullThenDrain(p, "open", "orbit_open", function() - UIManager:scheduleIn(1, function() Sync.waitOutbox(p, 20, function() Wifi.release("open") end) end) - end) - end) - end - -- The plugin pulls on open by itself, or on NetworkConnected when it was offline - -- (main.lua:1353-1361); its 25 s debounce keeps this from doubling up. - p:requestProgressPull(false, false, "orbit_open") - UIManager:scheduleIn(1, function() - Sync.waitOutbox(p, 20, function() Wifi.release("open") end) - end) - end) -end - -function OrbitAndroid:onNetworkConnected() - Wifi.kick() - if Mirror and Mirror.kick then Mirror.kick("network up") end -end - -function OrbitAndroid:onPageUpdate(page) - if self.ui and self.ui.document then Stats.page(stats_acc) end - -- The power settings choose cadence; the position rule chooses safe pull/push behavior. - if S.reading_schedule == "off" or not (self.ui and self.ui.document) then return end - local t = now_s() - Schedule.onPage(self.schedule, self:chapterKey(page), t) - if Schedule.isDue(self.schedule, t) then - -- Run once the reader settles on a page, never in the middle of turning. - if self.reading_task then UIManager:unschedule(self.reading_task) end - self.reading_task = function() - self.reading_task = nil - self:readingSync() - end - UIManager:scheduleIn(3, self.reading_task) - end -end - -function OrbitAndroid:readingSync() - if self.reading_running then return end - local p = serverPlugin(self.ui) - if not p or not p:isLoggedIn() or not inBook() then return end - if not can(p, "reading_sync") then return end - self.reading_running = true - local t0 = now_s() - Schedule.markSynced(self.schedule, t0) - log("reading: sync due (" .. S.reading_schedule .. ")") - Wifi.acquire("reading") - Net.up(p, { reason = "reading", cap = 20, need_server = true }, function(ok, res) - if not ok then - Wifi.release("reading") - self.reading_running = false - log("reading: network not ready; try again at the next interval:", res.detail or "") - return - end - if OSM and OSM.on() then - return OSM.pullThenDrain(p, "pause", "orbit_reading", function() - self.reading_running = false - UIManager:scheduleIn(1, function() Sync.waitOutbox(p, 20, function() Wifi.release("reading") end) end) - end) - end - p:requestLifecycleOutboxDrain("orbit_reading") - local digest = p:getDocumentDigest() - p:fetchRemoteProgress(digest, function(fetched) - self.reading_running = false - -- Wi-Fi goes back to its previous state once the plugin's push or pull is done. - UIManager:scheduleIn(1, function() - Sync.waitOutbox(p, 20, function() Wifi.release("reading") end) - end) - if not fetched then - log("reading: plugin could not read library's position") - return - end - local remote = p.last_remote_progress - local has_remote = remote ~= nil and remote.digest == digest and remote.percentage ~= nil - local local_pct = p:getLastPercent() - local action = Plan.readingAction{ - has_remote = has_remote, - same_place = has_remote and p:isSamePlace(remote, local_pct, p:getLastProgress()), - remote_newer = has_remote and p:remoteProgressIsNewer(remote, local_pct), - forward = p.settings.sync_forward, - } - if action == "pull" then - p.pull_timestamp = 0 - p:requestProgressPull(false, false, "orbit_reading") - elseif action == "push" then - p.push_timestamp = 0 - p:requestProgressPush(false, false, "orbit_reading") - end - log("reading: plugin", action, "in", fmt(now_s() - t0)) - end, true) - end) -end - ---------------------------------------------------------------------------------------------- diff --git a/android/koreader/orbit.koplugin/ko/server/bookorbit/sync.lua b/android/koreader/orbit.koplugin/ko/server/bookorbit/sync.lua deleted file mode 100644 index 411b8102..00000000 --- a/android/koreader/orbit.koplugin/ko/server/bookorbit/sync.lua +++ /dev/null @@ -1,81 +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"). - --- Waiting on the plugin's lifecycle outbox (bookorbit main.lua:374-547) ---------------------------------------------------------------------------------------------- - -Sync = {} - --- The plugin skips a non-interactive pull within 25 s of the last one --- (API_CALL_DEBOUNCE_DELAY, bookorbit_progress_sync.lua:26, 384-387). Clear it only when the --- last pull really was that recent; on a fresh start a pull that already ran stands. -function Sync.clearPullDebounce(p, reason) - local okc, cleared = pcall(function() - local last = p.pull_timestamp - if type(last) ~= "number" or last == 0 then return false end - if reason == "start" then return false end - local now = UIManager:getElapsedTimeSinceBoot() - local window = time.s(25) - if now - last <= window then p.pull_timestamp = 0; return true end - return false - end) - if okc and cleared then log("pull: cleared the plugin's 25 s debounce for this pull (" .. reason .. ")") end -end - --- Entries the plugin can send now. An entry backing off after a failure (next_attempt_at in --- the future) or in flight isn't drainable (bookorbit_lifecycle_outbox.lua:253-259, counted in --- diagnostics().drainable, :303-316): the plugin retries it on its own timer, and the --- coordinator's busy flag covers one in flight. Counting it held Wi-Fi on for minutes and made --- every wait run to its cap. Plugins without drainable: everything not parked. -function outboxPending(diag) - if type(diag.drainable) == "number" then return diag.drainable end - return (diag.count or 0) - (diag.blocked or 0) -end - -function Sync.waitOutbox(p, cap, cb) - if not can(p, "outbox") then - -- Can't see the plugin's outbox: leave it to the plugin's own sync. - return UIManager:nextTick(function() cb(true, "left to the plugin (compat)", 0) end) - end - local t0 = now_s() - local start_os = os.time() - local last_nudge = t0 - local function tick() - local el = now_s() - t0 - local okd, diag = pcall(function() return p:getLifecycleOutbox():diagnostics() end) - if not okd then - log("outbox: cannot read:", diag) - return cb(false, "outbox unreadable", el) - end - local coordinator = p:getSyncCoordinator() - local busy = coordinator:isBusy() or coordinator:queuedCount() > 0 - local err = p.settings.last_error - local verdict = Plan.outboxVerdict{ - pending = outboxPending(diag), - busy = busy, - new_error = err ~= nil and (err.at or 0) >= start_os, - elapsed = el, - cap = cap, - since_nudge = now_s() - last_nudge, - } - if verdict == "done" then - log("outbox: drained after", fmt(el), "(parked:", diag.blocked or 0, ")") - return cb(true, nil, el) - elseif verdict == "failed" then - log("outbox: plugin reported", err.event, err.message, "after", fmt(el)) - return cb(false, err.message or "plugin sync failed", el) - elseif verdict == "timeout" then - log("outbox: still", outboxPending(diag), "pending at the", cap .. "s cap") - return cb(false, "time limit reached", el) - elseif verdict == "nudge" then - last_nudge = now_s() - p:requestLifecycleOutboxDrain("orbit_wait") - end - UIManager:scheduleIn(0.5, tick) - end - tick() -end - ---------------------------------------------------------------------------------------------- diff --git a/android/koreader/orbit.koplugin/ko/shared.lua b/android/koreader/orbit.koplugin/ko/shared.lua index 6108ae67..d42ce1ad 100644 --- a/android/koreader/orbit.koplugin/ko/shared.lua +++ b/android/koreader/orbit.koplugin/ko/shared.lua @@ -38,7 +38,7 @@ function Shared.refresh(why) 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(Server.reportRecommended, "refresh " .. why) end + 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 local m = Clicks.parse(st.keymap) @@ -156,13 +156,13 @@ function Shared.onChange(key, why) elseif key == "sleep_mode" or key == "sleep_from" or key == "sleep_leave_out" then try(Sleep and Sleep.changed, "companion settings") elseif key == "storage_limit_mb" then - try(Server.countStorage, "limit changed") + try(Library.backgroundCommand,"storage.recount", "limit changed") elseif key == "mirror_covers" then - if S.mirror_covers then try(Server.refreshCovers, "turned on") end + if S.mirror_covers then try(Library.backgroundCommand,"covers.refresh", "turned on") end elseif key == "sync_mode" then - try(Server.positionModeChanged, "companion") + try(ReadingSync and ReadingSync.modeChanged, "companion") elseif key == "recommended_choice" then - try(Server.applyRecommended, why) + try(Library.backgroundCommand,"preferences.apply", why) end end @@ -196,8 +196,8 @@ function Shared.capsChanged(why, before, after, real) local lost, gained = Caps.diff(before, after) if #lost == 0 and #gained == 0 then return end log("companion: caps changed (" .. why .. "): lost", table.concat(lost, ","), "| gained", table.concat(gained, ",")) - if #lost > 0 then pcall(Server.capabilitiesLost, why) end - if #gained > 0 then pcall(Server.capabilitiesGained, "caps " .. why) end + if #lost > 0 then pcall(Library.backgroundCommand,"capabilities.lost",why) end + if #gained > 0 then pcall(Library.backgroundCommand,"capabilities.gained","caps " .. why) end end function Shared.push(why) diff --git a/android/koreader/orbit.koplugin/ko/sleep.lua b/android/koreader/orbit.koplugin/ko/sleep.lua index 3836fbfc..d0fe171b 100644 --- a/android/koreader/orbit.koplugin/ko/sleep.lua +++ b/android/koreader/orbit.koplugin/ko/sleep.lua @@ -7,6 +7,7 @@ --------------------------------------------------------------------------------------------- function OrbitAndroid:onSuspend() + ReadingSync.queue("suspend",self.ui) -- Screen off or another app in front: KOReader isn't being read until Resume. if stats_acc.at then Stats.send("suspend", nil, false) @@ -60,7 +61,6 @@ end function OrbitAndroid:sleepSync(reason) local cap = S.sleep_cap or 20 local t0 = now_s() - local p = serverPlugin(self.ui) log(reason .. ": sleep sync start, cap", cap .. "s") local held = false state.sleep_syncing = true @@ -79,25 +79,10 @@ function OrbitAndroid:sleepSync(reason) Companion.netDone(reason, ok, seconds, detail, restore) if held then Wifi.release("sleep", true) end end - if not p or not Server.signedIn(p) then - return done(false, "library plugin missing or signed out") - end Wifi.acquire("sleep") - held = true - Net.up(p, { reason = reason, cap = cap, need_server = true, wake_lock_s = cap + 5 }, function(ok, res) - if not ok then return done(false, res.detail) end - -- OrbiSmart: pull first, so the behind-hold judges the snapshot against the server's place. - if Server.positionOn() and inBook() and can(p, "reading_sync") then - return Server.pullThenDrain(p, "sleep", "orbit_" .. reason, function() - Server.waitOutbox(p, math.max(1, cap - (now_s() - t0)), function(synced, why) done(synced, why) end) - end) - end - -- The plugin queued its snapshot in its own _onSuspend (main.lua:1340-1351) but drains - -- only when already connected (main.lua:411-419). Now we are: drain and wait. - if can(p, "outbox") then Server.drain(p, "orbit_" .. reason) end - Server.waitOutbox(p, math.max(1, cap - (now_s() - t0)), function(synced, why) - done(synced, why) - end) + held=true + Net.up(nil,{reason=reason,cap=cap,wake_lock_s=cap+5},function() + ReadingSync.run("sleep",done) end) end @@ -186,28 +171,13 @@ function OrbitAndroid:onOrbitSyncAndSleep(stay_awake) end end - local p = serverPlugin(self.ui) - if not p or not Server.signedIn(p) then - finish(false, "library plugin missing or signed out") - return true - end Wifi.acquire("sync_and_sleep") - self.sas_held = true - Net.up(p, { reason = flow, cap = cap, need_server = true, wake_lock_s = cap + 5 }, function(ok, res) - if cancelled then return finish(false, "cancelled") end - if not ok then return finish(false, res.detail) end - if inBook() and can(p, "sleep_snapshot") then - -- Exactly what the plugin does on sleep: snapshot the open book into its - -- durable outbox and drain it (main.lua:1340-1351). - state.force_snapshot = true - Server.snapshot(p) - state.force_snapshot = nil - elseif can(p, "outbox") then - Server.drain(p, "orbit_sync_and_sleep", true) - end - Server.waitOutbox(p, math.max(1, cap - (now_s() - t0)), function(synced, why) - if cancelled then return finish(false, "cancelled") end - finish(synced, why) + self.sas_held=true + Net.up(nil,{reason=flow,cap=cap,wake_lock_s=cap+5},function() + if cancelled then return finish(false,"cancelled") end + ReadingSync.run(stay_awake and "manual" or "sleep",function(ok,why) + if cancelled then return finish(false,"cancelled") end + finish(ok,why) end) end) return true diff --git a/android/koreader/orbit.koplugin/ko/start.lua b/android/koreader/orbit.koplugin/ko/start.lua index 4944db13..4739a35a 100644 --- a/android/koreader/orbit.koplugin/ko/start.lua +++ b/android/koreader/orbit.koplugin/ko/start.lua @@ -7,6 +7,7 @@ --------------------------------------------------------------------------------------------- function OrbitAndroid:onResume() + if ReadingSync then ReadingSync.resume(self.ui) end if not stats_acc.at then stats_acc.at = now_s() if readerContent() ~= "none" then Stats.send("resume") end @@ -36,64 +37,23 @@ function OrbitAndroid:onResume() end function OrbitAndroid:wakeFlow(reason) - -- OrbiSmart: a short nap rarely follows reading elsewhere; its sleep sync already ran - -- (docs/design/position-sync.md §3.3, wake check after >= 5 min asleep). - if Server.positionOn() and reason == "wake" and state.paused_for and state.paused_for < Server.positionWakeMinimum() then - log("orbismart: woke after " .. fmt(state.paused_for) .. "; no wake check under " .. Server.positionWakeMinimum() .. " s") - return - end - if not S.sync_on_wake then - log(reason .. ": sync on wake is off") - return - end - local p = serverPlugin(self.ui) - if not p or not Server.signedIn(p) then - log(reason .. ": library plugin missing or signed out; nothing to do") - return - end - local t0 = now_s() - local lease = "wake" - Wifi.acquire(lease) - Net.up(p, { reason = reason, cap = 20, need_server = true }, function(ok, res) - if not ok then - Wifi.release(lease) - self:showWakeBanner(res) - return - end - -- OrbiSmart: pull and decide first, then the outbox under the behind-hold. - if Server.positionOn() and inBook() and can(p, "reading_sync") then - log(reason .. ": OrbiSmart pull, then the outbox; network ready in", fmt(now_s() - t0)) - return Server.pullThenDrain(p, "wake", "orbit_" .. reason, function() - UIManager:scheduleIn(1, function() Server.waitOutbox(p, 20, function() Wifi.release(lease) end) end) - end) - end - if can(p, "outbox") then Server.drain(p, "orbit_" .. reason) end - -- Hold Wi-Fi until the plugin's drain and pull are done, then restore. - UIManager:scheduleIn(1, function() - Server.waitOutbox(p, 20, function() Wifi.release(lease) end) + if ReadingSync.on() and reason=="wake" and state.paused_for and state.paused_for<300 then return end + if not S.sync_on_wake then return end + Wifi.acquire("wake") + Net.up(nil,{reason=reason,cap=20},function(ok,res) + ReadingSync.run("wake",function(synced,why) + Wifi.release("wake") + Library.idle() + if not ok then self:showWakeBanner(res) end end) - if inBook() and can(p, "wake_pull") then - -- The plugin debounces pulls for 25 s (bookorbit_progress_sync.lua:26, 383-387). - -- Clear it for this one pull; on a fresh start skip it if a pull already ran. - Server.clearPullDebounce(p, reason) - Server.pull(p, "orbit_" .. reason) - log(reason .. ": asked plugin to drain outbox and pull, network ready in", fmt(now_s() - t0)) - else - log(reason .. ": asked plugin to drain outbox (no book open), network ready in", fmt(now_s() - t0)) - end end) end function OrbitAndroid:showWakeBanner(res) local text = _("Can't reach library. Reading from this device's place.") .. "\n" .. (res.detail or "") local retry = function() self:wakeFlow("retry") end - local okt, Toast = pcall(Server.require, "toast") Gate.show("wake banner: " .. text, function() - if okt then - Toast.error(text, retry, { timeout = 6 }) -- gate: Gate.show - else - UIManager:show(InfoMessage:new{ text = text, timeout = 6 }) -- gate: Gate.show - end + UIManager:show(InfoMessage:new{ text=text,timeout=6 }) -- gate: Gate.show end, 60) end diff --git a/android/koreader/orbit.koplugin/ko/test_sync_path.lua b/android/koreader/orbit.koplugin/ko/test_sync_path.lua index 76b03c7e..33a7bd24 100644 --- a/android/koreader/orbit.koplugin/ko/test_sync_path.lua +++ b/android/koreader/orbit.koplugin/ko/test_sync_path.lua @@ -7,7 +7,6 @@ --------------------------------------------------------------------------------------------- function OrbitAndroid:testSyncPath() - local p = serverPlugin(self.ui) local lines = {} local t0 = now_s() local wait = InfoMessage:new{ text = _("Testing the sync path…") } @@ -36,9 +35,7 @@ function OrbitAndroid:testSyncPath() end UIManager:close(wait) local text = table.concat(lines, "\n") .. "\n\n" .. string.format(_("Total %s."), fmt(now_s() - t0)) - .. "\n" .. _("Step 4 only checks that the server answers at its base address; it uses no login.") - local cl = compatLines(serverPlugin(self.ui)) - if #cl > 0 then text = text .. "\n\n" .. table.concat(cl, "\n") end + .. "\n" .. _("Server requests run in BookSync Companion; saved changes are sent through its sync owner.") UIManager:show(TextViewer:new{ title = _("Test sync path"), text = text }) -- gate: user action (menu) end @@ -53,17 +50,12 @@ function OrbitAndroid:testSyncPath() else add(false, _("Companion answered"), nil, _("BookSync Companion is not installed: Wi-Fi stays as it is, Tailscale is woken directly.")) end - if not p or not Server.signedIn(p) then - add(false, _("library plugin signed in"), nil, _("Sign in to library first.")) - return show() - end local was_on = Wifi.acquire("test") held = true if was_on == false then add(Companion.has("wifi"), _("Wi-Fi was off: turning it on for the test"), nil, Companion.problem()) end - Net.up(p, { reason = "test", cap = 20, need_server = true }, function(ok, res) + Net.up(nil, { reason = "test", cap = 20, need_server = true }, function(ok, res) add(res.wifi_s ~= nil, _("Wi-Fi connected"), res.wifi_s, _("Turn Wi-Fi on, or check BookSync Companion's Wi-Fi permission.")) add(res.vpn_s ~= nil, _("Tailscale up"), res.vpn_s, _("Tailscale not connected: open Tailscale and sign in.")) - add(res.server_s ~= nil, _("library server answered"), res.server_s, _("No answer from the server: check Tailscale and the server address in library settings.")) if not ok then return show() end local s0 = now_s() local reported = false @@ -71,15 +63,10 @@ function OrbitAndroid:testSyncPath() if reported then return end reported = true add(err == nil, _("library plugin synced"), now_s() - s0, - err and (_("The plugin reported: ") .. tostring(Server.testError(p, err))) or nil) + err and (_("The plugin reported: ") .. tostring(err)) or nil) show() end - if not (Server.testReady(p)) then - add(true, _("library plugin step skipped: ") .. Compat.fallback("test_sync"), nil) - return show() - end - -- The plugin's own Sync now: this book in a book, the library otherwise. - Server.testSync(p, inBook(), plugin_done) + ReadingSync.run(inBook() and "manual" or "close",function(ok,why) plugin_done(not ok and (why or "delivery pending") or nil) end) UIManager:scheduleIn(60, function() plugin_done("timeout") end) end) end diff --git a/android/koreader/orbit.koplugin/ko/wifi.lua b/android/koreader/orbit.koplugin/ko/wifi.lua index e900eb69..6ade4762 100644 --- a/android/koreader/orbit.koplugin/ko/wifi.lua +++ b/android/koreader/orbit.koplugin/ko/wifi.lua @@ -54,15 +54,11 @@ function Wifi.busy() if Wifi.inflight_http > 0 then return true, "download in progress" end -- The cache's background checks and the offline mirror run in child processes, which this -- process's request counter never sees. - if Server.cacheBusy then - local okc, why = pcall(Server.cacheBusy) + if Library and Library.backgroundBusy then + local okc, why = pcall(Library.backgroundBusy) if okc and why then return true, why end end - local p = serverPlugin() - if p and can(p, "outbox") then - local okb, busy = pcall(Server.syncBusy, p) - if okb and busy then return true, "library plugin syncing" end - end + if ReadingSync and ReadingSync.busy then return true,"companion sync" end return false end @@ -107,7 +103,7 @@ function Wifi.evaluate(why) Wifi.tx = tx local busy, busy_why = Wifi.busy() local screen_off = Jni.isInteractive() == false - local okb, browsing = pcall(function() return serverOverBook(serverPlugin()) end) -- the reading gate's own test + local okb, browsing = pcall(function() return not reading() end) local action, reason, force = WifiPlan.decide(st, { now = now_s(), wifi_on = wifi_on, busy = busy, screen_off = screen_off, browsing = okb and browsing == true }) if action == "off" then diff --git a/android/koreader/orbit.koplugin/logic/budgets.lua b/android/koreader/orbit.koplugin/logic/budgets.lua index 11eeda2d..6937e0cf 100644 --- a/android/koreader/orbit.koplugin/logic/budgets.lua +++ b/android/koreader/orbit.koplugin/logic/budgets.lua @@ -95,6 +95,8 @@ Budgets.screens["booklist-config"] = budget(0, 0, 100) Budgets.screens["booklist-config"].roundTrips = 0 Budgets.screens["booklist-sources"] = budget(6, 16384, 50) +Budgets.screens["position-consent"] = budget(1, 16384, 50) +Budgets.screens["position-verification"] = budget(1, 16384, 50) -- Storage, its confirmations and folder chooser use one local materialized row. Budgets.screens.storage = budget(1,16384,50) Budgets.screens.collections = budget(6,16384,50) diff --git a/android/koreader/orbit.koplugin/logic/wifi_plan.lua b/android/koreader/orbit.koplugin/logic/wifi_plan.lua index 4df6de1f..f1bdfe8f 100644 --- a/android/koreader/orbit.koplugin/logic/wifi_plan.lua +++ b/android/koreader/orbit.koplugin/logic/wifi_plan.lua @@ -55,7 +55,10 @@ end -- A flow needs the network. wifi_on: the radio state now (nil = unknown). function WifiPlan.acquire(st, name, wifi_on, now) - if st.n == 0 then st.restore_off = (wifi_on == false) end + -- A fast companion command may finish before a second wake/open lease starts. + -- Preserve ownership through the grace window; the companion still rejects auto-off + -- if the reader has manually taken ownership of the radio in the meantime. + if st.n == 0 and not (st.restore_off and st.release_at) then st.restore_off = (wifi_on == false) end st.leases[name] = (st.leases[name] or 0) + 1 st.n = st.n + 1 st.release_at = nil diff --git a/android/koreader/orbit.koplugin/main.lua b/android/koreader/orbit.koplugin/main.lua index 3329e99e..dbc90e79 100644 --- a/android/koreader/orbit.koplugin/main.lua +++ b/android/koreader/orbit.koplugin/main.lua @@ -4,16 +4,10 @@ Orbit: a KOReader plugin for Android e-readers (generic Android; vendor quirks live in VENDORS, ko/jni.lua). It was the user patch 2-orbit-android.lua up to BookSync 0.7.x and behaves the same. -The official BookOrbit plugin (bookorbit.koplugin) does ALL syncing and holds the login. -Orbit never talks to BookOrbit's API. It only: - - * gets the network ready (Wi-Fi through the "Orbit Companion" app, Tailscale wake), - * checks that the plugin's configured server answers at its base URL (no login), - * then triggers or waits on the plugin: its public action BookOrbitOpenDashboard and its - "Push while reading" setting, and, behind a compatibility check with a fallback for each - (logic/compat.lua; android/koreader/README.md "Plugin hook points"), its internals - requestLifecycleOutboxDrain, requestProgressPull, requestProgressPush, - fetchRemoteProgress, _onSuspend, onBookOrbitSyncBook, startSweep. +BookSync's companion owns sync transport, durable lifecycle replay and position decisions. +The reader captures small native locators/geometry and displays explicit consent. The +migration gate disables the retired sync client before any plugin instances start. +KOReader's own built-in sync remains independent. Layout (docs/design/orbit-plugin.md): FILES below, loaded in that order into one environment shared by the plugin's files, so each file's top-level names are visible to the others, as @@ -39,14 +33,14 @@ local LOGIC = { } local KO = { "ko/base.lua", "ko/settings.lua", "ko/jni.lua", "ko/companion.lua", "ko/shared.lua", - "ko/server/bookorbit.lua", "ko/net.lua", "ko/server/bookorbit/sync.lua", "ko/wifi.lua", "ko/updater.lua", + "ko/server/bookorbit/quiesce.lua", "ko/server/bookorbit.lua", "ko/net.lua", "ko/wifi.lua", "ko/updater.lua", "ko/background.lua", "ko/runtime.lua", "ko/clicks_channel.lua", "ko/keys.lua", - "ko/module.lua", "ko/server/bookorbit/lifecycle.lua", "ko/start.lua", "ko/home.lua", "ko/sleep.lua", "ko/server/bookorbit/reading_sync.lua", + "ko/module.lua", "ko/start.lua", "ko/home.lua", "ko/sleep.lua", "ko/reading_sync.lua", "ko/test_sync_path.lua", "ko/companion_ui.lua", "ko/server/bookorbit/recommended.lua", "ko/menu.lua", "ko/wifi_backend.lua", "ko/server/bookorbit/grouping.lua", "ko/endsheet.lua", "ko/server/bookorbit/endofbook.lua", - "ko/server/bookorbit/localfirst.lua", "ko/db.lua", "ko/store.lua", "ko/badge.lua", "ko/server/bookorbit/copies.lua", "ko/sleepscreen.lua", - "ko/sqlite_stress.lua", "ko/library.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/battery.lua", "ko/home_host.lua", "ko/series.lua", "ko/home_editor.lua", "ko/booklist_config.lua", "ko/settings_view.lua", - "ko/server/bookorbit/orbismart.lua", "ko/status_layout.lua", "ko/notices.lua", "ko/main_loop.lua", + "ko/server/bookorbit/local_view.lua", "ko/db.lua", "ko/store.lua", "ko/badge.lua", "ko/server/bookorbit/copies.lua", "ko/sleepscreen.lua", + "ko/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/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", } -- This plugin's folder: PluginLoader dofile()s /main.lua (frontend/pluginloader.lua:244). diff --git a/android/koreader/test/koreader_compat.lua b/android/koreader/test/koreader_compat.lua index 76c1c2af..3f3aef9b 100644 --- a/android/koreader/test/koreader_compat.lua +++ b/android/koreader/test/koreader_compat.lua @@ -90,12 +90,14 @@ local NEEDS = { { "frontend/ui/widget/progresswidget.lua", { {"percentage", F}, {"ticks", F}, {"bordersize", F}, {"margin_h", F}, {"margin_v", F}, {"radius", F} } }, { "frontend/ui/widget/container/rightcontainer.lua", { {"RightContainer", T} } }, { "frontend/ui/widget/container/topcontainer.lua", { {"TopContainer", T} } }, + { "frontend/apps/reader/modules/readerpaging.lua", { "getLastPercent", "getLastProgress" } }, + { "frontend/apps/reader/modules/readerrolling.lua", { "getLastPercent", "getLastProgress" } }, { "frontend/apps/reader/modules/readertoc.lua", { "isChapterStart", "getPreviousChapter" } }, { "frontend/apps/reader/modules/readerstatus.lua", { "onEndOfBook", "markBook", "onShowBookStatus", { "end_document_action", T } } }, { "frontend/dispatcher.lua", { "registerAction" } }, -- Plugin handlers are HandlerSandbox tables with __call (compat.lua Compat.callable). - { "frontend/pluginloader.lua", { "loadPlugins", "genPluginManagerSubItem", "getPluginInstance", + { "frontend/pluginloader.lua", { "loadPlugins", "genPluginManagerSubItem", "getPluginInstance", "createPluginInstance", { "HandlerSandbox", T }, { "__call", T } } }, -- Recommended settings (ko/recommended.lua): the stock gesture defaults, Gestures.default_settings. { "plugins/gestures.koplugin/main.lua", { "onFlushSettings", { "data", F }, { "updated", F }, { "default_settings", F } } }, diff --git a/android/koreader/test/position_sync_flows.lua b/android/koreader/test/position_sync_flows.lua new file mode 100644 index 00000000..de5e026d --- /dev/null +++ b/android/koreader/test/position_sync_flows.lua @@ -0,0 +1,169 @@ +-- The native half never simulates policy: responses come from a deliberately neutral port. +return function(test,eq,ok,E,W,UIManager,run,newUI,ReaderUI,FileManager) + local function world(fn) + local saved={reader=ReaderUI.instance,fm=FileManager.instance,shown=W.shown,queue=W.queue, + command=E.Library.positionCommand,cached=E.Library.positionCached,preview=E.Library.positionPreview, + problem=E.Companion.workerProblem,mode=E.S.sync_mode,schedule=E.S.reading_schedule} + local x={page=120,commands={},moves={},callbacks={},snapshot={document="toy:one",token="place-one", + remote={position="/p214",percentage=214/300,at=900,label="fixture reader"},marker={position="/p100",percentage=100/300,at=800}}} + local doc={file="/fixture/one.epub",info={has_pages=false},getPageCount=function() return 300 end, + getCurrentPage=function() return x.page end,getPageFromXPointer=function(_,p) return tonumber(p:match("%d+")) end} + local ui={document=doc,view={footer={percent_finished=.4}},rolling={getLastProgress=function() return "/p"..x.page end}, + doc_settings={readSetting=function() return {status="reading"} end}, + toc={isChapterStart=function(_,p) return p%10==1 end,getPreviousChapter=function(_,p) return p-(p-1)%10 end}} + function ui:handleEvent(event) table.insert(x.moves,event); if event.name=="GotoXPointer" then x.page=tonumber(event.args[1]:match("%d+")) end end + x.ui=ui; ReaderUI.instance=ui; FileManager.instance=nil; W.shown={ui}; W.queue={} + E.Companion.workerProblem=function() return nil end + E.S.sync_mode="orbismart"; E.S.reading_schedule="off" + E.ReadingSync.ready=true; E.ReadingSync.running=0; E.ReadingSync.busy=false; E.ReadingSync.prompt=nil + E.Library.positionCached=function(path) return path==ui.document.file and x.snapshot or nil end + E.Library.positionPreview=function(args) x.preview_args=args; return x.preview_result end + E.Library.positionCommand=function(op,args,done) + table.insert(x.commands,{op=op,args=args}) + local function response() + if op=="sync.activate" then done({ok=true}) + elseif op=="sync.capture" or op=="sync.override" then done({document="toy:one",snapshot=x.snapshot}) + elseif op=="sync.answer" then done({move=args.yes,remote=x.snapshot.remote,token=args.token}) + else done(x.decision or {decision="take",applied="ask",document="toy:one",token=x.snapshot.token,remote=x.snapshot.remote,remaining=0}) end + end + if x.delay then table.insert(x.callbacks,response) else UIManager:nextTick(response) end + return true + end + local success,err=pcall(fn,x) + E.ReadingSync.closePrompt() + ReaderUI.instance,FileManager.instance,W.shown,W.queue=saved.reader,saved.fm,saved.shown,saved.queue + E.Library.positionCommand,E.Library.positionCached,E.Library.positionPreview=saved.command,saved.cached,saved.preview + E.Companion.workerProblem,E.S.sync_mode,E.S.reading_schedule=saved.problem,saved.mode,saved.schedule + E.ReadingSync.running=0; E.ReadingSync.busy=false + ok(success,err) + end + test("sync retirement: legacy class and API are disarmed before instance init",function() + local writes=0 + local function writer() writes=writes+1 end + local legacy={name="bookorbit",requestProgressPull=writer,enqueueLifecycleSnapshot=writer} + local api={updateProgress=writer,request=writer} + 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() + 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") + end) + test("startup smoke: last document remains the top reader through a yielding progress pull",function() world(function(x) + x.delay=true + E.ReadingSync.run("open") + eq(#x.commands,1); eq(x.commands[1].op,"sync.capture") + eq(W.shown[1],x.ui); eq(ReaderUI.instance,x.ui); eq(#x.moves,0) + x.callbacks[1](); eq(x.commands[2].op,"sync.decide") + eq(W.shown[1],x.ui,"yielding companion never clears the reader") + eq(#x.moves,0,"no silent jump after render") + end) end) + test("position consent: one popup, Yes uses the companion answer, No never moves",function() world(function(x) + E.ReadingSync.run("open"); run(1) + local prompt=E.ReadingSync.prompt; ok(prompt) + eq(prompt.widget.text,"Continue from fixture reader, p. 214?") + E.ReadingSync.present({applied="ask",token=x.snapshot.token,document="toy:one",remote=x.snapshot.remote},x.ui) + eq(E.ReadingSync.prompt,prompt,"same remote place draws only once") + prompt.widget.cancel_callback(); run(1) + eq(#x.moves,0); eq(x.commands[#x.commands].op,"sync.answer"); eq(x.commands[#x.commands].args.yes,false) + E.ReadingSync.present({applied="ask",token="new-place",document="toy:one",remote=x.snapshot.remote},x.ui) + E.ReadingSync.prompt.widget.ok_callback(); run(1) + eq(#x.moves,1); eq(x.page,214) + eq(x.commands[#x.commands].args.yes,true) + end) end) + test("position consent: a cancelled or different document rejects late results",function() world(function(x) + E.ReadingSync.run("open"); run(1) + x.delay=true; E.ReadingSync.prompt.widget.ok_callback() + x.ui.document={file="/fixture/other.epub"} + x.callbacks[1](); eq(#x.moves,0,"accepted old-document result cannot move the new document") + end) end) + test("position preview: known forward placement moves before draw; worker owns the decision",function() world(function(x) + x.preview_result={applied="now",document="toy:one",token=x.snapshot.token,remote=x.snapshot.remote} + E.ReadingSync.preview(x.ui) + eq(x.page,214); eq(E.ReadingSync.prompt,nil) + eq(x.preview_args.remote_page,214); eq(x.preview_args.marker_page,100) + eq(x.commands[1].op,"sync.answer","marker acknowledgment goes back to the owner") + eq(x.commands[1].args.yes,true) + end) end) + test("position wake: a sleep-deferred move is asked from local state before network work",function() world(function(x) + x.snapshot.pending=true + E.ReadingSync.resume(x.ui); run(1) + eq(x.commands[1].op,"sync.decide"); eq(x.commands[1].args.moment,"wake-local") + ok(E.ReadingSync.prompt); eq(#x.moves,0) + end) end) + test("position decision: replacing the native document rejects delayed consent and verification",function() world(function(x) + x.delay=true + E.ReadingSync.run("open"); x.callbacks[1]() + eq(x.commands[2].op,"sync.decide") + x.ui.document={file="/fixture/other.epub"} + x.callbacks[2]() + eq(E.ReadingSync.prompt,nil); eq(#x.commands,2); eq(#x.moves,0) + end) end) + test("position decision: changing mode rejects the old in-flight decision",function() world(function(x) + x.delay=true + E.ReadingSync.run("open"); x.callbacks[1]() + E.S.sync_mode="custom"; E.ReadingSync.modeChanged() + x.callbacks[2]() + eq(E.ReadingSync.prompt,nil); eq(#x.commands,2); eq(#x.moves,0) + end) end) + test("position capture: a close arriving during another sync is not dropped",function() world(function(x) + x.delay=true + E.ReadingSync.run("open"); E.ReadingSync.run("close") + eq(#x.commands,2); eq(x.commands[1].op,"sync.capture"); eq(x.commands[2].op,"sync.capture") + eq(x.commands[2].args.moment,"close") + eq(x.commands[2].args.position,"/p120") + end) end) + test("position command: companion restart reactivates before retrying immutable capture",function() world(function(x) + local command=E.Library.positionCommand + local attempts=0 + E.Library.positionCommand=function(op,args,done) + if op=="sync.capture" then + attempts=attempts+1 + if attempts==1 then table.insert(x.commands,{op=op,args=args}); done({error="writer-active"}); return true end + end + return command(op,args,done) + end + E.ReadingSync.command("sync.capture",{path="/fixture/one.epub",percentage=.4,online=false},function() end) + run(1) + eq(x.commands[1].op,"sync.capture"); eq(x.commands[2].op,"sync.activate"); eq(x.commands[3].op,"sync.capture") + eq(x.commands[1].args,x.commands[3].args,"same immutable native capture is retried") + end) end) + test("position close: native locator is captured before ReaderUI clears the document",function() world(function(x) + local m=setmetatable({ui=x.ui},{__index=E.OrbitAndroid}) + m:onCloseDocument() + x.ui.document=nil + run(1) + eq(x.commands[1].op,"sync.capture"); eq(x.commands[1].args.position,"/p120") + eq(x.commands[1].args.online,false); eq(m.closed_file,"/fixture/one.epub") + end) end) + test("position verification: one row resolves at most two native locators without moving",function() world(function(x) + local command=E.Library.positionCommand + local requested=false + E.Library.positionCommand=function(op,args,done) + if op=="sync.verify.next" then + if not requested then requested=true; done({row={key="fixture",start="/p10",["end"]="/p11"}}) + else done({}) end + return true + end + return command(op,args,done) + end + E.ReadingSync.verify(x.ui,"toy:one"); run(1) + eq(x.commands[1].op,"sync.verify.result"); eq(x.commands[1].args.valid,true); eq(x.commands[1].args.page,10) + eq(#x.moves,0) + end) end) + test("settings: Off reading cadence adds no hidden position-sync pause timer",function() world(function(x) + local m=setmetatable({ui=x.ui,schedule=E.Schedule.new("off",E.now_s())},{__index=E.OrbitAndroid}) + for page=1,60 do m:onPageUpdate(page) end + run(121); eq(#x.commands,0) + end) end) + test("position sync: no old marker/override/decline table is mutated in the reader",function() world(function(x) + local old=E.S.orbismart; local before=old and E.Cache.encode(old) + E.ReadingSync.readFromHere("test"); run(1) + eq(x.commands[1].op,"sync.override") + eq(old and E.Cache.encode(old),before) + local b=E.Budgets.get("screens","position-consent") + eq(b.rows,1); eq(b.bytes,16384); eq(b.roundTrips,1); eq(b.spawns,0); eq(b.network,0) + end) end) +end diff --git a/android/koreader/test/reader_panel_flows.lua b/android/koreader/test/reader_panel_flows.lua index 4896b381..1bbbc8ab 100644 --- a/android/koreader/test/reader_panel_flows.lua +++ b/android/koreader/test/reader_panel_flows.lua @@ -267,39 +267,18 @@ return function(here, test, ok, eq) E.Library.readerAction(W.ui,"clock"); E.Library.readerAction(W.ui,"status") eq(session.top_visible,true); eq(session.bottom_visible,true); eq(W.relayout,4) end) - test("reader Sync adapter: existing writer, offline, document change and late timeout",function() + test("reader Sync adapter: explicit sync uses the companion owner",function() local ui={document={file="fixture.epub"},view={footer={percent_finished=0.73}}} - local up, reply, timeout, done, message, sent, released - sent,released=0,0 - local E={liveUI=function() return ui end, serverPlugin=function() return {} end, - hasHandler=function() return true end, - Wifi={acquire=function() end,release=function() released=released+1 end}, - Net={up=function(_,_,cb) up=cb end}, - UIManager={scheduleIn=function(_,_,cb) timeout=cb end}, - pluginEvent=function(_,_,event,options) - eq(event,"BookOrbitSyncBook"); eq(options.quiet,true) - sent=sent+1; reply=options.on_done - end} - setfenv(assert(loadfile(here.."/../orbit.koplugin/ko/server/bookorbit.lua")),setmetatable(E,{__index=_G}))() - E.serverPlugin=function() return {} end - E.liveUI=function() return ui end + local called,reply,done,message + local E={liveUI=function() return ui end,ReadingSync={run=function(moment,callback) called=moment; reply=callback; return true end}} setfenv(assert(loadfile(here.."/../orbit.koplugin/ko/library.lua")),setmetatable(E,{__index=_G}))() eq(E.LibraryAdapter.readerPosition("fixture.epub"),0.73) eq(E.LibraryAdapter.readerPosition("other.epub"),nil) - ui.view.footer.percent_finished=0/0 - eq(E.LibraryAdapter.readerPosition("fixture.epub"),nil) - ui.view.footer.percent_finished=0 - eq(E.LibraryAdapter.readerPosition("fixture.epub"),0) - local function complete(ok,text) done,message=ok,text end - E.Server.syncCurrent(complete); up(false) - eq(sent,0); eq(released,1); eq(done,false); eq(message,"Offline · will sync when connected") - E.Server.syncCurrent(complete); ui.document={file="other.epub"}; up(true) - eq(sent,0); eq(released,2); eq(done,false) - E.Server.syncCurrent(complete); up(true) - eq(sent,1); reply(nil); eq(done,true); eq(message,"Synced"); eq(released,3) - timeout(); eq(released,3,"late timer cannot complete twice") - E.Server.syncCurrent(complete); up(true); timeout() - eq(done,false); eq(released,4); reply(nil); eq(released,4) + ui.view.footer.percent_finished=0/0; eq(E.LibraryAdapter.readerPosition("fixture.epub"),nil) + E.LibraryAdapter.syncCurrent(function(ok,text) done,message=ok,text end) + eq(called,"manual"); reply(false,"Offline · saved"); eq(done,false); eq(message,"Offline · saved") + E.LibraryAdapter.syncCurrent(function(ok,text) done,message=ok,text end) + reply(true); eq(done,true); eq(message,"Synced") end) local function styleReader(W) diff --git a/android/koreader/test/test_flows.lua b/android/koreader/test/test_flows.lua index da298259..84da6706 100644 --- a/android/koreader/test/test_flows.lua +++ b/android/koreader/test/test_flows.lua @@ -303,6 +303,7 @@ local PluginLoader = {} function PluginLoader:loadPlugins() return { { name = "bookorbit" } }, {} end function PluginLoader:genPluginManagerSubItem() return self:loadPlugins() end function PluginLoader:getPluginInstance() return nil end +function PluginLoader:createPluginInstance(plugin, attr) return true,plugin:new(attr) end local ReaderUI, FileManager = {}, {} function ReaderUI:showReader(file) W.opened = file end @@ -411,7 +412,7 @@ local preload = { mkdir = function(dir) sh("mkdir -p", dir) return true end }, json = { decode = function(s) if W.json[s] then return W.json[s] end return { version = "1" } end }, -- Stand-in hash: "sha:" padded, enough to check the wiring (the real one is ffi/sha2). - ["ffi/sha2"] = { sha256 = function(s) return W.fake_sha(s) end }, + ["ffi/sha2"] = { sha256 = function(s) return W.fake_sha(s) end, md5=function(s) return W.fake_sha(s):sub(1,32) end }, } for k, v in pairs(preload) do package.preload[k] = function() return v end end @@ -631,6 +632,33 @@ store.orbit_android.open_book_at_exit = "/books/killed.epub" store.orbit_android.sync_mode = "custom" local PLUGIN_MAIN = here .. "/../orbit.koplugin/main.lua" local Orbit = dofile(PLUGIN_MAIN) +-- Neutral companion port. Policy is tested against the real Kotlin owner/shared fixtures; +-- these native flows control only the asynchronous response and never emulate server JSON. +local SYNC_OPS={ ["sync.activate"]=true,["sync.capture"]=true,["sync.override"]=true,["sync.pull"]=true, + ["sync.decide"]=true,["sync.drain"]=true,["sync.answer"]=true,["sync.verify.next"]=true,["sync.verify.result"]=true } +local SyncEnv=getfenv(Orbit.onSuspend) +local stockCommand=SyncEnv.LibraryAdapter.command +SyncEnv.LibraryAdapter.command=function(op,args,done) + if not SYNC_OPS[op] then return stockCommand(op,args,done) end + W.sync_commands=W.sync_commands or {}; table.insert(W.sync_commands,{op=op,args=args}) + if op=="sync.capture" or op=="sync.override" then + W.sync_captures=W.sync_captures or {}; table.insert(W.sync_captures,args) + end + UIManager:scheduleIn(0.01,function() + if W.sync_reply then return done(W.sync_reply(op,args)) end + if op=="sync.activate" then return done({ok=true}) end + if op=="sync.capture" or op=="sync.override" or op=="sync.pull" then + if args.online==false then return done({queued=true}) end + if W.server_code==nil then return done({error="offline"}) end + return done({document="toy:document",snapshot={token="toy:place",remote={percentage=0.4,position="/p120",at=10}}}) + end + if W.server_code==nil then return done({error="offline"}) end + if op=="sync.answer" then return done({move=args.yes,remote={percentage=0.4,position="/p120"}}) end + return done({decision="push",applied="no",remaining=0}) + end) + return true +end + -- Historical upstream Home compatibility scenarios explicitly exercise that path. assert(store.orbit_android.home_screen == "booksync", "fresh 0.12 defaults to owned Home") store.orbit_android.home_screen = "server" @@ -641,7 +669,7 @@ local ADDON = { "install", "setup", "stats", "relaunch" } local FULL = { "install", "setup", "stats", "relaunch", "home", "apps", "wifi", "sleep_sync", "screen_off", "clicker", "pin" } local function capsFile(mode, caps) local f = io.open(CAPS_FILE, "wb") - if mode then f:write("CAPSFILE"); W.json.CAPSFILE = { proto = "1", mode = mode, caps = caps } end + if mode then f:write("CAPSFILE"); W.json.CAPSFILE = { proto = "1", mode = mode, caps = caps, version=SyncEnv.PATCH_VERSION } end f:close() end do @@ -703,49 +731,34 @@ test("dispatcher actions are registered", function() end end) -test("start: network up, then drain and pull with the debounce cleared", function() - W.broadcasts = {} - local ui = newUI(true) - run(30) - local p = ui.bookorbit - ok(lastBroadcast(".NET_UP"), "NET_UP sent") - ok(lastBroadcast(".NET_UP").extras.reason == "start", "reason start") - ok(has(p.calls, "drain:orbit_start"), "drain") - ok(has(p.calls, "pull:orbit_start:0"), "pull") - ok(W.probed == "https://books.example.test", "probed server") +test("start: network preparation dispatches only neutral companion sync", function() + W.sync_commands={}; W.probed=nil + local ui=newUI(true); run(30) + ok(lastBroadcast(".NET_UP"),"network preparation") + ok(#W.sync_commands>0,"companion command dispatched") + ok(not has(ui.bookorbit.calls,"drain:orbit_start"),"retired writer untouched") + eq(W.probed,nil,"no plugin HTTP probe") end) -test("plugin's Push while reading is off while Sync while reading is on, then restored", function() - local ui, m = newUI(true) - local p = ui.bookorbit - p.settings.pages_before_update = 7 - store.orbit_android.reading_schedule = "pg25" - m:hookPluginPagePush() - ok(p.settings.pages_before_update == 0, "off while ours is on") - ok(store.orbit_android.saved_pages_before_update == 7, "kept the reader's value") - m:hookPluginPagePush() -- again (another UI): still kept - ok(store.orbit_android.saved_pages_before_update == 7, "not overwritten by 0") - store.orbit_android.reading_schedule = "off" - m:hookPluginPagePush() - ok(p.settings.pages_before_update == 7, "restored") - ok(store.orbit_android.saved_pages_before_update == nil, "forgotten") - p.settings.pages_before_update = nil +test("sync retirement: legacy classes and API entry points are inert before instances start", function() + local original=package.loaded.bookorbit_api + local called=0 + package.loaded.bookorbit_api={request=function() called=called+1 end,updateProgress=function() called=called+1 end} + local plugin={name="bookorbit",new=function(self) return self end,requestLifecycleOutboxDrain=function() called=called+1 end} + local yes,instance=PluginLoader:createPluginInstance(plugin,{}) + ok(yes); instance:requestLifecycleOutboxDrain("startup") + package.loaded.bookorbit_api:updateProgress("digest",.5) + package.loaded.bookorbit_api:request("PUT","retired") + eq(called,0,"old code never runs") + package.loaded.bookorbit_api=original end) -test("suspend with the screen off: plugin drain, wait, NET_DONE ok", function() - W.broadcasts = {} - W.screen_on = false - local ui, m = newUI(true) - run(5) - local p = ui.bookorbit - p.calls = {} - p.pending = 1 - m:onSuspend() - run(30) - ok(has(p.calls, "drain:orbit_sleep"), "drain") - local done = lastBroadcast(".NET_DONE") - ok(done and done.extras.ok == "1", "NET_DONE ok") - ok(store.orbit_android.last_sleep_sync.ok == true, "recorded") +test("suspend with the screen off: companion capture, drain and NET_DONE", function() + W.screen_on=false; W.sync_captures={}; W.broadcasts={} + local ui,m=newUI(true); run(5); m:onSuspend(); run(30) + ok(#W.sync_captures>0,"native capture saved") + local done=lastBroadcast(".NET_DONE"); ok(done and done.extras.ok=="1","sync complete") + ok(not has(ui.bookorbit.calls,"onSuspend"),"retired snapshot not called") end) test("suspend with the screen on (app switch): no sleep sync", function() @@ -775,19 +788,13 @@ test("suspend: server never answers -> NET_DONE not ok at the cap", function() W.server_code = 200 end) -test("sync and sleep: plugin snapshot, then SLEEP_NOW, and the following Suspend is skipped", function() - W.broadcasts = {} - local ui, m = newUI(true) - run(30) - W.broadcasts = {} - m:onOrbitSyncAndSleep() - run(5) -- (the Wi-Fi timer keeps the fake clock running; the skip window is 15 s) - ok(has(ui.bookorbit.calls, "onSuspend"), "plugin _onSuspend") - ok(lastBroadcast(".SLEEP_NOW"), "SLEEP_NOW") - local n = #W.broadcasts - m:onSuspend() - run(10) - ok(#W.broadcasts == n, "suspend after sync-and-sleep skipped") +test("sync and sleep: companion capture then sleep; the following sleep sync is skipped", function() + local ui,m=newUI(true); run(30); W.broadcasts={}; W.sync_captures={} + m:onOrbitSyncAndSleep(); run(5) + ok(#W.sync_captures>0,"captured through companion") + ok(lastBroadcast(".SLEEP_NOW"),"screen off") + local n=#W.broadcasts; m:onSuspend(); run(10) + eq(#W.broadcasts,n,"no second sleep flow") end) test("sync and sleep failure: message, then sleep anyway", function() @@ -829,32 +836,24 @@ test("wifi turn-on goes to the companion, not Android settings", function() ok(not W.settings_opened, "settings not opened") end) -test("sync while reading, every 25 pages: push when this device is ahead", function() - store.orbit_android.reading_schedule = "pg25" - local ui, m = newUI(true) - run(30) - local p = ui.bookorbit - p.calls = {} - p.remote = { digest = "d1", percentage = 0.4 } - for pg = 1, 25 do m:onPageUpdate(pg) end +test("sync while reading: page cadence delegates to the companion", function() + store.orbit_android.reading_schedule="pg25" + local ui,m=newUI(true); run(30); W.sync_captures={} + for page=1,25 do m:onPageUpdate(page) end run(30) - ok(has(p.calls, "fetch"), "fetched") - ok(has(p.calls, "push:orbit_reading"), "pushed") - store.orbit_android.reading_schedule = "off" + ok(#W.sync_captures>0,"capture dispatched") + ok(not has(ui.bookorbit.calls,"fetch"),"no old API") + store.orbit_android.reading_schedule="off" end) -test("sync while reading, every chapter: Ask + server ahead never pulls or prompts", function() - store.orbit_android.reading_schedule = "ch1" - local ui, m = newUI(true) +test("sync while reading: chapter cadence never invokes the retired client", function() + store.orbit_android.reading_schedule="ch1" + local ui,m=newUI(true); run(30); W.sync_captures={} + for page=5,12 do m:onPageUpdate(page) end run(30) - local p = ui.bookorbit - p.calls = {} - p.remote = { digest = "d1", percentage = 0.9 } - for pg = 5, 12 do m:onPageUpdate(pg) end - run(30) - ok(has(p.calls, "fetch"), "fetched") - ok(count(p.calls, function(c) return c:match("^pull") or c:match("^push") end) == 0, "no pull/push") - store.orbit_android.reading_schedule = "off" + ok(#W.sync_captures>0,"capture dispatched") + ok(not has(ui.bookorbit.calls,"fetch"),"no old API") + store.orbit_android.reading_schedule="off" end) test("home from the companion: library home opens over the book, which stays open", function() @@ -888,32 +887,19 @@ test("menu is its own Tools entry, not inside the plugin's menu, and builds", fu end end) -test("pull debounce: cleared only when the last pull was within 25 s", function() - local ui, m = newUI(true) - run(30) - local p = ui.bookorbit - p.pull_timestamp = W.clock * 1e6 - 5e6 -- 5 s ago - p.calls = {} - m:wakeFlow("wake") - run(5) - ok(has(p.calls, "pull:orbit_wake:0"), "recent pull: debounce cleared") - p.pull_timestamp = W.clock * 1e6 - 100e6 -- 100 s ago - local before = p.pull_timestamp - p.calls = {} - m:wakeFlow("wake") - run(5) - ok(has(p.calls, "pull:orbit_wake:" .. before), "old pull: left alone") - p.pull_timestamp = 0 +test("sync: retired debounce state is never read or changed", function() + local ui,m=newUI(true); ui.bookorbit.pull_timestamp=1234 + m:wakeFlow("retry"); run(30) + eq(ui.bookorbit.pull_timestamp,1234) + ok(not has(ui.bookorbit.calls,"pull:orbit_retry:0")) end) -test("test sync path reports five steps", function() - local ui, m = newUI(false) - run(30) - W.shown = {} - m:testSyncPath() - run(30) - local viewer = W.shown[#W.shown] - ok(viewer and viewer.text and viewer.text:match("5%. library plugin synced ✓"), viewer and viewer.text or "no viewer") +test("test sync path reports companion-owned delivery", function() + local ui,m=newUI(true); run(30); W.shown={}; W.sync_commands={} + m:testSyncPath(); run(30) + ok(#W.sync_commands>0,"worker tested") + local text=""; for _,w in ipairs(W.shown) do text=text..tostring(w.text or "") end; ok(text:find("Companion",1,true),text) + ok(not has(ui.bookorbit.calls,"fetch"),"no upstream test sync") end) ---------------------------------------------------------------- Wi-Fi modes (v0.2) @@ -2181,39 +2167,25 @@ test("home button menu says it is about KOReader, and notes the companion's Home ok(not homeText():find("(", 1, true), "no companion: no note") end) -test("compat: a check that found something missing early doesn't stick", function() - local ui, m = newUI(true) - local q = newPlugin() - local drain, outbox = q.requestLifecycleOutboxDrain, q.getLifecycleOutbox - q.getLifecycleOutbox, q.requestLifecycleOutboxDrain, q.PLUGIN_VERSION = nil, nil, "9.9.8" - ui.bookorbit = q - ok(m:statusText():find("BookOrbit 9.9.8 changed", 1, true), "missing at first") - q.getLifecycleOutbox, q.requestLifecycleOutboxDrain = outbox, drain -- the plugin finished init - ok(not m:statusText():find("BookOrbit 9.9.8 changed", 1, true), "re-checked: " .. m:statusText()) +test("compat: missing retired sync APIs do not disable owned sync", function() + local ui,m=newUI(true) + ui.bookorbit.getLifecycleOutbox=nil; ui.bookorbit.requestLifecycleOutboxDrain=nil + W.sync_commands={}; m:readingSync(); run(30) + ok(#W.sync_commands>0,"own sync remains available") end) -test("compat: a plugin without its outbox API -> sleep sync leaves it to the plugin, no error", function() - local ui, m = newUI(true) - local q = newPlugin() - q.getLifecycleOutbox, q.requestLifecycleOutboxDrain, q.PLUGIN_VERSION = nil, nil, "9.9.9" - ui.bookorbit = q - W.broadcasts = {} - m:sleepSync("sleep") - run(30) - local done = lastBroadcast(".NET_DONE") - ok(done and done.extras.ok == "1", "NET_DONE ok") - ok(m:statusText():find("BookOrbit 9.9.9 changed: wake and sleep syncs use the plugin's own sync", 1, true), - "menu status: " .. m:statusText()) +test("compat: sleep sync uses the companion without an upstream outbox", function() + local ui,m=newUI(true); run(5) + ui.bookorbit=nil; W.broadcasts={} + m:sleepSync("sleep"); run(30) + local done=lastBroadcast(".NET_DONE"); ok(done and done.extras.ok=="1","no upstream dependency") end) -test("compat: a plugin without fetchRemoteProgress -> Sync while reading does nothing", function() - local ui, m = newUI(true) - local q = newPlugin(); q.fetchRemoteProgress = nil - ui.bookorbit = q - m:readingSync() - run(30) - ok(not has(q.calls, "fetch"), "no fetch") - ok(m:statusText():find("Sync while reading is off", 1, true), "status says so") +test("compat: reading sync does not require an upstream progress API", function() + local ui,m=newUI(true); ui.bookorbit.fetchRemoteProgress=nil + W.sync_commands={}; m:readingSync(); run(30) + ok(#W.sync_commands>0,"neutral sync called") + ok(not has(ui.bookorbit.calls,"fetch")) end) test("compat: a catalog without dashboardMode -> not treated as library home", function() @@ -3311,18 +3283,19 @@ test("background notices: start and wake pulls are silent, including delayed cal local burst, restore, Trapper = noticeFixture() local ui, m = newUI(false) local p = ui.bookorbit - local pulls = 0 - function p:requestLifecycleOutboxDrain() - pulls = pulls + 1 - burst("pull") - UIManager:nextTick(function() burst("delayed pull") end) - Trapper:wrap(function() - burst("coroutine pull") - local co = coroutine.running() - UIManager:scheduleIn(0.1, function() assert(coroutine.resume(co)) end) - coroutine.yield() - burst("resumed pull") - end) + local pulls=0 + local command=E.LibraryAdapter.command + E.LibraryAdapter.command=function(op,args,done) + if op=="sync.capture" or op=="sync.drain" then + pulls=pulls+1; burst("pull") + UIManager:nextTick(function() burst("delayed pull") end) + Trapper:wrap(function() + burst("coroutine pull"); local co=coroutine.running() + UIManager:scheduleIn(0.1,function() assert(coroutine.resume(co)) end) + coroutine.yield(); burst("resumed pull") + end) + end + return command(op,args,done) end local started = E.state.started E.state.started = false @@ -3344,6 +3317,7 @@ test("background notices: start and wake pulls are silent, including delayed cal burst("explicit action") ok(#W.shown > 0 and noticeLog("notice: shown: explicit action: direct InfoMessage"), "user notices show and log text after background finishes") E.state.started = started + E.LibraryAdapter.command=command restore() end) @@ -3525,19 +3499,14 @@ test("end of book: a finish marked here leaves Continue reading at once (plugin E.LocalState.data.books["d1"] = nil end) -test("outbox: an entry backing off (not drainable) neither holds Wi-Fi nor runs the wait to its cap", function() - local ui = newUI(true) - local p = ui.bookorbit - p.getLifecycleOutbox = function() return { diagnostics = function() return { count = 1, blocked = 0, drainable = 0 } end } end - local done_at - local t0 = W.clock - E.Sync.waitOutbox(p, 20, function(okw) done_at = W.clock; W.wait_ok = okw end) - run(25) - ok(done_at and done_at - t0 < 2 and W.wait_ok, "done at once, not at the cap: " .. tostring(done_at and done_at - t0)) - local busy = E.Wifi.busy() - ok(not busy, "Wi-Fi not held for it") - p.getLifecycleOutbox = function() return { diagnostics = function() return { count = 1, blocked = 0, drainable = 1 } end } end - ok(E.Wifi.busy(), "a drainable entry still holds Wi-Fi") +test("outbox: completion releases the native sync lease without polling upstream diagnostics", function() + local ui,m=newUI(true); run(30); W.sync_commands={} + local completed=false + local env=getfenv(Orbit.onSuspend) + env.ReadingSync.run("manual",function() completed=true end) + run(1); ok(completed,"asynchronous command completed") + ok(not env.ReadingSync.busy,"native busy flag released") + ok(not has(ui.bookorbit.calls,"fetch")) end) test("end of book: a finished book's stale position is held", function() @@ -4095,28 +4064,18 @@ test("wifi: just in time keeps Wi-Fi on while BookOrbit's Home is over the book, E.Library.catalog_active=nil end) -test("suspend: a Home press (app switch) with the book unmoved skips BookOrbit's snapshot; a page turn, Sync and sleep always snapshot", function() - local snaps = 0 - local p = { last_page = 10 } - function p:getDocumentDigest() return "d1" end - function p:getLastPercent() return 0.25 end - function p:_onSuspend() snaps = snaps + 1 end - p.onSuspend = p._onSuspend - local ui = { annotation = { annotations = {} }, doc_settings = { readSetting = function() return { status = "reading" } end } } - local hosts, inter = E.serverPlugin, E.Jni.isInteractive - E.serverPlugin = function() return p end - E.Jni.isInteractive = function() return true end - E.state.last_snapshot_key = nil - local self = setmetatable({ ui = ui }, { __index = E.OrbitAndroid }) - self:hookSuspendSnapshot() - p:onSuspend(); p:onSuspend(); p:onSuspend() - ok(snaps == 1, "three Home presses, one snapshot: " .. snaps) - p.last_page = 11 - p:onSuspend() - ok(snaps == 2, "a page turned: snapshot") - E.state.force_snapshot = true; p:_onSuspend(); E.state.force_snapshot = nil - ok(snaps == 3, "Sync and sleep: always") - E.serverPlugin, E.Jni.isInteractive = hosts, inter +test("suspend: unchanged app switches coalesce native captures; real sleep always captures", function() + local ui,m=newUI(true); run(30) + local env=getfenv(Orbit.onSuspend); local interactive=env.Jni.isInteractive + env.Jni.isInteractive=function() return true end + env.ReadingSync.last_snapshot=nil; W.sync_captures={} + env.ReadingSync.queue("suspend",ui); env.ReadingSync.queue("suspend",ui); run(1) + eq(#W.sync_captures,1) + env.ReadingSync.last_page=11; env.ReadingSync.queue("suspend",ui); run(1) + eq(#W.sync_captures,2) + env.Jni.isInteractive=function() return false end + env.ReadingSync.queue("suspend",ui); run(1); eq(#W.sync_captures,3) + 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() @@ -4975,35 +4934,15 @@ test("reading: finish sync skips catalog calls and file writes, then completes o RE.reading, RE.EOB.usable = reading, usable end) -test("network: even an unanswered probe runs only in a background worker", function() +test("network: native preparation never probes a server or starts a subprocess", function() run(30) - local background, probe = RE.Background.run, RE.probeServer - local job, done - local jobs, probes = 0, 0 - RE.Background.run = function(name, fn, timeout, cb) - jobs = jobs + 1; job = { fn = fn, cb = cb } - end - RE.probeServer = function() - probes = probes + 1 - ok(W.in_child, "HTTP must never execute on the UI thread") - return false, "timeout" - end - uiWorkBudget(function() - RE.Net.up(newPlugin(), { reason = "tap regression", cap = 2, need_server = true }, function() done = true end) - end) - eq(jobs, 1, "one background job") - eq(probes, 0, "no synchronous probe") - ok(job and not done, "probe pending without blocking input") - W.in_child = true - local result = job.fn() - W.in_child = nil - -- The whole network budget elapsed while input remained available. - W.clock = W.clock + 2 - job.cb(result) - RE.Background.run, RE.probeServer = background, probe - ok(done and RE.Net.inflight == nil, "timeout completes, no synchronous retry") - eq(jobs, 1, "no retry job") - eq(probes, 1, "only the background probe ran") + local background=RE.Background.run; local jobs=0 + RE.Background.run=function() jobs=jobs+1 end + local done=false + uiWorkBudget(function() RE.Net.up(nil,{reason="tap regression",cap=2},function() done=true end) end) + RE.Background.run=background + ok(done,"network preparation complete"); eq(jobs,0,"zero subprocesses") + eq(RE.probeServer,nil,"no Lua transport primitive") end) test("main-loop diagnostics: slow callbacks log, preserve returns/errors and cancel by original identity", function() @@ -5035,514 +4974,12 @@ test("sqlite stress: the verdict line", function() ok(notes[1]:find("didn't answer") ~= nil) end) ----------------------------------------------------------------- OrbiSmart sync (docs/design/position-sync.md) --- A 300-page book; places are pages, xpointers "/p". The BookOrbit plugin's API client is --- a fake bookorbit_api (getProgress answers W.osm_server; updateProgress stores it), wrapped by --- ko/server/bookorbit/orbismart.lua like the real one. -local OSMApi = { puts = 0 } -function OSMApi:getProgress(d) return W.osm_server end -function OSMApi:updateProgress(d, pct, progress, ts) - OSMApi.puts = OSMApi.puts + 1 - W.osm_server = { percentage = pct, progress = progress, timestamp = ts, device = "M8C", device_id = "me" } - return { document = d, timestamp = ts } -end -package.loaded["bookorbit_api"] = OSMApi -local OSM = RE.OSM -local function osmLog(pat) - for i = #W.logs, 1, -1 do if W.logs[i]:find(pat, 1, true) then return W.logs[i] end end -end -local function osmPopup() - for i = #W.shown, 1, -1 do local w = W.shown[i]; if type(w) == "table" and w.ok_callback and w.cancel_callback then return w end end -end -local function osmAnswer(yes) - local w = osmPopup() - UIManager:close(w) -- KOReader's ConfirmBox closes itself, then runs the callback - if yes then w.ok_callback() else w.cancel_callback() end -end -local function osmServer(page, at, device) - W.osm_server = { percentage = page / 300, progress = "/p" .. page, timestamp = at, device = device or "Boox", device_id = "boox" } -end --- A book open on this reader at page `page`, OrbiSmart on, with what this reader knew before. -local function osmBook(page, rec) - store.orbit_android.sync_mode = "orbismart" - store.orbit_android.orbismart = { d1 = rec } - store.orbit_android.osm_saved_plugin = nil - W.page, W.logs, W.shown, OSMApi.puts = page, {}, {}, 0 - W.osm_server = nil - local ui, m = newUI(true) - ui.document.info = {} - function ui.document:getPageCount() return 300 end - function ui.document:getCurrentPage() return W.page end - function ui.document:getPageFromXPointer(xp) return tonumber(xp:match("%d+")) end - ui.doc_settings = { readSetting = function(_, k) if k == "summary" then return { status = W.osm_status } end end } - local p = ui.bookorbit - p.device_id = "me" - function p:getLastPercent() return W.page / 300 end - function p:getLastProgress() return "/p" .. W.page end - function p:syncToProgress(progress) W.page = tonumber(progress:match("%d+")); table.insert(p.calls, "goto:" .. W.page) end - function p:noteProgressCompared() end - function p:fetchRemoteProgress(d, cb) - table.insert(p.calls, "fetch") - local body = require("bookorbit_api"):getProgress(d) - p.last_remote_progress = body and { digest = d, percentage = body.percentage, progress = body.progress, timestamp = body.timestamp } or nil - UIManager:nextTick(function() cb(body ~= nil) end) - end - function p:requestProgressPush(_, _, src) - table.insert(p.calls, "push:" .. src) - require("bookorbit_api"):updateProgress("d1", W.page / 300, "/p" .. W.page, os.time()) - end - return ui, m, p -end -local function osmRec() return store.orbit_android.orbismart.d1 end - --- KOReader doShowReader constructs ReaderUI in a coroutine, sends ReaderReady during --- init, then shows it. BookOrbit runInSyncCoroutine reuses ANY current coroutine --- (Trapper:isWrapped), and its background GET yields until the first 125 ms poll. --- An empty window stack exits UIManager before that poll can resume construction. -test("startup smoke: last document remains the top reader through a yielding progress pull", function() - W.queue, W.shown = {}, {} - capsReset() - W.wifi, W.vpn, W.server_code = true, true, 200 - W.radio = true - RE.Net.inflight, RE.state.started = nil, nil - store.lastfile = "/b.epub" - store.orbit_android.open_book_at_exit = store.lastfile - store.orbit_android.wifi_mode = "jit" - RE.Wifi.plan = nil - local ui, m, p = osmBook(120, nil) - local closes, quits = 0, W.quits or 0 - local stock_close = UIManager.close - UIManager.close = function(self, w, ...) - if w == ui then closes = closes + 1 end - return stock_close(self, w, ...) - end - W.after_fail = function() UIManager.close = stock_close end - -- Host LuaJIT builds with Lua 5.2 compatibility may return (main_thread, true) - -- on the main thread. KOReader's Trapper expects Lua 5.1's nil there. - local function running() - local co, main = coroutine.running() - return not main and co or nil - end - local Trapper = { - isWrapped = function() return running() ~= nil end, - wrap = function(_, fn) - local resumed, err = coroutine.resume(coroutine.create(fn)) - assert(resumed, err) - end, - } - -- CI also runs this case with the pinned KOReader's actual Trapper methods. - local checkout = os.getenv("ORBIT_KOREADER_SOURCE") - if checkout then - local chunk = assert(loadfile(checkout .. "/frontend/ui/trapper.lua")) - local co_api = setmetatable({ running = running }, { __index = coroutine }) - setfenv(chunk, setmetatable({ coroutine = co_api, require = function(name) - if name == "string.buffer" then return {} end - return require(name) - end }, { __index = _G })) - Trapper = chunk() - UIManager.preventStandby, UIManager.allowStandby = function() end, function() end - end - local started, completed = 0, 0 - function p:fetchRemoteProgress(_, cb) - local function fetch() - started = started + 1 - local co = coroutine.running() - UIManager:scheduleIn(0.125, function() - local resumed, err = coroutine.resume(co) - assert(resumed, err) - end) - coroutine.yield() - completed = completed + 1 - cb(false) - end - if Trapper:isWrapped() then return fetch() end - return Trapper:wrap(fetch) - end - -- The opening message has expired; the reader is the only persistent window. - local co = coroutine.create(function() - m:onReaderReady() - UIManager:show(ui) - end) - local resumed, err = coroutine.resume(co) - ok(resumed, err) - eq(UIManager:getTopmostVisibleWidget(), ui, "ReaderReady must finish before yielding network work") - eq(coroutine.status(co), "dead", "reader construction completed") - eq(started, 0, "network pull deferred until after construction") - run(30) - ok(started > 0, "progress pull actually ran") - eq(completed, started, "yielding pulls resumed and completed") - eq(UIManager:getTopmostVisibleWidget(), ui, "reader stays on top after open and wake tasks") - eq(closes, 0, "no reader close requested") - eq(W.quits or 0, quits, "no exit requested") - UIManager.close = stock_close - store.orbit_android.sync_mode = "custom" -end) +---------------------------------------------------------------- Companion-owned position sync -test("orbismart: before render, a further place already known opens there with no popup", function() - local ui, m, p = osmBook(120, { server = { at = 5000, pct = 214 / 300, progress = "/p214", device = "Boox" } }) - m:onReaderReady() - eq(W.page, 214, "opened at the further place") - ok(osmLog("orbismart: rule3 L=120 R=214 -> take (prerender, now)"), "decision logged") - run(30) - eq(osmPopup(), nil, "no popup") -end) - -test("orbismart: after render, a further place asks; Yes moves there", function() - local ui, m, p = osmBook(120, nil) - m:onReaderReady() - run(5) - osmServer(214, 5000) - p:fetchRemoteProgress("d1", function() end) - run(2) - local w = osmPopup() - ok(w, "popup") - eq(w.text, "Continue from Boox, p. 214?") - eq(w.ok_text, "Yes"); eq(w.cancel_text, "No") - eq(W.page, 120, "not moved before the answer") - ok(osmLog("orbismart: rule3 L=120 R=214 -> take (open, ask)"), "decision logged") - osmAnswer(true) - eq(W.page, 214, "moved") - eq(osmRec().m.at, 5000, "marker") - ok(osmLog("orbismart: popup 120->214 yes"), "answer logged") -end) - -test("orbismart: after render, No stays, pushes nothing and never asks again for that place", function() - local ui, m, p = osmBook(120, nil) - m:onReaderReady() - run(5) - osmServer(214, 5000) - p:fetchRemoteProgress("d1", function() end) - run(2) - osmAnswer(false) - eq(W.page, 120, "stayed") - eq(osmRec().declined_at, 5000, "declined") - eq(osmRec().override, nil, "No is not an override") - p:fetchRemoteProgress("d1", function() end) - run(2) - eq(osmPopup(), nil, "not asked again") - ok(osmLog("orbismart: declined L=120 R=214 -> stay (open, no)"), "declined logged") - eq(OSMApi.puts, 0, "nothing pushed") - -- A newer place elsewhere asks again. - osmServer(230, 5200) - p:fetchRemoteProgress("d1", function() end) - run(2) - ok(osmPopup() and osmPopup().text == "Continue from Boox, p. 230?", "a newer place asks") - osmAnswer(false) -end) - -test("orbismart: No declines a standing reset until normal progress returns", function() - local ui, m, p = osmBook(120, {}) - run(1) - OSM.installApi() - local function reset(at) - OSM.onPulled("d1", { percentage = 0, progress = "/p0", timestamp = at, - device = "web", device_id = "bookorbit-web" }) - run(1) - end - reset(5000) - ok(OSM.popup, "reset asks") - osmAnswer(false) - reset(5001) - eq(OSM.popup, nil, "same standing reset was only re-dated") - OSM.onPulled("d1", { percentage = 0.4, progress = "/p120", timestamp = 6000, device_id = "other" }) - run(1) - eq(osmRec().declined_reset, nil, "normal progress ends the declined reset") - reset(7000) - ok(OSM.popup, "a later reset asks again") - osmAnswer(false) -end) - -test("orbismart: scheduled reading sync asks once, no silent jump", function() - local ui, m, p = osmBook(100, nil) - osmServer(100, 4000) - m:onReaderReady() - run(30) - eq(osmPopup(), nil, "same place: no popup") - for pg = 101, 110 do W.page = pg; m:onPageUpdate(pg) end - osmServer(214, 5000) - m:readingSync() - run(5) - ok(has(p.calls, "fetch"), "the pause pulled") - local w = osmPopup() - ok(w and w.text == "Continue from Boox, p. 214?", "asked") - eq(W.page, 110, "no silent jump mid-book") - ok(osmLog("orbismart: rule3 L=110 R=214 -> take (pause, ask)"), "logged as a pause") - osmAnswer(true) - eq(W.page, 214) -end) - -test("orbismart: scheduled reading sync where this reader is further pushes", function() - local ui, m, p = osmBook(100, nil) - osmServer(100, 4000) - m:onReaderReady() - run(30) - for pg = 101, 140 do W.page = pg; m:onPageUpdate(pg) end - m:readingSync() - run(5) - ok(has(p.calls, "push:orbismart"), "pushed") - eq(W.osm_server.progress, "/p140") - ok(osmLog("orbismart: rule4 L=140 R=100 -> push (pause, no)"), "logged") -end) - -test("orbismart: never push behind the server's place (the behind-hold), further goes", function() - local ui, m, p = osmBook(150, { server = { at = 5000, pct = 214 / 300, progress = "/p214" }, m = { at = 5000, pct = 214 / 300, progress = "/p214" } }) - run(1) - OSM.installApi() - p:requestProgressPush(false, false, "close") - eq(OSMApi.puts, 0, "held") - ok(osmLog("orbismart: push held L=150 R=214 (behind the server)"), "held logged") - -- The outbox's snapshot goes through the same client. - local body = require("bookorbit_api"):updateProgress("d1", 150 / 300, "/p150", 6000) - ok(body and body.orbit_held, "answered as done, not sent") - eq(OSMApi.puts, 0) - W.page = 230 - p:requestProgressPush(false, false, "close") - eq(OSMApi.puts, 1, "further: sent") - -- A closed book (no open document for it): compared by percent. - store.orbit_android.orbismart.d2 = { server = { at = 1, pct = 0.6 } } - require("bookorbit_api"):updateProgress("d2", 0.3, nil, 7000) - eq(OSMApi.puts, 1, "closed book held too") -end) - -test("orbismart: Read from here everywhere online: sent now, skipping the hold", function() - local ui, m, p = osmBook(50, { server = { at = 5000, pct = 214 / 300, progress = "/p214" }, m = { at = 5000, pct = 214 / 300, progress = "/p214" } }) - run(1) - OSM.installApi() - OSM.readFromHere("test") - run(30) - eq(OSMApi.puts, 1, "sent") - eq(W.osm_server.progress, "/p50", "the server has this place") - eq(osmRec().override, nil, "done") - ok(osmLog("orbismart: override sent"), "logged") -end) - -test("orbismart: Read from here everywhere offline: queued, then sent first at the next sync", function() - local ui, m, p = osmBook(50, { server = { at = 5000, pct = 214 / 300, progress = "/p214" }, m = { at = 5000, pct = 214 / 300, progress = "/p214" } }) - run(1) - OSM.installApi() - W.server_code = nil - OSM.readFromHere("test") - run(40) - W.server_code = 200 - ok(osmLog("orbismart: override queued (offline)"), "queued") - eq(OSMApi.puts, 0) - ok(osmRec().override, "still queued") - -- The next sync (a wake after a real sleep): the override decides first and goes. - osmServer(214, 5000) - RE.state.paused_for = 900 - m:wakeFlow("wake") - run(40) - ok(osmLog("orbismart: override L=50 R=214 -> override (wake, no)"), "decided first") - eq(W.osm_server.progress, "/p50", "sent") - eq(osmRec().override, nil) -end) - -test("orbismart: a released reread replaces a completed place short of the end once", function() - local ui, m, p = osmBook(50, { server = { at = 5000, pct = 0.9, progress = "/p270" } }) - run(1) - W.osm_status = "complete" - RE.EOB.session.d1 = { released = true, forward = 10 } - OSM.installApi() - OSM.decide("pause") - eq(W.osm_server.progress, "/p50", "released reread starts behind completed place") - require("bookorbit_api"):updateProgress("d1", 0.1, "/p30", 4000) - eq(OSMApi.puts, 1, "exemption consumed after successful push") - W.osm_status = nil -end) - -test("orbismart: a finished-book override is one shot and later stale pushes stay held", function() - local ui, m, p = osmBook(50, { server = { at = 5000, pct = 1, progress = "/p300" } }) - run(1) - W.osm_status = "complete" - OSM.installApi() - OSM.readFromHere("test") - run(30) - eq(W.osm_server.progress, "/p50", "backward override starts reread") - require("bookorbit_api"):updateProgress("d1", 0.1, "/p30", 4000) - eq(OSMApi.puts, 1, "reread release cannot exempt another backward push") - W.osm_status = nil -end) - -test("orbismart: offline override sends the chosen place before an older outbox snapshot", function() - local ui, m, p = osmBook(50, { server = { at = 5000, pct = 214 / 300, progress = "/p214" } }) - run(1) - OSM.installApi() - W.server_code = nil - OSM.readFromHere("test") - run(40) - eq(osmRec().override.progress, "/p50", "chosen place persisted") - W.page = 80 - W.server_code = 200 - require("bookorbit_api"):updateProgress("d1", 0.1, "/p30", 4000) - eq(W.osm_server.progress, "/p50", "override precedes the stale snapshot and later reading") - eq(osmRec().override, nil, "acknowledged once") - require("bookorbit_api"):updateProgress("d1", 0.1, "/p30", 4000) - eq(OSMApi.puts, 1, "stale snapshot is now held") -end) - -test("orbismart: a deferred pull cannot move or ask for a different open book", function() - local ui, m, p = osmBook(120, {}) - run(1) - OSM.installApi() - osmServer(214, 5000) - OSM.onPulled("d1", W.osm_server) - p.getDocumentDigest = function() return "d2" end - run(1) - eq(osmPopup(), nil) - eq(W.page, 120) -end) - -test("orbismart: a further place found at sleep is asked at wake, before any network", function() - W.screen_on = false - local ui, m, p = osmBook(120, nil) - osmServer(120, 4000) - m:onReaderReady() - run(30) - osmServer(214, 5000) - m:onSuspend() - run(30) - eq(osmPopup(), nil, "nothing shown at sleep") - ok(osmRec().pending, "kept for the wake") - ok(osmLog("orbismart: rule3 L=120 R=214 -> take (sleep, wake)"), "logged") - W.server_code = nil -- the wake's network never comes up - m:onResume() - local w = osmPopup() - ok(w and w.text == "Continue from Boox, p. 214?", "asked at once") - osmAnswer(true) - eq(W.page, 214) - run(40) - W.server_code = 200 -end) - -test("orbismart: an update keeps Custom for a reader whose sync settings were changed by hand", function() - local S0 = store.orbit_android - local saved = { S0.reading_schedule, S0.sync_mode, S0.settings_at.sync_mode } - S0.orbismart_migrated, S0.reading_schedule, S0.sync_mode, S0.settings_at.sync_mode = nil, "pg25", "orbismart", 1 - OSM.migrate() - eq(S0.sync_mode, "custom", "Sync while reading was set by hand") - ok(S0.settings_at.sync_mode > 1, "sent to the companion") - S0.orbismart_migrated, S0.reading_schedule, S0.sync_mode, S0.settings_at.sync_mode = nil, "off", "orbismart", 1 - OSM.migrate() - eq(S0.sync_mode, "orbismart", "untouched settings: OrbiSmart") - S0.orbismart_migrated, S0.reading_schedule, S0.settings_at.sync_mode = nil, "pg25", 5000 - OSM.migrate() - eq(S0.sync_mode, "orbismart", "a Sync value chosen already stays") - OSM.migrate() - S0.reading_schedule, S0.sync_mode, S0.settings_at.sync_mode = saved[1], saved[2], saved[3] -end) - -test("orbismart: no wake check after a short nap", function() - local ui, m, p = osmBook(120, nil) - run(30) - p.calls = {} - RE.state.paused_for = 60 - m:wakeFlow("wake") - run(30) - ok(not has(p.calls, "fetch"), "no pull") - ok(osmLog("no wake check under 300 s"), "logged") - RE.state.paused_for = nil -end) - -test("orbismart: a move back elsewhere (an override there) is asked, labelled", function() - local ui, m, p = osmBook(214, { server = { at = 4000, pct = 214 / 300, progress = "/p214" }, m = { at = 4000, pct = 214 / 300, progress = "/p214" } }) - m:onReaderReady() - run(5) - osmServer(12, 5000, "X4 Pro") - p:fetchRemoteProgress("d1", function() end) - run(2) - local w = osmPopup() - ok(w and w.text == "Continue from X4 Pro, p. 12 (moved back there)?", w and w.text) - osmAnswer(true) - eq(W.page, 12) -end) - -test("orbismart: OrbiSmart enables automatic lifecycle sync and Custom restores it", function() - local ui, m, p = osmBook(120, {}) - run(1) - p.settings.auto_sync = false - OSM.preset(p) - eq(p.settings.auto_sync, true, "lifecycle snapshots and drains enabled") - eq(OSM.savedPluginSetting("auto_sync").value, false, "Custom value kept") - store.orbit_android.sync_mode = "custom" - OSM.modeChanged("test") - eq(p.settings.auto_sync, false, "Custom value restored") - store.orbit_android.sync_mode = "orbismart" -end) - -test("orbismart: the plugin never moves the reader itself (today's newest-dated jump); Custom gives its settings back", function() - local ui, m, p = osmBook(120, nil) - p.settings.sync_forward, p.settings.sync_backward = 2, 3 - m:onReaderReady() - eq(p.settings.sync_forward, 3, "further ahead: Don't sync") - eq(p.settings.sync_backward, 3, "further behind: Don't sync") - -- A newer-dated place behind this reader, while reading here: furthest wins, no move. - for pg = 121, 125 do W.page = pg; m:onPageUpdate(pg) end - p.last_page_turn_timestamp = os.time() - osmServer(60, os.time() - 30) - store.orbit_android.orbismart.d1 = { m = { at = 1, pct = 120 / 300, progress = "/p120" } } - p:fetchRemoteProgress("d1", function() end) - run(2) - eq(W.page, 125, "not moved back") - eq(osmPopup(), nil, "not asked either") - ok(osmLog("orbismart: rule6 L=125 R=60 -> push"), "furthest wins") - store.orbit_android.sync_mode = "custom" - OSM.modeChanged("test") - eq(p.settings.sync_forward, 2, "given back") - store.orbit_android.sync_mode = "orbismart" -end) - -test("orbismart: Recommended settings review the plugin's own value kept for Custom", function() - local ui, m, p = osmBook(50, nil) - p.settings.sync_forward, p.settings.sync_backward = 1, 3 - m:onReaderReady() - eq(OSM.savedPluginSetting("sync_forward").value, 1, "the reader's Ask, kept") - ok(OSM.setSavedPluginSetting("sync_forward", 2), "Recommended writes the kept value") - eq(p.settings.sync_forward, 3, "OrbiSmart's stays in force") - store.orbit_android.sync_mode = "custom" - OSM.modeChanged("test") - eq(p.settings.sync_forward, 2, "Custom gets the recommended value") - eq(OSM.savedPluginSetting("sync_forward"), nil, "nothing kept under Custom") - store.orbit_android.sync_mode = "orbismart" -end) - -test("orbismart: This book sheet gets Read from here everywhere", function() - local made = {} - package.loaded["bookorbit_menu_ui"] = { row = function(w, o) local r = { row = o }; table.insert(made, r); return r end, - divider = function() return { divider = true } end } - package.loaded["bookorbit_menu_page"] = { runAction = function(page, action) page.ran = action.kind end } - package.loaded["bookorbit_board_ui"] = { vstack = function(o, kids) return { stack = kids } end } - local ui, m, p = osmBook(50, { server = { at = 5000, pct = 0.7, progress = "/p210" } }) - OSM.sheet_hooked = nil - m:onReaderReady() - local MenuUI = package.loaded["bookorbit_menu_ui"] - local auto = MenuUI.row(400, { label = "Auto-sync", action = { kind = "auto" } }) - ok(auto.stack and auto.stack[3].row.label == "Read from here everywhere", "the row under Auto-sync") - local other = MenuUI.row(400, { label = "Book details", action = { kind = "details" } }) - eq(other.stack, nil, "other rows unchanged") - local page = { close = function(pg) pg.closed = true end } - package.loaded["bookorbit_menu_page"].runAction(page, { kind = "orbit_read_here" }) - ok(page.closed, "sheet closed") - run(1) - ok(osmLog("orbismart: override queued (This book)"), "override made from the sheet") - package.loaded["bookorbit_menu_page"].runAction(page, { kind = "sync" }) - eq(page.ran, "sync", "the sheet's own actions still run") - run(40) -end) - -test("settings: Off reading cadence adds no pause sync under the furthest-position rule", function() - local ui, m, p = osmBook(100, nil) - RE.S.reading_schedule = "off" - m:onReaderReady() - run(30) - p.calls = {} - W.page = 110; m:onPageUpdate(110) - run(150) - ok(not has(p.calls, "fetch"), "Off means no automatic pause pull") - eq(OSM.pause_task, nil) -end) +dofile(here .. "/position_sync_flows.lua")(test,eq,ok,RE,W,UIManager,run,newUI,ReaderUI,FileManager) test("settings: sync controls remain visible under either position rule", function() - local _, m = osmBook(50, nil) + local _, m = newUI(true) for _, mode in ipairs({"orbismart", "custom"}) do store.orbit_android.sync_mode = mode local texts = {} @@ -5554,36 +4991,6 @@ test("settings: sync controls remain visible under either position rule", functi end end) -test("settings: Sync now uses the existing snapshot/drain without sleeping", function() - local ui, m = newUI(true) - run(30) - W.broadcasts = {}; ui.bookorbit.calls = {} - local release, handled = RE.Wifi.release, nil - RE.Wifi.release = function(name, flag) - if name == "sync_and_sleep" then handled = flag end - return release(name, flag) - end - RE.Library.syncNow(m) - run(5) - RE.Wifi.release = release - eq(handled, false, "normal Wi-Fi lease restoration") - eq(lastBroadcast(".NET_DONE").extras.reason, "menu_sync") - ok(has(ui.bookorbit.calls, "onSuspend"), "current position snapshotted") - ok(not lastBroadcast(".SLEEP_NOW"), "screen stays awake") -end) - -test("settings: failed Sync now leaves the screen awake", function() - W.server_code = nil - local _, m = newUI(true) - run(30) - W.broadcasts = {} - RE.Library.syncNow(m) - run(40) - ok(not lastBroadcast(".SLEEP_NOW"), "failed sync also stays awake") - eq(lastBroadcast(".NET_DONE").extras.reason, "menu_sync") - W.server_code = 200 -end) - test("settings PIN: keep-open Custom editors and copy remain read-only", function() local _,m = newUI(false) local reading diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 0fcf177f..9ce0f070 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -20,10 +20,10 @@ Counts include settings exposure as separate rows; they are not feature quality | Platform | ✅ | 🟡 | ❌ | ➖ | |---|---:|---:|---:|---:| -| Android (M8C / Boox) | 75 | 13 | 1 | 3 | -| X4 Pro | 55 | 12 | 13 | 12 | -| X4 classic | 54 | 12 | 13 | 13 | -| X3 | 20 | 16 | 43 | 13 | +| Android (M8C / Boox) | 76 | 13 | 1 | 3 | +| X4 Pro | 55 | 12 | 14 | 12 | +| X4 classic | 54 | 12 | 14 | 13 | +| X3 | 20 | 16 | 44 | 13 | ## Behaviour @@ -40,18 +40,18 @@ Counts include settings exposure as separate rows; they are not feature quality | Lazy covers and repair on Full refresh | ✅ (v0.11.3-rc.17) Thumbnail cache and ETag-aware fetch. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ThumbnailCache.kt:8](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/ThumbnailCache.kt#L8) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Cache plus mirror. [xteink/orbify/Mirror.cpp:26](../xteink/orbify/Mirror.cpp#L26), [xteink/orbify/CacheStore.cpp:26](../xteink/orbify/CacheStore.cpp#L26) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Cache plus mirror. [xteink/orbify/Mirror.cpp:26](../xteink/orbify/Mirror.cpp#L26), [xteink/orbify/CacheStore.cpp:26](../xteink/orbify/CacheStore.cpp#L26) | 🟡 Live catalog covers; no retained BookSync cache/repair; **hardware: cached cover path cut for flash/PSRAM**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | | Download progress and return to catalog | ✅ (v0.11.3-rc.17) BookOrbit download integration; companion copy worker. [android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua:18](../android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua#L18) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Return-to-catalog patch; native progress on S3. [xteink/tailnet/tailnet_build.py:239](../xteink/tailnet/tailnet_build.py#L239) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Return-to-catalog patch; native progress on S3. [xteink/tailnet/tailnet_build.py:239](../xteink/tailnet/tailnet_build.py#L239) | 🟡 Progress bar only if largest free block fits framebuffer plus 40,000-byte margin; otherwise static Downloading screen; **hardware: conditional framebuffer restoration to preserve TLS heap**. [xteink/tailnet/tailnet_build.py:247](../xteink/tailnet/tailnet_build.py#L247), [xteink/tailnet/tailnet_build.py:248](../xteink/tailnet/tailnet_build.py#L248), [xteink/overlay/patches/v2.0/0013-download-progress-ui.patch:13](../xteink/overlay/patches/v2.0/0013-download-progress-ui.patch#L13) | | Replace changed library copies; preserve reading state | ✅ (v0.11.3-rc.17) Companion copy refresh. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesLogic.kt:10](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/CopiesLogic.kt#L10), [android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua:18](../android/koreader/orbit.koplugin/ko/server/bookorbit/copies.lua#L18) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Copy check and refresh on sync. [xteink/orbify/CopyRefresh.cpp:31](../xteink/orbify/CopyRefresh.cpp#L31), [xteink/tailnet/tailnet_build.py:281](../xteink/tailnet/tailnet_build.py#L281) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Copy check and refresh on sync. [xteink/orbify/CopyRefresh.cpp:31](../xteink/orbify/CopyRefresh.cpp#L31), [xteink/tailnet/tailnet_build.py:281](../xteink/tailnet/tailnet_build.py#L281) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Copy check and refresh on sync. [xteink/orbify/CopyRefresh.cpp:31](../xteink/orbify/CopyRefresh.cpp#L31), [xteink/tailnet/tailnet_build.py:281](../xteink/tailnet/tailnet_build.py#L281) | -| Furthest-place position sync, behind hold and explicit Yes/No | ✅ (v0.11.3-rc.17) BookSync position sync pull/drain and prompt. [android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua:33](../android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua#L33) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) BookSync position sync state and reader prompt. [xteink/orbify/OrbiSmartSync.cpp:31](../xteink/orbify/OrbiSmartSync.cpp#L31), [xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch:5](../xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch#L5) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) BookSync position sync state and reader prompt. [xteink/orbify/OrbiSmartSync.cpp:31](../xteink/orbify/OrbiSmartSync.cpp#L31), [xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch:5](../xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch#L5) | 🟡 Sleep/foreground sync; no in-reader pause/wake background transport; **hardware: TLS cannot coexist with open book on X3**. [xteink/orbify/OrbiSmartSync.cpp:31](../xteink/orbify/OrbiSmartSync.cpp#L31), [xteink/tailnet/tailnet_build.py:268](../xteink/tailnet/tailnet_build.py#L268) | -| Read from here everywhere; offline queued override | ✅ (v0.11.3-rc.17) BookSync position sync override. [android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua:33](../android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua#L33) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable override drain. [xteink/orbify/OrbiSmartSync.cpp:333](../xteink/orbify/OrbiSmartSync.cpp#L333) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable override drain. [xteink/orbify/OrbiSmartSync.cpp:333](../xteink/orbify/OrbiSmartSync.cpp#L333) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable override drain. [xteink/orbify/OrbiSmartSync.cpp:333](../xteink/orbify/OrbiSmartSync.cpp#L333) | +| Furthest-place position sync, behind hold and explicit Yes/No | ✅ (0.12 (feature branch; device acceptance pending)) BookSync position sync pull/drain and prompt; 0.12 sync runs through the companion single owner with durable lifecycle replay. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt:66](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt#L66) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) BookSync position sync state and reader prompt. [xteink/orbify/OrbiSmartSync.cpp:31](../xteink/orbify/OrbiSmartSync.cpp#L31), [xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch:5](../xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch#L5) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) BookSync position sync state and reader prompt. [xteink/orbify/OrbiSmartSync.cpp:31](../xteink/orbify/OrbiSmartSync.cpp#L31), [xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch:5](../xteink/overlay/patches/v2.0/0052-orbify-orbismart.patch#L5) | 🟡 Sleep/foreground sync; no in-reader pause/wake background transport; **hardware: TLS cannot coexist with open book on X3**. [xteink/orbify/OrbiSmartSync.cpp:31](../xteink/orbify/OrbiSmartSync.cpp#L31), [xteink/tailnet/tailnet_build.py:268](../xteink/tailnet/tailnet_build.py#L268) | +| Read from here everywhere; offline queued override | ✅ (0.12 (feature branch; device acceptance pending)) BookSync position sync override; 0.12 sync runs through the companion single owner with durable lifecycle replay. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt:66](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt#L66) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable override drain. [xteink/orbify/OrbiSmartSync.cpp:333](../xteink/orbify/OrbiSmartSync.cpp#L333) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable override drain. [xteink/orbify/OrbiSmartSync.cpp:333](../xteink/orbify/OrbiSmartSync.cpp#L333) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable override drain. [xteink/orbify/OrbiSmartSync.cpp:333](../xteink/orbify/OrbiSmartSync.cpp#L333) | | Sync at sleep, with bounded time and wake cancellation | ✅ (v0.11.3-rc.17) Sleep flow and configurable cap. [android/koreader/orbit.koplugin/ko/sleep.lua:9](../android/koreader/orbit.koplugin/ko/sleep.lua#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Deadline/watchdog overlay. [xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch:9](../xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Deadline/watchdog overlay. [xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch:9](../xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Deadline/watchdog overlay. [xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch:9](../xteink/overlay/patches/v2.0/0037a-orbify-sleep-sync-budget.patch#L9) | -| Periodic/page/chapter sync or pause sync while book stays open | ✅ (v0.11.3-rc.17) Reading schedule and BookSync position sync pause. [android/koreader/orbit.koplugin/ko/server/bookorbit/reading_sync.lua:139](../android/koreader/orbit.koplugin/ko/server/bookorbit/reading_sync.lua#L139), [android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua:33](../android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua#L33) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Background sync task. [xteink/orbify/BookOrbitBackgroundSync.cpp:42](../xteink/orbify/BookOrbitBackgroundSync.cpp#L42) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Background sync task. [xteink/orbify/BookOrbitBackgroundSync.cpp:42](../xteink/orbify/BookOrbitBackgroundSync.cpp#L42) | ❌ TLS session does not fit beside an open book; no PSRAM; **hardware: TLS session does not fit beside an open book; no PSRAM**. [xteink/tailnet/tailnet_build.py:268](../xteink/tailnet/tailnet_build.py#L268) | -| Highlight and bookmark sync carried through lifecycle sync | ✅ (v0.11.3-rc.17) Drains BookOrbit lifecycle outbox. [android/koreader/orbit.koplugin/ko/server/bookorbit/sync.lua:14](../android/koreader/orbit.koplugin/ko/server/bookorbit/sync.lua#L14) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Full sync; background reading defers annotation work. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Full sync; background reading defers annotation work. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sleep/foreground full sync; background unavailable. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392), [xteink/tailnet/tailnet_build.py:268](../xteink/tailnet/tailnet_build.py#L268) | -| Reading sessions uploaded in full sync | ✅ (v0.11.3-rc.17) Lifecycle outbox integration. [android/koreader/orbit.koplugin/ko/server/bookorbit/sync.lua:14](../android/koreader/orbit.koplugin/ko/server/bookorbit/sync.lua#L14) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sessions deferred to full sync while book open. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sessions deferred to full sync while book open. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sessions deferred to full sync while book open. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | +| Periodic/page/chapter sync or pause sync while book stays open | ✅ (0.12 (feature branch; device acceptance pending)) Reading schedule and BookSync position sync pause; 0.12 sync runs through the companion single owner with durable lifecycle replay. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt:66](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt#L66), [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt:66](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt#L66) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Background sync task. [xteink/orbify/BookOrbitBackgroundSync.cpp:42](../xteink/orbify/BookOrbitBackgroundSync.cpp#L42) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Background sync task. [xteink/orbify/BookOrbitBackgroundSync.cpp:42](../xteink/orbify/BookOrbitBackgroundSync.cpp#L42) | ❌ TLS session does not fit beside an open book; no PSRAM; **hardware: TLS session does not fit beside an open book; no PSRAM**. [xteink/tailnet/tailnet_build.py:268](../xteink/tailnet/tailnet_build.py#L268) | +| Highlight and bookmark sync carried through lifecycle sync | ✅ (0.12 (feature branch; device acceptance pending)) Drains BookOrbit lifecycle outbox; 0.12 sync runs through the companion single owner with durable lifecycle replay. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt:127](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt#L127) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Full sync; background reading defers annotation work. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Full sync; background reading defers annotation work. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sleep/foreground full sync; background unavailable. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392), [xteink/tailnet/tailnet_build.py:268](../xteink/tailnet/tailnet_build.py#L268) | +| Reading sessions uploaded in full sync | ✅ (0.12 (feature branch; device acceptance pending)) Lifecycle outbox integration; 0.12 sync runs through the companion single owner with durable lifecycle replay. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt:127](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt#L127) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sessions deferred to full sync while book open. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sessions deferred to full sync while book open. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Sessions deferred to full sync while book open. [xteink/overlay/patches/v2.0/0022-background-sync.patch:392](../xteink/overlay/patches/v2.0/0022-background-sync.patch#L392) | | Final progress before durable read-status; Undo | ✅ (v0.11.3-rc.17) Finish queue and sheet. [android/koreader/orbit.koplugin/ko/server/bookorbit/endofbook.lua:39](../android/koreader/orbit.koplugin/ko/server/bookorbit/endofbook.lua#L39), [android/koreader/orbit.koplugin/ko/endsheet.lua:15](../android/koreader/orbit.koplugin/ko/endsheet.lua#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable finish queue. [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37), [xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch:9](../xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable finish queue. [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37), [xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch:9](../xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch#L9) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Durable finish queue. [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37), [xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch:9](../xteink/overlay/patches/v2.0/0027-orbify-finish-at-end.patch#L9) | | End-of-book sheet: next series book, suggestion, author books | ✅ (v0.11.3-rc.17) End sheet. [android/koreader/orbit.koplugin/ko/endsheet.lua:15](../android/koreader/orbit.koplugin/ko/endsheet.lua#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) End page; two suggestions configured. [xteink/orbify/EndPage.cpp:27](../xteink/orbify/EndPage.cpp#L27), [xteink/tailnet/tailnet_build.py:288](../xteink/tailnet/tailnet_build.py#L288) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) End page; two suggestions configured. [xteink/orbify/EndPage.cpp:27](../xteink/orbify/EndPage.cpp#L27), [xteink/tailnet/tailnet_build.py:288](../xteink/tailnet/tailnet_build.py#L288) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) End page; two suggestions configured. [xteink/orbify/EndPage.cpp:27](../xteink/orbify/EndPage.cpp#L27), [xteink/tailnet/tailnet_build.py:288](../xteink/tailnet/tailnet_build.py#L288) | | End-of-book stars and rating upload | ✅ (v0.11.3-rc.17) Stars on end sheet. [android/koreader/orbit.koplugin/ko/endsheet.lua:15](../android/koreader/orbit.koplugin/ko/endsheet.lua#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Rating enabled. [xteink/tailnet/tailnet_build.py:285](../xteink/tailnet/tailnet_build.py#L285), [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Rating enabled. [xteink/tailnet/tailnet_build.py:285](../xteink/tailnet/tailnet_build.py#L285), [xteink/orbify/FinishSync.cpp:37](../xteink/orbify/FinishSync.cpp#L37) | ❌ X3 rating code/strings excluded to preserve flash gate; **hardware: X3 rating code/strings excluded to preserve flash gate**. [xteink/tailnet/tailnet_build.py:285](../xteink/tailnet/tailnet_build.py#L285) | | Next-in-series cover on end sheet | ✅ (v0.11.3-rc.17) Cover on end sheet. [android/koreader/orbit.koplugin/ko/endsheet.lua:15](../android/koreader/orbit.koplugin/ko/endsheet.lua#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Cached cover drawn offline. [xteink/orbify/EndPage.cpp:8](../xteink/orbify/EndPage.cpp#L8) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Cached cover drawn offline. [xteink/orbify/EndPage.cpp:8](../xteink/orbify/EndPage.cpp#L8) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:298](../xteink/tailnet/tailnet_build.py#L298) | | 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/localfirst.lua:30](../android/koreader/orbit.koplugin/ko/server/bookorbit/localfirst.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) 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) | | 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) | @@ -87,6 +87,7 @@ Counts include settings exposure as separate rows; they are not feature quality | Clear, editable Custom reading styles and apply-then-edit quick choices | 🟡 Font and weight, device-local margins, line spacing and contrast; editors, native-style copy with Undo, and clear sync labels. Device acceptance pending.; **deliberately deferred: unreleased Android implementation awaits device visual and performance acceptance; firmware follows separately**. [android/koreader/orbit.koplugin/ko/custom_reading.lua:1](../android/koreader/orbit.koplugin/ko/custom_reading.lua#L1), [android/koreader/test/reader_panel_flows.lua:170](../android/koreader/test/reader_panel_flows.lua#L170) | ❌ Custom style editors await the firmware slice; KOReader copy does not apply.; **deliberately deferred: maintainer authorized Android first on 2026-11-25; firmware follows with device-specific margin ranges.**. [docs/design/booksync-home/DESIGN-NOTES.md:715](../docs/design/booksync-home/DESIGN-NOTES.md#L715) | ❌ Custom style editors await the firmware slice; KOReader copy does not apply.; **deliberately deferred: maintainer authorized Android first on 2026-11-25; firmware follows with device-specific margin ranges.**. [docs/design/booksync-home/DESIGN-NOTES.md:715](../docs/design/booksync-home/DESIGN-NOTES.md#L715) | ❌ Custom style editors await the firmware slice; KOReader copy does not apply.; **deliberately deferred: maintainer authorized Android first on 2026-11-25; firmware follows with device-specific margin ranges.**. [docs/design/booksync-home/DESIGN-NOTES.md:715](../docs/design/booksync-home/DESIGN-NOTES.md#L715) | | BookSync Home battery widget and snapshot Battery page | 🟡 Six widget sizes, Overview/Rates/Daily/Charges and Settings link; **deliberately deferred: 0.12 Android source implementation is building, unreleased and awaiting device validation. Grouped rates, page/refresh efficiency and export/compare actions remain later work; missing evidence is labelled explicitly.**. [docs/design/booksync-home/F12-O-NOTES.md:1](../docs/design/booksync-home/F12-O-NOTES.md#L1) | ❌ Owned battery widget and page follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; implement the snapshot widget and page in the later Xteink slice.**. [docs/design/booksync-home/F12-O-NOTES.md:1](../docs/design/booksync-home/F12-O-NOTES.md#L1) | ❌ Owned battery widget and page follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; implement the snapshot widget and page in the later Xteink slice.**. [docs/design/booksync-home/F12-O-NOTES.md:1](../docs/design/booksync-home/F12-O-NOTES.md#L1) | ❌ Owned battery widget and page follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; implement the snapshot widget and page in the later Xteink slice. X3 also requires measured flash fit.**. [docs/design/booksync-home/F12-O-NOTES.md:1](../docs/design/booksync-home/F12-O-NOTES.md#L1) | | Home editor Book list configuration (0.12 foundation; unreleased) | 🟡 One Book list renderer with friendly presets, settings, paged counted sources and local Custom filters; **deliberately deferred: real-device acceptance and release follow the Android 0.12 foundation**. [android/koreader/orbit.koplugin/ko/booklist_config.lua:3](../android/koreader/orbit.koplugin/ko/booklist_config.lua#L3) | ❌ Book list settings and sources follow Android; shared cfg and focus logic are ready for firmware integration; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware implementation follows**. [docs/design/booksync-home/DESIGN-NOTES.md:809](../docs/design/booksync-home/DESIGN-NOTES.md#L809) | ❌ Book list settings and sources follow Android; shared cfg and focus logic are ready for firmware integration; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware implementation follows**. [docs/design/booksync-home/DESIGN-NOTES.md:809](../docs/design/booksync-home/DESIGN-NOTES.md#L809) | ❌ Book list settings and sources follow Android; shared cfg and focus logic are ready for firmware integration; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware implementation follows**. [docs/design/booksync-home/DESIGN-NOTES.md:809](../docs/design/booksync-home/DESIGN-NOTES.md#L809) | +| Companion-owned Android sync and durable lifecycle upgrade replay | ✅ (0.12 (feature branch; device acceptance pending)) Server-free plugin sync; checkpointed five-phase import, offline queue and consent. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt:6](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt#L6) | ❌ Existing firmware sync retained; companion cutover is Android-only; **deliberately deferred: maintainer authorized Android first; firmware adapter migration comes later**. [docs/design/booksync-home/F12-Q-NOTES.md:3](../docs/design/booksync-home/F12-Q-NOTES.md#L3) | ❌ Existing firmware sync retained; companion cutover is Android-only; **deliberately deferred: maintainer authorized Android first; firmware adapter migration comes later**. [docs/design/booksync-home/F12-Q-NOTES.md:3](../docs/design/booksync-home/F12-Q-NOTES.md#L3) | ❌ Existing firmware sync retained; companion cutover is Android-only; **deliberately deferred: maintainer authorized Android first; firmware adapter migration comes later**. [docs/design/booksync-home/F12-Q-NOTES.md:3](../docs/design/booksync-home/F12-Q-NOTES.md#L3) | | Owned Storage, Library storage figures, Collections and download folder (0.12 foundation; unreleased) | 🟡 Real StatFs capacity, tracked file/cache figures, patterned bar, confirmed local removal, Collections paging and folder selection; **deliberately deferred: real-device acceptance and release follow the Android 0.12 foundation**. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/DeviceStorage.kt:12](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/DeviceStorage.kt#L12), [android/koreader/orbit.koplugin/ko/storage.lua:3](../android/koreader/orbit.koplugin/ko/storage.lua#L3) | ❌ Owned storage and Collections screens follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware implementation follows**. [docs/design/booksync-home/DESIGN-NOTES.md:293](../docs/design/booksync-home/DESIGN-NOTES.md#L293) | ❌ Owned storage and Collections screens follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware implementation follows**. [docs/design/booksync-home/DESIGN-NOTES.md:293](../docs/design/booksync-home/DESIGN-NOTES.md#L293) | ❌ Owned storage and Collections screens follow Android; **deliberately deferred: maintainer authorised Android first on 2026-11-25; firmware implementation follows**. [docs/design/booksync-home/DESIGN-NOTES.md:293](../docs/design/booksync-home/DESIGN-NOTES.md#L293) | ## Settings exposure diff --git a/docs/design/backend-independence.md b/docs/design/backend-independence.md index 8ac259bf..cdd21e86 100644 --- a/docs/design/backend-independence.md +++ b/docs/design/backend-independence.md @@ -157,60 +157,38 @@ render-path network/subprocesses, one batched companion round-trip per Home pain filtering, sorting, joins, stats and battery work stay on the companion worker; timing spans record real device milliseconds. Moving protocol ownership adds no new screen or widget. -### Lua compatibility adapter and remaining transport work - -F12-Q's [checkpoint notes](booksync-home/F12-Q-NOTES.md) track the companion transport -cutover. Its durable position queue prerequisite is not wired into lifecycle hooks; -the Android plugin is not yet server-free. The remaining paths below still apply. - -The owned UI still calls `ko/library.lua`; it receives normalized bounded projections. -`ko/server/bookorbit.lua` binds the existing plugin account and compatibility operations. -The reviewed facade callers are `ko/home.lua` (reading gate/Home), `ko/start.lua` (toast), -`ko/notices.lua` (catalog lifecycle), `ko/test_sync_path.lua` (explicit test action), -`ko/sleepscreen.lua` (credential handoff). Only -`main.lua` loads implementation files. Guards forbid additional facade consumers and still -check every reviewed caller for protocol fields/routes and direct imports. The remaining -legacy lifecycle callers (`ko/wifi.lua`, `ko/sleep.lua`, `ko/module.lua`, -`ko/endsheet.lua`, `ko/menu.lua`) may obtain the compatibility plugin through `serverPlugin`; -owned UI cannot. The remaining middleware callers are `ko/net.lua` (cache resume), -`ko/shared.lua` (settings follow-up jobs) and `ko/main_loop.lua` (timing wrappers). -Direct shared implementation globals are forbidden even in these reviewed files. Local -file IO and directory/clock providers live on generic `Store`; legacy protocol lookups and -search live in the adapter. The storage provider has no facade permission. Historical Home wire values and cover-cache folder names stay in the adapter, -so the guard rejects backend names in every casing without breaking installed settings. -Its adapter package owns the old cache/mirror/copies, finish, grouping, local-first and -position-sync hooks; pure protocol helpers live in `logic/server/bookorbit`. Generic cache -encoding remains `logic/cache.lua`; `ko/store.lua` keeps the small owned projection read. -Mirror planning and legacy query interpretation now live only in the companion's -`CatalogPlan`/`MirrorLogic`, `CacheStore` and `BulkCatalog`. The native connector consumes -neutral bounded display snapshots through `ko/library.lua`; no Lua catalog request -wrapper or query interpreter remains. `mirror.lua`, `store.lua` (the adapter's legacy -interpreter) and `library_bookorbit.lua` are deleted. The generic `ko/store.lua` still -reads one owned `library_views` row; the library's neutral companion transport and durable -event pump reuse that path. Private `mirror/` checkpoints never cross the plugin boundary. -`catalog.state` has one row, 16 KiB and zero polling round-trips; Home nested records count -against the same 24-row snapshot limit. Catalog ownership changes wait for a running writer -to stop. Existing lifecycle/finish/copy queues remain owned by their existing writers. - -The maintainer explicitly permits routing oversized migrations through this one Lua adapter -for this slice. Remaining server calls **inside that adapter**, to move to companion commands -in a later transport/sole-sync-owner slice, are: - -- `ko/server/bookorbit.lua`: `probeServer` (HEAD reachability in the background child). -- `ko/server/bookorbit.lua`: temporary native widget/sync bindings and the existing - copy/finish event and state contracts. Catalog getters read only neutral local snapshots; - refresh actions dispatch `catalog.control`. Cover acquisition uses neutral commands and - local references. No legacy catalog transport or SQL interpreter is installed. -- `ko/server/bookorbit/endofbook.lua`: compatibility detail/status/rating calls through the - existing finish outbox. Preserve sole-writer ordering when moving these. -- `ko/server/bookorbit/grouping.lua`: legacy grouping over bounded local catalog snapshots. Its whole-list Lua aggregation is the next catalog slice. - Owned lists/filtering use companion projections; do not reuse this full-list path for Home. -- `ko/server/bookorbit/sync.lua`, `reading_sync.lua` and `lifecycle.lua`: legacy outbox, - pull/push, remote-progress parsing and upstream snapshot/settings bindings. Root start/sleep/ - Wi-Fi flows call the adapter facade; the guard also forbids upstream primitive API names. -- `ko/server/bookorbit/orbismart.lua`: upstream progress client interception. Keep the approved - one-draw position prompt and reading gate while moving sync ownership. - -These are adapter-contained compatibility implementations, not permission to introduce new -Lua HTTP, backend JSON, full-catalog work or legacy views into the owned client. Firmware -adapter enforcement remains deferred under the Android-first instruction. +### Android sync is server-free; remaining catalog compatibility + +The Android plugin's sync path now calls only neutral commands through `ko/library.lua`. +The companion's single `SyncOwner` owns policy, durable marker/override/decline state, +offline queues and delivery through `ServerAdapter`. The production adapter alone owns +backend requests and payloads. The native reader captures small locators/geometry and +shows the approved one-draw consent prompt. It does not call a server for sync. + +[F12-Q notes](booksync-home/F12-Q-NOTES.md) document the retirement handshake, five-phase +legacy import, generation fallback, account provenance and crash boundaries. Checkpoints +commit before source retirement; uncertain ownership retains the original files. The +old Lua sync, reading_sync, lifecycle, orbismart and localfirst implementations are +removed. KOReader's own built-in sync remains independent. The guard checks retired +sync calls/routes in every plugin Lua file, including private adapter files, without +an exemption. Shared policy fixtures and a neutral toy companion adapter cover the new +owner, offline restart, override, stale consent and account isolation. + +Cover acquisition and refresh now use neutral companion commands; the plugin reads +bounded local references. The former cover downloader and thumbnail child scanner +are removed. Mirror planning and catalog refresh now run in the companion; the neutral library reads +bounded snapshots and dispatches `catalog.control`. The Lua mirror, catalog interpreter +and old library binding are deleted. The parallel F12-Q2 slice owns remaining grouping, +copies, recommendations and end-of-book transport. Until that slice lands, the **whole +plugin** is not yet server-free. Its cached catalog display helpers are extracted into +`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. + +Every screen/widget keeps its budget. Consent and bounded native verification add named +one-row / 16 KiB budgets; commands, drains and paints log timing spans. No sync is added +to Home paint. Heavy capture, sidecar processing and statistics stay on the companion. +Device acceptance targets remain pending maintainer confirmation. Firmware adapter +enforcement is deferred under the Android-first instruction. diff --git a/docs/design/booksync-home/F12-Q-NOTES.md b/docs/design/booksync-home/F12-Q-NOTES.md index ab24e072..f872e9ab 100644 --- a/docs/design/booksync-home/F12-Q-NOTES.md +++ b/docs/design/booksync-home/F12-Q-NOTES.md @@ -1,60 +1,99 @@ -# F12-Q: companion transport ownership checkpoints - -Status: prerequisite only. The Android plugin is **not yet server-free**. No lifecycle -hook uses the new position queue and no legacy queue or adapter file has been removed. -This work does not change the shipped feature matrix or enable a second writer. - -## Reuse and scope - -The existing library UI boundary (`android/koreader/orbit.koplugin/ko/library.lua:134`) -already dispatches neutral explicit position commands. The companion serial worker -(`android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt:42`) -and `ServerAdapter.position` remain the intended command path. The new -`ProgressOutbox` reuses the existing `Sql.transaction` port and `LuaValue` codec rather -than introducing another persistence/transport stack. It has not been connected to -that worker: the cutover must first establish the position policy and sole writer. - -The prerequisite provides immutable FIFO position intents, commit before delivery, -acknowledgment after success and bounded retries. Every row carries its adapter and -opaque sync account namespace. Catalog ownership is insufficient because directly -entered sync and acquisition logins may belong to different users. Sign-out or an -account change retains old rows without sending them with another account's credentials. -Capture timestamps survive retries; a crash after server delivery and before local -acknowledgment may replay the same immutable intent. No exactly-once guarantee is claimed. - -There are at most 1,000 pending rows across all accounts. A drain reads at most 24; -each position is at most 4,096 bytes and each encoded row at most 16 KiB. Capacity -failure retains existing work. Unknown extra inputs are not persisted, so credentials -cannot enter the queue through an unreviewed command field. These are worker limits, -not screen budgets. Every screen/widget retains its declared `logic/budgets.lua` -budget: no render network or subprocesses, at most one batched companion round trip -per Home paint, and at most 16 KiB per widget. Runtime integration must log a timing -span for each command/drain; host timings are not device acceptance. - -## Migration evidence and remaining work - -Pinned upstream `bookorbit` at `c1dd6b4f1947ff50843a155e12e70f1e7d15f0c7` stores +# F12-Q: companion-owned Android sync + +Status: the Android plugin's **sync path is server-free** on feature/0.12. F12-Q2’s cover cutover is merged; that slice +owns the remaining catalog/mirror/copies/recommendations/end-of-book cutover. +This is source implementation, not a release or device acceptance claim. Xteink +remains deferred under the maintainer's Android-first authorization. + +## Existing modules extended + +Reuse anchors from the prerequisite commit 71f7fc5d: the neutral library command +boundary (`android/koreader/orbit.koplugin/ko/library.lua:134`), serial companion +worker (`android/companion/app/src/main/java/net/fledgewing/orbitcompanion/LibraryAccount.kt:42`), +`ProgressOutbox` and its existing `Sql` transaction / `LuaValue` ports. The queue +facade now delegates to `LifecycleQueue`; it is not another writer. Existing reading +cadence (`logic/schedule.lua`) and Wi-Fi leases (`logic/wifi_plan.lua`) still govern +native lifecycle work. The pure position policy reuses the shared fixture contract +at `shared/fixtures/orbismart/cases.json`, now exercised against `PositionPolicy.kt`. + +The library adds only neutral `sync.*` commands and one pure preview operation. +`SyncOwner.kt` serializes policy, consent, per-document marker/override/decline state, +account-scoped capture, retry and delivery on the existing companion executor. +Backend routes, credentials, JSON and legacy source formats stay in +`server/bookorbit/BookOrbitSync.kt`, `LegacyLifecycleImport.kt` and the adapter binding. +The plugin's `ko/position_sync.lua` captures native locators and bounded geometry; +`ko/reading_sync.lua` owns native lifecycle scheduling and the one-draw consent UI. +No sync request or backend response parsing remains in the plugin. + +## Writer retirement and migration + +`ko/server/bookorbit/quiesce.lua` is migration-only: it disarms the installed legacy +class and API before instances initialize. Unknown startup ordering refuses activation. +It never invokes the retired transport. The companion requires this retirement +handshake before importing or sending anything. KOReader's built-in sync is unchanged. + +Pinned upstream `bookorbit` at c1dd6b4f1947ff50843a155e12e70f1e7d15f0c7 stores five independently acknowledged phases: match, stats, annotations, state and progress -(`koreader-plugin/bookorbit.koplugin/bookorbit_lifecycle_outbox.lua:33`). Metadata -generations reference separate immutable payload generations; the loader validates -the entry ID, digest and payload before attaching its snapshot (`:183–211`). -The request preserves the capture timestamp (`bookorbit_api.lua:582–591`). - -The remaining cutover must: - -- Quiesce the old writer and import complete, unacknowledged lifecycle snapshots, - including metadata/payload generation fallback, account provenance and every phase. - Commit an import checkpoint before acknowledging or retiring source files. Test crashes - at both boundaries. The position queue does not consume these files. -- Move the position policy and durable per-book marker/override/decline state behind the - sole companion sync owner. Preserve every shared BookSync position sync fixture, including rereads, - resets and behind-hold; keep the one-draw consent UI in the reader. -- Move cover acquisition and the remaining catalog, mirror, copies, recommendations - and end-of-book operations onto neutral commands/snapshots using the existing workers. -- Replace lifecycle/middleware callers, remove the Lua server adapters, and strengthen - the boundary guard without compatibility consumers or adapter exemptions for plugin Lua. -- Exercise the plugin end to end against a toy companion adapter. Only after those - checks pass can backend-independence documentation say the plugin is server-free. - -Xteink remains deferred under the maintainer's Android-first authorization. No release, -device operation, source-queue deletion or default flip is part of this prerequisite. +(`koreader-plugin/bookorbit.koplugin/bookorbit_lifecycle_outbox.lua:33`). Its loader +validates metadata and payload generations (`:183`); capture timestamps are preserved +by `bookorbit_api.lua:582`. The importer selects the newest valid generation, falls +back on damaged newer generations, and imports the entire immutable snapshot plus +all phase acknowledgments and pending remote applications. Pending applications reopen +their phase even when its original exchange was acknowledged. + +Every job has an adapter and opaque sync-account namespace, distinct from catalog +ownership. Per-account legacy state proves ownership where available; ambiguous or +corrupt sources remain untouched for recovery. Import checkpoints, source hashes and +payloads commit in one SQLite transaction **before** any source file moves. Originals +then move into `booksync-retired-lifecycle`; interrupted individual renames resume +from the checkpoint. Imported jobs cannot drain before retirement completes. Tests +inject crashes before and after checkpoint, during retirement and after retirement. + +The companion imports prior marker/override/decline state and known rating/review +state without overwriting newer owned records. It keeps positions and timestamps +immutable across retries, consumes overrides once, rejects stale consent and isolates +accounts. Every shared policy fixture passes, including resets, rereads and behind-hold. +A crash after delivery but before acknowledgment can replay a request; exactly-once +server delivery is not claimed. Proven old-account rating/review history is imported +under its own namespace too, preserving explicit clears when a different login is active. + +Custom direction preferences are translated inside the companion adapter, including +values saved before the automatic preset. The single owner preserves Keep, prompt and +lifecycle-push decisions; scheduled prompt checks stay quiet. A known silent placement +can run before the first draw; after draw it uses the approved one-draw consent rather +than a hidden jump. Native code sends only the selected mode and geometry. + +Annotations and book-state changes wait until the document closes before writing its +sidecar. Closed-file writes precede acknowledgments. Native xpointer verification uses +one small companion row per callback; its durable queue survives restarts. Malformed +sidecars are retained rather than overwritten. Statistics use bounded 256-row windows +with a composite cursor, preserving rows sharing a timestamp. Network and sidecar work +run off the reader thread. Close capture occurs on CloseDocument, before KOReader +clears its document (`koreader` 9192014d, `frontend/apps/reader/readerui.lua`). + +## Performance and parallel boundary + +The strict screen/widget rule remains binding: every screen/widget has a row and byte +budget, no render-path network or subprocess, at most one batched companion round trip +per Home paint and at most 16 KiB per widget snapshot. Consent and native verification +have named one-row / 16 KiB budgets in `logic/budgets.lua`, with info timing spans. +The synchronous prerender preview reads an immutable in-memory publication; it does no +SQL, network or disk IO. Old-path previews for the same document are invalidated +when another path updates its state, and delayed captures cannot claim the current +reader's sidecar lease. Cached position files are bounded to 16 KiB. Commands and drains +log milliseconds. Host timing is not device acceptance; the maintainer's device targets +remain pending confirmation. + +The journal holds at most 1,000 pending jobs and reads windows of 24. Legacy payloads +have a 200 MiB safety cap and remain companion-private; they never reach the reader. +Private decision records are bounded to 64 KiB; public projections are at most 16 KiB. +Offline capture commits before transport, and a companion restart repeats the retirement +handshake without losing the journal. Home paints gain no sync call. + +The five retired Lua implementations (sync, reading_sync, lifecycle, orbismart, +localfirst) are deleted. The latter's unrelated cached catalog display helpers survive +as `ko/server/bookorbit/local_view.lua` for Q2. Neutral middleware event hooks bridge +its existing jobs without adding any sync transport. The boundary guard rejects retired +sync primitive calls and sync routes in **every** plugin Lua file, including adapter +files. Companion toy-adapter tests exercise capture, restart, decisions, delivery and +account isolation without using the production backend. diff --git a/shared/features.json b/shared/features.json index a7116e7a..dbc5e3c7 100644 --- a/shared/features.json +++ b/shared/features.json @@ -693,15 +693,15 @@ "platforms": { "android": { "status": "supported", - "note": "BookSync position sync pull/drain and prompt", + "note": "BookSync position sync pull/drain and prompt; 0.12 sync runs through the companion single owner with durable lifecycle replay", "reason": null, "evidence": [ { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua", - "line": 33 + "path": "android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt", + "line": 66 } ], - "version": "v0.11.3-rc.17" + "version": "0.12 (feature branch; device acceptance pending)" }, "x4_pro": { "status": "supported", @@ -760,15 +760,15 @@ "platforms": { "android": { "status": "supported", - "note": "BookSync position sync override", + "note": "BookSync position sync override; 0.12 sync runs through the companion single owner with durable lifecycle replay", "reason": null, "evidence": [ { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua", - "line": 33 + "path": "android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt", + "line": 66 } ], - "version": "v0.11.3-rc.17" + "version": "0.12 (feature branch; device acceptance pending)" }, "x4_pro": { "status": "supported", @@ -870,19 +870,19 @@ "platforms": { "android": { "status": "supported", - "note": "Reading schedule and BookSync position sync pause", + "note": "Reading schedule and BookSync position sync pause; 0.12 sync runs through the companion single owner with durable lifecycle replay", "reason": null, "evidence": [ { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/reading_sync.lua", - "line": 139 + "path": "android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt", + "line": 66 }, { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/orbismart.lua", - "line": 33 + "path": "android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt", + "line": 66 } ], - "version": "v0.11.3-rc.17" + "version": "0.12 (feature branch; device acceptance pending)" }, "x4_pro": { "status": "supported", @@ -929,15 +929,15 @@ "platforms": { "android": { "status": "supported", - "note": "Drains BookOrbit lifecycle outbox", + "note": "Drains BookOrbit lifecycle outbox; 0.12 sync runs through the companion single owner with durable lifecycle replay", "reason": null, "evidence": [ { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/sync.lua", - "line": 14 + "path": "android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt", + "line": 127 } ], - "version": "v0.11.3-rc.17" + "version": "0.12 (feature branch; device acceptance pending)" }, "x4_pro": { "status": "supported", @@ -988,15 +988,15 @@ "platforms": { "android": { "status": "supported", - "note": "Lifecycle outbox integration", + "note": "Lifecycle outbox integration; 0.12 sync runs through the companion single owner with durable lifecycle replay", "reason": null, "evidence": [ { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/sync.lua", - "line": 14 + "path": "android/companion/app/src/main/java/net/fledgewing/orbitcompanion/server/bookorbit/BookOrbitSync.kt", + "line": 127 } ], - "version": "v0.11.3-rc.17" + "version": "0.12 (feature branch; device acceptance pending)" }, "x4_pro": { "status": "supported", @@ -1378,7 +1378,7 @@ "line": 9 }, { - "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/localfirst.lua", + "path": "android/koreader/orbit.koplugin/ko/server/bookorbit/local_view.lua", "line": 30 } ], @@ -5834,6 +5834,61 @@ }, "deferred": "Device acceptance, firmware renderers and configuration pages." }, + { + "id": "companion-sync-owner", + "feature": "Companion-owned Android sync and durable lifecycle upgrade replay", + "category": "Behaviour", + "platforms": { + "android": { + "status": "supported", + "note": "Server-free plugin sync; checkpointed five-phase import, offline queue and consent", + "reason": null, + "evidence": [ + { + "path": "android/companion/app/src/main/java/net/fledgewing/orbitcompanion/SyncOwner.kt", + "line": 6 + } + ], + "version": "0.12 (feature branch; device acceptance pending)" + }, + "x4_pro": { + "status": "missing", + "note": "Existing firmware sync retained; companion cutover is Android-only", + "reason": "deliberately deferred: maintainer authorized Android first; firmware adapter migration comes later", + "evidence": [ + { + "path": "docs/design/booksync-home/F12-Q-NOTES.md", + "line": 3 + } + ], + "version": null + }, + "x4": { + "status": "missing", + "note": "Existing firmware sync retained; companion cutover is Android-only", + "reason": "deliberately deferred: maintainer authorized Android first; firmware adapter migration comes later", + "evidence": [ + { + "path": "docs/design/booksync-home/F12-Q-NOTES.md", + "line": 3 + } + ], + "version": null + }, + "x3": { + "status": "missing", + "note": "Existing firmware sync retained; companion cutover is Android-only", + "reason": "deliberately deferred: maintainer authorized Android first; firmware adapter migration comes later", + "evidence": [ + { + "path": "docs/design/booksync-home/F12-Q-NOTES.md", + "line": 3 + } + ], + "version": null + } + } + }, { "id": "home-storage", "feature": "Owned Storage, Library storage figures, Collections and download folder (0.12 foundation; unreleased)", diff --git a/tools/test/test-server-boundary.py b/tools/test/test-server-boundary.py index 9a6b7f61..33665461 100644 --- a/tools/test/test-server-boundary.py +++ b/tools/test/test-server-boundary.py @@ -31,15 +31,14 @@ # 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', 'start.lua', 'notices.lua', 'test_sync_path.lua', 'sleepscreen.lua', - 'wifi.lua', 'sleep.lua', 'module.lua', 'endsheet.lua', 'menu.lua', - 'net.lua', 'shared.lua', 'main_loop.lua', + '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) -LEGACY_API = re.compile(r'\b(?:requestLifecycleOutboxDrain|requestProgressPull|requestProgressPush|fetchRemoteProgress|getLifecycleOutbox|getSyncCoordinator|last_remote_progress|pull_timestamp|push_timestamp|promptLogin|startSweep|enqueueLifecycleSnapshot|catalogSetReadStatus|catalogSetRating|catalogBooks|catalogBook|newClient|getDocumentDigest|getLastPercent|getLastProgress|remoteProgressIsNewer|isSamePlace|pages_before_update|isLoggedIn|_onSuspend)\b') +LEGACY_API = re.compile(r'\b(?:requestLifecycleOutboxDrain|requestProgressPull|requestProgressPush|fetchRemoteProgress|getLifecycleOutbox|getSyncCoordinator|last_remote_progress|pull_timestamp|push_timestamp|promptLogin|startSweep|enqueueLifecycleSnapshot|catalogSetReadStatus|catalogSetRating|catalogBooks|catalogBook|newClient|getDocumentDigest|remoteProgressIsNewer|isSamePlace|pages_before_update|isLoggedIn|_onSuspend)\b') @@ -52,6 +51,18 @@ def code_only(source, lua=False): def violations(path, source): path = Path(path) + # Sync ownership has completed its cutover. This check precedes adapter handling: + # no Lua adapter/facade can resurrect the retired client's server-call primitives. + if path.is_relative_to(LUA) and path.suffix == '.lua': + code = code_only(source, True) + identifiers = LUA_STRINGS.sub(lambda m: re.sub(r'[^\n]', ' ', m[0]), code) + if re.search(r'[:.]\s*(?:requestLifecycleOutboxDrain|requestProgressPull|requestProgressPush|fetchRemoteProgress|' + r'getLifecycleOutbox|getSyncCoordinator|enqueueLifecycleSnapshot|startSweep|' + r'getProgress|updateProgress|matchCheck|uploadPageStats|uploadAnnotations|exchangeAnnotations|' + r'exchangeAck|exchangeBookmarks|exchangeBookmarksAck|uploadBookStates|bulkProgress|sweepComplete)\s*\(', identifiers): + return [f'{path}: retired server sync call in the Android plugin; use Library companion commands'] + if re.search(r'/koreader/(?:syncs\b|plugin/(?:match-check|page-stats|annotations(?:/|[\"\'])|bookmarks(?:/|[\"\'])|book-states|bulk-progress|sweep-complete))', code): + return [f'{path}: sync route in Android plugin'] 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') @@ -114,6 +125,12 @@ def violations(path, source): class GuardTests(unittest.TestCase): + def test_sync_transport_cannot_hide_inside_a_lua_adapter(self): + for name in ('ko/sync.lua','ko/server/hidden.lua','ko/server/bookorbit.lua'): + for code in ('p:requestProgressPull()', 'api:updateProgress(doc, .5)', 'api:exchangeBookmarks({})', '"/koreader/syncs/progress"', '"/koreader/plugin/page-stats"', '"/koreader/plugin/annotations/exchange"'): + self.assertTrue(violations(LUA / name, code), (name,code)) + # These are native KOReader locator captures, also used by its independent built-in sync. + self.assertFalse(violations(LUA / 'ko/position_sync.lua','engine:getLastProgress(); engine:getLastPercent()')) def test_rejects_protocol_and_imports_even_with_suppression_comments(self): for path in (KOTLIN / 'Widget.kt', LUA / 'ko/widget.lua'): for value in ('"/api/v1/books"', '"catalog/books"', '"/auth/login"', '"/opds/catalog"', '"x-auth-key"', '"Smart Scopes"', '"/koreader/plugin/catalog/books"', '"readStatus"', '"BookOrbit"', '"bookorbit"', '"BOOKORBIT"', '"bookorbit_api"'):