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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -302,3 +302,8 @@ Storage and folder screens inherit a one-row, 16 KiB local snapshot budget;
Collections uses six projected rows. Capacity, file eligibility and removal
previews belong to the companion; render paths never scan folders. Preserve
reading sidecars and exclude the foreground book from removal previews.

Device-local library projections use their own reserved owner without changing catalog
ownership. They inherit the same screen/widget row, byte and one-batch limits; folder and
sidecar work stays on the companion. Login adoption checkpoints secrets and its migration
marker together in the existing encrypted vault; never activate a second lifecycle writer.
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ CrossInk 2.x only; 1.6 is retired).
| Server-free Android catalog operations: companion-owned covers, refresh, copies, recommendations and end-of-book snapshots and commands. | Android; X4 Pro, X4, X3 later under Android-first ruling | building: covers, mirror planning and query/store reads migrated; copies, grouping, recommendations and finish pending |
| Independent optional account, sync and OPDS logins, encrypted credentials, origin-aware sign-out and account-wide reading statistics through the library interface. | Android; X4 Pro, X4, X3 later | building (Android F12-K foundation and F12-N plugin screens implemented; device acceptance and firmware follow) |
| Configure one Book list widget with presets, paged counted sources and local Custom filters in the Home editor. | Android building; X4 Pro, X4, X3 follow Android | building (approved design rev 16; device acceptance pending) |
| Three-page Android Home, Library and Stats layout with Library widgets, shared filtered lists/search and saving custom filters as Home tiles. | Android building; X4 Pro, X4, X3 deferred by Android-first ruling | building (authorised 2026-11-25; device acceptance pending) |
| Two-page Android Home and Stats default (§4), with Library widgets, shared filtered lists/search and saving custom filters as Home tiles. | Android building; X4 Pro, X4, X3 deferred by Android-first ruling | building (authorised 2026-11-25; device acceptance pending) |
| Clear, editable Custom reading values, apply-then-edit quick choices, device-local margins and one-time KOReader copy with Undo. | Android building (approved rev 16); X4 Pro, X4, X3 deferred to firmware implementation | building (F12-M; implemented, device acceptance pending) |
| On-device Home editor: add/remove/move/resize widgets, manage and name pages, reset and atomically save layouts. | Android building (authorised 2026-11-25); X4 Pro, X4, X3 deferred to firmware implementation | building (device acceptance pending) |
| Default owned Home for fresh installs and upgrades, additive migration, once-only upgrade news and clear signed-out shelves; paged widgets share one budgeted batch per paint. | Android; X4 Pro, X4, X3 later | building (authorised 2026-11-25; device acceptance pending) |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// SPDX-License-Identifier: MIT
package net.fledgewing.orbitcompanion

import java.io.File
import java.security.MessageDigest

