diff --git a/plugins/gzreader.koplugin/gzreader_annotations.lua b/plugins/gzreader.koplugin/gzreader_annotations.lua index 45854f996..61c459be2 100644 --- a/plugins/gzreader.koplugin/gzreader_annotations.lua +++ b/plugins/gzreader.koplugin/gzreader_annotations.lua @@ -42,7 +42,7 @@ function Anno:new(sync) end function Anno:enabled() - return self.plugin:syncEnabled() and self.plugin.store.annotation_sync_disabled ~= true + return self.plugin:syncEnabled() and self.plugin:serverCan("annotations") and self.plugin.store.annotation_sync_disabled ~= true and self.is_epub and self.file ~= nil end diff --git a/plugins/gzreader.koplugin/gzreader_async.lua b/plugins/gzreader.koplugin/gzreader_async.lua index 15afd1142..96bbcd710 100644 --- a/plugins/gzreader.koplugin/gzreader_async.lua +++ b/plugins/gzreader.koplugin/gzreader_async.lua @@ -471,6 +471,9 @@ end --- A valid login for a process forked outside this queue (downloads, the --- library index): refreshed in the background if needed, then cb(ok, err). function Async.ensureToken(api, cb) + -- (BookOrbit has no login to refresh: its sign-in goes with every request. Without this, + -- every download and index run started a background process that did nothing.) + if api.koreader_positions then return cb(true) end local store = api.store or {} if store.access_token and os.time() < (store.access_expires_at or 0) - 120 then return cb(true) end Async.run(api, function() return true end, function(ok, err) cb(ok == true, err) end, "refresh login") diff --git a/plugins/gzreader.koplugin/gzreader_bo_annotations.lua b/plugins/gzreader.koplugin/gzreader_bo_annotations.lua new file mode 100644 index 000000000..2640ee074 --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_bo_annotations.lua @@ -0,0 +1,344 @@ +--[[-- +Two-way highlight and note sync with BookOrbit, for books whose place is an +XPointer (EPUB and the other reflowable formats). + +BookOrbit's exchange (POST /koreader/plugin/annotations/exchange): the Kindle +sends, for one book, + * the key of every highlight it has (md5 of "|"), so the + server can tell which ones were deleted here; + * the highlights that are new or changed since the last exchange, as KOReader + keeps them (XPointers, text, note, style, colour); +and BookOrbit answers with what this Kindle lacks: highlights to add, to change +and to remove, made or changed on its web reader or another device. They are +put into the open book (or its settings file, if it closed meanwhile), and an +acknowledgement says which were applied. BookOrbit converts positions between +KOReader's and its web reader's itself, so nothing is converted here (Grimmory's +highlights are, gzreader_annotations.lua). + +The same interface as gzreader_annotations.lua (new, run, onAnnotationsModified, +onClose): main picks this one when the book server is BookOrbit. + +State in the download entry: + entry.bo_anno = { [key] = fingerprint of what was last exchanged } + (nil: this copy has never been through an exchange: sent as sidecarState + "new", so nothing is deleted and everything is offered again) + entry.anno_dirty = true while changes here may not be on BookOrbit yet + +Written from BookOrbit's routes and field names; none of its plugin's code is here. +]] + +local UIManager = require("ui/uimanager") +local Log = require("gzreader_log") + +local Anno = { DEBOUNCE = 3, MAX_CHANGES = 50, MAX_KEYS = 5000, MAX_ROUNDS = 8 } +Anno.__index = Anno + +local DRAWERS = { lighten = true, underscore = true, strikeout = true, invert = true } + +function Anno:new(sync) + return setmetatable({ + sync = sync, ui = sync.ui, api = sync.api, plugin = sync.plugin, entry = sync.entry, + book_id = sync.book_id, file = sync.ui.document and sync.ui.document.file, + rolling = sync.ui.document ~= nil and sync:isRolling(), + }, self) +end + +function Anno:enabled() + return self.plugin:syncEnabled() and self.plugin:serverCan("annotations") and self.plugin.store.annotation_sync_disabled ~= true + and self.rolling and self.file ~= nil and type(self.entry.hash) == "string" and not self.off +end + +local function isHighlight(a) + return type(a) == "table" and type(a.pos0) == "string" and type(a.pos1) == "string" and type(a.datetime) == "string" +end + +local function md5(s) return require("ffi/sha2").md5(s) end + +--- A highlight's identity for BookOrbit: md5 of "|". +function Anno.key(a) return md5(tostring(a.datetime) .. "|" .. tostring(a.pos0)) end + +local function text(v) return type(v) == "string" and v ~= "" and v or nil end + +--- What BookOrbit keeps of a highlight, as one string: it changed when this did. +function Anno.fingerprint(a) + return md5(table.concat({ DRAWERS[a.drawer] and a.drawer or "lighten", tostring(a.color or ""), tostring(a.text or ""), + tostring(text(a.note) or ""), tostring(a.pos1 or "") }, "\0")) +end + +--- A highlight as the exchange takes one. +function Anno.toRemote(a) + return { + datetime = a.datetime, + datetimeUpdated = text(a.datetime_updated), + drawer = DRAWERS[a.drawer] and a.drawer or "lighten", + color = text(a.color) and a.color:sub(1, 30) or nil, + text = text(a.text) and a.text:sub(1, 10000) or nil, + note = text(a.note) and a.note:sub(1, 5000) or nil, + chapter = text(a.chapter) and a.chapter:sub(1, 500) or nil, + pageno = type(a.pageno) == "number" and a.pageno >= 0 and math.floor(a.pageno) or nil, + posFormat = "xpointer", + pos0 = a.pos0, + pos1 = a.pos1, + } +end + +--- The book's highlights now: the open book's, or its settings file's. +function Anno:live() + local ui = self.ui + if ui.document and ui.document.file == self.file and ui.annotation then + return ui.annotation.annotations or {}, true + end + local ok, list = pcall(function() return require("docsettings"):open(self.file):readSetting("annotations") end) + return ok and type(list) == "table" and list or {}, false +end + +--- What to send: every highlight's key, and the ones new or changed since `known` +--- (entry.bo_anno). Returns keys, changes (all of them), complete (the key list is whole). +function Anno.outgoing(list, known) + local keys, changes = {}, {} + known = type(known) == "table" and known or {} + for _i, a in ipairs(list) do + if isHighlight(a) then + local k = Anno.key(a) + if #keys < Anno.MAX_KEYS then keys[#keys + 1] = { k = k, dt = a.datetime } end + if known[k] ~= Anno.fingerprint(a) then changes[#changes + 1] = Anno.toRemote(a) end + end + end + local n = 0 + for _i, a in ipairs(list) do if isHighlight(a) then n = n + 1 end end + return keys, changes, n <= Anno.MAX_KEYS +end + +--- In the background: the exchanges for one book (its changes 50 at a time). +--- Returns { add, edit, delete, sent } or nil, err. +function Anno.work(api, hash, keys, changes, complete, state) + local Json = require("gzreader_json") + local out = { add = {}, edit = {}, delete = {}, sent = 0, taken = {} } + local from, rounds = 1, 0 + repeat + rounds = rounds + 1 + local part = {} + for i = from, math.min(from + Anno.MAX_CHANGES - 1, #changes) do part[#part + 1] = changes[i] end + from = from + #part + local res, err = api:exchangeAnnotations({ hash = hash, keys = Json.list(keys), keysComplete = complete, + sidecarState = state, changes = Json.list(part) }) + if not res then return nil, err end + state = "known" -- (only the first round of a fresh copy says "new") + out.sent = out.sent + #part + for _i, c in ipairs(part) do out.taken[#out.taken + 1] = c end + local t = type(res.toApply) == "table" and res.toApply or {} + local seen = {} + for _i, kind in ipairs({ "add", "edit", "delete" }) do + for _j, e in ipairs(type(t[kind]) == "table" and t[kind] or {}) do + if type(e) == "table" and type(e.serverId) == "number" and not seen[kind .. e.serverId] then + seen[kind .. e.serverId] = true + out[kind][#out[kind] + 1] = e + end + end + end + -- (what BookOrbit still has for this Kindle comes after these are acknowledged: the next pass) + out.more = res.more == true + until from > #changes or rounds >= Anno.MAX_ROUNDS + out.unsent = #changes - out.sent + return out +end + +local function clean(v) return type(v) == "string" and v ~= "" and v or nil end + +--- Put BookOrbit's answer into the list of highlights (in place). `valid(xp)`: +--- is this XPointer in the book (nil when the book isn't open: taken as it is). +--- Returns changed, applied (for the acknowledgement), deleted (same). +function Anno.merge(list, res, valid) + local by_key = {} + for i, a in ipairs(list) do if isHighlight(a) then by_key[Anno.key(a)] = i end end + local applied, deleted, changed = {}, {}, false + local remove = {} + for _i, e in ipairs(res.delete or {}) do + local i = type(e.key) == "string" and by_key[e.key] + if i then remove[i] = true end + -- (not here any more is what was asked for) + deleted[#deleted + 1] = { serverId = e.serverId, status = "applied" } + end + for _i, e in ipairs(res.edit or {}) do + local i = type(e.key) == "string" and by_key[e.key] + local a = i and not remove[i] and list[i] + if a then + a.drawer = DRAWERS[e.drawer] and e.drawer or a.drawer + a.color = clean(e.color) or a.color + if clean(e.text) then a.text = e.text end + a.note = clean(e.note) + if clean(e.chapter) then a.chapter = e.chapter end + a.datetime_updated = clean(e.datetimeUpdated) or a.datetime_updated + changed = true + applied[#applied + 1] = { serverId = e.serverId, version = e.version, status = "applied" } + else + applied[#applied + 1] = { serverId = e.serverId, version = e.version, status = "failed" } + end + end + if next(remove) then + for i = #list, 1, -1 do if remove[i] then table.remove(list, i) end end + changed = true + by_key = {} + for i, a in ipairs(list) do if isHighlight(a) then by_key[Anno.key(a)] = i end end + end + for _i, e in ipairs(res.add or {}) do + local ok = e.posFormat == "xpointer" and clean(e.pos0) and clean(e.pos1) and clean(e.datetime) + and (not valid or (valid(e.pos0) and valid(e.pos1))) + if ok then + local a = { datetime = e.datetime, datetime_updated = clean(e.datetimeUpdated), drawer = DRAWERS[e.drawer] and e.drawer or "lighten", + color = clean(e.color) or "yellow", text = clean(e.text) or "", note = clean(e.note), chapter = clean(e.chapter), + pageno = type(e.pageno) == "number" and e.pageno or nil, page = e.pos0, pos0 = e.pos0, pos1 = e.pos1 } + if not by_key[Anno.key(a)] then -- (already here: sent again because the last answer was lost) + list[#list + 1] = a + by_key[Anno.key(a)] = #list + changed = true + end + applied[#applied + 1] = { serverId = e.serverId, version = e.version, status = "applied" } + else + applied[#applied + 1] = { serverId = e.serverId, version = e.version, status = "failed" } + end + end + return changed, applied, deleted +end + +--- Act on a finished pass. +function Anno:apply(res) + local list, open = self:live() + local doc = open and self.ui.document + local valid = doc and doc.isXPointerInDocument and function(xp) + local ok, yes = pcall(doc.isXPointerInDocument, doc, xp) + return ok and yes + end or nil + local changed, applied, deleted = Anno.merge(list, res, valid) + local saved = true + if changed then + self.applying = true + if open and self.ui.annotation.sortItems then pcall(self.ui.annotation.sortItems, self.ui.annotation, list) end + local copy = {} -- (saveLocal refills the book's own table from what it's given) + for i, item in ipairs(list) do copy[i] = item end + saved = require("gzreader_annotations").saveLocal(self, copy) + if open then list = self.ui.annotation.annotations end + self.applying = false + end + -- what BookOrbit now has of this Kindle's highlights: what was sent, and what it gave + local known = type(self.entry.bo_anno) == "table" and self.entry.bo_anno or {} + local now = {} + local sent = {} + for _i, c in ipairs(res.taken or {}) do sent[md5(tostring(c.datetime) .. "|" .. tostring(c.pos0))] = true end + local given = {} + for _i, e in ipairs(res.add or {}) do given[md5(tostring(e.datetime) .. "|" .. tostring(e.pos0))] = true end + for _i, e in ipairs(res.edit or {}) do if type(e.key) == "string" then given[e.key] = true end end + for _i, a in ipairs(list) do + if isHighlight(a) then + local k = Anno.key(a) + if sent[k] or given[k] then now[k] = Anno.fingerprint(a) else now[k] = known[k] end + end + end + self.entry.bo_anno = now + local failed = 0 + for _i, e in ipairs(applied) do if e.status == "failed" then failed = failed + 1 end end + local more = res.more or (res.unsent or 0) > 0 + self.entry.anno_dirty = (not saved or more) and true or nil + self.plugin:save() + Log.info("BookOrbit highlights", self.book_id, "sent", res.sent or 0, "added here", #(res.add or {}) - failed, "changed here", #(res.edit or {}), + "removed here", #(res.delete or {}), failed > 0 and ("couldn't be placed: " .. failed) or "") + if saved and (#applied > 0 or #deleted > 0) then + local hash = self.entry.hash + require("gzreader_async").run(self.api, function(api) return api:ackAnnotations(hash, applied, deleted) end, function(ok, err) + if not ok then Log.info("BookOrbit highlights: the acknowledgement didn't arrive (asked again next time):", tostring(err)) end + if more and not self.closed and self.plugin.sync == self.sync then self:run() end + end, "annotations ack") + end + return list +end + +--- One pass (in the background). on_done(ok) optional. +function Anno:run(on_done) + if not self:enabled() then return on_done and on_done(false) end + if self.busy then self.again = true; return end + if not require("gzreader_net").connected() then return on_done and on_done(false) end + self.busy, self.again, self.touched = true, false, false + local list = self.snapshot and self.snapshot() or self:live() + local keys, changes, complete = Anno.outgoing(list, self.entry.bo_anno) + local hash, state = self.entry.hash, type(self.entry.bo_anno) == "table" and "known" or "new" + require("gzreader_async").run(self.api, function(api) + return Anno.work(api, hash, keys, changes, complete, state) + end, function(res, err) + self.busy = false + local ok = false + if type(res) ~= "table" then + if err == "bookorbit_unmatched" or err == "bookorbit_incompatible" then + -- (BookOrbit has no book with this file, or its copy differs: nothing to place highlights on) + Log.info("BookOrbit highlights: not synced for this book:", err) + self.off = true + else + Log.warn("BookOrbit highlight sync failed:", tostring(err)) + self.entry.anno_dirty = true + self.plugin:save() + end + elseif self.touched then + self.again = true -- changed here while the pass ran: start over from the new state + else + local done, crash = pcall(self.apply, self, res) + if not done then Log.warn("BookOrbit highlight merge failed:", tostring(crash)) else ok = true end + end + if self.again and not self.closed then + self.again = false + UIManager:scheduleIn(1, function() self:run(on_done) end) + return + end + if on_done then on_done(ok) end + end, "annotations", { nice = true, timeout = 300 }) +end + +--- KOReader event: a highlight or note was added, changed or removed. +function Anno:onAnnotationsModified(items) + if self.applying or type(items) ~= "table" or items.gz_synced then return end + if not isHighlight(items[1]) then return end -- page bookmarks: their own sync + if not self:enabled() then return end + self.entry.anno_dirty = true + self.touched = true + if self.pending then UIManager:unschedule(self.pending) end + if not require("gzreader_net").connected() then return end -- sent on close / next open + self.pending = function() + self.pending = nil + self:run() + end + UIManager:scheduleIn(Anno.DEBOUNCE, self.pending) +end + +--- Anything here that BookOrbit doesn't have yet (a note edited: KOReader says nothing then)? +function Anno:changedHere() + local known = type(self.entry.bo_anno) == "table" and self.entry.bo_anno or nil + if not known then return true end + local list = self:live() + local seen = {} + for _i, a in ipairs(list) do + if isHighlight(a) then + local k = Anno.key(a) + seen[k] = true + if known[k] ~= Anno.fingerprint(a) then return true end + end + end + for k in pairs(known) do if not seen[k] then return true end end + return false +end + +--- The book is closing: send what's waiting (Wi-Fi only when needed: brought up quietly). +function Anno:onClose() + if self.pending then UIManager:unschedule(self.pending); self.pending = nil end + self.closed = true + if not self:enabled() then return end + if not self.entry.anno_dirty and self:changedHere() then self.entry.anno_dirty = true end + if not self.entry.anno_dirty then return end + local Net = require("gzreader_net") + local copy = {} + for i, a in ipairs((self:live())) do copy[i] = a end + self.snapshot = function() return copy end -- the book's highlights as it closed + if Net.connected() then return self:run() end + UIManager:scheduleIn(1, function() + Net.run(function() self:run() end, { quiet = true, reason = "highlights on close" }) + end) +end + +return Anno diff --git a/plugins/gzreader.koplugin/gzreader_bo_bookmarks.lua b/plugins/gzreader.koplugin/gzreader_bo_bookmarks.lua new file mode 100644 index 000000000..c21dc5e4f --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_bo_bookmarks.lua @@ -0,0 +1,236 @@ +--[[-- +Two-way page-bookmark sync with BookOrbit (the dog-ears), for books whose +place is an XPointer (EPUB and the other reflowable formats), when the server +says it does bookmarks (its `bookmarkSync` capability). + +BookOrbit's exchange (POST /koreader/plugin/bookmarks/exchange), like the one +for highlights (gzreader_bo_annotations.lua): the Kindle sends the key of every +bookmark in the book (md5 of "|") and the ones BookOrbit hasn't +had from it; BookOrbit answers with bookmarks to add (made elsewhere) and to +remove. A bookmark BookOrbit gives has no date: the Kindle dates it and says +in the acknowledgement which key it now has here. Bookmarks aren't edited. + +The same interface as gzreader_bookmarks.lua (new, reconcile, +onAnnotationsModified): main picks this one when the book server is BookOrbit. + +State in the download entry: + entry.bo_marks = { [key] = true } what BookOrbit has had from, or given to, this copy + (nil: never exchanged: sent as sidecarState "new", so nothing is deleted) + +Written from BookOrbit's routes and field names; none of its plugin's code is here. +]] + +local UIManager = require("ui/uimanager") +local Log = require("gzreader_log") + +local BM = { DEBOUNCE = 3, MAX_CHANGES = 50, MAX_KEYS = 2000 } +BM.__index = BM + +function BM:new(sync) + return setmetatable({ + sync = sync, ui = sync.ui, api = sync.api, plugin = sync.plugin, entry = sync.entry, + book_id = sync.book_id, file = sync.ui.document and sync.ui.document.file, + rolling = sync.ui.document ~= nil and sync:isRolling(), + }, self) +end + +function BM:enabled() + return self.plugin:syncEnabled() and self.plugin:serverCan("bookmarks") and self.plugin.store.bookmark_sync_disabled ~= true + and self.rolling and self.file ~= nil and type(self.entry.hash) == "string" and not self.off + and (type(self.api.can) ~= "function" or self.api:can("bookmarkSync")) +end + +local function md5(s) return require("ffi/sha2").md5(s) end +local function text(v) return type(v) == "string" and v ~= "" and v or nil end + +local function isPageBookmark(item) + return type(item) == "table" and not item.drawer and not item.pos0 and type(item.page) == "string" +end +BM.isPageBookmark = isPageBookmark + +function BM.key(item) return md5(tostring(item.datetime) .. "|" .. tostring(item.page)) end + +function BM.toRemote(item) + return { datetime = item.datetime, datetimeUpdated = text(item.datetime_updated), pos = item.page, + pageno = type(item.pageno) == "number" and item.pageno >= 0 and math.floor(item.pageno) or nil, + chapter = text(item.chapter) and item.chapter:sub(1, 500) or nil, + note = text(item.text) and item.text:sub(1, 500) or nil } +end + +function BM:live() + local ui = self.ui + if ui.document and ui.document.file == self.file and ui.annotation then return ui.annotation.annotations or {}, true end + local ok, list = pcall(function() return require("docsettings"):open(self.file):readSetting("annotations") end) + return ok and type(list) == "table" and list or {}, false +end + +--- What to send: every bookmark's key, and the ones not in `known`. A bookmark with no +--- date (one an older GZreader put there) is dated now, once (dated = true then). +function BM.outgoing(list, known, now) + local keys, changes, dated = {}, {}, false + known = type(known) == "table" and known or {} + for _i, item in ipairs(list) do + if isPageBookmark(item) then + if not text(item.datetime) then item.datetime = now or os.date("%Y-%m-%d %H:%M:%S"); dated = true end + local k = BM.key(item) + if #keys < BM.MAX_KEYS then keys[#keys + 1] = { k = k, dt = item.datetime } end + if not known[k] and #changes < BM.MAX_CHANGES then changes[#changes + 1] = BM.toRemote(item) end + end + end + return keys, changes, #keys < BM.MAX_KEYS, dated +end + +--- Put BookOrbit's answer into the list (in place). Returns changed, applied, deleted. +function BM.merge(list, res, valid, chapterOf, now) + local by_key, by_pos = {}, {} + for i, item in ipairs(list) do + if isPageBookmark(item) then + if text(item.datetime) then by_key[BM.key(item)] = i end + by_pos[item.page] = i + end + end + local applied, deleted, changed, remove = {}, {}, false, {} + for _i, e in ipairs(res.delete or {}) do + local i = type(e.key) == "string" and by_key[e.key] + if i then remove[i] = true end + deleted[#deleted + 1] = { serverId = e.serverId, status = "applied" } + end + if next(remove) then + for i = #list, 1, -1 do + if remove[i] then by_pos[list[i].page] = nil; table.remove(list, i) end + end + changed = true + by_pos = {} + for i, item in ipairs(list) do if isPageBookmark(item) then by_pos[item.page] = i end end + end + for _i, e in ipairs(res.add or {}) do + local pos = text(e.pos) + if pos and pos:sub(1, 1) == "/" and (not valid or valid(pos)) then + local item = by_pos[pos] and list[by_pos[pos]] + if not item then -- (a page that's already dog-eared here keeps its own bookmark) + item = { datetime = now or os.date("%Y-%m-%d %H:%M:%S"), page = pos, text = text(e.title), + pageno = type(e.pageno) == "number" and e.pageno or nil, chapter = chapterOf and text(chapterOf(pos)) or nil } + list[#list + 1] = item + by_pos[pos] = #list + changed = true + elseif not text(item.datetime) then + item.datetime = now or os.date("%Y-%m-%d %H:%M:%S") + changed = true + end + applied[#applied + 1] = { serverId = e.serverId, status = "applied", key = BM.key(item), datetime = item.datetime, pos = pos } + else + applied[#applied + 1] = { serverId = e.serverId, status = "failed" } + end + end + return changed, applied, deleted +end + +function BM:apply(res, sent_keys) + local list, open = self:live() + local doc = open and self.ui.document + local valid = doc and doc.isXPointerInDocument and function(xp) + local ok, yes = pcall(doc.isXPointerInDocument, doc, xp) + return ok and yes + end or nil + local chapterOf = open and self.ui.toc and function(xp) + local ok, title = pcall(self.ui.toc.getTocTitleByPage, self.ui.toc, xp) + return ok and title or nil + end or nil + local changed, applied, deleted = BM.merge(list, res, valid, chapterOf) + local saved = true + if changed or self.dated then + self.applying = true + if open and self.ui.annotation.sortItems then pcall(self.ui.annotation.sortItems, self.ui.annotation, list) end + local copy = {} + for i, item in ipairs(list) do copy[i] = item end + saved = require("gzreader_annotations").saveLocal(self, copy) + if open then + list = self.ui.annotation.annotations + if self.ui.bookmark and self.ui.bookmark.setDogearVisibility then + pcall(function() self.ui.bookmark:setDogearVisibility(self.ui.bookmark:getCurrentPageNumber()) end) + end + end + self.applying = false + self.dated = nil + end + local known = {} + local ok_keys = {} + for _i, k in ipairs(sent_keys or {}) do ok_keys[k] = true end + for _i, e in ipairs(applied) do if e.key then ok_keys[e.key] = true end end + local old = type(self.entry.bo_marks) == "table" and self.entry.bo_marks or {} + for _i, item in ipairs(list) do + if isPageBookmark(item) and text(item.datetime) then + local k = BM.key(item) + if ok_keys[k] or old[k] then known[k] = true end + end + end + self.entry.bo_marks = known + self.entry.bm_dirty = (not saved or res.more) and true or nil + self.plugin:save() + Log.info("BookOrbit bookmarks", self.book_id, "sent", #(sent_keys or {}), "added here", #(res.add or {}), "removed here", #(res.delete or {})) + if saved and (#applied > 0 or #deleted > 0) then + local hash = self.entry.hash + require("gzreader_async").run(self.api, function(api) return api:ackExchange("bookmarks", hash, applied, deleted) end, function(ok, err) + if not ok then Log.info("BookOrbit bookmarks: the acknowledgement didn't arrive (asked again next time):", tostring(err)) end + end, "bookmarks ack") + end +end + +--- One pass (in the background): called when the book opens, on Sync now, and after a change. +function BM:reconcile(on_done) + if not self:enabled() then return on_done and on_done(false) end + if self.busy then self.again = true; return end + if not require("gzreader_net").connected() then return on_done and on_done(false) end + self.busy, self.again = true, false + local list = self:live() + local keys, changes, complete, dated = BM.outgoing(list, self.entry.bo_marks) + self.dated = dated or self.dated + local sent = {} + for _i, c in ipairs(changes) do sent[#sent + 1] = md5(c.datetime .. "|" .. c.pos) end + local Json = require("gzreader_json") + local book = { hash = self.entry.hash, keys = Json.list(keys), keysComplete = complete, + sidecarState = type(self.entry.bo_marks) == "table" and "known" or "new", changes = Json.list(changes) } + require("gzreader_async").run(self.api, function(api) return api:exchange("bookmarks", book) end, function(res, err) + self.busy = false + local ok = false + if type(res) ~= "table" then + if err == "bookorbit_unmatched" or err == "bookorbit_incompatible" then + Log.info("BookOrbit bookmarks: not synced for this book:", err) + self.off = true + else + Log.warn("BookOrbit bookmark sync failed:", tostring(err)) + self.entry.bm_dirty = true + self.plugin:save() + end + else + res.add = type(res.toApply) == "table" and res.toApply.add or {} + res.delete = type(res.toApply) == "table" and res.toApply.delete or {} + local done, crash = pcall(self.apply, self, res, sent) + if not done then Log.warn("BookOrbit bookmark merge failed:", tostring(crash)) else ok = true end + end + if self.again then + self.again = false + UIManager:scheduleIn(1, function() self:reconcile(on_done) end) + return + end + if on_done then on_done(ok) end + end, "bookmarks", { nice = true }) +end + +--- KOReader event: a bookmark was added or removed. +function BM:onAnnotationsModified(items) + if self.applying or type(items) ~= "table" then return end + local item = items[1] + if type(item) ~= "table" or item.drawer or item.pos0 then return end -- (a highlight: its own sync) + if not self:enabled() then return end + self.entry.bm_dirty = true + if self.pending then UIManager:unschedule(self.pending) end + if not require("gzreader_net").connected() then return end -- sent at the next open + self.pending = function() + self.pending = nil + self:reconcile() + end + UIManager:scheduleIn(BM.DEBOUNCE, self.pending) +end + +return BM diff --git a/plugins/gzreader.koplugin/gzreader_bo_requests.lua b/plugins/gzreader.koplugin/gzreader_bo_requests.lua new file mode 100644 index 000000000..52512b489 --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_bo_requests.lua @@ -0,0 +1,170 @@ +--[[-- +Book requests (BookOrbit): ask the server for a book or audiobook it doesn't +have, and see what became of what you asked for. + +BookOrbit keeps requests on its main API (POST / GET /api/v1/book-requests, +POST :id/cancel), so they need its API key, with the "Request books" +permission. The rows are in the Catalog's BookOrbit card (gzreader_browser.lua). +Nothing is kept on the Kindle: the list is BookOrbit's each time. +]] + +local _ = require("gettext") +local T = require("ffi/util").template + +local Requests = {} + +--- BookOrbit's request states, as shown. +local STATUS = { + pending = _("Waiting for approval"), + approved = _("Approved"), + rejected = _("Declined"), + cancelled = _("Cancelled"), + searching = _("Searching"), + grabbed = _("Downloading"), + downloading = _("Downloading"), + importing = _("Being added to the library"), + needs_review = _("Needs a look in BookOrbit"), + available = _("In the library"), + failed = _("Failed"), +} +-- (states a request can still be cancelled in) +local OPEN = { pending = true, approved = true, searching = true, grabbed = true, downloading = true, needs_review = true, failed = true } + +function Requests.statusText(status) + return STATUS[status] or (type(status) == "string" and status ~= "" and status or _("Unknown")) +end + +function Requests.cancellable(status) return OPEN[status] == true end + +--- Can this Kindle ask for books (BookOrbit, signed in, API key saved)? +function Requests.can(plugin) + local api = type(plugin) == "table" and plugin.api + return type(api) == "table" and type(api.canRequestBooks) == "function" and api:isPaired() and api:canRequestBooks() == true +end + +local function show(text, timeout) + local UIManager = require("ui/uimanager") + UIManager:show(require("ui/widget/infomessage"):new{ text = text, timeout = timeout }) +end + +local function needKey() + show(_("Requesting books needs BookOrbit's API key, with “Request books” ticked: Settings → Accounts and services → Books → BookOrbit API key.")) +end + +--- A row's right-hand text and the line under a request's title. +function Requests.line(r) + local who = type(r.authors) == "table" and table.concat(r.authors, ", ") or "" + local kind = r.kind == "audiobook" and _("audiobook") or _("book") + return who ~= "" and T(_("%1 · %2"), who, kind) or kind +end + +--- What a tap on a request shows. +function Requests.detail(r) + local lines = { r.title or "?", Requests.line(r), "", T(_("Status: %1"), Requests.statusText(r.status)) } + if r.reason and r.reason ~= "" then lines[#lines + 1] = r.reason end + if r.note and r.note ~= "" then lines[#lines + 1] = T(_("Note from BookOrbit: %1"), r.note) end + if r.status == "available" then + lines[#lines + 1] = "" + lines[#lines + 1] = r.kind == "audiobook" and _("It's in the Catalog's Audiobooks page now.") or _("It's in the Catalog now.") + end + return table.concat(lines, "\n") +end + +--- Send a request. `kind`: "ebook" or "audiobook". on_done(ok) afterwards. +function Requests.send(plugin, title, author, kind, on_done) + title = type(title) == "string" and title:gsub("^%s+", ""):gsub("%s+$", "") or "" + author = type(author) == "string" and author:gsub("^%s+", ""):gsub("%s+$", "") or "" + if title == "" then + show(_("Enter the book's title."), 3) + return on_done and on_done(false) + end + require("gzreader_net").run(function() + local res, err = plugin.api:requestBook(title, author ~= "" and { author } or nil, kind) + if not res then + show(plugin:describeError(err)) + return on_done and on_done(false) + end + local what = kind == "audiobook" and _("audiobook") or _("book") + if res.status == "available" then + show(T(_("BookOrbit already has “%1”. Look for it in the Catalog."), res.title or title)) + elseif res.joined then + show(T(_("Someone already asked for “%1” (%2): you'll be counted in. Status: %3."), res.title or title, what, Requests.statusText(res.status))) + else + show(T(_("Asked BookOrbit for “%1” (%2). Status: %3."), res.title or title, what, Requests.statusText(res.status)), 5) + end + require("gzreader_log").info("book requests: one sent,", kind, "status", tostring(res.status)) + if on_done then on_done(true) end + end, { reason = "requesting a book" }) +end + +--- The form: title and author, then Book or Audiobook. +function Requests.ask(plugin, on_done, title) + if not Requests.can(plugin) then return needKey() end + local UIManager = require("ui/uimanager") + local MultiInputDialog = require("ui/widget/multiinputdialog") + local d + local function go(kind) + local f = d:getFields() + UIManager:close(d) + Requests.send(plugin, f[1], f[2], kind, on_done) + end + d = MultiInputDialog:new{ + title = _("Request a book"), + fields = { + { description = _("Title"), text = title or "" }, + { description = _("Author (optional)"), text = "" }, + }, + buttons = { { + { text = _("Cancel"), id = "close", callback = function() UIManager:close(d) end }, + { text = _("Audiobook"), callback = function() go("audiobook") end }, + { text = _("Book"), is_enter_default = true, callback = function() go("ebook") end }, + } }, + } + Requests.dialog = d + UIManager:show(d) + d:onShowKeyboard() +end + +--- The rows of "My requests": a way to ask, then what you asked for, newest first. +function Requests.rows(plugin, list, reopen) + local UIManager = require("ui/uimanager") + local items = { { text = _("Request a book…"), gz_action = "request", callback = function() Requests.ask(plugin, reopen) end } } + for _i, r in ipairs(list) do + items[#items + 1] = { + text = r.title or "?", mandatory = Requests.statusText(r.status), gz_request = r.id, keep_menu_open = true, + callback = function() + if not Requests.cancellable(r.status) then return show(Requests.detail(r)) end + UIManager:show(require("ui/widget/confirmbox"):new{ + text = Requests.detail(r), + ok_text = _("Cancel this request"), cancel_text = _("Close"), + ok_callback = function() + require("gzreader_net").run(function() + local ok, err = plugin.api:cancelRequest(r.id) + if not ok then return show(plugin:describeError(err)) end + show(T(_("The request for “%1” was cancelled."), r.title or "?"), 3) + if reopen then reopen() end + end, { reason = "cancelling a book request" }) + end, + }) + end, + } + end + if #list == 0 then + items[#items + 1] = { text = _("You haven't asked for anything yet."), select_enabled = false } + end + return items +end + +--- "My requests" in the Catalog (`browser`: gzreader_browser.lua's). `replace`: over the list that's open. +function Requests.open(browser, replace) + local plugin = browser.plugin + if not Requests.can(plugin) then return needKey() end + require("gzreader_net").run(function() + local list, err = plugin.api:listRequests() + if not list then return show(plugin:describeError(err)) end + local items = Requests.rows(plugin, list, function() Requests.open(browser, true) end) + if replace then browser:replace(_("Book requests"), items) else browser:push(_("Book requests"), items) end + end, { reason = "book requests" }) +end + +return Requests diff --git a/plugins/gzreader.koplugin/gzreader_bo_stats.lua b/plugins/gzreader.koplugin/gzreader_bo_stats.lua new file mode 100644 index 000000000..b3e468917 --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_bo_stats.lua @@ -0,0 +1,144 @@ +--[[-- +Reading time and ratings for BookOrbit. + +Reading time: KOReader's own statistics (statistics.sqlite3: one row per page +read, with when and for how long) are what BookOrbit's reading activity is made +from. For each book downloaded from BookOrbit (or matched to one of its books), +the rows since the last upload are sent to POST /koreader/plugin/page-stats, by +the book's fingerprint; BookOrbit turns them into reading sessions itself and +ignores a row it has had. Sent a few seconds after a book closes and at most +every ten minutes otherwise, in a background process (it reads the database +there, so the screen's thread never waits on it). + + store.bookorbit_stats = { [fingerprint] = start time of the last row sent } + +(Ratings need nothing here: gzreader_ratings.lua sends them through the client's +putRating and reads them from its getBook, as for Grimmory.) + +Written from BookOrbit's routes and field names; none of its plugin's code is here. +]] + +local Log = require("gzreader_log") + +local Stats = { EVERY = 600, AFTER_CLOSE = 6, MAX_EVENTS = 500, MAX_BOOKS = 50, MAX_DURATION = 86400 } + +function Stats.dbPath() + return require("datastorage"):getSettingsDir() .. "/statistics.sqlite3" +end + +--- A book's page rows after `since` (oldest first, at most `limit`), from KOReader's +--- statistics database: { { page, startTime, durationSeconds, totalPages }… }. +function Stats.read(db_path, hash, since, limit) + local lfs = require("libs/libkoreader-lfs") + if lfs.attributes(db_path, "mode") ~= "file" then return {} end + local SQ3 = require("lua-ljsqlite3/init") + local conn = SQ3.open(db_path, "ro") + local out = {} + local ok, err = pcall(function() + local stmt = conn:prepare([[SELECT page, start_time, duration, total_pages FROM page_stat_data + JOIN book ON book.id = page_stat_data.id_book + WHERE book.md5 = ? AND start_time > ? ORDER BY start_time LIMIT ?]]) + local res = stmt:reset():bind(hash, since or 0, limit or Stats.MAX_EVENTS):resultset("i") + stmt:close() + local n = res and res[1] and #res[1] or 0 + for i = 1, n do + local page, start, dur, total = tonumber(res[1][i]), tonumber(res[2][i]), tonumber(res[3][i]), tonumber(res[4][i]) + if page and start and start >= 1 and total and total >= 1 then + out[#out + 1] = { page = math.max(0, page), startTime = start, + durationSeconds = math.max(0, math.min(Stats.MAX_DURATION, dur or 0)), totalPages = total } + end + end + end) + conn:close() + if not ok then return nil, tostring(err) end + return out +end + +--- In the background: read and send. books = { { hash, since, file_id }… }. +--- Returns { until_ = { [hash] = last start time sent }, sent = rows, unmatched = { hash… } }, or nil, err. +function Stats.work(api, db_path, books) + local Json = require("gzreader_json") + local out = { until_ = {}, sent = 0, unmatched = {} } + local batch, last = {}, {} + local function flush() + if #batch == 0 then return true end + local res, err = api:putPageStats(batch) + if not res then return nil, err end + local gone = {} + for _i, h in ipairs(res.unmatched or {}) do gone[h] = true; out.unmatched[#out.unmatched + 1] = h end + for _i, b in ipairs(batch) do + if not gone[b.hash] then + out.until_[b.hash] = last[b.hash] + out.sent = out.sent + #b.events + end + end + batch = {} + return true + end + for _i, book in ipairs(books) do + local events, err = Stats.read(db_path, book.hash, book.since, Stats.MAX_EVENTS) + if not events then return nil, err end + if #events > 0 then + last[book.hash] = events[#events].startTime + batch[#batch + 1] = { hash = book.hash, bookFileId = tonumber(book.file_id), events = Json.list(events) } + if #batch >= Stats.MAX_BOOKS then + local ok, ferr = flush() + if not ok then return nil, ferr end + end + end + end + local ok, ferr = flush() + if not ok then return nil, ferr end + return out +end + +function Stats.enabled(plugin) + return plugin:syncEnabled() and plugin:serverCan("stats") and type(plugin.api.putPageStats) == "function" +end + +--- Send what's new (in the background). force: now, whatever was sent when. on_done(ok) optional. +function Stats.send(plugin, force, on_done) + if not Stats.enabled(plugin) or Stats.busy then return on_done and on_done(false) end + if not require("gzreader_net").connected() then return on_done and on_done(false) end + local now = os.time() + if not force and Stats.last and now - Stats.last < Stats.EVERY then return on_done and on_done(false) end + local sent_until = type(plugin.store.bookorbit_stats) == "table" and plugin.store.bookorbit_stats or {} + local books, seen = {}, {} + for _id, e in pairs(plugin.store.downloads or {}) do + if type(e) == "table" and type(e.hash) == "string" and not seen[e.hash] then + seen[e.hash] = true + books[#books + 1] = { hash = e.hash, since = tonumber(sent_until[e.hash]) or 0, file_id = e.file_id } + end + end + if #books == 0 then return on_done and on_done(false) end + Stats.busy, Stats.last = true, now + local db_path = Stats.dbPath() + require("gzreader_async").run(plugin.api, function(api) return Stats.work(api, db_path, books) end, function(res, err) + Stats.busy = nil + if type(res) ~= "table" then + Log.info("BookOrbit reading time: not sent:", tostring(err)) + return on_done and on_done(false) + end + plugin.store.bookorbit_stats = type(plugin.store.bookorbit_stats) == "table" and plugin.store.bookorbit_stats or {} + local n_books = 0 + for hash, t in pairs(res.until_ or {}) do + plugin.store.bookorbit_stats[hash] = t + n_books = n_books + 1 + end + if n_books > 0 then + plugin:save() + Log.info("BookOrbit reading time: sent", res.sent or 0, "page rows of", n_books, "books") + -- (Home's reading stats are older than what BookOrbit now has) + if (tonumber(res.sent) or 0) > 0 then require("gzreader_grimstats").stale(plugin) end + end + if on_done then on_done(true) end + end, "reading time", { nice = true }) +end + +--- A book just closed: its pages are in the database a moment later. +function Stats.later(plugin) + if not Stats.enabled(plugin) then return end + require("ui/uimanager"):scheduleIn(Stats.AFTER_CLOSE, function() Stats.send(plugin, true) end) +end + +return Stats diff --git a/plugins/gzreader.koplugin/gzreader_bookmarks.lua b/plugins/gzreader.koplugin/gzreader_bookmarks.lua index 5fec60640..10aa7aa02 100644 --- a/plugins/gzreader.koplugin/gzreader_bookmarks.lua +++ b/plugins/gzreader.koplugin/gzreader_bookmarks.lua @@ -188,7 +188,7 @@ function BM:bookHad(key, id) end function BM:enabled() - return self.plugin:syncEnabled() and self.plugin.store.bookmark_sync_disabled ~= true + return self.plugin:syncEnabled() and self.plugin:serverCan("bookmarks") and self.plugin.store.bookmark_sync_disabled ~= true end --- Can talk to Grimmory now: Wi-Fi, or (no Wi-Fi) the journal the sync diff --git a/plugins/gzreader.koplugin/gzreader_bookorbit.lua b/plugins/gzreader.koplugin/gzreader_bookorbit.lua new file mode 100644 index 000000000..7b79b58c5 --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_bookorbit.lua @@ -0,0 +1,1136 @@ +--[[-- +BookOrbit as the book server, in place of Grimmory. + +The same methods as the Grimmory client (gzreader_api.lua), answering in the +shapes the rest of GZreader already reads (a list page's `content`, a book's +`primaryFileType`…), so the Catalog, the library index, covers and downloads +work unchanged. Main swaps `plugin.api`'s class to this one when the sign-in +is a BookOrbit one (`store.backend == "bookorbit"`, Grimmory:useBackend). + +BookOrbit's KOReader API (/api/v1/koreader/…) is what it offers e-readers: + * sign-in: the KOReader sync user name and password from BookOrbit's + Settings → Devices → KOReader, sent on every request as x-auth-user and x-auth-key + (the password's MD5, as KOReader's own sync does). Only that MD5 is kept + (store.bookorbit.key; off the USB drive, gzreader_secrets.lua): the + password itself is never stored. + * the catalog: /koreader/plugin/catalog/… (sections, books, a book, its + cover, its file). + +What is synced with BookOrbit so far is in `supports` (main's serverCan): reading +progress. Highlights, bookmarks, statistics, collections and audiobooks are not +yet, so every method for those answers nil, "unsupported"; `books_only` keeps +the Grimmory-only parts (its statistics, shelf editing, copying the sign-in) off. + +Books are told apart by their file's fingerprint (KOReader's partial MD5, kept +as the download's `hash`): progress is sent by it, and the files already on the +Kindle are matched to BookOrbit's books by it (matchCheck). + * progress out: POST /koreader/plugin/progress, the percentage as KOReader counts + it (0-1) and the page's XPointer (or the page number): BookOrbit turns that + into its web reader's place itself, so nothing is converted here. + * progress in: the book's catalog record (its `progress`), given to + gzreader_sync.lua in the shape it reads Grimmory's in. + +Written from BookOrbit's routes and field names; none of its code is here. +]] + +local Api = require("gzreader_api") +local lfs = require("libs/libkoreader-lfs") +local ltn12 = require("ltn12") +local Log = require("gzreader_log") +local _ = require("gettext") +local T = require("ffi/util").template + +local BookOrbit = { + books_only = true, + supports = { progress = true, annotations = true, bookmarks = true, audiobooks = true, stats = true, ratings = true }, + koreader_positions = true, -- (the percentage and place are KOReader's own, not a web reader's) + NAME = "BookOrbit", + BASE = "/api/v1/koreader", + CATALOG = "/api/v1/koreader/plugin/catalog", + PAGE_MAX = 100, -- (the server's limit for one page) + -- what KOReader opens, in the order a book with several files is offered + READABLE = { "epub", "kepub", "azw3", "mobi", "fb2", "pdf", "cbz", "cbr", "djvu", "txt" }, + AUDIO = { m4b = true, mp3 = true, m4a = true, flac = true, ogg = true, opus = true, aac = true, wav = true }, + READABLE_TYPES = Api.READABLE_TYPES, + IN_PROGRESS = Api.IN_PROGRESS, +} +BookOrbit.__index = BookOrbit + +BookOrbit.PAGED = { pdf = true, cbz = true, cbr = true, djvu = true } + +local READABLE_RANK = {} +for i, f in ipairs(BookOrbit.READABLE) do READABLE_RANK[f] = i end +BookOrbit.READABLE_EXT = READABLE_RANK + +-- (JSON null is a function here: only real values are taken) +local function s(v) return type(v) == "string" and v ~= "" and v or nil end +local function n(v) return type(v) == "number" and v or nil end +local function list(v) return type(v) == "table" and v or {} end + +--- What is and isn't synced with BookOrbit, in a sentence or two, for every place +--- that tells the user (the sign-in message, the setup page, the Catalog's About, +--- the setup guide): it follows `supports`, so it's right after each new part. +BookOrbit.FEATURES = { + { "progress", _("your place in each book") }, + { "annotations", _("highlights and their notes") }, + { "bookmarks", _("bookmarks") }, + { "stats", _("reading time") }, + { "ratings", _("ratings") }, + { "audiobooks", _("audiobooks and changing collections (with a BookOrbit API key)") }, +} +function BookOrbit.note() + local yes, no = {}, {} + for _i, f in ipairs(BookOrbit.FEATURES) do + local into = BookOrbit.supports[f[1]] and yes or no + into[#into + 1] = f[2] + end + local out = _("You can browse and download your books.") + if #yes > 0 then out = out .. " " .. T(_("Synced with BookOrbit: %1."), table.concat(yes, ", ")) end + if #no > 0 then out = out .. " " .. T(_("Not yet: %1."), table.concat(no, ", ")) end + return out +end + +-- (an audiobook's id here is "a": see "audiobooks" below) +function BookOrbit.isAudioId(id) return type(id) == "string" and id:match("^a%d+$") ~= nil end +local function audioId(id) return tonumber((tostring(id):gsub("^a", ""))) end + +function BookOrbit:new(store, on_change) + return setmetatable({ store = store, on_change = on_change or function() end }, self) +end + +function BookOrbit:isPaired() + local b = self.store.bookorbit + return self.store.server ~= nil and type(b) == "table" and type(b.key) == "string" and b.key ~= "" +end + +function BookOrbit:ensureToken() + if self:isPaired() then return true end + return false, "not_paired" +end + +function BookOrbit:clearTokens() + if type(self.store.bookorbit) == "table" then self.store.bookorbit.key, self.store.bookorbit.api_key = nil, nil end + self.on_change() +end + +--- (nothing to tell the server: the sign-in is only kept here) +function BookOrbit:logout() self:clearTokens() end + +function BookOrbit:authHeaders() + return { ["x-auth-user"] = tostring(self.store.username or ""), ["x-auth-key"] = tostring((self.store.bookorbit or {}).key or "") } +end + +--- A signed-in request. `path` is relative to the server. Returns code, data, err, headers +--- (as the Grimmory client's call does). +function BookOrbit:call(method, path, opts) + if not self:isPaired() then return nil, nil, "not_paired" end + local o = {} + for k, v in pairs(opts or {}) do o[k] = v end + o.headers = self:authHeaders() + for k, v in pairs((opts or {}).headers or {}) do o.headers[k] = v end + local code, data, headers = Api.rawRequest(method, self.store.server .. path, o) + if not code then return nil, nil, "unreachable" end + if code == 401 or code == 403 then + -- (the password was changed, or sync was switched off for it, in BookOrbit: the + -- sign-in is kept, so switching it back on there is enough) + Log.warn("BookOrbit refused this Kindle's sign-in (HTTP " .. tostring(code) .. ")") + return code, data, code == 403 and "bookorbit_sync_off" or "bookorbit_refused", headers + end + return code, data, nil, headers +end + +local function get(self, path, timeouts) + local code, data, err = self:call("GET", path, { timeouts = timeouts or { 10, 30 } }) + if code == 200 and type(data) == "table" then return data end + return nil, err or ("http_" .. tostring(code)), code +end + +--- Sign in with the KOReader sync user name and password. Returns true, or false, err. +function BookOrbit:login(server, username, password) + local md5 = require("ffi/sha2").md5 + local key = md5(password) + -- no scheme typed and no HTTPS: plain HTTP only on the home network (gzreader_lan.lua) + local candidates = { server } + local typed_bare = server:match("^https://") and not self.explicit_https + if typed_bare and require("gzreader_lan").isPrivate(server) then + candidates[2] = "http://" .. server:sub(9) + end + local last_err + for _i, base in ipairs(candidates) do + local ok, err, final = self:signInWith(base, username, key) + if ok then return true end + last_err = err + if final then + if err ~= "bookorbit_not_found" and not err:match("^http_") then return false, err end + break + end + end + if last_err == "unreachable" and typed_bare and not candidates[2] then last_err = "no_https" end + return false, last_err +end + +--- Check a KOReader sync user name and key (the password's MD5) with the server at `base` +--- and, when it accepts them, keep them. Returns true; or false, err, final (true: the +--- server answered, so another address needn't be tried). +function BookOrbit:signInWith(base, username, key, api_key) + local code, data = Api.rawRequest("GET", base .. BookOrbit.BASE .. "/users/auth", { + headers = { ["x-auth-user"] = username, ["x-auth-key"] = key }, + timeouts = { 10, 20 }, + }) + if code == 200 and type(data) == "table" and data.authorized == "OK" then + -- (the API key stays when this is the same server and user again) + local old = self.store.bookorbit + local same = type(old) == "table" and self.store.server == base and self.store.username == username + self.store.server = base + self.store.username = username + self.store.bookorbit = { key = key, api_key = api_key or (same and old.api_key) or nil, delivery = same and old.delivery or nil } + self:deviceId() + self.store.access_token, self.store.refresh_token, self.store.access_expires_at = nil, nil, nil + self:readVersion() + self.on_change() + return true + elseif code == 401 then + return false, "bookorbit_credentials", true + elseif code == 403 then + return false, "bookorbit_sync_off", true + elseif code == 429 then + return false, "rate_limited", true + elseif code then + -- (a 404 here: an address that answers but isn't BookOrbit, or one too old for this) + return false, code == 404 and "bookorbit_not_found" or ("http_" .. code), true + end + return false, "unreachable" +end + +--- A password nobody has to remember (48 hex digits), for a sign-in GZreader makes itself. +local function newPassword() + local f = io.open("/dev/urandom", "rb") + local bytes = f and f:read(24) + if f then f:close() end + if type(bytes) == "string" and #bytes == 24 then + return (bytes:gsub(".", function(c) return string.format("%02x", c:byte()) end)) + end + local md5 = require("ffi/sha2").md5 + local seed = tostring(os.time()) .. tostring(os.clock()) .. tostring({}) .. tostring(math.random()) + return md5(seed) .. md5(seed .. tostring({})):sub(1, 16) +end + +--- Sign in with only an API key: BookOrbit is asked, with the key, for the account's +--- KOReader sync sign-in, and the Kindle then signs in with that as usual. +--- * There is one already: its user name (GET koreader/credentials) and its key, which +--- BookOrbit only hands out inside its "preconfigured plugin" download (GET +--- koreader/plugin-package: a zip whose bookorbit_provision.lua has it). Only that one +--- value is read from the zip; nothing in it is kept or run. +--- * There is none: one is made (POST koreader/credentials) under the account's name with +--- a random password that only its MD5 is kept of. It can be changed in BookOrbit. +--- The key needs the "KOReader sync" permission (and write access to make a sign-in). +--- Returns true, or false, err. +function BookOrbit:loginWithApiKey(server, api_key) + api_key = type(api_key) == "string" and api_key:gsub("%s+", "") or "" + if api_key == "" then return false, "bookorbit_no_api_key" end + local auth = { ["Authorization"] = "Bearer " .. api_key } + local candidates = { server } + local typed_bare = server:match("^https://") and not self.explicit_https + if typed_bare and require("gzreader_lan").isPrivate(server) then + candidates[2] = "http://" .. server:sub(9) + end + local base, code, creds + for _i, b in ipairs(candidates) do + code, creds = Api.rawRequest("GET", b .. "/api/v1/koreader/credentials", { headers = auth, timeouts = { 10, 20 } }) + if code then base = b break end + end + if not base then return false, (typed_bare and not candidates[2]) and "no_https" or "unreachable" end + if code == 401 then return false, "bookorbit_api_key_refused" end + if code == 403 then return false, "bookorbit_key_no_kosync" end + if code == 404 then return false, "bookorbit_not_found" end + if code ~= 200 then return false, "http_" .. tostring(code) end + local username, key + if type(creds) == "table" and s(creds.username) then + username = creds.username + if creds.syncEnabled == false then return false, "bookorbit_sync_off" end + local chunks, size = {}, 0 + local zcode = Api.rawRequest("GET", base .. "/api/v1/koreader/plugin-package?origin=" + .. base:gsub("[^%w%-%._~]", function(c) return string.format("%%%02X", c:byte()) end), { + headers = auth, timeouts = { 15, 60 }, log_url = base .. "/api/v1/koreader/plugin-package", + sink = function(chunk) + if chunk then + size = size + #chunk + if size > 16 * 1024 * 1024 then return nil, "too big" end + chunks[#chunks + 1] = chunk + end + return 1 + end, + }) + if zcode == 400 then return false, "bookorbit_key_old_signin" end + if zcode ~= 200 then return false, zcode and ("http_" .. tostring(zcode)) or "unreachable" end + local text = require("gzreader_zipread").read(table.concat(chunks), "bookorbit_provision.lua") + chunks = nil -- luacheck: ignore + key = type(text) == "string" and text:match('\n%s*userkey%s*=%s*"(%x+)"') or nil + if not key or #key ~= 32 then + Log.warn("BookOrbit: the plugin download had no sync key in it") + return false, "bookorbit_key_no_signin" + end + key = key:lower() + else + -- none yet: make one, named after the account + local mcode, me = Api.rawRequest("GET", base .. "/api/v1/auth/me", { headers = auth, timeouts = { 8, 15 } }) + local name = mcode == 200 and type(me) == "table" and (s(me.username) or s(me.name)) or nil + name = name and name:gsub("%s+", "-") or "gzreader" + if #name < 3 then name = name .. "-reader" end + local password = newPassword() + local made + for try = 1, 2 do + -- (only a name and a password: BookOrbit's own defaults for the rest are the ones a Kindle + -- wants: progress sync on, audiobook-only books hidden, read-aloud EPUBs text-only when it can) + local pcode, pdata = Api.rawRequest("POST", base .. "/api/v1/koreader/credentials", { + headers = auth, body = { username = name:sub(1, 100), password = password }, timeouts = { 10, 30 } }) + if pcode == 200 or pcode == 201 then made = true break end + if pcode == 403 then + return false, (type(pdata) == "table" and pdata.errorCode == "API_KEY_READ_ONLY") and "bookorbit_key_cannot_create" or "bookorbit_key_no_kosync" + end + local taken = pcode == 409 and type(pdata) == "table" and tostring(pdata.message):lower():find("taken", 1, true) + if not taken or try == 2 then return false, pcode and ("http_" .. tostring(pcode)) or "unreachable" end + name = name:sub(1, 90) .. "-" .. newPassword():sub(1, 4) -- (someone has that name: with four digits) + end + if not made then return false, "unreachable" end + Log.info("BookOrbit: no e-reader sign-in existed for this account, so one was made") + username, key = name:sub(1, 100), require("ffi/sha2").md5(password) + end + local ok, err = self:signInWith(base, username, key, api_key) + if not ok then return false, err end + self:readSyncSettings(base, api_key) + self.on_change() + return true +end + +--- What this server can do (its version and capabilities), kept for the parts that depend on it. +function BookOrbit:readVersion() + local data = get(self, BookOrbit.BASE .. "/plugin/version", { 8, 15 }) + local b = self.store.bookorbit + if type(data) ~= "table" or type(b) ~= "table" then return nil end + b.server_version = s(data.serverVersion) + b.capabilities = {} + for _i, c in ipairs(list(data.capabilities)) do + if type(c) == "string" then b.capabilities[c] = true end + end + return b.capabilities +end + +--- This Kindle's name to BookOrbit (its KOReader devices list): made once and kept. +function BookOrbit:deviceId() + if type(self.store.bookorbit_device) ~= "string" or not self.store.bookorbit_device:match("^[%w_-]+$") then + local md5 = require("ffi/sha2").md5 + self.store.bookorbit_device = "gz-" .. md5(tostring(os.time()) .. tostring(math.random()) .. tostring({})):sub(1, 16) + self.on_change() + end + return self.store.bookorbit_device +end + +--- What every plugin request carries: which device, and which GZreader. +function BookOrbit:deviceFields(body) + body = body or {} + body.deviceId = self:deviceId() + local ok, model = pcall(function() return require("device").model end) + body.deviceModel = ("GZreader " .. tostring(ok and model or "e-reader")):sub(1, 100) + local okv, v = pcall(function() return require("gzreader_update").currentVersion() end) + body.pluginVersion = ("gz" .. tostring(okv and v or "")):sub(1, 20) + return body +end + +--- KOReader's fingerprint of a file (its partial MD5), or nil. +--- (As KOReader's util.partialMD5, which its own sync and BookOrbit use: 1 KB at +--- offsets 0, 1 KB, 4 KB, 16 KB… up to 1 GB, as far as the file goes.) +function BookOrbit.hashFile(path) + local ok, h = pcall(function() + local f = io.open(path, "rb") + if not f then return nil end + local update = require("ffi/sha2").md5() + for i = -1, 10 do + f:seek("set", i < 0 and 0 or 1024 * 4 ^ i) + local sample = f:read(1024) + if not sample then break end + update(sample) + end + f:close() + return update() + end) + return ok and type(h) == "string" and #h == 32 and h:lower() or nil +end + +--- Which of these fingerprints BookOrbit has a book for: +--- { [hash] = { book_id =, file_id = } }, or nil, err. +function BookOrbit:matchCheck(hashes) + local out = {} + for from = 1, #hashes, 500 do + local part = {} + for i = from, math.min(from + 499, #hashes) do part[#part + 1] = hashes[i] end + local code, data, err = self:call("POST", BookOrbit.BASE .. "/plugin/match-check", + { body = self:deviceFields({ hashes = require("gzreader_json").list(part) }), timeouts = { 10, 30 } }) + if not ((code == 200 or code == 201) and type(data) == "table") then return nil, err or ("http_" .. tostring(code)) end + for _i, m in ipairs(list(data.matches)) do + if type(m) == "table" and s(m.hash) and n(m.bookId) then + out[m.hash:lower()] = { book_id = m.bookId, file_id = n(m.bookFileId) } + end + end + end + return out +end + +--- Send a book's place (body as gzreader_sync.lua makes it for Grimmory, with the +--- page's XPointer in gz_xp). The book is named by its file's fingerprint +--- (the download's `hash`). Returns true, or false, err, code (404: BookOrbit has +--- no book with that file, so it isn't asked again). +function BookOrbit:putProgress(book_id, body) + if BookOrbit.isAudioId(tostring(book_id)) then return self:putAudioProgress(tostring(book_id), body) end + local entry = type(self.store.downloads) == "table" and self.store.downloads[tostring(book_id)] + local hash = type(entry) == "table" and s(entry.hash) + if not hash then return false, "bookorbit_unmatched", 404 end + local fp = type(body) == "table" and type(body.fileProgress) == "table" and body.fileProgress or {} + local pct = n(fp.progressPercent) + if not pct then return false, "bookorbit_unmatched", 400 end + local item = { hash = hash, percentage = math.max(0, math.min(1, pct / 100)), timestamp = os.time(), + progress = s(body.gz_xp) or s(fp.positionData) } + local code, data, err = self:call("POST", BookOrbit.BASE .. "/plugin/progress", + { body = self:deviceFields({ items = require("gzreader_json").list({ item }) }), timeouts = { 8, 15 } }) + if (code == 200 or code == 201) and type(data) == "table" then + for _i, r in ipairs(list(data.results)) do + if type(r) == "table" and r.accepted == true then return true end + end + return false, "bookorbit_unmatched", 404 + end + return false, err or ("http_" .. tostring(code)), code +end + +--- A book's rating (value as gzreader_ratings.lua has Grimmory's: 1-10, nil for none): +--- BookOrbit's is 0-5 stars. Returns true, or false, err, code. +function BookOrbit:putRating(book_id, value) + local stars = tonumber(value) and math.max(0, math.min(5, tonumber(value) / 2)) or 0 + local code, _, err = self:call("PUT", BookOrbit.CATALOG .. "/books/" .. tostring(book_id) .. "/rating", + { body = { rating = stars }, timeouts = { 8, 15 } }) + if code == 200 then return true end + return false, err or ("http_" .. tostring(code)), code +end + +--- The reader's numbers as BookOrbit keeps them, over every device (gzreader_grimstats.lua): +--- GET catalog/dashboard has the streak, the year's goal, minutes read per day for the past +--- year, badges, the book read most a year ago, this year's finished books and a highlight. +--- Returns the reply, or nil, err. +function BookOrbit:readingDashboard() + local code, data, err = self:call("GET", BookOrbit.CATALOG .. "/dashboard", { timeouts = { 10, 30 } }) + if code == 200 and type(data) == "table" then return data end + return nil, err or ("http_" .. tostring(code)), code +end + +--- Reading time: pages read, by book (gzreader_bo_stats.lua). books = { { hash, bookFileId, +--- events = { { page, startTime, durationSeconds, totalPages }… } }… }. +--- Returns { unmatched = { hash… } }, or nil, err. +function BookOrbit:putPageStats(books) + local code, data, err = self:call("POST", BookOrbit.BASE .. "/plugin/page-stats", + { body = self:deviceFields({ books = require("gzreader_json").list(books) }), timeouts = { 10, 60 } }) + if (code == 200 or code == 201) and type(data) == "table" then + local unmatched = {} + for _i, h in ipairs(list(data.unmatched)) do if type(h) == "string" then unmatched[#unmatched + 1] = h:lower() end end + return { unmatched = unmatched } + end + return nil, err or ("http_" .. tostring(code)) +end + +--- One book's highlight exchange (gzreader_bo_annotations.lua). book: { hash, keys, +--- keysComplete, sidecarState, changes }. Returns its result ({ toApply, more… }), or +--- nil, err ("bookorbit_unmatched": no book with this file; "bookorbit_incompatible": +--- BookOrbit's copy differs, so its positions can't be placed). +function BookOrbit:exchangeAnnotations(book) return self:exchange("annotations", book) end + +--- The same for `kind` "annotations" (highlights) or "bookmarks" (gzreader_bo_bookmarks.lua). +function BookOrbit:exchange(kind, book) + local body = self:deviceFields({ books = require("gzreader_json").list({ book }) }) + body.deviceTime = os.date("%Y-%m-%d %H:%M:%S") -- (BookOrbit dates what it makes in this Kindle's clock) + local code, data, err = self:call("POST", BookOrbit.BASE .. "/plugin/" .. kind .. "/exchange", { body = body, timeouts = { 10, 45 } }) + if not ((code == 200 or code == 201) and type(data) == "table") then return nil, err or ("http_" .. tostring(code)) end + local res = list(data.results)[1] + if type(res) == "table" then return res end + if #list(data.positionIncompatible) > 0 then return nil, "bookorbit_incompatible" end + return nil, "bookorbit_unmatched" +end + +--- Tell BookOrbit which of its changes were put into the book. Returns true, or false, err. +function BookOrbit:ackAnnotations(hash, applied, deleted) return self:ackExchange("annotations", hash, applied, deleted) end + +function BookOrbit:ackExchange(kind, hash, applied, deleted) + local Json = require("gzreader_json") + local code, data, err = self:call("POST", BookOrbit.BASE .. "/plugin/" .. kind .. "/exchange-ack", { + body = self:deviceFields({ books = Json.list({ { hash = hash, applied = Json.list(applied or {}), deleted = Json.list(deleted or {}) } }) }), + timeouts = { 10, 30 } }) + if (code == 200 or code == 201) and type(data) == "table" then return true end + return false, err or ("http_" .. tostring(code)) +end + +function BookOrbit:can(capability) + local b = self.store.bookorbit + return type(b) == "table" and type(b.capabilities) == "table" and b.capabilities[capability] == true +end + +function BookOrbit:me() + if not self:isPaired() then return nil, "not_paired" end + return { username = self.store.username, name = self.store.username } +end + +---------------------------------------------------------------- books + +--- The file GZreader would open: the first format KOReader reads, by READABLE's order. +function BookOrbit.pickFormat(formats) + local best, rank + for _i, f in ipairs(list(formats)) do + local r = type(f) == "string" and READABLE_RANK[f:lower()] + if r and (not rank or r < rank) then best, rank = f:lower(), r end + end + return best +end + +local STATUS = { reading = "READING", finished = "READ", unread = "UNREAD" } + +local function fileName(title, format) + local name = tostring(title or "book"):gsub("[%c/\\:%*%?\"<>|]", " "):gsub("%s+", " "):gsub("^%s+", ""):gsub("[%s%.]+$", "") + if name == "" then name = "book" end + if #name > 120 then name = name:sub(1, 120):gsub("[\128-\191]*$", ""):gsub("[\192-\255]$", "") end + return name .. "." .. format +end +BookOrbit.fileName = fileName + +--- A catalog list item as the app's book lists give one. +function BookOrbit.toBook(item) + if type(item) ~= "table" or n(item.id) == nil then return nil end + local format = BookOrbit.pickFormat(item.formats) + local audio = false + for _i, f in ipairs(list(item.formats)) do + if type(f) == "string" and BookOrbit.AUDIO[f:lower()] then audio = true end + end + local authors = {} + for _i, a in ipairs(list(item.authors)) do if s(a) then authors[#authors + 1] = a end end + local title = s(item.title) or ("Book " .. tostring(item.id)) + return { + id = item.id, + title = title, + authors = authors, + seriesName = s(item.seriesName), + seriesNumber = n(item.seriesIndex), + primaryFileType = format and format:upper() or (audio and "AUDIOBOOK" or nil), + primaryFileName = format and fileName(title, format) or nil, + readProgress = n(item.progressPercentage), -- (0–100, as Grimmory's) + lastReadTime = s(item.lastReadAt), + readStatus = STATUS[item.readStatus], + addedOn = s(item.addedAt), + hasCover = item.hasCover == true, + } +end + +local SORT = { title = "title", addedOn = "recently_added", lastReadTime = "recently_read", seriesNumber = "series", + author = "author", publishedDate = "published", updatedOn = "recently_updated" } + +local function wantsOnlyAudio(types) + if type(types) ~= "table" or #types == 0 then return false end + for _i, t in ipairs(types) do + if tostring(t):upper() ~= "AUDIOBOOK" then return false end + end + return true +end + +local function emptyPage(page, size) + return { content = {}, page = page, size = size, totalElements = 0, totalPages = 0, hasNext = false, hasPrevious = page > 0 } +end + +--- A page of books. params as the Grimmory client's: page (from 0), size, sort, dir, search, +--- libraryId, shelfId (a collection), magicShelfId (a SmartScope), authors, series, status, fileType. +function BookOrbit:listBooks(params) + params = params or {} + local page, size = tonumber(params.page) or 0, math.min(tonumber(params.size) or 20, BookOrbit.PAGE_MAX) + if wantsOnlyAudio(params.fileType) then return self:listAudiobooks(params) end -- (the main API, with an API key) + local q = { page = page + 1, size = size, sort = SORT[params.sort] or "title", + order = (params.dir == "asc" or params.dir == "desc") and params.dir or nil, + q = s(params.search), libraryId = params.libraryId, collectionId = params.shelfId, smartScopeId = params.magicShelfId, + author = s(params.authors), series = s(params.series) } + if type(params.status) == "table" or params.status == "READING" then q.readStatus = "reading" end + local data, err = get(self, BookOrbit.CATALOG .. "/books" .. Api.query(q), { 15, 45 }) + if not data then return nil, err end + local content = {} + for _i, item in ipairs(list(data.items)) do + local book = BookOrbit.toBook(item) + -- (a book with nothing KOReader opens, an audiobook say, isn't listed among the books) + if book and book.primaryFileType and book.primaryFileType ~= "AUDIOBOOK" then content[#content + 1] = book end + end + local total = n(data.total) or #content + return { content = content, page = page, size = size, totalElements = total, + totalPages = math.ceil(total / size), hasNext = data.hasNext == true, hasPrevious = data.hasPrevious == true } +end + +function BookOrbit:searchBooks(q, page, size) + return self:listBooks{ search = q, page = page or 0, size = size or 25, sort = "title", dir = "asc" } +end + +--- The Grimmory lists the home page asks for by name. +function BookOrbit:simpleList(endpoint, limit) + local params = { page = 0, size = limit or 20, sort = "addedOn", dir = "desc" } + if endpoint == "continue-reading" then params.sort, params.status = "lastReadTime", BookOrbit.IN_PROGRESS end + local data, err = self:listBooks(params) + if not data then return nil, err end + return data.content +end + +function BookOrbit:continueReading(limit) return self:simpleList("continue-reading", limit) end + +local function section(self, name) + local data, err = get(self, BookOrbit.CATALOG .. "/sections/" .. name) + if not data then return nil, err end + local out = {} + for _i, e in ipairs(list(data.items)) do + local id = type(e) == "table" and (tonumber(e.id) or s(e.id)) + if id then out[#out + 1] = { id = id, name = s(e.title) or tostring(id), bookCount = n(e.count) } end + end + return out +end + +function BookOrbit:listLibraries() return section(self, "libraries") end + +--- How many books each library has ({ [id as text] = count }), for the library index: +--- BookOrbit's book lists don't say which library a book is in. +function BookOrbit:libraryCounts() + local libs = section(self, "libraries") + if not libs then return nil end + local out = {} + for _i, lib in ipairs(libs) do out[tostring(lib.id)] = lib.bookCount or 0 end + return out +end + +--- Collections, and SmartScopes as the "magic" ones. +function BookOrbit:listShelves() + local out, err = section(self, "collections") + if not out then return nil, err end + for _i, e in ipairs(section(self, "smart-scopes") or {}) do + e.magic = true + out[#out + 1] = e + end + return out +end + +local function detail(self, book_id) + return get(self, BookOrbit.CATALOG .. "/books/" .. tostring(book_id), { 10, 20 }) +end + +--- The file of a book's detail that GZreader downloads: one of the book's own files +--- (role "primary", its main file, or "content", another one; both download) in the +--- first format KOReader reads; the main file when two share that format. +function BookOrbit.pickFile(d) + local best, rank + for _i, f in ipairs(list(type(d) == "table" and d.files)) do + local r = type(f) == "table" and type(f.format) == "string" and READABLE_RANK[f.format:lower()] + if r and (f.role == "primary" or f.role == "content") and s(f.downloadUrl) then + r = r * 2 - (f.role == "primary" and 1 or 0) + if not rank or r < rank then best, rank = f, r end + end + end + return best +end + +local function names(v) + local out = {} + for _i, x in ipairs(list(v)) do + local name = s(x) or (type(x) == "table" and s(x.name)) + if name then out[#out + 1] = name end + end + return out +end + +--- A book's record, as Grimmory's /books/{id}: its file and metadata. +function BookOrbit:getBook(book_id) + if BookOrbit.isAudioId(book_id) then return self:audiobookRecord(book_id) end + local d, err = detail(self, book_id) + if not d then return nil, err end + local f = BookOrbit.pickFile(d) + local book = BookOrbit.toBook(d) or { id = d.id } + book.primaryFile = f and { id = f.id, bookType = f.format:upper(), fileSizeKb = n(f.sizeBytes) and math.ceil(f.sizeBytes / 1024) or nil, + fileHash = s(f.fileHash) } or nil + book.primaryFileId = f and f.id or nil + book.fileSizeKb = book.primaryFile and book.primaryFile.fileSizeKb or nil + book.libraryId = n(d.libraryId) + -- (BookOrbit's stars, 0-5, as Grimmory's 1-10: gzreader_ratings.lua reads that) + book.personalRating = n(d.rating) and d.rating > 0 and math.floor(d.rating * 2 + 0.5) or nil + -- where the book was left, on any device: as gzreader_sync.lua reads Grimmory's + local p = type(d.progress) == "table" and d.progress + if p and n(p.percentage) and p.percentage > 0 then + local place = s(p.koreaderProgress) + if f and BookOrbit.PAGED[f.format:lower()] then + book.pdfProgress = { percentage = p.percentage, page = tonumber(place) } + else + book.epubProgress = { percentage = p.percentage } + if place and place:sub(1, 1) == "/" then book.gz_xp = place end + end + end + book.metadata = { title = book.title, subtitle = s(d.subtitle), description = s(d.description), publisher = s(d.publisher), + publishedDate = s(d.publishedDate), pageCount = n(d.pageCount), seriesName = book.seriesName, seriesNumber = book.seriesNumber, + categories = names(d.genres), authors = book.authors } + return book +end + +--- A book's page (description, publisher…), as Grimmory's app detail. +function BookOrbit:getBookDetail(book_id) + local book, err = self:getBook(book_id) + if not book then return nil, err end + local m = book.metadata + return { id = book.id, title = book.title, subtitle = m.subtitle, description = m.description, categories = m.categories, + pageCount = m.pageCount, publisher = m.publisher, publishedDate = m.publishedDate, + seriesName = m.seriesName, seriesNumber = m.seriesNumber } +end + +---------------------------------------------------------------- covers and files + +function BookOrbit:downloadThumbnail(book_id, path, kind) + if not self:isPaired() then return false, "not_paired" end + local audio = BookOrbit.isAudioId(tostring(book_id)) + if kind == "audiobook" and not audio then return false, "http_404", 404 end + if audio and not self:hasApiKey() then return false, "bookorbit_no_api_key", 404 end + local part = path .. ".part" + local fh, ferr = io.open(part, "wb") + if not fh then return false, ferr end + local headers = audio and { ["Authorization"] = "Bearer " .. self.store.bookorbit.api_key } or self:authHeaders() + headers["Accept"] = "image/*" + local where = audio and ("/api/v1/books/" .. tostring(audioId(book_id)) .. "/thumbnail") + or (BookOrbit.CATALOG .. "/books/" .. tostring(book_id) .. "/thumbnail") + local code, _, resp = Api.rawRequest("GET", self.store.server .. where, { + headers = headers, sink = ltn12.sink.file(fh), timeouts = { 10, 30 }, + }) + local ctype = type(resp) == "table" and (resp["content-type"] or resp["Content-Type"]) or "" + if code == 200 and (lfs.attributes(part, "size") or 0) > 0 and tostring(ctype):find("image", 1, true) then + os.rename(part, path) + return true + end + os.remove(part) + return false, code and ("http_" .. code) or "unreachable", code +end + +function BookOrbit:downloadThumbnails(items) + local got, none = 0, {} + for _i, it in ipairs(items or {}) do + local ok, err, code = self:downloadThumbnail(it.id, it.path, it.kind) + if ok then + got = got + 1 + elseif code == 404 then + none[#none + 1] = it.id + elseif err == "unreachable" or err == "not_paired" or code == 401 or code == 403 then + break + end + end + return { got = got, none = none } +end + +--- A book's file straight into `path`. BookOrbit's download doesn't continue a part +--- (no Range), so a part left by an interrupted download is started again. +function BookOrbit:downloadToFile(book_id, path, _resume) + local d, err = detail(self, book_id) + if not d then return false, err end + local f = BookOrbit.pickFile(d) + if not f then return false, "bookorbit_no_file" end + local fh, ferr = io.open(path, "wb") + if not fh then return false, ferr end + local headers = self:authHeaders() + headers["Accept"] = "*/*" + -- (the address the server gave for this file; only ever on the signed-in server) + local where = f.downloadUrl:sub(1, 1) == "/" and f.downloadUrl or (BookOrbit.CATALOG .. "/files/" .. tostring(f.id) .. "/download") + local code, _, resp, status = Api.rawRequest("GET", self.store.server .. where, { + headers = headers, + sink = require("gzreader_xferlog").sink(ltn12.sink.file(fh), "book " .. tostring(book_id)), + timeouts = { 30, -1 }, + }) + if code == 200 then + local want = type(resp) == "table" and tonumber(resp["content-length"]) + local have = lfs.attributes(path, "size") or 0 + if have > 0 and (not want or want == have) then return true end + os.remove(path) + return false, "stalled: " .. tostring(have) .. " of " .. tostring(want) .. " bytes" + end + os.remove(path) + return false, code and ("http_" .. code) or tostring(status or "unreachable") +end + +---------------------------------------------------------------- audiobooks (the main API, with an API key) + +-- BookOrbit's e-reader sign-in doesn't reach its audiobook routes (the manifest, the +-- audio files with resume, the listening position): those take an API key the user +-- makes in BookOrbit (Settings → You → API keys), kept as store.bookorbit.api_key with the +-- other secrets. Without one there are no BookOrbit audiobooks here. +-- +-- A BookOrbit book can be an ebook and an audiobook at once, under one id. GZreader +-- keeps the two apart everywhere (downloads, the progress queue), so an audiobook's +-- id here is "a": added in the lists below, taken off again in each call. + +BookOrbit.AUDIO_PREFIX = "a" +local AUDIO_FORMATS = { "m4b", "mp3", "m4a", "flac", "ogg", "opus", "aac", "wav" } + + +function BookOrbit:hasApiKey() + local b = self.store.bookorbit + return self.store.server ~= nil and type(b) == "table" and type(b.api_key) == "string" and b.api_key ~= "" +end + +--- A request with the API key. Returns code, data, err, headers. +function BookOrbit:keyCall(method, path, opts) + if not self:hasApiKey() then return nil, nil, "bookorbit_no_api_key" end + local o = {} + for k, v in pairs(opts or {}) do o[k] = v end + o.headers = { ["Authorization"] = "Bearer " .. self.store.bookorbit.api_key } + for k, v in pairs((opts or {}).headers or {}) do o.headers[k] = v end + local code, data, headers = Api.rawRequest(method, self.store.server .. path, o) + if not code then return nil, nil, "unreachable" end + if code == 401 then + Log.warn("BookOrbit refused the API key (HTTP 401): expired, deleted, or API keys switched off") + return code, data, "bookorbit_api_key_refused", headers + end + if code == 403 and type(data) == "table" and data.errorCode == "API_KEY_READ_ONLY" then + return code, data, "bookorbit_api_key_read_only", headers + end + return code, data, nil, headers +end + +--- Check an API key against the signed-in server and keep it. Returns true, or false, err. +--- What the key has to be allowed, as BookOrbit's "Create API key" page names things +--- (checked against its source, v3.9.0; the wiki's BookOrbit page has the table): +--- Access "Read and write" the listening position, collections, requests, making a sync sign-in +--- ("Read only" is enough to list and download audiobooks) +--- Libraries the ones with your books and audiobooks +--- "KOReader sync" signing in with only the key +--- "Request books" requesting books +--- Nothing else: not "Download books" (audiobook files need no extra permission) and not +--- "Administrator access". +BookOrbit.KEY_NEEDS = "Access: Read and write. Libraries: all (or the ones with your books). Extra permissions: “KOReader sync” to sign in with the key, “Request books” to request books. Nothing else, and not Administrator access." + +--- How BookOrbit is set to deliver this sync sign-in's read-aloud EPUBs (nil: Automatic, +--- text-only when it can; "audioless_epub"; "original": with the narration, which a +--- Kindle can't play and which makes the files much bigger). Read with the API key when +--- it may see the sync sign-in (its "KOReader sync" permission); kept as +--- store.bookorbit.delivery, false when it couldn't be read. A sign-in GZreader makes +--- itself is left on BookOrbit's defaults: progress sync on, audiobook-only books hidden +--- from the e-reader lists, delivery Automatic. +function BookOrbit:readSyncSettings(base, api_key) + if type(self.store.bookorbit) ~= "table" then return nil end + local code, creds = Api.rawRequest("GET", (base or self.store.server) .. "/api/v1/koreader/credentials", + { headers = { ["Authorization"] = "Bearer " .. (api_key or self.store.bookorbit.api_key or "") }, timeouts = { 8, 15 } }) + if code == 200 and type(creds) == "table" then + self.store.bookorbit.delivery = s(creds.readAloudDelivery) or "automatic" + Log.info("BookOrbit: this sync sign-in's read-aloud EPUBs are delivered:", self.store.bookorbit.delivery, + "| audiobook-only books hidden from the e-reader lists:", tostring(creds.hideAudioOnlyBooks)) + else + self.store.bookorbit.delivery = false + end + return self.store.bookorbit.delivery +end + +--- What the saved key turns out to be allowed, asked of the server (two small requests): +--- { signin = it may see the sync sign-in ("KOReader sync"), requests = it may request +--- books ("Request books") }; nil for a part that couldn't be asked. +function BookOrbit:keyAbilities() + if not self:hasApiKey() then return {} end + local out = {} + local code = self:keyCall("GET", "/api/v1/koreader/credentials", { timeouts = { 8, 15 } }) + if code == 200 then out.signin = true elseif code == 403 then out.signin = false end + code = self:keyCall("GET", "/api/v1/book-requests?page=1&limit=1", { timeouts = { 8, 15 } }) + if code == 200 then out.requests = true elseif code == 403 then out.requests = false end + return out +end + +--- A line for the user when a BookOrbit setting works against the Kindle, or nil. +function BookOrbit:settingsAdvice() + local b = self.store.bookorbit + if type(b) == "table" and b.delivery == "original" then return "delivery_original" end + return nil +end + +function BookOrbit:setApiKey(key) + if not self:isPaired() then return false, "not_paired" end + key = type(key) == "string" and key:gsub("%s+", "") or "" + if key == "" then + self.store.bookorbit.api_key = nil + self.on_change() + return true + end + local code = Api.rawRequest("GET", self.store.server .. "/api/v1/auth/me", + { headers = { ["Authorization"] = "Bearer " .. key }, timeouts = { 10, 20 } }) + if code == 200 then + self.store.bookorbit.api_key = key + self:readSyncSettings() + self.on_change() + return true + end + return false, code == 401 and "bookorbit_api_key_refused" or (code and ("http_" .. code) or "unreachable") +end + +--- A page of audiobooks (the main API's book query), as the Catalog reads one. +function BookOrbit:listAudiobooks(params) + local page, size = tonumber(params.page) or 0, math.min(tonumber(params.size) or 20, BookOrbit.PAGE_MAX) + if not self:hasApiKey() then return emptyPage(page, size) end + local formats = {} + for _i, f in ipairs(AUDIO_FORMATS) do formats[#formats + 1] = f; formats[#formats + 1] = f:upper() end + local Json = require("gzreader_json") + local field = ({ title = "title", addedOn = "addedAt", lastReadTime = "lastReadAt" })[params.sort] or "title" + local body = { + sort = Json.list({ { field = field, dir = (params.dir == "desc") and "desc" or "asc" } }), + pagination = { page = page + 1, size = size }, + filter = { type = "group", join = "AND", rules = Json.list({ + { type = "rule", field = "format", operator = "includesAny", value = Json.list(formats) } }) }, + q = s(params.search), + } + local code, data, err = self:keyCall("POST", "/api/v1/books/query", { body = body, timeouts = { 15, 45 } }) + if not ((code == 200 or code == 201) and type(data) == "table") then return nil, err or ("http_" .. tostring(code)) end + local content = {} + for _i, card in ipairs(list(data.items)) do + if type(card) == "table" and n(card.id) then + content[#content + 1] = { + id = BookOrbit.AUDIO_PREFIX .. tostring(card.id), title = s(card.title) or ("Audiobook " .. tostring(card.id)), + authors = names(card.authors), narrators = names(card.narrators), primaryFileType = "AUDIOBOOK", + seriesName = s(card.seriesName), seriesNumber = n(card.seriesIndex), readProgress = n(card.readingProgress), + hasCover = card.hasCover == true, + } + end + end + local total = n(data.total) or #content + return { content = content, page = page, size = size, totalElements = total, totalPages = math.ceil(total / size), + hasNext = (page + 1) * size < total, hasPrevious = page > 0 } +end + +local function manifest(self, book_id) + local code, data, err = self:keyCall("GET", "/api/v1/audiobooks/" .. tostring(audioId(book_id)) .. "/manifest", { timeouts = { 10, 30 } }) + if code == 200 and type(data) == "table" and type(data.assets) == "table" and #data.assets > 0 then + table.sort(data.assets, function(a, b) return (n(a.sequence) or 0) < (n(b.sequence) or 0) end) + return data + end + return nil, err or ("http_" .. tostring(code)), code +end + +--- An audiobook's files and chapters, as Grimmory's audiobook info (what +--- gzreader_audiobook.lua's describe reads): one file with chapters, or one per track. +function BookOrbit:audiobookInfo(book_id) + local m, err = manifest(self, book_id) + if not m then return nil, err end + local book = type(m.book) == "table" and m.book or {} + local first = m.assets[1] + local info = { + title = s(book.title), author = table.concat(names(book.authors), ", "), narrator = table.concat(names(book.narrators), ", "), + bookFileId = n(first.fileId), durationMs = n(m.totalDurationMs) or 0, folderBased = #m.assets > 1, + codec = (s(first.format) or ""):lower() == "mp3" and "mp3" or "aac", totalSizeBytes = 0, tracks = {}, chapters = {}, + gz_manifest = s(m.revision), + } + if info.author == "" then info.author = nil end + if info.narrator == "" then info.narrator = nil end + local at = 0 + for i, a in ipairs(m.assets) do + info.totalSizeBytes = info.totalSizeBytes + (n(a.sizeBytes) or 0) + info.tracks[i] = { index = n(a.sequence) or (i - 1), fileName = string.format("%03d.%s", i, (s(a.format) or "mp3"):lower()), + title = nil, durationMs = n(a.durationMs) or 0, fileSizeBytes = n(a.sizeBytes), cumulativeStartMs = at } + at = at + (n(a.durationMs) or 0) + end + for i, c in ipairs(list(m.chapters)) do + if type(c) == "table" then + local start, stop = n(c.startMs) or 0, n(c.endMs) + info.chapters[#info.chapters + 1] = { index = i - 1, title = s(c.title) or ("Chapter " .. i), startTimeMs = start, + endTimeMs = stop, durationMs = stop and (stop - start) or nil } + -- (one file per track: a track is named after the chapter that starts it) + for _j, t in ipairs(info.tracks) do + if t.title == nil and t.cumulativeStartMs == start then t.title = s(c.title) end + end + end + end + if not info.folderBased then info.tracks = nil end + return info +end + +--- One audio file of an audiobook to `path`, continuing what's there (BookOrbit's +--- audio files take a Range). track: its sequence (nil: the only file). +--- Returns true | false, err, retryable. +function BookOrbit:downloadAudio(book_id, track, path) + local m, err, mcode = manifest(self, book_id) + if not m then return false, err, mcode == nil end + local asset = m.assets[1] + for _i, a in ipairs(m.assets) do if track ~= nil and n(a.sequence) == tonumber(track) then asset = a end end + local have = lfs.attributes(path, "size") or 0 + local fh, ferr = io.open(path, have > 0 and "ab" or "wb") + if not fh then return false, ferr end + local headers = { ["Authorization"] = "Bearer " .. self.store.bookorbit.api_key, ["Accept"] = "*/*" } + if have > 0 then headers["Range"] = "bytes=" .. have .. "-" end + local code = Api.rawRequest("GET", self.store.server .. "/api/v1/audiobooks/" .. tostring(audioId(book_id)) .. "/assets/" + .. tostring(asset.assetId) .. "/content", { headers = headers, sink = ltn12.sink.file(fh), timeouts = { 60, -1 } }) + if code == 206 or (code == 200 and have == 0) or code == 416 then return true end + if code == 200 and have > 0 then + os.remove(path) -- (the whole file came after the part: start it again) + return false, "restart", true + end + if code == 401 or code == 403 or code == 404 then return false, "http_" .. code, false end + return false, code and ("http_" .. code) or "unreachable", true +end + +local function uuid4() + local md5 = require("ffi/sha2").md5 + local h = md5(tostring(os.time()) .. tostring(math.random()) .. tostring({}) .. tostring(os.clock())) + local variant = ({ "8", "9", "a", "b" })[(tonumber(h:sub(17, 17), 16) % 4) + 1] + return h:sub(1, 8) .. "-" .. h:sub(9, 12) .. "-4" .. h:sub(14, 16) .. "-" .. variant .. h:sub(18, 20) .. "-" .. h:sub(21, 32) +end +BookOrbit.uuid4 = uuid4 + +local function playbackState(self, book_id) + local code, data, err = self:keyCall("GET", "/api/v1/audiobooks/" .. tostring(audioId(book_id)) .. "/playback-state", { timeouts = { 8, 15 } }) + if code == 200 then return type(data) == "table" and n(data.positionMs) and data or false end -- (false: none stored) + return nil, err or ("http_" .. tostring(code)), code +end + +--- Where an audiobook was left, as Grimmory's record gives it (audiobookProgress: +--- positionMs within the track, trackIndex), for gzreader_audiobook.lua's pull. +function BookOrbit:audiobookRecord(book_id) + local state, err = playbackState(self, book_id) + if state == nil then return nil, err end + local book = { id = book_id, metadata = {} } + if state then + local m = manifest(self, book_id) + local index = 0 + for _i, a in ipairs(m and m.assets or {}) do if a.assetId == state.assetId then index = n(a.sequence) or 0 end end + book.audiobookProgress = { positionMs = state.positionMs, trackIndex = index, percentage = n(state.percentage) } + end + return book +end + +--- Save where an audiobook is (body as gzreader_audiobook.lua makes it for Grimmory: +--- positionData = ms in the track, positionHref = the track's index when it has +--- several files). BookOrbit wants the file, its place, and the revisions this is +--- based on; a place moved elsewhere meanwhile (409) is read again and sent once more. +function BookOrbit:putAudioProgress(book_id, body) + local fp = type(body) == "table" and type(body.fileProgress) == "table" and body.fileProgress or {} + local ms = tonumber(fp.positionData) + if not ms then return false, "bookorbit_unmatched", 400 end + local m, merr, mcode = manifest(self, book_id) + if not m then return false, merr, mcode end + local asset = m.assets[1] + for _i, a in ipairs(m.assets) do if fp.positionHref ~= nil and n(a.sequence) == tonumber(fp.positionHref) then asset = a end end + ms = math.max(0, math.min(math.floor(ms), n(asset.durationMs) or math.floor(ms))) + local last_err, last_code + for _try = 1, 2 do + local state, serr, scode = playbackState(self, book_id) + if state == nil then return false, serr, scode end + local code, _, err = self:keyCall("PUT", "/api/v1/audiobooks/" .. tostring(audioId(book_id)) .. "/playback-state", { + body = { assetId = asset.assetId, positionMs = ms, capturedAt = os.date("!%Y-%m-%dT%H:%M:%SZ"), operationId = uuid4(), + baseRevision = state and n(state.revision) or 0, manifestRevision = m.revision }, + timeouts = { 8, 15 } }) + if code == 200 then return true end + last_err, last_code = err or ("http_" .. tostring(code)), code + if code ~= 409 then break end -- (409: moved elsewhere since we read it: once more from its new revision) + end + -- (a read-only key, or the audiobook gone or changed: not something to keep retrying) + if last_code == 403 or last_code == 404 or last_code == 400 or last_code == 412 then return false, last_err, 404 end + return false, last_err, last_code +end + +---------------------------------------------------------------- collections (GZreader's shelves), changed from here + +-- Reading collections is the e-reader catalog's (listShelves, listBooks{ shelfId }). Putting a +-- book on one or taking it off is only on the main API, so it needs the API key too. + +function BookOrbit:canEditShelves() return self:hasApiKey() end + +--- Your own collections, as gzreader_shelves.lua reads Grimmory's shelves ({ id, name, bookCount, own }). +function BookOrbit:listMyShelves() + local code, data, err = self:keyCall("GET", "/api/v1/collections", { timeouts = { 10, 20 } }) + if code ~= 200 or type(data) ~= "table" then return nil, err or ("http_" .. tostring(code)) end + local mine + if type(data[1]) == "table" and data[1].userId ~= nil then + -- (others' shared collections are listed too: only your own can be changed) + local mcode, me = self:keyCall("GET", "/api/v1/auth/me", { timeouts = { 8, 15 } }) + mine = mcode == 200 and type(me) == "table" and n(me.id) or nil + end + local out = {} + for _i, c in ipairs(data) do + if type(c) == "table" and n(c.id) and (mine == nil or n(c.userId) == nil or c.userId == mine) then + out[#out + 1] = { id = c.id, name = s(c.name) or ("#" .. tostring(c.id)), bookCount = n(c.bookCount), own = true } + end + end + return out +end + +--- Put a book on collections `add` and take it off `remove` (lists of ids). Returns {} +--- (nothing more is known of the book), or nil, err, code. +function BookOrbit:setBookShelves(book_id, add, remove) + local Json = require("gzreader_json") + local id = tonumber(book_id) + if not id then return nil, "bookorbit_unmatched", 400 end + for _i, step in ipairs({ { "POST", add }, { "DELETE", remove } }) do + for _j, cid in ipairs(type(step[2]) == "table" and step[2] or {}) do + local code, _, err = self:keyCall(step[1], "/api/v1/collections/" .. tostring(cid) .. "/books", + { body = { bookIds = Json.list({ id }) }, timeouts = { 10, 20 } }) + if not (code == 200 or code == 201 or code == 204) then return nil, err or ("http_" .. tostring(code)), code end + end + end + return {} +end + +---------------------------------------------------------------- book requests (API key) + +-- Asking BookOrbit for a book it doesn't have (its Requests page). On the main API, so +-- with the API key, which needs the "Request books" permission (gzreader_bo_requests.lua). + +function BookOrbit:canRequestBooks() return self:hasApiKey() end + +local function requestRecord(r) + if type(r) ~= "table" or not n(r.id) then return nil end + local authors = {} + for _i, a in ipairs(type(r.authors) == "table" and r.authors or {}) do + if s(a) then authors[#authors + 1] = a end + end + return { id = r.id, title = s(r.title), authors = authors, kind = r.mediaKind == "audiobook" and "audiobook" or "ebook", + status = s(r.status), reason = s(r.statusReason), note = s(r.decisionNote), book_id = n(r.matchedBookId) } +end + +local function requestError(code, err) + if err then return err end + if code == 403 then return "bookorbit_requests_refused" end + return "http_" .. tostring(code) +end + +--- Ask for a book. `kind`: "ebook" or "audiobook"; `authors`: a list or nil. Returns the +--- request ({ id, title, status, …, joined = someone had asked already }), or nil, err, code. +function BookOrbit:requestBook(title, authors, kind) + local Json = require("gzreader_json") + local body = { title = title, mediaKind = kind == "audiobook" and "audiobook" or "ebook" } + if type(authors) == "table" and #authors > 0 then body.authors = Json.list(authors) end + local code, data, err = self:keyCall("POST", "/api/v1/book-requests", { body = body, timeouts = { 10, 30 } }) + if not (code == 200 or code == 201) or type(data) ~= "table" then return nil, requestError(code, err), code end + local r = requestRecord(data.request) or { title = title, kind = body.mediaKind } + r.joined = data.subscribed == true or nil + return r +end + +--- What you asked for, newest first (up to 100), or nil, err. +function BookOrbit:listRequests() + local code, data, err = self:keyCall("GET", "/api/v1/book-requests?page=1&limit=100", { timeouts = { 10, 30 } }) + if code ~= 200 or type(data) ~= "table" then return nil, requestError(code, err), code end + local out = {} + for _i, r in ipairs(type(data.items) == "table" and data.items or {}) do + out[#out + 1] = requestRecord(r) + end + return out +end + +--- Cancel one of your requests. Returns true, or false, err, code. +function BookOrbit:cancelRequest(id) + if not tonumber(id) then return false, "http_400", 400 end + local code, _, err = self:keyCall("POST", "/api/v1/book-requests/" .. tostring(id) .. "/cancel", { body = {}, timeouts = { 10, 30 } }) + if code == 200 or code == 201 or code == 204 then return true end + return false, requestError(code, err), code +end + +---------------------------------------------------------------- not yet + +-- Grimmory-only (its single sign-on, its web list) or not sent to BookOrbit yet: each +-- answers nil, "unsupported". Main and the sync modules don't call them while +-- `books_only` is set; this is so a call that slips through fails quietly. +for _i, name in ipairs{ "listWebBooks", "listAuthors", "listSeries", + "listBookmarks", "createBookmark", "deleteBookmark", "listAnnotations", + "createAnnotation", "updateAnnotation", "deleteAnnotation", "listBookNotes", "createBookNote", "updateBookNote", + "deleteBookNote", "postSession", "hasSession", "publicSettings", "oidcExchange" } do + BookOrbit[name] = function() return nil, "unsupported" end +end + +return BookOrbit diff --git a/plugins/gzreader.koplugin/gzreader_bookpage.lua b/plugins/gzreader.koplugin/gzreader_bookpage.lua index 8cf30d60a..b3cbb5c95 100644 --- a/plugins/gzreader.koplugin/gzreader_bookpage.lua +++ b/plugins/gzreader.koplugin/gzreader_bookpage.lua @@ -195,7 +195,7 @@ function BookPage:build() -- the description takes the rest local desc = BookPage.description(self.detail) if not desc then - desc = self.detail and _("No description in Grimmory.") or (self.failed and _("Couldn't get the description from Grimmory.") or _("Getting the description…")) + desc = require("gzreader_servername").fix(self.detail and _("No description in Grimmory.") or (self.failed and _("Couldn't get the description from Grimmory.") or _("Getting the description…"))) end if busy then desc = T(_("Another download is running; this one is queued (%1 waiting)."), #Download.queue) .. "\n\n" .. desc end local used = head:getSize().h + self.buttontable:getSize().h + 2 * pad + S(28) diff --git a/plugins/gzreader.koplugin/gzreader_bookshop.lua b/plugins/gzreader.koplugin/gzreader_bookshop.lua index aa6273c1d..f04f95581 100644 --- a/plugins/gzreader.koplugin/gzreader_bookshop.lua +++ b/plugins/gzreader.koplugin/gzreader_bookshop.lua @@ -938,7 +938,7 @@ local function paintContents(bb, kind, room, info) end elseif kind == "faceout" then local cw = math.min(S(42), math.floor(h * 0.62)) - x = miniCover(bb, x, bottom, cw, math.floor(h * 0.86), info.shelf_name or _("Shelves")) + x = miniCover(bb, x, bottom, cw, math.floor(h * 0.86), info.shelf_name or require("gzreader_servername").shelves()) local _, sp = spines(bb, x, bottom, right, h * 0.95, sd .. "shelf") spans = sp elseif kind == "dividers" then @@ -1026,7 +1026,7 @@ function Page:paintLedge(bb, ox, oy, i, L) local bottom = ledge.y local Sh = Shelf() local p = S(Sh.PAGES) - local msg = #spec.books == 0 and (spec.loading and _("Fetching from Grimmory…") or spec.empty) or "" + local msg = #spec.books == 0 and (spec.loading and require("gzreader_servername").fix(_("Fetching from Grimmory…")) or spec.empty) or "" if msg ~= "" then text(bb, msg, hand(20), ox + math.floor(L.w / 2), bottom - math.floor(led.cover_h / 2), { center = true, middle = true, color = gray(0.7) }) end @@ -1379,7 +1379,7 @@ function Shop.build(m, browser, select_number, no_recalculate_dimen) page.info = info page.cells = {} local names = { - all = _("All books"), libraries = _("Libraries"), shelves = _("Shelves"), authors = _("Authors"), + all = _("All books"), libraries = _("Libraries"), shelves = require("gzreader_servername").shelves(), authors = _("Authors"), series = _("Series"), audiobooks = _("Audiobooks"), } local comps = Shop.arrange(pspec.compartments, function(id) return by[id] ~= nil end, section == "books" or signed_out, #L.cells) diff --git a/plugins/gzreader.koplugin/gzreader_browser.lua b/plugins/gzreader.koplugin/gzreader_browser.lua index 3d45be739..b086ec606 100644 --- a/plugins/gzreader.koplugin/gzreader_browser.lua +++ b/plugins/gzreader.koplugin/gzreader_browser.lua @@ -255,6 +255,12 @@ local function hostOf(server) return type(server) == "string" and (server:gsub("^https?://", ""):gsub("/+$", "")) or "?" end +--- The book server's name, as shown: "Grimmory", or "BookOrbit" when signed in to that. +function Browser.serverName(self) + local p = type(self) == "table" and self.plugin + return type(p) == "table" and type(p.serverName) == "function" and p:serverName() or "Grimmory" +end + --- The Grimmory card (last in the Books and Audiobooks pages' bookcase, as --- Plex's is on the Music page): who you are, or that you aren't signed in. function Browser:grimmoryItem(gz_id) @@ -265,7 +271,7 @@ function Browser:grimmoryItem(gz_id) else sub = (store.server and store.username) and _("signed out") or _("not signed in") end - return { gz_id = gz_id, gz_kind = "section", gz_contents = "none", text = _("Grimmory"), mandatory = sub, + return { gz_id = gz_id, gz_kind = "section", gz_contents = "none", text = Browser.serverName(self), mandatory = sub, callback = function() self:openGrimmory() end } end @@ -296,12 +302,13 @@ function Browser.grimmoryItems(self) local function account() return T(_("%1 · %2"), store.username or "?", hostOf(store.server)) end local items = {} local function add(text, icon, fn) items[#items + 1] = { text = text, gz_icon = icon, callback = fn } end + local orbit = type(plugin.backend) == "function" and plugin:backend() == "bookorbit" if Browser.signedIn(self) then items[1] = { text = _("Signed in"), mandatory = account(), gz_icon = "name:settings_account_outline", select_enabled = false } add(_("Rebuild library"), "refresh", function() plugin:rebuildLibrary() end) if not usb then add(_("Reconnect with QR code"), "send", function() plugin:onGrimmoryPair() end) - add(_("Connect by typing"), "keyboard", function() plugin:keyboardLogin() end) + add(_("Connect by typing"), "keyboard", function() plugin:keyboardLogin(nil, orbit and "bookorbit" or nil) end) end elseif usb then -- (a Kindle without Wi-Fi signs in through the sync page) @@ -312,8 +319,27 @@ function Browser.grimmoryItems(self) mandatory = (store.server and store.username) and account() or nil, gz_icon = "name:settings_account_outline", select_enabled = false } add(_("Connect with QR code"), "send", function() plugin:onGrimmoryPair() end) - add(_("Connect by typing"), "keyboard", function() plugin:keyboardLogin() end) + add(_("Connect by typing"), "keyboard", function() plugin:keyboardLogin(nil, orbit and "bookorbit" or nil) end) add(_("Copy from another GZreader"), "copy", function() require("gzreader_copy").receive(plugin, { only = "grimmory" }) end) + if orbit then + add(_("Connect to Grimmory by typing"), "keyboard", function() plugin:keyboardLogin(nil, "grimmory") end) + elseif type(plugin.backend) == "function" then + add(_("Connect to BookOrbit by typing"), "keyboard", function() plugin:keyboardLogin(nil, "bookorbit") end) + end + end + if Browser.signedIn(self) then + -- (every device's reading, as the server counts it: gzreader_statspage.lua) + add(_("Reading stats"), "details", function() require("gzreader_statspage").show(plugin) end) + end + if orbit and Browser.signedIn(self) and not usb and type(self.push) == "function" then + -- (asking BookOrbit for a book it doesn't have: gzreader_bo_requests.lua) + local Requests = require("gzreader_bo_requests") + add(_("Request a book"), "add", function() Requests.ask(plugin) end) + add(_("My book requests"), "details", function() Requests.open(self) end) + end + if orbit then + items[#items + 1] = Rows.about(_("About BookOrbit"), T(_("BookOrbit is your book server: the Catalog's books come from it.") .. " " .. require("gzreader_bookorbit").note() .. _("\n\nSign in with the %1 sync user name and password you made in BookOrbit (Settings → %1), not your website sign-in.\n\nRebuild library: BookOrbit's list of books fetched again, when the Catalog is missing books or shows old ones.\n\nBookOrbit is its own project (github.com/bookorbit/bookorbit), under the GNU AGPL version 3 with additional terms. GZreader isn't part of it or endorsed by it: it only talks to your BookOrbit server, and has none of BookOrbit's code in it."), "KOReader")) + return Rows.mark(items) end items[#items + 1] = Rows.about(_("About Grimmory"), usb and _("Grimmory is your book server. This Kindle has no Wi-Fi: sign in on the sync page on a computer, then sync. Books, progress and shelves come and go with each sync.") @@ -322,7 +348,7 @@ function Browser.grimmoryItems(self) end function Browser:openGrimmory() - self:push(_("Grimmory"), Browser.grimmoryItems(self)) + self:push(Browser.serverName(self), Browser.grimmoryItems(self)) end --- Signed in (or out) while the Catalog is open: its page again, from the top. @@ -339,12 +365,12 @@ function Browser:bookItems() if not Browser.signedIn(self) then return Browser.signedOutItems(self, "books") end return { gz_root = true, - { gz_id = "search", gz_action = "search", text = _("Search Grimmory…"), callback = function() self:promptSearch() end }, + { gz_id = "search", gz_action = "search", text = T(_("Search %1…"), Browser.serverName(self)), callback = function() self:promptSearch() end }, { gz_id = "continue", text = _("Continue reading"), callback = function() self:openSimple("continue-reading", _("Continue reading")) end }, { gz_id = "recent", text = _("Recently added"), callback = function() self:openSimple("recently-added", _("Recently added")) end }, { gz_id = "all", text = _("All books"), callback = function() self:openPaged(_("All books"), { sort = "title", dir = "asc" }) end }, { gz_id = "libraries", text = _("Libraries"), callback = function() self:openLibraries() end }, - { gz_id = "shelves", text = _("Shelves"), callback = function() self:openShelves() end }, + { gz_id = "shelves", text = require("gzreader_servername").shelves(), callback = function() self:openShelves() end }, { gz_id = "authors", text = _("Authors"), callback = function() self:openAuthors() end }, { gz_id = "series", text = _("Series"), callback = function() self:openSeries() end }, Browser.grimmoryItem(self, "grimmory"), @@ -529,7 +555,7 @@ function Browser:audiobookItems() mandatory = audioCount(n) or _("M4B and MP3"), callback = function() self:openAudiobooks() end }, { gz_id = "ab_authors", gz_kind = "section", gz_contents = "dividers", text = _("Authors"), mandatory = na and na > 0 and T(_("%1 · A–Z"), na) or _("A–Z"), callback = function() self:openAudioAuthors() end }, - { gz_id = "ab_shelves", gz_kind = "section", gz_contents = "faceout", text = _("Shelves"), + { gz_id = "ab_shelves", gz_kind = "section", gz_contents = "faceout", text = require("gzreader_servername").shelves(), mandatory = _("yours and magic"), callback = function() self:openAudioShelves() end }, { gz_id = "ab_series", gz_kind = "section", gz_contents = "piles", text = _("Series"), mandatory = ns and ns > 0 and (ns == 1 and _("1 series") or T(_("%1 series"), ns)) or _("in order"), @@ -611,7 +637,7 @@ function Browser:openAudioShelves() end self:openCached{ key = "shelves", - title = _("Shelves"), + title = require("gzreader_servername").shelves(), fetch = function() return self.api:listShelves() end, build = function(shelves) local items = {} @@ -940,7 +966,7 @@ function Browser:openPaged(title, params, with_series_number, opts) or (opts.audio and Browser.audioScope()) or nil header = { { gz_action = "search", - text = scoped and T(_("Search in %1…"), title) or (opts.audio and _("Search audiobooks…") or _("Search Grimmory…")), + text = scoped and T(_("Search in %1…"), title) or (opts.audio and _("Search audiobooks…") or T(_("Search %1…"), Browser.serverName(self))), callback = function() self:promptSearch(scope) end, } } end @@ -983,7 +1009,7 @@ end local function refreshItem(self, reopen) return { gz_action = "refresh", - text = _("Refresh list from Grimmory"), + text = require("gzreader_servername").fix(_("Refresh list from Grimmory")), callback = function() -- (a list opened from the saved index needs no Wi-Fi, so it may be -- off by now: "Wi-Fi only when needed" turns it off when idle) @@ -1037,7 +1063,7 @@ end function Browser:openShelves() self:openCached{ key = "shelves", - title = _("Shelves"), + title = require("gzreader_servername").shelves(), fetch = function() return self.api:listShelves() end, build = function(shelves) local items = {} @@ -1048,7 +1074,7 @@ function Browser:openShelves() text = name, sort_key = (sh.magic and "1" or "0") .. name:lower(), gz_kind = "shelf", gz_magic = sh.magic and true or nil, gz_count = tonumber(sh.bookCount), - mandatory = sh.magic and _("smart shelf") or countText(sh.bookCount), + mandatory = sh.magic and require("gzreader_servername").smart() or countText(sh.bookCount), callback = function() local params = { sort = "title", dir = "asc" } if sh.magic then params.magicShelfId = sh.id else params.shelfId = sh.id end @@ -1162,7 +1188,7 @@ end function Browser:promptSearch(scope, text) local dialog dialog = InputDialog:new{ - title = scope and T(_("Search in %1"), scope.title) or _("Search Grimmory"), + title = scope and T(_("Search in %1"), scope.title) or T(_("Search %1"), Browser.serverName(self)), input = text, input_hint = _("Title, author or series"), buttons = {{ diff --git a/plugins/gzreader.koplugin/gzreader_changelog.lua b/plugins/gzreader.koplugin/gzreader_changelog.lua index 330df6a81..71bd30428 100644 --- a/plugins/gzreader.koplugin/gzreader_changelog.lua +++ b/plugins/gzreader.koplugin/gzreader_changelog.lua @@ -6,6 +6,27 @@ -- on one line (the beta branch combines "next" lines). A plain string is the -- text alone (the screen shows its first sentence). return { + { + version = "next", + changes = { + { short = "BookOrbit: the Catalog says Collections and BookOrbit", text = "Signed in to BookOrbit, the Catalog's Shelves card and list are now called Collections, as BookOrbit calls them, and the list's self-filling ones are marked SmartScope (they were smart shelf). Texts that named Grimmory name BookOrbit: Fetching from BookOrbit… while a list loads, Refresh list from BookOrbit, a book's missing description, the Audiobooks tab's line, and the messages about a different copy and about a book that can't be synced. With Grimmory everything reads as before." }, + { short = "BookOrbit: books already on the Kindle are recognised right after signing in", text = "After switching to BookOrbit, books downloaded earlier (from Grimmory, or copied over) still said Download in the Catalog: they were only matched to BookOrbit's books when the library list was next rebuilt, which could be much later. They're now matched by their files a couple of seconds after signing in, and again whenever Wi-Fi comes on, so the Catalog says Read and their progress syncs. A file BookOrbit doesn't have as the very same file stays unmatched; the log says how many were matched." }, + { short = "Setup page: a Books tab that fits the server you choose", text = "The setup page's Grimmory tab is now called Books, and its heading names the server: Grimmory or BookOrbit, changing as you choose under Book server. Choosing BookOrbit shows BookOrbit's own form: the API key first (the easy way: the key alone signs the Kindle in), with the KOReader sync user name and password as the other way, and no single sign-on button, which BookOrbit's e-reader sign-in doesn't have. After connecting, the page and the Kindle say Connected to BookOrbit (they said Grimmory). Saving an API key is now confirmed on the page, with what the key can do (request books, sign in by itself), and removing one is confirmed too. Disconnecting and the Kindle's summary after setup also name the right server." }, + { short = "BookOrbit: what to tick for the API key", text = "Wherever GZreader asks for BookOrbit's API key it now says what the key needs, in the words of BookOrbit's Create API key page: Access Read and write; Extra permissions KOReader sync (to sign in with the key) and Request books (to request books); nothing else, and not Administrator access. Messages point at BookOrbit's settings where they really are (Settings → You → API keys, Settings → Devices → KOReader). When the key can see your sync sign-in, GZreader also checks how BookOrbit delivers read-aloud EPUBs to it: if that's set to the original with narration, which a Kindle can't play and which makes the files much bigger, the setup page says so and where to set it back to Automatic. A sync sign-in the Kindle makes itself is left on BookOrbit's defaults." }, + { short = "BookOrbit: nothing of Grimmory's runs in the background", text = "Signed in to BookOrbit, every download and library refresh used to start a background process to refresh a Grimmory login that BookOrbit doesn't have; it did nothing, but starting it costs time and memory on an old Kindle. It no longer starts. Grimmory's bookmark module is also no longer loaded when the book server is BookOrbit. Measured on a Kindle 3 in the emulator, opening a book, 20 page turns and closing it take the same CPU time signed in to BookOrbit as signed in to nothing." }, + { short = "Reading stats from BookOrbit too, and a stats page", text = "Home's reading stats widget (now called Reading stats (every device)) takes its numbers from the book server this Kindle is signed in to: Grimmory as before, or BookOrbit. With BookOrbit the slots can show Read today, this week, this month or this year, Day streak, Longest streak, Days read this year, Finished this year, Reading goal, Badges, Books in the library and Reading now. Tapping the widget opens a reading stats page (also Catalog → the server's card → Reading stats). With BookOrbit: the last seven days as bars, the past year as a grid of days, the reading goal and next badge as progress bars, the book of a year ago, this year's finished books and the highlight of the day. With Grimmory: this week's books, the month as a calendar and books finished by month. In colour on colour screens. About BookOrbit now says that BookOrbit is a separate project and GZreader isn't part of it." }, + { short = "BookOrbit: sign in with just an API key", text = "BookOrbit can now be signed in to with only its address and an API key, on the setup page (the QR code): choose BookOrbit, open “sign in with an API key instead”, paste the key. The Kindle uses the key to ask BookOrbit for your KOReader sync sign-in and signs in with it, so there's no sync user name or password to type, and the same key is kept for audiobooks, collections and book requests. If your BookOrbit account has no sync sign-in yet, one is made for you under your account's name. The key needs “KOReader sync” ticked and read and write access when you make it (BookOrbit: Settings → API keys). Signing in with the sync user name and password works as before." }, + { short = "BookOrbit: request a book", text = "With BookOrbit as the book server and its API key entered, the Catalog's BookOrbit card has Request a book: type a title (and the author if you like), choose Book or Audiobook, and BookOrbit gets the request as if you'd made it on its Requests page. My book requests lists what you asked for with its state (waiting for approval, searching, downloading, in the library, declined) and any note from whoever decided; a request that isn't finished can be cancelled from there. The API key needs “Request books” ticked when you make it in BookOrbit. The key's setting is now called BookOrbit API key (it was BookOrbit API key (audiobooks)), since audiobooks, collections and requests all use it." }, + { short = "BookOrbit: add books to collections", text = "With BookOrbit as the book server and its API key entered, a book's menu can put it on your BookOrbit collections and take it off them (Add to shelf / Remove from shelf, as with Grimmory's shelves): the change shows on the Kindle at once and reaches BookOrbit the next time there's Wi-Fi. Only your own collections are offered, not ones other people shared with you. Without the API key the menu says where to enter it (Settings → Accounts and services → Books); browsing collections in the Catalog doesn't need the key." }, + { short = "BookOrbit: reading time and ratings", text = "With BookOrbit as the book server, your reading time now reaches BookOrbit's reading activity: the pages you read and how long each took, as KOReader's own statistics record them, are sent a few seconds after a book closes (and at most every ten minutes otherwise) for the books that are BookOrbit's. BookOrbit makes its reading sessions from them and ignores anything it already has, so nothing is counted twice. Ratings sync both ways too: the stars you give a book on the Kindle are set in BookOrbit, and BookOrbit's rating is taken on the Kindle when you haven't rated the book here. Both follow the Sync switch in Settings → Accounts and services → Books; reading time needs KOReader's reading statistics to be on (they are by default)." }, + { short = "BookOrbit: audiobooks, with a BookOrbit API key", text = "With BookOrbit as the book server, its audiobooks are now in the Catalog's Audiobooks page: listed with covers, downloaded (an interrupted download continues where it stopped), played with their chapters, and where you stopped listening syncs both ways with BookOrbit's player. BookOrbit keeps its audiobook routes apart from the e-reader sign-in, so this needs an API key as well: make one in BookOrbit (Settings → API keys, with read and write access) and enter it on the setup page under the BookOrbit connection, or in Settings → Accounts and services → Books → BookOrbit API key. The key is checked when you enter it, kept on the Kindle's own disk with the other sign-ins, never shown again and never logged. A read-only key lists and downloads but can't save your place; a key that has expired is reported so you can make a new one. Without a key nothing changes: books, progress, highlights and bookmarks need only the sign-in." }, + { short = "BookOrbit: page bookmarks sync both ways", text = "With BookOrbit as the book server, the pages you dog-ear now sync both ways in EPUBs and the other reflowable books: a bookmark made on the Kindle appears in BookOrbit, one made on another device appears on the Kindle (the page gets its dog-ear), and removing one on either side removes it on the other. It runs when a book opens, a few seconds after you add or remove a bookmark, and on Sync now. It needs a BookOrbit that offers bookmark sync (GZreader asks the server at sign-in); bookmarks in PDFs stay on the Kindle. The switch is the same one as for Grimmory, in Settings → Accounts and services → Books." }, + { short = "BookOrbit: highlights and their notes sync both ways", text = "With BookOrbit as the book server, highlights and the notes on them now sync both ways in EPUBs and the other reflowable books: a highlight you make on the Kindle (with its colour, style and note) appears in BookOrbit's web reader, and one made, changed or removed there appears, changes or goes on the Kindle. It runs a few seconds after a book opens, a few seconds after you change a highlight, on Sync now, and when the book closes if something is waiting. BookOrbit converts the positions for its web reader itself. A highlight BookOrbit can't place in this copy of the book is skipped and noted in the log. Highlights in PDFs aren't exchanged (BookOrbit places them in reflowable books only). The switch is the same one as for Grimmory: Settings → Accounts and services → Books → Sync highlights and notes." }, + { short = "BookOrbit: your place in each book syncs, and books already on the Kindle are matched to it", text = "With BookOrbit as the book server, reading progress now syncs both ways: your place is sent as you read, when you close a book and when the Kindle sleeps (queued while Wi-Fi is off), and when you open a book GZreader goes to where you left it on another device, asking first before going back. BookOrbit works out its web reader's place from the Kindle's itself, so the exact page carries over. Books already in GZreader/books (downloaded from Grimmory before you switched, or copied over USB) are matched to BookOrbit's by the file's fingerprint: the ones BookOrbit has become its downloads (marked in the Catalog, progress synced) whatever the file is called. A file that was changed since BookOrbit's copy (some servers write the cover or details into a download) won't match and stays a plain book on the Kindle. Highlights, bookmarks, reading time, ratings and audiobooks aren't synced with BookOrbit yet." }, + { short = "The setup guide first asks how you'll use GZreader: Grimmory, BookOrbit, or on its own", text = "On its first start (and in Settings → General → Setup Guide) GZreader now begins by asking how you will use it: with Grimmory, with BookOrbit, or on its own, sending books from your browser. The next page fits the answer: for Grimmory or BookOrbit, setting up from a browser (the QR code, with that server already picked on the page) or typing the sign-in on the Kindle; on its own, the QR code that opens the page where you drop your books. The guide's later page about sync says what is true for your answer too. If the Kindle is already signed in, that server is the default and keeping the connection is offered as before. The answer only chooses what the guide offers: nothing is hidden or switched off, and you can connect a book server later in Settings → Accounts and services → Books." }, + { short = "BookOrbit can be the book server instead of Grimmory (first part: browse and download)", text = "GZreader can now sign in to a BookOrbit server instead of Grimmory. Choose BookOrbit under Book server on the setup page, or Settings → Accounts and services → Books → Connect to BookOrbit by typing, and give BookOrbit's address and the KOReader sync user name and password you made in BookOrbit (Settings → KOReader; not your website sign-in). The Catalog then shows BookOrbit's books: all books, libraries, collections as shelves, SmartScopes as magic shelves, authors, series and search, with covers, and you can download books and have a collection download by itself. This is the first part: reading progress, highlights, bookmarks, statistics and audiobooks aren't sent to BookOrbit yet, so GZreader only reads from it. A Kindle is signed in to one book server at a time: the books downloaded from the other one stay on the Kindle and in the Downloads tab, and open as before, but they aren't tied to a book on the new server (no downloaded mark in the Catalog, nothing synced for them) until you sign in to the old one again. The password is never stored (only its MD5, which is what BookOrbit's e-reader sign-in uses, kept on the Kindle's own disk), and nothing of the sign-in is logged." }, + }, + }, { version = "1.35.0", changes = { diff --git a/plugins/gzreader.koplugin/gzreader_copy.lua b/plugins/gzreader.koplugin/gzreader_copy.lua index d7cc324dd..b5ebcb470 100644 --- a/plugins/gzreader.koplugin/gzreader_copy.lua +++ b/plugins/gzreader.koplugin/gzreader_copy.lua @@ -109,7 +109,7 @@ end --- What this device could send, without anything secret (shown on the other). function Copy.offer(plugin) local store, out = plugin.store, { name = Copy.deviceName(plugin) } - if plugin.api and plugin.api:isPaired() then + if plugin.api and plugin.api:isPaired() and not plugin.api.books_only then out.grimmory = { host = host(store.server), username = store.username } end local ms = store.memos or {} @@ -135,7 +135,7 @@ end function Copy.payload(plugin, want) local store, out = plugin.store, {} want = type(want) == "table" and want or {} - if want.grimmory and plugin.api and plugin.api:isPaired() then + if want.grimmory and plugin.api and plugin.api:isPaired() and not plugin.api.books_only then -- (the address and account: Grimmory's sign-in stays on this device) out.grimmory = { server = store.server, username = store.username } end @@ -548,7 +548,7 @@ end function Copy.defaults(plugin, offer, only) local store = plugin.store local has = { - grimmory = plugin.api and plugin.api:isPaired(), + grimmory = plugin.api and plugin.api:isPaired() and not plugin.api.books_only, memos = (store.memos or {}).token ~= nil, caldav = (store.caldav or {}).password ~= nil, } diff --git a/plugins/gzreader.koplugin/gzreader_covers.lua b/plugins/gzreader.koplugin/gzreader_covers.lua index 898fa95af..beb242265 100644 --- a/plugins/gzreader.koplugin/gzreader_covers.lua +++ b/plugins/gzreader.koplugin/gzreader_covers.lua @@ -38,8 +38,17 @@ function Covers.notePlex(id, thumb) if id and thumb then Covers.plex_thumbs[tostring(id)] = thumb end end +--- Covers are kept by book id, and each book server has its own ids: BookOrbit's +--- are in their own folder (space = "bookorbit"; nil: Grimmory's, as before). +function Covers.useSpace(space) + space = space and ("-" .. space) or "" + if space == (Covers.space or "") then return end + Covers.space, Covers.dir_ok = space, nil + Covers.memory = {} -- (the shrunk ones in memory are the other server's books) +end + function Covers.dir() - local dir = DataStorage:getDataDir() .. "/cache/gzreader-covers" + local dir = DataStorage:getDataDir() .. "/cache/gzreader-covers" .. (Covers.space or "") if not Covers.dir_ok then lfs.mkdir(DataStorage:getDataDir() .. "/cache") lfs.mkdir(dir) diff --git a/plugins/gzreader.koplugin/gzreader_grimstats.lua b/plugins/gzreader.koplugin/gzreader_grimstats.lua index bf9c286b7..6bbcc81a8 100644 --- a/plugins/gzreader.koplugin/gzreader_grimstats.lua +++ b/plugins/gzreader.koplugin/gzreader_grimstats.lua @@ -1,26 +1,55 @@ --[[-- -Reading stats from Grimmory for Home's "Grimmory reading stats" widget -(zenos: home/widgets/grimmory_stats.lua). They count every device: each -GZreader (and Grimmory's web reader) sends its reading sessions, and -Grimmory adds them up (its user stats, /api/v1/user-stats/...): +Reading stats from the book server, for Home's reading stats widget (zenos: +home/widgets/grimmory_stats.lua) and the page a tap on it opens +(gzreader_statspage.lua). They count every device, because the server adds up +what each one sends. Which server: the one this Kindle is signed in to. + +Grimmory (its user stats, /api/v1/user-stats/...): streak, longest_streak, reading_days reading/streak week_time, week_books reading/timeline (this ISO week) month_sessions reading/heatmap/monthly year_finished reading/completion-timeline +BookOrbit (one call, GET koreader/plugin/catalog/dashboard, with the e-reader +sign-in; GS.fromDashboard turns it into the same kind of values): + + streak, longest_streak readingStreak + today_time, week_time, month_time, + year_time, year_days readingYear (minutes per day, a year back) + year_finished, goal readingGoal + badges achievements (absent when switched off) + library_books, reading_now totalBooks, browseCounts + +Beside the values, `detail` keeps what the page draws (GS.FIELDS says which +values each server has): BookOrbit's days, goal, badges, the book of a year ago, +finished books and the day's highlight; Grimmory's books of the week, days of +the month and finished books by month. + Fetched in the background when Home shows them and they're over 15 minutes old (only while Wi-Fi is already on, never turning it on), and after this -Kindle's reading sessions reach Grimmory. The last ones are kept for when -it's offline. Grimmory only answers users allowed to see their statistics -(its "access user stats" permission): without it, the widget shows dashes -and the log says why. +Kindle's reading reaches the server. The last ones are kept for when it's +offline. Grimmory only answers users allowed to see their statistics (its +"access user stats" permission): without it, the widget shows dashes and the +log says why. ]] local Log = require("gzreader_log") local GS = { TTL = 15 * 60 } +--- Which values each server has (the widget offers these; the first three are its defaults). +GS.FIELDS = { + grimmory = { "week_time", "streak", "year_finished", "longest_streak", "reading_days", "week_books", "month_sessions" }, + bookorbit = { "week_time", "streak", "year_finished", "longest_streak", "today_time", "month_time", "year_time", "year_days", + "goal", "badges", "library_books", "reading_now" }, +} + +--- "grimmory" or "bookorbit": whose numbers this Kindle shows. +function GS.server(plugin) + return type(plugin) == "table" and type(plugin.backend) == "function" and plugin:backend() == "bookorbit" and "bookorbit" or "grimmory" +end + --- ISO week of year as Grimmory's WeekFields.ISO.weekOfYear() counts it --- (Monday first; week 1 has at least 4 days of the year; days before it: 0). function GS.isoWeekOfYear(t) @@ -54,16 +83,139 @@ function GS.fetch(api, now) reading_days = tonumber(streak.totalReadingDays), } local week, wyear = GS.isoWeekOfYear(now) + local detail = { year = d.year, month = d.month } local timeline = get("timeline?year=" .. wyear .. "&week=" .. week) if type(timeline) == "table" then values.week_time = sum(timeline, "totalDurationSeconds") values.week_books = #timeline + -- (the week's books, most read first, for the page) + local books = {} + for _i, r in ipairs(timeline) do + if type(r) == "table" and (tonumber(r.totalDurationSeconds) or 0) > 0 then + books[#books + 1] = { title = type(r.bookTitle) == "string" and r.bookTitle or "?", seconds = tonumber(r.totalDurationSeconds) } + end + end + table.sort(books, function(a, b) return a.seconds > b.seconds end) + for i = #books, 6, -1 do books[i] = nil end + detail.week_books = books end local heat = get("heatmap/monthly?year=" .. d.year .. "&month=" .. d.month) - if type(heat) == "table" then values.month_sessions = sum(heat, "count") end + if type(heat) == "table" then + values.month_sessions = sum(heat, "count") + local days = {} + for _i, r in ipairs(heat) do + local day = type(r) == "table" and type(r.date) == "string" and tonumber(r.date:match("^%d+%-%d+%-(%d+)")) + if day and (tonumber(r.count) or 0) > 0 then days[#days + 1] = { day = day, count = tonumber(r.count) } end + end + detail.month_days = days + end local done = get("completion-timeline?year=" .. d.year) - if type(done) == "table" then values.year_finished = sum(done, "finishedBooks") end - return { values = values } + if type(done) == "table" then + values.year_finished = sum(done, "finishedBooks") + local months = {} + for _i, r in ipairs(done) do + local m = type(r) == "table" and tonumber(r.month) + if m and m >= 1 and m <= 12 then months[#months + 1] = { month = m, finished = tonumber(r.finishedBooks) or 0 } end + end + detail.finished_months = months + end + return { values = values, detail = detail } +end + +local function text(v, max) + if type(v) ~= "string" or v == "" then return nil end + return max and #v > max and (v:sub(1, max):gsub("[\128-\191]*$", ""):gsub("[\192-\255]$", "") .. "…") or v +end + +local function dayTime(key, add) + local y, m, d = tostring(key):match("^(%d+)%-(%d+)%-(%d+)") + if not y then return nil end + return os.time{ year = tonumber(y), month = tonumber(m), day = tonumber(d) + (add or 0), hour = 12 } +end + +local function bookLine(b) + if type(b) ~= "table" then return nil end + local who = type(b.authors) == "table" and type(b.authors[1]) == "string" and b.authors[1] or nil + return { title = text(b.title, 80) or "?", author = text(who, 60) } +end + +--- BookOrbit's dashboard reply as { values, detail } (no network: tested by itself). +function GS.fromDashboard(dash) + if type(dash) ~= "table" then return { error = "bad_reply" } end + local values, detail = {}, {} + local streak = type(dash.readingStreak) == "table" and dash.readingStreak or {} + values.streak = tonumber(streak.currentStreak) + values.longest_streak = tonumber(streak.longestStreak) + local goal = type(dash.readingGoal) == "table" and dash.readingGoal or {} + values.year_finished = tonumber(goal.completedBooks) + if tonumber(goal.goalBooks) and tonumber(goal.goalBooks) > 0 then + values.goal = string.format("%d/%d", tonumber(goal.completedBooks) or 0, tonumber(goal.goalBooks)) + detail.goal = { done = tonumber(goal.completedBooks) or 0, books = tonumber(goal.goalBooks), year = tonumber(goal.year) } + end + values.library_books = tonumber(dash.totalBooks) + values.reading_now = type(dash.browseCounts) == "table" and tonumber(dash.browseCounts.inProgress) or nil + -- minutes read per day, oldest first, ending today (the reader's time zone, as the server has it) + local ry = type(dash.readingYear) == "table" and dash.readingYear or nil + local mins = ry and type(ry.minutes) == "table" and ry.minutes or nil + local last = mins and dayTime(ry.startDate, #mins - 1) + if last and #mins > 0 then + local today = os.date("*t", last) + local since_monday = (today.wday + 5) % 7 -- Monday 0 … Sunday 6 + local week, month, year, year_days = 0, 0, 0, 0 + local kept = {} + for i, m in ipairs(mins) do + m = math.max(0, math.floor(tonumber(m) or 0)) + kept[i] = m + local back = #mins - i -- days before today + if back <= since_monday then week = week + m end + if back < today.day then month = month + m end + if back < today.yday then + year = year + m + if m > 0 then year_days = year_days + 1 end + end + end + values.today_time = kept[#kept] * 60 + values.week_time, values.month_time, values.year_time, values.year_days = week * 60, month * 60, year * 60, year_days + detail.days = { start = ry.startDate, minutes = kept } + end + local ach = type(dash.achievements) == "table" and dash.achievements or nil + if ach and tonumber(ach.total) then + values.badges = string.format("%d/%d", tonumber(ach.earned) or 0, tonumber(ach.total)) + local function badge(b) + if type(b) ~= "table" or not text(b.name) then return nil end + return { name = text(b.name, 60), about = text(b.description, 160), progress = tonumber(b.currentProgress), threshold = tonumber(b.threshold) } + end + detail.badges = { earned = tonumber(ach.earned) or 0, total = tonumber(ach.total), next = badge(ach.next), latest = badge(ach.latest) } + end + local ago = type(dash.yearAgo) == "table" and dash.yearAgo or nil + if ago and type(ago.book) == "table" then + local b = bookLine(ago.book) + detail.year_ago = { title = b.title, author = b.author, minutes = tonumber(ago.minutes) or 0, days = tonumber(ago.days) or 0 } + end + if type(dash.finishedThisYear) == "table" then + local done = {} + for i, b in ipairs(dash.finishedThisYear) do + if i > 8 then break end + done[#done + 1] = bookLine(b) + end + detail.finished = done + detail.finished_count = #dash.finishedThisYear + end + local hl = type(dash.highlightOfTheDay) == "table" and dash.highlightOfTheDay or nil + if hl and text(hl.text) then + detail.highlight = { text = text(hl.text, 400), book = text(hl.bookTitle, 80), chapter = text(hl.chapterTitle, 80) } + end + return { values = values, detail = detail } +end + +--- Ask the server this Kindle is signed in to (in the background process). +function GS.fetchFor(api, now) + if type(api.readingDashboard) == "function" then + local dash, err = api:readingDashboard() + if not dash then return { error = tostring(err) } end + return GS.fromDashboard(dash) + end + return GS.fetch(api, now) end local function same(a, b) @@ -76,37 +228,56 @@ end --- Fetch them if they're old (and Wi-Fi is on): Home redraws when they change. function GS.refresh(plugin, force) if GS.busy or not (plugin.api and plugin.api:isPaired()) then return end - local cached = plugin.store.grimmory_stats + local server = GS.server(plugin) + local name = server == "bookorbit" and "BookOrbit" or "Grimmory" + local cached = GS.kept(plugin) if not force and cached and os.time() - (tonumber(cached.at) or 0) < GS.TTL then return end local NetworkMgr = require("ui/network/manager") if not NetworkMgr:isConnected() then return end GS.busy = true - require("gzreader_async").run(plugin.api, function(api) return GS.fetch(api) end, function(res) + require("gzreader_async").run(plugin.api, function(api) return GS.fetchFor(api) end, function(res) GS.busy = nil if type(res) ~= "table" then return end local old = cached and cached.values if res.error then - Log.warn("Grimmory reading stats:", res.error == "permission" + Log.warn(name, "reading stats:", res.error == "permission" and "this user may not see reading statistics (Grimmory: user settings → permissions)" or res.error) - plugin.store.grimmory_stats = { at = os.time(), values = old or {}, error = res.error } + plugin.store.grimmory_stats = { at = os.time(), values = old or {}, detail = cached and cached.detail, error = res.error, server = server } else - plugin.store.grimmory_stats = { at = os.time(), values = res.values } + plugin.store.grimmory_stats = { at = os.time(), values = res.values, detail = res.detail, server = server } end plugin:save() if not same(old, plugin.store.grimmory_stats.values) then local UIManager = require("ui/uimanager") UIManager:nextTick(function() pcall(function() require("common/gz_view").redrawHome() end) end) end - end, "grimmory stats") + end, "reading stats") +end + +--- The numbers kept, when they're from the server this Kindle is signed in to now +--- (ones kept before the server was noted are Grimmory's). +function GS.kept(plugin) + local cached = plugin.store.grimmory_stats + if type(cached) ~= "table" or (cached.server or "grimmory") ~= GS.server(plugin) then return nil end + return cached end --- What the widget shows now (and a refresh if they're old). function GS.values(plugin) pcall(GS.refresh, plugin) - local cached = plugin.store.grimmory_stats + local cached = GS.kept(plugin) return cached and cached.values or {} end +--- Everything for the page: { server, name, values, detail, at, error }. +function GS.all(plugin) + pcall(GS.refresh, plugin) + local cached = GS.kept(plugin) or {} + local server = GS.server(plugin) + return { server = server, name = server == "bookorbit" and "BookOrbit" or "Grimmory", values = cached.values or {}, + detail = cached.detail or {}, at = tonumber(cached.at), error = cached.error, usb = cached.usb } +end + --- After reading sessions reached Grimmory: fetch again next time. function GS.stale(plugin) if plugin.store.grimmory_stats then plugin.store.grimmory_stats.at = 0 end diff --git a/plugins/gzreader.koplugin/gzreader_gzip.lua b/plugins/gzreader.koplugin/gzreader_gzip.lua index ca9cac986..30ffc7e4f 100644 --- a/plugins/gzreader.koplugin/gzreader_gzip.lua +++ b/plugins/gzreader.koplugin/gzreader_gzip.lua @@ -74,4 +74,39 @@ function Gzip.inflate(data) return table.concat(parts) end +--- Decompress a bare deflate stream (a zip's entry: gzreader_zipread.lua); nil, err on +--- failure. `max`: give up past that many bytes ("too big"). Its own function, so the +--- gzip one above stays as it is. +function Gzip.inflateRaw(data, max) + local z = lib() + if not z then return nil, "no zlib" end + local strm = ffi.new("gz_z_stream") + strm.next_in = ffi.cast("const unsigned char *", data) + strm.avail_in = #data + if z.inflateInit2_(strm, -15, z.zlibVersion(), ffi.sizeof("gz_z_stream")) ~= 0 then + return nil, "inflateInit failed" + end + local chunk = math.max(65536, #data * 4) + local buf = ffi.new("unsigned char[?]", chunk) + local parts, total = {}, 0 + local ret + repeat + strm.next_out = buf + strm.avail_out = chunk + ret = z.inflate(strm, 0) + if ret ~= 0 and ret ~= 1 then + z.inflateEnd(strm) + return nil, "inflate error " .. tostring(ret) + end + parts[#parts + 1] = ffi.string(buf, chunk - strm.avail_out) + total = total + chunk - strm.avail_out + if max and total > max then + z.inflateEnd(strm) + return nil, "too big" + end + until ret == 1 or (strm.avail_in == 0 and strm.avail_out ~= 0) + z.inflateEnd(strm) + return table.concat(parts) +end + return Gzip diff --git a/plugins/gzreader.koplugin/gzreader_index.lua b/plugins/gzreader.koplugin/gzreader_index.lua index 291b8fd91..cf4b3bbcf 100644 --- a/plugins/gzreader.koplugin/gzreader_index.lua +++ b/plugins/gzreader.koplugin/gzreader_index.lua @@ -91,6 +91,10 @@ local function collect(api, report) page = page + 1 report(page, pages) end + -- (a server whose book lists don't say each book's library, BookOrbit, counts them itself) + if next(libraries) == nil and type(api.libraryCounts) == "function" then + libraries = api:libraryCounts() or libraries + end -- Subtitles: only Grimmory's web book list has them. Optional (older -- servers may not have /books/page); failures just leave them out. local subtitles = {} diff --git a/plugins/gzreader.koplugin/gzreader_musictab.lua b/plugins/gzreader.koplugin/gzreader_musictab.lua index 150874b34..c6c77f6b0 100644 --- a/plugins/gzreader.koplugin/gzreader_musictab.lua +++ b/plugins/gzreader.koplugin/gzreader_musictab.lua @@ -539,7 +539,7 @@ end function Tab.audiobooksText(plugin) local sec = require("gzreader_plex").audiobookSection(plugin.store.plex) if sec then return T(_("Audiobooks: from Plex (%1)"), sec.title or "?") end - return _("Audiobooks: from Grimmory") + return require("gzreader_servername").fix(_("Audiobooks: from Grimmory")) end --- Where the audiobooks come from on its own (the Plex card's value). diff --git a/plugins/gzreader.koplugin/gzreader_newcopy.lua b/plugins/gzreader.koplugin/gzreader_newcopy.lua index 518c0dcfc..79e769dc2 100644 --- a/plugins/gzreader.koplugin/gzreader_newcopy.lua +++ b/plugins/gzreader.koplugin/gzreader_newcopy.lua @@ -61,8 +61,8 @@ function NewCopy.check(plugin, ui, book_id, entry) UIManager:scheduleIn(2, function() if not (ui.document and ui.document.file == entry.path) then return end UIManager:show(require("ui/widget/confirmbox"):new{ - text = T(_("Grimmory has a different copy of “%1” now (%2 here, %3 on Grimmory): it may have been replaced with another edition.\n\nDownload it again? Your place in the book comes back from Grimmory."), - entry.title or name or key, mb(size), mb(kb * 1024)), + text = require("gzreader_servername").fix(T(_("Grimmory has a different copy of “%1” now (%2 here, %3 on Grimmory): it may have been replaced with another edition.\n\nDownload it again? Your place in the book comes back from Grimmory."), + entry.title or name or key, mb(size), mb(kb * 1024))), ok_text = _("Download again"), cancel_text = _("Keep this one"), ok_callback = function() diff --git a/plugins/gzreader.koplugin/gzreader_pairpage.lua b/plugins/gzreader.koplugin/gzreader_pairpage.lua index ca1569027..ae200b1fe 100644 --- a/plugins/gzreader.koplugin/gzreader_pairpage.lua +++ b/plugins/gzreader.koplugin/gzreader_pairpage.lua @@ -154,43 +154,92 @@ end local function grimmorySection(st, base) local g = st.grimmory or {} - local parts = { '

Grimmory

', + local orbit = g.backend == "bookorbit" + -- which book server the form is for: the one typed last, else the one signed in to + local picked = ((g.form or {}).backend or g.backend) == "bookorbit" and "bookorbit" or "grimmory" + -- The heading names the server: the one connected, else the one chosen below (it follows the choice). + local title = g.connected and (orbit and "BookOrbit" or "Grimmory") or (picked == "bookorbit" and "BookOrbit" or "Grimmory") + local parts = { '

" .. title .. "

", '

Your book library: browse and download books on the Kindle, reading progress kept in sync.

' } if g.connected then - parts[#parts + 1] = status(true, "Connected as " .. esc(g.username) .. " · " .. esc(g.host)) + parts[#parts + 1] = status(true, (orbit and "Connected to BookOrbit as " or "Connected as ") .. esc(g.username) .. " · " .. esc(g.host)) + if orbit then + parts[#parts + 1] = '

' .. esc(g.bookorbit_note or "") .. "

" + if g.bookorbit_advice then parts[#parts + 1] = '

' .. esc(g.bookorbit_advice) .. "

" end + -- the API key for BookOrbit's audiobooks (never shown back: only whether one is kept) + if g.key_error then parts[#parts + 1] = '

' .. esc(g.key_error) .. "

" end + parts[#parts + 1] = form(base .. "/grimmory/apikey", + '" + .. '' + .. '

From BookOrbit: Settings → You → API keys → Create API key. ' .. esc(g.bookorbit_key_needs or "") + .. " Needed for audiobooks, changing collections and book requests. Leave empty and save to remove it.

" + .. '', "Checking…") + end parts[#parts + 1] = form(base .. "/grimmory/disconnect", - '", "Disconnecting…") - parts[#parts + 1] = "
Sign in again or with another account
" + parts[#parts + 1] = "Sign in again or with another account
" else parts[#parts + 1] = status(false, "Not connected") end if g.error then parts[#parts + 1] = '

' .. esc(g.error) .. "

" end + -- Each server's own way in, in its own block: only the chosen server's block shows and is sent + -- (the other's fields are disabled, so a browser leaves them out). + local function block(server, inner) + local on = picked == server + return '
" .. inner .. "
" + end + local function off(server) return picked == server and "" or " disabled" end + -- Grimmory: user name and password, and single sign-on when the server has it local sso = g.sso local sso_block = "" if sso ~= false then local label = type(sso) == "table" and sso.name and ("Sign in with " .. sso.name) or "Sign in with SSO" sso_block = '" + .. '" type="submit" name="action" value="sso" formnovalidate' .. off("grimmory") .. ">" .. esc(label) .. "" .. '

For single sign-on, your identity provider must allow this redirect address: ' .. esc(g.redirect_uri or "") .. "" .. (g.sso_relay and " (the same for every Kindle; the browser just needs to be on the Kindle's Wi-Fi to finish)" or "") .. "

" end - local pw = input("g_username", "username", "Username", (g.form or {}).username, 'autocomplete="username" ' .. NAME_ATTRS) - .. '' - .. '' - local body + local pw = input("g_username", "username", "Username", (g.form or {}).username, 'autocomplete="username" ' .. NAME_ATTRS .. off("grimmory")) + .. '" + .. '" + local grim if type(sso) == "table" and sso.only then - body = sso_block .. "
Use a local Grimmory password instead" .. pw .. "
" + grim = sso_block .. "
Use a local Grimmory password instead" .. pw .. "
" elseif sso ~= false then - body = pw .. '
or
' .. sso_block + grim = pw .. '
or
' .. sso_block else - body = pw + grim = pw end + -- BookOrbit: an API key alone (it fetches, or makes, the e-reader sign-in), or the KOReader + -- sync user name and password. BookOrbit's e-reader sign-in has no single sign-on. + local bo = '' + .. '" + .. '

The easy way: with the key alone, the Kindle gets your KOReader sync sign-in from BookOrbit (or makes one if you have none) ' + .. "and keeps the key for audiobooks, collections and book requests. Make it in BookOrbit: Settings → You → API keys → Create API key. " + .. esc(g.bookorbit_key_needs or "") .. "

" + .. '" + .. '
or
' + .. "Use the KOReader sync user name and password instead" + .. input("g_ko_username", "username", "KOReader sync user name", (g.form or {}).username, 'autocomplete="username" ' .. NAME_ATTRS .. off("bookorbit")) + .. '" + .. '

From BookOrbit\'s Settings → Devices → KOReader (not your website sign-in). ' .. esc(g.bookorbit_note or "") .. "

" + .. '
" + local which = '" parts[#parts + 1] = form(base .. "/grimmory", - input("g_server", "server", "Grimmory address", (g.form or {}).server, 'required placeholder="https://books.example.com or 192.168.1.20:6060" ' .. URL_ATTRS) - .. body, "Connecting…") + which .. input("g_server", "server", "Server address", (g.form or {}).server, 'required placeholder="https://books.example.com or 192.168.1.20:6060" ' .. URL_ATTRS) + .. block("grimmory", grim) .. block("bookorbit", bo), "Connecting…") + -- choosing a server shows its block, names the heading after it, and switches the other's fields off + parts[#parts + 1] = '" if g.connected then parts[#parts + 1] = "" end parts[#parts + 1] = "
" return table.concat(parts) @@ -631,7 +680,7 @@ function PairPage.hub(st) .. esc(st.flash.text) .. "" end -- one tab at a time (all of them, one under the other, without JavaScript) - local tabs = { { "grimmory", "Grimmory", (st.grimmory or {}).connected }, { "notes", "Notes", (st.memos or {}).connected }, + local tabs = { { "grimmory", "Books", (st.grimmory or {}).connected }, { "notes", "Notes", (st.memos or {}).connected }, { "calendar", "Calendar", (st.caldav or {}).connected or #((st.links or {}).list or {}) > 0 or (st.holidays or {}).enabled } } if st.house then tabs[#tabs + 1] = { "house", "House", st.house.connected } end if st.paper then tabs[#tabs + 1] = { "paper", "Daily paper", st.paper.enabled } end diff --git a/plugins/gzreader.koplugin/gzreader_phone.lua b/plugins/gzreader.koplugin/gzreader_phone.lua index e02ce16ab..3b1ac82bb 100644 --- a/plugins/gzreader.koplugin/gzreader_phone.lua +++ b/plugins/gzreader.koplugin/gzreader_phone.lua @@ -107,14 +107,26 @@ local function state(S, flash) local st = { base = S.base, flash = flash.text and { ok = flash.ok, text = flash.text } or nil } -- Grimmory local store = plugin.store - local g = { connected = plugin.api and plugin.api:isPaired() or false, username = store.username, + local g = { connected = plugin.api and plugin.api:isPaired() or false, username = store.username, backend = plugin:backend(), + bookorbit_note = require("gzreader_bookorbit").note(), + bookorbit_api_key = plugin.api.hasApiKey ~= nil and plugin.api:hasApiKey() or false, + bookorbit_key_needs = require("gzreader_bookorbit").KEY_NEEDS, + -- (a BookOrbit setting that works against the Kindle, said in words) + bookorbit_advice = plugin.api.settingsAdvice ~= nil and plugin.api:settingsAdvice() and plugin:describeError("bookorbit_" .. plugin.api:settingsAdvice()) or nil, host = host(store.server) } g.redirect_uri, g.sso_relay = Phone.ssoRedirect(plugin, S.origin) g.form = sec == "grimmory" and flash.form -- (copied from another GZreader: its address and account, to sign in with) or (not g.connected and type(S.opts.grimmory_form) == "table" and S.opts.grimmory_form) or { server = store.server, username = store.username } - if sec == "grimmory" then g.error = flash.error end + -- (opened for the other book server, from the setup guide: that one picked, its + -- form empty: the saved address and name are this server's) + local hint = type(S.opts.grimmory_form) == "table" and S.opts.grimmory_form.backend + if hint and hint ~= g.backend and not (sec == "grimmory" and flash.form) then + g.form = { backend = hint } + g.other = true + end + if sec == "grimmory" then g.error, g.key_error = flash.error, flash.key_error end -- single sign-on: asked from Grimmory when the form is in view (not -- connected, or a sign-in just tried); otherwise what was learnt before if not g.connected or sec == "grimmory" then @@ -389,7 +401,7 @@ function Phone.open(plugin, opts) if cached ~= nil then return cached end local srv = Api.normalizeServer(server_input) if not srv then return nil end - local base, settings = plugin.api:publicSettings(srv) + local base, settings = plugin:clientFor("grimmory"):publicSettings(srv) if not base or type(settings) ~= "table" then return nil end local info = false if settings.oidcEnabled == true then @@ -403,19 +415,22 @@ function Phone.open(plugin, opts) local function grimmoryOk() S.changes.grimmory = true - toast(T(_("Connected to Grimmory as %1."), plugin.store.username or "?")) - return back({ ok = true, text = T(_("Connected to Grimmory as %1."), plugin.store.username or "?"), section = "grimmory" }) + -- (the server signed in to: Grimmory or BookOrbit) + local said = T(_("Connected to %1 as %2."), plugin:serverName(), plugin.store.username or "?") + toast(said) + return back({ ok = true, text = said, section = "grimmory" }) end local function grimmoryFailed(form, err) if failedLogin() then return 200, "text/html", PairPage.gone() end - return back({ section = "grimmory", error = err, form = { server = form.server, username = form.username } }) + return back({ section = "grimmory", error = err, form = { server = form.server, username = form.username, backend = form.backend } }) end local function startSso(form) local srv = Api.normalizeServer(form.server or "") if not srv then return grimmoryFailed(form, _("Enter your Grimmory address first.")) end - plugin.api.explicit_https = (form.server or ""):match("^%s*https://") ~= nil - local base, settings = plugin.api:publicSettings(srv) + local client = plugin:clientFor("grimmory") -- (single sign-on is Grimmory's) + client.explicit_https = (form.server or ""):match("^%s*https://") ~= nil + local base, settings = client:publicSettings(srv) if not base then return grimmoryFailed(form, plugin:describeError(settings)) end local pd = type(settings.oidcProviderDetails) == "table" and settings.oidcProviderDetails or {} if settings.oidcEnabled ~= true or not Api.str(pd.clientId) or not Api.str(pd.issuerUri) then @@ -455,15 +470,15 @@ function Phone.open(plugin, opts) return 200, "text/html", PairPage.gone() end S.sso = nil -- single use - local previous = { plugin.store.server, plugin.store.username } - local ok, err = plugin.api:oidcExchange(session.base, { + local previous = plugin:signedInAs() + local ok, err = plugin:clientFor("grimmory"):oidcExchange(session.base, { code = params.code, code_verifier = session.verifier, redirect_uri = session.redirect_uri, nonce = session.nonce, state = session.state, }, Phone.originOf(session.redirect_uri)) if ok then Log.info("sso: signed in as", tostring(plugin.store.username), session.relay and "(hand-off page)" or "(this Kindle's address)") if not session.relay then plugin.store.sso_direct_ok = true end - plugin:afterLogin(previous) + plugin:afterLogin(previous, "grimmory") return grimmoryOk() end Log.warn("sso: exchange failed:", tostring(err)) @@ -472,19 +487,40 @@ function Phone.open(plugin, opts) local routes = {} routes["/grimmory"] = function(form) - if form.action == "sso" then return startSso(form) end - local ok, err = plugin:connect(form.server or "", form.username or "", form.password or "") + if form.action == "sso" and form.backend ~= "bookorbit" then return startSso(form) end + if form.action == "sso" and form.backend == "bookorbit" then + return grimmoryFailed(form, T(_("BookOrbit is signed in to with its %1 sync user name and password, not single sign-on."), "KOReader")) + end + local ok, err + if form.action == "apikey" then form.backend = "bookorbit" end + if form.action == "apikey" or form.backend == "bookorbit" and (form.api_key or ""):gsub("%s+", "") ~= "" and (form.password or "") == "" then + -- (BookOrbit with only an API key: the key gets the e-reader sign-in itself) + ok, err = plugin:connectWithApiKey(form.server or "", form.api_key or "") + else + ok, err = plugin:connect(form.server or "", form.username or "", form.password or "", form.backend) + end if ok then return grimmoryOk() end return grimmoryFailed(form, err) end + -- BookOrbit's API key (audiobooks): checked against the server, never echoed back + routes["/grimmory/apikey"] = function(form) + local ok, err = plugin:setBookOrbitApiKey(form.api_key or "") + if ok then + -- said on the page and on the Kindle: accepted (and what the key can do), or removed + local said = plugin:bookOrbitKeyReport() + toast((form.api_key or ""):gsub("%s+", "") == "" and _("The BookOrbit API key was removed.") or _("BookOrbit accepted the API key.")) + return back({ ok = true, text = said, section = "grimmory" }) + end + return back({ section = "grimmory", key_error = err }) + end routes["/grimmory/disconnect"] = function() if plugin.sync then pcall(plugin.sync.onLeave, plugin.sync) end pcall(plugin.api.logout, plugin.api) plugin.api:clearTokens() S.changes.grimmory = true - Log.info("phone: disconnected from Grimmory") - toast(_("Disconnected from Grimmory.")) - return back({ ok = true, text = _("Disconnected from Grimmory. Downloaded books stay on the Kindle."), section = "grimmory" }) + Log.info("phone: disconnected from", plugin:serverName()) + toast(T(_("Disconnected from %1."), plugin:serverName())) + return back({ ok = true, text = T(_("Disconnected from %1. Downloaded books stay on the Kindle."), plugin:serverName()), section = "grimmory" }) end -- Plex: its own sign-in page (a "strong" PIN), then back here local function Music() return require("gzreader_music") end @@ -966,8 +1002,8 @@ function Phone.afterClose(S) local plugin = S.plugin local ch = S.changes if ch.grimmory then - lines[#lines + 1] = plugin.api:isPaired() and T(_("Grimmory: connected as %1."), plugin.store.username or "?") - or _("Grimmory: disconnected.") + lines[#lines + 1] = plugin.api:isPaired() and T(_("%1: connected as %2."), plugin:serverName(), plugin.store.username or "?") + or _("Books: disconnected.") end if ch.notes then local m = plugin.store.memos or {} diff --git a/plugins/gzreader.koplugin/gzreader_ratings.lua b/plugins/gzreader.koplugin/gzreader_ratings.lua index 639cc1f8b..194117d2f 100644 --- a/plugins/gzreader.koplugin/gzreader_ratings.lua +++ b/plugins/gzreader.koplugin/gzreader_ratings.lua @@ -51,6 +51,7 @@ end --- The Kindle's rating changed since it last agreed with Grimmory? Queue it. function Ratings.check(plugin, book_id, entry, doc_settings) if not entry then return false end + if type(plugin.serverCan) == "function" and not plugin:serverCan("ratings") then return false end local here = Ratings.localStars(doc_settings) or 0 local synced = tonumber(entry.rating_synced) if synced == nil then diff --git a/plugins/gzreader.koplugin/gzreader_secrets.lua b/plugins/gzreader.koplugin/gzreader_secrets.lua index a09bf0f31..87631b644 100644 --- a/plugins/gzreader.koplugin/gzreader_secrets.lua +++ b/plugins/gzreader.koplugin/gzreader_secrets.lua @@ -7,7 +7,7 @@ state (settings/gzreader.lua, and gzreader_recent.lua between full saves) held the sign-ins in it: the CalDAV password, the Home Assistant, Memos and Plex tokens, the Immich key, the Access key and Cloudflare token, the handwriting services' keys (Claude, OpenAI-style), Grimmory's -sign-in tokens and the calendar links (their keys are in the address). +sign-in tokens, BookOrbit's sign-in key and the calendar links (their keys are in the address). Those (PATHS, and each calendar link's url) are kept in SECRET_FILE on the Kindle's own disk instead (/var/local: not shared over USB), and every save @@ -35,6 +35,7 @@ local Secrets = { -- { key, key, … } inside the state PATHS = { { "refresh_token" }, { "access_token" }, + { "bookorbit", "key" }, { "bookorbit", "api_key" }, { "caldav", "password" }, { "memos", "token" }, { "plex", "token" }, { "plex", "server", "token" }, diff --git a/plugins/gzreader.koplugin/gzreader_servername.lua b/plugins/gzreader.koplugin/gzreader_servername.lua new file mode 100644 index 000000000..05cbb4476 --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_servername.lua @@ -0,0 +1,38 @@ +--[[-- +The book server's own words, for texts shown on screen. + +GZreader's Catalog was written for Grimmory, and many of its texts say so. +Signed in to BookOrbit they should name BookOrbit, and BookOrbit calls its +shelves collections and its smart shelves SmartScopes. Rather than a second +copy of every text, a text passes through Name.fix on its way to the screen. +]] + +local _ = require("gettext") + +local Name = {} + +--- "bookorbit" or "grimmory": the server this Kindle's books come from. +function Name.server() + local get = rawget(_G, "__GZ_BOOK_SERVER") + local ok, name = pcall(function() return get and get() end) + return ok and name == "bookorbit" and "bookorbit" or "grimmory" +end + +function Name.orbit() return Name.server() == "bookorbit" end + +--- The server's name. +function Name.get() return Name.orbit() and "BookOrbit" or "Grimmory" end + +--- A text that names Grimmory, naming the server signed in to instead. +function Name.fix(text) + if type(text) ~= "string" or not Name.orbit() then return text end + return (text:gsub("Grimmory", "BookOrbit")) +end + +--- What the server calls a list you put books on: Shelves (Grimmory), Collections (BookOrbit). +function Name.shelves() return Name.orbit() and _("Collections") or _("Shelves") end + +--- …and one that fills itself by rules. +function Name.smart() return Name.orbit() and _("SmartScope") or _("smart shelf") end + +return Name diff --git a/plugins/gzreader.koplugin/gzreader_shelves.lua b/plugins/gzreader.koplugin/gzreader_shelves.lua index 7c75c2429..e713fc150 100644 --- a/plugins/gzreader.koplugin/gzreader_shelves.lua +++ b/plugins/gzreader.koplugin/gzreader_shelves.lua @@ -304,9 +304,18 @@ function Shelves.applyDone(plugin, done) return n end +--- Can this book server's shelves be changed from here? Grimmory: yes. BookOrbit (its +--- collections): only with its API key (gzreader_bookorbit.lua's canEditShelves). +local function editable(api) + if type(api) ~= "table" then return false end + if not api.books_only then return true end + return type(api.canEditShelves) == "function" and api:canEditShelves() == true +end +Shelves.editable = editable + local function online(plugin) local api = plugin.api - if type(api) ~= "table" or api.offline or not api:isPaired() then return false end + if type(api) ~= "table" or api.offline or not editable(api) or not api:isPaired() then return false end local ok, NetworkMgr = pcall(require, "ui/network/manager") return ok and NetworkMgr:isConnected() and true or false end @@ -398,10 +407,15 @@ end ---------------------------------------------------------------- the menus +--- (the messages below name Grimmory: with another book server, its name) +local function named(text) + return Shelves.server and Shelves.server ~= "Grimmory" and (text:gsub("Grimmory", Shelves.server)) or text +end + local function info(text, timeout) local UIManager = require("ui/uimanager") local InfoMessage = require("ui/widget/infomessage") - UIManager:show(InfoMessage:new{ text = text, timeout = timeout }) + UIManager:show(InfoMessage:new{ text = named(text), timeout = timeout }) end --- Signed in to Grimmory (a Kindle without Wi-Fi: the sync page left a copy)? @@ -409,6 +423,11 @@ end function Shelves.ready(plugin) local _ = require("gettext") local api = plugin.api + Shelves.server = type(plugin.serverName) == "function" and plugin:serverName() or nil + if type(api) == "table" and api:isPaired() and not editable(api) then + info(_("Changing BookOrbit's collections from here needs its API key: Settings → Accounts and services → Books → BookOrbit API key."), 6) + return false + end if type(api) == "table" and api:isPaired() then return true end if type(api) == "table" and api.offline then info(_("Sign in to Grimmory to continue: plug this Kindle into a computer and sync with the sync page (Settings → General → Transfer → Sync through a computer)."), 6) @@ -429,7 +448,7 @@ local function shelvesThen(plugin, fn) require("gzreader_net").run(function() local UIManager = require("ui/uimanager") local InfoMessage = require("ui/widget/infomessage") - local wait = InfoMessage:new{ text = _("Asking Grimmory about your shelves…") } + local wait = InfoMessage:new{ text = named(_("Asking Grimmory about your shelves…")) } UIManager:show(wait) Shelves.sync(plugin, true, function(ok, err) UIManager:close(wait) diff --git a/plugins/gzreader.koplugin/gzreader_statspage.lua b/plugins/gzreader.koplugin/gzreader_statspage.lua new file mode 100644 index 000000000..2d888eb5f --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_statspage.lua @@ -0,0 +1,464 @@ +--[[-- +The reading stats page: what a tap on Home's reading stats widget opens (also +Catalog → the book server's card → Reading stats). It shows the numbers the +book server keeps for every device (gzreader_grimstats.lua) with charts: + + BookOrbit the last seven days as bars, the past year as a grid of days + (darker = more reading), the year's goal and the next badge as + progress bars, the book of a year ago, this year's finished + books and the day's highlight. + Grimmory the week's books as bars, the month as a calendar of days read, + and books finished by month. + +The charts are GZreader's own drawings from the numbers (Page.sections decides +what is shown; the painters below draw it): grey on grey screens, in colour on +colour ones. Nothing here is taken from BookOrbit's or Grimmory's programs. + +A tap or any key closes it. +]] + +local _ = require("gettext") +local T = require("ffi/util").template + +local Page = {} + +--- A length of time in words: "2 h 5 min", "45 min". +function Page.time(seconds) + local mins = math.floor((tonumber(seconds) or 0) / 60 + 0.5) + if mins < 60 then return T(_("%1 min"), mins) end + local h, m = math.floor(mins / 60), mins % 60 + return m == 0 and T(_("%1 h"), h) or T(_("%1 h %2 min"), h, m) +end + +--- How dark a day is drawn: 0 (nothing read) to 4 (an hour or more). +function Page.level(minutes) + minutes = tonumber(minutes) or 0 + if minutes <= 0 then return 0 end + if minutes < 15 then return 1 end + if minutes < 30 then return 2 end + if minutes < 60 then return 3 end + return 4 +end + +local function dayTime(key, add) + local y, m, d = tostring(key):match("^(%d+)%-(%d+)%-(%d+)") + if not y then return nil end + return os.time{ year = tonumber(y), month = tonumber(m), day = tonumber(d) + (add or 0), hour = 12 } +end + +local WEEKDAYS = { _("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"), _("Sun") } +local MONTHS = { _("Jan"), _("Feb"), _("Mar"), _("Apr"), _("May"), _("Jun"), _("Jul"), _("Aug"), _("Sep"), _("Oct"), _("Nov"), _("Dec") } + +--- The last seven days of BookOrbit's days, oldest first: { { label, minutes, today }… }. +function Page.lastWeek(days) + local mins = type(days) == "table" and type(days.minutes) == "table" and days.minutes or {} + local out = {} + for back = 6, 0, -1 do + local i = #mins - back + local t = dayTime(days and days.start, i - 1) + if i >= 1 and t then + local wday = (os.date("*t", t).wday + 5) % 7 + 1 -- Monday 1 … Sunday 7 + out[#out + 1] = { label = WEEKDAYS[wday], minutes = mins[i], today = back == 0 or nil } + end + end + return out +end + +--- BookOrbit's days as a grid: columns are weeks (oldest first), rows Monday to Sunday. +--- { cols = { { level or false ×7 }… }, months = { [col] = label } } (false: no such day). +function Page.yearGrid(days, max_cols) + local mins = type(days) == "table" and type(days.minutes) == "table" and days.minutes or {} + local first = dayTime(days and days.start, 0) + if not first or #mins == 0 then return { cols = {}, months = {} } end + local lead = (os.date("*t", first).wday + 5) % 7 -- days of the first week before the first day + local n_cols = math.ceil((lead + #mins) / 7) + local skip = math.max(0, n_cols - (max_cols or n_cols)) -- (a narrow screen: the newest weeks) + local cols, months = {}, {} + local last_month + for c = skip + 1, n_cols do + local col = {} + for r = 1, 7 do + local i = (c - 1) * 7 + r - lead + col[r] = i >= 1 and i <= #mins and Page.level(mins[i]) + end + cols[#cols + 1] = col + -- (a month's name over the week its first Monday-row day falls in) + local i = math.max(1, (c - 1) * 7 + 1 - lead) + local m = os.date("*t", dayTime(days.start, i - 1)).month + if m ~= last_month then + if last_month then months[#cols] = MONTHS[m] end + last_month = m + end + end + return { cols = cols, months = months } +end + +--- Grimmory's month as a calendar: rows are weeks, Monday first. +--- { rows = { { { day, count } or false ×7 }… }, max = most sessions in a day }. +function Page.monthGrid(year, month, month_days) + local first = os.time{ year = year, month = month, day = 1, hour = 12 } + local n_days = os.date("*t", os.time{ year = year, month = month + 1, day = 0, hour = 12 }).day + local lead = (os.date("*t", first).wday + 5) % 7 + local count, max = {}, 0 + for _i, r in ipairs(type(month_days) == "table" and month_days or {}) do + count[r.day] = r.count + max = math.max(max, tonumber(r.count) or 0) + end + local rows = {} + for cell = 1, math.ceil((lead + n_days) / 7) * 7 do + local row = math.ceil(cell / 7) + rows[row] = rows[row] or {} + local day = cell - lead + rows[row][(cell - 1) % 7 + 1] = day >= 1 and day <= n_days and { day = day, count = count[day] or 0 } or false + end + return { rows = rows, max = max } +end + +local function bookText(b) + if type(b) ~= "table" then return nil end + return b.author and T(_("%1, by %2"), b.title, b.author) or b.title +end + +--- What the page shows, top to bottom, from GS.all(plugin): a list of sections +--- { kind, title, … }. Kinds: "numbers", "bars", "year", "month", "progress", "text". +function Page.sections(stats) + stats = type(stats) == "table" and stats or {} + local v, d = stats.values or {}, stats.detail or {} + local out = {} + local function num(x) return x ~= nil and tostring(x) or "—" end + out[#out + 1] = { kind = "numbers", items = { + { value = num(v.streak), label = _("Day streak") }, + { value = v.week_time and Page.time(v.week_time) or "—", label = _("Read this week") }, + { value = num(v.year_finished), label = _("Finished this year") }, + } } + if stats.server == "bookorbit" then + local week = Page.lastWeek(d.days) + if #week > 0 then + local bars = {} + for i, w in ipairs(week) do bars[i] = { label = w.label, value = w.minutes, mark = w.today, text = w.minutes > 0 and tostring(w.minutes) or "" } end + out[#out + 1] = { kind = "bars", title = _("The last seven days (minutes)"), bars = bars } + end + if d.days and #(d.days.minutes or {}) > 7 then + local mins, read, total = d.days.minutes, 0, 0 + for _i, m in ipairs(mins) do + if m > 0 then read = read + 1 end + total = total + m + end + out[#out + 1] = { kind = "year", title = T(_("The past year: %1 on %2 days"), Page.time(total * 60), read), days = d.days } + end + if d.goal then + out[#out + 1] = { kind = "progress", title = d.goal.year and T(_("Reading goal for %1"), d.goal.year) or _("Reading goal"), + done = d.goal.done, of = d.goal.books, text = T(_("%1 of %2 books"), d.goal.done, d.goal.books) } + end + if d.badges then + local line = T(_("Badges: %1 of %2"), d.badges.earned, d.badges.total) + local nb = d.badges.next + if nb and nb.threshold and nb.threshold > 0 then + out[#out + 1] = { kind = "progress", title = T(_("%1. Next: %2"), line, nb.name), done = math.min(nb.progress or 0, nb.threshold), of = nb.threshold, + text = T(_("%1 of %2"), nb.progress or 0, nb.threshold), note = nb.about } + else + out[#out + 1] = { kind = "text", title = line, text = d.badges.latest and T(_("Latest: %1"), d.badges.latest.name) or nil } + end + end + if d.year_ago then + out[#out + 1] = { kind = "text", title = _("A year ago you were reading"), + text = T(_("%1 (%2 over %3 days)"), bookText(d.year_ago), Page.time(d.year_ago.minutes * 60), d.year_ago.days) } + end + if d.finished and #d.finished > 0 then + local lines = {} + for i, b in ipairs(d.finished) do lines[i] = "• " .. bookText(b) end + local more = (tonumber(d.finished_count) or #lines) - #lines + if more > 0 then lines[#lines + 1] = T(_("… and %1 more"), more) end + out[#out + 1] = { kind = "text", title = _("Finished this year"), text = table.concat(lines, "\n"), shrink = true } + end + if d.highlight then + local from = d.highlight.book and (d.highlight.chapter and T(_("%1, %2"), d.highlight.book, d.highlight.chapter) or d.highlight.book) or nil + out[#out + 1] = { kind = "text", title = _("Highlight of the day"), text = "“" .. d.highlight.text .. "”" .. (from and ("\n— " .. from) or ""), shrink = true } + end + local extra = {} + if v.longest_streak then extra[#extra + 1] = T(_("Longest streak: %1 days"), v.longest_streak) end + if v.library_books then extra[#extra + 1] = T(_("Books in the library: %1"), v.library_books) end + if v.reading_now then extra[#extra + 1] = T(_("Reading now: %1"), v.reading_now) end + if #extra > 0 then out[#out + 1] = { kind = "text", text = table.concat(extra, " · ") } end + else + if d.week_books and #d.week_books > 0 then + local bars = {} + for i, b in ipairs(d.week_books) do bars[i] = { label = b.title, value = b.seconds, text = Page.time(b.seconds) } end + out[#out + 1] = { kind = "bars", title = _("This week's books"), bars = bars, sideways = true } + end + if d.month_days and d.year and d.month then + out[#out + 1] = { kind = "month", title = T(_("%1: reading sessions by day"), MONTHS[d.month] .. " " .. d.year), + grid = Page.monthGrid(d.year, d.month, d.month_days) } + end + if d.finished_months and #d.finished_months > 0 then + local by = {} + for _i, m in ipairs(d.finished_months) do by[m.month] = m.finished end + local bars = {} + for m = 1, 12 do bars[m] = { label = MONTHS[m]:sub(1, 1), value = by[m] or 0, text = (by[m] or 0) > 0 and tostring(by[m]) or "", mark = m == d.month or nil } end + out[#out + 1] = { kind = "bars", title = d.year and T(_("Books finished in %1, by month"), d.year) or _("Books finished by month"), bars = bars } + end + local extra = {} + if v.longest_streak then extra[#extra + 1] = T(_("Longest streak: %1 days"), v.longest_streak) end + if v.reading_days then extra[#extra + 1] = T(_("Days read: %1"), v.reading_days) end + if v.month_sessions then extra[#extra + 1] = T(_("Sessions this month: %1"), v.month_sessions) end + if #extra > 0 then out[#out + 1] = { kind = "text", text = table.concat(extra, " · ") } end + end + return out +end + +--- The line under the page: where the numbers are from and how old. +function Page.footer(stats, now) + stats = type(stats) == "table" and stats or {} + local name = stats.name or "Grimmory" + local how = require("device"):isTouchDevice() and _("Tap to close.") or _("Press any key to close.") + if not stats.at or stats.at <= 0 then + return T(_("Nothing from %1 yet: the numbers come when Wi-Fi is on."), name) .. " " .. how + end + local age = math.max(0, (now or os.time()) - stats.at) + local when = age < 120 and _("just now") or age < 5400 and T(_("%1 minutes ago"), math.floor(age / 60)) + or age < 172800 and T(_("%1 hours ago"), math.floor(age / 3600)) or T(_("%1 days ago"), math.floor(age / 86400)) + return T(_("Every device's reading, from %1, as of %2."), name, when) .. " " .. how +end + +---------------------------------------------------------------- drawing + +-- The five shades of a day (nothing … an hour or more): grey levels, and greens on a colour screen. +local GREY = { 0.08, 0.3, 0.5, 0.72, 1 } +local GREEN = { { 0xE6, 0xEC, 0xE6 }, { 0xB7, 0xE0, 0xA8 }, { 0x74, 0xC4, 0x76 }, { 0x31, 0x9B, 0x54 }, { 0x0B, 0x6B, 0x35 } } +local ACCENT = { 0x1F, 0x6F, 0xB5 } -- (bars and progress on a colour screen) + +local function painter() + local Blitbuffer = require("ffi/blitbuffer") + local ok, colour = pcall(function() return require("gzreader_colour").enabled() end) + colour = ok and colour == true + local P = { colour = colour } + function P.rect(bb, x, y, w, h, rgb, grey) + if w <= 0 or h <= 0 then return end + if colour and rgb and bb.paintRectRGB32 then + bb:paintRectRGB32(x, y, w, h, Blitbuffer.ColorRGB32(rgb[1], rgb[2], rgb[3], 0xFF)) + else + bb:paintRect(x, y, w, h, Blitbuffer.gray(grey)) + end + end + function P.shade(bb, x, y, w, h, level) P.rect(bb, x, y, w, h, GREEN[level + 1], GREY[level + 1]) end + function P.accent(bb, x, y, w, h, strong) P.rect(bb, x, y, w, h, ACCENT, strong and 1 or 0.6) end + function P.frame(bb, x, y, w, h) + bb:paintRect(x, y, w, 1, Blitbuffer.COLOR_DARK_GRAY); bb:paintRect(x, y + h - 1, w, 1, Blitbuffer.COLOR_DARK_GRAY) + bb:paintRect(x, y, 1, h, Blitbuffer.COLOR_DARK_GRAY); bb:paintRect(x + w - 1, y, 1, h, Blitbuffer.COLOR_DARK_GRAY) + end + return P +end + +--- The page itself. `plugin`: GZreader's; `stats`: GS.all's (read fresh when nil). +function Page.show(plugin, stats) + local Blitbuffer = require("ffi/blitbuffer") + local CenterContainer = require("ui/widget/container/centercontainer") + local Device = require("device") + local Font = require("ui/font") + local FrameContainer = require("ui/widget/container/framecontainer") + local Geom = require("ui/geometry") + local GestureRange = require("ui/gesturerange") + local InputContainer = require("ui/widget/container/inputcontainer") + local TextBoxWidget = require("ui/widget/textboxwidget") + local TextWidget = require("ui/widget/textwidget") + local UIManager = require("ui/uimanager") + local VerticalGroup = require("ui/widget/verticalgroup") + local VerticalSpan = require("ui/widget/verticalspan") + local Widget = require("ui/widget/widget") + local Screen = Device.screen + + stats = stats or require("gzreader_grimstats").all(plugin) + local sw, sh = Screen:getWidth(), Screen:getHeight() + local pad = Screen:scaleBySize(18) + local W = sw - pad * 2 + local P = painter() + local small = Font:getFace("smallinfofont", 14) + local body = Font:getFace("smallinfofont", 16) + local head = Font:getFace("smallinfofont", 17) + + local Canvas = Widget:extend{ w = 0, h = 0, draw = nil } + function Canvas:getSize() return Geom:new{ w = self.w, h = self.h } end + function Canvas:paintTo(bb, x, y) + self.dimen = Geom:new{ x = x, y = y, w = self.w, h = self.h } + self.draw(bb, x, y, self.w, self.h) + end + local function label(bb, text, face, x, y, max_w, centre, bold, white) + if not text or text == "" then return 0 end + local tw = TextWidget:new{ text = text, face = face, bold = bold, max_width = max_w, fgcolor = white and Blitbuffer.COLOR_WHITE or nil } + local size = tw:getSize() + tw:paintTo(bb, centre and (x + math.floor((max_w - size.w) / 2)) or x, y) + tw:free() + return size.w + end + local line_h = TextWidget:new{ text = "Ag", face = small }:getSize().h + + local function numbers(sec) + local big = Font:getFace("tfont", 30) + local big_h = TextWidget:new{ text = "8", face = big }:getSize().h + return Canvas:new{ w = W, h = big_h + line_h + Screen:scaleBySize(6), draw = function(bb, x, y, w) + local cell = math.floor(w / #sec.items) + for i, it in ipairs(sec.items) do + local cx = x + (i - 1) * cell + label(bb, it.value, big, cx, y, cell, true, true) + label(bb, it.label, small, cx, y + big_h + Screen:scaleBySize(2), cell, true) + if i > 1 then bb:paintRect(cx, y + Screen:scaleBySize(6), 1, big_h + line_h - Screen:scaleBySize(8), Blitbuffer.COLOR_GRAY) end + end + end } + end + + local function bars(sec) + local max = 0 + for _i, b in ipairs(sec.bars) do max = math.max(max, tonumber(b.value) or 0) end + if sec.sideways then -- one row per bar: name, bar, amount + local row_h = line_h + Screen:scaleBySize(6) + local name_w, amount_w = math.floor(W * 0.42), math.floor(W * 0.2) + return Canvas:new{ w = W, h = row_h * #sec.bars, draw = function(bb, x, y, w) + local room = w - name_w - amount_w - Screen:scaleBySize(12) + for i, b in ipairs(sec.bars) do + local ry = y + (i - 1) * row_h + label(bb, b.label, small, x, ry, name_w - Screen:scaleBySize(6)) + local bw = max > 0 and math.max(2, math.floor(room * b.value / max)) or 0 + P.accent(bb, x + name_w, ry + Screen:scaleBySize(3), bw, row_h - Screen:scaleBySize(8), i == 1) + label(bb, b.text, small, x + name_w + bw + Screen:scaleBySize(6), ry, amount_w + room - bw) + end + end } + end + local chart_h = Screen:scaleBySize(70) + return Canvas:new{ w = W, h = chart_h + line_h * 2 + Screen:scaleBySize(4), draw = function(bb, x, y, w) + local n = #sec.bars + local cell = math.floor(w / n) + local bar_w = math.max(4, math.floor(cell * 0.56)) + local base = y + line_h + chart_h + bb:paintRect(x, base, cell * n, 1, Blitbuffer.COLOR_DARK_GRAY) + for i, b in ipairs(sec.bars) do + local cx = x + (i - 1) * cell + local bh = max > 0 and b.value > 0 and math.max(3, math.floor(chart_h * b.value / max)) or 0 + P.accent(bb, cx + math.floor((cell - bar_w) / 2), base - bh, bar_w, bh, b.mark) + label(bb, b.text, small, cx, base - bh - line_h, cell, true) + label(bb, b.label, small, cx, base + Screen:scaleBySize(3), cell, true, b.mark) + end + end } + end + + local function year(sec) + local gap = math.max(1, Screen:scaleBySize(1)) + local side = math.max(4, math.min(Screen:scaleBySize(14), math.floor((W + gap) / 53) - gap)) + local grid = Page.yearGrid(sec.days, math.floor((W + gap) / (side + gap))) + local gw = #grid.cols * (side + gap) - gap + return Canvas:new{ w = W, h = line_h + 7 * (side + gap) + Screen:scaleBySize(4) + line_h, draw = function(bb, x, y, w) + local gx = x + math.floor((w - gw) / 2) + local next_free = 0 -- (month names never run into each other) + for c, col in ipairs(grid.cols) do + local cx = gx + (c - 1) * (side + gap) + if grid.months[c] and cx >= next_free then + next_free = cx + label(bb, grid.months[c], small, cx, y, w) + Screen:scaleBySize(6) + end + for r = 1, 7 do + if col[r] then P.shade(bb, cx, y + line_h + (r - 1) * (side + gap), side, side, col[r]) end + end + end + -- what the shades mean + local ky = y + line_h + 7 * (side + gap) + Screen:scaleBySize(4) + local kx = gx + label(bb, _("Less"), small, gx, ky, w) + Screen:scaleBySize(6) + local ks = math.min(side, line_h - 4) + for level = 0, 4 do + P.shade(bb, kx, ky + math.floor((line_h - ks) / 2), ks, ks, level) + kx = kx + ks + gap + 1 + end + label(bb, _("More"), small, kx + Screen:scaleBySize(5), ky, w) + end } + end + + local function month(sec) + local rows = sec.grid.rows + local cell_w, cell_h = math.floor(W / 7), line_h + Screen:scaleBySize(8) + return Canvas:new{ w = W, h = line_h + #rows * cell_h, draw = function(bb, x, y) + for c = 1, 7 do label(bb, WEEKDAYS[c], small, x + (c - 1) * cell_w, y, cell_w, true) end + for r, row in ipairs(rows) do + for c = 1, 7 do + local cell = row[c] + if cell then + local cx, cy = x + (c - 1) * cell_w + 1, y + line_h + (r - 1) * cell_h + 1 + -- (one session light, more darker, the month's busiest day darkest; day numbers stay readable) + local level = cell.count <= 0 and 0 or math.min(3, math.max(1, math.ceil(3 * cell.count / math.max(1, sec.grid.max)))) + P.shade(bb, cx, cy, cell_w - 2, cell_h - 2, level) + label(bb, tostring(cell.day), small, cx, cy + Screen:scaleBySize(3), cell_w - 2, true, cell.count > 0, level >= 3) + end + end + end + end } + end + + local function progress(sec) + local bar_h = Screen:scaleBySize(14) + return Canvas:new{ w = W, h = bar_h + Screen:scaleBySize(2), draw = function(bb, x, y, w) + local text_w = math.floor(w * 0.3) + local bw = w - text_w + P.frame(bb, x, y, bw, bar_h) + local fill = sec.of > 0 and math.floor((bw - 4) * math.min(1, sec.done / sec.of)) or 0 + P.accent(bb, x + 2, y + 2, fill, bar_h - 4, true) + label(bb, sec.text, small, x + bw + Screen:scaleBySize(8), y + math.floor((bar_h - line_h) / 2), text_w - Screen:scaleBySize(8)) + end } + end + + -- Sections go on while they fit: the footer always shows. + local footer = TextBoxWidget:new{ text = Page.footer(stats), face = small, width = W, alignment = "center" } + local title = TextWidget:new{ text = T(_("Reading stats · %1"), stats.name or "Grimmory"), face = Font:getFace("tfont", 22), bold = true, max_width = W } + local span = Screen:scaleBySize(10) + local group = VerticalGroup:new{ align = "left", title, VerticalSpan:new{ width = span } } + local room = sh - pad * 2 - title:getSize().h - span - footer:getSize().h - span + local shown = 0 + for _i, sec in ipairs(Page.sections(stats)) do + local parts = {} + if sec.title then parts[#parts + 1] = TextWidget:new{ text = sec.title, face = head, bold = true, max_width = W } end + local chart = sec.kind == "numbers" and numbers(sec) or sec.kind == "bars" and bars(sec) or sec.kind == "year" and year(sec) + or sec.kind == "month" and month(sec) or sec.kind == "progress" and progress(sec) or nil + if chart then parts[#parts + 1] = chart end + local words = sec.kind == "text" and sec.text or sec.note + local used = span + for _j, p in ipairs(parts) do used = used + p:getSize().h end + if words then + local box = TextBoxWidget:new{ text = words, face = sec.kind == "text" and body or small, width = W } + if sec.shrink and used + box:getSize().h > room and room - used >= line_h * 2 then + -- (a long list or highlight: as many lines as there is room for) + box:free() + box = TextBoxWidget:new{ text = words, face = body, width = W, height = room - used, height_adjust = true, height_overflow_show_ellipsis = true } + end + parts[#parts + 1] = box + used = used + box:getSize().h + end + if used <= room then + for _j, p in ipairs(parts) do group[#group + 1] = p end + group[#group + 1] = VerticalSpan:new{ width = span } + room = room - used + shown = shown + 1 + else + for _j, p in ipairs(parts) do if p.free then p:free() end end + end + end + if room > 0 then group[#group + 1] = VerticalSpan:new{ width = room } end + group[#group + 1] = footer + + local StatsPage = InputContainer:extend{ name = "reading stats page", modal = true } + local page = StatsPage:new{ dimen = Geom:new{ x = 0, y = 0, w = sw, h = sh } } + if Device:hasKeys() then page.key_events = { AnyKeyPressed = { { Device.input.group.Any } } } end + if Device:isTouchDevice() then + page.ges_events = { TapClose = { GestureRange:new{ ges = "tap", range = page.dimen } } } + end + local function close() + UIManager:close(page) + return true + end + page.onAnyKeyPressed, page.onTapClose, page.onClose = close, close, close + function page:onShow() UIManager:setDirty(self, function() return "full", self.dimen end) end + function page:onCloseWidget() UIManager:setDirty(nil, "full") end + page[1] = FrameContainer:new{ background = Blitbuffer.COLOR_WHITE, bordersize = 0, padding = 0, width = sw, height = sh, + CenterContainer:new{ dimen = Geom:new{ w = sw, h = sh }, group } } + page.sections_shown = shown + Page.current = page + UIManager:show(page) + require("gzreader_log").info("reading stats page:", stats.name or "?", shown, "sections shown") + return page +end + +return Page diff --git a/plugins/gzreader.koplugin/gzreader_storage.lua b/plugins/gzreader.koplugin/gzreader_storage.lua index 6fbdec4bc..c36695145 100644 --- a/plugins/gzreader.koplugin/gzreader_storage.lua +++ b/plugins/gzreader.koplugin/gzreader_storage.lua @@ -200,7 +200,7 @@ function Storage.measure(plugin) out.notes = Storage.notes(data_dir, settings_dir) out.calendar = { bytes = fileSize(settings_dir .. "/gzreader-calendar.json") } local caches = fileSize(settings_dir .. "/gzreader_index.json") + fileSize(settings_dir .. "/bookinfo_cache.sqlite3") - for _i, d in ipairs({ "gzreader-thumbs", "gzreader-lists", "gzreader-covers", "gz-covers", "gzreader-update" }) do + for _i, d in ipairs({ "gzreader-thumbs", "gzreader-lists", "gzreader-covers", "gzreader-covers-bookorbit", "gz-covers", "gzreader-update" }) do caches = caches + (Storage.dirSize(data_dir .. "/cache/" .. d)) end out.caches = { bytes = caches } diff --git a/plugins/gzreader.koplugin/gzreader_sync.lua b/plugins/gzreader.koplugin/gzreader_sync.lua index 44355216a..b24ecad95 100644 --- a/plugins/gzreader.koplugin/gzreader_sync.lua +++ b/plugins/gzreader.koplugin/gzreader_sync.lua @@ -226,6 +226,8 @@ end --- The position sent to Grimmory: the local one, 100% on the last page. function Sync:sentPosition() local p = self:localPosition() + -- (BookOrbit takes KOReader's own percentage, the footer's; Grimmory the web reader's) + if self.api.koreader_positions and p.local_pct then p.pct = p.local_pct end if p.pct < 100 and self:atEnd() then p.pct = 100 end return p end @@ -425,7 +427,7 @@ end function Sync:canTalk() -- (syncing through a computer: the library copy has the other devices' places) - return self.api:isPaired() and (NetworkMgr:isConnected() or self.api.offline == true) + return self.api:isPaired() and self.plugin:serverCan("progress") and (NetworkMgr:isConnected() or self.api.offline == true) end --- Grimmory's progress fields of a book (what a download keeps for the @@ -487,15 +489,20 @@ function Sync:applyRemote(book, interactive, err) if interactive then self.plugin:showError(err) end return end - pcall(function() - require("gzreader_ratings").reconcile(self.plugin, self.book_id, self.entry, self.ui.doc_settings, book) - end) + if self.plugin:serverCan("ratings") then + pcall(function() + require("gzreader_ratings").reconcile(self.plugin, self.book_id, self.entry, self.ui.doc_settings, book) + end) + end -- which of your Grimmory shelves it's on (kept on the Kindle: gzreader_shelves.lua) - pcall(function() require("gzreader_shelves").remember(self.plugin, self.book_id, book) end) + if not self.api.books_only then + pcall(function() require("gzreader_shelves").remember(self.plugin, self.book_id, book) end) + end + local server = self.plugin:serverName() local remote = self:remotePosition(book) local here = self:localPosition() if not remote or remote.pct <= 0 then - if interactive then UIManager:show(InfoMessage:new{ text = _("No reading progress on Grimmory yet."), timeout = 3 }) end + if interactive then UIManager:show(InfoMessage:new{ text = T(_("No reading progress on %1 yet."), server), timeout = 3 }) end return end -- compare on KOReader's scale: where the remote place is in this book @@ -518,7 +525,7 @@ function Sync:applyRemote(book, interactive, err) Log.info("sync pull book", self.book_id, "remote", remote.pct .. "%", "(here " .. remote_local .. "%" .. (exact and ", from its CFI)" or ")"), remote.href or remote.cfi or "", "local", here.pct .. "%") if math.abs(diff) < SAME_POSITION_PCT then - if interactive then UIManager:show(InfoMessage:new{ text = _("Already in sync with Grimmory."), timeout = 2 }) end + if interactive then UIManager:show(InfoMessage:new{ text = T(_("Already in sync with %1."), server), timeout = 2 }) end return end local last = num(self.entry.last_pushed_pct) @@ -528,11 +535,11 @@ function Sync:applyRemote(book, interactive, err) self:jumpTo(remote) self.entry.last_pushed_pct = remote.pct -- now in agreement self.plugin:save() - UIManager:show(InfoMessage:new{ text = T(_("Jumped to %1% from Grimmory."), round1(remote_local)), timeout = 2 }) + UIManager:show(InfoMessage:new{ text = T(_("Jumped to %1% from %2."), round1(remote_local), server), timeout = 2 }) elseif diff < 0 and (not is_our_echo or interactive) then UIManager:show(ConfirmBox:new{ - text = T(_("Grimmory has an earlier position (%1%) than this Kindle (%2%), probably from another device. Go back to it?"), - round1(remote_local), round1(here.pct)), + text = T(_("%3 has an earlier position (%1%) than this Kindle (%2%), probably from another device. Go back to it?"), + round1(remote_local), round1(here.pct), server), ok_text = _("Go back"), cancel_text = _("Stay here"), ok_callback = function() @@ -571,7 +578,9 @@ function Sync:push(force, _background) return end local body = self:progressBody(p) - if p.xp and p.href and self:isEpub() then + if self.api.koreader_positions then + body.gz_xp = p.xp -- (BookOrbit takes the XPointer as it is) + elseif p.xp and p.href and self:isEpub() then body.gz_xp = p.xp -- turned into the CFI in the background (gz_* fields aren't sent) body.gz_file = self.ui.document.file end diff --git a/plugins/gzreader.koplugin/gzreader_zipread.lua b/plugins/gzreader.koplugin/gzreader_zipread.lua new file mode 100644 index 000000000..545c95cbb --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_zipread.lua @@ -0,0 +1,62 @@ +--[[-- +One small file out of a zip held in memory. + +For BookOrbit's "preconfigured plugin" download (gzreader_bookorbit.lua's +loginWithApiKey): the only way its API hands a device the KOReader sync key. +Reads the zip's directory at its end, then the one entry (stored or deflated; +zlib through gzreader_gzip.lua). Nothing is written to disk and nothing in +the zip is run. +]] + +local Zip = {} + +Zip.MAX = 256 * 1024 -- (the most one entry may unpack to) + +local function u16(s, i) local a, b = s:byte(i, i + 1); return a and b and (a + b * 256) or nil end +local function u32(s, i) + local a, b, c, d = s:byte(i, i + 3) + return a and d and (a + b * 256 + c * 65536 + d * 16777216) or nil +end + +--- The contents of the entry whose name is `name` or ends in "/" .. name; nil, err otherwise. +function Zip.read(data, name) + if type(data) ~= "string" or #data < 22 then return nil, "not a zip" end + -- the end record: in the last 64 KB (it may be followed by a comment) + local eocd + local from = math.max(1, #data - 65557) + local at = from + while true do + local i = data:find("PK\5\6", at, true) + if not i then break end + eocd, at = i, i + 1 + end + if not eocd then return nil, "not a zip" end + local count, dir_at = u16(data, eocd + 10), u32(data, eocd + 16) + if not count or not dir_at then return nil, "not a zip" end + local p = dir_at + 1 + for _i = 1, count do + if data:sub(p, p + 3) ~= "PK\1\2" then return nil, "bad zip directory" end + local method, csize, usize = u16(data, p + 10), u32(data, p + 20), u32(data, p + 24) + local nlen, xlen, clen, local_at = u16(data, p + 28), u16(data, p + 30), u16(data, p + 32), u32(data, p + 42) + if not (method and csize and usize and nlen and xlen and clen and local_at) then return nil, "bad zip directory" end + local entry = data:sub(p + 46, p + 45 + nlen) + if entry == name or entry:sub(-#name - 1) == "/" .. name then + if usize > Zip.MAX or csize > Zip.MAX then return nil, "too big" end + local l = local_at + 1 + if data:sub(l, l + 3) ~= "PK\3\4" then return nil, "bad zip entry" end + local ln, lx = u16(data, l + 26), u16(data, l + 28) + if not ln or not lx then return nil, "bad zip entry" end + local body = data:sub(l + 30 + ln + lx, l + 29 + ln + lx + csize) + if #body ~= csize then return nil, "bad zip entry" end + if method == 0 then return body end + if method ~= 8 then return nil, "unsupported compression" end + local out, err = require("gzreader_gzip").inflateRaw(body, Zip.MAX) + if not out then return nil, err end + return out + end + p = p + 46 + nlen + xlen + clen + end + return nil, "not in the zip" +end + +return Zip diff --git a/plugins/gzreader.koplugin/main.lua b/plugins/gzreader.koplugin/main.lua index 892f12662..404e07a8b 100644 --- a/plugins/gzreader.koplugin/main.lua +++ b/plugins/gzreader.koplugin/main.lua @@ -46,7 +46,6 @@ local Log = require("gzreader_log") require("socketutil") local Index = require("gzreader_index") local JSON = require("gzreader_json") -local Bookmarks = require("gzreader_bookmarks") local PAIR_TIMEOUT_S = 10 * 60 local MAX_QUEUED_SESSIONS = 200 @@ -194,6 +193,7 @@ function Grimmory:init() self.store.pending.ratings = self.store.pending.ratings or {} Log.enabled = self.store.logging_disabled ~= true self.api = Api:new(self.store, function() self:save() end) + if self.store.backend == "bookorbit" then self:useBackend("bookorbit") end -- no Wi-Fi (Kindle 2, DX): Grimmory through a computer, the library -- from the copy the sync page left (gzreader_usbsync.lua) local Usb = require("gzreader_usbsync") @@ -255,6 +255,9 @@ function Grimmory:init() -- Home's "Grimmory reading stats" (every device's reading, from Grimmory) local plugin_ref = self rawset(_G, "__GZ_GRIMMORY_STATS", function() return require("gzreader_grimstats").values(plugin_ref) end) + -- (which server they're from, for the widget's choices; and the page a tap on it opens) + rawset(_G, "__GZ_BOOK_SERVER", function() return plugin_ref:backend() end) + rawset(_G, "__GZ_SERVER_STATS_PAGE", function() return require("gzreader_statspage").show(plugin_ref) end) -- Downloads and the other book folders as bookshelves (the View) -- (after every plugin has patched the file browser) UIManager:nextTick(function() pcall(function() @@ -488,7 +491,7 @@ do end function Grimmory:syncEnabled() - return self.store.sync_disabled ~= true and self.api:isPaired() + return self.store.sync_disabled ~= true and self.api:isPaired() and self:serverCan("progress") end -- exit: the next save is a whole one, and there is one if only the recent part @@ -577,6 +580,7 @@ function Grimmory:menuItems() { text_func = function() if self.api:isPaired() then + if self:backend() == "bookorbit" then return T(_("Connected to BookOrbit as %1"), self.store.username or "?") end return T(_("Connected as %1"), self.store.username or "?") end return _("Not connected") @@ -628,7 +632,7 @@ function Grimmory:menuItems() }, { text = _("Rebuild library"), - help_text = _("Loads the list of your books from Grimmory again (what Authors, Series and searching use) and forgets the saved lists, so books removed from Grimmory disappear here and new ones show. The same as Refresh list from Grimmory in Authors or Series; it's also done by itself once a day."), + help_text = require("gzreader_servername").fix(_("Loads the list of your books from Grimmory again (what Authors, Series and searching use) and forgets the saved lists, so books removed from Grimmory disappear here and new ones show. The same as Refresh list from Grimmory in Authors or Series; it's also done by itself once a day.")), enabled_func = function() return self.api:isPaired() end, keep_menu_open = true, callback = function() self:rebuildLibrary() end, @@ -643,6 +647,23 @@ function Grimmory:menuItems() text = _("Connect by typing"), callback = function() self:keyboardLogin() end, }, + { + text_func = function() + return self.api.hasApiKey and self.api:hasApiKey() and _("BookOrbit API key: set") or _("BookOrbit API key") + end, + enabled_func = function() return self:backend() == "bookorbit" and self.api:isPaired() end, + help_text = _("BookOrbit's audiobooks (listing, downloading, and where you stopped listening), changing collections and requesting books need an API key as well as the sign-in. Make one in BookOrbit: Settings → You → API keys. Access: Read and write. Extra permissions: “KOReader sync” (to sign in with the key) and “Request books” (to request books); nothing else, and not Administrator access. Leave the box empty to remove the key."), + keep_menu_open = true, + callback = function(touchmenu) self:askBookOrbitApiKey(touchmenu) end, + }, + { + text = _("Connect to BookOrbit by typing"), + help_text_func = function() + return T(_("BookOrbit instead of Grimmory as this Kindle's book server. It asks for BookOrbit's address and the %1 sync user name and password (BookOrbit: Settings → Devices → %1)."), "KOReader") + .. " " .. require("gzreader_bookorbit").note() + end, + callback = function() self:keyboardLogin(nil, "bookorbit") end, + }, { text = _("Single sign-on (SSO)"), sub_item_table_func = function() return self:ssoMenu() end, @@ -849,6 +870,22 @@ local ERRORS = { bad_credentials = _("Wrong username or password."), rate_limited = _("Too many attempts. Wait a minute and try again."), usb = _("This Kindle syncs with Grimmory through a computer: Menu → Sync with computer."), + -- (the name goes in as an argument: gettext.lua turns "KOReader" in a message into "GZreader") + bookorbit_credentials = T(_("Wrong user name or password. BookOrbit wants the %1 sync user name and password (BookOrbit: Settings → Devices → %1), not the ones you sign in to its website with. Also check that the address is BookOrbit's."), "KOReader"), + bookorbit_sync_off = T(_("BookOrbit has sync switched off for this %1 user. Switch “Progress sync” on in BookOrbit: Settings → Devices → %1."), "KOReader"), + bookorbit_refused = T(_("BookOrbit didn't accept this Kindle's sign-in. If you changed the %1 sync password in BookOrbit, connect again."), "KOReader"), + bookorbit_not_found = _("That address answered, but not as BookOrbit (or its BookOrbit is too old for e-readers). Check the address."), + bookorbit_no_file = _("BookOrbit has no file for this book that this Kindle can open."), + bookorbit_no_api_key = _("BookOrbit's audiobooks need an API key: make one in BookOrbit (Settings → You → API keys, with Read and write access), then enter it in Settings → Accounts and services → Books → BookOrbit API key."), + bookorbit_api_key_refused = _("BookOrbit didn't accept the API key. It may have expired or been deleted: make a new one in BookOrbit (Settings → You → API keys) and enter it again."), + bookorbit_api_key_read_only = _("This BookOrbit API key is read-only, so nothing can be saved to BookOrbit with it (where you stopped listening, collections, book requests). Make one with read and write access."), + bookorbit_key_no_kosync = T(_("BookOrbit didn't let this API key see the %1 sync sign-in. Make a key with “%1 sync” ticked under Extra permissions (BookOrbit: Settings → You → API keys), or sign in with the %1 sync user name and password instead."), "KOReader"), + bookorbit_key_cannot_create = T(_("Your BookOrbit account has no %1 sync sign-in yet, and this API key is read-only, so one can't be made with it. Make the sign-in in BookOrbit (Settings → Devices → %1) or use a key with read and write access."), "KOReader"), + bookorbit_key_old_signin = T(_("BookOrbit can't hand over this account's %1 sync sign-in until its password has been saved once more: in BookOrbit, Settings → Devices → %1, set the sync password again (the same one is fine), then try again. Or sign in here with the %1 sync user name and password."), "KOReader"), + bookorbit_key_no_signin = T(_("BookOrbit accepted the API key but didn't hand over the %1 sync sign-in. Sign in with the %1 sync user name and password instead (BookOrbit: Settings → Devices → %1)."), "KOReader"), + bookorbit_delivery_original = T(_("BookOrbit is set to send this sign-in's read-aloud EPUBs with their narration. A Kindle can't play it and the files are much bigger. In BookOrbit: Settings → Devices → %1 → Read-aloud EPUB delivery → Automatic."), "KOReader"), + bookorbit_requests_refused = _("BookOrbit didn't allow that. The API key needs “Request books” ticked when you make it, and your BookOrbit account has to be allowed to request books."), + unsupported = _("That isn't available with BookOrbit yet."), no_https = require("gzreader_lan").noHttpsText(), } @@ -858,11 +895,44 @@ function Grimmory:describeError(err) return T(_("The download stalled (%1). Check the Kindle's Wi-Fi signal and try again."), err:gsub("^stalled:%s*", "")) end if type(err) == "string" and err:match("^http_") then - return T(_("Grimmory returned an error (%1)."), err:sub(6)) + return T(_("%1 returned an error (%2)."), self:serverName(), err:sub(6)) end return T(_("Something went wrong: %1"), tostring(err)) end +--- Which book server this Kindle is signed in to: "grimmory" (the default) or "bookorbit". +function Grimmory:backend() + return self.store.backend == "bookorbit" and "bookorbit" or "grimmory" +end + +function Grimmory:serverName() + return self:backend() == "bookorbit" and "BookOrbit" or "Grimmory" +end + +--- Make plugin.api the client for that server. The same table keeps being the +--- client (every part of GZreader that holds it follows): only its class changes. +function Grimmory:useBackend(name) + name = name == "bookorbit" and "bookorbit" or "grimmory" + self.store.backend = name == "bookorbit" and "bookorbit" or nil + if self.api.offline then return end -- (syncing through a computer: Grimmory's copy) + setmetatable(self.api, name == "bookorbit" and require("gzreader_bookorbit") or Api) + pcall(function() require("gzreader_covers").useSpace(name == "bookorbit" and "bookorbit" or nil) end) +end + +--- A book server that isn't Grimmory: the Grimmory-only parts (its statistics, +--- shelf editing, copying the sign-in) are left alone (gzreader_bookorbit.lua). +function Grimmory:booksOnly() + return self.api.books_only == true +end + +--- Is this synced with the book server signed in to? Grimmory: everything. +--- BookOrbit: what its client lists in `supports` ("progress", "annotations", +--- "bookmarks", "sessions", "ratings"…). +function Grimmory:serverCan(feature) + local supports = self.api.supports + return supports == nil or supports[feature] == true +end + function Grimmory:exportLog() local lib = self:libraryDir() local dest_dir = lib:match("^(.+)/[^/]+$") or lib -- next to the library, not in it @@ -1159,31 +1229,91 @@ end ---------------------------------------------------------------- pairing --- Log in. Returns ok, err. -function Grimmory:connect(server_input, username, password) +function Grimmory:connect(server_input, username, password, backend) + backend = backend == "bookorbit" and "bookorbit" or "grimmory" local server = Api.normalizeServer(server_input) if not server then return false, _("That server address doesn't look right.") end username = (username or ""):gsub("^%s+", ""):gsub("%s+$", "") if username == "" or not password or password == "" then return false, _("Enter your username and password.") end - local previous = { self.store.server, self.store.username } - self.api.explicit_https = server_input:match("^%s*https://") ~= nil - local ok, err = self.api:login(server, username, password) - Log.info("password login to", ok and self.store.server or server, ok and "ok" or ("failed: " .. tostring(err))) + local previous = self:signedInAs() + local client = self:clientFor(backend) + client.explicit_https = server_input:match("^%s*https://") ~= nil + local ok, err = client:login(server, username, password) + Log.info(backend == "bookorbit" and "BookOrbit sign-in to" or "password login to", ok and self.store.server or server, + ok and "ok" or ("failed: " .. tostring(err))) + if not ok then return false, self:describeError(err) end + self:afterLogin(previous, backend) + return true +end + +--- Sign in to BookOrbit with only its API key (gzreader_bookorbit.lua's loginWithApiKey: +--- the key fetches, or makes, the account's e-reader sign-in). Returns true, or false, message. +function Grimmory:connectWithApiKey(server_input, api_key) + local server = Api.normalizeServer(server_input) + if not server then return false, _("That server address doesn't look right.") end + api_key = type(api_key) == "string" and api_key:gsub("%s+", "") or "" + if api_key == "" then return false, _("Enter the API key.") end + local previous = self:signedInAs() + local client = self:clientFor("bookorbit") + client.explicit_https = server_input:match("^%s*https://") ~= nil + local ok, err = client:loginWithApiKey(server, api_key) + Log.info("BookOrbit sign-in with an API key to", ok and self.store.server or server, ok and "ok" or ("failed: " .. tostring(err))) if not ok then return false, self:describeError(err) end - self:afterLogin(previous) + self:afterLogin(previous, "bookorbit") return true end ---- Bookkeeping after any successful login. `previous` = { server, username } ---- from before the login. -function Grimmory:afterLogin(previous) - if type(previous) ~= "table" or previous[1] ~= self.store.server or previous[2] ~= self.store.username then - -- Different server/account: queued data belongs to the old one. +--- What this Kindle is signed in to, to compare after a sign-in (afterLogin). +function Grimmory:signedInAs() + return { self.store.server, self.store.username, self:backend() } +end + +--- The client to sign in to that book server with: plugin.api if it is that server's, +--- or one of its own (a sign-in that fails then leaves this Kindle as it was). +function Grimmory:clientFor(backend) + backend = backend == "bookorbit" and "bookorbit" or "grimmory" + if backend == self:backend() or self.api.offline then return self.api end + return (backend == "bookorbit" and require("gzreader_bookorbit") or Api):new(self.store, self.api.on_change) +end + +--- Bookkeeping after any successful login. `previous` = signedInAs() from before +--- the login; `backend`: the book server it was (nil: the one in use). +function Grimmory:afterLogin(previous, backend) + backend = backend or self:backend() + if backend ~= self:backend() then + if self.sync then pcall(self.sync.onLeave, self.sync) end + if backend ~= "bookorbit" then self.store.bookorbit = nil end + self:useBackend(backend) + end + if type(previous) ~= "table" or previous[1] ~= self.store.server or previous[2] ~= self.store.username + or (previous[3] or "grimmory") ~= self:backend() then + -- Different server/account: queued data belongs to the old one, and so do + -- the saved lists and the library index (book ids mean other books there). self.store.pending = { progress = {}, sessions = {}, ratings = {} } + self.store.bookorbit_unmatched = nil + self.store.bookorbit_stats = nil + local was = type(previous) == "table" and previous[3] or "grimmory" + if was ~= self:backend() then + -- The other server's books: its ids mean other books here, so the list of + -- its downloads is put aside (the files stay in the books folder) and comes + -- back if this Kindle signs in to it again; the saved lists go. + local other = self.store.downloads_other or {} + other[was] = self.store.downloads + self.store.downloads = other[self:backend()] or {} + other[self:backend()] = nil + self.store.downloads_other = other + pcall(self.writeManifest, self) + pcall(function() require("gzreader_listcache").clear() end) + Log.info("book server changed:", was, "->", self:backend()) + end self:save() end self:flushPending() + -- BookOrbit: the books already on this Kindle (downloaded from Grimmory, or copied over) + -- are matched to BookOrbit's by their files now, not only when the library list is next built + if self:backend() == "bookorbit" then UIManager:scheduleIn(2, function() pcall(self.matchLibraryFiles, self) end) end -- (the Catalog, if it's open saying to sign in: its page again) local B = package.loaded["gzreader_browser"] if B and B.signInChanged then UIManager:nextTick(B.signInChanged) end @@ -1196,6 +1326,85 @@ function Grimmory:onGrimmoryPair(touchmenu) return true end +--- The setup page with BookOrbit picked as the book server (the setup guide). +function Grimmory:onBookOrbitPair() + if self.pairing then return true end + if Net.usb then require("gzreader_usbsync").show(self); return true end + Net.run(function() + require("gzreader_phone").open(self, { section = "grimmory", grimmory_form = { backend = "bookorbit" } }) + end, { reason = "connecting to BookOrbit" }) + return true +end + +--- The setup page at Send books (the setup guide: GZreader on its own, no book server). +function Grimmory:onGzSendBooksPage() + self:openPhonePage("books") + return true +end + +--- Keep (or, empty, remove) the BookOrbit API key, checked against the server. +--- Returns true, or false and a message. +function Grimmory:setBookOrbitApiKey(key) + if self:backend() ~= "bookorbit" or type(self.api.setApiKey) ~= "function" then return false, self:describeError("not_paired") end + local ok, err = self.api:setApiKey(key) + Log.info("BookOrbit API key", (type(key) == "string" and key:gsub("%s+", "") ~= "") and (ok and "set" or ("not accepted: " .. tostring(err))) or "removed") + if not ok then return false, self:describeError(err) end + self:save() + pcall(function() require("gzreader_listcache").clear() end) -- (the audiobook lists were empty without it) + return true +end + +--- What to tell the user after the key was saved: that it was accepted, and what it can +--- and can't be used for (asked of BookOrbit), so a box left unticked shows at once. +function Grimmory:bookOrbitKeyReport() + if not (type(self.api.hasApiKey) == "function" and self.api:hasApiKey()) then return _("The BookOrbit API key was removed.") end + local can = self.api:keyAbilities() + local lines = { _("BookOrbit accepted the API key. Audiobooks and collections can use it.") } + if can.requests == true then + lines[#lines + 1] = _("Requesting books: yes.") + elseif can.requests == false then + lines[#lines + 1] = _("Requesting books: no (the key was made without “Request books”, or your account can't request books).") + end + if can.signin == true then + lines[#lines + 1] = _("Signing in with just the key: yes.") + elseif can.signin == false then + lines[#lines + 1] = T(_("Signing in with just the key: no (the key was made without “%1 sync”). You're signed in already, so this only matters next time."), "KOReader") + end + return table.concat(lines, " ") +end + +function Grimmory:askBookOrbitApiKey(touchmenu) + local InputDialog = require("ui/widget/inputdialog") + local dialog + dialog = InputDialog:new{ + title = _("BookOrbit API key"), + input = "", + input_hint = "bok_…", + text_type = "password", + description = _("From BookOrbit: Settings → You → API keys. Empty removes the key kept here."), + buttons = { { + { text = _("Cancel"), id = "close", callback = function() UIManager:close(dialog) end }, + { text = _("Save"), is_enter_default = true, callback = function() + local key = dialog:getInputText() + UIManager:close(dialog) + Net.run(function() + local ok, err = self:setBookOrbitApiKey(key) + UIManager:show(InfoMessage:new{ text = ok and ((key:gsub("%s+", "") == "") and _("The BookOrbit API key was removed.") + or _("BookOrbit accepted the API key. Its audiobooks are in the Catalog's Audiobooks page.")) or err, timeout = ok and 4 or nil }) + if touchmenu and touchmenu.updateItems then touchmenu:updateItems() end + end, { reason = "checking the BookOrbit API key" }) + end }, + } }, + } + UIManager:show(dialog) + dialog:onShowKeyboard() +end + +function Grimmory:onBookOrbitKeyboardLogin() + self:keyboardLogin(nil, "bookorbit") + return true +end + function Grimmory:onGrimmoryKeyboardLogin() self:keyboardLogin() return true @@ -1512,21 +1721,25 @@ end function Grimmory:announceConnected() UIManager:show(InfoMessage:new{ - text = T(_("Connected to Grimmory as %1."), self.store.username or "") .. "\n\n" - .. _("Reading progress syncs automatically for books you download from Grimmory."), + text = T(_("Connected to %1 as %2."), self:serverName(), self.store.username or "") .. "\n\n" + .. (self:booksOnly() and require("gzreader_bookorbit").note() + or require("gzreader_servername").fix(_("Reading progress syncs automatically for books you download from Grimmory."))), }) end --- prefill = { server, username } (copied from another GZreader), or the saved ones. -function Grimmory:keyboardLogin(prefill) +function Grimmory:keyboardLogin(prefill, backend) prefill = type(prefill) == "table" and prefill or {} + backend = backend == "bookorbit" and "bookorbit" or "grimmory" + local same = backend == self:backend() -- (the saved address and name are that server's) local dialog dialog = MultiInputDialog:new{ - title = _("Connect to Grimmory"), + title = backend == "bookorbit" and _("Connect to BookOrbit") or _("Connect to Grimmory"), fields = { - { text = prefill.server or self.store.server or "", hint = _("Server, e.g. https://books.example.com") }, - { text = prefill.username or self.store.username or "", hint = _("Username") }, - { text = "", hint = _("Password"), text_type = "password" }, + { text = prefill.server or (same and self.store.server) or "", hint = _("Server, e.g. https://books.example.com") }, + { text = prefill.username or (same and self.store.username) or "", + hint = backend == "bookorbit" and T(_("%1 sync user name (BookOrbit: Settings → Devices → %1)"), "KOReader") or _("Username") }, + { text = "", hint = backend == "bookorbit" and T(_("%1 sync password"), "KOReader") or _("Password"), text_type = "password" }, }, buttons = {{ { text = _("Cancel"), id = "close", callback = function() UIManager:close(dialog) end }, @@ -1537,7 +1750,7 @@ function Grimmory:keyboardLogin(prefill) local msg = InfoMessage:new{ text = _("Connecting…"), timeout = 0 } UIManager:show(msg) UIManager:forceRePaint() - local ok, err = self:connect(f[1], f[2], f[3]) + local ok, err = self:connect(f[1], f[2], f[3], backend) UIManager:close(msg) if ok then self:announceConnected() @@ -1554,13 +1767,13 @@ end function Grimmory:confirmDisconnect() UIManager:show(ConfirmBox:new{ - text = _("Disconnect this Kindle from Grimmory? Downloaded books stay on the Kindle. Progress sync will stop until you connect again."), + text = T(_("Disconnect this Kindle from %1? Downloaded books stay on the Kindle. Progress sync will stop until you connect again."), self:serverName()), ok_text = _("Disconnect"), ok_callback = function() if self.sync then self.sync:onLeave() end NetworkMgr:runWhenConnected(function() self.api:logout() end) self.api:clearTokens() - UIManager:show(InfoMessage:new{ text = _("Disconnected from Grimmory."), timeout = 3 }) + UIManager:show(InfoMessage:new{ text = T(_("Disconnected from %1."), self:serverName()), timeout = 3 }) end, }) end @@ -1572,6 +1785,8 @@ Grimmory.gone_books = {} -- book ids Grimmory answered "not found" for (this run function Grimmory:queue(kind, book_id, body) local pending = self.store.pending + -- (what the book server doesn't take isn't kept to send) + if not self:serverCan(kind == "progress" and "progress" or "sessions") then return end if kind == "progress" and Grimmory.gone_books[tostring(book_id)] then return end if kind == "progress" then pending.progress[tostring(book_id)] = body @@ -1590,7 +1805,7 @@ end --- Send progress and reading sessions queued while offline. In the --- background (gzreader_async): sending a backlog can take many seconds. function Grimmory:flushPending() - if self.flushing or not self.api:isPaired() or not NetworkMgr:isConnected() then return end + if self.flushing or not self.api:isPaired() or not self:serverCan("progress") or not NetworkMgr:isConnected() then return end local pending = self.store.pending pending.ratings = pending.ratings or {} if next(pending.progress) == nil and #pending.sessions == 0 and next(pending.ratings) == nil then return end @@ -1688,7 +1903,7 @@ function Grimmory:onNetworkConnected() pcall(function() require("gzreader_reqhelper").start(self.path) end) UIManager:scheduleIn(2, function() -- books rated in the file browser (not opened) since GZreader started - if self.api:isPaired() and self:syncEnabled() and not self._ratings_swept then + if self.api:isPaired() and self:syncEnabled() and self:serverCan("ratings") and not self._ratings_swept then local ok, _, done = pcall(require("gzreader_ratings").sweep, self, 60) if ok and done then self._ratings_swept = true end end @@ -1700,6 +1915,9 @@ function Grimmory:onNetworkConnected() UIManager:scheduleIn(8, function() pcall(require("gzreader_shelves").sync, self) end) -- the Immich album's pictures (sleep screen, wallpaper), when used (at most every 6 h) UIManager:scheduleIn(12, function() pcall(require("gzreader_immich").onNetworkConnected, self) end) + -- BookOrbit: books in the folder that aren't tied to one of its books yet (it does nothing + -- when every file is tied, or was asked about before and hasn't changed) + UIManager:scheduleIn(10, function() pcall(self.matchLibraryFiles, self) end) end ---------------------------------------------------------------- reader integration @@ -1829,14 +2047,21 @@ function Grimmory:onReaderReady() if pf then entry.file_id = pf; self:save(); self:writeManifest() end end) end + -- (BookOrbit knows a book by its file's fingerprint: worked out once, kept with the download) + if self.api.koreader_positions and not entry.hash then + entry.hash = self.api.hashFile(self.ui.document.file) + if entry.hash then self:save() end + end Log.info("opened Grimmory book", book_id, "file_id", tostring(entry.file_id), "format", tostring(entry.format)) -- (Grimmory's copy replaced since this one was downloaded: offered again, once) pcall(function() require("gzreader_newcopy").check(self, self.ui, book_id, entry) end) pcall(function() require("gzreader_layout").opened(self.ui.document, entry, book_id) end) self.sync = Sync:new(self, self.ui, entry, book_id) self.sync:onReady() -- (then openSync, below: a moment after the first page) - self.bookmarks = Bookmarks:new(self.sync) - self.annotations = Mod.Annotations:new(self.sync) + -- (each server's own modules, loaded only for the server signed in to) + self.bookmarks = require(self.api.koreader_positions and "gzreader_bo_bookmarks" or "gzreader_bookmarks"):new(self.sync) + -- (BookOrbit's highlights go by its own exchange: gzreader_bo_annotations.lua) + self.annotations = (self.api.koreader_positions and require("gzreader_bo_annotations") or Mod.Annotations):new(self.sync) if self:syncEnabled() and self.api:isPaired() and not Net.connected() then -- Wi-Fi only when needed: bring it up quietly to sync this book Net.run(function() self:syncOpenBook() end, { quiet = true, reason = "sync on open" }) @@ -1891,7 +2116,7 @@ end function Grimmory:onGrimmorySyncNow() if Net.usb then require("gzreader_usbsync").show(self); return true end if not self.sync then - UIManager:show(InfoMessage:new{ text = _("This book wasn't downloaded from Grimmory, so it can't be synced."), timeout = 3 }) + UIManager:show(InfoMessage:new{ text = require("gzreader_servername").fix(_("This book wasn't downloaded from Grimmory, so it can't be synced.")), timeout = 3 }) return true end Net.run(function() @@ -1978,6 +2203,8 @@ function Grimmory:onCloseDocument() pcall(self.annotations.onClose, self.annotations) self.annotations = nil end + -- (BookOrbit: the pages just read, from KOReader's statistics, a moment after they're saved) + if self.api.koreader_positions then pcall(function() require("gzreader_bo_stats").later(self) end) end if self.sync then self.sync:onLeave(true) pcall(self.sync.releaseCfi, self.sync) @@ -2154,7 +2381,7 @@ function Grimmory:writeManifest() end end local f = io.open(dir .. "/" .. MANIFEST, "wb") - if f then f:write(JSON.encode({ version = 1, books = list })); f:close() end + if f then f:write(JSON.encode({ version = 1, backend = self:backend(), books = list })); f:close() end end --- Merge the backup list into the settings (after an update wiped them). @@ -2165,7 +2392,9 @@ function Grimmory:restoreFromManifest() local ok, data = pcall(JSON.decode, f:read("*a")) f:close() local restored = 0 - if ok and type(data) == "table" and type(data.books) == "table" then + -- (a list from the other book server isn't this one's: its ids are other books here) + if ok and type(data) == "table" and type(data.books) == "table" + and (type(data.backend) == "string" and data.backend or "grimmory") == self:backend() then for _, b in ipairs(data.books) do local id = b.id and tostring(b.id) local path = type(b.file) == "string" and (dir .. "/" .. b.file) @@ -2193,9 +2422,78 @@ function Grimmory:libraryUpkeep(index, force) if not force and Grimmory.upkeep_sig == sig then return end Grimmory.upkeep_sig = sig pcall(self.relinkLibrary, self, index) + pcall(self.matchLibraryFiles, self, index) pcall(require("gzreader_titles").backfill, self) end +--- BookOrbit: books in the GZreader folder that aren't tied to one of its books yet +--- (downloaded from Grimmory before the switch, or copied over USB) are matched by +--- their file's fingerprint: BookOrbit says which of them it has (matchCheck), and +--- those become its downloads (the Catalog's mark, progress sync). In the background. +function Grimmory:matchLibraryFiles(index) + local dir = self.store.library_dir + if not dir or type(self.api.matchCheck) ~= "function" or not self.api:isPaired() or self.matching then return end + if not NetworkMgr:isConnected() then return end + local linked = {} + for _id, e in pairs(self.store.downloads) do if type(e) == "table" and e.path then linked[e.path] = true end end + local tried = self.store.bookorbit_unmatched or {} + local paths = {} + for name in lfs.dir(dir) do + local path = dir .. "/" .. name + local ext = name:match("%.([%w]+)$") + if ext and self.api.READABLE_EXT and self.api.READABLE_EXT[ext:lower()] and not linked[path] and name:sub(1, 1) ~= "." + and lfs.attributes(path, "mode") == "file" then + -- (asked before and not BookOrbit's: again only when the file changed) + local stamp = tostring(lfs.attributes(path, "size")) .. ":" .. tostring(lfs.attributes(path, "modification")) + if tried[name] ~= stamp then paths[#paths + 1] = { path = path, name = name, stamp = stamp } end + end + if #paths >= 400 then break end + end + if #paths == 0 then return end + self.matching = true + local titles = {} + for _name, info in pairs(type(index) == "table" and type(index.files) == "table" and index.files or {}) do + titles[tostring(info[1])] = info[4] + end + require("gzreader_async").run(self.api, function(api) + local hashes, by_hash = {}, {} + for _i, f in ipairs(paths) do + f.hash = api.hashFile(f.path) + if f.hash and not by_hash[f.hash] then hashes[#hashes + 1] = f.hash; by_hash[f.hash] = true end + end + if #hashes == 0 then return { files = paths, matches = {} } end + local matches, err = api:matchCheck(hashes) + if not matches then return nil, err end + return { files = paths, matches = matches } + end, function(res, err) + self.matching = nil + if type(res) ~= "table" then + Log.info("BookOrbit: matching the books on this Kindle failed:", tostring(err)) + return + end + local n_linked = 0 + self.store.bookorbit_unmatched = self.store.bookorbit_unmatched or {} + for _i, f in ipairs(res.files) do + local m = f.hash and res.matches[f.hash] + local id = type(m) == "table" and m.book_id and tostring(m.book_id) + if id and not self.store.downloads[id] and lfs.attributes(f.path, "mode") == "file" then + self.store.downloads[id] = { path = f.path, title = titles[id] or f.name:gsub("%.[%w]+$", ""), + format = (f.name:match("%.([%w]+)$") or ""):upper(), file_id = tonumber(m.file_id), hash = f.hash } + self.store.bookorbit_unmatched[f.name] = nil + n_linked = n_linked + 1 + elseif not id then + self.store.bookorbit_unmatched[f.name] = f.stamp + end + end + Log.info("BookOrbit: matched", n_linked, "of", #res.files, "books on this Kindle by their files (the rest aren't in BookOrbit as the same file)") + self:save() + if n_linked > 0 then + self:writeManifest() + pcall(self.refreshDownloadsTab, self) + end + end, "match books") +end + --- Match books in the folder that aren't linked yet to Grimmory books by --- file name, using the library index. Returns the number linked. function Grimmory:relinkLibrary(index) @@ -2306,6 +2604,7 @@ function Grimmory:downloadAndOpen(book, menu, opts) -- Grimmory's progress, for the book's first opening without Wi-Fi -- (gzreader_sync.lua: Sync:onReady) entry.grimmory_progress = Sync.progressOf(book) + if self.api.koreader_positions then entry.hash = self.api.hashFile(path) end self.store.downloads[tostring(book.id)] = entry self:save() self:writeManifest() @@ -2395,7 +2694,7 @@ end --- Downloads from before 1.22.4: ask Grimmory for their authors (in the --- background, while Wi-Fi is on anyway; 40 at a time; each book once). function Grimmory:backfillAuthors() - if self.backfilling or not self.api:isPaired() or not Net.connected() then return end + if self.backfilling or not self.api:isPaired() or self:booksOnly() or not Net.connected() then return end local ids = {} for id, e in pairs(self.store.downloads or {}) do if type(e) == "table" and e.authors == nil and not e.authors_asked and tonumber(id) then diff --git a/plugins/zenos.koplugin/common/quickstart/quickstart_pages.lua b/plugins/zenos.koplugin/common/quickstart/quickstart_pages.lua index 725ee79fe..426ebf373 100644 --- a/plugins/zenos.koplugin/common/quickstart/quickstart_pages.lua +++ b/plugins/zenos.koplugin/common/quickstart/quickstart_pages.lua @@ -720,37 +720,98 @@ local function buildGrimmoryPage(ctx) .. _("Later: Menu → Sync with computer."), } end - local choices = {} - if state.paired then - choices[#choices + 1] = { id = "keep", text = T(_("Keep connection (%1)"), state.username or "?"), checked = true } + -- GZreader: first, how it will be used (Grimmory, BookOrbit, or on its own with + -- books sent from a browser); the page after it offers what fits that answer. + local g = grimmoryPlugin(ctx) + local current = (state.paired and type(g.backend) == "function" and g:backend()) or nil + local saved = type(g.store) == "table" and g.store.book_source or nil + local mode = current or saved or "grimmory" + local connect = { choice_type = "radio" } + + local function fillConnect() + local touch = require("device"):isTouchDevice() + local later = touch and _("Later: swipe down → Connect.") or _("Later: Menu → Send books.") + local choices = {} + if mode == "local" then + connect.title = _("Send books from your browser") + connect.description = _("Scan the QR code with your phone, or open this Kindle's address in any browser on the same Wi‑Fi, and drop your books on the page. Notes and Calendar are connected there too.") .. "\n" .. later + choices[#choices + 1] = { id = "books", text = _("Show the QR code now"), checked = true } + choices[#choices + 1] = { id = "gz_copy", text = _("Copy from another GZreader"), checked = false } + else + local name = mode == "bookorbit" and "BookOrbit" or "Grimmory" + local keep = state.paired and current == mode + connect.title = _("Set up from your browser") + connect.description = T(_("Scan the QR code with your phone, or open this Kindle's address in any browser on the same Wi‑Fi, to connect %1, Notes and Calendar, or to send books."), name) .. "\n" + .. (mode == "bookorbit" and (T(_("BookOrbit asks for the %1 sync user name and password you made in its Settings → %1."), "KOReader") .. "\n") or "") + .. later + if keep then + choices[#choices + 1] = { id = "keep", text = T(_("Keep connection (%1)"), state.username or "?"), checked = true } + end + choices[#choices + 1] = { id = mode == "bookorbit" and "bo_qr" or "qr", text = _("Set up from a browser"), checked = not keep } + choices[#choices + 1] = { id = mode == "bookorbit" and "bo_type" or "type", text = T(_("Type my %1 login here"), name), checked = false } + -- GZreader: copy the connections of another GZreader on the Wi-Fi (PIN) + if mode ~= "bookorbit" then + choices[#choices + 1] = { id = "gz_copy", text = _("Copy from another GZreader"), checked = false } + end + end + if state.connected_any then + choices[#choices + 1] = { id = "gz_send", text = _("Send to another GZreader"), checked = false } + end + choices[#choices + 1] = { id = "skip", text = _("Skip for now"), checked = false } + connect.choices = choices + connect.reset_selection = true -- (the screen takes the new defaults when it shows the page) end - choices[#choices + 1] = { id = "qr", text = _("Set up from a browser"), checked = not state.paired } - choices[#choices + 1] = { id = "type", text = _("Type my Grimmory login here"), checked = false } - -- GZreader: copy the connections of another GZreader on the Wi-Fi (PIN) - choices[#choices + 1] = { id = "gz_copy", text = _("Copy from another GZreader"), checked = false } - if state.connected_any then - choices[#choices + 1] = { id = "gz_send", text = _("Send to another GZreader"), checked = false } + fillConnect() + connect.on_apply = function(sel) + local events = { qr = "GrimmoryPair", type = "GrimmoryKeyboardLogin", bo_qr = "BookOrbitPair", bo_type = "BookOrbitKeyboardLogin", + books = "GzSendBooksPage", gz_copy = "GzCopyReceive", gz_send = "GzCopySend" } + for id, name in pairs(events) do + if sel[id] then sendGrimmoryEvent(name) end + end end - choices[#choices + 1] = { id = "skip", text = _("Skip for now"), checked = false } - return { - title = _("Set up from your browser"), - description = _("Scan the QR code with your phone, or open this Kindle's address in any browser on the same Wi‑Fi, to connect Grimmory, Notes and Calendar, or to send books.") .. "\n" - .. (not require("device"):isTouchDevice() and _("Later: Menu → Send books.") - or _("Later: swipe down → Connect.")), + + -- (the guide's later page about sync says what's true for the answer: build_install_pages gives it) + local how + local function fillSync() + local page = how and how.sync_page + if type(page) ~= "table" then return end + if mode == "bookorbit" then + page.title = _("Books from BookOrbit") + local ok_note, note = pcall(function() return require("gzreader_bookorbit").note() end) + page.description = _("Your BookOrbit books are in the Catalog tab.") .. "\n\n" + .. (ok_note and type(note) == "string" and note or _("You can browse and download your books.")) + elseif mode == "local" then + page.title = _("Your books") + page.description = _("Books you send from your browser are kept on this Kindle, and keep their place and bookmarks here.") .. "\n\n" + .. _("Got a book server later? Connect it in Settings → Accounts and services → Books.") + else + page.title, page.description = page.grimmory_title or page.title, page.grimmory_description or page.description + end + end + how = { + fill_sync = fillSync, + title = _("How will you use GZreader?"), + description = _("GZreader can get its books from your own book server, or you can send them from a browser. You can change this later in Settings → Accounts and services → Books."), choice_type = "radio", - choices = choices, + choices = { + { id = "grimmory", text = _("With Grimmory, my book server"), checked = mode == "grimmory" }, + { id = "bookorbit", text = _("With BookOrbit, my book server"), checked = mode == "bookorbit" }, + { id = "local", text = _("On its own: I send books from my browser"), checked = mode == "local" }, + }, on_apply = function(sel) - if sel["qr"] then - sendGrimmoryEvent("GrimmoryPair") - elseif sel["type"] then - sendGrimmoryEvent("GrimmoryKeyboardLogin") - elseif sel["gz_copy"] then - sendGrimmoryEvent("GzCopyReceive") - elseif sel["gz_send"] then - sendGrimmoryEvent("GzCopySend") + local picked = (sel["bookorbit"] and "bookorbit") or (sel["local"] and "local") or "grimmory" + if type(g.store) == "table" and g.store.book_source ~= picked then + g.store.book_source = picked + if type(g.save) == "function" then pcall(g.save, g) end + end + if picked ~= mode then + mode = picked + fillConnect() + fillSync() end end, } + return how, connect end function M.build_install_pages(ctx) @@ -956,6 +1017,7 @@ function M.build_install_pages(ctx) -- 4b. GZreader: sync (static) { title = _("Synced with Grimmory"), + gz_sync_page = true, -- (retitled for BookOrbit or no server: buildGrimmoryPage's fillSync) icon_file = _plugin_root .. "/icons/library.svg", icon_size = 120, description = _("Books from the Catalog tab keep their place and bookmarks in sync with Grimmory and your other devices.") .. "\n\n" @@ -1090,9 +1152,21 @@ function M.build_install_pages(ctx) if g and type(g.useLibraryAsHome) == "function" then g:useLibraryAsHome() end end) - local ok_gp, grimmory_page = pcall(buildGrimmoryPage, ctx) - if not ok_gp then grimmory_page = nil end - if grimmory_page then table.insert(pages, 1, grimmory_page) end + local ok_gp, grimmory_page, connect_page = pcall(buildGrimmoryPage, ctx) + if not ok_gp then grimmory_page, connect_page = nil, nil end + if connect_page then table.insert(pages, 1, connect_page) end + if grimmory_page then + if type(grimmory_page.fill_sync) == "function" then + for _i, page in ipairs(pages) do + if page.gz_sync_page then + page.grimmory_title, page.grimmory_description = page.title, page.description + grimmory_page.sync_page = page + end + end + pcall(grimmory_page.fill_sync) + end + table.insert(pages, 1, grimmory_page) + end -- Inject real cover art and rendered icons into preview pages. local ok_inject, err_inject = pcall(function() diff --git a/plugins/zenos.koplugin/common/quickstart/quickstart_screen.lua b/plugins/zenos.koplugin/common/quickstart/quickstart_screen.lua index 10a61ba64..0a0bb4e65 100644 --- a/plugins/zenos.koplugin/common/quickstart/quickstart_screen.lua +++ b/plugins/zenos.koplugin/common/quickstart/quickstart_screen.lua @@ -811,6 +811,16 @@ end function QuickstartScreen:_nextPage() self:_applyCurrentPage() + -- (GZreader: a page's answer can change the next page's choices: its defaults again) + local nxt = self.pages[self._page_idx + 1] + if type(nxt) == "table" and nxt.reset_selection and nxt.choices then + local sel = {} + for _i, choice in ipairs(nxt.choices) do + if choice.checked then sel[choice.id] = true end + end + self._selections[self._page_idx + 1] = sel + nxt.reset_selection = nil + end if self._page_idx >= self._total then self:onClose() else diff --git a/plugins/zenos.koplugin/modules/filebrowser/patches/home/widgets/grimmory_stats.lua b/plugins/zenos.koplugin/modules/filebrowser/patches/home/widgets/grimmory_stats.lua index 0a769b41b..45b0c9aa3 100644 --- a/plugins/zenos.koplugin/modules/filebrowser/patches/home/widgets/grimmory_stats.lua +++ b/plugins/zenos.koplugin/modules/filebrowser/patches/home/widgets/grimmory_stats.lua @@ -1,37 +1,73 @@ --- GZreader: reading stats from Grimmory, the same widget as the local +-- GZreader: reading stats from the book server, the same widget as the local -- reading stats (stats_triplet.lua: notebook page, dividers, boxes…) with --- numbers that count every device: Grimmory adds up the reading sessions --- each GZreader (and its web reader) sends. GZreader fetches them --- (gzreader_grimstats.lua) and keeps the last ones for when it's offline. +-- numbers that count every device: the server (Grimmory or BookOrbit, +-- whichever this Kindle is signed in to) adds up what each device sends. +-- GZreader fetches them (gzreader_grimstats.lua) and keeps the last ones for +-- when it's offline. A tap opens the page with more (gzreader_statspage.lua). local _ = require("gettext") local base = require("modules/filebrowser/patches/home/widgets/stats_triplet") local fmt_time = base.fmt_time local function num(v) return v ~= nil and tostring(v) or "—" end +local function time(key) return function(s) return s[key] and fmt_time(s[key]) or "—" end end -local FIELDS = { +-- GZreader: which server's numbers (asked each time: the sign-in can change) +local function server() + local get = rawget(_G, "__GZ_BOOK_SERVER") + local ok, name = pcall(function() return get and get() end) + return ok and name == "bookorbit" and "bookorbit" or "grimmory" +end + +local ALL = { streak = { id = "streak", label = _("Day streak"), tally = "streak", icon = "streak", get = function(s) return num(s.streak) end }, longest_streak = { id = "longest_streak", label = _("Longest streak"), icon = "streak", get = function(s) return num(s.longest_streak) end }, reading_days = { id = "reading_days", label = _("Days read"), icon = "book_days", get = function(s) return num(s.reading_days) end }, - week_time = { id = "week_time", label = _("Read this week"), icon = "book_duration", - get = function(s) return s.week_time and fmt_time(s.week_time) or "—" end }, + week_time = { id = "week_time", label = _("Read this week"), icon = "book_duration", get = time("week_time") }, week_books = { id = "week_books", label = _("Books this week"), get = function(s) return num(s.week_books) end }, month_sessions = { id = "month_sessions", label = _("Sessions this month"), icon = "book_days", get = function(s) return num(s.month_sessions) end }, year_finished = { id = "year_finished", label = _("Finished this year"), get = function(s) return num(s.year_finished) end }, + -- GZreader: BookOrbit's + today_time = { id = "today_time", label = _("Read today"), icon = "book_duration", get = time("today_time") }, + month_time = { id = "month_time", label = _("Read this month"), icon = "book_duration", get = time("month_time") }, + year_time = { id = "year_time", label = _("Read this year"), icon = "book_duration", get = time("year_time") }, + year_days = { id = "year_days", label = _("Days read this year"), icon = "book_days", + get = function(s) return num(s.year_days) end }, + goal = { id = "goal", label = _("Reading goal"), get = function(s) return num(s.goal) end }, + badges = { id = "badges", label = _("Badges"), get = function(s) return num(s.badges) end }, + library_books = { id = "library_books", label = _("Books in the library"), + get = function(s) return num(s.library_books) end }, + reading_now = { id = "reading_now", label = _("Reading now"), get = function(s) return num(s.reading_now) end }, +} + +-- GZreader: what each server has (the same lists as gzreader_grimstats.lua's FIELDS) +local BY_SERVER = { + grimmory = { "week_time", "streak", "year_finished", "longest_streak", "reading_days", "week_books", "month_sessions" }, + bookorbit = { "week_time", "streak", "year_finished", "longest_streak", "today_time", "month_time", "year_time", "year_days", + "goal", "badges", "library_books", "reading_now" }, } -local OPTIONS = { "week_time", "streak", "year_finished", "longest_streak", "reading_days", "week_books", "month_sessions" } +local function has(list, id) + for _i, v in ipairs(list) do if v == id then return true end end + return false +end + +-- The fields of the server signed in to: a slot set to one the other server has +-- falls back to the widget's first default (build_stats does that for a missing id). +local FIELDS = setmetatable({}, { __index = function(_t, id) + local f = ALL[id] + return f and has(BY_SERVER[server()], id) and f or nil +end }) local widget = base.make{ id = "grimmory_stats", - label = _("Grimmory reading stats"), + label = _("Reading stats (every device)"), fields = FIELDS, config_key = "middle_grimmory_stats", defaults = { "week_time", "streak", "year_finished" }, @@ -41,6 +77,47 @@ local widget = base.make{ return ok and type(values) == "table" and values or {} end, } + +-- GZreader: a tap opens the reading stats page; a hold in edit mode, the widget's settings +local build = widget.build +widget.build = function(ctx) + local body = build(ctx) + local Device = require("device") + if not Device:isTouchDevice() then return body end + local Geom = require("ui/geometry") + local GestureRange = require("ui/gesturerange") + local InputContainer = require("ui/widget/container/inputcontainer") + local Screen = Device.screen + local whole = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight() } + local tap = InputContainer:new{ + dimen = Geom:new{ w = ctx.width, h = ctx.height }, + ges_events = { + TapServerStats = { GestureRange:new{ ges = "tap", range = whole } }, + HoldServerStats = { GestureRange:new{ ges = "hold", range = whole } }, + }, + } + tap.onTapServerStats = function(tap_self, _arg, ges) + if not (tap_self.dimen and ges and ges.pos and tap_self.dimen:contains(ges.pos)) then return false end + if ctx.openTopMenu and ctx.openTopMenu(ges) then return true end + if ctx.editMode then return false end + local open = rawget(_G, "__GZ_SERVER_STATS_PAGE") + if not open then return false end + pcall(open) + return true + end + tap.onHoldServerStats = function(tap_self, _arg, ges) + if not (tap_self.dimen and ges and ges.pos and tap_self.dimen:contains(ges.pos)) then return false end + if ctx.editMode and ctx.openWidgetSettings then return ctx.openWidgetSettings() end + return false + end + tap[1] = body + return tap +end + widget.FIELDS = FIELDS -widget.OPTIONS = OPTIONS -return widget +widget.ALL = ALL +widget.BY_SERVER = BY_SERVER +-- (label and OPTIONS follow the server signed in to) +return setmetatable(widget, { __index = function(_t, key) + if key == "OPTIONS" then return BY_SERVER[server()] end +end }) diff --git a/tools/gzreader/bookorbit-probe.py b/tools/gzreader/bookorbit-probe.py new file mode 100644 index 000000000..c6b1b5964 --- /dev/null +++ b/tools/gzreader/bookorbit-probe.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Ask a real BookOrbit server the questions GZreader's BookOrbit support +depends on, and print what came back in a form that is safe to paste into a +pull request: status codes, field names and counts only. It never prints the +address, the user name, the password, the API key, a book's title or any +other value from the library. + + python3 tools/gzreader/bookorbit-probe.py + +It asks for the server's address, the KOReader sync user name and password +(BookOrbit: Settings, KOReader), and optionally an API key (for audiobooks). +Or set BOOKORBIT_URL, BOOKORBIT_KO_USER, BOOKORBIT_KO_PASSWORD and +BOOKORBIT_API_KEY. It also says whether the server answers GZreader's sync page (the +web page that fills Kindles without Wi-Fi from a computer), and what the API key +is allowed to do. It only reads books and positions; the one trace it leaves is +a device named "GZreader probe" in BookOrbit's KOReader device list (from the +match check), which can be removed there. +""" +import getpass, hashlib, json, os, socket, ssl, sys, urllib.error, urllib.request + +TLS = None + +MOCK_SHAPES = { # what the tests' mock server (tests/mock_bookorbit.py) sends, to compare with + "list item": {"id", "title", "authors", "seriesId", "seriesName", "seriesIndex", "progressPercentage", "lastReadAt", + "readStatus", "formats", "hasCover", "thumbnailUrl", "detailUrl", "addedAt", "updatedAt"}, + "file": {"id", "format", "role", "downloadVariant", "sizeBytes", "sourceSizeBytes", "durationSeconds", "fileHash", + "downloadUrl", "devicePath"}, + "manifest": {"schema", "schemaVersion", "revision", "book", "assets", "chapters", "totalDurationMs"}, + "asset": {"assetId", "fileId", "sequence", "format", "durationMs", "sizeBytes", "etag"}, +} + + +def ask(env, prompt, secret=False, optional=False): + v = os.environ.get(env) + if v: + return v.strip() + if not sys.stdin.isatty(): + return "" if optional else sys.exit("Set %s (not a terminal, so I can't ask)." % env) + v = (getpass.getpass(prompt) if secret else input(prompt)).strip() + if not v and not optional: + sys.exit("Needed: " + prompt.strip(": ")) + return v + + +def tls_context(): + """The system's certificates; where Python has none of its own (python.org's + Python on a Mac before its "Install Certificates" step), macOS's bundle or certifi's.""" + ctx = ssl.create_default_context() + if ctx.cert_store_stats().get("x509_ca", 0) == 0: + for bundle in ("/etc/ssl/cert.pem", "/etc/ssl/certs/ca-certificates.crt"): + if os.path.exists(bundle): + try: + ctx.load_verify_locations(bundle) + break + except (OSError, ssl.SSLError): + pass + else: + try: + import certifi + ctx.load_verify_locations(certifi.where()) + except Exception: + pass + return ctx + + +def why(e): + """Why a request got no answer, in words that name no address.""" + r = getattr(e, "reason", e) + text = str(r) + if isinstance(r, ssl.SSLCertVerificationError) or "CERTIFICATE_VERIFY_FAILED" in text: + return "the server's certificate wasn't accepted (%s)" % (getattr(r, "verify_message", "") or "verification failed") + if isinstance(r, ssl.SSLError): + return "a TLS error (%s)" % (getattr(r, "reason", None) or type(r).__name__) + if isinstance(r, socket.gaierror): + return "the address's name wasn't found (DNS)" + if isinstance(r, (socket.timeout, TimeoutError)) or "timed out" in text: + return "timed out" + if isinstance(r, ConnectionRefusedError): + return "connection refused" + if isinstance(r, ConnectionResetError): + return "connection reset" + code = getattr(r, "errno", None) + return type(r).__name__ + (code and " (errno %s)" % code or "") + + +def call(base, path, headers, method="GET", body=None, want_bytes=0): + data = json.dumps(body).encode() if body is not None else None + h = dict(headers) + h.setdefault("User-Agent", "GZreader-probe/1") + h.setdefault("Accept", "*/*") + if data is not None: + h["Content-Type"] = "application/json" + req = urllib.request.Request(base + path, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(req, timeout=30, context=TLS) as r: + code, raw, hdr = r.status, r.read(want_bytes or 4 << 20), r.headers + except urllib.error.HTTPError as e: + code, raw, hdr = e.code, e.read(1 << 16), e.headers + except (urllib.error.URLError, OSError) as e: + return None, None, {}, why(e) + if want_bytes: + return code, raw, hdr, None + try: + return code, json.loads(raw) if raw else None, hdr, None + except ValueError: + return code, None, hdr, "not JSON" + + +SYNC_PAGE = "https://9retirement6irk.github.io" # where GZreader's sync page is served from + + +def cors(A, ko): + """Would a browser on the sync page be allowed to call this server? BookOrbit itself + sends no cross-origin headers in production, so this is a question about the reverse + proxy in front of it.""" + want = {"x-auth-user", "x-auth-key", "authorization", "content-type"} + code, _, hdr, err = call(A, "/koreader/users/auth", { + "Origin": SYNC_PAGE, "Access-Control-Request-Method": "GET", + "Access-Control-Request-Headers": ", ".join(sorted(want))}, "OPTIONS") + allow = (hdr.get("Access-Control-Allow-Origin") or "").strip() + heads = {h.strip().lower() for h in (hdr.get("Access-Control-Allow-Headers") or "").split(",") if h.strip()} + pre_ok = code in (200, 204) and allow in (SYNC_PAGE, "*") and (want <= heads or "*" in heads) + line("sync page: preflight (OPTIONS)", code, err or "allowed origin: %s; headers allowed: %s" % ( + allow == SYNC_PAGE and "the sync page" or allow == "*" and "any" or allow and "another site" or "none", + "all GZreader sends" if (want <= heads or "*" in heads) else heads and "missing " + ", ".join(sorted(want - heads)) or "none")) + code, _, hdr, err = call(A, "/koreader/users/auth", dict(ko, Origin=SYNC_PAGE)) + allow = (hdr.get("Access-Control-Allow-Origin") or "").strip() + get_ok = code == 200 and allow in (SYNC_PAGE, "*") + line("sync page: a signed-in request", code, err or "allowed origin: %s" % ( + allow == SYNC_PAGE and "the sync page" or allow == "*" and "any" or allow and "another site" or "none")) + print(" Kindles without Wi-Fi (the sync page) could use this server: %s" % ( + "yes" if pre_ok and get_ok else "no: BookOrbit sends no cross-origin headers itself, so the reverse proxy in front of it would have to let %s in" % SYNC_PAGE)) + + +def keys(v): + return sorted(v) if isinstance(v, dict) else type(v).__name__ + + +def line(name, code, note=""): + print("%-44s %s %s" % (name, code if code is not None else "no answer", note)) + + +def compare(name, got): + want = MOCK_SHAPES[name] + got = set(got) + if got >= want: + extra = sorted(got - want) + print(" %s: has every field GZreader's tests use%s" % (name, extra and "; also " + ", ".join(extra) or "")) + else: + print(" %s: MISSING %s" % (name, ", ".join(sorted(want - got)))) + + +def main(): + base = ask("BOOKORBIT_URL", "BookOrbit address (https://...): ").rstrip("/") + if not base.startswith(("http://", "https://")): + sys.exit("The address must start with http:// or https://") + user = ask("BOOKORBIT_KO_USER", "KOReader sync user name: ") + password = ask("BOOKORBIT_KO_PASSWORD", "KOReader sync password (not shown): ", secret=True) + key = ask("BOOKORBIT_API_KEY", "API key for audiobooks (not shown; Enter to skip): ", secret=True, optional=True) + ko = {"x-auth-user": user, "x-auth-key": hashlib.md5(password.encode()).hexdigest()} + A = base + "/api/v1" + global TLS + TLS = tls_context() + print("\nBookOrbit probe (status codes and field names only)\n") + print("Python %s on %s; %d certificate authorities loaded\n" % (sys.version.split()[0], sys.platform, TLS.cert_store_stats().get("x509_ca", 0))) + + code, j, _, err = call(A, "/koreader/users/auth", ko) + line("sign-in (koreader/users/auth)", code, err or keys(j)) + if code is None: + print("\nNo answer from the server (%s), so the rest is skipped. The sign-in wasn't tried." % err) + return 1 + if code != 200: + ctype = "a web page" if j is None else "JSON" + print("\nThe sign-in didn't work (the answer was %s), so the rest is skipped. 401: wrong user name or password; 403 with JSON:" + " sync is switched off for these credentials in BookOrbit; 403 or 302 with a web page: something in front of" + " BookOrbit (an access proxy or a bot check) answered instead of it." % ctype) + return 1 + code, j, _, err = call(A, "/koreader/plugin/version", ko) + line("version", code, err or (isinstance(j, dict) and "server %s; capabilities: %s" % ( + j.get("serverVersion"), ", ".join(j.get("capabilities") or [])) or "")) + + code, j, _, err = call(A, "/koreader/plugin/catalog/root", ko) + line("catalog root", code, err or (isinstance(j, dict) and "sections: " + ", ".join( + str(s.get("section")) for s in j.get("sections") or []) or keys(j))) + for s in ("libraries", "collections", "authors", "series"): + code, j, _, err = call(A, "/koreader/plugin/catalog/sections/" + s, ko) + items = isinstance(j, dict) and j.get("items") or [] + line("section " + s, code, err or "%d entries; entry fields: %s" % (len(items), items and keys(items[0]) or "-")) + + code, j, _, err = call(A, "/koreader/plugin/catalog/books?size=5&sort=recently_added", ko) + items = isinstance(j, dict) and j.get("items") or [] + line("books (first 5)", code, err or "total %s; page fields: %s" % (isinstance(j, dict) and j.get("total"), keys(j))) + file_hash = None + if items: + compare("list item", items[0]) + code, d, _, err = call(A, "/koreader/plugin/catalog/books/%d" % items[0]["id"], ko) + line("book detail", code, err or "") + files = isinstance(d, dict) and d.get("files") or [] + if files: + compare("file", files[0]) + f = files[0] + file_hash = f.get("fileHash") + print(" file: format %s, role %s, variant %s, hash %s" % ( + f.get("format"), f.get("role"), f.get("downloadVariant"), + "32 hex (KOReader's kind)" if isinstance(file_hash, str) and len(file_hash) == 32 else "absent or another kind")) + code, raw, hdr, err = call(base, f["downloadUrl"], ko, want_bytes=4096) + line("download (first 4 KB only)", code, err or "type %s; length header %s" % ( + hdr.get("Content-Type"), "present" if hdr.get("Content-Length") else "absent")) + if items[0].get("thumbnailUrl"): + code, raw, hdr, err = call(base, items[0]["thumbnailUrl"], ko, want_bytes=64) + line("cover", code, err or "type %s; ETag %s" % (hdr.get("Content-Type"), "present" if hdr.get("ETag") else "absent")) + if file_hash: + dev = {"deviceId": "gzreader-probe", "deviceModel": "GZreader probe", "pluginVersion": "0.0.0"} + code, j, _, err = call(A, "/koreader/plugin/match-check", ko, "POST", dict(dev, hashes=[file_hash])) + line("match-check (that book's hash)", code, err or "%s; matched %d" % (keys(j), len(isinstance(j, dict) and j.get("matches") or []))) + code, j, _, err = call(A, "/koreader/syncs/progress/" + file_hash, ko) + line("reading position (KOSync)", code, err or (j and keys(j) or "none stored ({})")) + + # Can the e-reader sign-in alone list and download an audio file? (Only when BookOrbit's + # "Hide audiobook-only books" is off; GZreader uses an API key for audiobooks until this says yes.) + found = None + for fmt in ("m4b", "mp3", "m4a"): + code, j, _, err = call(A, "/koreader/plugin/catalog/books?size=1&format=" + fmt, ko) + items = isinstance(j, dict) and j.get("items") or [] + if items: + found = (fmt, items[0]["id"]) + break + if not found: + line("audio through the e-reader sign-in", "-", "no audiobook in the e-reader catalog (BookOrbit's \"Hide audiobook-only books\" is on, or there are none)") + else: + code, d, _, err = call(A, "/koreader/plugin/catalog/books/%d" % found[1], ko) + audio = [f for f in (isinstance(d, dict) and d.get("files") or []) if str(f.get("format")).lower() in ("m4b", "mp3", "m4a", "flac", "ogg", "opus")] + if not audio: + line("audio through the e-reader sign-in", code, err or "a %s book is listed, but its record has no audio file" % found[0]) + else: + f = audio[0] + code, raw, hdr, err = call(base, f["downloadUrl"], dict(ko, Range="bytes=0-1023"), want_bytes=1024) + line("audio through the e-reader sign-in", code, err or "format %s, role %s, duration %s; type %s; Content-Range %s" % ( + f.get("format"), f.get("role"), "present" if f.get("durationSeconds") else "absent", hdr.get("Content-Type"), + "present" if hdr.get("Content-Range") else "absent")) + + cors(A, ko) + + if not key: + print("\nNo API key given: audiobooks not checked.") + return 0 + api = {"Authorization": "Bearer " + key} + code, j, _, err = call(A, "/auth/me", api) + line("API key (auth/me)", code, err or (isinstance(j, dict) and "method %s" % j.get("authenticationMethod") or "")) + if code != 200: + return 1 + # What the key is allowed to do (each is a tick box when the key is made) + code, j, _, err = call(A, "/koreader/credentials", api) + line("key: KOReader sync sign-in", code, err or (code == 200 and (isinstance(j, dict) and "can sign in with only the key (fields: %s)" % ", ".join(keys(j)) + or "no sync sign-in on the account yet (GZreader would make one)") + or code == 403 and "the key lacks \"KOReader sync\"" or "")) + code, j, _, err = call(A, "/collections", api) + line("key: collections", code, err or (isinstance(j, list) and "%d listed; fields: %s" % (len(j), j and ", ".join(keys(j[0])) or "-") or "")) + code, j, _, err = call(A, "/book-requests?page=1&limit=1", api) + items = isinstance(j, dict) and j.get("items") or [] + line("key: book requests", code, err or (code == 200 and "total %s; fields: %s" % (j.get("total"), items and ", ".join(keys(items[0])) or "-") + or code == 403 and "the key (or the account) lacks \"Request books\"" or "")) + audio = ["m4b", "mp3", "m4a", "flac", "ogg", "opus"] + query = {"sort": [{"field": "title", "dir": "asc"}], "pagination": {"page": 1, "size": 1}, + "filter": {"type": "group", "join": "AND", "rules": [ + {"type": "rule", "field": "format", "operator": "includesAny", "value": audio + [f.upper() for f in audio]}]}} + code, j, _, err = call(A, "/books/query", api, "POST", query) + items = isinstance(j, dict) and j.get("items") or [] + line("books/query (audiobooks)", code, err or "total %s; page fields: %s; card fields: %s" % ( + isinstance(j, dict) and j.get("total"), keys(j), items and keys(items[0]) or "-")) + if not items: + print(" no audiobook found (none in the library, or the format filter doesn't match): send this line back") + return 0 + bid = items[0].get("id") + code, m, _, err = call(A, "/audiobooks/%s/manifest" % bid, api) + line("audiobook manifest", code, err or "") + if isinstance(m, dict) and m.get("assets"): + compare("manifest", m) + compare("asset", m["assets"][0]) + print(" %d file(s), %d chapter(s), formats: %s" % (len(m["assets"]), len(m.get("chapters") or []), + ", ".join(sorted({str(a.get("format")) for a in m["assets"]})))) + code, raw, hdr, err = call(A, "/audiobooks/%s/assets/%s/content" % (bid, m["assets"][0]["assetId"]), + dict(api, Range="bytes=0-1023"), want_bytes=1024) + line("audio file (first 1 KB, resumable?)", code, err or "Content-Range %s" % ("present" if hdr.get("Content-Range") else "absent")) + code, j, _, err = call(A, "/audiobooks/%s/playback-state" % bid, api) + line("listening position", code, err or (j and keys(j) or "none stored")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gzreader/emulator/bookorbit_audiobooks.lua b/tools/gzreader/emulator/bookorbit_audiobooks.lua new file mode 100644 index 000000000..cf03406b1 --- /dev/null +++ b/tools/gzreader/emulator/bookorbit_audiobooks.lua @@ -0,0 +1,53 @@ +-- BookOrbit audiobooks (tests/mock_bookorbit.py on 127.0.0.1:18096): sign in, enter the +-- API key, list the audiobooks, download one of two files through the player's own +-- download, and send and read back where it was left. (The mock's audio isn't real +-- audio: nothing is played.) Prints what each step found. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +local KEY = "bok_" .. string.rep("a1B2c3D4e5", 4) .. "f6G7h8I9j" +local state = {} +add({ fn = function() + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" or w.name == "QR code screen" then UIManager:close(w) end + end +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + local ok, err = p:connect("http://127.0.0.1:18096", "will-kindle", "hunter22", "bookorbit") + local none = p.api:listBooks{ page = 0, size = 20, fileType = { "AUDIOBOOK" } } + local k_ok, k_err = p:setBookOrbitApiKey(KEY) + local list = p.api:listBooks{ page = 0, size = 20, sort = "title", dir = "asc", fileType = { "AUDIOBOOK" } } + local names = {} + for _i, b in ipairs(list and list.content or {}) do names[#names + 1] = b.id .. "=" .. b.title end + E.say("sign-in:", tostring(ok), tostring(err), "| audiobooks before the key:", tostring(none and #none.content), "| key:", tostring(k_ok), tostring(k_err), + "| after:", table.concat(names, ", ")) + state.summary = list and list.content[1] + require("gzreader_audiobook").download(p, state.summary, function(book, derr) + state.book, state.err = book, derr + end) +end, after = 25 }) +add({ fn = function(E) + local lfs = require("libs/libkoreader-lfs") + local b = state.book + local files = {} + for _i, t in ipairs(b and b.tracks or {}) do files[#files + 1] = t.file .. ":" .. tostring(lfs.attributes(b.dir .. "/" .. t.file, "size")) end + E.say("downloaded:", tostring(b ~= nil), tostring(state.err), "| id", tostring(b and b.id), "| files:", table.concat(files, ", "), + "| chapters:", tostring(b and #b.chapters), "| file id:", tostring(b and b.file_id)) + local p = plugin() + p:queue("progress", b.id, { fileProgress = { bookFileId = b.file_id, positionData = "12000", positionHref = "1", progressPercent = 68.5 } }) + p:flushPending() +end, after = 10 }) +add({ fn = function(E) + local p = plugin() + local rec = p.api:getBook(state.book.id) + local ap = rec and rec.audiobookProgress + E.say("the place sent and read back: track", tostring(ap and ap.trackIndex), "ms", tostring(ap and ap.positionMs), "| still queued:", tostring(p.store.pending.progress[state.book.id] ~= nil)) + local log = io.open(require("datastorage"):getDataDir() .. "/gzreader.log", "rb") + local text = log and log:read("*a") or "" + if log then log:close() end + E.say("log has the API key:", tostring(text:find(KEY, 1, true) ~= nil), "| part of it:", tostring(text:find("a1B2c3D4", 1, true) ~= nil)) +end, after = 2 }) +return s diff --git a/tools/gzreader/emulator/bookorbit_bookmarks.lua b/tools/gzreader/emulator/bookorbit_bookmarks.lua new file mode 100644 index 000000000..b577995c5 --- /dev/null +++ b/tools/gzreader/emulator/bookorbit_bookmarks.lua @@ -0,0 +1,95 @@ +-- BookOrbit page bookmarks, end to end (tests/mock_bookorbit.py on 127.0.0.1:18096; +-- GZ_EMU_BOOK = a real EPUB): a page dog-eared here reaches BookOrbit; a bookmark made +-- "elsewhere" dog-ears its page here; removing one here removes it there. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local BO = "http://127.0.0.1:18096" +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +local function rplugin() local R = require("apps/reader/readerui").instance; return R and R.gzreader end +local function http(method, path, body, headers) + local ltn12, json = require("ltn12"), require("gzreader_json") + local out = {} + local src = body and json.encode(body) or nil + local h = headers or {} + if src then h["Content-Type"] = "application/json"; h["Content-Length"] = #src end + local _, code = require("socket.http").request{ url = BO .. path, method = method, headers = h, + source = src and ltn12.source.string(src) or nil, sink = ltn12.sink.table(out) } + local ok, data = pcall(json.decode, table.concat(out)) + return code, ok and data or nil +end +local state = {} +add({ fn = function() + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" or w.name == "QR code screen" then UIManager:close(w) end + end +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + local src = os.getenv("GZ_EMU_BOOK") + state.path = p.store.library_dir .. "/Named by another server.epub" + local i, o = io.open(src, "rb"), io.open(state.path, "wb") + o:write(i:read("*a")); i:close(); o:close() + local BookOrbit = require("gzreader_bookorbit") + state.hash = BookOrbit.hashFile(state.path) + E.say("fingerprint:", tostring(state.hash ~= nil), "| the same as KOReader's own:", tostring(state.hash == require("util").partialMD5(state.path)), + "| file bytes:", tostring(require("libs/libkoreader-lfs").attributes(state.path, "size"))) + http("POST", "/_mock/set", { book_hashes = { ["101"] = state.hash } }) + local ok, err = p:connect(BO, "will-kindle", "hunter22", "bookorbit") + E.say("sign-in:", tostring(ok), tostring(err), "| progress synced:", tostring(p:serverCan("progress"))) + p:matchLibraryFiles() +end, after = 10 }) +add({ fn = function(E) + local e = plugin().store.downloads["101"] + E.say("matched to BookOrbit's book 101:", tostring(e ~= nil), "| path:", tostring(e and e.path:match("[^/]+$")), "| file id:", tostring(e and e.file_id)) + require("apps/reader/readerui"):showReader(state.path) +end, after = 18 }) +local function marks() + local n, list = 0, {} + for _i, a in ipairs(require("apps/reader/readerui").instance.annotation.annotations) do + if not a.drawer and not a.pos0 then n = n + 1; list[#list + 1] = tostring(a.pageno) .. ":" .. tostring(a.text):sub(1, 24) end + end + return n, table.concat(list, " | ") +end +local function server() + local _, st = http("GET", "/_mock/state") + return st and st.bookmarks and st.bookmarks["101"] or {} +end +add({ fn = function(E) + local R = require("apps/reader/readerui").instance + R:handleEvent(require("ui/event"):new("GotoPage", 5)) + R.bookmark:onToggleBookmark() + state.there = R.document:getPageXPointer(9) + E.say("page 5 dog-eared here; bookmarks in the book:", (marks()), "| module on:", tostring(rplugin().bookmarks:enabled())) +end, after = 12 }) +add({ fn = function(E) + local sv = server() + E.say("BookOrbit has:", #sv, "| place is an XPointer:", tostring(sv[1] and sv[1].pos:sub(1, 18))) + http("POST", "/_mock/set", { web_bookmark = { book = 101, op = "add", pos = state.there, pageno = 9, title = "From another device" } }) + rplugin().bookmarks:reconcile() +end, after = 10 }) +add({ fn = function(E) + local n, list = marks() + E.say("after a bookmark made elsewhere:", n, "|", list) + require("apps/reader/readerui").instance:handleEvent(require("ui/event"):new("GotoPage", 9)) +end, after = 3 }) +add({ shot = "bookorbit-bookmark-from-elsewhere" }) +add({ fn = function(E) + local R = require("apps/reader/readerui").instance + R.bookmark:onToggleBookmark() -- (page 9: off again) + E.say("page 9's dog-ear removed here; bookmarks in the book:", (marks())) +end, after = 12 }) +add({ fn = function(E) + local live, gone = 0, 0 + for _i, m in ipairs(server()) do if m.deleted then gone = gone + 1 else live = live + 1 end end + E.say("BookOrbit after the removal: live", live, "deleted", gone) + local log = io.open(require("datastorage"):getDataDir() .. "/gzreader.log", "rb") + local text = log and log:read("*a") or "" + if log then log:close() end + for line in text:gmatch("[^\n]+") do + if line:find("BookOrbit bookmark", 1, true) then E.say("log:", line:sub(1, 200)) end + end + require("apps/reader/readerui").instance:onHome() +end, after = 4 }) +return s diff --git a/tools/gzreader/emulator/bookorbit_browse.lua b/tools/gzreader/emulator/bookorbit_browse.lua new file mode 100644 index 000000000..38fba09af --- /dev/null +++ b/tools/gzreader/emulator/bookorbit_browse.lua @@ -0,0 +1,95 @@ +-- BookOrbit as the book server (tests/mock_bookorbit.py on 127.0.0.1:18096): +-- sign in with the KOReader sync user, then the Catalog's first page, the +-- libraries, All books and the menu's first line. Prints what each step found. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +local function browser() return require("gzreader_browser").current end +add({ fn = function() + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" or w.name == "QR code screen" then UIManager:close(w) end + end +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + -- a book downloaded from Grimmory before the switch: it must stay in the Downloads tab's list + local old = p.store.library_dir .. "/From Grimmory.epub" + local f = io.open(old, "wb"); f:write("a book from the other server"); f:close() + p.store.downloads["900"] = { path = old, title = "From Grimmory" } + local ok, err = p:connect("http://127.0.0.1:18096", "will-kindle", "wrong", "bookorbit") + E.say("wrong password:", tostring(ok), tostring(err)) + ok, err = p:connect("http://127.0.0.1:18096", "will-kindle", "hunter22", "bookorbit") + E.say("sign-in:", tostring(ok), tostring(err), "backend", p:backend(), "books only", tostring(p:booksOnly()), + "server", tostring((p.store.bookorbit or {}).server_version)) + p:announceConnected() + local fm = require("apps/filemanager/filemanager").instance + fm.file_chooser:changeToPath(p.store.library_dir) + local listed = false + for _i, it in ipairs(fm.file_chooser.item_table or {}) do + if tostring(it.path or ""):match("From Grimmory%.epub$") then listed = true end + end + E.say("the Grimmory book after the switch: in the Downloads list:", tostring(listed), "| linked to a server book:", + tostring(p.store.downloads["900"] ~= nil), "| put aside:", tostring(((p.store.downloads_other or {}).grimmory or {})["900"] ~= nil)) +end, after = 2 }) +add({ shot = "bookorbit-1-connected" }) +add({ fn = function() + local UIManager = require("ui/uimanager") + local top = UIManager._window_stack[#UIManager._window_stack].widget + if top and top.text then UIManager:close(top) end + plugin():onShowGrimmoryLibrary() +end, after = 12 }) +add({ shot = "bookorbit-2-catalog" }) +add({ fn = function() browser():openLibraries() end, after = 8 }) +add({ fn = function(E) + local m = browser().menu + local names = {} + for _i, it in ipairs(m and m.item_table or {}) do names[#names + 1] = tostring(it.text) .. "=" .. tostring(it.mandatory or it.gz_count) end + E.say("libraries:", table.concat(names, ", ")) +end }) +add({ shot = "bookorbit-3-libraries" }) +add({ fn = function() browser():openPaged("All books", { sort = "title", dir = "asc" }) end, after = 12 }) +add({ fn = function(E) + local m = browser().menu + local names = {} + for _i, it in ipairs(m and m.item_table or {}) do names[#names + 1] = tostring(it.text) end + E.say("all books:", #names, table.concat(names, " | ")) +end }) +add({ shot = "bookorbit-4-all-books" }) +-- a download through the plugin (quietly, as the shelf's auto-download does), then that auto-download +add({ fn = function() + require("gzreader_download").background = true + plugin():downloadAndOpen({ id = 101, title = "The Long Way Round", authors = { "Ada Marsh" }, primaryFileType = "EPUB", + primaryFileName = "The Long Way Round.epub" }, nil) +end, after = 20 }) +add({ fn = function(E) + local e = plugin().store.downloads["101"] + local lfs = require("libs/libkoreader-lfs") + E.say("downloaded 101:", tostring(e and e.path and e.path:match("[^/]+$")), "bytes", tostring(e and lfs.attributes(e.path, "size")), + "file id", tostring(e and e.file_id)) + local SS = require("gzreader_shelfsync") + SS.set(plugin(), { id = 11, name = "Beach reads" }) + SS.run(plugin(), true) +end, after = 25 }) +add({ fn = function(E) + local got = {} + for id, e in pairs(plugin().store.downloads) do got[#got + 1] = id .. "=" .. tostring(e.path and e.path:match("[^/]+$")) end + table.sort(got) + E.say("after the shelf's auto-download:", table.concat(got, ", ")) + local UIManager = require("ui/uimanager") + local top = UIManager._window_stack[#UIManager._window_stack].widget + if top and top.text then UIManager:close(top) end + require("apps/filemanager/filemanager").instance.gzreader:onShowGrimmoryLibrary() +end, after = 8 }) +add({ shot = "bookorbit-5-after-downloads" }) +add({ fn = function(E) + local p = plugin() + E.say("menu:", p:menuItems()[1].text_func(), "| sync:", tostring(p:syncEnabled()), "| covers:", require("gzreader_covers").dir():match("[^/]+$")) + local log = io.open(require("datastorage"):getDataDir() .. "/gzreader.log", "rb") + local text = log and log:read("*a") or "" + if log then log:close() end + E.say("log has the password:", tostring(text:find("hunter22", 1, true) ~= nil), "its MD5:", + tostring(text:find(require("ffi/sha2").md5("hunter22"), 1, true) ~= nil), "x-auth-key:", tostring(text:find("x-auth-key", 1, true) ~= nil)) +end }) +return s diff --git a/tools/gzreader/emulator/bookorbit_highlights.lua b/tools/gzreader/emulator/bookorbit_highlights.lua new file mode 100644 index 000000000..c986deebc --- /dev/null +++ b/tools/gzreader/emulator/bookorbit_highlights.lua @@ -0,0 +1,102 @@ +-- BookOrbit highlights, end to end (tests/mock_bookorbit.py on 127.0.0.1:18096; +-- GZ_EMU_BOOK = a real EPUB): the book is matched and opened; a highlight with a note +-- made here reaches BookOrbit; one made "on the web" appears in the book; a note added +-- on the web arrives; a highlight removed here is removed there. Prints what each step found. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local BO = "http://127.0.0.1:18096" +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +local function rplugin() local R = require("apps/reader/readerui").instance; return R and R.gzreader end +local function http(method, path, body, headers) + local ltn12, json = require("ltn12"), require("gzreader_json") + local out = {} + local src = body and json.encode(body) or nil + local h = headers or {} + if src then h["Content-Type"] = "application/json"; h["Content-Length"] = #src end + local _, code = require("socket.http").request{ url = BO .. path, method = method, headers = h, + source = src and ltn12.source.string(src) or nil, sink = ltn12.sink.table(out) } + local ok, data = pcall(json.decode, table.concat(out)) + return code, ok and data or nil +end +local state = {} +add({ fn = function() + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" or w.name == "QR code screen" then UIManager:close(w) end + end +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + local src = os.getenv("GZ_EMU_BOOK") + state.path = p.store.library_dir .. "/Named by another server.epub" + local i, o = io.open(src, "rb"), io.open(state.path, "wb") + o:write(i:read("*a")); i:close(); o:close() + local BookOrbit = require("gzreader_bookorbit") + state.hash = BookOrbit.hashFile(state.path) + E.say("fingerprint:", tostring(state.hash ~= nil), "| the same as KOReader's own:", tostring(state.hash == require("util").partialMD5(state.path)), + "| file bytes:", tostring(require("libs/libkoreader-lfs").attributes(state.path, "size"))) + http("POST", "/_mock/set", { book_hashes = { ["101"] = state.hash } }) + local ok, err = p:connect(BO, "will-kindle", "hunter22", "bookorbit") + E.say("sign-in:", tostring(ok), tostring(err), "| progress synced:", tostring(p:serverCan("progress"))) + p:matchLibraryFiles() +end, after = 10 }) +add({ fn = function(E) + local e = plugin().store.downloads["101"] + E.say("matched to BookOrbit's book 101:", tostring(e ~= nil), "| path:", tostring(e and e.path:match("[^/]+$")), "| file id:", tostring(e and e.file_id)) + require("apps/reader/readerui"):showReader(state.path) +end, after = 18 }) +local function annos() return require("apps/reader/readerui").instance.annotation.annotations end +local function server() + local _, st = http("GET", "/_mock/state") + return st and st.annotations and st.annotations["101"] or {} +end +add({ fn = function(E) + local R = require("apps/reader/readerui").instance + local doc = R.document + state.a, state.b, state.c = doc:getPageXPointer(3), doc:getPageXPointer(4), doc:getPageXPointer(6) + local item = { datetime = os.date("%Y-%m-%d %H:%M:%S"), drawer = "lighten", color = "yellow", text = "made on the Kindle", note = "a note from the Kindle", + page = state.a, pos0 = state.a, pos1 = state.b, chapter = "One", pageno = 3 } + R.annotation:addItem(item) + R:handleEvent(require("ui/event"):new("AnnotationsModified", { item, nb_highlights_added = 1 })) + E.say("a highlight made here; highlights in the book:", #annos(), "| module:", tostring(rplugin().annotations and rplugin().annotations.enabled and rplugin().annotations:enabled())) +end, after = 12 }) +add({ fn = function(E) + local sv = server() + E.say("BookOrbit has:", #sv, "|", tostring(sv[1] and sv[1].text), "| note:", tostring(sv[1] and sv[1].note), "| style:", tostring(sv[1] and sv[1].drawer)) + state.first = sv[1] and sv[1].serverId + local code, web = http("POST", "/_mock/set", { web_highlight = { book = 101, op = "add", pos0 = state.c, pos1 = state.c, text = "made on the web", color = "blue", + datetime = "2026-11-22 10:00:00" } }) + http("POST", "/_mock/set", { web_highlight = { book = 101, op = "edit", serverId = state.first, note = "changed on the web" } }) + state.web = web and web.serverId + E.say("the web added one and changed the first one's note:", tostring(code)) + rplugin().annotations:run() +end, after = 12 }) +add({ fn = function(E) + local out = {} + for _i, a in ipairs(annos()) do out[#out + 1] = tostring(a.text) .. " / " .. tostring(a.note) .. " / " .. tostring(a.color) end + E.say("in the book now:", #annos(), "|", table.concat(out, " | ")) + require("apps/reader/readerui").instance:handleEvent(require("ui/event"):new("GotoPage", 6)) +end, after = 3 }) +add({ shot = "bookorbit-highlight-from-web" }) +add({ fn = function(E) + local R = require("apps/reader/readerui").instance + local list = annos() + local gone + for i, a in ipairs(list) do if a.text == "made on the Kindle" then gone = table.remove(list, i) break end end + R:handleEvent(require("ui/event"):new("AnnotationsModified", { gone, nb_highlights_added = -1 })) + E.say("removed here:", tostring(gone ~= nil)) +end, after = 12 }) +add({ fn = function(E) + local n_deleted, n_live = 0, 0 + for _i, a in ipairs(server()) do if a.deleted then n_deleted = n_deleted + 1 else n_live = n_live + 1 end end + E.say("BookOrbit after the removal: live", n_live, "deleted", n_deleted) + local log = io.open(require("datastorage"):getDataDir() .. "/gzreader.log", "rb") + local text = log and log:read("*a") or "" + if log then log:close() end + for line in text:gmatch("[^\n]+") do + if line:find("BookOrbit highlight", 1, true) then E.say("log:", line:sub(1, 200)) end + end + require("apps/reader/readerui").instance:onHome() +end, after = 4 }) +return s diff --git a/tools/gzreader/emulator/bookorbit_key_signin.lua b/tools/gzreader/emulator/bookorbit_key_signin.lua new file mode 100644 index 000000000..9e132021c --- /dev/null +++ b/tools/gzreader/emulator/bookorbit_key_signin.lua @@ -0,0 +1,36 @@ +-- BookOrbit with only an API key (tests/mock_bookorbit.py on 127.0.0.1:18096): the key +-- fetches the e-reader sign-in (out of the server's plugin zip) and the Kindle signs in +-- with it; then the same with no sign-in on the server, where one is made. Prints what +-- each step found. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +local KEY = "bok_" .. string.rep("a1B2c3D4e5", 4) .. "f6G7h8I9j" +add({ fn = function() + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" or w.name == "QR code screen" then UIManager:close(w) end + end +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + local ok, err = p:connectWithApiKey("http://127.0.0.1:18096", KEY) + local list = p.api:listBooks{ page = 0, size = 20 } + E.say("with a sign-in on the server:", tostring(ok), tostring(err), "| as", tostring(p.store.username), "| key kept:", tostring(p.api:hasApiKey()), + "| books:", tostring(list and #list.content)) +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + local Api = require("gzreader_api") + Api.rawRequest("POST", "http://127.0.0.1:18096/_mock/set", { body = { ko_credentials = false } }) + p.api:clearTokens() + local ok, err = p:connectWithApiKey("http://127.0.0.1:18096", KEY) + local list = p.api:listBooks{ page = 0, size = 20 } + E.say("with none on the server:", tostring(ok), tostring(err), "| as", tostring(p.store.username), "| books:", tostring(list and #list.content)) + local log = io.open(require("datastorage"):getDataDir() .. "/gzreader.log", "rb") + local text = log and log:read("*a") or "" + if log then log:close() end + E.say("log has the API key:", tostring(text:find(KEY, 1, true) ~= nil), "| the sync key:", tostring(text:find(tostring(p.store.bookorbit and p.store.bookorbit.key), 1, true) ~= nil)) +end, after = 4 }) +return s diff --git a/tools/gzreader/emulator/bookorbit_progress.lua b/tools/gzreader/emulator/bookorbit_progress.lua new file mode 100644 index 000000000..d170f5098 --- /dev/null +++ b/tools/gzreader/emulator/bookorbit_progress.lua @@ -0,0 +1,86 @@ +-- BookOrbit reading progress, end to end (tests/mock_bookorbit.py on 127.0.0.1:18096; +-- GZ_EMU_BOOK = a real EPUB). The EPUB is put in the books folder as if it came from +-- another server; BookOrbit is told it has that file (by fingerprint); then: sign in, +-- the book is matched, opened, a place is sent, and a later place from "another +-- device" is jumped to. Prints what each step found. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local BO = "http://127.0.0.1:18096" +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +local function rplugin() local R = require("apps/reader/readerui").instance; return R and R.gzreader end +local function http(method, path, body, headers) + local ltn12, json = require("ltn12"), require("gzreader_json") + local out = {} + local src = body and json.encode(body) or nil + local h = headers or {} + if src then h["Content-Type"] = "application/json"; h["Content-Length"] = #src end + local _, code = require("socket.http").request{ url = BO .. path, method = method, headers = h, + source = src and ltn12.source.string(src) or nil, sink = ltn12.sink.table(out) } + local ok, data = pcall(json.decode, table.concat(out)) + return code, ok and data or nil +end +local state = {} +add({ fn = function() + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" or w.name == "QR code screen" then UIManager:close(w) end + end +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + local src = os.getenv("GZ_EMU_BOOK") + state.path = p.store.library_dir .. "/Named by another server.epub" + local i, o = io.open(src, "rb"), io.open(state.path, "wb") + o:write(i:read("*a")); i:close(); o:close() + local BookOrbit = require("gzreader_bookorbit") + state.hash = BookOrbit.hashFile(state.path) + E.say("fingerprint:", tostring(state.hash ~= nil), "| the same as KOReader's own:", tostring(state.hash == require("util").partialMD5(state.path)), + "| file bytes:", tostring(require("libs/libkoreader-lfs").attributes(state.path, "size"))) + http("POST", "/_mock/set", { book_hashes = { ["101"] = state.hash } }) + local ok, err = p:connect(BO, "will-kindle", "hunter22", "bookorbit") + E.say("sign-in:", tostring(ok), tostring(err), "| progress synced:", tostring(p:serverCan("progress"))) + p:matchLibraryFiles() +end, after = 10 }) +add({ fn = function(E) + local e = plugin().store.downloads["101"] + E.say("matched to BookOrbit's book 101:", tostring(e ~= nil), "| path:", tostring(e and e.path:match("[^/]+$")), "| file id:", tostring(e and e.file_id)) + require("apps/reader/readerui"):showReader(state.path) +end, after = 18 }) +add({ fn = function(E) + local R = require("apps/reader/readerui").instance + local Event = require("ui/event") + R:handleEvent(Event:new("GotoPage", 7)) + state.far = { xp = R.document:getPageXPointer(15), pages = R.document:getPageCount() } + E.say("open; sync running:", tostring(rplugin() and rplugin().sync ~= nil), "| pages:", tostring(state.far.pages)) +end, after = 3 }) +add({ fn = function() rplugin().sync:push(true) end, after = 8 }) +add({ fn = function(E) + local _, st = http("GET", "/_mock/state") + local sent = st and st.progress[state.hash] + local R = require("apps/reader/readerui").instance + local last = R.rolling:getLastPercent() + E.say("BookOrbit has:", tostring(sent and sent.percentage), "| KOReader's own percentage:", tostring(last), + "| place is an XPointer:", tostring(sent and tostring(sent.progress):sub(1, 18)), "| device:", tostring(sent and sent.device)) + -- another device reads on: page 15 + local md5 = require("ffi/sha2").md5 + local code = http("PUT", "/api/v1/koreader/syncs/progress", { document = state.hash, percentage = 15 / state.far.pages, progress = state.far.xp, + device = "Another reader", device_id = "other-1" }, { ["x-auth-user"] = "will-kindle", ["x-auth-key"] = md5("hunter22") }) + E.say("another device sent page 15:", tostring(code)) + rplugin().sync:pull(true) +end, after = 10 }) +add({ fn = function(E) + local R = require("apps/reader/readerui").instance + E.say("after the pull, this Kindle is on page:", tostring(R.rolling.current_page)) +end, after = 1 }) +add({ shot = "bookorbit-progress-jumped" }) +add({ fn = function(E) + local log = io.open(require("datastorage"):getDataDir() .. "/gzreader.log", "rb") + local text = log and log:read("*a") or "" + if log then log:close() end + for line in text:gmatch("[^\n]+") do + if line:find("sync pull book", 1, true) or line:find("BookOrbit: matched", 1, true) then E.say("log:", line:sub(1, 200)) end + end + require("apps/reader/readerui").instance:onHome() +end, after = 4 }) +return s diff --git a/tools/gzreader/emulator/bookorbit_requests.lua b/tools/gzreader/emulator/bookorbit_requests.lua new file mode 100644 index 000000000..9546843c9 --- /dev/null +++ b/tools/gzreader/emulator/bookorbit_requests.lua @@ -0,0 +1,58 @@ +-- BookOrbit book requests (tests/mock_bookorbit.py on 127.0.0.1:18096): sign in, enter the +-- API key, open the Catalog's BookOrbit card, the request form, send two requests and +-- show the list and one request's details. Prints what each step found. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +local KEY = "bok_" .. string.rep("a1B2c3D4e5", 4) .. "f6G7h8I9j" +local function closeTop(name) + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if not name or w.name == name then UIManager:close(w) return true end + end +end +add({ fn = function() + closeTop("setup guide"); closeTop("QR code screen") +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + local ok, err = p:connect("http://127.0.0.1:18096", "will-kindle", "hunter22", "bookorbit") + local k_ok, k_err = p:setBookOrbitApiKey(KEY) + E.say("sign-in:", tostring(ok), tostring(err), "| key:", tostring(k_ok), tostring(k_err)) + local UIManager = require("ui/uimanager") + local top = UIManager._window_stack[#UIManager._window_stack].widget + if top and top.text then UIManager:close(top) end + p:onShowGrimmoryLibrary() +end, after = 8 }) +add({ fn = function(E) + local B = require("gzreader_browser") + local b = B.instance or B.current + E.say("browser:", tostring(b ~= nil)) + if b then b:openGrimmory() end +end, after = 4 }) +add({ shot = "requests-1-card" }) +add({ fn = function() require("gzreader_bo_requests").ask(plugin()) end, after = 4 }) +add({ shot = "requests-2-form" }) +add({ fn = function(E) + local Rq = require("gzreader_bo_requests") + local UIManager = require("ui/uimanager") + if Rq.dialog then UIManager:close(Rq.dialog) end + local p = plugin() + local a = p.api:requestBook("The Salt Road", { "Ines Ward" }, "ebook") + local b = p.api:requestBook("Low Tide: Notes from a Northern Shore", { "Mara Quill" }, "audiobook") + E.say("requested:", tostring(a and a.status), tostring(b and b.status)) + local B = require("gzreader_browser") + local br = B.instance or B.current + if br then Rq.open(br) end +end, after = 6 }) +add({ shot = "requests-3-list" }) +add({ fn = function(E) + local B = require("gzreader_browser") + local br = B.instance or B.current + local it = br and br.menu and br.menu.item_table and br.menu.item_table[2] + E.say("row:", tostring(it and it.text), tostring(it and it.mandatory)) + if it then it.callback() end +end, after = 4 }) +add({ shot = "requests-4-detail" }) +return s diff --git a/tools/gzreader/emulator/bookorbit_speed.lua b/tools/gzreader/emulator/bookorbit_speed.lua new file mode 100644 index 000000000..fe00c4821 --- /dev/null +++ b/tools/gzreader/emulator/bookorbit_speed.lua @@ -0,0 +1,121 @@ +-- Is a Kindle as quick signed in to BookOrbit as signed in to nothing? (tests/mock_bookorbit.py +-- on 127.0.0.1:18096; GZ_EMU_BOOK = a real EPUB.) The same book is opened, read for 20 +-- page turns and closed twice: before signing in, and signed in to BookOrbit with the +-- book matched (so progress, highlights, bookmarks and reading time all sync). Prints each +-- phase's CPU time in this process, the background jobs started, and which of GZreader's +-- modules were loaded by the end. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local BO = "http://127.0.0.1:18096" +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +local state = { jobs = {} } +local function cpu(E) return os.clock() - E.clock0 end + +local function round(name) + add({ fn = function(E) + state.c0, state.n0 = cpu(E), #state.jobs + require("apps/reader/readerui"):showReader(state.path) + end, after = 1 }) + add({ wait_for = function() + local ui = require("apps/reader/readerui").instance + return ui and ui.document and ui.document:getCurrentPage() ~= nil + end, timeout = 90, after = 10 }) + add({ fn = function(E) state.open = cpu(E) - state.c0; state.c0 = cpu(E) end, after = 0.2 }) + for _i = 1, 20 do + add({ fn = function(E) + if not pcall(E.key, "RPgFwd") then + local Screen = require("device").screen + E.tap({ Screen:getWidth() * 0.9, Screen:getHeight() / 2 }) + end + end, after = 2 }) + end + add({ fn = function(E) state.turns = cpu(E) - state.c0; state.c0 = cpu(E) end, after = 0.2 }) + add({ fn = function(E) + if not pcall(E.key, "Home") then require("ui/uimanager"):sendEvent(require("ui/event"):new("Home")) end + end, after = 12 }) + add({ fn = function(E) + local tags = {} + for i = state.n0 + 1, #state.jobs do tags[#tags + 1] = state.jobs[i] end + E.say(string.format("SPEED %s: open %.2f s, 20 page turns %.2f s, close %.2f s CPU | background jobs: %d (%s)", + name, state.open, state.turns, cpu(E) - state.c0, #tags, table.concat(tags, ", "))) + end, after = 1 }) +end + +add({ fn = function(E) + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" or w.name == "QR code screen" then UIManager:close(w) end + end + local p = plugin() + state.path = p.store.library_dir .. "/Speed test.epub" + local i, o = io.open(os.getenv("GZ_EMU_BOOK"), "rb"), io.open(state.path, "wb") + o:write(i:read("*a")); i:close(); o:close() + -- count what's handed to the background + local Async = require("gzreader_async") + local run = Async.run + Async.run = function(api, fn, cb, tag, ...) + state.jobs[#state.jobs + 1] = tostring(tag or "?") + return run(api, fn, cb, tag, ...) + end + -- every request, from this process and the background ones (they inherit this), to a file + local Api = require("gzreader_api") + local raw = Api.rawRequest + state.reqs = require("datastorage"):getDataDir() .. "/speed-requests.txt" + os.remove(state.reqs) + Api.rawRequest = function(method, url, ...) + local f = io.open(state.reqs, "a") + if f then f:write(method, " ", (tostring(url):gsub("^https?://[^/]+", ""):gsub("%?.*$", ""):gsub("%x%x%x%x%x%x%x%x%x%x+", ""):gsub("%d+", "N")), "\n"); f:close() end + return raw(method, url, ...) + end + local before = {} + for k in pairs(package.loaded) do if tostring(k):match("^gzreader_") then before[k] = true end end + state.before = before + E.say("ready") +end, after = 6 }) +round("signed in to nothing") +round("signed in to nothing, again") +add({ fn = function(E) + local p = plugin() + local hash = require("gzreader_bookorbit").hashFile(state.path) + require("gzreader_api").rawRequest("POST", BO .. "/_mock/set", { body = { book_hashes = { ["101"] = hash } } }) + local ok, err = p:connect(BO, "will-kindle", "hunter22", "bookorbit") + local UIManager = require("ui/uimanager") + local top = UIManager._window_stack[#UIManager._window_stack].widget + if top and top.text then UIManager:close(top) end + p:matchLibraryFiles() + E.say("sign-in:", tostring(ok), tostring(err)) +end, after = 12 }) +add({ fn = function(E) + E.say("matched:", tostring(plugin().store.downloads["101"] ~= nil)) +end, after = 1 }) +round("BookOrbit") +round("BookOrbit, again") +add({ fn = function(E) + local new, all = {}, 0 + for k in pairs(package.loaded) do + if tostring(k):match("^gzreader_") then + all = all + 1 + if not state.before[k] then new[#new + 1] = k end + end + end + table.sort(new) + E.say("GZreader modules loaded:", all, "| loaded since signing in:", table.concat(new, " ")) + local grim = {} + for _i, k in ipairs{ "gzreader_bookmarks", "gzreader_annotations", "gzreader_cfi", "gzreader_copy", "gzreader_sso", "gzreader_migrate", "gzreader_sessions" } do + grim[#grim + 1] = k .. "=" .. tostring(package.loaded[k] ~= nil) + end + E.say("Grimmory-only modules loaded:", table.concat(grim, " ")) + local counts, order = {}, {} + local f = io.open(state.reqs, "r") + for line in (f and f:lines() or function() end) do + if not counts[line] then order[#order + 1] = line end + counts[line] = (counts[line] or 0) + 1 + end + if f then f:close() end + for i, line in ipairs(order) do order[i] = counts[line] .. "x " .. line end + E.say("requests made (" .. #order .. " kinds):", table.concat(order, " | ")) + collectgarbage(); collectgarbage() + E.say(string.format("Lua memory: %.1f MB", collectgarbage("count") / 1024)) +end, after = 1 }) +return s diff --git a/tools/gzreader/emulator/bookorbit_stats.lua b/tools/gzreader/emulator/bookorbit_stats.lua new file mode 100644 index 000000000..52c674498 --- /dev/null +++ b/tools/gzreader/emulator/bookorbit_stats.lua @@ -0,0 +1,61 @@ +-- BookOrbit reading time, end to end (tests/mock_bookorbit.py on 127.0.0.1:18096; +-- GZ_EMU_BOOK = a real EPUB): pages are read in a real book, KOReader's statistics +-- plugin writes them to its database, and after the book closes GZreader reads that +-- database (the real SQLite) and sends the rows to BookOrbit. Prints what each step found. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local BO = "http://127.0.0.1:18096" +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +local function http(method, path, body) + local ltn12, json = require("ltn12"), require("gzreader_json") + local out = {} + local src = body and json.encode(body) or nil + local h = {} + if src then h["Content-Type"] = "application/json"; h["Content-Length"] = #src end + local _, code = require("socket.http").request{ url = BO .. path, method = method, headers = h, + source = src and ltn12.source.string(src) or nil, sink = ltn12.sink.table(out) } + local ok, data = pcall(json.decode, table.concat(out)) + return code, ok and data or nil +end +local state = {} +add({ fn = function() + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" or w.name == "QR code screen" then UIManager:close(w) end + end +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + state.path = p.store.library_dir .. "/A real book.epub" + local i, o = io.open(os.getenv("GZ_EMU_BOOK"), "rb"), io.open(state.path, "wb") + o:write(i:read("*a")); i:close(); o:close() + state.hash = require("gzreader_bookorbit").hashFile(state.path) + http("POST", "/_mock/set", { book_hashes = { ["101"] = state.hash } }) + local ok, err = p:connect(BO, "will-kindle", "hunter22", "bookorbit") + E.say("sign-in:", tostring(ok), tostring(err), "| reading time synced:", tostring(p:serverCan("stats"))) + p:matchLibraryFiles() +end, after = 10 }) +add({ fn = function() require("apps/reader/readerui"):showReader(state.path) end, after = 16 }) +for page = 2, 6 do + add({ fn = function() require("apps/reader/readerui").instance:handleEvent(require("ui/event"):new("GotoPage", page)) end, after = 7 }) +end +add({ fn = function(E) + local R = require("apps/reader/readerui").instance + E.say("read five pages; statistics plugin on:", tostring(R.statistics ~= nil and R.statistics.settings and R.statistics.settings.is_enabled)) + R:onHome() +end, after = 16 }) +add({ fn = function(E) + local _, st = http("GET", "/_mock/state") + local rows = st and st.page_stats and st.page_stats[state.hash] or {} + local first = rows[1] or {} + E.say("BookOrbit has page rows:", #rows, "| first: page", tostring(first[1]), "seconds", tostring(first[3]), "of", tostring(first[4]), "pages", + "| remembered up to:", tostring((plugin().store.bookorbit_stats or {})[state.hash] ~= nil)) + local log = io.open(require("datastorage"):getDataDir() .. "/gzreader.log", "rb") + local text = log and log:read("*a") or "" + if log then log:close() end + for line in text:gmatch("[^\n]+") do + if line:find("BookOrbit reading time", 1, true) then E.say("log:", line:sub(1, 160)) end + end +end }) +return s diff --git a/tools/gzreader/emulator/server_stats.lua b/tools/gzreader/emulator/server_stats.lua new file mode 100644 index 000000000..a0d2e6d0f --- /dev/null +++ b/tools/gzreader/emulator/server_stats.lua @@ -0,0 +1,52 @@ +-- The reading stats page (gzreader_statspage.lua): BookOrbit's numbers fetched from +-- tests/mock_bookorbit.py on 127.0.0.1:18096 and shown on Home's widget and on the page a +-- tap opens; then the page as it is with Grimmory's numbers (made up here, no server). +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +add({ fn = function() + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" or w.name == "QR code screen" then UIManager:close(w) end + end +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + local ok, err = p:connect("http://127.0.0.1:18096", "will-kindle", "hunter22", "bookorbit") + local UIManager = require("ui/uimanager") + local top = UIManager._window_stack[#UIManager._window_stack].widget + if top and top.text then UIManager:close(top) end + require("gzreader_grimstats").refresh(p, true) + E.say("sign-in:", tostring(ok), tostring(err)) +end, after = 8 }) +add({ fn = function(E) + local p = plugin() + local all = require("gzreader_grimstats").all(p) + E.say("stats from:", all.name, "| streak", tostring(all.values.streak), "| today", tostring(all.values.today_time), "| goal", tostring(all.values.goal), + "| days kept", tostring(all.detail.days and #all.detail.days.minutes)) + pcall(function() require("common/gz_view").redrawHome() end) +end, after = 4 }) +add({ shot = "stats-1-home" }) +add({ fn = function(E) + local page = rawget(_G, "__GZ_SERVER_STATS_PAGE")() + E.say("BookOrbit page: sections shown", tostring(page and page.sections_shown)) +end, after = 4 }) +add({ shot = "stats-2-bookorbit" }) +add({ fn = function(E) + local UIManager = require("ui/uimanager") + local Page = require("gzreader_statspage") + if Page.current then UIManager:close(Page.current) end + local d = os.date("*t") + local page = Page.show(plugin(), { server = "grimmory", name = "Grimmory", at = os.time() - 1500, + values = { streak = 6, longest_streak = 19, reading_days = 212, week_time = 5 * 3600 + 1200, week_books = 3, month_sessions = 31, year_finished = 14 }, + detail = { year = d.year, month = d.month, + week_books = { { title = "The Salt Road", seconds = 9800 }, { title = "Low Tide: Notes from a Northern Shore", seconds = 6100 }, { title = "A Field Guide to Getting Lost", seconds = 3300 } }, + month_days = { { day = 1, count = 2 }, { day = 2, count = 1 }, { day = 4, count = 3 }, { day = 5, count = 1 }, { day = 8, count = 4 }, { day = 9, count = 2 }, + { day = 12, count = 1 }, { day = 13, count = 2 }, { day = 15, count = 5 }, { day = 16, count = 1 }, { day = 19, count = 2 }, { day = 20, count = 3 }, { day = 21, count = 1 } }, + finished_months = { { month = 1, finished = 1 }, { month = 2, finished = 2 }, { month = 4, finished = 1 }, { month = 5, finished = 3 }, { month = 7, finished = 2 }, + { month = 8, finished = 1 }, { month = 9, finished = 2 }, { month = 10, finished = 1 }, { month = 11, finished = 1 } } } }) + E.say("Grimmory page: sections shown", tostring(page and page.sections_shown)) +end, after = 4 }) +add({ shot = "stats-3-grimmory" }) +return s diff --git a/tools/gzreader/emulator/setup_how.lua b/tools/gzreader/emulator/setup_how.lua new file mode 100644 index 000000000..c2da7c24d --- /dev/null +++ b/tools/gzreader/emulator/setup_how.lua @@ -0,0 +1,34 @@ +-- The setup guide's first question (How will you use GZreader?) and the page +-- that follows each answer. A fresh install: the guide is on screen at start. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local function guide() + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" then return w end + end +end +local function answer(E, id, what) + local g = guide() + if not g then return E.say(what, "no setup guide") end + if g._page_idx > 1 then g:_prevPage() end + g._selections[1] = { [id] = true } + g:_nextPage() + local page = g.pages[g._page_idx] + local ids = {} + for _i, c in ipairs(page.choices or {}) do ids[#ids + 1] = c.id .. ((g._selections[g._page_idx] or {})[c.id] and "*" or "") end + E.say(what, "->", tostring(page.title), "|", table.concat(ids, ","), "| saved:", tostring(require("apps/filemanager/filemanager").instance.gzreader.store.book_source)) +end +add({ fn = function(E) + local g = guide() + E.say("first page:", tostring(g and g.pages[g._page_idx].title), "of", tostring(g and g._total)) +end, after = 2 }) +add({ shot = "how-1-question" }) +add({ fn = function(E) answer(E, "grimmory", "Grimmory") end, after = 3 }) +add({ shot = "how-2-grimmory" }) +add({ fn = function(E) answer(E, "bookorbit", "BookOrbit") end, after = 3 }) +add({ shot = "how-3-bookorbit" }) +add({ fn = function(E) answer(E, "local", "on its own") end, after = 3 }) +add({ shot = "how-4-on-its-own" }) +return s diff --git a/tools/gzreader/tests/mock_bookorbit.py b/tools/gzreader/tests/mock_bookorbit.py new file mode 100644 index 000000000..4ed228f6b --- /dev/null +++ b/tools/gzreader/tests/mock_bookorbit.py @@ -0,0 +1,1170 @@ +"""Mock BookOrbit server: the routes GZreader's BookOrbit backend uses. + +A book's file is listed with role "primary" (the book's main file) or "content" +(another of its files), as a real server (v3.9.0, probed 2026-11-22) does; both +download. + +Shapes and checks follow BookOrbit's source at commit e60ab43 (2026-11-21; +github.com/bookorbit/bookorbit: server/src/modules/koreader, .../audiobook, +packages/types/src/koreader.ts and audiobook.ts). Nothing of BookOrbit's code +is copied: this is a stand-in written from its routes and field names. + +Two sign-ins, as the real server: + * the KOReader API (/api/v1/koreader/...): headers x-auth-user and + x-auth-key (the password, or its MD5 as KOSync clients send); + * the main API (/api/v1/auth/me, /api/v1/audiobooks/...): an API key + ("bok_" + 49 characters) as Authorization: Bearer or X-Api-Key. + + python3 -I mock_bookorbit.py + +Control routes for tests (no sign-in): GET /_mock/state, POST /_mock/set +(a JSON object merged into STATE's switches), POST /_mock/reset. +""" +import hashlib, io, json, re, sys, time, zipfile +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlparse, parse_qs, quote + +KO_USER, KO_PASSWORD = "will-kindle", "hunter22" +KO_KEY = hashlib.md5(KO_PASSWORD.encode()).hexdigest() +API_KEY = "bok_" + "a1B2c3D4e5" * 4 + "f6G7h8I9j" # 53 characters +MD5 = re.compile(r"^[0-9a-f]{32}$", re.I) +DEVICE_ID = re.compile(r"^[A-Za-z0-9_-]{1,100}$") +DEVICE_TIME = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$") +ASSET_ID = re.compile(r"^aud_[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.I) +UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.I) +ISO = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$") +CAPABILITIES = ["catalogBulkManifest", "catalogDashboardSections", "bookmarkSync", "readAloudDeliveryVariants", + "readAloudDeliverySettings", "catalogListsV2", "catalogPublishedSort", "sidecarState", + "annotationPendingBooks", "catalogBooksQuery"] +SORTS = {"title", "author", "published", "recently_added", "recently_updated", "recently_read", "series"} + +# The "book files": their bytes are what a download returns. fileHash here is the +# file's MD5 (the real server's is KOReader's partial MD5; the tests only need the +# two ends to agree). +def _png(w, h): + """A plain cover: light grey with a dark edge (stdlib only).""" + import struct, zlib + rows = b"".join(b"\0" + bytes(60 if x < 3 or y < 3 or x >= w - 3 or y >= h - 3 else 205 for x in range(w)) for y in range(h)) + def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 0, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"") + + +PNG = _png(120, 168) + + +def book(i, title, authors, library, series=None, idx=None, fmt="epub", collections=()): + data = ("%s by %s\n" % (title, ", ".join(authors))).encode() * 40 + return {"id": i, "title": title, "authors": authors, "libraryId": library, "seriesName": series, + "seriesId": (900 + sum(map(ord, series)) % 90) if series else None, "seriesIndex": idx, + "format": fmt, "fileId": 5000 + i, "data": data, "hash": hashlib.md5(data).hexdigest(), + "collections": list(collections), "addedAt": "2026-10-%02dT08:00:00.000Z" % (i % 27 + 1), + "updatedAt": "2026-11-%02dT09:30:00.000Z" % (i % 20 + 1)} + + +LIBRARIES = {1: "Fiction", 2: "Non-fiction"} +COLLECTIONS = {11: "Beach reads", 12: "Book club"} +COLLECTION_OWNERS = {} # collection id -> user id, for the ones that aren't the signed-in user's (id 1) +BOOKS = [ + book(101, "The Long Way Round", ["Ada Marsh"], 1, "Waymarks", 1, collections=[11]), + book(102, "The Short Way Back", ["Ada Marsh"], 1, "Waymarks", 2), + book(103, "A Field Guide to Fog", ["Ben Okafor"], 2, collections=[12]), + book(104, "Night Trains", ["Clara Voss", "Ben Okafor"], 1, collections=[11, 12]), + book(105, "Tide Tables", ["Dmitri Hale"], 2, fmt="pdf"), +] +AUDIOBOOK = { + "id": 201, "title": "The Long Way Round", "authors": ["Ada Marsh"], "narrators": ["June Park"], + "assets": [ + {"assetId": "aud_11111111-1111-4111-8111-111111111111", "fileId": 6201, "sequence": 0, "format": "mp3", + "durationMs": 60000, "data": b"ID3" + b"\0" * 4000}, + {"assetId": "aud_22222222-2222-4222-8222-222222222222", "fileId": 6202, "sequence": 1, "format": "mp3", + "durationMs": 45000, "data": b"ID3" + b"\1" * 3000}, + ], +} +# A second audiobook: one M4B file with chapters inside it (and a book that is also ebook 102). +AUDIOBOOK_2 = { + "id": 102, "title": "The Short Way Back", "authors": ["Ada Marsh"], "narrators": ["June Park", "Sam Lee"], + "assets": [{"assetId": "aud_33333333-3333-4333-8333-333333333333", "fileId": 6301, "sequence": 0, "format": "m4b", + "durationMs": 600000, "data": b"\0\0\0\x20ftypM4B " + b"\2" * 5000}], + "chapters": [("Opening", 0, 200000), ("Middle", 200000, 400000), ("End", 400000, 600000)], +} +AUDIOBOOKS = {201: AUDIOBOOK, 102: AUDIOBOOK_2} + + +def fresh(): + return { + "capabilities": list(CAPABILITIES), + "sync_enabled": True, # the KOReader credentials' "sync enabled" switch + "ko_permission": True, # the account's KOReader sync permission + "api_keys_enabled": True, + "api_key_write": True, # False: a read key (PUT answers 403 API_KEY_READ_ONLY) + "offline": False, # every route answers 503 + "ko_credentials": True, # the account has a KOReader sync sign-in (False: none yet; the API key can make one) + "ko_made": None, # {username, md5}: the sign-in made through POST koreader/credentials + "ko_md5_known": True, # False: an old sign-in whose key the server can't hand over (plugin-package answers 400) + "key_ko_permission": True, # the API key's "KOReader sync" permission + "ko_delivery": None, # the sync sign-in's read-aloud EPUB delivery: None (Automatic), "audioless_epub", "original" + "ko_names_taken": [], # sync user names other accounts have + "goal_books": 30, # the year's reading goal (None: no goal set) + "achievements": True, # False: the reader switched badges off (the dashboard sends null) + "reading_year": True, # False: a server from before the dashboard sent minutes per day + "cors_origin": None, # a site a reverse proxy in front lets in (BookOrbit itself sends no CORS headers) + "requests": [], # book requests: {id, userId, title, authors, mediaKind, status, ...} + "request_permission": True, # the "Request books" permission (False: 403) + "request_status": "pending", # what a new request starts as ("approved" with auto-approve) + "progress": {}, # hash -> {percentage, progress, device, device_id, timestamp} + "playback": {}, # book id -> state + "seen": [], # (method, path) of signed-in requests, newest last + "devices": {}, # deviceId -> deviceModel + "annotations": {}, # book id -> [server highlights: serverId, version, key, datetime, ..., deleted] + "anno_devices": {}, # ":" -> {serverId (as text): the version that device has} + "bookmarks": {}, # book id -> [server bookmarks: serverId, pos, pageno, title, deleted] + "mark_devices": {}, # ":" -> {serverId (as text): that device's key for it} + "page_stats": {}, # hash -> [[page, startTime, durationSeconds, totalPages]] (one per page and start) + "ratings": {}, # book id -> stars (0-5) + "next_id": 1, + } + + +STATE = fresh() + + +def manifest_revision(ab=None): + h = hashlib.sha256() + for a in (ab or AUDIOBOOK)["assets"]: + h.update(a["assetId"].encode() + a["data"]) + return h.hexdigest() + + +def pct100(p): + """KOReader sends 0-1; BookOrbit keeps and shows 0-100, to two places.""" + return round(p * 10000) / 100.0 + + +def list_item(b): + p = STATE["progress"].get(b["hash"]) + return {"id": b["id"], "title": b["title"], "authors": b["authors"], "seriesId": b["seriesId"], + "seriesName": b["seriesName"], "seriesIndex": b["seriesIndex"], + "progressPercentage": p and pct100(p["percentage"]), "lastReadAt": p and p["updatedAt"], + "readStatus": p and "reading" or None, "formats": [b["format"]], "hasCover": True, + "thumbnailUrl": "/api/v1/koreader/plugin/catalog/books/%d/thumbnail" % b["id"], + "detailUrl": "/api/v1/koreader/plugin/catalog/books/%d" % b["id"], + "addedAt": b["addedAt"], "updatedAt": b["updatedAt"]} + + +def detail(b): + d = list_item(b) + p = STATE["progress"].get(b["hash"]) + d.update({"subtitle": None, "description": "About %s." % b["title"], "publisher": "Example House", + "publishedDate": "2020-05-01", "publishedYear": 2020, "language": "en", "isbn10": None, "isbn13": None, + "libraryId": b["libraryId"], "libraryName": LIBRARIES[b["libraryId"]], "rating": STATE["ratings"].get(str(b["id"])), "pageCount": 240, + "collections": [{"id": c, "name": COLLECTIONS[c]} for c in b["collections"]], "genres": [], "tags": [], + "progress": p and {"fileId": b["fileId"], "percentage": pct100(p["percentage"]), + "koreaderProgress": p.get("progress"), "updatedAt": p["updatedAt"]} or None, + "files": [{"id": b["fileId"], "format": b["format"], "role": "primary", "downloadVariant": "original", + "sizeBytes": len(b["data"]), "sourceSizeBytes": len(b["data"]), "durationSeconds": None, "fileHash": b["hash"], + "downloadUrl": "/api/v1/koreader/plugin/catalog/files/%d/download" % b["fileId"], + "devicePath": "%s/%s.%s" % (b["authors"][0], b["title"], b["format"])}], + "relatedSections": []}) + return d + + +# ---------------------------------------------------------------- highlights (the exchange) +DRAWERS = {"lighten", "underscore", "strikeout", "invert"} +CONTENT = ("drawer", "color", "text", "note", "chapter") + + +def anno_key(datetime, pos0): + """A highlight's identity on the device: md5 of "|", as the plugin and server make it.""" + return hashlib.md5(("%s|%s" % (datetime, pos0)).encode()).hexdigest() + + +def check_exchange_book(book): + if not isinstance(book, dict) or not isinstance(book.get("hash"), str) or not MD5.match(book["hash"]): + return "hash must be an MD5 hex string" + keys = book.get("keys") + if not isinstance(keys, list) or len(keys) > 5000: + return "keys must be an array of at most 5000" + for k in keys: + if not isinstance(k, dict) or not isinstance(k.get("k"), str) or not MD5.match(k["k"]) \ + or not isinstance(k.get("dt"), str) or not DEVICE_TIME.match(k["dt"]): + return "each key needs k (MD5 hex) and dt (YYYY-MM-DD HH:MM:SS)" + if not isinstance(book.get("keysComplete"), bool): + return "keysComplete must be a boolean" + if "sidecarState" in book and book["sidecarState"] not in ("known", "new"): + return "sidecarState must be known or new" + changes = book.get("changes") + if not isinstance(changes, list) or len(changes) > 50: + return "changes must be an array of at most 50" + for c in changes: + if not isinstance(c, dict) or not isinstance(c.get("datetime"), str) or not DEVICE_TIME.match(c["datetime"]): + return "datetime must be YYYY-MM-DD HH:MM:SS" + if "datetimeUpdated" in c and not (isinstance(c["datetimeUpdated"], str) and DEVICE_TIME.match(c["datetimeUpdated"])): + return "datetimeUpdated must be YYYY-MM-DD HH:MM:SS" + if c.get("drawer") not in DRAWERS: + return "drawer must be one of lighten, underscore, strikeout, invert" + if c.get("posFormat") not in ("xpointer", "pdf"): + return "posFormat must be xpointer or pdf" + if not isinstance(c.get("pos0"), str) or not c["pos0"] or len(c["pos0"]) > 4000: + return "pos0 must be a string" + for name, limit in (("color", 30), ("text", 10000), ("note", 5000), ("chapter", 500), ("pos1", 4000)): + if name in c and not (isinstance(c[name], str) and len(c[name]) <= limit): + return "%s must be a string of at most %d characters" % (name, limit) + if "pageno" in c and not (isinstance(c["pageno"], int) and not isinstance(c["pageno"], bool) and c["pageno"] >= 0): + return "pageno must be a whole number" + extra = set(c) - {"datetime", "datetimeUpdated", "drawer", "color", "text", "note", "chapter", "pageno", "posFormat", "pos0", "pos1"} + if extra: + return "property %s should not exist" % sorted(extra)[0] + return None + + +def check_ack_book(book): + if not isinstance(book, dict) or not isinstance(book.get("hash"), str) or not MD5.match(book["hash"]): + return "hash must be an MD5 hex string" + for name in ("applied", "deleted"): + rows = book.get(name) + if not isinstance(rows, list) or len(rows) > 200: + return "%s must be an array of at most 200" % name + for r in rows: + if not isinstance(r, dict) or not isinstance(r.get("serverId"), int) or r["serverId"] < 1 or r.get("status") not in ("applied", "failed"): + return "%s entries need serverId and status (applied or failed)" % name + if name == "applied" and not (isinstance(r.get("version"), int) and r["version"] >= 1): + return "applied entries need version" + return None + + +def exchange_book(device_id, b, book): + """One book's exchange: take the device's changes and deletions, answer with what it lacks.""" + anns = STATE["annotations"].setdefault(str(b["id"]), []) + dev_key = "%s:%d" % (device_id, b["id"]) + if book.get("sidecarState") == "new": + STATE["anno_devices"][dev_key] = {} # a fresh copy: nothing deleted, everything offered again + has = STATE["anno_devices"].setdefault(dev_key, {}) + created = updated = unchanged = device_deleted = 0 + for c in book["changes"]: + key = anno_key(c["datetime"], c["pos0"]) + a = next((a for a in anns if a["key"] == key and not a["deleted"]), None) + fields = {f: c.get(f) for f in CONTENT} + fields["color"] = fields["color"] or "yellow" + fields["text"] = fields["text"] or "" + if a is None: + a = dict(fields, serverId=STATE["next_id"], version=1, key=key, datetime=c["datetime"], + datetimeUpdated=c.get("datetimeUpdated"), pos0=c["pos0"], pos1=c.get("pos1"), pageno=c.get("pageno"), + posFormat=c["posFormat"], deleted=False) + STATE["next_id"] += 1 + anns.append(a) + created += 1 + elif any(a[f] != fields[f] for f in CONTENT): + a.update(fields) + a["version"] += 1 + a["datetimeUpdated"] = c.get("datetimeUpdated") or a["datetimeUpdated"] + updated += 1 + else: + unchanged += 1 + has[str(a["serverId"])] = a["version"] + if book["keysComplete"] and book.get("sidecarState") != "new": + present = {k["k"] for k in book["keys"]} + for a in anns: + if not a["deleted"] and str(a["serverId"]) in has and a["key"] not in present: + a["deleted"] = True # removed on the device + has.pop(str(a["serverId"]), None) + device_deleted += 1 + add, edit, delete = [], [], [] + for a in anns: + sid = str(a["serverId"]) + if a["deleted"]: + if sid in has: + delete.append({"serverId": a["serverId"], "key": a["key"], "datetime": a["datetime"]}) + elif sid not in has: + add.append({k: a[k] for k in ("serverId", "version", "datetime", "datetimeUpdated", "drawer", "color", "text", "note", + "chapter", "posFormat", "pos0", "pos1", "pageno")}) + elif has[sid] < a["version"]: + edit.append({"serverId": a["serverId"], "version": a["version"], "key": a["key"], "datetime": a["datetime"], + "datetimeUpdated": a["datetimeUpdated"] or a["datetime"], "drawer": a["drawer"], "color": a["color"], + "text": a["text"], "note": a["note"], "chapter": a["chapter"]}) + return {"hash": b["hash"], "bookId": b["id"], + "applied": {"created": created, "updated": updated, "unchanged": unchanged, "deviceDeleted": device_deleted}, + "toApply": {"add": add[:50], "edit": edit, "delete": delete}, "more": len(add) > 50, "skippedNoPosition": 0} + + +def ack_book(device_id, b, book): + has = STATE["anno_devices"].setdefault("%s:%d" % (device_id, b["id"]), {}) + acked = 0 + for r in book["applied"]: + if r["status"] == "applied": + has[str(r["serverId"])] = r["version"] + acked += 1 + for r in book["deleted"]: + if r["status"] == "applied": + has.pop(str(r["serverId"]), None) + acked += 1 + return {"hash": b["hash"], "acked": acked} + + +def web_highlight(w): + """What the web reader would do: {"book": id, "op": "add"|"edit"|"delete", ...}. Returns the highlight.""" + anns = STATE["annotations"].setdefault(str(w["book"]), []) + if w["op"] == "add": + a = {"serverId": STATE["next_id"], "version": 1, "datetime": w.get("datetime", "2026-11-22 10:00:00"), "datetimeUpdated": None, + "drawer": w.get("drawer", "lighten"), "color": w.get("color", "yellow"), "text": w.get("text", ""), "note": w.get("note"), + "chapter": w.get("chapter"), "posFormat": "xpointer", "pos0": w["pos0"], "pos1": w.get("pos1"), "pageno": w.get("pageno"), + "deleted": False} + a["key"] = anno_key(a["datetime"], a["pos0"]) + STATE["next_id"] += 1 + anns.append(a) + return a + a = next(a for a in anns if a["serverId"] == w["serverId"]) + if w["op"] == "delete": + a["deleted"] = True + else: + for f in CONTENT: + if f in w: + a[f] = w[f] + a["version"] += 1 + a["datetimeUpdated"] = w.get("datetimeUpdated", "2026-11-22 12:00:00") + return a + + +# ---------------------------------------------------------------- bookmarks (the exchange) +def check_mark_book(book): + if not isinstance(book, dict) or not isinstance(book.get("hash"), str) or not MD5.match(book["hash"]): + return "hash must be an MD5 hex string" + keys = book.get("keys") + if not isinstance(keys, list) or len(keys) > 2000: + return "keys must be an array of at most 2000" + for k in keys: + if not isinstance(k, dict) or not isinstance(k.get("k"), str) or not MD5.match(k["k"]) \ + or not isinstance(k.get("dt"), str) or not DEVICE_TIME.match(k["dt"]): + return "each key needs k (MD5 hex) and dt (YYYY-MM-DD HH:MM:SS)" + if not isinstance(book.get("keysComplete"), bool): + return "keysComplete must be a boolean" + if "sidecarState" in book and book["sidecarState"] not in ("known", "new"): + return "sidecarState must be known or new" + changes = book.get("changes") + if not isinstance(changes, list) or len(changes) > 50: + return "changes must be an array of at most 50" + for c in changes: + if not isinstance(c, dict) or not isinstance(c.get("datetime"), str) or not DEVICE_TIME.match(c["datetime"]): + return "datetime must be YYYY-MM-DD HH:MM:SS" + if not isinstance(c.get("pos"), str) or not c["pos"] or len(c["pos"]) > 4000: + return "pos must be a string" + for name in ("chapter", "note"): + if name in c and not (isinstance(c[name], str) and len(c[name]) <= 500): + return "%s must be a string of at most 500 characters" % name + if "pageno" in c and not (isinstance(c["pageno"], int) and not isinstance(c["pageno"], bool) and c["pageno"] >= 0): + return "pageno must be a whole number" + extra = set(c) - {"datetime", "datetimeUpdated", "pos", "pageno", "chapter", "note"} + if extra: + return "property %s should not exist" % sorted(extra)[0] + return None + + +def check_mark_ack(book): + if not isinstance(book, dict) or not isinstance(book.get("hash"), str) or not MD5.match(book["hash"]): + return "hash must be an MD5 hex string" + for name in ("applied", "deleted"): + rows = book.get(name) + if not isinstance(rows, list) or len(rows) > 200: + return "%s must be an array of at most 200" % name + for r in rows: + if not isinstance(r, dict) or not isinstance(r.get("serverId"), int) or r["serverId"] < 1 or r.get("status") not in ("applied", "failed"): + return "%s entries need serverId and status (applied or failed)" % name + if "key" in r and not (isinstance(r["key"], str) and MD5.match(r["key"])): + return "key must be an MD5 hex string" + return None + + +def mark_exchange(device_id, b, book): + marks = STATE["bookmarks"].setdefault(str(b["id"]), []) + dev_key = "%s:%d" % (device_id, b["id"]) + if book.get("sidecarState") == "new": + STATE["mark_devices"][dev_key] = {} + links = STATE["mark_devices"].setdefault(dev_key, {}) + accepted = duplicates = device_deleted = 0 + for c in book["changes"]: + key = anno_key(c["datetime"], c["pos"]) + m = next((m for m in marks if m["pos"] == c["pos"] and not m["deleted"]), None) + if m is None: + m = {"serverId": STATE["next_id"], "pos": c["pos"], "pageno": c.get("pageno"), "title": c.get("note") or c.get("chapter") or "", + "datetime": c["datetime"], "deleted": False} + STATE["next_id"] += 1 + marks.append(m) + accepted += 1 + else: + duplicates += 1 + links[str(m["serverId"])] = key + if book["keysComplete"] and book.get("sidecarState") != "new": + present = {k["k"] for k in book["keys"]} + for m in marks: + sid = str(m["serverId"]) + if not m["deleted"] and sid in links and links[sid] not in present: + m["deleted"] = True + links.pop(sid, None) + device_deleted += 1 + add = [{"serverId": m["serverId"], "pos": m["pos"], "pageno": m["pageno"], "title": m["title"]} + for m in marks if not m["deleted"] and str(m["serverId"]) not in links] + delete = [{"serverId": m["serverId"], "key": links[str(m["serverId"])], "datetime": m.get("datetime")} + for m in marks if m["deleted"] and str(m["serverId"]) in links] + return {"hash": b["hash"], "bookId": b["id"], "accepted": accepted, "duplicates": duplicates, "rejected": 0, + "deviceDeleted": device_deleted, "toApply": {"add": add, "delete": delete}, "more": False, "skippedConversion": 0} + + +def mark_ack(device_id, b, book): + links = STATE["mark_devices"].setdefault("%s:%d" % (device_id, b["id"]), {}) + acked = 0 + for r in book["applied"]: + if r["status"] == "applied" and r.get("key"): + links[str(r["serverId"])] = r["key"] + acked += 1 + for r in book["deleted"]: + if r["status"] == "applied": + links.pop(str(r["serverId"]), None) + acked += 1 + return {"hash": b["hash"], "acked": acked} + + +def web_bookmark(w): + """What another device or the web would do: {"book": id, "op": "add"|"delete", ...}.""" + marks = STATE["bookmarks"].setdefault(str(w["book"]), []) + if w["op"] == "add": + m = {"serverId": STATE["next_id"], "pos": w["pos"], "pageno": w.get("pageno"), "title": w.get("title", ""), "datetime": None, "deleted": False} + STATE["next_id"] += 1 + marks.append(m) + return m + m = next(m for m in marks if m["serverId"] == w["serverId"]) + m["deleted"] = True + return m + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + # ---------------------------------------------------------------- plumbing + def send(self, code, body=None, ctype="application/json", headers=None): + raw = body if isinstance(body, (bytes, bytearray)) else json.dumps(body if body is not None else {}).encode() + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(raw))) + for k, v in (headers or {}).items(): + self.send_header(k, v) + if STATE.get("cors_origin") and self.headers.get("Origin") == STATE["cors_origin"]: + self.send_header("Access-Control-Allow-Origin", STATE["cors_origin"]) + self.send_header("Access-Control-Expose-Headers", "content-length, content-range, content-disposition, etag") + self.end_headers() + if self.command != "HEAD": + self.wfile.write(raw) + + def error(self, code, message, error_code=None): + body = {"statusCode": code, "message": message, "path": self.path.split("?")[0], + "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()), "requestId": "req-mock"} + if error_code: + body["errorCode"] = error_code + self.send(code, body) + + def body(self): + n = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(n) if n else b"" + try: + return json.loads(raw) if raw else {} + except ValueError: + return None + + def ko_user(self): + """The KOReader guard: x-auth-user + x-auth-key (the password or its MD5).""" + user, key = self.headers.get("x-auth-user"), self.headers.get("x-auth-key") + if not user or not key: + return self.error(401, "Missing KOReader credentials") + made = STATE["ko_made"] # (a sign-in made with the API key stands in for the usual one) + if not made and not STATE["ko_credentials"]: + return self.error(401, "Invalid credentials") + if user != (made["username"] if made else KO_USER): + return self.error(401, "Invalid credentials") + if not STATE["sync_enabled"]: + return self.error(403, "Sync is disabled") + want = made["md5"] if made else KO_KEY + got = key.lower() if MD5.match(key) else hashlib.md5(key.encode()).hexdigest() + if got != want: + return self.error(401, "Invalid credentials") + if not STATE["ko_permission"]: + return self.error(401, "KOReader sync permission revoked") + return user + + def api_key(self, write=False): + """The main API's key: Bearer or X-Api-Key, never the query string.""" + auth = self.headers.get("Authorization") + m = re.match(r"^Bearer\s+(\S+)\s*$", auth or "", re.I) + bearer = m and m.group(1) or None + header = (self.headers.get("X-Api-Key") or "").strip() or None + if header and auth is not None and bearer != header: + return self.error(401, "Conflicting credentials") + key = header or (bearer if bearer and bearer.startswith("bok_") else None) + if not key: + return self.error(401, "Unauthorized") # (a Bearer that isn't a key is taken for a session token) + if len(key) != len(API_KEY): + return self.error(401, "Invalid API key") # malformed: the real key carries a checksum + if not STATE["api_keys_enabled"]: + return self.error(401, "API keys are turned off on this server", "API_KEYS_DISABLED") + if key != API_KEY: + return self.error(401, "Invalid API key") + if write and not STATE["api_key_write"]: + return self.error(403, "This API key is read-only", "API_KEY_READ_ONLY") + return key + + def device(self, dto): + """PluginDeviceDto: what every plugin POST carries.""" + if not isinstance(dto, dict): + return self.error(400, "Bad JSON") + if not isinstance(dto.get("deviceId"), str) or not DEVICE_ID.match(dto["deviceId"]): + return self.error(400, "deviceId must match /^[A-Za-z0-9_-]{1,100}$/") + if not isinstance(dto.get("deviceModel"), str) or len(dto["deviceModel"]) > 100: + return self.error(400, "deviceModel must be a string of at most 100 characters") + if not isinstance(dto.get("pluginVersion"), str) or len(dto["pluginVersion"]) > 20: + return self.error(400, "pluginVersion must be a string of at most 20 characters") + if "deviceTime" in dto and not (isinstance(dto["deviceTime"], str) and DEVICE_TIME.match(dto["deviceTime"])): + return self.error(400, "deviceTime must be YYYY-MM-DD HH:MM:SS") + STATE["devices"][dto["deviceId"]] = dto["deviceModel"] + return True + + # ---------------------------------------------------------------- routes + def do_OPTIONS(self): + # (only a reverse proxy answers a browser's preflight: without one set up, as production BookOrbit, 404) + allowed = STATE["cors_origin"] + if not allowed or self.headers.get("Origin") != allowed: + return self.error(404, "Cannot OPTIONS " + self.path.split("?")[0]) + self.send_response(204) + self.send_header("Access-Control-Allow-Origin", allowed) + self.send_header("Access-Control-Allow-Headers", "x-auth-user, x-auth-key, authorization, content-type, range, if-none-match") + self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + self.send_header("Content-Length", "0") + self.end_headers() + + def do_GET(self): + self.route("GET") + + def do_POST(self): + self.route("POST") + + def do_PUT(self): + self.route("PUT") + + def do_DELETE(self): + self.route("DELETE") + + def route(self, method): + global STATE + url = urlparse(self.path) + path, q = url.path, {k: v[-1] for k, v in parse_qs(url.query).items()} + if path == "/_mock/state": + return self.send(200, {k: v for k, v in STATE.items()}) + if path == "/_mock/reset": + STATE = fresh() + return self.send(200, {"ok": True}) + if path == "/_mock/set": + changes = self.body() or {} + # "book_hashes": {"101": "<32 hex>"}: a book's file is the one with that fingerprint + # (for a test that puts a real book on the device) + mark = changes.pop("web_bookmark", None) + if mark: + return self.send(200, web_bookmark(mark)) + web = changes.pop("web_highlight", None) + if web: + return self.send(200, web_highlight(web)) + # "add_request": {"title", "mediaKind", "userId"?, "status"?, ...}: a request as the server has it + add = changes.pop("add_request", None) + if add: + r = {"id": 500 + len(STATE["requests"]) + 1, "userId": 1, "authors": [], "mediaKind": "ebook", "status": "pending"} + r.update(add) + STATE["requests"].append(r) + return self.send(200, {"id": r["id"]}) + # "request_update": {"id", ...}: what the server did with one (approved it, found it, ...) + upd = changes.pop("request_update", None) + if upd: + for r in STATE["requests"]: + if r["id"] == upd.get("id"): + r.update(upd) + return self.send(200, {"ok": True}) + for cid, owner in (changes.pop("collection_owners", None) or {}).items(): + COLLECTIONS.setdefault(int(cid), "Shared by someone else") + COLLECTION_OWNERS[int(cid)] = owner + for bid, h in (changes.pop("book_hashes", None) or {}).items(): + for b in BOOKS: + if str(b["id"]) == str(bid): + b["hash"] = h + STATE.update(changes) + return self.send(200, {"ok": True}) + if STATE["offline"]: + return self.error(503, "Service Unavailable") + if not path.startswith("/api/v1/"): + return self.error(404, "Not Found") + p = path[len("/api/v1/"):] + if p.startswith("koreader/") and p not in ("koreader/credentials", "koreader/plugin-package"): + if not self.ko_user(): + return + STATE["seen"].append([method, p]) + return self.koreader(method, p[len("koreader/"):], q) + if p == "auth/me" and method == "GET": + if not self.api_key(): + return + return self.send(200, {"id": 1, "username": "will", "name": "Will", "email": "will@example.com", "active": True, + "isSuperuser": False, "isDefaultPassword": False, "settings": {}, "avatarUrl": None, + "provisioningMethod": "local", "authenticationMethod": "api_key", + "permissions": ["koreader_sync", "book_download"]}) + if p == "books/query" and method == "POST": + # Marked safe for read-only keys in the real server. Only the part GZreader uses: the + # audiobooks, found by a format rule. (The real card has many more fields.) + if not self.api_key(): + return + d = self.body() + pg = isinstance(d, dict) and d.get("pagination") + if not isinstance(pg, dict) or not isinstance(pg.get("page"), int) or not isinstance(pg.get("size"), int) \ + or not isinstance(d.get("sort"), list): + return self.error(400, "sort and pagination are required") + rules = (d.get("filter") or {}).get("rules") or [] + fmts = {str(v).lower() for r in rules if r.get("field") == "format" and r.get("operator") == "includesAny" + for v in r.get("value") or []} + if "q" in d and not isinstance(d["q"], str): + return self.error(400, "q must be a string") + found = [] + for ab in sorted(AUDIOBOOKS.values(), key=lambda ab: ab["title"].lower()): + if rules and not fmts & {a["format"] for a in ab["assets"]}: + continue + if d.get("q") and d["q"].lower() not in (ab["title"] + " " + " ".join(ab["authors"])).lower(): + continue + state = STATE["playback"].get(ab["id"]) + found.append({"id": ab["id"], "title": ab["title"], "authors": ab["authors"], "narrators": ab["narrators"], + "seriesName": None, "seriesIndex": None, "hasCover": True, "subtitle": None, + "readingProgress": state and state["percentage"] or None, + "files": [{"id": a["fileId"], "format": a["format"]} for a in ab["assets"]]}) + if d["sort"] and isinstance(d["sort"][0], dict) and d["sort"][0].get("dir") == "desc": + found.reverse() + items = found[(pg["page"] - 1) * pg["size"]:pg["page"] * pg["size"]] + return self.send(201, {"items": items, "total": len(found), "page": pg["page"], "size": pg["size"]}) + m = re.match(r"^books/(\d+)/thumbnail$", p) + if m and method == "GET": + if not self.api_key(): + return + if int(m.group(1)) not in AUDIOBOOKS and not any(b["id"] == int(m.group(1)) for b in BOOKS): + return self.error(404, "Book not found") + return self.send(200, PNG, "image/png", {"ETag": '"1790000000000"'}) + # collections on the main API: your own and others' shared ones listed; only your own changed + if p == "collections" and method == "GET": + if not self.api_key(): + return + STATE["seen"].append([method, p]) + return self.send(200, [{"id": i, "name": n, "userId": COLLECTION_OWNERS.get(i, 1), + "bookCount": sum(i in b["collections"] for b in BOOKS)} for i, n in COLLECTIONS.items()]) + m = re.match(r"^collections/(\d+)/books$", p) + if m and method in ("POST", "DELETE"): + if not self.api_key(write=True): + return + STATE["seen"].append([method, p]) + cid = int(m.group(1)) + if cid not in COLLECTIONS: + return self.error(404, "Collection not found") + if COLLECTION_OWNERS.get(cid, 1) != 1: + return self.error(403, "You cannot edit this collection") + d = self.body() + ids = isinstance(d, dict) and d.get("bookIds") + if not isinstance(ids, list) or not ids or not all(isinstance(i, int) and not isinstance(i, bool) for i in ids) or set(d) - {"bookIds", "query"}: + return self.error(400, "bookIds must be a non-empty array of book ids") + changed = 0 + for b in BOOKS: + if b["id"] in ids: + if method == "POST" and cid not in b["collections"]: + b["collections"].append(cid); changed += 1 + if method == "DELETE" and cid in b["collections"]: + b["collections"].remove(cid); changed += 1 + return self.send(200 if method == "DELETE" else 201, {"changed": changed}) + # the KOReader sync sign-in, managed with the API key (its "KOReader sync" permission) + if p in ("koreader/credentials", "koreader/plugin-package"): + if not self.api_key(write=method != "GET"): + return + STATE["seen"].append([method, p]) + if not STATE["key_ko_permission"]: + return self.error(403, "Forbidden resource") + made = STATE["ko_made"] + has = STATE["ko_credentials"] or made + name = made["username"] if made else KO_USER + if p == "koreader/credentials" and method == "GET": + if not has: + return self.send(200, b"", "application/json") + return self.send(200, {"username": name, "syncEnabled": STATE["sync_enabled"], "hideAudioOnlyBooks": True, + "createdAt": "2026-10-01T08:00:00.000Z", "readAloudDelivery": STATE["ko_delivery"]}) + if p == "koreader/credentials" and method == "POST": + d = self.body() + if (not isinstance(d, dict) or set(d) - {"username", "password", "readAloudDelivery"} or not isinstance(d.get("username"), str) + or not 3 <= len(d["username"]) <= 100 or not isinstance(d.get("password"), str) or not 6 <= len(d["password"]) <= 128): + return self.error(400, "Bad Request") + if has: + return self.error(409, "KOReader credentials already exist") + if d["username"] in STATE["ko_names_taken"]: + return self.error(409, "Username already taken") + if d.get("readAloudDelivery") not in (None, "original", "audioless_epub"): + return self.error(400, "Bad Request") + STATE["ko_delivery"] = d.get("readAloudDelivery") # (none sent: the default, Automatic) + STATE["ko_made"] = {"username": d["username"], "md5": hashlib.md5(d["password"].encode()).hexdigest()} + return self.send(201, {"success": True}) + if p == "koreader/plugin-package" and method == "GET": + origin = q.get("origin", "") + if not re.match(r"^https?://[^/]+", origin): + return self.error(400, "origin must be a valid http(s) URL") + if not has: + return self.error(404, "Create KOReader sync credentials first") + if not STATE["ko_md5_known"]: + return self.error(400, "Update your KOReader password once to enable the preconfigured download") + key = made["md5"] if made else KO_KEY + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr("bookorbit.koplugin/bookorbit_provision.lua", + "-- (a stand-in for the sign-in file a real server puts in its plugin download)\nreturn {\n" + ' server_url = "%s",\n username = "%s",\n userkey = "%s",\n generated_at = "2026-11-22T10:00:00.000Z",\n}\n' + % (origin, name, key)) + z.writestr("bookorbit.koplugin/_meta.lua", 'return { name = "bookorbit" }\n') + z.writestr("bookorbit.koplugin/main.lua", "-- (the plugin itself: not GZreader's to read)\n" * 400) + return self.send(200, buf.getvalue(), "application/zip", {"Cache-Control": "no-store"}) + return self.error(404, "Not Found") + # book requests: ask for a book the server doesn't have; your own listed, newest first + if p == "book-requests" or p.startswith("book-requests/"): + if not self.api_key(write=method != "GET"): + return + STATE["seen"].append([method, p]) + if not STATE["request_permission"]: + return self.error(403, "Forbidden resource") + return self.book_requests(method, p[len("book-requests"):].lstrip("/"), q) + if p.startswith("audiobooks/"): + if not self.api_key(write=method != "GET"): + return + STATE["seen"].append([method, p]) + return self.audiobooks(method, p[len("audiobooks/"):]) + return self.error(404, "Not Found") + + # KOReader API ------------------------------------------------------------ + def koreader(self, method, p, q): + if p == "users/auth" and method == "GET": + return self.send(200, {"authorized": "OK", "username": KO_USER}) + if p == "plugin/version" and method == "GET": + return self.send(200, {"pluginVersion": "0.9.0", "serverVersion": "0.9.0", "capabilities": STATE["capabilities"]}) + m = re.match(r"^syncs/progress/([^/]+)$", p) + if m and method == "GET": + p = STATE["progress"].get(m.group(1)) + return self.send(200, p and {"document": m.group(1), "percentage": p["percentage"], "progress": p.get("progress") or "", + "device": p["device"], "device_id": p["device_id"], "timestamp": p["timestamp"]} or {}) + if p == "syncs/progress" and method == "PUT": + d = self.body() + if not isinstance(d, dict) or not isinstance(d.get("document"), str): + return self.error(400, "document must be a string") + if not isinstance(d.get("percentage"), (int, float)) or not 0 <= d["percentage"] <= 1: + return self.error(400, "percentage must be a number from 0 to 1") + if not any(b["hash"] == d["document"] for b in BOOKS): + return self.error(404, "Book not found for the given document hash") + self.keep_progress(d["document"], d, d.get("device"), d.get("device_id")) + return self.send(200, {"document": d["document"], "timestamp": STATE["progress"][d["document"]]["timestamp"]}) + if p == "plugin/match-check" and method == "POST": + d = self.body() + if not self.device(d): + return + hashes = d.get("hashes") + if not isinstance(hashes, list) or not 1 <= len(hashes) <= 500 or not all(isinstance(h, str) and MD5.match(h) for h in hashes): + return self.error(400, "hashes must be 1 to 500 MD5 hex strings") + by = {b["hash"]: b for b in BOOKS} + return self.send(201, {"matches": [{"hash": h, "bookId": by[h]["id"], "bookFileId": by[h]["fileId"]} for h in hashes if h in by], + "libraryVersion": "lib-%d" % len(BOOKS)}) + if p == "plugin/progress" and method == "POST": + d = self.body() + if not self.device(d): + return + items = d.get("items") + if not isinstance(items, list) or not items: + return self.error(400, "items must be a non-empty array") + by = {b["hash"] for b in BOOKS} + results, unmatched = [], [] + for it in items: + if not isinstance(it, dict) or not isinstance(it.get("hash"), str) or not MD5.match(it["hash"]): + return self.error(400, "hash must be an MD5 hex string") + if not isinstance(it.get("percentage"), (int, float)) or not 0 <= it["percentage"] <= 1: + return self.error(400, "percentage must be a number from 0 to 1") + if "progress" in it and not isinstance(it["progress"], str): + return self.error(400, "progress must be a string") + if it["hash"] in by: + self.keep_progress(it["hash"], it, d["deviceModel"], d["deviceId"]) + results.append({"hash": it["hash"], "accepted": True}) + else: + unmatched.append(it["hash"]) + return self.send(201, {"results": results, "unmatched": unmatched}) + if p in ("plugin/annotations/exchange", "plugin/annotations/exchange-ack") and method == "POST": + d = self.body() + if not self.device(d): + return + books = d.get("books") + if not isinstance(books, list) or not 1 <= len(books) <= 20: + return self.error(400, "books must hold 1 to 20 books") + ack = p.endswith("-ack") + results, unmatched = [], [] + for book in books: + bad = check_ack_book(book) if ack else check_exchange_book(book) + if bad: + return self.error(400, bad) + b = next((b for b in BOOKS if b["hash"] == book["hash"].lower()), None) + if not b: + unmatched.append(book["hash"].lower()) + continue + results.append((ack_book if ack else exchange_book)(d["deviceId"], b, book)) + return self.send(201, {"results": results, "unmatched": unmatched, "positionIncompatible": []}) + if p == "plugin/page-stats" and method == "POST": + d = self.body() + if not self.device(d): + return + books = d.get("books") + if not isinstance(books, list) or not 1 <= len(books) <= 50: + return self.error(400, "books must hold 1 to 50 books") + results, unmatched = [], [] + whole = lambda v: isinstance(v, int) and not isinstance(v, bool) + for book in books: + if not isinstance(book, dict) or not isinstance(book.get("hash"), str) or not MD5.match(book["hash"]): + return self.error(400, "hash must be an MD5 hex string") + events = book.get("events") + if not isinstance(events, list) or not events: + return self.error(400, "events must not be empty") + for e in events: + if not isinstance(e, dict) or not (whole(e.get("page")) and e["page"] >= 0 and whole(e.get("startTime")) and e["startTime"] >= 1 + and whole(e.get("durationSeconds")) and 0 <= e["durationSeconds"] <= 86400 + and whole(e.get("totalPages")) and e["totalPages"] >= 1) or set(e) - {"page", "startTime", "durationSeconds", "totalPages"}: + return self.error(400, "each event needs page, startTime, durationSeconds (0 to 86400) and totalPages, as whole numbers") + h = book["hash"].lower() + if not any(b["hash"] == h for b in BOOKS): + unmatched.append(h) + continue + rows = STATE["page_stats"].setdefault(h, []) + accepted = 0 + for e in events: + if not any(r[0] == e["page"] and r[1] == e["startTime"] for r in rows): + rows.append([e["page"], e["startTime"], e["durationSeconds"], e["totalPages"]]) + accepted += 1 + results.append({"hash": h, "accepted": accepted, "duplicates": len(events) - accepted}) + return self.send(201, {"results": results, "unmatched": unmatched}) + m = re.match(r"^plugin/catalog/books/(\d+)/rating$", p) + if m and method == "PUT": + d = self.body() + if not any(b["id"] == int(m.group(1)) for b in BOOKS): + return self.error(404, "Book not found") + r = isinstance(d, dict) and d.get("rating") + if r is not None and not (isinstance(r, (int, float)) and not isinstance(r, bool) and 0 <= r <= 5): + return self.error(400, "rating must be a number from 0 to 5") + if isinstance(d, dict) and set(d) - {"rating"}: + return self.error(400, "property %s should not exist" % sorted(set(d) - {"rating"})[0]) + STATE["ratings"][m.group(1)] = r + return self.send(200, {"rating": r}) + if p in ("plugin/bookmarks/exchange", "plugin/bookmarks/exchange-ack") and method == "POST": + d = self.body() + if not self.device(d): + return + books = d.get("books") + if not isinstance(books, list) or not 1 <= len(books) <= 20: + return self.error(400, "books must hold 1 to 20 books") + ack = p.endswith("-ack") + results, unmatched = [], [] + for book in books: + bad = check_mark_ack(book) if ack else check_mark_book(book) + if bad: + return self.error(400, bad) + b = next((b for b in BOOKS if b["hash"] == book["hash"].lower()), None) + if not b: + unmatched.append(book["hash"].lower()) + continue + results.append((mark_ack if ack else mark_exchange)(d["deviceId"], b, book)) + return self.send(201, {"results": results, "unmatched": unmatched, "positionIncompatible": []}) + if p.startswith("plugin/catalog/") and method == "GET": + return self.catalog(p[len("plugin/catalog/"):], q) + return self.error(404, "Not Found") + + def keep_progress(self, h, src, device, device_id): + STATE["progress"][h] = {"percentage": src["percentage"], "progress": src.get("progress"), "device": device or "KOReader", + "device_id": device_id or "mock", "timestamp": int(src.get("timestamp") or time.time()), + "updatedAt": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())} + + def page(self, items, q, base): + try: + size = int(q.get("size", 20)) + page = int(q.get("page", 1)) + except ValueError: + return self.error(400, "page and size must be integers") + if not 1 <= size <= 100 or page < 1: + return self.error(400, "size must be from 1 to 100 and page at least 1") + start = (page - 1) * size + part = items[start:start + size] + more = start + size < len(items) + return self.send(200, {"items": part, "total": len(items), "page": page, "size": size, "hasNext": more, + "hasPrevious": page > 1, + "nextUrl": more and "%s&page=%d" % (base, page + 1) or None, + "previousUrl": page > 1 and "%s&page=%d" % (base, page - 1) or None, + "seriesSummary": None}) + + def catalog(self, p, q): + C = "/api/v1/koreader/plugin/catalog" + if p == "root": + return self.send(200, {"sections": [ + {"id": "continue-reading", "title": "Continue reading", "section": "continue-reading", + "booksHref": C + "/books?sort=recently_read&readStatus=reading"}, + {"id": "recent", "title": "Recently added", "section": "recent", "booksHref": C + "/books?sort=recently_added"}, + {"id": "libraries", "title": "Libraries", "section": "libraries", "href": C + "/sections/libraries"}, + {"id": "collections", "title": "Collections", "section": "collections", "href": C + "/sections/collections"}, + {"id": "smart-scopes", "title": "SmartScopes", "section": "smart-scopes", "href": C + "/sections/smart-scopes"}, + {"id": "authors", "title": "Authors", "section": "authors", "href": C + "/sections/authors"}, + {"id": "series", "title": "Series", "section": "series", "href": C + "/sections/series"}, + {"id": "all-books", "title": "All Books", "section": "all-books", "booksHref": C + "/books?sort=title"}]}) + if p == "dashboard": + # The reader's own numbers, over every device. Minutes per day for 371 days ending today + # (k days ago: nothing every fifth day, else a number under 75; today 25). + if q.get("section") not in (None, "random", "recently-added", "want-to-read", "up-next-in-series", "smart-scope"): + return self.error(400, "Bad Request") + today = time.strftime("%Y-%m-%d") + minutes = [(0 if k % 5 == 1 else 25 if k == 0 else (k * 13) % 75) for k in range(370, -1, -1)] + start = time.strftime("%Y-%m-%d", time.localtime(time.time() - 370 * 86400)) + streak = 0 + for m in reversed(minutes): + if m <= 0: + break + streak += 1 + shown = [list_item(b) for b in BOOKS] + out = {"generatedAt": today + "T10:00:00.000Z", "username": "will", "displayName": "Will", "totalBooks": len(shown), + "browseCounts": {"inProgress": 2, "libraries": 2, "authors": 4, "series": 1, "collections": 2, "smartScopes": 0}, + "sections": [], "continueReading": shown[:2], "discover": [] if q.get("section") else shown[:3], + "readingGoal": {"goalBooks": STATE["goal_books"], "completedBooks": 12, "year": int(today[:4])}, + "readingStreak": {"currentStreak": streak, "longestStreak": 21, "lastSevenDays": [m > 0 for m in minutes[-7:]]}, + "highlightOfTheDay": {"text": "The tide does not ask the shore for leave.", "note": None, "bookTitle": shown[0]["title"], + "bookId": shown[0]["id"], "hasCover": True, "chapterTitle": "Chapter 3", "createdAt": today + "T08:00:00.000Z"}, + "yearAgo": {"book": shown[1], "minutes": 312, "days": 9, "endProgress": 100, "firstDay": "2025-11-10", "lastDay": "2025-12-02"}, + "finishedThisYear": shown[:3], + "achievements": {"earned": 5, "total": 40, + "next": {"key": "hours_read_50", "groupKey": "hours_read", "name": "Fifty hours", "description": "Read for fifty hours.", + "rarity": "common", "iconName": "clock", "threshold": 50, "currentProgress": 41, "awardedAt": None}, + "latest": {"key": "books_finished_10", "groupKey": "books_finished", "name": "Ten down", "description": "Finish ten books.", + "rarity": "common", "iconName": "book", "threshold": 10, "currentProgress": 10, + "awardedAt": today + "T09:00:00.000Z"}} if STATE["achievements"] else None} + if STATE["reading_year"]: + out["readingYear"] = {"startDate": start, "minutes": minutes} + return self.send(200, out) + m = re.match(r"^sections/([^/]+)$", p) + if m: + s = m.group(1) + if s == "libraries": + return self.send(200, {"section": s, "items": [ + {"id": str(i), "title": n, "section": s, "count": sum(b["libraryId"] == i for b in BOOKS), + "booksHref": C + "/books?sort=title&libraryId=%d" % i} for i, n in LIBRARIES.items()]}) + if s == "collections": + return self.send(200, {"section": s, "items": [ + {"id": str(i), "title": n, "section": s, "count": sum(i in b["collections"] for b in BOOKS), + "booksHref": C + "/books?sort=title&collectionId=%d" % i} for i, n in COLLECTIONS.items()]}) + if s == "smart-scopes": + return self.send(200, {"section": s, "items": []}) + if s == "authors": + names = sorted({a for b in BOOKS for a in b["authors"]}) + items = [{"id": n, "title": n, "section": s, "count": sum(n in b["authors"] for b in BOOKS), + "booksHref": C + "/books?sort=title&author=" + quote(n), "authorId": i + 1, "hasPhoto": False, + "photoUrl": None} for i, n in enumerate(names)] + elif s == "series": + names = sorted({b["seriesName"] for b in BOOKS if b["seriesName"]}) + items = [] + for n in names: + sid = next(b["seriesId"] for b in BOOKS if b["seriesName"] == n) + items.append({"id": "series-%d" % sid, "title": n, "section": s, "count": sum(b["seriesName"] == n for b in BOOKS), + "seriesId": sid, "booksHref": C + "/books?sort=series&seriesId=%d" % sid, + "authorNames": sorted({a for b in BOOKS if b["seriesName"] == n for a in b["authors"]})}) + else: + return self.error(400, "Unknown catalog section") + # (authors and series are the two sections the real server pages) + return self.send(200, {"section": s, "items": items, "page": 1, "hasNext": False, "hasPrevious": False, + "nextUrl": None, "previousUrl": None, "query": None, "total": len(items)}) + if p == "books": + if q.get("sort", "recently_added") not in SORTS: + return self.error(400, "sort must be one of " + ", ".join(sorted(SORTS))) + books = list(BOOKS) + if "readStatus" in q: + if q["readStatus"] not in ("unread", "reading", "finished"): + return self.error(400, "readStatus must be one of unread, reading, finished") + reading = lambda b: b["hash"] in STATE["progress"] + books = [b for b in books if {"reading": reading(b), "unread": not reading(b), "finished": False}[q["readStatus"]]] + for key, test in (("libraryId", lambda b, v: b["libraryId"] == int(v)), + ("collectionId", lambda b, v: int(v) in b["collections"]), + ("seriesId", lambda b, v: b["seriesId"] == int(v)), + ("author", lambda b, v: v in b["authors"]), + ("series", lambda b, v: b["seriesName"] == v), + ("format", lambda b, v: b["format"] == v.lower()), + ("q", lambda b, v: v.lower() in (b["title"] + " " + " ".join(b["authors"])).lower())): + if key in q: + try: + books = [b for b in books if test(b, q[key])] + except ValueError: + return self.error(400, "%s must be a number" % key) + sort = q.get("sort", "recently_added") + keyf = {"title": lambda b: b["title"].lower(), "author": lambda b: b["authors"][0].lower(), + "series": lambda b: ((b["seriesName"] or "~"), b["seriesIndex"] or 0)}.get(sort, lambda b: b["addedAt"]) + desc = q.get("order", "desc" if sort.startswith("recently") else "asc") == "desc" + books.sort(key=keyf, reverse=desc) + base = "/api/v1/koreader/plugin/catalog/books?" + "&".join("%s=%s" % (k, v) for k, v in sorted(q.items()) if k != "page") + return self.page([list_item(b) for b in books], q, base) + m = re.match(r"^books/(\d+)$", p) + if m: + b = next((b for b in BOOKS if b["id"] == int(m.group(1))), None) + return self.send(200, detail(b)) if b else self.error(404, "Book not found") + m = re.match(r"^books/(\d+)/thumbnail$", p) + if m: + if not any(b["id"] == int(m.group(1)) for b in BOOKS): + return self.error(404, "No thumbnail") + if self.headers.get("If-None-Match") == '"1790000000000"': + return self.send(304, b"", "image/png") + return self.send(200, PNG, "image/png", {"ETag": '"1790000000000"', "Cache-Control": "no-cache"}) + m = re.match(r"^files/(\d+)/download$", p) + if m: + b = next((b for b in BOOKS if b["fileId"] == int(m.group(1))), None) + if not b: + return self.error(404, "File not found") + return self.send(200, b["data"], "application/epub+zip" if b["format"] == "epub" else "application/pdf", + {"Content-Disposition": 'attachment; filename="%s.%s"' % (b["title"], b["format"])}) + return self.error(404, "Not Found") + + # Main API: audiobooks ------------------------------------------------------ + def book_requests(self, method, p, q): + def item(r): + return {"id": r["id"], "userId": r["userId"], "requesterUsername": "will" if r["userId"] == 1 else "someone", + "mediaKind": r["mediaKind"], "status": r["status"], "title": r["title"], "subtitle": None, + "authors": r["authors"], "statusReason": r.get("statusReason"), "decisionNote": r.get("decisionNote"), + "matchedBookId": r.get("matchedBookId"), "createdAt": "2026-11-%02dT08:00:00.000Z" % (r["id"] % 27 + 1)} + mine = [r for r in STATE["requests"] if r["userId"] == 1 or 1 in r.get("subscribers", [])] + if p == "" and method == "POST": + d = self.body() + allowed = {"title", "subtitle", "authors", "mediaKind", "note", "seriesName", "seriesIndex", "isbn10", "isbn13", "publishedYear", "language"} + if (not isinstance(d, dict) or set(d) - allowed or not isinstance(d.get("title"), str) or not d["title"].strip() or len(d["title"]) > 500 + or d.get("mediaKind") not in ("ebook", "audiobook") + or ("authors" in d and (not isinstance(d["authors"], list) or not all(isinstance(a, str) for a in d["authors"])))): + return self.error(400, "Bad Request") + for r in STATE["requests"]: + if r["title"].lower() == d["title"].strip().lower() and r["mediaKind"] == d["mediaKind"] and r["status"] not in ("cancelled", "rejected"): + if r["userId"] != 1 and 1 not in r.setdefault("subscribers", []): + r["subscribers"].append(1) + return self.send(201, {"request": item(r), "subscribed": r["userId"] != 1}) + r = {"id": 500 + len(STATE["requests"]) + 1, "userId": 1, "title": d["title"].strip(), "authors": d.get("authors") or [], + "mediaKind": d["mediaKind"], "status": STATE["request_status"]} + STATE["requests"].append(r) + return self.send(201, {"request": item(r), "subscribed": False}) + if p == "" and method == "GET": + try: + page, limit = int(q.get("page", "1")), int(q.get("limit", "20")) + except ValueError: + return self.error(400, "Bad Request") + if page < 1 or limit < 1 or limit > 100: + return self.error(400, "Bad Request") + rows = sorted(mine, key=lambda r: -r["id"]) + return self.send(200, {"items": [item(r) for r in rows[(page - 1) * limit:page * limit]], "total": len(rows)}) + m = re.match(r"^(\d+)/cancel$", p) + if m and method == "POST": + for r in STATE["requests"]: + if r["id"] == int(m.group(1)): + if r["userId"] != 1: + return self.error(403, "You cannot cancel this book request") + if r["status"] in ("cancelled", "rejected", "available"): + return self.error(400, "This request can no longer be cancelled") + r["status"] = "cancelled" + return self.send(200, item(r)) + return self.error(404, "Book request not found") + m = re.match(r"^(\d+)$", p) + if m and method == "GET": + for r in mine: + if r["id"] == int(m.group(1)): + return self.send(200, item(r)) + return self.error(404, "Book request not found") + return self.error(404, "Not Found") + + def audiobooks(self, method, p): + m = re.match(r"^(\d+)/(.+)$", p) + ab = m and AUDIOBOOKS.get(int(m.group(1))) + if not ab: + return self.error(404, "Book has no audiobook assets") + rest, bid = m.group(2), ab["id"] + if rest == "manifest" and method == "GET": + assets = [{"assetId": a["assetId"], "fileId": a["fileId"], "sequence": a["sequence"], "format": a["format"], + "durationMs": a["durationMs"], "sizeBytes": len(a["data"]), + "etag": hashlib.md5(a["data"]).hexdigest()} for a in ab["assets"]] + chapters, at = [], 0 + for a in ab["assets"]: + if "chapters" not in ab: + chapters.append({"id": "ch-%d" % a["sequence"], "title": "Part %d" % (a["sequence"] + 1), "assetId": a["assetId"], + "sequence": a["sequence"], "startMs": at, "endMs": at + a["durationMs"], "assetOffsetMs": 0}) + at += a["durationMs"] + for n, (title, start, end) in enumerate(ab.get("chapters", [])): + chapters.append({"id": "ch-%d" % n, "title": title, "assetId": ab["assets"][0]["assetId"], "sequence": n, + "startMs": start, "endMs": end, "assetOffsetMs": start}) + return self.send(200, {"schema": "bookorbit.audiobook-manifest", "schemaVersion": 2, "revision": manifest_revision(ab), + "book": {"id": bid, "title": ab["title"], "authors": ab["authors"], + "narrators": ab["narrators"], "hasCover": True}, + "assets": assets, "chapters": chapters, "totalDurationMs": at}) + m = re.match(r"^assets/([^/]+)/content$", rest) + if m and method == "GET": + a = next((a for a in ab["assets"] if a["assetId"] == m.group(1)), None) + if not a: + return self.error(404, "Audiobook asset not found") + data, size = a["data"], len(a["data"]) + rng = re.match(r"bytes=(\d+)-(\d*)", self.headers.get("Range") or "") + if rng: + start = int(rng.group(1)) + end = int(rng.group(2)) if rng.group(2) else size - 1 + if start >= size or end < start or end >= size: + return self.send(416, b"", "audio/mpeg", {"Content-Range": "bytes */%d" % size}) + return self.send(206, data[start:end + 1], "audio/mpeg", + {"Accept-Ranges": "bytes", "Content-Range": "bytes %d-%d/%d" % (start, end, size)}) + return self.send(200, data, "audio/mpeg", {"Accept-Ranges": "bytes"}) + if rest == "playback-state": + cur = STATE["playback"].get(bid) + if method == "GET": + if not cur: + return self.send(200, b"") # null: the real server sends 200 with no body + return self.send(200, {k: v for k, v in cur.items() if k != "operationId"}) + if method == "DELETE": + STATE["playback"].pop(bid, None) + return self.send(204, b"") + if method == "PUT": + d = self.body() + if not isinstance(d, dict): + return self.error(400, "Bad JSON") + checks = (("assetId", lambda v: isinstance(v, str) and ASSET_ID.match(v)), + ("positionMs", lambda v: isinstance(v, int) and not isinstance(v, bool) and v >= 0), + ("capturedAt", lambda v: isinstance(v, str) and ISO.match(v)), + ("operationId", lambda v: isinstance(v, str) and UUID.match(v)), + ("baseRevision", lambda v: isinstance(v, int) and not isinstance(v, bool) and v >= 0), + ("manifestRevision", lambda v: isinstance(v, str) and re.match(r"^[0-9a-f]{64}$", v))) + for name, ok in checks: + if not ok(d.get(name)): + return self.error(400, "%s is not valid" % name) + extra = set(d) - {n for n, _ in checks} + if extra: + return self.error(400, "property %s should not exist" % sorted(extra)[0]) + if d["manifestRevision"] != manifest_revision(ab): + return self.error(412, "Audiobook manifest has changed") + a = next((a for a in ab["assets"] if a["assetId"] == d["assetId"]), None) + if not a: + return self.error(400, "assetId does not belong to this audiobook") + if cur and cur.get("operationId") == d["operationId"]: + return self.send(200, {k: v for k, v in cur.items() if k != "operationId"}) # a resend: no change + if d["positionMs"] > a["durationMs"] + 1000: + return self.error(400, "positionMs exceeds the asset duration") + if d["baseRevision"] != (cur["revision"] if cur else 0): + return self.error(409, "Playback state revision conflict") + pos = min(d["positionMs"], a["durationMs"]) + total = sum(x["durationMs"] for x in ab["assets"]) + before = sum(x["durationMs"] for x in ab["assets"] if x["sequence"] < a["sequence"]) + pct = max(0.0, min(100.0, (before + pos) * 100.0 / total)) + STATE["playback"][bid] = {"assetId": d["assetId"], "positionMs": pos, "percentage": pct, + "completed": pct >= 100, "capturedAt": d["capturedAt"], + "revision": (cur["revision"] if cur else 0) + 1, + "manifestRevision": d["manifestRevision"], "operationId": d["operationId"]} + return self.send(200, {k: v for k, v in STATE["playback"][bid].items() if k != "operationId"}) + return self.error(404, "Not Found") + + +if __name__ == "__main__": + port = int(sys.argv[1]) if len(sys.argv) > 1 else 18096 + print("mock BookOrbit on 127.0.0.1:%d (KOReader user %s, API key %s...)" % (port, KO_USER, API_KEY[:8]), flush=True) + ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever() diff --git a/tools/gzreader/tests/mock_bookorbit_test.py b/tools/gzreader/tests/mock_bookorbit_test.py new file mode 100644 index 000000000..4a5e857d3 --- /dev/null +++ b/tools/gzreader/tests/mock_bookorbit_test.py @@ -0,0 +1,439 @@ +"""The mock BookOrbit server answers as the real one does (routes, sign-ins, +field names, refusals), so the tests built on it mean something. + + python3 -I mock_bookorbit_test.py + +Run by the plugin suite (run_tests.lua), which checks its last line. +""" +import hashlib, json, os, re, subprocess, sys, time, urllib.request, urllib.error + +PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18196 +HERE = os.path.dirname(os.path.abspath(__file__)) +BASE = "http://127.0.0.1:%d" % PORT +USER, PASSWORD = "will-kindle", "hunter22" +KEY = "bok_" + "a1B2c3D4e5" * 4 + "f6G7h8I9j" +KO = {"x-auth-user": USER, "x-auth-key": hashlib.md5(PASSWORD.encode()).hexdigest()} +API = {"Authorization": "Bearer " + KEY} +DEV = {"deviceId": "kindle-pw3_01", "deviceModel": "Kindle Paperwhite 3", "pluginVersion": "1.35.0"} +passed = failed = 0 + + +def check(cond, name): + global passed, failed + if cond: + passed += 1 + else: + failed += 1 + print("FAIL: " + name) + + +def call(method, path, headers=None, body=None, raw=False): + data = json.dumps(body).encode() if body is not None else None + h = dict(headers or {}) + if data is not None: + h["Content-Type"] = "application/json" + req = urllib.request.Request(BASE + path, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(req, timeout=10) as r: + code, out, hdr = r.status, r.read(), r.headers + except urllib.error.HTTPError as e: + code, out, hdr = e.code, e.read(), e.headers + if raw: + return code, out, hdr + try: + return code, json.loads(out) if out else None + except ValueError: + return code, None + + +proc = subprocess.Popen([sys.executable, "-I", os.path.join(HERE, "mock_bookorbit.py"), str(PORT)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +try: + for _ in range(50): + try: + call("GET", "/_mock/state") + break + except OSError: + time.sleep(0.1) + + # --- the KOReader sign-in + code, j = call("GET", "/api/v1/koreader/users/auth", KO) + check(code == 200 and j == {"authorized": "OK", "username": USER}, "sign-in with the MD5 key") + code, j = call("GET", "/api/v1/koreader/users/auth", {"x-auth-user": USER, "x-auth-key": PASSWORD}) + check(code == 200, "sign-in with the plain password") + check(call("GET", "/api/v1/koreader/users/auth")[0] == 401, "no credentials: 401") + check(call("GET", "/api/v1/koreader/users/auth", {"x-auth-user": USER, "x-auth-key": "wrong"})[0] == 401, "wrong password: 401") + check(call("GET", "/api/v1/koreader/users/auth", API)[0] == 401, "an API key is not a KOReader sign-in") + call("POST", "/_mock/set", body={"sync_enabled": False}) + check(call("GET", "/api/v1/koreader/users/auth", KO)[0] == 403, "sync switched off: 403") + call("POST", "/_mock/reset") + + # --- version and capabilities + code, j = call("GET", "/api/v1/koreader/plugin/version", KO) + check(code == 200 and "bookmarkSync" in j["capabilities"] and j["serverVersion"], "version lists capabilities") + call("POST", "/_mock/set", body={"capabilities": ["catalogListsV2"]}) + check(call("GET", "/api/v1/koreader/plugin/version", KO)[1]["capabilities"] == ["catalogListsV2"], "capabilities can be switched") + call("POST", "/_mock/reset") + + # --- catalog + code, j = call("GET", "/api/v1/koreader/plugin/catalog/root", KO) + check(code == 200 and [i["section"] for i in j["sections"]] == ["continue-reading", "recent", "libraries", "collections", + "smart-scopes", "authors", "series", "all-books"], "catalog root") + check(j["sections"][2]["href"].endswith("/sections/libraries") and "booksHref" in j["sections"][7], "root: lists and book links") + code, j = call("GET", "/api/v1/koreader/plugin/catalog/sections/libraries", KO) + check(code == 200 and j["section"] == "libraries" and j["items"][0]["title"] == "Fiction" and j["items"][0]["count"] == 3, "libraries section") + check(j["items"][0]["id"] == "1" and "libraryId=1" in j["items"][0]["booksHref"], "libraries: id and link") + check(call("GET", "/api/v1/koreader/plugin/catalog/sections/nope", KO)[0] == 400, "unknown section: 400") + code, a = call("GET", "/api/v1/koreader/plugin/catalog/sections/authors", KO) + check(a["total"] == 4 and a["items"][0]["title"] == "Ada Marsh" and a["items"][0]["authorId"] == 1, "authors section") + check(call("GET", a["items"][0]["booksHref"], KO)[1]["total"] == 2, "an author's link lists their books") + code, se = call("GET", "/api/v1/koreader/plugin/catalog/sections/series", KO) + check(call("GET", se["items"][0]["booksHref"], KO)[1]["items"][0]["seriesIndex"] == 1, "a series link lists it in order") + code, j = call("GET", "/api/v1/koreader/plugin/catalog/books?size=2&sort=title", KO) + check(code == 200 and j["total"] == 5 and len(j["items"]) == 2 and j["hasNext"] and not j["hasPrevious"] and j["nextUrl"], "books: first page") + check(j["items"][0]["title"] == "A Field Guide to Fog" and j["items"][0]["formats"] == ["epub"], "books: sorted by title") + need = {"id", "title", "authors", "seriesId", "seriesName", "seriesIndex", "progressPercentage", "lastReadAt", "readStatus", + "formats", "hasCover", "thumbnailUrl", "detailUrl", "addedAt", "updatedAt"} + check(j["seriesSummary"] is None and set(j["items"][0]) == need, "books: the list item's fields") + code, j = call("GET", "/api/v1/koreader/plugin/catalog/books?size=2&sort=title&page=3", KO) + check(len(j["items"]) == 1 and not j["hasNext"] and j["hasPrevious"], "books: last page") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?libraryId=2", KO)[1]["total"] == 2, "books: by library") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?collectionId=12", KO)[1]["total"] == 2, "books: by collection") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?q=okafor", KO)[1]["total"] == 2, "books: search") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?sort=bogus", KO)[0] == 400, "books: bad sort is refused") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?size=500", KO)[0] == 400, "books: oversize page is refused") + code, d = call("GET", "/api/v1/koreader/plugin/catalog/books/101", KO) + f = d["files"][0] + check(code == 200 and d["libraryName"] == "Fiction" and d["seriesName"] == "Waymarks" and f["format"] == "epub" and f["role"] == "primary" and f["downloadUrl"], "book detail (its main file is \"primary\")") + check(call("GET", "/api/v1/koreader/plugin/catalog/books/999", KO)[0] == 404, "missing book: 404") + code, png, hdr = call("GET", "/api/v1/koreader/plugin/catalog/books/101/thumbnail", KO, raw=True) + check(code == 200 and png[:4] == b"\x89PNG" and hdr["Content-Type"] == "image/png", "thumbnail is a PNG") + check(call("GET", "/api/v1/koreader/plugin/catalog/books/101/thumbnail", dict(KO, **{"If-None-Match": hdr["ETag"]}), raw=True)[0] == 304, + "thumbnail: not changed is 304") + code, data, hdr = call("GET", f["downloadUrl"], KO, raw=True) + check(code == 200 and len(data) == f["sizeBytes"] and hashlib.md5(data).hexdigest() == f["fileHash"], "download gives the file") + check(call("GET", f["downloadUrl"])[0] == 401, "download needs the sign-in") + + # --- matching and progress + h = f["fileHash"] + code, j = call("POST", "/api/v1/koreader/plugin/match-check", KO, dict(DEV, hashes=[h, "0" * 32])) + check(code == 201 and j["matches"] == [{"hash": h, "bookId": 101, "bookFileId": f["id"]}] and j["libraryVersion"], "match-check") + check(call("POST", "/api/v1/koreader/plugin/match-check", KO, {"hashes": [h]})[0] == 400, "match-check needs the device fields") + check(call("POST", "/api/v1/koreader/plugin/match-check", KO, dict(DEV, deviceId="bad id!", hashes=[h]))[0] == 400, "bad deviceId is refused") + check(call("POST", "/api/v1/koreader/plugin/match-check", KO, dict(DEV, hashes=["x"]))[0] == 400, "a non-MD5 hash is refused") + code, j = call("POST", "/api/v1/koreader/plugin/progress", KO, + dict(DEV, items=[{"hash": h, "percentage": 0.42, "progress": "/body/DocFragment[3]/body/p[7]/text().0", "timestamp": 1790000000}, + {"hash": "f" * 32, "percentage": 0.1}])) + check(code == 201 and j["results"] == [{"hash": h, "accepted": True}] and j["unmatched"] == ["f" * 32], "progress: accepted and unmatched") + check(call("POST", "/api/v1/koreader/plugin/progress", KO, dict(DEV, items=[{"hash": h, "percentage": 42}]))[0] == 400, "progress: percentage is 0 to 1") + code, j = call("GET", "/api/v1/koreader/syncs/progress/" + h, KO) + check(code == 200 and j["percentage"] == 0.42 and j["progress"].startswith("/body/") and j["document"] == h + and j["device"] == DEV["deviceModel"] and j["timestamp"] == 1790000000, "KOSync reads the position back") + check(call("GET", "/api/v1/koreader/syncs/progress/" + "e" * 32, KO) == (200, {}), "KOSync: no position is {}") + code, j = call("PUT", "/api/v1/koreader/syncs/progress", KO, {"document": h, "percentage": 0.5, "progress": "x", "device": "K", "device_id": "k1"}) + check(code == 200 and j["document"] == h and j["timestamp"], "KOSync writes a position") + check(call("PUT", "/api/v1/koreader/syncs/progress", KO, {"document": "d" * 32, "percentage": 0.5})[0] == 404, "KOSync: unknown book is 404") + d = call("GET", "/api/v1/koreader/plugin/catalog/books/101", KO)[1] + check(d["progressPercentage"] == 50 and d["progress"]["fileId"] == f["id"] and d["readStatus"] == "reading", + "the catalog shows the progress, out of 100") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?readStatus=reading", KO)[1]["total"] == 1, "books: by read status") + + # --- highlights: the exchange + X = "/api/v1/koreader/plugin/annotations/exchange" + hl = {"datetime": "2026-11-22 09:00:00", "drawer": "lighten", "color": "yellow", "text": "a line", "note": "mine", + "chapter": "One", "pageno": 3, "posFormat": "xpointer", "pos0": "/body/DocFragment[2]/body/p[1]/text().0", "pos1": "/body/DocFragment[2]/body/p[1]/text().6"} + k1 = hashlib.md5(("%s|%s" % (hl["datetime"], hl["pos0"])).encode()).hexdigest() + bk = {"hash": h, "keys": [{"k": k1, "dt": hl["datetime"]}], "keysComplete": True, "sidecarState": "new", "changes": [hl]} + code, j = call("POST", X, KO, dict(DEV, books=[bk])) + r = j["results"][0] + check(code == 201 and r["bookId"] == 101 and r["applied"]["created"] == 1 and r["toApply"] == {"add": [], "edit": [], "delete": []} + and j["unmatched"] == [] and j["positionIncompatible"] == [], "a new highlight from the device is taken; nothing comes back") + web = call("POST", "/_mock/set", body={"web_highlight": {"book": 101, "op": "add", "pos0": "/body/DocFragment[3]/body/p[2]/text().0", + "pos1": "/body/DocFragment[3]/body/p[2]/text().9", "text": "from the web", "color": "blue"}})[1] + bk2 = dict(bk, sidecarState="known", changes=[]) + r = call("POST", X, KO, dict(DEV, books=[bk2]))[1]["results"][0] + check(len(r["toApply"]["add"]) == 1 and r["toApply"]["add"][0]["text"] == "from the web" and r["toApply"]["add"][0]["serverId"] == web["serverId"] + and r["applied"]["created"] == 0, "a highlight made on the web is offered to the device") + check(len(call("POST", X, KO, dict(DEV, books=[bk2]))[1]["results"][0]["toApply"]["add"]) == 1, "…and again until the device says it has it") + code, j = call("POST", X + "-ack", KO, dict(DEV, books=[{"hash": h, "applied": [{"serverId": web["serverId"], "version": 1, "status": "applied"}], "deleted": []}])) + check(code == 201 and j["results"] == [{"hash": h, "acked": 1}], "the device acknowledges it") + kw = web["key"] + bk3 = dict(bk2, keys=[{"k": k1, "dt": hl["datetime"]}, {"k": kw, "dt": web["datetime"]}]) + check(call("POST", X, KO, dict(DEV, books=[bk3]))[1]["results"][0]["toApply"]["add"] == [], "…and it isn't offered again") + call("POST", "/_mock/set", body={"web_highlight": {"book": 101, "op": "edit", "serverId": web["serverId"], "note": "a note added on the web"}}) + r = call("POST", X, KO, dict(DEV, books=[bk3]))[1]["results"][0] + check(len(r["toApply"]["edit"]) == 1 and r["toApply"]["edit"][0]["key"] == kw and r["toApply"]["edit"][0]["note"] == "a note added on the web" + and r["toApply"]["edit"][0]["version"] == 2, "an edit on the web comes as an edit, by the device's key") + call("POST", X + "-ack", KO, dict(DEV, books=[{"hash": h, "applied": [{"serverId": web["serverId"], "version": 2, "status": "applied"}], "deleted": []}])) + r = call("POST", X, KO, dict(DEV, books=[dict(bk3, changes=[dict(hl, note="changed on the device", datetimeUpdated="2026-11-22 13:00:00")])]))[1]["results"][0] + check(r["applied"]["updated"] == 1 and r["toApply"]["edit"] == [], "an edit on the device is taken") + r = call("POST", X, KO, dict(DEV, books=[dict(bk3, keys=[{"k": k1, "dt": hl["datetime"]}])]))[1]["results"][0] + check(r["applied"]["deviceDeleted"] == 1 and r["toApply"]["delete"] == [], "a highlight gone from the device's list is deleted on the server") + first = call("GET", "/_mock/state")[1]["annotations"]["101"][0] + call("POST", "/_mock/set", body={"web_highlight": {"book": 101, "op": "delete", "serverId": first["serverId"]}}) + r = call("POST", X, KO, dict(DEV, books=[dict(bk3, keys=[{"k": k1, "dt": hl["datetime"]}])]))[1]["results"][0] + check(r["toApply"]["delete"] == [{"serverId": first["serverId"], "key": k1, "datetime": hl["datetime"]}], "a delete on the web comes as a delete, by the device's key") + call("POST", X + "-ack", KO, dict(DEV, books=[{"hash": h, "applied": [], "deleted": [{"serverId": first["serverId"], "status": "applied"}]}])) + check(call("POST", X, KO, dict(DEV, books=[dict(bk3, keys=[])]))[1]["results"][0]["toApply"]["delete"] == [], "…once acknowledged, not again") + other = dict(DEV, deviceId="another-kindle") + r = call("POST", X, KO, dict(other, books=[dict(bk, changes=[], keys=[])]))[1]["results"][0] + check(r["toApply"]["add"] == [] and r["applied"]["deviceDeleted"] == 0, "another device with a fresh copy: nothing is deleted (both were deleted already)") + check(call("POST", X, KO, dict(DEV, books=[dict(bk, hash="f" * 32)]))[1]["unmatched"] == ["f" * 32], "a book BookOrbit doesn't have: unmatched") + for bad, what in ((dict(hl, drawer="wavy"), "an unknown style"), (dict(hl, datetime="yesterday"), "a bad datetime"), + (dict(hl, posFormat="cfi"), "an unknown position format"), (dict(hl, extra=1), "an unknown field"), + ({k: v for k, v in hl.items() if k != "pos0"}, "no position")): + check(call("POST", X, KO, dict(DEV, books=[dict(bk, changes=[bad])]))[0] == 400, "the exchange refuses " + what) + check(call("POST", X, KO, dict(DEV, books=[dict(bk, keys=[{"k": "nope", "dt": hl["datetime"]}])]))[0] == 400, "the exchange refuses a bad key") + check(call("POST", X, KO, dict(DEV, books=[]))[0] == 400 and call("POST", X, KO, {"books": [bk]})[0] == 400, "the exchange needs books and the device fields") + + # --- bookmarks: the exchange + B = "/api/v1/koreader/plugin/bookmarks/exchange" + bm = {"datetime": "2026-11-22 09:30:00", "pos": "/body/DocFragment[2]/body/p[4]/text().0", "pageno": 4, "chapter": "One", "note": "come back here"} + bk1 = hashlib.md5(("%s|%s" % (bm["datetime"], bm["pos"])).encode()).hexdigest() + mb = {"hash": h, "keys": [{"k": bk1, "dt": bm["datetime"]}], "keysComplete": True, "sidecarState": "new", "changes": [bm]} + code, j = call("POST", B, KO, dict(DEV, books=[mb])) + r = j["results"][0] + check(code == 201 and r["accepted"] == 1 and r["toApply"] == {"add": [], "delete": []}, "a bookmark from the device is taken") + check(call("POST", B, KO, dict(DEV, books=[dict(mb, sidecarState="known")]))[1]["results"][0]["duplicates"] == 1, "the same one again is a duplicate") + wm = call("POST", "/_mock/set", body={"web_bookmark": {"book": 101, "op": "add", "pos": "/body/DocFragment[5]/body/p[1]/text().0", "pageno": 30, "title": "Five"}})[1] + mb2 = dict(mb, sidecarState="known", changes=[]) + r = call("POST", B, KO, dict(DEV, books=[mb2]))[1]["results"][0] + check(r["toApply"]["add"] == [{"serverId": wm["serverId"], "pos": wm["pos"], "pageno": 30, "title": "Five"}], "a bookmark made elsewhere is offered (no date: the device dates it)") + wk = hashlib.md5(("2026-11-22 14:00:00|%s" % wm["pos"]).encode()).hexdigest() + code, j = call("POST", B + "-ack", KO, dict(DEV, books=[{"hash": h, "applied": [{"serverId": wm["serverId"], "status": "applied", "key": wk, + "datetime": "2026-11-22 14:00:00", "pos": wm["pos"]}], "deleted": []}])) + check(code == 201 and j["results"] == [{"hash": h, "acked": 1}], "the device says which key it has it under") + mb3 = dict(mb2, keys=[{"k": bk1, "dt": bm["datetime"]}, {"k": wk, "dt": "2026-11-22 14:00:00"}]) + check(call("POST", B, KO, dict(DEV, books=[mb3]))[1]["results"][0]["toApply"]["add"] == [], "…and it isn't offered again") + r = call("POST", B, KO, dict(DEV, books=[dict(mb3, keys=[{"k": bk1, "dt": bm["datetime"]}])]))[1]["results"][0] + check(r["deviceDeleted"] == 1, "a bookmark gone from the device's list is deleted on the server") + first_mark = call("GET", "/_mock/state")[1]["bookmarks"]["101"][0] + call("POST", "/_mock/set", body={"web_bookmark": {"book": 101, "op": "delete", "serverId": first_mark["serverId"]}}) + r = call("POST", B, KO, dict(DEV, books=[dict(mb3, keys=[{"k": bk1, "dt": bm["datetime"]}])]))[1]["results"][0] + check(r["toApply"]["delete"] == [{"serverId": first_mark["serverId"], "key": bk1, "datetime": bm["datetime"]}], "a delete elsewhere comes by the device's key") + check(call("POST", B, KO, dict(DEV, books=[dict(mb, changes=[dict(bm, extra=1)])]))[0] == 400 + and call("POST", B, KO, dict(DEV, books=[dict(mb, changes=[{"datetime": bm["datetime"]}])]))[0] == 400, "the bookmark exchange refuses an unknown field and no place") + + # --- reading time and ratings + P = "/api/v1/koreader/plugin/page-stats" + ev = [{"page": 3, "startTime": 1790000100, "durationSeconds": 40, "totalPages": 240}, {"page": 4, "startTime": 1790000140, "durationSeconds": 35, "totalPages": 240}] + code, j = call("POST", P, KO, dict(DEV, books=[{"hash": h, "bookFileId": f["id"], "events": ev}, {"hash": "e" * 32, "events": ev}])) + check(code == 201 and j["results"] == [{"hash": h, "accepted": 2, "duplicates": 0}] and j["unmatched"] == ["e" * 32], "page rows taken; a book BookOrbit doesn't have is unmatched") + check(call("POST", P, KO, dict(DEV, books=[{"hash": h, "events": ev}]))[1]["results"][0] == {"hash": h, "accepted": 0, "duplicates": 2}, "the same rows again are duplicates") + for bad, what in (([dict(ev[0], durationSeconds=90000)], "a duration over a day"), ([dict(ev[0], startTime=0)], "no start time"), + ([dict(ev[0], page=1.5)], "a fractional page"), ([], "no events")): + check(call("POST", P, KO, dict(DEV, books=[{"hash": h, "events": bad}]))[0] == 400, "page-stats refuses " + what) + R = "/api/v1/koreader/plugin/catalog/books/101/rating" + check(call("PUT", R, KO, {"rating": 4}) == (200, {"rating": 4}) and call("GET", "/api/v1/koreader/plugin/catalog/books/101", KO)[1]["rating"] == 4, "a rating set, and in the book's record") + check(call("PUT", R, KO, {"rating": 0})[0] == 200 and call("PUT", R, KO, {"rating": 6})[0] == 400 and call("PUT", R, KO, {"stars": 3})[0] == 400 + and call("PUT", "/api/v1/koreader/plugin/catalog/books/999/rating", KO, {"rating": 3})[0] == 404, "ratings: 0 to 5, known books only") + + # --- the main API: key, audiobooks + code, j = call("GET", "/api/v1/auth/me", API) + check(code == 200 and j["authenticationMethod"] == "api_key", "API key as Bearer") + check(call("GET", "/api/v1/auth/me", {"X-Api-Key": KEY})[0] == 200, "API key as X-Api-Key") + check(call("GET", "/api/v1/auth/me?api_key=" + KEY)[0] == 401, "API key in the address is refused") + check(call("GET", "/api/v1/auth/me", {"Authorization": "Bearer bok_wrong"})[0] == 401, "wrong API key: 401") + check(call("GET", "/api/v1/auth/me", {"Authorization": "Bearer " + KEY, "X-Api-Key": KEY[:-1] + "x"})[1]["message"] == "Conflicting credentials", + "two keys that disagree are refused") + call("POST", "/_mock/set", body={"api_keys_enabled": False}) + check(call("GET", "/api/v1/auth/me", API)[1].get("errorCode") == "API_KEYS_DISABLED", "API keys switched off") + call("POST", "/_mock/set", body={"api_keys_enabled": True}) + check(call("GET", "/api/v1/auth/me", KO)[0] == 401, "a KOReader sign-in is not an API key") + code, m = call("GET", "/api/v1/audiobooks/201/manifest", API) + a0, a1 = m["assets"] + check(code == 200 and m["schema"] == "bookorbit.audiobook-manifest" and len(m["revision"]) == 64 and m["totalDurationMs"] == 105000 and a0["sequence"] == 0 + and m["chapters"][1]["startMs"] == 60000 and m["chapters"][1]["assetId"] == a1["assetId"], "audiobook manifest") + check(call("GET", "/api/v1/audiobooks/999/manifest", API)[0] == 404, "missing audiobook: 404") + url = "/api/v1/audiobooks/201/assets/%s/content" % a0["assetId"] + code, data, hdr = call("GET", url, API, raw=True) + check(code == 200 and len(data) == a0["sizeBytes"] and hdr["Accept-Ranges"] == "bytes", "audio file, whole") + code, part, hdr = call("GET", url, dict(API, Range="bytes=1000-"), raw=True) + check(code == 206 and part == data[1000:] and hdr["Content-Range"] == "bytes 1000-%d/%d" % (len(data) - 1, len(data)), "audio file, resumed") + check(call("GET", url, dict(API, Range="bytes=999999-"), raw=True)[0] == 416, "audio file: a range past the end is 416") + check(call("GET", url, raw=True)[0] == 401, "audio file needs the key") + + state = "/api/v1/audiobooks/201/playback-state" + check(call("GET", state, API, raw=True)[:2] == (200, b""), "no position yet: an empty reply") + put = {"assetId": a1["assetId"], "positionMs": 15000, "capturedAt": "2026-11-22T10:00:00.000Z", + "operationId": "3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6b", "baseRevision": 0, "manifestRevision": m["revision"]} + code, j = call("PUT", state, API, put) + check(code == 200 and j["revision"] == 1 and j["positionMs"] == 15000 and abs(j["percentage"] - 7500000 / 105000.0) < 1e-9 + and j["completed"] is False and "operationId" not in j, "position saved, out of 100") + check(call("PUT", state, API, put)[1]["revision"] == 1, "the same operation sent twice changes nothing") + code, j = call("PUT", state, API, dict(put, operationId="3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6c", positionMs=20000)) + check(code == 409, "a stale base revision is a conflict") + code, j = call("PUT", state, API, dict(put, operationId="3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6c", positionMs=20000, baseRevision=1)) + check(code == 200 and j["revision"] == 2, "the next save with the new base revision") + check(call("PUT", state, API, dict(put, manifestRevision="0" * 64, baseRevision=2, operationId="3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6d"))[0] + == 412, "an old manifest revision is refused (412)") + check(call("PUT", state, API, dict(put, positionMs=99000, baseRevision=2, operationId="3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6e"))[0] == 400, + "a position past the file's end is refused") + check(call("PUT", state, API, dict(put, assetId="aud_33333333-3333-4333-8333-333333333333", baseRevision=2, + operationId="3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6f"))[0] == 400, "another book's file is refused") + check(call("PUT", state, API, dict(put, assetId="6201"))[0] == 400, "the asset id must be aud_") + check(call("PUT", state, API, dict(put, positionMs=1.5))[0] == 400, "the position is whole milliseconds") + check(call("PUT", state, API, dict(put, extra=1))[0] == 400, "unknown fields are refused") + call("POST", "/_mock/set", body={"api_key_write": False}) + code, j = call("PUT", state, API, put) + check(code == 403 and j["errorCode"] == "API_KEY_READ_ONLY", "a read-only key can't save a position") + check(call("GET", state, API)[1]["revision"] == 2, "a read-only key can read it") + call("POST", "/_mock/set", body={"api_key_write": True}) + check(call("DELETE", state, API, raw=True)[0] == 204 and call("GET", state, API, raw=True)[1] == b"", "position cleared") + + # --- finding the audiobooks, and the probe script + q = {"sort": [{"field": "title", "dir": "asc"}], "pagination": {"page": 1, "size": 5}, + "filter": {"type": "group", "join": "AND", "rules": [{"type": "rule", "field": "format", "operator": "includesAny", "value": ["MP3"]}]}} + code, j = call("POST", "/api/v1/books/query", API, q) + check(code == 201 and j["total"] == 1 and j["items"][0]["id"] == 201, "books/query finds the audiobook by format") + q["filter"]["rules"][0]["value"] = ["epub"] + check(call("POST", "/api/v1/books/query", API, q)[1]["total"] == 0, "books/query: no audio format, no audiobook") + check(call("POST", "/api/v1/books/query", API, {"page": 1})[0] == 400, "books/query needs sort and pagination") + call("POST", "/_mock/set", body={"api_key_write": False}) + check(call("POST", "/api/v1/books/query", API, q)[0] == 201, "a read-only key can run books/query") + call("POST", "/_mock/set", body={"api_key_write": True}) + + call("POST", "/_mock/set", body={"seen": []}) + env = dict(os.environ, BOOKORBIT_URL=BASE, BOOKORBIT_KO_USER=USER, BOOKORBIT_KO_PASSWORD=PASSWORD, BOOKORBIT_API_KEY=KEY) + probe = [sys.executable, "-I", os.path.join(HERE, "..", "bookorbit-probe.py")] + r = subprocess.run(probe, env=env, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=60) + out = r.stdout + r.stderr + check(r.returncode == 0 and "MISSING" not in out and "no answer" not in out, "the probe runs clean against the mock") + check(out.count("has every field GZreader's tests use") == 4, "the probe compares four shapes") + check("audio file (first 1 KB, resumable?) 206" in out and "2 file(s), 2 chapter(s)" in out, "the probe reaches the audiobook") + for secret, what in ((PASSWORD, "password"), (KO["x-auth-key"], "password's MD5"), (KEY, "API key"), (USER, "user name"), + ("127.0.0.1", "address"), ("Long Way", "a book's title"), ("Marsh", "an author")): + check(secret not in out, "the probe never prints the " + what) + seen = call("GET", "/_mock/state")[1] + check(all(m == "GET" or p in ("koreader/plugin/match-check",) for m, p in seen["seen"]) and len(seen["seen"]) > 10 + and seen["playback"] == {}, "the probe only reads") + env["BOOKORBIT_KO_PASSWORD"] = "nope-nope" + r = subprocess.run(probe, env=env, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=60) + env2 = dict(env, BOOKORBIT_URL="http://127.0.0.1:1") + r2 = subprocess.run(probe, env=env2, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=60) + check(r2.returncode == 1 and "connection refused" in r2.stdout and "The sign-in wasn't tried" in r2.stdout and "127.0.0.1" not in r2.stdout, + "the probe says why there was no answer, without the address") + env2["BOOKORBIT_URL"] = "https://no-such-host.invalid" + r2 = subprocess.run(probe, env=env2, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=60) + check(r2.returncode == 1 and "no-such-host" not in r2.stdout and "no answer" in r2.stdout, "a name that doesn't exist: said, not echoed") + check(r.returncode == 1 and "401" in r.stdout and "nope-nope" not in r.stdout and "version" not in r.stdout, "the probe stops at a failed sign-in") + + # --- collections on the main API + code, cols = call("GET", "/api/v1/collections", API) + check(code == 200 and [c["id"] for c in cols] == [11, 12] and cols[0]["bookCount"] == 2 and cols[0]["userId"] == 1, "collections listed with the API key") + check(call("GET", "/api/v1/collections", KO)[0] == 401, "…not with the e-reader sign-in") + CB = "/api/v1/collections/11/books" + check(call("POST", CB, API, {"bookIds": [103]})[0] == 201 and call("GET", "/api/v1/koreader/plugin/catalog/books?collectionId=11", KO)[1]["total"] == 3, + "a book added to a collection shows in the e-reader catalog") + check(call("DELETE", CB, API, {"bookIds": [103]})[0] == 200 and call("GET", "/api/v1/koreader/plugin/catalog/books?collectionId=11", KO)[1]["total"] == 2, "…and taken off again") + check(call("POST", CB, API, {"bookIds": []})[0] == 400 and call("POST", "/api/v1/collections/99/books", API, {"bookIds": [103]})[0] == 404, "collections: bad or unknown") + call("POST", "/_mock/set", body={"collection_owners": {"13": 2}}) + check(call("POST", "/api/v1/collections/13/books", API, {"bookIds": [103]})[0] == 403 and len(call("GET", "/api/v1/collections", API)[1]) == 3, + "someone else's shared collection is listed but can't be changed") + call("POST", "/_mock/set", body={"api_key_write": False}) + check(call("POST", CB, API, {"bookIds": [103]})[1].get("errorCode") == "API_KEY_READ_ONLY", "a read-only key can't change a collection") + call("POST", "/_mock/set", body={"api_key_write": True}) + + # --- book requests on the main API + BR = "/api/v1/book-requests" + code, j = call("POST", BR, API, {"title": "The Salt Road", "authors": ["Ines Ward"], "mediaKind": "ebook"}) + check(code == 201 and j["subscribed"] is False and j["request"]["status"] == "pending" and j["request"]["authors"] == ["Ines Ward"], "a book requested") + rid = j["request"]["id"] + check(call("POST", BR, KO, {"title": "x", "mediaKind": "ebook"})[0] == 401, "…not with the e-reader sign-in") + check(call("POST", BR, API, {"title": "", "mediaKind": "ebook"})[0] == 400 and call("POST", BR, API, {"title": "x", "mediaKind": "comic"})[0] == 400 + and call("POST", BR, API, {"title": "x", "mediaKind": "ebook", "extra": 1})[0] == 400, "requests: bad ones refused") + code, j = call("POST", BR, API, {"title": "the salt road", "mediaKind": "ebook"}) + check(code == 201 and j["request"]["id"] == rid and j["subscribed"] is False, "asking again for the same book is the same request") + other = call("POST", "/_mock/set", body={"add_request": {"title": "Low Tide", "mediaKind": "audiobook", "userId": 2, "status": "searching"}})[1]["id"] + code, j = call("POST", BR, API, {"title": "Low Tide", "mediaKind": "audiobook"}) + check(code == 201 and j["request"]["id"] == other and j["subscribed"] is True and j["request"]["status"] == "searching", "someone else's request joined") + code, j = call("GET", BR + "?page=1&limit=100", API) + check(code == 200 and j["total"] == 2 and [r["id"] for r in j["items"]] == [other, rid], "your requests listed, newest first (the joined one too)") + check(call("GET", BR + "?limit=500", API)[0] == 400, "requests: at most 100 a page") + call("POST", "/_mock/set", body={"request_update": {"id": rid, "status": "rejected", "decisionNote": "Not this month"}}) + check(call("GET", BR + "/%d" % rid, API)[1]["decisionNote"] == "Not this month" and call("POST", BR + "/%d/cancel" % rid, API)[0] == 400, + "a decided request shows its note and can't be cancelled") + code, j = call("POST", BR, API, {"title": "The Salt Road", "mediaKind": "ebook"}) + rid2 = j["request"]["id"] + check(code == 201 and rid2 != rid and call("POST", BR + "/%d/cancel" % rid2, API, {})[1]["status"] == "cancelled", "asked again after a no; then cancelled") + check(call("POST", BR + "/%d/cancel" % other, API, {})[0] == 403 and call("POST", BR + "/999/cancel", API, {})[0] == 404, "someone else's can't be cancelled") + call("POST", "/_mock/set", body={"request_permission": False}) + check(call("GET", BR, API)[0] == 403 and call("POST", BR, API, {"title": "x", "mediaKind": "ebook"})[0] == 403, "without the Request books permission: 403") + call("POST", "/_mock/set", body={"request_permission": True, "api_key_write": False}) + check(call("GET", BR, API)[0] == 200 and call("POST", BR, API, {"title": "x", "mediaKind": "ebook"})[1].get("errorCode") == "API_KEY_READ_ONLY", + "a read-only key lists requests but can't make one") + call("POST", "/_mock/set", body={"api_key_write": True}) + + # --- the KOReader sync sign-in through the API key + KC = "/api/v1/koreader/credentials" + code, j = call("GET", KC, API) + check(code == 200 and j["username"] == "will-kindle" and j["syncEnabled"] is True and "password" not in j and "passwordMd5" not in j, + "the sync sign-in's name with the API key (never its password)") + check(call("GET", KC, KO)[0] == 401, "…not with the e-reader sign-in") + check(call("POST", KC, API, {"username": "another", "password": "secret12"})[0] == 409, "a second sign-in can't be made") + import io as _io, zipfile as _zip, hashlib as _hl + code, raw, _h = call("GET", "/api/v1/koreader/plugin-package?origin=http%3A%2F%2Fbooks.example.com", API, raw=True) + names = _zip.ZipFile(_io.BytesIO(raw)).namelist() if code == 200 else [] + prov = _zip.ZipFile(_io.BytesIO(raw)).read("bookorbit.koplugin/bookorbit_provision.lua").decode() if names else "" + check(code == 200 and 'username = "will-kindle"' in prov and ('userkey = "%s"' % _hl.md5(b"hunter22").hexdigest()) in prov + and 'server_url = "http://books.example.com"' in prov, "the preconfigured plugin download carries the sync name and key") + check(call("GET", "/api/v1/koreader/plugin-package", API)[0] == 400, "…and needs an origin") + call("POST", "/_mock/set", body={"ko_md5_known": False}) + check(call("GET", "/api/v1/koreader/plugin-package?origin=http%3A%2F%2Fbooks.example.com", API)[0] == 400, "an old sign-in: its key can't be handed over") + call("POST", "/_mock/set", body={"ko_md5_known": True, "key_ko_permission": False}) + check(call("GET", KC, API)[0] == 403, "a key without the KOReader sync permission: 403") + call("POST", "/_mock/set", body={"key_ko_permission": True, "ko_credentials": False, "ko_names_taken": ["will"]}) + code, raw, _h = call("GET", KC, API, raw=True) + check(code == 200 and raw == b"" and call("GET", "/api/v1/koreader/users/auth", KO)[0] == 401, "no sign-in yet: an empty answer, and the old one doesn't work") + check(call("POST", KC, API, {"username": "will", "password": "secret12"})[0] == 409 and call("POST", KC, API, {"username": "wi", "password": "secret12"})[0] == 400 + and call("POST", KC, API, {"username": "will-2", "password": "short"})[0] == 400, "making one: a taken name, a short name, a short password refused") + check(call("POST", KC, API, {"username": "will-2", "password": "secret12"})[0] == 201 + and call("GET", "/api/v1/koreader/users/auth", {"x-auth-user": "will-2", "x-auth-key": _hl.md5(b"secret12").hexdigest()})[0] == 200 + and call("GET", KC, API)[1]["username"] == "will-2", "one made with the key signs in") + call("POST", "/_mock/set", body={"ko_credentials": True, "ko_made": None, "ko_names_taken": []}) + + # --- a browser on another site (the sync page): only when a reverse proxy lets it in + PAGE = "https://sync.example.com" + pre = {"Origin": PAGE, "Access-Control-Request-Method": "GET", "Access-Control-Request-Headers": "x-auth-user, x-auth-key"} + code, raw, hdr = call("OPTIONS", "/api/v1/koreader/users/auth", pre, raw=True) + code2, raw, hdr2 = call("GET", "/api/v1/koreader/users/auth", dict(KO, Origin=PAGE), raw=True) + check(code == 404 and hdr.get("Access-Control-Allow-Origin") is None and code2 == 200 and hdr2.get("Access-Control-Allow-Origin") is None, + "as BookOrbit in production: no preflight answer, no cross-origin headers") + call("POST", "/_mock/set", body={"cors_origin": PAGE}) + code, raw, hdr = call("OPTIONS", "/api/v1/koreader/users/auth", pre, raw=True) + code2, raw, hdr2 = call("GET", "/api/v1/koreader/users/auth", dict(KO, Origin=PAGE), raw=True) + check(code == 204 and hdr.get("Access-Control-Allow-Origin") == PAGE and "x-auth-key" in hdr.get("Access-Control-Allow-Headers", "") + and code2 == 200 and hdr2.get("Access-Control-Allow-Origin") == PAGE, "behind a proxy that lets the page in: preflight and requests answered for it") + code, raw, hdr = call("OPTIONS", "/api/v1/koreader/users/auth", dict(pre, Origin="https://other.example.com"), raw=True) + check(code == 404 and hdr.get("Access-Control-Allow-Origin") is None, "…and for no other site") + call("POST", "/_mock/set", body={"cors_origin": None}) + + # --- the reader's dashboard (stats over every device) + code, j = call("GET", "/api/v1/koreader/plugin/catalog/dashboard", KO) + ry = j.get("readingYear") or {} + check(code == 200 and len(ry.get("minutes", [])) == 371 and ry["minutes"][-1] == 25 and ry["minutes"][-2] == 0 and re.match(r"^\d{4}-\d\d-\d\d$", ry["startDate"]) + and j["readingStreak"] == {"currentStreak": 1, "longestStreak": 21, "lastSevenDays": [m > 0 for m in ry["minutes"][-7:]]} + and j["readingGoal"]["goalBooks"] == 30 and j["readingGoal"]["completedBooks"] == 12 and j["totalBooks"] >= 3 + and j["achievements"]["next"]["threshold"] == 50 and j["yearAgo"]["days"] == 9 and len(j["finishedThisYear"]) == 3 + and j["highlightOfTheDay"]["chapterTitle"] == "Chapter 3" and j["browseCounts"]["inProgress"] == 2, + "the dashboard: streak, goal, a year of minutes per day, badges, a year ago, finished books, a highlight") + check(call("GET", "/api/v1/koreader/plugin/catalog/dashboard", API)[0] == 401 + and call("GET", "/api/v1/koreader/plugin/catalog/dashboard?section=nope", KO)[0] == 400, "…with the e-reader sign-in only; an unknown section refused") + call("POST", "/_mock/set", body={"goal_books": None, "achievements": False, "reading_year": False}) + code, j = call("GET", "/api/v1/koreader/plugin/catalog/dashboard", KO) + check(code == 200 and j["readingGoal"]["goalBooks"] is None and j["achievements"] is None and "readingYear" not in j, + "no goal, badges off, an older server: the dashboard says so") + call("POST", "/_mock/set", body={"goal_books": 30, "achievements": True, "reading_year": True}) + + # --- the server away + call("POST", "/_mock/set", body={"offline": True}) + check(call("GET", "/api/v1/koreader/users/auth", KO)[0] == 503, "offline: 503") + call("POST", "/_mock/reset") + seen = call("GET", "/_mock/state")[1] + check(seen["seen"] == [] and seen["progress"] == {}, "reset clears the state") +finally: + proc.terminate() + proc.wait(timeout=5) + +print("%d passed, %d failed" % (passed, failed)) +sys.exit(1 if failed else 0) diff --git a/tools/gzreader/tests/qs_test.lua b/tools/gzreader/tests/qs_test.lua index 209966d41..b65b22040 100644 --- a/tools/gzreader/tests/qs_test.lua +++ b/tools/gzreader/tests/qs_test.lua @@ -17,8 +17,9 @@ table.insert(package.loaders, 2, function(name) end) G_reader_settings = { readSetting = function() end } local M = dofile(ZEN .. "/common/quickstart/quickstart_pages.lua") -local function build(paired) - local grimmory = { api = { isPaired = function() return paired end }, store = { username = "will" }, +local function build(paired, backend, source) + local grimmory = { api = { isPaired = function() return paired end }, store = { username = "will", book_source = source }, + backend = function() return backend or "grimmory" end, save = function() SAVES = (SAVES or 0) + 1 end, useLibraryAsHome = function() HOME_SET = (HOME_SET or 0) + 1 end } return M.build_install_pages({ plugin = { ui = { gzreader = grimmory } }, config = { navbar = { show_tabs = {} }, _meta = {}, features = {} } }) @@ -32,8 +33,9 @@ local has_folder_page = false for _, pg in ipairs(pages) do if pg.title == "Home Folder" then has_folder_page = true end end check(not has_folder_page, "no 'Home Folder' question in the guide") check(HOME_SET == 1, "guide sets the home folder to the Grimmory folder instead") -check(pages[1].title == "Set up from your browser", "setup guide starts with Set up from your browser (Grimmory, Notes, Calendar, books)") -check(pages[2].title == "Welcome to GZreader", "GZreader welcome follows") +check(pages[1].title == "How will you use GZreader?", "the setup guide starts by asking how GZreader will be used") +check(pages[2].title == "Set up from your browser", "then Set up from your browser (the book server, Notes, Calendar, books)") +check(pages[3].title == "Welcome to GZreader", "GZreader welcome follows") local titles = {} for _, pg in ipairs(pages) do titles[#titles + 1] = pg.title end local tl = table.concat(titles, "|") check(tl:match("Your keyboard") and tl:match("Synced with Grimmory"), "GZreader pages: keyboard, sync") @@ -75,17 +77,52 @@ check(sleep.choice_layout == "tiles" and #sleep.choices == 4 and sleep.choices[3 local SAVED = {} G_reader_settings.makeTrue = function(_, k) SAVED[k] = true end G_reader_settings.makeFalse = function(_, k) SAVED[k] = false end sleep.on_apply({ gz_auto = true }) check(SAVED.gzreader_sleep_auto == true and SAVED.screensaver_show_message == false, "choosing it turns GZreader sleep mode on (no message over it)") -local ids = {} for _, c in ipairs(pages[1].choices) do ids[#ids + 1] = c.id .. (c.checked and "*" or "") end -check(table.concat(ids, ",") == "qr*,type,gz_copy,skip", "not connected: QR (default), type, copy from another GZreader, skip") -BROADCAST = nil; pages[1].on_apply({ qr = true }); check(BROADCAST == "GrimmoryPair", "QR choice -> GrimmoryPair event") -BROADCAST = nil; pages[1].on_apply({ type = true }); check(BROADCAST == "GrimmoryKeyboardLogin", "type choice -> keyboard login event") -BROADCAST = nil; pages[1].on_apply({ skip = true }); check(BROADCAST == nil, "skip -> nothing") -BROADCAST = nil; pages[1].on_apply({ gz_copy = true }); check(BROADCAST == "GzCopyReceive", "copy choice -> GzCopyReceive event") +local function idsOf(pg) local ids = {} for _, c in ipairs(pg.choices) do ids[#ids + 1] = c.id .. (c.checked and "*" or "") end return table.concat(ids, ",") end +-- the first question: Grimmory, BookOrbit, or on its own +local how, connect = pages[1], pages[2] +check(how.choice_type == "radio" and idsOf(how) == "grimmory*,bookorbit,local", "how: Grimmory (the default), BookOrbit, or on its own with books from a browser") +check(idsOf(connect) == "qr*,type,gz_copy,skip" and connect.description:match("connect Grimmory"), "Grimmory, not connected: QR (default), type, copy from another GZreader, skip") +BROADCAST = nil; connect.on_apply({ qr = true }); check(BROADCAST == "GrimmoryPair", "QR choice -> GrimmoryPair event") +BROADCAST = nil; connect.on_apply({ type = true }); check(BROADCAST == "GrimmoryKeyboardLogin", "type choice -> keyboard login event") +BROADCAST = nil; connect.on_apply({ skip = true }); check(BROADCAST == nil, "skip -> nothing") +BROADCAST = nil; connect.on_apply({ gz_copy = true }); check(BROADCAST == "GzCopyReceive", "copy choice -> GzCopyReceive event") +connect.reset_selection = nil; SAVES = 0 +how.on_apply({ grimmory = true }) +check(connect.reset_selection == nil and SAVES == 1, "answering Grimmory: the next page stays as it is; the answer is saved") +how.on_apply({ grimmory = true }) +check(SAVES == 1, "the same answer again isn't saved twice") +how.on_apply({ bookorbit = true }) +check(idsOf(connect) == "bo_qr*,bo_type,skip" and connect.reset_selection == true and connect.description:match("connect BookOrbit") + and connect.description:match("KOReader sync user name") and connect.choices[2].text == "Type my BookOrbit login here", + "answering BookOrbit: the next page is BookOrbit's (which sign-in it wants), its defaults again") +BROADCAST = nil; connect.on_apply({ bo_qr = true }); check(BROADCAST == "BookOrbitPair", "BookOrbit, from a browser -> BookOrbitPair event") +BROADCAST = nil; connect.on_apply({ bo_type = true }); check(BROADCAST == "BookOrbitKeyboardLogin", "BookOrbit, typed -> its keyboard login event") +how.on_apply({ ["local"] = true }) +check(idsOf(connect) == "books*,gz_copy,skip" and connect.title == "Send books from your browser" and connect.description:match("drop your books"), + "answering on its own: the next page is sending books from a browser") +BROADCAST = nil; connect.on_apply({ books = true }); check(BROADCAST == "GzSendBooksPage", "show the QR code -> the setup page at Send books") +check(SAVES == 3, "each new answer is saved") +local function syncPage(pgs) for _, pg in ipairs(pgs) do if pg.gz_sync_page then return pg end end end +check(syncPage(pages).title == "Your books" and syncPage(pages).description:match("kept on this Kindle"), "on its own: the guide's sync page says the books stay on the Kindle") +how.on_apply({ bookorbit = true }) +check(syncPage(pages).title == "Books from BookOrbit" and syncPage(pages).description:match("browse and download your books"), "BookOrbit: it says what works (gzreader_bookorbit's note, when it loads)") +how.on_apply({ grimmory = true }) +check(syncPage(pages).title == "Synced with Grimmory" and syncPage(pages).description:match("in sync with Grimmory"), "Grimmory again: as before") +-- what was answered before, and what this Kindle is signed in to +local again = build(false, nil, "local") +check(syncPage(again).title == "Your books", "…and the sync page fits it from the start") +check(idsOf(again[1]) == "grimmory,bookorbit,local*" and again[2].title == "Send books from your browser", "the guide again: the earlier answer is the default") pages = build(true) -ids = {} for _, c in ipairs(pages[1].choices) do ids[#ids + 1] = c.id .. (c.checked and "*" or "") end -check(table.concat(ids, ",") == "keep*,qr,type,gz_copy,gz_send,skip" and pages[1].choices[1].text:match("will"), "already connected: keep (default) shows account; send to another GZreader offered") -BROADCAST = nil; pages[1].on_apply({ gz_send = true }); check(BROADCAST == "GzCopySend", "send choice -> GzCopySend event") -BROADCAST = nil; pages[1].on_apply({ keep = true }); check(BROADCAST == nil, "keep -> nothing") +how, connect = pages[1], pages[2] +check(idsOf(how) == "grimmory*,bookorbit,local" and idsOf(connect) == "keep*,qr,type,gz_copy,gz_send,skip" and connect.choices[1].text:match("will"), + "connected to Grimmory: keep (default) shows the account; send to another GZreader offered") +BROADCAST = nil; connect.on_apply({ gz_send = true }); check(BROADCAST == "GzCopySend", "send choice -> GzCopySend event") +BROADCAST = nil; connect.on_apply({ keep = true }); check(BROADCAST == nil, "keep -> nothing") +how.on_apply({ bookorbit = true }) +check(idsOf(connect) == "bo_qr*,bo_type,gz_send,skip", "connected to Grimmory, answering BookOrbit: no \"keep\" (it's the other server's)") +local orbit = build(true, "bookorbit", "grimmory") +check(idsOf(orbit[1]) == "grimmory,bookorbit*,local" and idsOf(orbit[2]) == "keep*,bo_qr,bo_type,gz_send,skip", + "connected to BookOrbit: that's the default (whatever was answered before), and its connection can be kept") local np = M.build_install_pages({ plugin = { ui = {} }, config = { navbar = { show_tabs = {} }, _meta = {}, features = {} } }) check(np[1].title == "Welcome to GZreader", "no Grimmory plugin -> starts with the welcome") diff --git a/tools/gzreader/tests/run_tests.lua b/tools/gzreader/tests/run_tests.lua index c143bd10e..8414cf303 100644 --- a/tools/gzreader/tests/run_tests.lua +++ b/tools/gzreader/tests/run_tests.lua @@ -4897,6 +4897,30 @@ do GS.stale(rplugin) GS.values(rplugin) check(rplugin.store.grimmory_stats.error == nil, "asked again after this Kindle's sessions reached Grimmory") + -- what the page draws: the week's books, the month's days, finished books by month + local all = GS.all(rplugin) + local Page = require("gzreader_statspage") + check(all.server == "grimmory" and all.name == "Grimmory" and rplugin.store.grimmory_stats.server == "grimmory" + and type(all.detail.week_books) == "table" and #all.detail.week_books == 1 and all.detail.week_books[1].seconds == all.values.week_time + and type(all.detail.month_days) == "table" and #all.detail.month_days >= 1 and all.detail.month_days[1].count >= 1 + and #all.detail.finished_months == 2 and all.detail.finished_months[2].month == 11 and all.detail.finished_months[2].finished == 1, + "the page's detail kept: the week's books, the month's days read, finished by month") + local kinds = {} + for _i, sec in ipairs(Page.sections(all)) do kinds[#kinds + 1] = sec.kind .. (sec.sideways and "-side" or "") end + check(table.concat(kinds, " ") == "numbers bars-side month bars text", "the Grimmory page: numbers, the week's books, the month, finished by month, the rest " .. table.concat(kinds, " ")) + local grid = Page.monthGrid(2026, 11, { { day = 1, count = 2 }, { day = 30, count = 5 } }) + check(#grid.rows == 6 and grid.rows[1][7] and grid.rows[1][7].day == 1 and grid.rows[1][7].count == 2 and grid.rows[1][6] == false + and grid.rows[6][1].day == 30 and grid.rows[6][2] == false and grid.max == 5, + "the month as a calendar: November 2026 starts on a Sunday and ends on a Monday") + check(Page.time(59) == "1 min" and Page.time(3600) == "1 h" and Page.time(7500) == "2 h 5 min" and Page.time(nil) == "0 min", + "times in words") + check(Page.footer({ name = "Grimmory", at = 1000 }, 1000 + 600):find("from Grimmory, as of 10 minutes ago", 1, true) ~= nil + and Page.footer({ name = "BookOrbit" }, 5):find("Nothing from BookOrbit yet", 1, true) ~= nil, "the page says whose numbers and how old") + -- numbers kept from the other server aren't shown as this one's + rplugin.store.grimmory_stats.server = "bookorbit" + check(GS.kept(rplugin) == nil and next(GS.all(rplugin).values) == nil or GS.all(rplugin).values.week_books ~= nil, + "numbers kept from another server aren't this one's (asked again)") + check(rplugin.store.grimmory_stats.server == "grimmory", "…and Grimmory's are back after asking") end print("Ratings (Grimmory's personal rating)") @@ -14922,6 +14946,1180 @@ print("Immich: an album's pictures for the sleep screen and the Home wallpaper") plugin.store.immich = nil end)() +print("The mock BookOrbit server answers as the real one does, and the probe script (mock_bookorbit_test.py)") +;(function() + local pp = io.popen("python3 -I " .. PLUGIN .. "/../../tools/gzreader/tests/mock_bookorbit_test.py " .. (PORT + 60) .. " 2>&1") + local out = pp:read("*a"); pp:close() + for line in out:gmatch("[^\n]+") do + if line:find("FAIL", 1, true) then print(" " .. line) end + end + local passed, failed = out:match("(%d+) passed, (%d+) failed") + check(tonumber(passed) and tonumber(passed) >= 88 and failed == "0", "mock_bookorbit_test.py: " .. tostring(passed) .. " passed, " .. tostring(failed) .. " failed") +end)() + +print("BookOrbit as the book server: sign in, browse, covers, download") +;(function() + local BP = PORT + 61 + local BO = "http://127.0.0.1:" .. BP + os.execute("python3 -I " .. PLUGIN .. "/../../tools/gzreader/tests/mock_bookorbit.py " .. BP + .. " > " .. WORK .. "/bookorbit.log 2>&1 & echo $! > " .. WORK .. "/bookorbit.pid") + local function bctl(path, body) + local pp = io.popen("curl -s " .. (body and ("-H 'Content-Type: application/json' -d '" .. body .. "' ") or "") .. BO .. path) + local t = pp:read("*a"); pp:close() + return t ~= "" and json.decode(t) or {} + end + for _try = 1, 50 do + if bctl("/_mock/state").capabilities then break end + socket.sleep(0.2) + end + local BookOrbit = require("gzreader_bookorbit") + local Api = require("gzreader_api") + local Covers = require("gzreader_covers") + local lfs = require("libs/libkoreader-lfs") + local md5 = require("ffi/sha2").md5 + + -- the pure parts + check(BookOrbit.pickFormat({ "pdf", "m4b", "EPUB" }) == "epub" and BookOrbit.pickFormat({ "m4b" }) == nil and BookOrbit.pickFormat(nil) == nil, + "the format to read: the first KOReader opens, EPUB before PDF; none for an audiobook") + local tb = BookOrbit.toBook({ id = 7, title = "A: B/C?", authors = { "X", json.null }, formats = { "epub" }, seriesName = json.null, + seriesIndex = 2, progressPercentage = 42.5, readStatus = "reading", lastReadAt = "2026-11-21T10:00:00.000Z" }) + check(tb.id == 7 and tb.primaryFileType == "EPUB" and tb.primaryFileName == "A B C.epub" and #tb.authors == 1 and tb.seriesName == nil + and tb.seriesNumber == 2 and tb.readProgress == 42.5 and tb.readStatus == "READING", "a catalog item as a GZreader book (nulls dropped, a safe file name)") + check(BookOrbit.toBook({ id = 8, title = "T", formats = { "m4b" } }).primaryFileType == "AUDIOBOOK" and BookOrbit.toBook({ title = "no id" }) == nil, + "an audiobook is told apart; an item without an id is left out") + check(BookOrbit.pickFile({ files = { { id = 1, format = "pdf", role = "primary", downloadUrl = "/a" }, { id = 2, format = "epub", role = "content", downloadUrl = "/b" }, + { id = 3, format = "epub", role = "primary", downloadUrl = "/c" }, { id = 4, format = "epub", role = "supplement", downloadUrl = "/d" } } }).id == 3, + "the file to download: EPUB before PDF, the book's main file before another of the same format") + check(BookOrbit.pickFile({ files = { { id = 5, format = "m4b", role = "primary", downloadUrl = "/a" }, { id = 6, format = "epub", role = "content", downloadUrl = "/b" } } }).id == 6 + and BookOrbit.pickFile({ files = { { id = 7, format = "epub", role = "cover", downloadUrl = "/a" }, { id = 8, format = "epub", role = "primary" } } }) == nil, + "…a book whose main file is audio: its ebook; a file that isn't the book's, or has no address: none") + + -- signing in + local saved = { server = plugin.store.server, username = plugin.store.username, downloads = plugin.store.downloads } + -- (earlier tests put their stand-ins back as fields of the client itself, which would hide the other class's methods) + for k, v in pairs(plugin.api) do + if type(v) == "function" and k ~= "on_change" then plugin.api[k] = nil end + end + check(plugin:backend() == "grimmory" and plugin.api:isPaired() and not plugin:booksOnly(), "before: signed in to Grimmory") + plugin.store.downloads = { ["101"] = { path = "/nowhere/grimmory-book.epub", title = "Grimmory's 101" } } + local g_refresh = plugin.store.refresh_token + local ok, err = plugin:connect(BO, "will-kindle", "wrong", "bookorbit") + check(not ok and err:find("KOReader sync user name", 1, true) and plugin:backend() == "grimmory" and plugin.store.refresh_token == g_refresh + and plugin.store.server == saved.server and getmetatable(plugin.api) == Api, + "a wrong BookOrbit password: said plainly, and the Grimmory sign-in is untouched") + bctl("/_mock/set", '{"sync_enabled": false}') + ok, err = plugin:connect(BO, "will-kindle", "hunter22", "bookorbit") + check(not ok and err:find("sync switched off", 1, true), "sync switched off in BookOrbit: said so") + bctl("/_mock/set", '{"sync_enabled": true}') + ok, err = plugin:connect("http://127.0.0.1:" .. PORT, "will-kindle", "hunter22", "bookorbit") + check(not ok and err:find("check that the address is BookOrbit's", 1, true) and plugin:backend() == "grimmory", + "Grimmory's address given as BookOrbit's (it answers 401): the message also says to check the address") + check(plugin:describeError("bookorbit_not_found"):find("not as BookOrbit", 1, true) ~= nil, "an address with no BookOrbit there (404): said so") + local api_table = plugin.api + ok, err = plugin:connect(BO, "will-kindle", "hunter22", "bookorbit") + check(ok and plugin:backend() == "bookorbit" and plugin.api == api_table and getmetatable(plugin.api) == BookOrbit and plugin:booksOnly() + and plugin.api:isPaired() and plugin:serverName() == "BookOrbit", "signed in to BookOrbit: the same client table, now BookOrbit's") + check(plugin.store.server == BO and plugin.store.username == "will-kindle" and plugin.store.bookorbit.key == md5("hunter22") + and plugin.store.refresh_token == nil and plugin.store.access_token == nil, "kept: the address, the name and the password's MD5; Grimmory's tokens gone") + local dump = require("dump") and require("dump")(plugin.store) or "" + check(not dump:find("hunter22", 1, true), "the password itself is nowhere in the settings") + check(plugin.store.bookorbit.server_version == "0.9.0" and plugin.api:can("bookmarkSync") and not plugin.api:can("nope"), "the server's version and capabilities are read") + check(next(plugin.store.downloads) == nil and plugin.store.downloads_other.grimmory["101"].title == "Grimmory's 101", + "Grimmory's list of downloads is put aside (its ids are other books here)") + check(Covers.dir():match("gzreader%-covers%-bookorbit$") ~= nil, "BookOrbit's covers have their own folder") + local S = require("gzreader_secrets") + local in_secrets = false + for _i, p in ipairs(S.PATHS) do if p[1] == "bookorbit" and p[2] == "key" then in_secrets = true end end + check(in_secrets, "the sign-in key is one of the secrets kept off the USB drive") + check(plugin:syncEnabled() and plugin:serverCan("progress") and plugin:serverCan("annotations") and plugin:serverCan("bookmarks") + and plugin:serverCan("ratings") and plugin:serverCan("stats") and not plugin:serverCan("sessions"), + "with BookOrbit: progress, highlights, bookmarks, ratings and reading time are synced (Grimmory's own reading sessions aren't sent to it)") + plugin:queue("session", nil, { bookId = 101 }) + check(#plugin.store.pending.sessions == 0, "…and what it doesn't take (reading sessions) isn't kept to send") + check(type(plugin.store.bookorbit_device) == "string" and plugin.store.bookorbit_device:match("^gz%-%x+$") ~= nil, "this Kindle's device id is made at sign-in") + + -- browsing + local page = plugin.api:listBooks{ page = 0, size = 2, sort = "title", dir = "asc", fileType = plugin.api.READABLE_TYPES } + check(page and #page.content == 2 and page.totalElements == 5 and page.totalPages == 3 and page.hasNext and not page.hasPrevious + and page.content[1].title == "A Field Guide to Fog" and page.content[1].primaryFileType == "EPUB" + and page.content[1].primaryFileName == "A Field Guide to Fog.epub", "a page of books, as the Catalog reads one") + local last = plugin.api:listBooks{ page = 2, size = 2, sort = "title", dir = "asc" } + check(last and #last.content == 1 and not last.hasNext and last.content[1].primaryFileType == "PDF", "the last page; a PDF book") + check(plugin.api:listBooks{ page = 0, size = 50, libraryId = 2 }.totalElements == 2, "a library's books") + check(plugin.api:listBooks{ page = 0, size = 50, shelfId = 12 }.totalElements == 2, "a collection's books (GZreader's shelf)") + check(plugin.api:listBooks{ page = 0, size = 50, authors = "Ada Marsh" }.totalElements == 2, "an author's books") + local ser = plugin.api:listBooks{ page = 0, size = 50, series = "Waymarks", sort = "seriesNumber", dir = "asc" } + check(ser.totalElements == 2 and ser.content[1].seriesNumber == 1 and ser.content[2].seriesNumber == 2, "a series, in order") + check(plugin.api:searchBooks("okafor").totalElements == 2 and plugin.api:listBooks{ page = 0, size = 50, search = "trains" }.content[1].id == 104, "searching") + check(plugin.api:listBooks{ page = 0, size = 500 }.size == 100, "a page is never asked for bigger than the server gives") + local audio = plugin.api:listBooks{ page = 0, size = 20, fileType = { "AUDIOBOOK" } } + check(audio and #audio.content == 0 and audio.totalPages == 0 and not plugin.api:hasApiKey(), "audiobooks without an API key: an empty list, not an error") + local libs = plugin.api:listLibraries() + check(libs and #libs == 2 and libs[1].id == 1 and libs[1].name == "Fiction" and libs[1].bookCount == 3, "libraries") + local shelves = plugin.api:listShelves() + check(shelves and #shelves == 2 and shelves[1].name == "Beach reads" and shelves[1].bookCount == 2 and not shelves[1].magic, "collections as shelves") + local recent = plugin.api:simpleList("recently-added", 3) + check(recent and #recent == 3 and recent[1].addedOn >= recent[2].addedOn, "recently added, newest first") + check(#plugin.api:continueReading(10) == 0, "continue reading: nothing in progress yet") + local full = plugin.api:getBook(101) + check(full and full.primaryFile.id == 5101 and full.primaryFileId == 5101 and full.metadata.description == "About The Long Way Round." + and full.libraryId == 1 and full.fileSizeKb == 2 and #full.primaryFile.fileHash == 32, "a book's record: its file and metadata") + local d = plugin.api:getBookDetail(101) + check(d and d.publisher == "Example House" and d.pageCount == 240 and d.seriesName == "Waymarks" and d.seriesNumber == 1, "a book's page") + local none, nerr = plugin.api:getBook(999) + check(none == nil and nerr == "http_404" and plugin:describeError(nerr) == "BookOrbit returned an error (404).", "a missing book: BookOrbit's error, by name") + -- the library index (authors and series come from it) builds from these pages + local Index = require("gzreader_index") + local built + Index.build(plugin, false, function(data) built = data end) + runLoop(function() return built ~= nil end, 30) + if type(built) ~= "table" then print(" index:", tostring(built)) end + check(type(built) == "table" and built.total == 5 and built.authors["Ben Okafor"] == 2 and built.series["Waymarks"].count == 2 + and built.libraries["1"] == 3, "the library index builds from BookOrbit (authors, series, libraries)") + + -- covers and files + local cover = WORK .. "/bo-cover.jpg" + os.remove(cover) + check(plugin.api:downloadThumbnail(101, cover) == true and lfs.attributes(cover, "size") > 50, "a cover") + local c_ok, c_err, c_code = plugin.api:downloadThumbnail(999, cover .. "2") + check(c_ok == false and c_code == 404 and lfs.attributes(cover .. "2.part") == nil, "no cover: 404, nothing left behind") + local got = plugin.api:downloadThumbnails{ { id = 102, path = WORK .. "/bo-c102.jpg" }, { id = 999, path = WORK .. "/bo-c999.jpg" } } + check(got.got == 1 and #got.none == 1 and got.none[1] == 999, "a page of covers: the ones there, and which have none") + local file = WORK .. "/bo-book.epub.part" + local f = io.open(file, "wb"); f:write("an interrupted part from before"); f:close() + local d_ok, d_err = plugin.api:downloadToFile(101, file, true) + local fh = io.open(file, "rb"); local data = fh and fh:read("*a") or ""; if fh then fh:close() end + check(d_ok == true and md5(data) == full.primaryFile.fileHash and #data == 1280, "a book's file, whole (an old part is started again, not added to)", d_err) + d_ok, d_err = plugin.api:downloadToFile(999, file .. "x") + check(d_ok == false and d_err == "http_404" and lfs.attributes(file .. "x") == nil, "a missing book's file: an error, nothing left behind") + local seen = bctl("/_mock/state").seen + local only_get = #seen > 10 + -- (match-check is a POST that only asks which of the Kindle's files BookOrbit has) + for _i, e in ipairs(seen) do if e[1] ~= "GET" and e[2] ~= "koreader/plugin/match-check" then only_get = false end end + check(only_get, "browsing and downloading only ever read from BookOrbit") + + -- reading progress: out by the file's fingerprint, in from the book's record + local xp = "/body/DocFragment[3]/body/p[7]/text().0" + local p_ok, p_err, p_code = plugin.api:putProgress(101, { fileProgress = { progressPercent = 42.5 }, gz_xp = xp }) + check(p_ok == false and p_err == "bookorbit_unmatched" and p_code == 404, "progress for a book with no fingerprint kept: not sent (dropped, as a book that's gone)") + local hash101 = BookOrbit.hashFile(file) + check(hash101 == full.primaryFile.fileHash, "the downloaded file's fingerprint (KOReader's partial MD5) is the one BookOrbit has") + plugin.store.downloads["101"] = { path = file, title = "The Long Way Round", file_id = 5101, hash = hash101 } + p_ok, p_err = plugin.api:putProgress(101, { fileProgress = { progressPercent = 42.5 }, gz_xp = xp, gz_file = "ignored" }) + local st = bctl("/_mock/state") + local sent = st.progress[hash101] + check(p_ok == true and sent and math.abs(sent.percentage - 0.425) < 1e-9 and sent.progress == xp and sent.device:match("^GZreader ") + and sent.device_id == plugin.store.bookorbit_device and st.devices[plugin.store.bookorbit_device] ~= nil, + "progress sent: the percentage as 0-1, the page's XPointer as it is, this Kindle named", p_err) + local back = plugin.api:getBook(101) + check(back.epubProgress and back.epubProgress.percentage == 42.5 and back.gz_xp == xp and back.readProgress == 42.5, + "…and read back from the book's record in the shape the progress sync reads (percent, exact place)") + local kept = require("gzreader_sync").progressOf(back) + check(kept and kept.epubProgress.percentage == 42.5, "a download keeps it for the book's first opening") + plugin.store.downloads["105"] = { path = "/nowhere/tide.pdf", hash = plugin.api:getBook(105).primaryFile.fileHash } + check(plugin.api:putProgress(105, { fileProgress = { progressPercent = 30, positionData = "12" } }) == true + and plugin.api:getBook(105).pdfProgress.page == 12 and plugin.api:getBook(105).epubProgress == nil, "a PDF: the page number out and back") + plugin.store.downloads["105"] = nil + plugin.store.downloads["900"] = { path = "/nowhere/x.epub", hash = string.rep("ab", 16) } + p_ok, p_err, p_code = plugin.api:putProgress(900, { fileProgress = { progressPercent = 10 } }) + check(p_ok == false and p_err == "bookorbit_unmatched" and p_code == 404, "a file BookOrbit has no book for: said so (it's dropped, not retried forever)") + plugin.store.downloads["900"] = nil + -- queued and sent in the background, as when reading + plugin:queue("progress", 101, { fileProgress = { progressPercent = 55 }, gz_xp = "/body/DocFragment[4]/body/p[1]/text().0" }) + check(plugin.store.pending.progress["101"] ~= nil, "progress is queued") + plugin:flushPending() + runLoop(function() return not plugin.flushing and plugin.store.pending.progress["101"] == nil end, 20) + check(plugin.store.pending.progress["101"] == nil and math.abs(bctl("/_mock/state").progress[hash101].percentage - 0.55) < 1e-9, + "…and sent by the usual queue") + local Sync = require("gzreader_sync") + local sy = setmetatable({ api = plugin.api, localPosition = function() return { pct = 15, local_pct = 11.2 } end, atEnd = function() return false end }, { __index = Sync }) + check(sy:sentPosition().pct == 11.2, "the percentage sent to BookOrbit is KOReader's own (the footer's), not the web reader's") + sy.api = { } + check(sy:sentPosition().pct == 15, "…Grimmory still gets the web reader's") + -- the books already on the Kindle are matched to BookOrbit's by fingerprint + local m = plugin.api:matchCheck({ hash101, string.rep("0", 32) }) + check(m and m[hash101].book_id == 101 and m[hash101].file_id == 5101 and m[string.rep("0", 32)] == nil, "match-check: which fingerprints BookOrbit has a book for") + local ldir = plugin.store.library_dir + local other = ldir .. "/Grimmory named it differently.epub" + check(plugin.api:downloadToFile(104, other) == true, "(a copy of book 104 under another name, as left by another server)") + local stray = io.open(ldir .. "/Stray.epub", "wb"); stray:write("not a book BookOrbit has"); stray:close() + plugin.store.downloads["104"] = nil + plugin:matchLibraryFiles() + runLoop(function() return plugin.matching == nil end, 20) + local e104 = plugin.store.downloads["104"] + check(e104 and e104.path == other and e104.file_id == 5104 and #e104.hash == 32 and e104.format == "EPUB", + "a book on the Kindle that BookOrbit has is tied to it by its file, whatever its name") + check(plugin.store.bookorbit_unmatched["Stray.epub"] ~= nil and plugin.store.bookorbit_unmatched["Grimmory named it differently.epub"] == nil, + "a file BookOrbit doesn't have is remembered as asked") + local function matchCalls() + local c = 0 + for _i, e in ipairs(bctl("/_mock/state").seen) do if e[2] == "koreader/plugin/match-check" then c = c + 1 end end + return c + end + local calls = matchCalls() + plugin:matchLibraryFiles() + runLoop(function() return plugin.matching == nil end, 5) + check(matchCalls() == calls, "…and isn't asked about again until it changes") + -- it happens by itself: right after signing in, and whenever Wi-Fi comes on + plugin.store.downloads["104"] = nil + plugin.store.bookorbit_unmatched = nil + plugin:afterLogin(plugin:signedInAs(), "bookorbit") + runLoop(function() return plugin.store.downloads["104"] ~= nil end, 20) + check(plugin.store.downloads["104"] and plugin.store.downloads["104"].path == other, + "after signing in to BookOrbit the books already on the Kindle are matched without waiting for the library list") + runLoop(function() return plugin.matching == nil end, 5) + do + local mf = io.open(PLUGIN .. "/main.lua", "rb") + local msrc = mf:read("*a"); mf:close() + local hook = msrc:match("function Grimmory:onNetworkConnected%(%)(.-)\nend\n") or "" + check(hook:find("pcall(self.matchLibraryFiles, self)", 1, true) ~= nil, "…and again whenever Wi-Fi comes on") + end + os.remove(other); os.remove(ldir .. "/Stray.epub") + plugin.store.downloads["104"] = nil + + -- highlights and their notes: BookOrbit's exchange + local BA = require("gzreader_bo_annotations") + local function hl(dt, n, extra) + local a = { datetime = dt, drawer = "lighten", color = "yellow", text = "text " .. n, chapter = "One", pageno = n, + page = "/body/DocFragment[2]/body/p[" .. n .. "]/text().0", pos0 = "/body/DocFragment[2]/body/p[" .. n .. "]/text().0", + pos1 = "/body/DocFragment[2]/body/p[" .. n .. "]/text().9" } + for k, v in pairs(extra or {}) do a[k] = v end + return a + end + local h1, h2 = hl("2026-11-22 09:00:00", 1, { note = "mine" }), hl("2026-11-22 09:05:00", 2) + local page_mark = { datetime = "2026-11-22 09:06:00", page = "/body/DocFragment[2]/body/p[3]/text().0" } + check(BA.key(h1) == md5("2026-11-22 09:00:00|/body/DocFragment[2]/body/p[1]/text().0"), "a highlight's key is md5 of its datetime and start") + local keys, changes, complete = BA.outgoing({ h1, page_mark, h2 }, nil) + check(#keys == 2 and #changes == 2 and complete and keys[1].dt == h1.datetime and changes[1].note == "mine" and changes[1].posFormat == "xpointer" + and changes[2].note == nil and changes[1].page == nil, "what's sent: every highlight's key, the new ones in full; a page bookmark isn't a highlight") + local known = { [BA.key(h1)] = BA.fingerprint(h1), [BA.key(h2)] = BA.fingerprint(h2) } + keys, changes = BA.outgoing({ h1, h2 }, known) + check(#keys == 2 and #changes == 0, "nothing changed since the last exchange: keys only") + h2.note = "added later" + keys, changes = BA.outgoing({ h1, h2 }, known) + check(#changes == 1 and changes[1].note == "added later", "a note added to a highlight: that highlight is sent again") + h2.note = nil + check(BA.toRemote(hl("2026-11-22 09:00:00", 1, { drawer = "wavy", color = "" })).drawer == "lighten" + and BA.toRemote(hl("2026-11-22 09:00:00", 1, { color = "" })).color == nil, "a style BookOrbit doesn't know goes as a plain highlight; no empty fields") + -- merging an answer + local mlist = { hl("2026-11-22 09:00:00", 1), hl("2026-11-22 09:05:00", 2), page_mark } + local ch, applied, deleted = BA.merge(mlist, { + add = { { serverId = 7, version = 1, datetime = "2026-11-22 10:00:00", drawer = "underscore", color = "blue", text = "from the web", note = json.null, + posFormat = "xpointer", pos0 = "/body/DocFragment[3]/body/p[2]/text().0", pos1 = "/body/DocFragment[3]/body/p[2]/text().9", pageno = 12 }, + { serverId = 8, version = 1, datetime = "2026-11-22 10:01:00", drawer = "lighten", posFormat = "xpointer", pos0 = "/bad", pos1 = "/bad2" }, + { serverId = 9, version = 1, datetime = "2026-11-22 10:02:00", drawer = "lighten", posFormat = "pdf", pos0 = "1", pos1 = "2" } }, + edit = { { serverId = 3, version = 4, key = BA.key(mlist[1]), drawer = "strikeout", color = "red", text = "text 1", note = "from the web", datetimeUpdated = "2026-11-22 11:00:00" }, + { serverId = 4, version = 2, key = string.rep("9", 32), drawer = "lighten", color = "red", text = "?" } }, + delete = { { serverId = 5, key = BA.key(mlist[2]), datetime = "2026-11-22 09:05:00" }, { serverId = 6, key = string.rep("8", 32) } }, + }, function(xp) return xp:sub(1, 5) == "/body" end) + check(ch and #mlist == 3 and mlist[1].drawer == "strikeout" and mlist[1].note == "from the web" and mlist[1].color == "red" + and mlist[1].datetime_updated == "2026-11-22 11:00:00" and mlist[2] == page_mark and mlist[3].text == "from the web" + and mlist[3].drawer == "underscore" and mlist[3].note == nil and mlist[3].page == mlist[3].pos0 and mlist[3].pageno == 12, + "an answer merged: a highlight added, one changed, one removed; the page bookmark untouched") + local function status(list, id) for _i, e in ipairs(list) do if e.serverId == id then return e.status, e.version end end end + check(status(applied, 7) == "applied" and status(applied, 8) == "failed" and status(applied, 9) == "failed" and status(applied, 3) == "applied" + and select(2, status(applied, 3)) == 4 and status(applied, 4) == "failed" and status(deleted, 5) == "applied" and status(deleted, 6) == "applied", + "…and what's acknowledged: placed or not (a place not in the book, a PDF place, a highlight not here); a removal already done counts as done") + local before_n = #mlist + BA.merge(mlist, { add = { { serverId = 7, version = 1, datetime = "2026-11-22 10:00:00", drawer = "underscore", posFormat = "xpointer", + pos0 = "/body/DocFragment[3]/body/p[2]/text().0", pos1 = "/body/DocFragment[3]/body/p[2]/text().9" } } }) + check(#mlist == before_n, "a highlight offered twice (the acknowledgement was lost) isn't added twice") + -- a whole pass against the server, with a book "open" + local saves = 0 + local entry101 = plugin.store.downloads["101"] + local book = { h1, h2 } + local ui = { document = { file = file, isXPointerInDocument = function(_d, xp) return xp:sub(1, 5) == "/body" end }, + annotation = { annotations = book, updateAnnotations = function() end, sortItems = function(_s, l) table.sort(l, function(a, b) return a.pos0 < b.pos0 end) end }, + doc_settings = { saveSetting = function() saves = saves + 1 end, flush = function() end }, view = {} } + local fsync = { ui = ui, api = plugin.api, plugin = plugin, entry = entry101, book_id = "101", isRolling = function() return true end } + local anno = BA:new(fsync) + check(anno:enabled(), "highlight sync is on for a BookOrbit book with a fingerprint") + local finished + anno:run(function(ok) finished = ok end) + runLoop(function() return finished ~= nil and not next(require("gzreader_async").jobs or {}) end, 20) + local srv = bctl("/_mock/state").annotations["101"] + check(finished == true and #srv == 2 and srv[1].note == "mine" and srv[1].pos0 == h1.pos0 and entry101.bo_anno[BA.key(h1)] == BA.fingerprint(h1) + and entry101.anno_dirty == nil, "first pass: this Kindle's highlights are on BookOrbit, and remembered as sent") + local web = bctl("/_mock/set", '{"web_highlight": {"book": 101, "op": "add", "pos0": "/body/DocFragment[3]/body/p[2]/text().0", "pos1": "/body/DocFragment[3]/body/p[2]/text().9", "text": "from the web", "color": "blue", "datetime": "2026-11-22 10:00:00"}}') + bctl("/_mock/set", '{"web_highlight": {"book": 101, "op": "edit", "serverId": ' .. srv[1].serverId .. ', "note": "changed on the web"}}') + bctl("/_mock/set", '{"web_highlight": {"book": 101, "op": "delete", "serverId": ' .. srv[2].serverId .. '}}') + finished = nil + anno:run(function(ok) finished = ok end) + runLoop(function() return finished ~= nil end, 20) + runLoop(function() return bctl("/_mock/state").anno_devices[plugin.store.bookorbit_device .. ":101"][tostring(web.serverId)] ~= nil end, 10) + book = ui.annotation.annotations + check(finished == true and #book == 2 and book[1].note == "changed on the web" and book[2].text == "from the web" and book[2].color == "blue" and saves >= 1, + "second pass: the web's new highlight, changed note and removal are in the book, and saved") + local dev = bctl("/_mock/state").anno_devices[plugin.store.bookorbit_device .. ":101"] + check(dev[tostring(web.serverId)] == 1 and dev[tostring(srv[1].serverId)] == 2 and dev[tostring(srv[2].serverId)] == nil, + "…and acknowledged, so BookOrbit doesn't offer them again") + finished = nil + anno:run(function(ok) finished = ok end) + runLoop(function() return finished ~= nil end, 20) + check(#ui.annotation.annotations == 2 and not anno:changedHere(), "a third pass changes nothing") + -- changes here: a note edited (KOReader says nothing), a highlight removed + book[2].note = "my note on the web's highlight" + check(anno:changedHere(), "a note edited here is noticed when the book closes") + table.remove(book, 1) + anno:onAnnotationsModified({ hl("2026-11-22 09:00:00", 1) }) + check(entry101.anno_dirty == true and anno.pending ~= nil, "removing a highlight schedules a pass") + UI.scheduled[anno.pending] = nil; anno.pending = nil + finished = nil + anno:run(function(ok) finished = ok end) + runLoop(function() return finished ~= nil end, 20) + srv = bctl("/_mock/state").annotations["101"] + local gone, noted = false, false + for _i, a in ipairs(srv) do + if a.pos0 == h1.pos0 and a.deleted then gone = true end + if a.text == "from the web" and a.note == "my note on the web's highlight" then noted = true end + end + check(finished == true and gone and noted and #ui.annotation.annotations == 1, "…both reach BookOrbit: the removal and the note") + anno:onAnnotationsModified({ page_mark }) + check(anno.pending == nil, "a page bookmark changing doesn't start a highlight pass") + plugin.store.annotation_sync_disabled = true + check(not anno:enabled(), "the highlights switch in Settings turns it off") + plugin.store.annotation_sync_disabled = nil + fsync.isRolling = function() return false end + check(not BA:new(fsync):enabled(), "a PDF's highlights aren't exchanged (BookOrbit places them in reflowable books only)") + fsync.isRolling = function() return true end + -- a book BookOrbit doesn't have + local lost = BA:new({ ui = ui, api = plugin.api, plugin = plugin, entry = { hash = string.rep("cd", 16) }, book_id = "901", isRolling = function() return true end }) + finished = nil + lost:run(function(ok) finished = ok end) + runLoop(function() return finished ~= nil end, 20) + check(finished == false and lost.off == true and not lost:enabled(), "a book BookOrbit doesn't have: said once in the log, not tried again") + + -- page bookmarks: the same kind of exchange + local BB = require("gzreader_bo_bookmarks") + local function mark(dt, n, label) return { datetime = dt, page = "/body/DocFragment[2]/body/p[" .. n .. "]/text().0", pageno = n, chapter = "One", text = label } end + local m1, m_old = mark("2026-11-22 09:30:00", 4, "come back here"), { page = "/body/DocFragment[2]/body/p[5]/text().0" } + check(BB.isPageBookmark(m1) and not BB.isPageBookmark(h1) and not BB.isPageBookmark({ page = 12 }), "a page bookmark: no highlight, a place in a reflowable book") + local bkeys, bchanges, bcomplete, bdated = BB.outgoing({ m1, h1, m_old }, nil, "2026-11-22 15:00:00") + check(#bkeys == 2 and #bchanges == 2 and bcomplete and bdated and m_old.datetime == "2026-11-22 15:00:00" and bchanges[1].pos == m1.page + and bchanges[1].note == "come back here" and bkeys[1].k == md5(m1.datetime .. "|" .. m1.page), + "what's sent: every bookmark's key and the new ones; one without a date (an older GZreader's) is dated once") + bkeys, bchanges = BB.outgoing({ m1 }, { [BB.key(m1)] = true }) + check(#bkeys == 1 and #bchanges == 0, "a bookmark BookOrbit has had isn't sent again") + local blist = { mark("2026-11-22 09:30:00", 4), h1, mark("2026-11-22 09:40:00", 6) } + local bch, bapplied, bdeleted = BB.merge(blist, { + add = { { serverId = 21, pos = "/body/DocFragment[5]/body/p[1]/text().0", pageno = 30, title = "Five" }, + { serverId = 22, pos = blist[1].page, title = "already dog-eared here" }, { serverId = 23, pos = "/nowhere" }, { serverId = 24, pos = "12" } }, + delete = { { serverId = 25, key = BB.key(blist[3]) }, { serverId = 26, key = string.rep("7", 32) } }, + }, function(xp) return xp:sub(1, 5) == "/body" end, function() return "Chapter Five" end, "2026-11-22 16:00:00") + check(bch and #blist == 3 and blist[2] == h1 and blist[3].page == "/body/DocFragment[5]/body/p[1]/text().0" and blist[3].text == "Five" + and blist[3].chapter == "Chapter Five" and blist[3].datetime == "2026-11-22 16:00:00", + "an answer merged: a bookmark added (dated here, its chapter looked up), one removed; the highlight untouched") + check(status(bapplied, 21) == "applied" and bapplied[1].key == BB.key(blist[3]) and status(bapplied, 22) == "applied" and bapplied[2].key == BB.key(blist[1]) + and status(bapplied, 23) == "failed" and status(bapplied, 24) == "failed" and status(bdeleted, 25) == "applied" and status(bdeleted, 26) == "applied", + "…acknowledged with the key each has here (a page already dog-eared keeps its own); a place not in the book or a page number: not placed") + -- whole passes against the server + plugin.store.downloads["101"] = entry101 + entry101.bo_marks, entry101.bm_dirty = nil, nil + ui.annotation.annotations = { m1, ui.annotation.annotations[1] } + local marks = BB:new(fsync) + check(marks:enabled(), "bookmark sync is on (the server says it does bookmarks)") + finished = nil + marks:reconcile(function(ok) finished = ok end) + runLoop(function() return finished ~= nil end, 20) + local smarks = bctl("/_mock/state").bookmarks["101"] + check(finished == true and #smarks == 1 and smarks[1].pos == m1.page and smarks[1].title == "come back here" and entry101.bo_marks[BB.key(m1)] == true, + "first pass: this Kindle's bookmark is on BookOrbit") + local wmark = bctl("/_mock/set", '{"web_bookmark": {"book": 101, "op": "add", "pos": "/body/DocFragment[5]/body/p[1]/text().0", "pageno": 30, "title": "Five"}}') + finished = nil + marks:reconcile(function(ok) finished = ok end) + runLoop(function() return finished ~= nil end, 20) + runLoop(function() return bctl("/_mock/state").mark_devices[plugin.store.bookorbit_device .. ":101"][tostring(wmark.serverId)] ~= nil end, 10) + local n_marks, added + local function countMarks() + n_marks, added = 0, nil + for _i, a in ipairs(ui.annotation.annotations) do + if BB.isPageBookmark(a) then n_marks = n_marks + 1; if a.text == "Five" then added = a end end + end + end + countMarks() + check(finished == true and n_marks == 2 and added and bctl("/_mock/state").mark_devices[plugin.store.bookorbit_device .. ":101"][tostring(wmark.serverId)] == BB.key(added), + "second pass: a bookmark made elsewhere is in the book, and BookOrbit knows it by this Kindle's key") + -- removed here; removed elsewhere + for i, a in ipairs(ui.annotation.annotations) do if a == added then table.remove(ui.annotation.annotations, i) break end end + marks:onAnnotationsModified({ added, index_modified = -1 }) + check(entry101.bm_dirty == true and marks.pending ~= nil, "removing a bookmark schedules a pass") + UI.scheduled[marks.pending] = nil; marks.pending = nil + bctl("/_mock/set", '{"web_bookmark": {"book": 101, "op": "delete", "serverId": ' .. smarks[1].serverId .. '}}') + finished = nil + marks:reconcile(function(ok) finished = ok end) + runLoop(function() return finished ~= nil end, 20) + countMarks() + local all_gone = true + for _i, m in ipairs(bctl("/_mock/state").bookmarks["101"]) do if not m.deleted then all_gone = false end end + check(finished == true and n_marks == 0 and all_gone, "one removed here and one removed elsewhere: gone on both sides") + marks:onAnnotationsModified({ h1 }) + check(marks.pending == nil, "a highlight changing doesn't start a bookmark pass") + local caps = plugin.store.bookorbit.capabilities + plugin.store.bookorbit.capabilities = { catalogListsV2 = true } + check(not marks:enabled(), "a server that doesn't say it does bookmarks: not tried") + plugin.store.bookorbit.capabilities = caps + plugin.store.bookmark_sync_disabled = true + check(not marks:enabled(), "the bookmarks switch in Settings turns it off") + plugin.store.bookmark_sync_disabled = nil + plugin.store.downloads["101"] = nil + + -- ratings: BookOrbit's 0-5 stars, through the usual rating sync + local Ratings = require("gzreader_ratings") + check(plugin.api:putRating(101, Ratings.toGrimmory(4)) == true and bctl("/_mock/state").ratings["101"] == 4 + and Ratings.fromGrimmory(plugin.api:getBook(101).personalRating) == 4, "a rating out as stars, and read back as the rating sync reads Grimmory's") + check(plugin.api:putRating(101, nil) == true and bctl("/_mock/state").ratings["101"] == 0 and plugin.api:getBook(101).personalRating == nil, "a rating taken off") + local r_ok, r_err, r_code = plugin.api:putRating(999, 6) + check(r_ok == false and r_code == 404, "a rating for a book that's gone: dropped by the queue, as with Grimmory", r_err) + local rate_ds = { data = { summary = { rating = 5 } }, readSetting = function(self, k) return self.data[k] end, saveSetting = function(self, k, v) self.data[k] = v end, flush = function() end } + plugin.store.downloads["101"] = entry101 + entry101.rating_synced = nil + plugin.store.pending.ratings = {} + check(Ratings.check(plugin, "101", entry101, rate_ds) == true and plugin.store.pending.ratings["101"] == 5, "a rating made on the Kindle is queued for BookOrbit") + plugin:flushPending() + runLoop(function() return not plugin.flushing and plugin.store.pending.ratings["101"] == nil end, 20) + check(bctl("/_mock/state").ratings["101"] == 5, "…and sent by the usual queue") + -- reading time: KOReader's own statistics, page by page + local Stats = require("gzreader_bo_stats") + local rows = { [hash101] = {} } + for i = 1, 620 do rows[hash101][i] = { page = i % 240, startTime = 1790000000 + i * 30, durationSeconds = 25, totalPages = 240 } end + rows[string.rep("ef", 16)] = { { page = 1, startTime = 1790000001, durationSeconds = 10, totalPages = 10 } } + local real_read, asked = Stats.read, {} + Stats.read = function(_db, hash, since, limit) + asked[#asked + 1] = { hash = hash, since = since } + local out = {} + for _i, r in ipairs(rows[hash] or {}) do + if r.startTime > (since or 0) and #out < limit then out[#out + 1] = r end + end + return out + end + plugin.store.downloads["902"] = { path = "/nowhere/y.epub", hash = string.rep("ef", 16) } + plugin.store.bookorbit_stats = nil + Stats.last, Stats.busy = nil, nil + check(Stats.enabled(plugin), "reading time is sent to BookOrbit") + local s_done + Stats.send(plugin, true, function(ok) s_done = ok end) + runLoop(function() return s_done ~= nil end, 30) + local got_rows = bctl("/_mock/state").page_stats[hash101] + check(s_done == true and #got_rows == 500 and got_rows[1][2] == 1790000030 and got_rows[1][3] == 25 and got_rows[1][4] == 240 + and plugin.store.bookorbit_stats[hash101] == 1790000000 + 500 * 30, "the pages read are sent (500 rows at a time), and how far is remembered") + check(plugin.store.bookorbit_stats[string.rep("ef", 16)] == nil, "a book BookOrbit doesn't have: nothing remembered as sent") + s_done = nil + Stats.send(plugin, false, function(ok) s_done = ok end) + check(s_done == false and #bctl("/_mock/state").page_stats[hash101] == 500, "not again within ten minutes unless asked (a book just closed)") + s_done = nil + Stats.send(plugin, true, function(ok) s_done = ok end) + runLoop(function() return s_done ~= nil end, 30) + check(s_done == true and #bctl("/_mock/state").page_stats[hash101] == 620 and plugin.store.bookorbit_stats[hash101] == 1790000000 + 620 * 30, + "the next send carries on from there: no row twice, none missed") + local since_ok = false + for _i, a in ipairs(asked) do if a.hash == hash101 and a.since == 1790000000 + 500 * 30 then since_ok = true end end + check(since_ok, "…asking the database only for rows after the last one sent") + plugin.store.sync_disabled = true + check(not Stats.enabled(plugin), "with sync switched off, no reading time is sent") + plugin.store.sync_disabled = nil + Stats.read = real_read + plugin.store.downloads["902"], plugin.store.downloads["101"] = nil, nil + + -- audiobooks: BookOrbit's main API, with an API key + local KEY = "bok_" .. string.rep("a1B2c3D4e5", 4) .. "f6G7h8I9j" + local k_ok, k_err = plugin:setBookOrbitApiKey("bok_" .. string.rep("x", 49)) + check(k_ok == false and k_err:find("didn't accept the API key", 1, true) and not plugin.api:hasApiKey(), "a wrong API key: said so, not kept") + k_ok, k_err = plugin:setBookOrbitApiKey(" " .. KEY .. "\n") + check(k_ok == true and plugin.api:hasApiKey() and plugin.store.bookorbit.api_key == KEY, "the API key is checked against the server and kept (spaces around it dropped)", k_err) + local key_secret = false + for _i, sp in ipairs(require("gzreader_secrets").PATHS) do if sp[1] == "bookorbit" and sp[2] == "api_key" then key_secret = true end end + check(key_secret, "…with the other secrets, off the USB drive") + local abs = plugin.api:listBooks{ page = 0, size = 20, sort = "title", dir = "asc", fileType = { "AUDIOBOOK" } } + check(abs and #abs.content == 2 and abs.totalElements == 2 and abs.content[1].id == "a201" and abs.content[1].title == "The Long Way Round" + and abs.content[1].primaryFileType == "AUDIOBOOK" and abs.content[1].authors[1] == "Ada Marsh" and abs.content[2].id == "a102" + and abs.content[2].narrators[2] == "Sam Lee", "the audiobooks list: each under its own id (a…), so an ebook with the same BookOrbit id stays apart") + check(#plugin.api:listBooks{ page = 0, size = 20, fileType = { "AUDIOBOOK" }, search = "short" }.content == 1, "searching the audiobooks") + check(#plugin.api:listBooks{ page = 0, size = 50, fileType = plugin.api.READABLE_TYPES }.content == 5, "the books list is unchanged") + local AB = require("gzreader_audiobook") + local info = plugin.api:audiobookInfo("a201") + check(info and info.folderBased == true and #info.tracks == 2 and info.tracks[2].index == 1 and info.tracks[2].cumulativeStartMs == 60000 + and info.tracks[2].fileSizeBytes == 3003 and info.durationMs == 105000 and info.bookFileId == 6201 and info.title == "The Long Way Round" + and info.author == "Ada Marsh" and info.narrator == "June Park" and info.codec == "mp3" and info.tracks[1].title == "Part 1", + "an audiobook of several files: its tracks, as the player reads Grimmory's") + local described = AB.describe("a201", info) + check(described.id == "a201" and described.folder and #described.tracks == 2 and described.tracks[2].start == 60000 and described.file_id == 6201 + and described.files[1] == "track-001.mp3" and #described.chapters == 2, "…and the player's own record of it") + local info2 = plugin.api:audiobookInfo("a102") + local d2 = AB.describe("a102", info2) + check(info2.folderBased == false and info2.tracks == nil and #info2.chapters == 3 and info2.chapters[2].startTimeMs == 200000 and info2.chapters[2].durationMs == 200000 + and info2.codec == "aac" and d2.files[1] == "audiobook.m4b" and #d2.chapters == 3 and d2.tracks[1].size == 5012 and not d2.folder, + "an audiobook in one M4B file: its chapters from BookOrbit's manifest") + check(select(2, plugin.api:audiobookInfo("a999")) == "http_404", "an audiobook that isn't there: its error") + local apath = WORK .. "/bo-audio.part" + os.remove(apath) + local a_ok, a_err = plugin.api:downloadAudio("a201", 1, apath) + check(a_ok == true and lfs.attributes(apath, "size") == 3003, "a track downloaded (the second file)", a_err) + local cut = io.open(apath, "rb"); local whole = cut:read("*a"); cut:close() + cut = io.open(apath, "wb"); cut:write(whole:sub(1, 1000)); cut:close() + a_ok = plugin.api:downloadAudio("a201", 1, apath) + cut = io.open(apath, "rb"); local again2 = cut:read("*a"); cut:close() + check(a_ok == true and again2 == whole, "an interrupted download continues where it stopped (BookOrbit's audio takes a Range)") + check(plugin.api:downloadAudio("a201", 1, apath) == true and lfs.attributes(apath, "size") == 3003, "a finished one asked again: nothing more to fetch") + os.remove(apath) + check(plugin.api:downloadAudio("a102", nil, apath) == true and lfs.attributes(apath, "size") == 5012, "the single file of an M4B audiobook") + os.remove(apath) + local acover = WORK .. "/bo-acover.jpg" + check(plugin.api:downloadThumbnail("a201", acover, "audiobook") == true and lfs.attributes(acover, "size") > 50, "an audiobook's cover") + check(select(3, plugin.api:downloadThumbnail(101, acover .. "x", "audiobook")) == 404, "a book asked for as an audiobook: no cover (as before)") + -- where you stopped listening + local rec = plugin.api:getBook("a201") + check(rec and rec.audiobookProgress == nil, "no listening position yet") + local put_ok, put_err = plugin.api:putProgress("a201", { fileProgress = { bookFileId = 6201, positionData = "15000", positionHref = "1", progressPercent = 71.4 } }) + local pstate = bctl("/_mock/state").playback["201"] + check(put_ok == true and pstate and pstate.positionMs == 15000 and pstate.assetId:match("^aud_2222") and pstate.revision == 1 + and pstate.operationId:match("^%x+%-%x+%-4%x+%-[89ab]%x+%-%x+$") ~= nil, "the position saved: which file, where in it, with a fresh operation id", put_err) + rec = plugin.api:getBook("a201") + check(rec.audiobookProgress.positionMs == 15000 and rec.audiobookProgress.trackIndex == 1, "…and read back as the player reads Grimmory's (ms in the track, the track's index)") + put_ok = plugin.api:putProgress("a201", { fileProgress = { positionData = "30000", positionHref = "1" } }) + check(put_ok == true and bctl("/_mock/state").playback["201"].revision == 2 and bctl("/_mock/state").playback["201"].positionMs == 30000, + "the next save is based on the revision BookOrbit has now") + put_ok = plugin.api:putProgress("a201", { fileProgress = { positionData = "99999999", positionHref = "0" } }) + check(put_ok == true and bctl("/_mock/state").playback["201"].positionMs == 60000, "a position past the file's end is sent as its end") + check(plugin.api:putProgress("a102", { fileProgress = { positionData = "250000" } }) == true + and plugin.api:getBook("a102").audiobookProgress.positionMs == 250000 and plugin.api:getBook("a102").audiobookProgress.trackIndex == 0, + "an M4B audiobook: the place in its one file") + plugin:queue("progress", "a201", { fileProgress = { bookFileId = 6201, positionData = "20000", positionHref = "0" } }) + plugin:queue("progress", 101, { fileProgress = { progressPercent = 12 } }) + check(plugin.store.pending.progress["a201"] ~= nil and plugin.store.pending.progress["101"] ~= nil, "an audiobook's place and a book's place queue apart") + plugin.store.pending.progress["101"] = nil + plugin:flushPending() + runLoop(function() return not plugin.flushing and plugin.store.pending.progress["a201"] == nil end, 20) + check(bctl("/_mock/state").playback["201"].positionMs == 20000, "…and the audiobook's goes out by the usual queue") + bctl("/_mock/set", '{"api_key_write": false}') + local ro_ok, ro_err, ro_code = plugin.api:putProgress("a201", { fileProgress = { positionData = "1000", positionHref = "0" } }) + check(ro_ok == false and ro_err == "bookorbit_api_key_read_only" and ro_code == 404 and plugin:describeError(ro_err):find("read%-only") ~= nil + and #plugin.api:listBooks{ page = 0, size = 20, fileType = { "AUDIOBOOK" } }.content == 2, + "a read-only key: listing still works, the position isn't saved (and isn't retried forever)") + bctl("/_mock/set", '{"api_key_write": true, "api_keys_enabled": false}') + local off, off_err = plugin.api:listBooks{ page = 0, size = 20, fileType = { "AUDIOBOOK" } } + check(off == nil and off_err == "bookorbit_api_key_refused" and plugin:describeError(off_err):find("make a new one", 1, true) ~= nil, "a key that stopped working: said so") + bctl("/_mock/set", '{"api_keys_enabled": true}') + -- the setup page: the key's form, and the key never shown back + PS.new = function(self, o) screen = o; return o end + plugin:startQrPairing() + local kurl = screen.url:gsub("#.*$", "") + local kcode, kbody = phone("'" .. kurl .. "'") + check(kcode == 200 and kbody:find('name="api_key" type="password"', 1, true) and kbody:find("(one is saved)", 1, true) and not kbody:find(KEY, 1, true) + and not kbody:find("a1B2c3", 1, true), "the setup page: a form for the API key; it says one is saved, never which") + kcode, kbody = phone("-L --data-urlencode 'api_key=bok_wrongwrong' '" .. kurl .. "/grimmory/apikey'") + check(kbody:find("accept the API key. It may have expired", 1, true) and plugin.api:hasApiKey() and not kbody:find("bok_wrongwrong", 1, true), + "the setup page: a wrong key is refused, the saved one kept, the typed one not echoed") + kcode, kbody = phone("-L --data-urlencode 'api_key=' '" .. kurl .. "/grimmory/apikey'") + check(not plugin.api:hasApiKey() and not kbody:find("(one is saved)", 1, true), "the setup page: saving it empty removes the key") + phone("-L --data-urlencode 'api_key=" .. KEY .. "' '" .. kurl .. "/grimmory/apikey'") + check(plugin.api:hasApiKey(), "the setup page: a good key is kept") + screen.on_cancel() + -- collections (GZreader's shelves): changed with the API key, your own only + do + local Sh = require("gzreader_shelves") + local NM = require("ui/network/manager") + local was_conn = NM.isConnected + NM.isConnected = function() return true end + plugin.store.shelves_cache, plugin.store.pending.shelves, Sh.running = nil, nil, nil + check(plugin.api:canEditShelves() == true and Sh.editable(plugin.api) == true, "collections: with the API key they can be changed from here") + bctl("/_mock/set", '{"collection_owners": {"12": 2}}') + local mine = plugin.api:listMyShelves() + check(type(mine) == "table" and #mine == 1 and mine[1].id == 11 and mine[1].name == "Beach reads" and mine[1].own == true, + "collections: yours listed, someone else's shared one left out") + local set_ok = plugin.api:setBookShelves(102, { 11 }, {}) + check(type(set_ok) == "table" and #plugin.api:listBooks{ shelfId = 11, page = 0, size = 20 }.content == 3, "collections: a book added to one") + set_ok = plugin.api:setBookShelves(102, {}, { 11 }) + check(type(set_ok) == "table" and #plugin.api:listBooks{ shelfId = 11, page = 0, size = 20 }.content == 2, "…and taken off again") + local no, no_err, no_code = plugin.api:setBookShelves(102, { 12 }, {}) + check(no == nil and no_code == 403 and no_err ~= nil, "collections: someone else's can't be changed (said so, not retried)") + local done + Sh.sync(plugin, true, function(ok) done = ok end) + runLoop(function() return done ~= nil end, 20) + local kept = Sh.mine(plugin) + check(done == true and kept and #kept == 1 and kept[1].name == "Beach reads" and Sh.isOn(plugin, 101, 11) and not Sh.isOn(plugin, 102, 11), + "collections: kept on the Kindle with their books") + Sh.set(plugin, { 102 }, 11, true) + check(Sh.isOn(plugin, 102, 11), "collections: a change shows at once") + runLoop(function() return not Sh.running and not Sh.hasPending(plugin) end, 20) + check(not Sh.hasPending(plugin) and #plugin.api:listBooks{ shelfId = 11, page = 0, size = 20 }.content == 3, "…and reaches BookOrbit") + Sh.set(plugin, { 102 }, 11, false) + runLoop(function() return not Sh.running and not Sh.hasPending(plugin) end, 20) + check(#plugin.api:listBooks{ shelfId = 11, page = 0, size = 20 }.content == 2, "collections: taken off again through the queue") + local IM_was = package.loaded["ui/widget/infomessage"] + package.loaded["ui/widget/infomessage"] = { new = function(_, o) captured.info = o.text; return o end } + captured.info = nil + check(Sh.ready(plugin) == true and captured.info == nil, "collections: the menus open with the key") + -- without the key: said so, nothing sent + local key_was = plugin.store.bookorbit.api_key + plugin.store.bookorbit.api_key = nil + check(plugin.api:canEditShelves() == false and Sh.editable(plugin.api) == false, "collections: without the API key they can't be changed") + captured.info = nil + check(Sh.ready(plugin) == false and captured.info and captured.info:find("BookOrbit's collections from here needs its API key", 1, true) ~= nil, + "…and adding to one says where to put the key") + done = nil + Sh.sync(plugin, true, function(ok) done = ok end) + check(done == false, "…and nothing is asked of BookOrbit") + package.loaded["ui/widget/infomessage"] = IM_was + plugin.store.bookorbit.api_key = key_was + bctl("/_mock/set", '{"collection_owners": {}}') + plugin.store.shelves_cache, plugin.store.pending.shelves = nil, nil + NM.isConnected = was_conn + end + -- book requests: asked for from the Catalog's BookOrbit card, with the API key + do + local Rq = require("gzreader_bo_requests") + local Browser = require("gzreader_browser") + local NetQ = require("gzreader_net") + local was_run, was_usb = NetQ.run, NetQ.usb + NetQ.run = function(fn) fn() end + NetQ.usb = false + local IM_was, CB_was = package.loaded["ui/widget/infomessage"], package.loaded["ui/widget/confirmbox"] + local box + package.loaded["ui/widget/infomessage"] = { new = function(_, o) captured.info = o.text; return o end } + package.loaded["ui/widget/confirmbox"] = { new = function(_, o) box = o; return o end } + local pushed, replaced + local fake = { plugin = plugin, api = plugin.api, push = function(_s, t, items) pushed = { t, items } end, + replace = function(_s, t, items) replaced = { t, items } end } + local function texts(items) + local t = {} + for _i, it in ipairs(items) do t[#t + 1] = it.text .. (it.mandatory and (" = " .. it.mandatory) or "") end + return table.concat(t, "|") + end + local card = texts(Browser.grimmoryItems(fake)) + check(card:find("|Request a book|My book requests|About BookOrbit", 1, true) ~= nil, "requests: the BookOrbit card has Request a book and My book requests " .. card) + check(Rq.can(plugin) == true and plugin.api:canRequestBooks() == true, "requests: possible with the API key") + captured.info = nil + local sent + Rq.send(plugin, " The Salt Road ", " Ines Ward ", "ebook", function(ok) sent = ok end) + local st = bctl("/_mock/state").requests + check(sent == true and #st == 1 and st[1].title == "The Salt Road" and st[1].authors[1] == "Ines Ward" and st[1].mediaKind == "ebook" + and captured.info == "Asked BookOrbit for “The Salt Road” (book). Status: Waiting for approval.", + "requests: a book asked for, by title and author (" .. tostring(captured.info) .. ")") + sent = nil + Rq.send(plugin, " ", "", "ebook", function(ok) sent = ok end) + check(sent == false and captured.info == "Enter the book's title." and #bctl("/_mock/state").requests == 1, "requests: no title, nothing sent") + bctl("/_mock/set", '{"add_request": {"title": "Low Tide", "mediaKind": "audiobook", "userId": 2, "status": "searching"}}') + Rq.send(plugin, "Low Tide", "", "audiobook") + check(captured.info == "Someone already asked for “Low Tide” (audiobook): you'll be counted in. Status: Searching.", + "requests: one someone else made is joined, and said so (" .. tostring(captured.info) .. ")") + local list = plugin.api:listRequests() + check(type(list) == "table" and #list == 2 and list[1].title == "Low Tide" and list[1].kind == "audiobook" and list[1].status == "searching" + and list[2].title == "The Salt Road" and list[2].authors[1] == "Ines Ward", "requests: yours listed, newest first") + Rq.open(fake) + check(pushed and pushed[1] == "Book requests" + and texts(pushed[2]) == "Request a book…|Low Tide = Searching|The Salt Road = Waiting for approval", "requests: the list, each with its status " .. texts(pushed and pushed[2] or {})) + -- a tap: what it is; one still open can be cancelled + box = nil + pushed[2][3].callback() + check(box and box.text == "The Salt Road\nInes Ward · book\n\nStatus: Waiting for approval" and box.ok_text == "Cancel this request", + "requests: a tap shows it, with a way to cancel " .. tostring(box and box.text)) + box.ok_callback() + check(bctl("/_mock/state").requests[1].status == "cancelled" and captured.info == "The request for “The Salt Road” was cancelled." + and replaced and texts(replaced[2]):find("The Salt Road = Cancelled", 1, true) ~= nil, "requests: cancelled, and the list shows it") + box, captured.info = nil, nil + replaced[2][3].callback() + check(box == nil and captured.info == "The Salt Road\nInes Ward · book\n\nStatus: Cancelled", "requests: one that's over is only shown") + local low = bctl("/_mock/state").requests[2].id + bctl("/_mock/set", '{"request_update": {"id": ' .. low .. ', "status": "available", "matchedBookId": 102}}') + check(Rq.detail(plugin.api:listRequests()[1]) == "Low Tide\naudiobook\n\nStatus: In the library\n\nIt's in the Catalog's Audiobooks page now.", + "requests: one that arrived says where it is") + bctl("/_mock/set", '{"request_update": {"id": ' .. low .. ', "status": "rejected", "decisionNote": "Not this month"}}') + check(Rq.detail(plugin.api:listRequests()[1]):find("Status: Declined\nNote from BookOrbit: Not this month", 1, true) ~= nil, "requests: a no shows its note") + check(Rq.statusText("importing") == "Being added to the library" and Rq.statusText("someday") == "someday" and Rq.statusText(nil) == "Unknown", + "requests: every state has words; a new one is shown as it is") + -- refused: the permission, a read-only key, no key + bctl("/_mock/set", '{"request_permission": false}') + local no, no_err, no_code = plugin.api:requestBook("X", nil, "ebook") + check(no == nil and no_err == "bookorbit_requests_refused" and no_code == 403 and plugin:describeError(no_err):find("“Request books” ticked", 1, true) ~= nil, + "requests: a key without the permission: said so") + pushed, captured.info = nil, nil + Rq.open(fake) + check(pushed == nil and captured.info and captured.info:find("Request books", 1, true) ~= nil, "…and the list says so too") + bctl("/_mock/set", '{"request_permission": true, "api_key_write": false}') + no, no_err = plugin.api:requestBook("X", nil, "ebook") + check(no == nil and no_err == "bookorbit_api_key_read_only" and plugin:describeError(no_err):find("book requests", 1, true) ~= nil + and #plugin.api:listRequests() == 2, "requests: a read-only key lists them but can't ask") + bctl("/_mock/set", '{"api_key_write": true}') + local key_was = plugin.store.bookorbit.api_key + plugin.store.bookorbit.api_key = nil + captured.info, pushed = nil, nil + Rq.ask(plugin) + Rq.open(fake) + check(Rq.can(plugin) == false and pushed == nil and captured.info and captured.info:find("needs BookOrbit's API key", 1, true) ~= nil, + "requests: without the API key, where to enter it") + plugin.store.bookorbit.api_key = key_was + NetQ.usb = true + check(not texts(Browser.grimmoryItems(fake)):find("Request a book", 1, true), "requests: not offered on a Kindle without Wi-Fi") + NetQ.run, NetQ.usb = was_run, was_usb + package.loaded["ui/widget/infomessage"], package.loaded["ui/widget/confirmbox"] = IM_was, CB_was + end + -- signing in with only the API key: the key gets (or makes) the e-reader sign-in + do + local md5 = require("ffi/sha2").md5 + local Zip = require("gzreader_zipread") + check(Zip.read("not a zip at all, just some text", "x.lua") == nil and Zip.read("", "x.lua") == nil and Zip.read(nil, "x.lua") == nil, + "zip reader: junk is refused") + local function seen(method, path) + for _i, r in ipairs(bctl("/_mock/state").seen) do if r[1] == method and r[2] == path then return true end end + return false + end + plugin.api:clearTokens() + plugin.store.bookorbit, plugin.store.username = nil, nil + bctl("/_mock/reset") + local ok, err = plugin:connectWithApiKey(BO, " " .. KEY .. " ") + check(ok == true and plugin.store.username == "will-kindle" and plugin.store.bookorbit.key == md5("hunter22") and plugin.api:hasApiKey() + and plugin.store.bookorbit.api_key == KEY and seen("GET", "koreader/credentials") and seen("GET", "koreader/plugin-package") + and #plugin.api:listBooks{ page = 0, size = 20 }.content > 0, + "API-key sign-in: the sync name and key fetched with the key, signed in, the key kept (" .. tostring(err) .. ")") + check(not seen("POST", "koreader/credentials"), "…and no sign-in made when there is one") + -- none yet: one is made, named after the account, with a password only this Kindle had + plugin.api:clearTokens() + plugin.store.bookorbit, plugin.store.username = nil, nil + bctl("/_mock/reset") + bctl("/_mock/set", '{"ko_credentials": false}') + ok, err = plugin:connectWithApiKey(BO, KEY) + local made = bctl("/_mock/state").ko_made + check(ok == true and type(made) == "table" and made.username == "will" and plugin.store.username == "will" and made.md5 == plugin.store.bookorbit.key + and #made.md5 == 32 and made.md5 ~= md5("hunter22") and plugin.api:hasApiKey() and #plugin.api:listBooks{ page = 0, size = 20 }.content > 0, + "API-key sign-in: no sync sign-in yet, so one is made under the account's name and used (" .. tostring(err) .. ")") + plugin.api:clearTokens() + plugin.store.bookorbit, plugin.store.username = nil, nil + bctl("/_mock/reset") + bctl("/_mock/set", '{"ko_credentials": false, "ko_names_taken": ["will"]}') + ok = plugin:connectWithApiKey(BO, KEY) + made = bctl("/_mock/state").ko_made + check(ok == true and type(made) == "table" and made.username:match("^will%-%x%x%x%x$") and plugin.store.username == made.username, + "…a taken name gets four digits added (" .. tostring(made and made.username) .. ")") + -- what can go wrong, each said plainly; the Kindle stays signed in as it was + local was_user, was_key = plugin.store.username, plugin.store.bookorbit.key + bctl("/_mock/set", '{"ko_credentials": false, "ko_made": null, "api_key_write": false}') + ok, err = plugin:connectWithApiKey(BO, KEY) + check(ok == false and err:find("this API key is read-only, so one can't be made", 1, true) ~= nil and err:find("GZreader sync", 1, true) == nil, + "API-key sign-in: no sync sign-in and a read-only key: said so " .. tostring(err)) + bctl("/_mock/set", '{"ko_credentials": true, "api_key_write": true, "key_ko_permission": false}') + ok, err = plugin:connectWithApiKey(BO, KEY) + check(ok == false and err:find("sync” ticked", 1, true) ~= nil, "API-key sign-in: a key without the sync permission: said so " .. tostring(err)) + bctl("/_mock/set", '{"key_ko_permission": true, "ko_md5_known": false}') + ok, err = plugin:connectWithApiKey(BO, KEY) + check(ok == false and err:find("saved once more", 1, true) ~= nil, "API-key sign-in: an old sync sign-in BookOrbit can't hand over: said so " .. tostring(err)) + bctl("/_mock/set", '{"ko_md5_known": true, "sync_enabled": false}') + ok, err = plugin:connectWithApiKey(BO, KEY) + check(ok == false and err:find("sync switched off", 1, true) ~= nil, "API-key sign-in: sync switched off: said so " .. tostring(err)) + bctl("/_mock/set", '{"sync_enabled": true}') + ok, err = plugin:connectWithApiKey(BO, "bok_wrongwrongwrong") + check(ok == false and err:find("didn't accept the API key", 1, true) ~= nil, "API-key sign-in: a wrong key: said so") + ok, err = plugin:connectWithApiKey(BO, " ") + check(ok == false and err == "Enter the API key.", "API-key sign-in: no key, nothing asked") + check(plugin.store.username == was_user and plugin.store.bookorbit.key == was_key and plugin.api:isPaired(), "…and after each the Kindle is signed in as before") + -- the setup page: the key alone, never shown back + bctl("/_mock/reset") + plugin.api:clearTokens() + plugin.store.bookorbit, plugin.store.username = nil, nil + PS.new = function(self, o) screen = o; return o end + plugin:startQrPairing() + local purl = screen.url:gsub("#.*$", "") + local pcode, pbody = phone("'" .. purl .. "'") + check(pcode == 200 and pbody:find('name="api_key" type="password"', 1, true) and pbody:find("Connect with the API key", 1, true), + "the setup page: BookOrbit can be signed in to with an API key") + pcode, pbody = phone("-L --data-urlencode 'server=" .. BO .. "' --data-urlencode 'backend=grimmory' --data-urlencode 'action=apikey' --data-urlencode 'api_key=bok_wrongwrongwrong' '" .. purl .. "/grimmory'") + check(pbody:find("accept the API key", 1, true) and not pbody:find("bok_wrongwrongwrong", 1, true) and not plugin.api:isPaired(), + "the setup page: a wrong key is refused and not echoed") + pcode, pbody = phone("-L --data-urlencode 'server=" .. BO .. "' --data-urlencode 'backend=bookorbit' --data-urlencode 'action=apikey' --data-urlencode 'api_key=" .. KEY .. "' '" .. purl .. "/grimmory'") + check(plugin.api:isPaired() and plugin:backend() == "bookorbit" and plugin.store.username == "will-kindle" and plugin.api:hasApiKey() + and pbody:find("Connected to BookOrbit as will-kindle", 1, true) and not pbody:find(KEY, 1, true) and not pbody:find(md5("hunter22"), 1, true), + "the setup page: the key alone signs the Kindle in; neither key is shown") + screen.on_cancel() + local lf = io.open(WORK .. "/gzreader.log", "rb") + local ltext = lf and lf:read("*a") or "" + if lf then lf:close() end + check(not ltext:find(KEY, 1, true) and not ltext:find(md5("hunter22"), 1, true), "the log has neither the API key nor the sync key") + end + -- reading stats from BookOrbit: Home's widget and the page a tap opens + do + local GS = require("gzreader_grimstats") + local Page = require("gzreader_statspage") + -- the dashboard turned into the widget's values (Sunday 22 November 2026 is "today") + local mins = {} + for i = 1, 371 do mins[i] = 0 end + mins[371], mins[370], mins[369], mins[365], mins[364] = 25, 0, 40, 70, 10 -- Sun 22, Sat 21, Fri 20, Mon 16, Sun 15 + mins[350] = 30 -- 1 November + mins[349] = 15 -- 31 October + mins[46] = 60 -- 1 January 2026 + mins[45] = 500 -- 31 December 2025 + local res = GS.fromDashboard{ + totalBooks = 240, browseCounts = { inProgress = 3 }, + readingGoal = { goalBooks = 30, completedBooks = 12, year = 2026 }, + readingStreak = { currentStreak = 4, longestStreak = 21, lastSevenDays = { true } }, + readingYear = { startDate = "2025-11-17", minutes = mins }, + achievements = { earned = 5, total = 40, next = { name = "Fifty hours", description = "Read for fifty hours.", threshold = 50, currentProgress = 41 }, + latest = { name = "Ten down" } }, + yearAgo = { book = { title = "Low Tide", authors = { "Mara Quill" } }, minutes = 312, days = 9 }, + finishedThisYear = { { title = "A", authors = { "X" } }, { title = "B", authors = {} } }, + highlightOfTheDay = { text = "The tide does not ask.", bookTitle = "Low Tide", chapterTitle = "Chapter 3" }, + } + local v, d = res.values, res.detail + check(v.streak == 4 and v.longest_streak == 21 and v.year_finished == 12 and v.goal == "12/30" and v.badges == "5/40" + and v.library_books == 240 and v.reading_now == 3, "BookOrbit stats: streak, goal, badges, library from the dashboard") + check(v.today_time == 25 * 60 and v.week_time == (25 + 40 + 70) * 60 and v.month_time == (25 + 40 + 70 + 10 + 30) * 60 + and v.year_time == (25 + 40 + 70 + 10 + 30 + 15 + 60) * 60 and v.year_days == 7, + "BookOrbit stats: today, this week (from Monday), this month and this year added up from the days " + .. tostring(v.week_time) .. " " .. tostring(v.month_time) .. " " .. tostring(v.year_time) .. " " .. tostring(v.year_days)) + check(d.goal.books == 30 and d.badges.next.threshold == 50 and d.year_ago.title == "Low Tide" and d.year_ago.author == "Mara Quill" + and #d.finished == 2 and d.finished[2].author == nil and d.highlight.chapter == "Chapter 3" and #d.days.minutes == 371, + "BookOrbit stats: what the page draws is kept") + local bare = GS.fromDashboard{ readingGoal = { goalBooks = nil, completedBooks = 2 }, readingStreak = { currentStreak = 0, longestStreak = 0 } } + check(bare.values.goal == nil and bare.values.badges == nil and bare.values.week_time == nil and bare.values.year_finished == 2 + and bare.detail.days == nil and GS.fromDashboard("x").error == "bad_reply", + "BookOrbit stats: no goal, badges off, an older server: those are left out, the rest shown") + -- the page's parts + local week = Page.lastWeek(d.days) + check(#week == 7 and week[1].label == "Mon" and week[1].minutes == 70 and week[7].label == "Sun" and week[7].minutes == 25 and week[7].today == true, + "the page: the last seven days, oldest first, today marked") + local grid = Page.yearGrid(d.days) + check(#grid.cols == 53 and grid.cols[53][7] == 2 and grid.cols[53][1] == 4 and grid.cols[53][5] == 3 and grid.cols[53][6] == 0 + and grid.cols[1][1] == 0 and grid.months[3] == "Dec", "the page: the year as weeks of days, darker for more reading " .. #grid.cols) + check(#Page.yearGrid(d.days, 20).cols == 20 and Page.yearGrid(d.days, 20).cols[20][7] == 2, "…a narrow screen gets the newest weeks") + check(Page.level(0) == 0 and Page.level(1) == 1 and Page.level(15) == 2 and Page.level(30) == 3 and Page.level(60) == 4, "the page: five shades of a day") + local kinds, titles = {}, {} + for _i, sec in ipairs(Page.sections{ server = "bookorbit", values = v, detail = d }) do + kinds[#kinds + 1] = sec.kind + titles[#titles + 1] = (sec.title or "") .. (sec.text and (" / " .. sec.text) or "") + end + local all_titles = table.concat(titles, " | ") + check(table.concat(kinds, " ") == "numbers bars year progress progress text text text text", "the BookOrbit page's parts in order: " .. table.concat(kinds, " ")) + check(all_titles:find("Reading goal for 2026 / 12 of 30 books", 1, true) and all_titles:find("Badges: 5 of 40. Next: Fifty hours / 41 of 50", 1, true) + and all_titles:find("A year ago you were reading / Low Tide, by Mara Quill (5 h 12 min over 9 days)", 1, true) + and all_titles:find("Finished this year / • A, by X\n• B", 1, true) and all_titles:find("“The tide does not ask.”\n— Low Tide, Chapter 3", 1, true) + and all_titles:find("Longest streak: 21 days · Books in the library: 240 · Reading now: 3", 1, true), + "the BookOrbit page: goal, badges, a year ago, finished, the highlight, the rest " .. all_titles) + -- from the server, into the widget + plugin.store.grimmory_stats = nil + bctl("/_mock/reset") + local got = GS.values(plugin) + check(GS.server(plugin) == "bookorbit" and plugin.store.grimmory_stats and plugin.store.grimmory_stats.server == "bookorbit" + and got.today_time == 25 * 60 and got.streak == 1 and got.longest_streak == 21 and got.goal == "12/30" and got.badges == "5/40" + and got.year_finished == 12 and got.reading_now == 2 and got.week_time and got.week_time >= 25 * 60, + "BookOrbit stats: fetched with the e-reader sign-in for Home's widget") + local at = plugin.store.grimmory_stats.at + GS.values(plugin) + check(plugin.store.grimmory_stats.at == at, "…not asked again within 15 minutes") + GS.stale(plugin) + bctl("/_mock/set", '{"goal_books": null, "achievements": false, "reading_year": false}') + got = GS.values(plugin) + check(got.goal == nil and got.badges == nil and got.today_time == nil and got.streak == 1 and GS.all(plugin).detail.days == nil, + "BookOrbit stats: asked again after reading time was sent; what the server lacks is left out") + bctl("/_mock/set", '{"goal_books": 30, "achievements": true, "reading_year": true, "offline": true}') + GS.refresh(plugin, true) + check(plugin.store.grimmory_stats.error ~= nil and plugin.store.grimmory_stats.values.streak == 1, "BookOrbit stats: the server away: the last numbers stay") + bctl("/_mock/set", '{"offline": false}') + GS.refresh(plugin, true) + -- the widget offers each server's own numbers + local saved_triplet = package.loaded["modules/filebrowser/patches/home/widgets/stats_triplet"] + package.loaded["modules/filebrowser/patches/home/widgets/stats_triplet"] = { + make = function(spec) return { id = spec.id, label = spec.label, spec = spec, build = function() return { "body" } end } end, + fmt_time = function(sec) return math.floor(sec / 60) .. "m" end, + } + local Wg = dofile(PLUGIN .. "/../zenos.koplugin/modules/filebrowser/patches/home/widgets/grimmory_stats.lua") + package.loaded["modules/filebrowser/patches/home/widgets/stats_triplet"] = saved_triplet + local was_server, was_stats, was_page = rawget(_G, "__GZ_BOOK_SERVER"), rawget(_G, "__GZ_GRIMMORY_STATS"), rawget(_G, "__GZ_SERVER_STATS_PAGE") + rawset(_G, "__GZ_BOOK_SERVER", function() return plugin:backend() end) + check(table.concat(Wg.OPTIONS, ",") == table.concat(GS.FIELDS.bookorbit, ",") and Wg.FIELDS.goal and Wg.FIELDS.today_time and Wg.FIELDS.reading_days == nil + and Wg.FIELDS.month_sessions == nil and Wg.FIELDS.week_time.get{ week_time = 600 } == "10m" and Wg.FIELDS.goal.get{} == "—" + and Wg.FIELDS.goal.get{ goal = "12/30" } == "12/30" and Wg.label == "Reading stats (every device)", + "the widget with BookOrbit: its numbers offered, Grimmory-only ones not") + rawset(_G, "__GZ_BOOK_SERVER", function() return "grimmory" end) + check(table.concat(Wg.OPTIONS, ",") == table.concat(GS.FIELDS.grimmory, ",") and Wg.FIELDS.reading_days and Wg.FIELDS.goal == nil and Wg.FIELDS.badges == nil, + "the widget with Grimmory: its numbers offered, BookOrbit-only ones not") + for _i, id in ipairs(GS.FIELDS.bookorbit) do if not Wg.ALL[id] then check(false, "the widget has no field for " .. id) end end + for _i, id in ipairs(Wg.spec.defaults) do + check(Wg.BY_SERVER.grimmory[_i] == id and Wg.BY_SERVER.bookorbit[_i] == id, "the widget's default " .. id .. " is one both servers have") + end + rawset(_G, "__GZ_BOOK_SERVER", was_server); rawset(_G, "__GZ_GRIMMORY_STATS", was_stats); rawset(_G, "__GZ_SERVER_STATS_PAGE", was_page) + -- the Catalog's card has the page too + local Browser = require("gzreader_browser") + local rows = {} + for _i, it in ipairs(Browser.grimmoryItems({ plugin = plugin, api = plugin.api, push = function() end })) do rows[#rows + 1] = it.text end + check(table.concat(rows, "|"):find("|Reading stats|Request a book|", 1, true) ~= nil, "the BookOrbit card has Reading stats " .. table.concat(rows, "|")) + plugin.store.grimmory_stats = nil + end + -- with BookOrbit, nothing of Grimmory's runs or is loaded + do + local Async = require("gzreader_async") + local run, ran, answered = Async.run, 0, nil + Async.run = function() ran = ran + 1 end + Async.ensureToken(plugin.api, function(ok) answered = ok end) + check(answered == true and ran == 0, "BookOrbit: no background process to refresh a login it doesn't have") + answered = nil + Async.ensureToken({ store = { access_token = "t", access_expires_at = os.time() - 5 } }, function(ok) answered = ok end) + check(ran == 1, "…Grimmory's login is still refreshed when it's old") + Async.run = run + local mf = io.open(PLUGIN .. "/main.lua", "rb") + local msrc = mf:read("*a"); mf:close() + local top = true + for line in msrc:gmatch("[^\n]+") do + if line:match('^local [%w_]+ = require%("gzreader_bookmarks"%)') or line:match('^local [%w_]+ = require%("gzreader_annotations"%)') + or line:match('^local [%w_]+ = require%("gzreader_cfi"%)') then top = false end + end + check(top and msrc:find('require(self.api.koreader_positions and "gzreader_bo_bookmarks" or "gzreader_bookmarks")', 1, true) ~= nil, + "Grimmory's bookmark, highlight and position modules are loaded only when Grimmory is the server") + end + -- what the API key needs, and BookOrbit's settings for the sync sign-in + do + local BookOrbit = require("gzreader_bookorbit") + check(BookOrbit.KEY_NEEDS:find("Access: Read and write", 1, true) and BookOrbit.KEY_NEEDS:find("“KOReader sync” to sign in with the key", 1, true) + and BookOrbit.KEY_NEEDS:find("“Request books” to request books", 1, true) and BookOrbit.KEY_NEEDS:find("not Administrator access", 1, true), + "the key's needs are named as BookOrbit's page names them") + check(plugin:describeError("bookorbit_sync_off"):find("Switch “Progress sync” on in BookOrbit: Settings → Devices → KOReader", 1, true) ~= nil + and plugin:describeError("bookorbit_no_api_key"):find("Settings → You → API keys, with Read and write access", 1, true) ~= nil + and plugin:describeError("bookorbit_key_no_kosync"):find("ticked under Extra permissions (BookOrbit: Settings → You → API keys)", 1, true) ~= nil, + "messages point at BookOrbit's settings where they are " .. plugin:describeError("bookorbit_sync_off")) + -- a sign-in the Kindle makes is left on BookOrbit's defaults (Automatic delivery) + plugin.api:clearTokens() + plugin.store.bookorbit, plugin.store.username = nil, nil + bctl("/_mock/reset") + bctl("/_mock/set", '{"ko_credentials": false, "ko_delivery": "original"}') + check(plugin:connectWithApiKey(BO, KEY) == true and bctl("/_mock/state").ko_delivery == nil and plugin.store.bookorbit.delivery == "automatic" + and plugin.api:settingsAdvice() == nil, "a sign-in made by the Kindle: only a name and password sent, so delivery is BookOrbit's default, Automatic") + -- an existing one set to send narration: said so, not changed + plugin.api:clearTokens() + plugin.store.bookorbit, plugin.store.username = nil, nil + bctl("/_mock/reset") + bctl("/_mock/set", '{"ko_delivery": "original"}') + check(plugin:connectWithApiKey(BO, KEY) == true and plugin.store.bookorbit.delivery == "original" and plugin.api:settingsAdvice() == "delivery_original" + and bctl("/_mock/state").ko_delivery == "original", "an existing sign-in set to send narration: noticed, and left as it is") + PS.new = function(self, o) screen = o; return o end + plugin:startQrPairing() + local purl = screen.url:gsub("#.*$", "") + local _c, pbody = phone("'" .. purl .. "'") + check(pbody:find("read-aloud EPUBs with their narration", 1, true) and pbody:find("Read-aloud EPUB delivery → Automatic", 1, true) + and pbody:find("Settings → You → API keys → Create API key. Access: Read and write.", 1, true), + "the setup page says what to change in BookOrbit, and what the key needs") + -- the same sign-in by name and password, the key saved after: read then too + bctl("/_mock/set", '{"ko_delivery": "audioless_epub"}') + check(plugin:setBookOrbitApiKey(KEY) == true and plugin.store.bookorbit.delivery == "audioless_epub" and plugin.api:settingsAdvice() == nil, + "saving the key reads the setting again: text-only is fine") + bctl("/_mock/set", '{"key_ko_permission": false}') + check(plugin:setBookOrbitApiKey(KEY) == true and plugin.store.bookorbit.delivery == false and plugin.api:settingsAdvice() == nil and plugin.api:hasApiKey(), + "a key that can't see the sync sign-in is still saved; nothing is claimed about the setting") + _c, pbody = phone("'" .. purl .. "'") + check(not pbody:find("with their narration", 1, true), "…and the setup page has no advice then") + screen.on_cancel() + bctl("/_mock/set", '{"key_ko_permission": true, "ko_delivery": null}') + plugin:setBookOrbitApiKey(KEY) + check(plugin.store.bookorbit.delivery == "automatic" and plugin.store.username == "will-kindle", "Automatic: nothing to say") + end + -- the setup page's Books tab: named for the server, each server's own way in, and what happened said + do + plugin.api:clearTokens() + plugin.store.bookorbit, plugin.store.username = nil, nil + bctl("/_mock/reset") + PS.new = function(self, o) screen = o; return o end + plugin:startQrPairing() + local purl = screen.url:gsub("#.*$", "") + local _c, page = phone("'" .. purl .. "'") + if os.getenv("GZ_KEEP_PAGE") then local keep = io.open(os.getenv("GZ_KEEP_PAGE"), "wb"); keep:write(page); keep:close() end + check(page:find(">Books<", 1, true) ~= nil or page:find(">Books ", 1, true) ~= nil, "the setup page: the tab is called Books") + check(page:find('

BookOrbit

', 1, true) ~= nil and page:find('t.textContent=v=="bookorbit"?"BookOrbit":"Grimmory"', 1, true) ~= nil, + "the setup page: the heading names the server chosen (BookOrbit was the last one) and follows the choice") + local grim = page:match('
(.-)
') + local bo = page:match('
(.-)') + check(grim and grim:find('name="username"', 1, true) and not grim:find("API key", 1, true) + and grim:find('autocomplete="current-password" disabled>', 1, true) and grim:find('name="action" value="password" disabled>', 1, true) + and grim:find('id="g_username"[^>]- disabled') and (not grim:find('value="sso"', 1, true) or grim:find('value="sso" formnovalidate disabled>', 1, true)), + "the setup page: Grimmory's user name, password and single sign-on are hidden and switched off while BookOrbit is chosen") + check(bo and not bo:find("SSO", 1, true) and not bo:find("single sign", 1, true) and not bo:find("disabled", 1, true) + and bo:find("Use the KOReader sync user name and password instead", 1, true) + and bo:find("The easy way: with the key alone", 1, true) and bo:find("Access: Read and write.", 1, true) + and bo:find("Connect with the API key", 1, true) < bo:find("KOReader sync user name", 1, true), + "the setup page, BookOrbit's block: the API key first, the sync name and password as the other way, no single sign-on") + -- a wrong try at BookOrbit comes back with BookOrbit chosen and named + _c, page = phone("-L --data-urlencode 'server=" .. BO .. "' --data-urlencode 'backend=bookorbit' --data-urlencode 'action=password' --data-urlencode 'username=will-kindle' --data-urlencode 'password=wrong' '" .. purl .. "/grimmory'") + check(page:find('

BookOrbit

', 1, true) and page:find('
', 1, true) + and page:find('
', 1, true) and page:find('
Use the KOReader sync user name', 1, true) + and page:find('value="sso" formnovalidate disabled', 1, true), + "the setup page: after a wrong BookOrbit password it's still BookOrbit's form, with Grimmory's parts off") + -- connecting says which server, on the page and on the Kindle + captured.notify = nil + _c, page = phone("-L --data-urlencode 'server=" .. BO .. "' --data-urlencode 'backend=bookorbit' --data-urlencode 'action=password' --data-urlencode 'username=will-kindle' --data-urlencode 'password=hunter22' '" .. purl .. "/grimmory'") + check(page:find("Connected to BookOrbit as will%-kindle%.") and not page:find("Connected to Grimmory", 1, true) and page:find('

BookOrbit

', 1, true), + "the setup page: connected to BookOrbit is said as BookOrbit, and the heading is BookOrbit") + -- saving the key says it worked and what the key can do + _c, page = phone("-L --data-urlencode 'api_key=" .. KEY .. "' '" .. purl .. "/grimmory/apikey'") + check(page:find("BookOrbit accepted the API key. Audiobooks and collections can use it. Requesting books: yes. Signing in with just the key: yes.", 1, true) + and page:find("(one is saved)", 1, true) and not page:find(KEY, 1, true), "the setup page: a saved key is confirmed, with what it can do") + bctl("/_mock/set", '{"request_permission": false, "key_ko_permission": false}') + _c, page = phone("-L --data-urlencode 'api_key=" .. KEY .. "' '" .. purl .. "/grimmory/apikey'") + check(page:find("Requesting books: no (the key was made without “Request books”", 1, true) and page:find("Signing in with just the key: no (the key was made without “KOReader sync”)", 1, true), + "the setup page: a key without the two permissions: said which") + bctl("/_mock/set", '{"request_permission": true, "key_ko_permission": true}') + _c, page = phone("-L --data-urlencode 'api_key=bok_wrongwrongwrong' '" .. purl .. "/grimmory/apikey'") + check(page:find("accept the API key. It may have expired", 1, true) and plugin.api:hasApiKey(), "the setup page: a wrong key is refused in words; the saved one stays") + _c, page = phone("-L --data-urlencode 'api_key=' '" .. purl .. "/grimmory/apikey'") + check(page:find("The BookOrbit API key was removed.", 1, true) and not plugin.api:hasApiKey(), "the setup page: removing the key is confirmed") + _c, page = phone("-L --data-urlencode 'api_key=" .. KEY .. "' '" .. purl .. "/grimmory/apikey'") + local UIM = require("ui/uimanager") + local show_was, summary = UIM.show, nil + UIM.show = function(_s, w) if type(w) == "table" and type(w.text) == "string" then summary = w.text end end + require("gzreader_phone").afterClose({ plugin = plugin, changes = { grimmory = true }, opts = {} }) + UIM.show = show_was + screen.on_cancel() + check(type(summary) == "string" and summary:find("BookOrbit: connected as will-kindle.", 1, true) ~= nil and not summary:find("Grimmory", 1, true), + "the Kindle's summary after setup names BookOrbit " .. tostring(summary)) + check(plugin.api:hasApiKey() and plugin.store.username == "will-kindle", "(signed in with the key saved for what follows)") + end + -- the Catalog speaks the server's words: BookOrbit, Collections, SmartScope + do + local Name = require("gzreader_servername") + local was = rawget(_G, "__GZ_BOOK_SERVER") + rawset(_G, "__GZ_BOOK_SERVER", function() return plugin:backend() end) + check(Name.get() == "BookOrbit" and Name.shelves() == "Collections" and Name.smart() == "SmartScope" + and Name.fix("Fetching from Grimmory…") == "Fetching from BookOrbit…" and Name.fix(nil) == nil, + "with BookOrbit: its name, Collections and SmartScope") + local Browser = require("gzreader_browser") + local opened + local fake = setmetatable({ plugin = plugin, api = plugin.api, openCached = function(_s, spec) opened = spec end, openPaged = function() end }, { __index = Browser }) + fake:openShelves() + local listed = plugin.api:listShelves() + listed[#listed + 1] = { id = 9, name = "Unread this year", magic = true } -- (a SmartScope, as listShelves marks them) + local items = opened.build(listed) + local names = {} + for _i, it in ipairs(items) do names[#names + 1] = it.text .. "=" .. tostring(it.mandatory) end + check(opened.title == "Collections" and table.concat(names, "|"):find("=SmartScope", 1, true) ~= nil and #items >= 3, + "the Catalog's shelves list with BookOrbit: called Collections, with its collections and its SmartScopes " .. table.concat(names, "|")) + rawset(_G, "__GZ_BOOK_SERVER", function() return "grimmory" end) + fake:openShelves() + check(Name.get() == "Grimmory" and Name.shelves() == "Shelves" and Name.smart() == "smart shelf" and Name.fix("Fetching from Grimmory…") == "Fetching from Grimmory…" + and opened.title == "Shelves", "with Grimmory everything reads as before") + rawset(_G, "__GZ_BOOK_SERVER", was) + local left = {} + for _i, f in ipairs{ "gzreader_bookshop.lua", "gzreader_bookpage.lua" } do + local fh = io.open(PLUGIN .. "/" .. f, "rb"); local src = fh:read("*a"); fh:close() + for line in src:gmatch("[^\n]+") do + if line:find('_%("[^"]*Grimmory') and not line:find("gzreader_servername", 1, true) and not line:match("^%s*%-%-") then left[#left + 1] = f end + end + end + check(#left == 0, "the Catalog's screens have no text naming Grimmory that doesn't follow the server " .. table.concat(left, " ")) + end + -- signing in again as the same user keeps the key; another user doesn't get it + plugin:connect(BO, "will-kindle", "hunter22", "bookorbit") + check(plugin.api:hasApiKey(), "signing in again to the same server and user keeps the API key") + local dumped = require("dump")(plugin.store) + check(not dumped:find("hunter22", 1, true), "(still no password in the settings)") + plugin.api:setApiKey("") + check(not plugin.api:hasApiKey(), "the key removed") + + -- a refused sign-in later, and the server away + bctl("/_mock/set", '{"ko_permission": false}') + local r, rerr = plugin.api:listLibraries() + check(r == nil and rerr == "bookorbit_refused" and plugin.api:isPaired(), "refused later: an error to show, the sign-in kept") + bctl("/_mock/set", '{"ko_permission": true, "offline": true}') + r, rerr = plugin.api:listBooks{ page = 0, size = 5 } + check(r == nil and rerr == "http_503", "the server down: its error") + bctl("/_mock/set", '{"offline": false}') + check(select(2, plugin.api:postSession({})) == "unsupported" and select(2, plugin.api:listBookmarks(101)) == "unsupported", + "what isn't sent to BookOrbit yet answers \"unsupported\"") + + -- the setup page + PS.new = function(self, o) screen = o; return o end + plugin:startQrPairing() + local url = screen.url:gsub("#.*$", "") + local code, body = phone("'" .. url .. "'") + local sec = body and body:match('
') or "" + check(code == 200 and sec:find("Connected to BookOrbit as will%-kindle") and sec:find('