🚚 (split): 从月读拆出独立仓库,沿用原书源 id
Release / release (push) Successful in 10s

This commit is contained in:
Garfield committed 2026-11-27 08:08:02 +08:00
commit 3598b9f825
21 files changed
+2240

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
local _ = require("gettext")
return {
fullname = _("月读书源:BookOrbit"),
description = _("给月读增加「BookOrbit」书源。需要同时安装月读,与平台官方无关。"),
}
+9
View File
@@ -0,0 +1,9 @@
--[[--
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
--]]
local WidgetContainer = require("ui/widget/container/widgetcontainer")
return WidgetContainer:extend{
name = "moonsource_bookorbit",
is_doc_only = false,
}
@@ -0,0 +1,17 @@
--[[--
月读第三方书源描述:BookOrbit。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。
--]]
local function lazy(module)
return setmetatable({}, { __index = function(_, key) return require(module)[key] end })
end
return {
api = 1,
provides = {
source = true,
},
meta = function() return require("moonsource_bookorbit.source").meta() end,
new = function() return require("moonsource_bookorbit.source").new() end,
setting = lazy("moonsource_bookorbit.setting"),
}
@@ -0,0 +1,16 @@
# BookOrbit
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| 服务连接 | 支持 | 使用 BookOrbit 的 KOReader 同步账号;可导入官方插件配置 |
| 书库选择 | 支持 | 未选择时读取全部可访问书库 |
| 书架拉取 | 支持 | 分页读取 |
| 加入远端书架 | 不支持 | 本地新增书籍不上传 |
| 删除远端书籍 | 不支持 | 仅清本地缓存并留墓碑,不删除服务器藏书 |
| 详情与封面 | 支持 | 读取书籍元数据及可读文件 |
| 整本下载与阅读 | 支持 | EPUB、AZW3、AZW、MOBI、FB2、DOCX、PDF、DjVu、CBZ、TXT |
| 阅读进度同步 | 支持 | 仅已下载文件;按文件摘要匹配,使用 xpointer 或页码 |
| 划线同步 | 部分支持 | 仅上传已下载书籍的支持类型划线,不拉取远端笔记 |
| 阅读统计同步 | 不支持 | 本地记录保留 |
| 书评、章评、段评与回复 | 不支持 | 当前同步契约未接入;不代表所有服务端版本都没有评论 |
| 离线阅读 | 支持 | 已下载文件可用;连接、下载和同步需要服务器在线 |
@@ -0,0 +1,15 @@
--[[--
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
@module moonsource_bookorbit._meta
--]]
local _ = require("l10n").get("moonsource_bookorbit")
return {
id = "bookorbit",
name = _("BookOrbit"),
type = "book",
description = _("连接 BookOrbit KOReader 接口"),
abilities = { _("书架与整本下载"), _("已下载书籍进度同步"), _("已下载书籍划线上传") },
}
@@ -0,0 +1,125 @@
--[[--
BookOrbit HTTP 客户端:KOReader 同步账号认证(x-auth-user / x-auth-key),只回 wire,不做领域转换。
x-auth-key 是密码的 MD5(同 kosync,服务端也收明文)。接口都在 `<server_url>/api/v1/koreader/` 下。
调用方先看 configured(),这里不再判。
@module moonsource_bookorbit.client
--]]
local JSON = require("json")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_bookorbit")
local T = require("ffi/util").template
---@class BookOrbitClient
---@field server_url string 用户填的地址,不带 /api/v1
---@field username string
---@field userkey string 密码 MD5
local Client = {}
Client.__index = Client
--- 用户填的地址:去空白、尾斜杠,以及照抄来的 `/api/v1`、`/api/v1/koreader` 后缀。
---@param value string|nil
---@return string
function Client.normalizeUrl(value)
local url = Text.rtrimSlashes(Text.stripWhitespace(value))
return (url:gsub("/api/v1/koreader$", ""):gsub("/api/v1$", ""))
end
---@param cfg { server_url: string|nil, username: string|nil, userkey: string|nil }
---@return BookOrbitClient
function Client.new(cfg)
return setmetatable({
server_url = Client.normalizeUrl(cfg.server_url),
username = Text.trim(cfg.username),
userkey = Text.stripWhitespace(cfg.userkey),
}, Client)
end
---@return boolean
function Client:configured()
return self.server_url ~= "" and self.username ~= "" and self.userkey ~= ""
end
---@return table
function Client:headers()
return { ["x-auth-user"] = self.username, ["x-auth-key"] = self.userkey }
end
---@param path string `/koreader/...`
---@param query table|nil
---@return string
function Client:url(path, query)
local url = self.server_url .. "/api/v1" .. path
if query then return url .. "?" .. Text.formEncode(query) end
return url
end
--- JSON 请求:2xx 回 cb(data),否则 cb(nil, err, code)。空体按 {} 交回。
---@param method string
---@param path string
---@param query table|nil
---@param body table|nil JSON 请求体
---@param cb fun(data: table|nil, err: string|nil, code: integer|nil)
---@return HttpJob
function Client:json(method, path, query, body, cb)
local headers = self:headers()
headers["Accept"] = "application/json"
local payload
if body then
headers["Content-Type"] = "application/json"
payload = JSON.encode(body)
end
return Request.request({
url = self:url(path, query), method = method, headers = headers, body = payload, timeout = 30,
}, function(res, err)
if err or not res then
cb(nil, err and tostring(err) or _("网络请求失败"))
return
end
local code = tonumber(res.code)
if code == 401 or code == 403 then
cb(nil, _("BookOrbit 用户名或密码错误,或未开启 KOReader 同步"), code)
return
end
if not Request.ok(code) then
cb(nil, T(_("请求失败 (HTTP %1)"), tostring(code)), code)
return
end
local raw = Text.trim(Text.stripBom(res.body or ""))
if raw == "" then
cb({}, nil, code)
return
end
-- 反代可能回 HTML 错误页:解析失败按请求失败处理,不让异常冒到回调链外。
-- simple:null 解成 nil。默认模式解成 json.util.null 函数,写进书库会绑定失败、整行丢掉。
local ok, data = pcall(JSON.decode, raw, JSON.decode.simple)
if ok and type(data) == "table" then
cb(data, nil, code)
else
cb(nil, _("响应不是 JSON"), code)
end
end)
end
--- 下载书库文件原件。Request.download 遇到非 2xx 也会落盘,这里删掉并报错。
---@param file_id integer
---@param dest string
---@param on_progress fun(bytes: number, total: number|nil)
---@param cb fun(ok: boolean, err: string|nil)
---@return HttpJob
function Client:download(file_id, dest, on_progress, cb)
return Request.download({
url = self:url("/koreader/plugin/catalog/files/" .. file_id .. "/download"),
headers = self:headers(), timeout = 60, on_progress = on_progress,
}, dest, function(ok, err, res)
if ok and not Request.ok(res and res.code) then
os.remove(dest)
ok, err = false, T(_("请求失败 (HTTP %1)"), tostring(res and res.code))
end
cb(ok, err and tostring(err))
end)
end
return Client
@@ -0,0 +1,29 @@
return {
["书架与整本下载"] = "Bookshelf and full-book downloads",
["已下载书籍划线上传"] = "Upload highlights from downloaded books",
["已下载书籍进度同步"] = "Sync progress for downloaded books",
["连接 BookOrbit KOReader 接口"] = "Connect to the BookOrbit KOReader API",
["下载文件校验失败"] = "Downloaded file failed verification",
["确定退出 BookOrbit 账号?"] = "Sign out of BookOrbit?",
["正在下载…"] = "Downloading…",
["请求失败 (HTTP %1)"] = "Request failed (HTTP %1)",
["连接正常"] = "Connected",
["响应不是 JSON"] = "Response is not JSON",
["正在拉取书架(%1 本)"] = "Fetching shelf (%1 books)",
["BookOrbit"] = "BookOrbit",
["BookOrbit 上没有可同步的书库,请检查书库选择"] = "No library to sync on BookOrbit; check the library selection",
["BookOrbit 不认识本地这个文件,可能服务端的书已更换"] = "BookOrbit does not recognize this local file; the book on the server may have been replaced",
["BookOrbit 用户名或密码错误,或未开启 KOReader 同步"] = "BookOrbit username or password is wrong, or KOReader sync is not enabled",
["BookOrbit 设置 → KOReader 里创建的同步账号"] = "Sync account created in BookOrbit Settings → KOReader",
["从 BookOrbit 插件导入账号"] = "Import account from the BookOrbit plugin",
["同步账号的密码"] = "Password of the sync account",
["已导入账号 %1"] = "Imported account %1",
["无法识别服务器响应"] = "Unrecognized server response",
["正在连接 BookOrbit…"] = "Connecting to BookOrbit…",
["请先在设置里填写 BookOrbit 服务器和账号"] = "Fill in the BookOrbit server and account in Settings first",
["请先填写服务器地址、用户名和密码"] = "Fill in the server address, username and password first",
["这本书没有 KOReader 能打开的文件"] = "This book has no file KOReader can open",
["这本书还没下载,无法同步"] = "This book is not downloaded yet; cannot sync",
["选择书库(不选 = 全部)"] = "Select libraries (none = all)",
["连接 BookOrbit 服务器"] = "Connect to a BookOrbit server",
}
@@ -0,0 +1,29 @@
return {
["书架与整本下载"] = "書架與整本下載",
["已下载书籍划线上传"] = "已下載書籍畫線上傳",
["已下载书籍进度同步"] = "已下載書籍進度同步",
["连接 BookOrbit KOReader 接口"] = "連接 BookOrbit KOReader 介面",
["下载文件校验失败"] = "下載檔案校驗失敗",
["确定退出 BookOrbit 账号?"] = "確定登出 BookOrbit 帳號?",
["正在下载…"] = "正在下載…",
["请求失败 (HTTP %1)"] = "請求失敗 (HTTP %1)",
["连接正常"] = "連線正常",
["响应不是 JSON"] = "回應不是 JSON",
["正在拉取书架(%1 本)"] = "正在拉取書架(%1 本)",
["BookOrbit"] = "BookOrbit",
["BookOrbit 上没有可同步的书库,请检查书库选择"] = "BookOrbit 上沒有可同步的書庫,請檢查書庫選擇",
["BookOrbit 不认识本地这个文件,可能服务端的书已更换"] = "BookOrbit 不認識本地這個檔案,可能伺服端的書已更換",
["BookOrbit 用户名或密码错误,或未开启 KOReader 同步"] = "BookOrbit 使用者名稱或密碼錯誤,或未開啟 KOReader 同步",
["BookOrbit 设置 → KOReader 里创建的同步账号"] = "BookOrbit 設定 → KOReader 裡建立的同步帳號",
["从 BookOrbit 插件导入账号"] = "從 BookOrbit 外掛匯入帳號",
["同步账号的密码"] = "同步帳號的密碼",
["已导入账号 %1"] = "已匯入帳號 %1",
["无法识别服务器响应"] = "無法識別伺服器回應",
["正在连接 BookOrbit…"] = "正在連接 BookOrbit…",
["请先在设置里填写 BookOrbit 服务器和账号"] = "請先在設定裡填寫 BookOrbit 伺服器和帳號",
["请先填写服务器地址、用户名和密码"] = "請先填寫伺服器位址、使用者名稱和密碼",
["这本书没有 KOReader 能打开的文件"] = "這本書沒有 KOReader 能開啟的檔案",
["这本书还没下载,无法同步"] = "這本書還沒下載,無法同步",
["选择书库(不选 = 全部)"] = "選擇書庫(不選 = 全部)",
["连接 BookOrbit 服务器"] = "連接 BookOrbit 伺服器",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_bookorbit._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,240 @@
--[[--
BookOrbit 源设置:服务器地址、KOReader 同步账号、书库选择、测试连接;
装过 BookOrbit 官方插件时可一键导入它的账号。
配置经月读 utils.settings.getSource / saveSource("bookorbit") 落盘;密码只存 MD5(userkey)。
@module moonsource_bookorbit.setting
--]]
local Client = require("moonsource_bookorbit.client")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_bookorbit")
local T = require("ffi/util").template
local ID = "bookorbit"
local Setting = {}
---@return table
local function config()
return require("utils.settings").getSource(ID)
end
--- 服务器身份:地址 + 用户名。换了就是另一套书架。
local function libraryFingerprint(cfg)
return table.concat({
Client.normalizeUrl(cfg.server_url or ""),
Text.trim(cfg.username or ""),
}, "\0")
end
---@param text string
local function toast(text)
require("ui.themes.widgets.toast"):new{ text = text, timeout = 3 }:show()
end
--- 落盘并重建源实例;换服务器 / 用户保留记录,先准备同步。
---@param cfg table
---@param previous_fingerprint string|nil
---@return boolean
local function save(cfg, previous_fingerprint)
local function commit()
require("utils.settings").saveSource(ID, cfg)
end
if previous_fingerprint and previous_fingerprint ~= libraryFingerprint(cfg) then
if not require("source.logout").replaceLibrary(ID, commit) then
toast(_("准备本地同步失败"))
return false
end
else
commit()
require("source.registry").reload()
end
return true
end
--- 密码 → x-auth-key(MD5,同 kosync);空串表示清掉。
---@param value string|nil
---@return string
local function userkey(value)
value = Text.trim(value)
return value == "" and "" or require("ffi/sha2").md5(value) --[[@as string]]
end
--- 官方插件存在 G_reader_settings["bookorbit"] 里的账号(它的 server_url 带 /api/v1)。
---@return table|nil
local function officialAccount()
local reader = rawget(_G, "G_reader_settings")
local account = reader and reader:readSetting("bookorbit")
if type(account) ~= "table" then return nil end
local client = Client.new(account)
return client:configured() and client or nil
end
--- 未配置 / 断网当场提示;否则带忙碌提示调 fn(client, done),fn 结束时必须调 done()。
---@param fn fun(client: BookOrbitClient, done: fun())
local function withServer(fn)
local client = Client.new(config())
if not client:configured() then
toast(_("请先填写服务器地址、用户名和密码"))
return
end
if not require("ui/network/manager"):isConnected() then
toast(_("网络不可用,请先连接 Wi-Fi"))
return
end
local busy = require("ui.themes.widgets.toast"):new{ text = _("正在连接 BookOrbit…"), dismissable = false }
busy:show()
fn(client, function() busy:close() end)
end
---@param key string
---@param title string
---@param hint string
---@param password boolean
---@param normalize fun(value: string|nil): string
---@param icon string
---@return fun(iw: number): table
local function field(key, title, hint, password, normalize, icon)
return function(iw)
local value = config()[key] or ""
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true,
kind = "nav", icon = icon, title = title,
status = value ~= "" and (password and "******" or value) or _("未设置"),
status_on = value ~= "",
callback = function()
local cfg = config()
require("ui.themes.widgets.input"):new{
title = title,
-- 密码只存摘要,回填不了原文。
fields = { { text = password and "" or (cfg[key] or ""), hint = hint,
text_type = password and "password" or nil } },
ok_text = _("保存"),
callback = function(input)
local before = libraryFingerprint(cfg)
local next_cfg = require("util").tableDeepCopy(cfg)
next_cfg[key] = normalize(input)
-- 只改密码不算换库;地址 / 用户名变了才撕本地书架。
save(next_cfg, (key == "server_url" or key == "username") and before or nil)
end,
}:show()
end,
})
end
end
--- 多选书库:只同步选中的库;一个都不选 = 全部可访问的书库。
local function pickLibraries()
withServer(function(client, done)
client:json("GET", "/koreader/plugin/catalog/sections/libraries", nil, nil, function(data, err)
done()
if not data then
toast(err)
return
end
local cfg = config()
local chosen = cfg.libraries or {}
local items = {}
for _idx, lib in ipairs(data.items or {}) do
local id = tostring(lib.id)
items[#items + 1] = { text = lib.title or id, value = id, checked = chosen[id] == true }
end
require("ui.themes.widgets.list"):new{
title = _("选择书库(不选 = 全部)"),
multi = true,
items = items,
close_callback = function()
local picked = {}
for _idx, item in ipairs(items) do
if item.checked then picked[item.value] = true end
end
cfg.libraries = picked
save(cfg)
end,
}:show()
end)
end)
end
local function testConnection()
withServer(function(client, done)
client:json("GET", "/koreader/users/auth", nil, nil, function(data, err)
done()
toast(data and data.authorized == "OK" and _("连接正常") or err or _("无法识别服务器响应"))
end)
end)
end
---@return fun(iw: number): table
local function libraryRow()
return function(iw)
local count = 0
for _id in pairs(config().libraries or {}) do count = count + 1 end
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true,
kind = "nav", icon = "library_books", title = _("书库"),
status = count > 0 and T(_("%1 个"), count) or _("全部"),
status_on = true,
callback = pickLibraries,
})
end
end
---@param icon string
---@param title string
---@param callback fun()
---@return fun(iw: number): table
local function action(icon, title, callback)
return function(iw)
return require("ui.themes.widgets.row").widget({
width = iw, kind = "action", icon = icon, title = title, callback = callback,
})
end
end
local function importOfficial()
local account = officialAccount()
if not account then return end
local before = libraryFingerprint(config())
local cfg = require("util").tableDeepCopy(config())
cfg.server_url, cfg.username, cfg.userkey = account.server_url, account.username, account.userkey
if not save(cfg, before) then return end
toast(T(_("已导入账号 %1"), account.username))
end
---@return table[]
function Setting.rows()
local rows = {
field("server_url", _("服务器地址"), "https://books.example.com", false, Client.normalizeUrl, "dns"),
field("username", _("用户名"), _("BookOrbit 设置 → KOReader 里创建的同步账号"), false, Text.trim, "person"),
field("userkey", _("密码"), _("同步账号的密码"), true, userkey, "key"),
libraryRow(),
action("network_check", _("测试连接"), testConnection),
}
local cfg = config()
if (cfg.username or "") ~= "" and (cfg.userkey or "") ~= "" then
rows[#rows + 1] = require("source.logout").row(ID, _("确定退出 BookOrbit 账号?"), function()
local current = config()
current.username, current.userkey = "", ""
-- 只落凭证。reload 会让桌面立刻同步,必须等本地书架清完再 reload。
require("utils.settings").saveSource(ID, current)
end)
end
if officialAccount() then
table.insert(rows, 1, action("download", _("从 BookOrbit 插件导入账号"), importOfficial))
end
return rows
end
--- 远程管理「连接配置」网页上的表单;书库要连服务器挑,仍在设备上选。
Setting.remote = {
{ key = "server_url", label = _("服务器地址"), type = "url", placeholder = "https://books.example.com",
normalize = Client.normalizeUrl },
{ key = "username", label = _("用户名"), normalize = Text.trim },
{ key = "userkey", label = _("密码"), secret = true, normalize = userkey },
}
--- 这些键变了 = 换库,远程保存后整源清本地书架。
Setting.replace_on_remote = { "server_url", "username" }
return Setting
@@ -0,0 +1,466 @@
--[[--
BookOrbit 书源(整本模式)。走 BookOrbit 给 KOReader 插件开的接口(/api/v1/koreader/...)。
身份:书架一行 = 一本书,stable_id = BookOrbit bookId,分类 = 书库名。
书架:所选书库(未选 = 全部可访问书库)按书名分页拉全量,交书库对账。BookOrbit 没有删书接口,
本地删除只留墓碑。
开书:详情里按格式偏好挑一个 KOReader 能开的文件,下载原件到工作目录 `<fileId>.<ext>`。
进度:kosync 兼容接口,文档摘要 = 本地文件的 partialMD5(服务端按它认文件,与 KOReader 自带
kosync、BookOrbit 官方插件同一套)。位置:流式文档是 xpointer,固定版式是页码串。
划线:注解交换接口只做上传(keys 不全、不回 ack):服务端不据此推断删除,网页上的改动也不落到本地。
@module moonsource_bookorbit.source
--]]
local Client = require("moonsource_bookorbit.client")
local SourceBase = require("source.base")
local _ = require("l10n").get("moonsource_bookorbit")
local T = require("ffi/util").template
local ID = "bookorbit"
local PAGE_SIZE = 100
local CHUNK = 50
local PLUGIN_VERSION = "moon-1.0"
-- 服务端已只给 primary / content 文件;按 KOReader 阅读体验排序,有声书等格式不在表里。
local READABLE = { "epub", "azw3", "azw", "mobi", "fb2", "docx", "pdf", "djvu", "cbz", "txt" }
local MAGIC = { epub = "PK\3\4", cbz = "PK\3\4", pdf = "%PDF" }
local DRAWERS = { lighten = true, underscore = true, strikeout = true, invert = true }
local DATETIME = "^%d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d$"
---@class BookOrbitSource : SourceBase
---@field client BookOrbitClient
local Source = setmetatable({}, { __index = SourceBase })
Source.__index = Source
---@return BookSourceMeta
local function meta()
return require("moonsource_bookorbit.loadmeta")()
end
---@return BookOrbitSource
local function new()
local self = setmetatable(meta(), Source) --[[@as BookOrbitSource]]
self.client = Client.new(require("utils.settings").getSource(ID))
return self
end
function Source:configured()
return self.client:configured()
end
---@return boolean
local function online()
return require("ui/network/manager"):isConnected()
end
--- 与 KOReader 自带 kosync / BookOrbit 官方插件共用设备 id,服务端设备列表里是同一台;
--- 没有时(或不合服务端格式)自己生成一个存进源配置。
---@return string
local function deviceId()
local reader = rawget(_G, "G_reader_settings")
local id = reader and reader:readSetting("device_id")
if type(id) == "string" and #id <= 100 and id:match("^[%w%-]+$") then return id end
local settings = require("utils.settings")
local cfg = settings.getSource(ID)
if not cfg.device_id then
cfg.device_id = require("ffi/sha2").md5(table.concat({ os.time(), math.random(), tostring({}) }, ":"))
settings.saveSource(ID, cfg)
end
return cfg.device_id --[[@as string]]
end
---@return string
local function deviceModel()
local device = package.loaded["device"]
local model = type(device) == "table" and type(device.model) == "string" and device.model or "KOReader"
return model:sub(1, 100)
end
---@param list any
---@return string|nil
local function authorsOf(list)
if type(list) ~= "table" or #list == 0 then return nil end
return table.concat(list, " / ")
end
--- 文件头对得上格式才算下载完整;没有魔数的格式只要求非空。
---@param path string|nil
---@return boolean
local function validFile(path)
local file = path and io.open(path, "rb")
if not file then return false end
local head = file:read(4)
file:close()
if not head then return false end
local magic = MAGIC[(path:match("%.(%w+)$") or ""):lower()]
return magic == nil or head == magic
end
--- 已登记且完整的本地文件。
---@param stable_id string
---@return string|nil
local function downloaded(stable_id)
local book = require("book.books_db").get(ID, stable_id)
local path = book and book.path
if validFile(path) then return path end
return nil
end
--- 服务端认文件用的摘要;没下载就没有。
---@param stable_id string
---@return string|nil
local function digestOf(stable_id)
local path = downloaded(stable_id)
return path and require("util").partialMD5(path) --[[@as string]]
end
---@param files table[]|nil
---@return table|nil
local function pickFile(files)
for _fidx, format in ipairs(READABLE) do
for _idx, file in ipairs(files or {}) do
if type(file.format) == "string" and file.format:lower() == format then return file end
end
end
return nil
end
--- 插件接口要求的设备字段(deviceTime 让服务端按设备时钟生成 datetime)。
---@param body table
---@return table
local function withDevice(body)
body.deviceId = deviceId()
body.deviceModel = deviceModel()
body.pluginVersion = PLUGIN_VERSION
body.deviceTime = os.date("%Y-%m-%d %H:%M:%S")
return body
end
--- 书架:书库列表 → 逐库按书名分页拉书 → 对账。没有删书接口,dirty_only 跳过。
---@param opts { dirty_only?: boolean, on_progress?: fun(text: string|nil, done: integer|nil, total: integer|nil) }|nil
---@param cb fun(result: SyncResult|nil, err: any)
---@return { cancel: fun() }
function Source:syncBooksAsync(opts, cb)
opts = opts or {}
if opts.dirty_only then return SourceBase.skipped(cb, "no remote delete") end
if not self:configured() then
return SourceBase.defer(cb, nil, _("请先在设置里填写 BookOrbit 服务器和账号"))
end
local chosen = require("utils.settings").getSource(ID).libraries or {}
local report = opts.on_progress or function() end
local books, libraries, index, page, cancelled = {}, {}, 1, 1, false
---@type HttpJob
local job
local function fetch()
local library = libraries[index]
report(T(_("正在拉取书架(%1 本)"), #books))
job = self.client:json("GET", "/koreader/plugin/catalog/books",
{ libraryId = library.id, page = page, size = PAGE_SIZE, sort = "title", order = "asc" }, nil,
function(data, err)
if cancelled then return end
if not data then return cb(nil, err) end
-- 空体会被 Client:json 交成 {};拿缺页的书单对账会把本地书判成远端已删。
if type(data.items) ~= "table" then return cb(nil, _("响应无效")) end
for _idx, item in ipairs(data.items) do
if item.id == nil then return cb(nil, _("响应无效")) end
books[#books + 1] = {
stable_id = tostring(item.id),
title = item.title,
authors = authorsOf(item.authors),
series = item.seriesName,
category = library.title,
-- Shelf.reconcile 见 percent>=100 就自动标已读(不覆盖手动未读)。
percent = (item.readStatus == "read" or item.readStatus == "skimmed") and 100 or nil,
}
end
if data.hasNext == true then
page = page + 1
elseif index < #libraries then
index, page = index + 1, 1
else
return cb(require("source.shelf").reconcile(self.id, books))
end
fetch()
end)
end
job = self.client:json("GET", "/koreader/plugin/catalog/sections/libraries", nil, nil, function(data, err)
if cancelled then return end
if not data then return cb(nil, err) end
for _idx, entry in ipairs(data.items or {}) do
if next(chosen) == nil or chosen[tostring(entry.id)] then libraries[#libraries + 1] = entry end
end
-- 一个库都没有时不能拿空列表对账:那会把整个书架判成远端已删。
if #libraries == 0 then return cb(nil, _("BookOrbit 上没有可同步的书库,请检查书库选择")) end
fetch()
end)
return { cancel = function()
cancelled = true
job:cancel()
end }
end
--- KoreaderCatalogBookDetail → 书库行。rating 是用户自己打的分,不是公共评分,不收。
---@param id string 源 id
---@param stable_id string
---@param detail table
---@return Book
local function detailRow(id, stable_id, detail)
local Text = require("utils.text")
local intro = detail.description
if type(intro) == "string" and intro ~= "" then
intro = Text.stripHtml(intro)
if intro == "" then intro = nil end
else
intro = nil
end
return {
source_id = id, stable_id = stable_id, title = detail.title,
authors = authorsOf(detail.authors), intro = intro, series = detail.seriesName,
meta = {
publisher = detail.publisher, published = detail.publishedDate or detail.publishedYear,
language = detail.language, isbn = detail.isbn13 or detail.isbn10,
},
}
end
--- 详情:写回作者 / 简介 / 系列 / 扩展元数据,回调原始详情(开书要 files)。
---@param stable_id string
---@param cb fun(detail: table|nil, err: string|nil)
---@return HttpJob
function Source:detail(stable_id, cb)
return self.client:json("GET", "/koreader/plugin/catalog/books/" .. stable_id, { deviceId = deviceId() }, nil,
function(detail, err)
if not detail then return cb(nil, err) end
require("book.store").rememberMany({ detailRow(self.id, stable_id, detail) })
cb(detail)
end)
end
---@param identity BookIdentity
---@param cb fun(book: Book|nil, err: string|nil)
---@return { cancel: fun() }
function Source:getDetailAsync(identity, cb)
return self:detail(identity.stable_id, function(detail, err)
if not detail then return cb(nil, err) end
cb(detailRow(self.id, identity.stable_id, detail))
end)
end
--- 下载到 `<工作目录>/<fileId>.<ext>.part`,完整后改名并登记路径:中途断掉不会留下半个文件被当成已下载。
---@param identity BookIdentity
---@param file table KoreaderCatalogFile
---@param title string|nil
---@param cb fun(path: string|nil, err: string|nil)
---@return { cancel: fun() }
function Source:fetchFile(identity, file, title, cb)
local Paths = require("utils.paths")
Paths.ensureBookWork(identity.stable_id, self.id)
local path = T("%1/%2.%3", Paths.bookWorkDir(identity.stable_id, self.id), file.id, file.format:lower())
local part = path .. ".part"
local dialog = require("ui.themes.widgets.progress_dialog"):new{ title = title, dismissable = false }
dialog:show()
dialog:set(_("正在下载…"))
local job = self.client:download(file.id, part, function(bytes, total)
total = total or tonumber(file.sizeBytes)
if total and total > 0 then dialog:bytes(bytes, total) end
end, function(ok, err)
dialog:close()
if not ok then
os.remove(part)
return cb(nil, err or _("下载失败"))
end
if not os.rename(part, path) or not validFile(path) then
os.remove(part)
os.remove(path)
return cb(nil, _("下载文件校验失败"))
end
local registered, rerr = require("book.store").touch(path, identity)
cb(registered and path or nil, rerr)
end)
return { cancel = function()
job:cancel()
dialog:close()
end }
end
--- 打开:已下载的直接开(不联网);否则取详情挑文件下载。
function Source:openBookAsync(identity, _opts, cb)
local path = downloaded(identity.stable_id)
if path then return SourceBase.defer(cb, path) end
if not online() then return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi")) end
local cancelled = false
---@type { cancel: fun() }
local job
local function finish(file, err)
if not cancelled then cb(file, err) end
end
job = self:detail(identity.stable_id, function(detail, err)
if cancelled then return end
if not detail then return finish(nil, err) end
local file = pickFile(detail.files)
if not file then return finish(nil, _("这本书没有 KOReader 能打开的文件")) end
job = self:fetchFile(identity, file, detail.title, finish)
end)
return { cancel = function()
cancelled = true
job:cancel()
end }
end
---@param identity BookIdentity
---@return BookCoverRequest|nil, string|nil
function Source:coverRequest(identity)
if not self:configured() then return nil, _("未配置") end
return {
url = self.client:url("/koreader/plugin/catalog/books/" .. identity.stable_id .. "/thumbnail"),
headers = self.client:headers(),
}
end
--- kosync 进度 → 月读位置;与本地同一 xpointer / 页时交回本地行(不算冲突)。
---@param stable_id string
---@param remote { percentage: number, progress: string|nil, timestamp: number|nil }
---@return ProgressPosition
local function position(stable_id, remote)
local progress = type(remote.progress) == "string" and remote.progress or ""
local page = tonumber(progress)
local here = require("book.progress_db").get(ID, stable_id)
if here and ((progress ~= "" and here.locator == progress) or (page and here.page == page)) then
return here
end
return {
fraction = math.max(0, math.min(1, tonumber(remote.percentage) or 0)),
locator = progress:sub(1, 1) == "/" and progress or nil,
page = page and math.floor(page) or nil,
updated_at = tonumber(remote.timestamp),
}
end
function Source:getProgressAsync(identity, cb)
local digest = digestOf(identity.stable_id)
if not digest then return SourceBase.defer(cb, nil, nil, { empty = true }) end
return self.client:json("GET", "/koreader/syncs/progress/" .. digest, nil, nil, function(remote, err)
if not remote then return cb(nil, err) end
-- 服务端没有这本书或没有进度都回 {}。
if type(remote.percentage) ~= "number" then return cb(nil, nil, { empty = true }) end
cb(position(identity.stable_id, remote))
end)
end
--- 月读位置 → kosync:流式文档推 xpointer,固定版式推页码。timestamp 用进度自己的时间,
--- 服务端会丢弃比已知更旧的推送,离线攒下的旧进度不会盖掉别处更新的位置。
function Source:putProgressAsync(identity, pos, cb)
local digest = digestOf(identity.stable_id)
if not digest then return SourceBase.defer(cb, nil, _("这本书还没下载,无法同步")) end
return self.client:json("PUT", "/koreader/syncs/progress", nil, {
document = digest,
percentage = math.max(0, math.min(1, tonumber(pos.fraction) or 0)),
progress = pos.locator or (pos.page and tostring(pos.page)) or nil,
device = deviceModel(),
device_id = deviceId(),
timestamp = pos.updated_at or os.time(),
}, function(data, err, code)
if code == 404 then return cb(nil, _("BookOrbit 不认识本地这个文件,可能服务端的书已更换")) end
cb(data and true, err)
end)
end
--- 按 UTF-8 字符边界截断(服务端按字符数限长;截成半个字符整块请求会被拒)。
---@param s any
---@param max integer
---@return string|nil
local function cut(s, max)
if type(s) ~= "string" then return nil end
if #s <= max then return s end
local out = s:sub(1, max)
local next_byte = s:byte(max + 1)
if next_byte >= 0x80 and next_byte < 0xC0 then
out = out:gsub("[\192-\255][\128-\191]*$", "")
end
return out
end
--- 位置序列化与官方插件一致:服务端注解键 = md5(datetime|pos0),写法不同就会重复建。
---@param pos any
---@return string|nil, string|nil
local function serializePos(pos)
if type(pos) == "string" then return pos, "xpointer" end
if type(pos) == "table" and type(pos.page) == "number" then
return string.format('{"page":%d,"x":%.2f,"y":%.2f}', pos.page, tonumber(pos.x) or 0, tonumber(pos.y) or 0), "pdf"
end
return nil
end
---@param value any
---@return string|nil
local function datetime(value)
return type(value) == "string" and value:match(DATETIME) and value or nil
end
--- 月读注解快照 → 服务端 KoreaderAnnotationDto;书签(无 drawer)不传。
---@param annotations table[]
---@return table[]
local function changesOf(annotations)
local out = {}
for _idx, ann in ipairs(annotations) do
local pos0, format = serializePos(ann.pos0)
if DRAWERS[ann.drawer] and datetime(ann.datetime) and pos0 then
out[#out + 1] = {
datetime = ann.datetime,
datetimeUpdated = datetime(ann.datetime_updated),
drawer = ann.drawer,
color = cut(ann.color, 30),
text = cut(ann.text, 10000),
note = cut(ann.note, 5000),
chapter = cut(ann.chapter, 500),
pageno = type(ann.pageno) == "number" and ann.pageno >= 0 and math.floor(ann.pageno) or nil,
posFormat = format,
pos0 = cut(pos0, 4000),
pos1 = cut((serializePos(ann.pos1)), 4000),
}
end
end
return out
end
--- 划线整份上传(服务端按 datetime|pos0 去重,重传是空操作),每次 50 条。
--- keysComplete = false:不让服务端拿这份清单推断「设备删了哪些」;服务端回传的改动不 ack,留在服务端。
---@param identity BookIdentity
---@param annotations table[]
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return { cancel: fun() }
function Source:pushNotesAsync(identity, annotations, cb)
local digest = digestOf(identity.stable_id)
if not digest then return SourceBase.defer(cb, nil, _("这本书还没下载,无法同步")) end
local pending = changesOf(annotations)
if #pending == 0 then return SourceBase.defer(cb, true) end
local cursor, cancelled = 1, false
---@type HttpJob
local job
local function nextChunk()
if cursor > #pending then return cb(true) end
local chunk = {}
for idx = cursor, math.min(cursor + CHUNK - 1, #pending) do chunk[#chunk + 1] = pending[idx] end
cursor = cursor + #chunk
job = self.client:json("POST", "/koreader/plugin/annotations/exchange", nil, withDevice({
-- 空表默认编码成 {},服务端要数组。
books = { { hash = digest, keys = require("json").util.InitArray({}), keysComplete = false, changes = chunk } },
}), function(data, err)
if cancelled then return end
if not data then return cb(nil, err) end
for _idx, hash in ipairs(data.unmatched or {}) do
if hash == digest then return cb(nil, _("BookOrbit 不认识本地这个文件,可能服务端的书已更换")) end
end
nextChunk()
end)
end
nextChunk()
return { cancel = function()
cancelled = true
job:cancel()
end }
end
return { meta = meta, new = new, ID = ID }
@@ -0,0 +1,4 @@
-- 版本号由 tools/package.sh 打包时把占位符换成发布版本;源码运行显示 0.0.0-dev。
local VERSION = "@VERSION@"
if VERSION:find("^@") then return "0.0.0-dev" end
return VERSION