/** Device files have an identity even before a server is configured. Only the companion
* scans and parses native sidecars; LibraryReadModel still bounds every published window. */
class DeviceLibrary(private val roots: List<File>) : ServerAdapter {
override val id = "device"
companion object { const val OWNER = "device-local" }
private val books by lazy {
roots.distinctBy { it.canonicalPath }.flatMap { root ->
if (!root.isDirectory) emptyList() else root.walkTopDown().onEnter {
BulkWork.checkpoint()
Places.inside(it,listOf(root)) != null && !java.nio.file.Files.isSymbolicLink(it.toPath()) && !it.name.endsWith(".sdr")
}.filter { it.isFile && it.extension.lowercase() in setOf("epub","pdf","mobi","azw","azw3","fb2","djvu","cbz","cbr","txt") &&
Places.inside(it,listOf(root)) != null }.map(::book).toList()
}.distinctBy { it["key"] }
}
private fun sidecar(file: File) = File(file.parentFile,"${file.nameWithoutExtension}.sdr")
private fun book(file: File): Map<String,Any?> {
BulkWork.checkpoint()
val metadata=File(sidecar(file),"metadata.${file.extension}.lua")
val data=if(metadata.isFile && metadata.length()<=1048576 && Places.inside(metadata,roots)!=null) runCatching {
val text=metadata.readText(Charsets.ISO_8859_1).replaceFirst(Regex("\\A(?:--[^\\n]*\\n)?\\s*return\\s+"),"")
LuaValue.parse(text.toByteArray(Charsets.ISO_8859_1)) as? Map<*,*>
}.getOrNull() else null
val props=data?.get("doc_props") as? Map<*,*>
val summary=data?.get("summary") as? Map<*,*>
val fraction=(data?.get("percent_finished") as? Number)?.toDouble()?.takeIf { it.isFinite() && it in 0.0..1.0 }
val status=when(summary?.get("status")) { "complete" -> "finished"; "reading" -> "reading"; "abandoned" -> "abandoned"; else -> if(fraction!=null && fraction>0) "reading" else "unread" }
val hash=MessageDigest.getInstance("SHA-256").digest(file.canonicalPath.toByteArray()).joinToString("") { "%02x".format(it) }
val cover=sidecar(file).listFiles()?.filter { it.isFile && it.nameWithoutExtension=="cover" && Places.inside(it,roots)!=null }?.sortedBy { it.name }?.firstOrNull()
return mapOf("key" to "device:book:$hash","title" to LuaValue.boundedText((props?.get("title") as? String)?.let(LuaValue::utf8) ?: file.nameWithoutExtension,256),
"authors" to listOfNotNull((props?.get("authors") as? String)?.let { LuaValue.boundedText(LuaValue.utf8(it),256) }),
"local_path" to LuaValue.str(file.canonicalPath),"on_device" to true,"status" to status,"progress" to fraction?.times(100),
"last_read" to (metadata.lastModified()/1000).takeIf { metadata.isFile },"cover_path" to cover?.path?.let(LuaValue::str),
"formats" to listOf(file.extension.lowercase()),"available" to mapOf("cover" to (cover!=null)),"downloadable" to false)
}
override fun localFiles(owner: String): List<LocalBook>? = if(owner==OWNER) books.map {
LocalBook(File(LuaValue.utf8(it["local_path"] as String)),it["status"]=="finished",null)
} else null
override fun project(owner: String, request: Map<*,*>): Map<String,Any?> {
if(owner!=OWNER) return mapOf("error" to "unauthorized")
val fresh=mapOf("saved" to true,"origin" to "local-device")
fun rows(items: List<*>) = mapOf("items" to items,"freshness" to fresh)
val op=request["op"]
if(op=="capabilities") return mapOf("onDevice" to true,"readingStats" to true,"catalog" to true,"detail" to true,"download" to false,
"lists" to mapOf("read" to false,"save" to false),"wantToRead" to false,"progress" to mapOf("read" to true,"write" to false),
"status" to mapOf("read" to true,"write" to false))
if(op in setOf("lists","collections")) return rows(emptyList<Any>())
if(op=="sources") {
val definitions=listOf(Triple("device","On this device",books.size),Triple("reading","Reading now",books.count { it["status"]=="reading" }),Triple("finished","Finished",books.count { it["status"]=="finished" }))
val offset=((request["offset"] as? Number)?.toInt() ?: 0).coerceAtLeast(0)
val limit=((request["limit"] as? Number)?.toInt() ?: 6).coerceIn(1,6)
val items=if(request["category"] in setOf("lists","authors")) emptyList() else definitions.drop(offset).take(limit).map { (src,title,count) -> mapOf("src" to src,"title" to title,"count" to count) }
return rows(items)+mapOf("total" to if(items.isEmpty()) 0 else definitions.size)
}
if(op=="catalog.state") return mapOf("state" to "idle","freshness" to fresh)
if(op=="library.summary") return mapOf("total" to books.size,"on_device" to books.size,"freshness" to fresh)
if(op in setOf("book","reader","progress","status","cover")) {
val row=books.firstOrNull { if(op=="reader") it["local_path"]==request["path"] else it["key"]==request["key"] } ?: return rows(emptyList<Any>())
return when(op) {
"cover" -> mapOf("local_path" to row["cover_path"],"freshness" to fresh)
"progress","status" -> row + mapOf("freshness" to fresh)
else -> rows(listOf(row))
}
}
if(op !in setOf("window","counts","facets","groups")) return rows(emptyList<Any>())
val filter=(request["query"] as? Map<*,*>).orEmpty().entries.associate { it.key.toString() to it.value }
LibraryFilter.validate(filter)
val source=request["source"]
val sourceFilter=when(source) { "reading" -> mapOf("show" to "reading"); "finished" -> mapOf("show" to "finished"); "want-to-read" -> mapOf("wtr" to true); else -> emptyMap() }
var selected=if(source !in setOf("all","library/all","on-device","reading","finished","search")) emptyList() else books.filter { LibraryFilter.matches(it,sourceFilter) && LibraryFilter.matches(it,filter) }
val sort=if(filter["sort"]==null && source=="reading") filter+mapOf("sort" to "last","dir" to "desc") else filter
selected=selected.sortedWith(LibraryFilter.comparator(sort))
if(request["exclude_current"]==true && source=="reading") selected=selected.drop(1)
val offset=((request["offset"] as? Number)?.toInt() ?: 0).coerceAtLeast(0)
val limit=((request["limit"] as? Number)?.toInt() ?: 24).coerceIn(1,24)
if(op=="groups") return SeriesPresentation.groups(selected,filter,offset,limit.coerceAtLeast(5),
((request["preview"] as? Number)?.toInt() ?: 3).coerceIn(1,9),
((request["group_limit"] as? Number)?.toInt() ?: 2).coerceIn(1,6))+mapOf("freshness" to fresh)
if(op=="counts") return mapOf("total" to selected.size,"freshness" to fresh)
if(op=="facets") return LibraryFacets(request["field"].toString(),filter,System.currentTimeMillis()/1000).let { facet ->
selected.forEach { facet.include(it) }; facet.page(offset,limit)+mapOf("freshness" to fresh) }
return rows(selected.drop(offset).take(limit)) + mapOf("total" to selected.size,"next" to (offset+limit).takeIf { it<selected.size },"local_coverage" to "device-files")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ class LibraryReadModel(
private val fallbackReadingStats: ((String) -> RemoteReadingStats?)? = null,
private val accountState: () -> Map<String, Any?> = { mapOf("signedIn" to false) },
private val accountStats: (String) -> Map<*, *>? = { null },
private val adapter: ServerAdapter = ServerAdapters.forStore(store, clock = clock,
fallbackReadingStats = fallbackReadingStats, accountState = accountState, accountStats = accountStats),
private val adapter: ServerAdapter? = null,
) {
companion object {
const val MAX_BYTES = 16384
Expand All @@ -27,18 +26,23 @@ class LibraryReadModel(
var changed = false
require(requests.size <= MAX_BATCH)
// Never take ownership from a read command, nor expose a prior account's data.
if (store.meta("owner") != owner) return false
val storage by lazy { DeviceStorage(store, adapter) }
if (owner != DeviceLibrary.OWNER && store.meta("owner") != owner) return false
val local = owner == DeviceLibrary.OWNER
val projection = if (local) DeviceLibrary(DeviceStorage.folders.map {
java.io.File(store.root.parentFile?.parentFile?.parentFile ?: store.root,it)
} + DeviceStorage.downloadRoot(store.root)) else adapter ?: ServerAdapters.forStore(store, clock = clock,
fallbackReadingStats = fallbackReadingStats, accountState = accountState, accountStats = accountStats)
val storage by lazy { DeviceStorage(store, projection) }
val power by lazy { battery() }
val account by lazy { accountStats(owner) }
val stats by lazy { ReadingStats.display(AccountStats.combine(readingStats(), adapter.cachedReadingStats(owner), account, clock()), clock(), AccountStats.zone(account)) }
val account by lazy { if (local) null else accountStats(owner) }
val stats by lazy { ReadingStats.display(AccountStats.combine(readingStats(), if (local) null else projection.cachedReadingStats(owner), account, clock()), clock(), AccountStats.zone(account)) }
for (encoded in requests) {
val start = System.nanoTime()
val request = encoded as? String ?: continue
if (request.length > 8192) continue
val args = LuaValue.parse(request.toByteArray(Charsets.ISO_8859_1)) as? Map<*, *> ?: continue
store.transaction {
if (store.meta("owner") != owner) return@transaction
if (!local && store.meta("owner") != owner) return@transaction
val result = try { when (args["op"]) {
"storage.summary" -> storage.summary(owner,(args["exclude_path"] as? String)?.let(LuaValue::utf8),(args["current_folder"] as? String)?.let(LuaValue::utf8))
"reader.controls" -> ReaderControls.project(args["native"] as? Map<*, *> ?: emptyMap<Any, Any>())
Expand All @@ -48,8 +52,8 @@ class LibraryReadModel(
"mode-estimates" -> BatteryEstimate.modeRows(power, (args["limit"] as? Number)?.toInt() ?: 3)
"battery" -> power
"sleep.choices" -> SleepChoiceWindow.project(SleepChoices.read(SleepScreen.dir()), args)
"capabilities" -> adapter.capabilities(owner) + mapOf("battery" to true)
else -> adapter.project(owner, args)
"capabilities" -> projection.capabilities(owner) + mapOf("battery" to true)
else -> projection.project(owner, args)
} } catch (_: IllegalArgumentException) { mapOf("error" to "unsupported", "items" to emptyList<Any>()) }
val items = result["items"] as? List<*>
val measuredRows = items.orEmpty().size + items.orEmpty().sumOf {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import net.fledgewing.orbitcompanion.server.bookorbit.BookOrbitProjection
import net.fledgewing.orbitcompanion.server.bookorbit.BookOrbitLibrary
import net.fledgewing.orbitcompanion.server.bookorbit.CacheStore
import net.fledgewing.orbitcompanion.server.bookorbit.ConnectorPlugin
import net.fledgewing.orbitcompanion.server.bookorbit.LegacyLoginAdoption
import net.fledgewing.orbitcompanion.server.bookorbit.SleepChoicesProjection

/** The only production composition root allowed to import an implementation. */
Expand All @@ -27,6 +28,9 @@ object ServerAdapters {
fun session(ctx: Context, id: String = "bookorbit"): ServerAdapter {
require(id == "bookorbit") { "unknown adapter" }
val credentials = ServerCredentials(EncryptedAccountVault.android(ctx))
LegacyLoginAdoption.run(credentials,
java.io.File(android.os.Environment.getExternalStorageDirectory(), "koreader/settings.reader.lua"),
java.io.File(android.os.Environment.getExternalStorageDirectory(), "koreader/settings/opds.lua"))
val account = BookOrbitAccount(credentials.accountVault, AccountHttp, setupOnSignIn = { false })
return BookOrbitServerAdapter(credentials, account, ConnectorHttp,
legacyAccount = { net.fledgewing.orbitcompanion.server.bookorbit.LegacyCoverSource.read(
Expand All @@ -36,6 +40,7 @@ object ServerAdapters {
AdapterWorker.acquireCoverReference(ctx,creds,owner,reference,refresh,done)
}, coverJob = { creds, owner, key, done -> AdapterWorker.acquireCover(ctx,creds,owner,key,done) })
}
fun projectionStore(root: java.io.File): ProjectionStore = CacheStore(root)
val cachedLists: CachedListProjection get() = SleepChoicesProjection
val connector: ConnectorInstaller get() = ConnectorPlugin
val runtime: ServerRuntime get() = AdapterWorker
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,32 @@ object Worker {
fun busy() = ServerAdapters.runtime.busy()
val mirrorRunning get() = ServerAdapters.runtime.mirrorRunning
fun progressLine() = ServerAdapters.runtime.progressLine()
fun onIntent(ctx: Context, i: Intent) = ServerAdapters.runtime.onIntent(ctx, i)
fun onIntent(ctx: Context, i: Intent) {
if (i.action == ACTION_PATCH && i.getStringExtra("owner") == DeviceLibrary.OWNER && i.hasExtra("library_batch")) {
val encoded=i.getStringExtra("library_batch")?.takeIf { it.length<=131072 } ?: return
val app=ctx.applicationContext
BulkWork.attach(app)
BulkWork.executor.execute {
runCatching {
val requests=LuaValue.parse(LuaValue.str(encoded).toByteArray(Charsets.ISO_8859_1)) as? List<*> ?: return@runCatching
ServerAdapters.projectionStore(root()).use { store ->
val model=LibraryReadModel(store,readingStats={
ReadingStats.read(File(root().parentFile,"statistics.sqlite3"),System.currentTimeMillis()/1000)
},battery={ StatsStore.get(app).batterySnapshot(System.currentTimeMillis(),java.time.ZoneId.systemDefault()) })
if(model.publish(DeviceLibrary.OWNER,requests)) {
val spool=File(root(),"events").apply { mkdirs() }
val file=File(spool,"device-${java.util.UUID.randomUUID()}.lua")
android.util.AtomicFile(file).let { atomic ->
val out=atomic.startWrite()
try { out.write(LuaValue.encode(mapOf("kind" to "library","owner" to DeviceLibrary.OWNER))); atomic.finishWrite(out) }
catch(e: Exception) { atomic.failWrite(out); throw e }
}
ServerAdapters.runtime.onIntent(app,Intent(ACTION_PATCH).putExtra("drain_events","1"))
}
}
}.onFailure { OLog.w("library.device publication unavailable") }
}
} else ServerAdapters.runtime.onIntent(ctx,i)
}
internal fun nativeFooterRepair(before: String, after: String, token: String) = ServerAdapters.runtime.nativeFooterRepair(before, after, token)
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ internal class BookOrbitServerAdapter(private val credentials: ServerCredentials
"username" to accountState["username"], "server" to accountState["server"],
"account" to mapOf("set" to (accountState["signedIn"] == true), "origin" to "user".takeIf { accountState["signedIn"] == true }),
"sync" to status("sync"), "opds" to status("opds"), "owner" to sourceOwner,
"catalog" to mapOf("cachedDetail" to (legacy!=null),"canRefresh" to (legacy!=null || credentials.login("sync")?.owner()==sourceOwner)))
"catalog" to mapOf("cachedDetail" to (legacy!=null || credentials.login("sync")?.let { it.adopted && it.owner()==sourceOwner }==true),"canRefresh" to (legacy!=null || credentials.login("sync")?.owner()==sourceOwner)))
}
override fun signIn(server: String, username: String, password: CharArray) {
try {
Expand Down
Loading
Loading