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

This commit is contained in:
Garfield committed 2026-11-27 08:08:01 +08:00
commit df896cbe3b
28 files changed
+3586

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
local _ = require("gettext")
return {
fullname = _("月读书源:开源阅读"),
description = _("给月读增加「开源阅读」书源。需要同时安装月读,与平台官方无关。"),
}
+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_legado",
is_doc_only = false,
}
@@ -0,0 +1,17 @@
--[[--
月读第三方书源描述:开源阅读。契约见月读 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_legado.source").meta() end,
new = function() return require("moonsource_legado.source").new() end,
setting = lazy("moonsource_legado.setting"),
}
@@ -0,0 +1,17 @@
# 开源阅读(Legado)
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| 服务连接 | 支持 | 阅读 App Web 服务、reader3、轻阅读;不是直接导入规则书源 |
| 局域网发现 | 支持 | 可扫描阅读服务地址 |
| 账号密码 | 部分支持 | reader3、轻阅读可配置;普通阅读 App Web 服务无需账号 |
| 书架拉取 | 支持 | 书籍须先在阅读 App 或服务端添加 |
| 加入远端书架 | 不支持 | 请在对应 App 或服务端添加 |
| 移出远端书架 | 支持 | 服务端确认后清除本地墓碑 |
| 目录与文字正文 | 支持 | 取决于服务端书源可用性;轻阅读需有效书源信息 |
| 封面与正文图片 | 部分支持 | 具体行为取决于后端 |
| 阅读进度同步 | 支持 | 章节及章内偏移;不同排版不保证精确对齐 |
| 笔记与统计同步 | 不支持 | 本地记录保留 |
| 书评、章评、段评与回复 | 不支持 | 桥接后端没有统一评论契约;不代表上游网站没有评论 |
| 章节预取与全本缓存 | 支持 | 内容需由服务端正常返回 |
| 离线阅读 | 支持 | 仅已缓存目录和章节 |
@@ -0,0 +1,16 @@
--[[--
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
@module moonsource_legado._meta
--]]
local _ = require("l10n").get("moonsource_legado")
return {
id = "legado",
name = _("开源阅读"),
type = "chapter",
description = _("连接阅读 App、reader3 或轻阅读服务"),
abilities = { _("书架与章节正文"), _("目录及整本缓存"), _("进度同步"), _("从服务端书架删除"),
_("他人段评(阅读 App)") },
}
@@ -0,0 +1,377 @@
--[[--
阅读(Legado)Web 服务 HTTP 客户端(仅异步)。
三种后端共用回包 `{ isSuccess, errorMsg, data }` 与 0 基章节 `index`,按地址后缀区分(Client.mode):
- app:阅读 App 的 Web 服务(http://192.168.1.8:1122),GET 查询、JSON 上报;
- reader3:服务器版(…/reader3),可登录;书架 GET,其余 POST JSON;
- qread:轻阅读(…/api/5),可登录;全部 POST 表单,章节 / 正文要带书源 origin。
@module koplugin.book.moonsource_legado.client
--]]
local JSON = require("json")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_legado")
local Client = {}
local SOURCE_ID = "legado"
--- 服务器地址,缺协议头按 http 补;没配置返回 nil。
---@param cfg table|nil 校验待保存配置时显式传入,不改变当前库
---@return string|nil
function Client.base(cfg)
local addr = (cfg or require("utils.settings").getSource(SOURCE_ID)).server_address
if type(addr) ~= "string" or addr == "" then return nil end
if not addr:match("^https?://") then addr = "http://" .. addr end
return (addr:gsub("/+$", ""))
end
--- 解回包:isSuccess 为真才算成功,返回 data。
---@param raw string|nil
---@param err any
---@return any|nil data, string|nil err
function Client.decode(raw, err)
if not raw then return nil, err and tostring(err) or _("请求失败") end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then return nil, _("响应无效") end
if not wire.isSuccess then return nil, wire.errorMsg ~= "" and wire.errorMsg or _("请求失败") end
if wire.data == nil then return {} end
return wire.data
end
---@alias LegadoMode "app"|"reader3"|"qread"
--- 后端类型,看地址路径的最后一段。
---@param cfg table|nil
---@return LegadoMode
function Client.mode(cfg)
local base = Client.base(cfg) or ""
if base:find("/reader3$") then return "reader3" end
if base:find("/api/%d+$") then return "qread" end
return "app"
end
--- 服务根(去掉 /reader3、/api/N),封面与书内图片的相对路径从这里起算。
---@return string
local function root()
return ((Client.base() or ""):gsub("/reader3$", ""):gsub("/api/%d+$", ""))
end
---@param path string
---@param query table<string, any>|nil
---@param cfg table|nil
---@return string|nil
local function url(path, query, cfg)
local base = Client.base(cfg)
if not base then return nil end
local out = base .. path
if query then
local qs = Text.formEncode(query)
if qs ~= "" then out = out .. "?" .. qs end
end
return out
end
--- 账号密码(阅读 App 的 Web 服务没有账号);缺一项视为无需登录。
---@param cfg table|nil
---@return string|nil user, string|nil password
local function credentials(cfg)
cfg = cfg or require("utils.settings").getSource(SOURCE_ID)
if type(cfg.username) == "string" and cfg.username ~= "" and type(cfg.password) == "string" and cfg.password ~= "" then
return cfg.username, cfg.password
end
return nil
end
-- accessToken 只在内存里,key 带地址与账号,改了配置自然作废。
local session = { key = nil, token = nil }
---@param method "GET"|"POST"
---@param enc "json"|"form"|nil POST 体编码
---@param target string
---@param body table|nil
---@param ratio number
---@param done fun(data: any|nil, err: string|nil)
---@return { cancel: fun() }
local function send(method, enc, target, body, ratio, done)
local opts = { accept = "application/json", timeout = require("http.timeout").net(ratio) }
local function finish(raw, err) done(Client.decode(raw, err)) end
if method == "GET" then return Request.get(target, opts, finish) end
if enc == "form" then
opts.content_type = "application/x-www-form-urlencoded"
local flat = {}
for k, v in pairs(body) do
if type(v) ~= "table" then flat[k] = v end
end
return Request.post(target, Text.formEncode(flat), opts, finish)
end
opts.content_type = "application/json"
return Request.post(target, JSON.encode(body), opts, finish)
end
---@param user string
---@param password string
---@param cb fun(token: string|nil, err: string|nil)
---@param cfg table|nil
---@return { cancel: fun() }
local function login(user, password, cb, cfg)
local target = url("/login", nil, cfg)
if not target then return require("source.base").defer(cb, nil, _("未配置阅读服务器地址")) end
local qread = Client.mode(cfg) == "qread"
local body = qread and { username = user, password = password, model = "web" }
or { username = user, password = password, code = "", isLogin = true, v = os.time() }
return send("POST", qread and "form" or "json", target, body, 0.5, function(data, reason)
local token = type(data) == "table" and data.accessToken
if type(token) ~= "string" or token == "" then
cb(nil, reason or _("登录失败"))
return
end
cb(token)
end)
end
--- 配了账号密码时先登录、请求带 accessToken;服务端回 NEED_LOGIN(令牌过期)就重新登录再试一次。
--- 重登仍失败 / 仍 NEED_LOGIN → Auth.expire,引导用户检查账号密码。
---@param go fun(token: string|nil, done: fun(data: any|nil, err: string|nil)): { cancel: fun() }
---@param cb fun(data: any|nil, err: string|nil)
---@param cfg table|nil
---@return { cancel: fun() }
local function authed(go, cb, cfg)
local user, password = credentials(cfg)
local base = Client.base(cfg)
-- 配置里可能只剩账号密码:没地址时交给 go 报「未配置」。
if not user or not base then return go(nil, cb) end
local auth_session = cfg and {} or session
local key = base .. "\0" .. user .. "\0" .. password
local expired_msg = _("打开「设置 → 书库 → 账号 → 开源阅读 → 阅读服务地址」。账号和密码重新填一遍,地址不用改,点「保存」。阅读 App 里如果改过密码,这里填新密码。")
---@type boolean, CancelHandle|nil
local cancelled, job = false, nil
local function run(retry)
local function call(token)
job = go(token, function(data, err)
if cancelled then return end
if retry and err and err:find("NEED_LOGIN", 1, true) then
auth_session.token = nil
run(false)
return
end
if err and err:find("NEED_LOGIN", 1, true) then
err = require("source.auth").expire(SOURCE_ID, expired_msg)
end
cb(data, err)
end)
end
if auth_session.key == key and auth_session.token then
call(auth_session.token)
else
job = login(user, password, function(token, err)
if cancelled then return end
if not token then
-- 令牌过期后的重登失败:明确通知;首次配置错误登录仍原样返回。
if not retry then
err = require("source.auth").expire(SOURCE_ID, expired_msg)
end
cb(nil, err)
return
end
auth_session.key, auth_session.token = key, token
require("source.auth").ok(SOURCE_ID)
call(token)
end, cfg)
end
end
run(true)
return { cancel = function()
cancelled = true
job.cancel()
end }
end
--- 一次调用。kind:shelf(app / reader3 用 GET)、read(只有 app 用 GET)、write;其余按后端走 POST JSON / 表单。
---@param path string
---@param params table<string, any>
---@param ratio number 超时倍率
---@param kind "shelf"|"read"|"write"
---@param cb fun(data: any|nil, err: string|nil)
---@param cfg table|nil
---@return { cancel: fun() }
local function call(path, params, ratio, kind, cb, cfg)
local mode = Client.mode(cfg)
local get = (kind == "shelf" and mode ~= "qread") or (kind == "read" and mode == "app")
local method = get and "GET" or "POST"
return authed(function(token, done)
local query = token and { accessToken = token } or nil
if method == "GET" then
query = query or {}
for k, v in pairs(params) do query[k] = v end
end
local target = url(path, query, cfg)
if not target then return require("source.base").defer(done, nil, _("未配置阅读服务器地址")) end
return send(method, mode == "qread" and "form" or "json", target, params, ratio, done)
end, cb, cfg)
end
--- 书内图片地址:服务端给的相对路径补成可直接下载的 URL(app 的相对路径没有意义,原样返回)。
---@param src string
---@param base string|nil EPUB 章节 URL,按它解析相对引用;只给同服务器的资源带令牌。
---@return string
function Client.imageUrl(src, base)
local out
if base then
out = assert(Text.absoluteUrl(base, src), "invalid chapter resource URL")
if out:match("^(https?://[^/]+)") ~= root():match("^(https?://[^/]+)") then return out end
else
if src:find("^https?://") then return src end
local mode = Client.mode()
if mode == "app" then return src end
if mode == "qread" then
out = src:find("^baseurl/") and (Client.base() .. src:sub(8))
or (Client.base() .. "/proxypng?url=" .. Text.urlEncode(src))
else
out = root() .. src:gsub("^__API_ROOT__", "")
end
end
if session.token then
local target, fragment = out:match("^([^#]*)(.*)$")
out = target .. (target:find("?", 1, true) and "&" or "?") .. "accessToken=" .. session.token .. fragment
end
return out
end
--- 封面地址。阅读 App 的原地址常要 Referer / 本地路径,一律走 /cover 代理。
---@param path string
---@return string
function Client.coverUrl(path)
if Client.mode() == "app" then return url("/cover", { path = path }) end
return Client.imageUrl(path)
end
---@param cb fun(rows: table[]|nil, err: string|nil)
---@param cfg table|nil 待保存配置;缺省读取当前配置
---@return { cancel: fun() }
function Client.shelfAsync(cb, cfg)
local params = { app = { refresh = 0 }, reader3 = { refresh = 0 }, qread = { version = "3.2.1" } }
return call("/getBookshelf", params[Client.mode(cfg)], 0.5, "shelf", function(data, err)
if type(data) ~= "table" then cb(nil, err); return end
cb(data)
end, cfg)
end
--- 书架分组(用户在阅读 App 里建的分组)。轻阅读没有这个接口,回 nil 即可。
---@param cb fun(rows: table[]|nil, err: string|nil)
---@return { cancel: fun() }
function Client.groupsAsync(cb)
if Client.mode() == "qread" then return require("source.base").defer(cb, nil, "unsupported") end
return call("/getBookGroups", {}, 0.5, "shelf", function(data, err)
if type(data) ~= "table" then cb(nil, err); return end
cb(data)
end)
end
--- 目录。book_url + 书源(轻阅读必需,其余忽略)。
---@param book_url string
---@param origin string|nil
---@param cb fun(rows: table[]|nil, err: string|nil)
---@return { cancel: fun() }
function Client.chaptersAsync(book_url, origin, cb)
return call("/getChapterList", { url = book_url, bookSourceUrl = origin }, 1, "read", function(data, err)
if type(data) ~= "table" then cb(nil, err); return end
cb(data)
end)
end
--- 一章正文(0 基序号),纯文本;轻阅读回包是 `{ text }`。
---@param book_url string
---@param index integer
---@param origin string|nil
---@param cb fun(text: string|nil, err: string|nil)
---@return { cancel: fun() }
function Client.contentAsync(book_url, index, origin, cb)
local params = { url = book_url, index = index, bookSourceUrl = origin, type = origin and 0 or nil }
return call("/getBookContent", params, 1, "read", function(data, err)
local text = type(data) == "table" and data.text or data
if type(text) ~= "string" or text == "" then
require("utils.log").warn("legado empty chapter", book_url, index, type(text), err)
cb(nil, err or (_("阅读章节内容为空") .. " #" .. (index + 1)))
return
end
cb(text)
end)
end
local function reviewCall(path, params, cb)
if Client.mode() ~= "app" then
return require("source.base").defer(cb, nil, _("段评仅支持阅读 App 的 Web 服务"))
end
return call(path, params, 1, "read", cb)
end
---@param book_url string
---@param index integer 阅读目录里的 0 基序号
---@param cb function
---@return { cancel: fun() }
function Client.reviewSummaryAsync(book_url, index, cb)
return reviewCall("/getReviewSummary", { url = book_url, index = index }, cb)
end
---@param book_url string
---@param index integer
---@param paragraph integer
---@param data string
---@param page integer
---@param cursor string|nil
---@param cb function
---@return { cancel: fun() }
function Client.reviewDetailAsync(book_url, index, paragraph, data, page, cursor, cb)
return reviewCall("/getReviewDetail", {
url = book_url, index = index, paraIndex = paragraph, paraData = data, page = page, cursor = cursor,
}, cb)
end
---@param book_url string
---@param index integer
---@param paragraph integer
---@param data string
---@param review_id string
---@param page integer
---@param cb function
---@return { cancel: fun() }
function Client.reviewRepliesAsync(book_url, index, paragraph, data, review_id, page, cb)
return reviewCall("/getReviewReplies", {
url = book_url, index = index, paraIndex = paragraph, paraData = data, reviewId = review_id, page = page,
}, cb)
end
--- 上报阅读位置。row 是书架原行(name / author / bookUrl / origin)。
---@param row table
---@param pos { index: integer, title: string|nil, offset: integer }
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return { cancel: fun() }
function Client.saveProgressAsync(row, pos, cb)
local body = {
name = row.name,
author = row.author,
url = row.bookUrl,
index = pos.index,
durChapterIndex = pos.index,
durChapterPos = pos.offset,
durChapterTitle = pos.title or "",
durChapterTime = os.time() * 1000,
}
if Client.mode() == "qread" then
body = { url = row.bookUrl, index = pos.index, title = pos.title or "", pos = pos.offset }
end
return call("/saveBookProgress", body, 0.5, "write", function(_data, reason) cb(reason == nil or nil, reason) end)
end
--- 把书从阅读 App 书架移除,row 是书架原行。
---@param row table
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return { cancel: fun() }
function Client.deleteBookAsync(row, cb)
return call("/deleteBook", row, 0.5, "write", function(_data, reason) cb(reason == nil or nil, reason) end)
end
return Client
@@ -0,0 +1,38 @@
return {
["本章讨论"] = "Chapter discussion",
["章节评论"] = "Chapter comments",
["他人段评(阅读 App)"] = "Paragraph comments (Legado app)",
["段评仅支持阅读 App 的 Web 服务"] = "Paragraph comments require the Legado app's web service",
["阅读段评位置无效"] = "Invalid Legado comment location",
["阅读段评分页位置无效"] = "Invalid Legado comment page position",
["阅读段评响应无效"] = "Invalid Legado comment response",
["书架与章节正文"] = "Bookshelf and chapter content",
["从服务端书架删除"] = "Remove from the server bookshelf",
["目录及整本缓存"] = "Table of contents and full-book caching",
["连接阅读 App、reader3 或轻阅读服务"] = "Connect to Legado, reader3 or a Qingyuedu service",
["打开「设置 → 书库 → 账号 → 开源阅读 → 阅读服务地址」。账号和密码重新填一遍,地址不用改,点「保存」。阅读 App 里如果改过密码,这里填新密码。"] = "Open Settings → Library → Account → Legado → Legado server address. Enter the username and password again, leave the address as it is, and tap Save. If you changed the password in the Legado app, enter the new one.",
["确定退出开源阅读?"] = "Sign out of Legado?",
["已配置"] = "Configured",
["章节目录保存失败"] = "Failed to save chapter list",
["开源阅读"] = "Legado",
["请在阅读 App 里添加书籍"] = "Add books in the Legado app",
["未配置阅读服务器地址"] = "Legado server address is not set",
["这本书不在阅读书架上"] = "This book is not on the Legado shelf",
["缺少阅读章节位置"] = "Missing Legado chapter position",
["阅读目录为空"] = "Legado table of contents is empty",
["阅读章节内容为空"] = "Chapter content is empty",
["阅读插图下载失败,请重试"] = "Failed to download chapter illustrations. Please retry.",
["阅读服务"] = "Legado server",
["账号(reader3 服务器版才需要)"] = "Account (reader3 server only)",
["阅读服务地址"] = "Legado server address",
["正在连接阅读服务…"] = "Connecting to Legado…",
["已连接,书架共 %1 本"] = "Connected, %1 books on the shelf",
["连接失败"] = "Connection failed",
["扫描局域网"] = "Scan the local network",
["正在扫描局域网…"] = "Scanning the local network…",
["没有找到阅读服务"] = "No Legado service found",
["没有局域网地址"] = "No local network address",
["选择阅读服务"] = "Choose a Legado service",
["进度同步"] = "Progress sync",
["连接开源阅读(Legado)服务"] = "Connect to an Open Reader (Legado) service",
}
@@ -0,0 +1,38 @@
return {
["本章讨论"] = "本章討論",
["章节评论"] = "章節評論",
["他人段评(阅读 App)"] = "他人段評(閱讀 App)",
["段评仅支持阅读 App 的 Web 服务"] = "段評僅支援閱讀 App 的 Web 服務",
["阅读段评位置无效"] = "閱讀段評位置無效",
["阅读段评分页位置无效"] = "閱讀段評分頁位置無效",
["阅读段评响应无效"] = "閱讀段評回應無效",
["书架与章节正文"] = "書架與章節正文",
["从服务端书架删除"] = "從伺服器書架刪除",
["目录及整本缓存"] = "目錄及整本快取",
["连接阅读 App、reader3 或轻阅读服务"] = "連接閱讀 App、reader3 或輕閱讀服務",
["打开「设置 → 书库 → 账号 → 开源阅读 → 阅读服务地址」。账号和密码重新填一遍,地址不用改,点「保存」。阅读 App 里如果改过密码,这里填新密码。"] = "打開「設定 → 書庫 → 帳號 → 開源閱讀 → 閱讀服務位址」。帳號和密碼重新填一遍,位址不用改,點「儲存」。閱讀 App 裡如果改過密碼,這裡填新密碼。",
["确定退出开源阅读?"] = "確定登出開源閱讀?",
["已配置"] = "已設定",
["章节目录保存失败"] = "章節目錄儲存失敗",
["开源阅读"] = "開源閱讀",
["请在阅读 App 里添加书籍"] = "請在閱讀 App 裡新增書籍",
["未配置阅读服务器地址"] = "未設定閱讀伺服器位址",
["这本书不在阅读书架上"] = "這本書不在閱讀書架上",
["缺少阅读章节位置"] = "缺少閱讀章節位置",
["阅读目录为空"] = "閱讀目錄為空",
["阅读章节内容为空"] = "閱讀章節內容為空",
["阅读插图下载失败,请重试"] = "閱讀插圖下載失敗,請重試",
["阅读服务"] = "閱讀服務",
["账号(reader3 服务器版才需要)"] = "帳號(僅 reader3 伺服器版需要)",
["阅读服务地址"] = "閱讀服務位址",
["正在连接阅读服务…"] = "正在連接閱讀服務…",
["已连接,书架共 %1 本"] = "已連接,書架共 %1 本",
["连接失败"] = "連接失敗",
["扫描局域网"] = "掃描區域網路",
["正在扫描局域网…"] = "正在掃描區域網路…",
["没有找到阅读服务"] = "沒有找到閱讀服務",
["没有局域网地址"] = "沒有區域網路位址",
["选择阅读服务"] = "選擇閱讀服務",
["进度同步"] = "進度同步",
["连接开源阅读(Legado)服务"] = "連接開源閱讀(Legado)服務",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_legado._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,155 @@
--[[--
阅读(Legado)Web 服务数据映射(纯函数)。
@module koplugin.book.moonsource_legado.mapper
--]]
local Text = require("utils.text")
local Mapper = {}
local SOURCE_ID = "legado"
--- 封面走阅读服务器的 /cover 代理(原地址常要 Referer / 本地路径)。
---@param coverUrl fun(path: string): string
---@param row table
---@return string|nil
local function cover(coverUrl, row)
local path = row.customCoverUrl
if type(path) ~= "string" or path == "" then path = row.coverUrl end
if type(path) ~= "string" or path == "" then return nil end
return coverUrl(path)
end
--- 书的 group 是分组 id 的位掩码(id 为 2 的幂);返回命中的分组名,没有分组返回 nil。
local function groupNames(groups, mask)
local names = {}
mask = tonumber(mask) or 0
for _idx, g in ipairs(groups) do
local id = tonumber(g.groupId)
if id and id > 0 and type(g.groupName) == "string" and math.floor(mask / id) % 2 == 1 then
names[#names + 1] = g.groupName
end
end
return #names > 0 and table.concat(names, ",") or nil
end
--- 书架行 → Book[]。rows.groups 有值时分类取阅读 App 的书架分组(权威:没分组就是未分类);否则退回书源标签 kind。bookUrl 是书在阅读 App 里的唯一键。
---@param coverUrl fun(path: string): string 封面代理地址构造(Client.coverUrl)
---@param rows table[]
---@return Book[]
function Mapper.shelfList(coverUrl, rows)
local out, groups = {}, rows.groups
local now = os.time()
local n = #rows
for idx, row in ipairs(rows) do
if type(row.bookUrl) == "string" and row.bookUrl ~= "" then
local dur_time = tonumber(row.durChapterTime)
local read_at = (dur_time and dur_time > 1000000000)
and math.floor(dur_time > 100000000000 and dur_time / 1000 or dur_time) or nil
out[#out + 1] = {
source_id = SOURCE_ID,
stable_id = row.bookUrl,
title = row.name,
authors = row.author,
category = groups and groupNames(groups, row.group) or (not groups and row.kind or nil),
category_authoritative = groups and true or nil,
intro = row.intro and Text.stripHtml(row.intro),
cover = cover(coverUrl, row),
read_at = read_at,
inserted_at = now + (n - idx),
}
end
end
return out
end
--- 书架行里的阅读位置(序号 0 基)。没读过返回 nil。
---@param row table|nil
---@return { index: integer, title: string|nil, offset: integer }|nil
function Mapper.readPos(row)
local index = row and tonumber(row.durChapterIndex)
if not index or (index == 0 and (tonumber(row.durChapterTime) or 0) <= 0) then return nil end
local title = row.durChapterTitle
return { index = index, title = type(title) == "string" and title ~= "" and title or nil,
offset = tonumber(row.durChapterPos) or 0 }
end
--- 目录:按服务端顺序,idx 连续,uid 是 0 基章节序号;origin 是书源(轻阅读取正文要用,随目录落盘)。
---@param rows table[]
---@param origin string|nil
---@return BookChapter[]
function Mapper.toc(rows, origin)
local toc = {}
for i, row in ipairs(rows) do
toc[i] = { idx = i, uid = tostring(tonumber(row.index) or (i - 1)), title = row.title, origin = origin }
end
return toc
end
--- 正文纯文本里夹着 ``<img>``(图片章、网站插图):图片留成真标签,其余照旧转义,否则标签原样显示。
--- 懒加载占位用的 data:image/svg+xml 没有内容,直接丢掉;src 尾部 Legado 的 ``,{请求头 JSON}`` 剥掉。
---@param title string
---@param text string
---@param imageUrl fun(src: string): string 相对图片地址补全(Client.imageUrl)
---@param reviews boolean|nil 保存阅读 App 的段落编号
---@return string
function Mapper.chapterHtml(title, text, imageUrl, reviews)
if reviews then
local paragraph = 0
text = (text:gsub("\n+", "\n") .. "\n"):gsub("(.-)\n", function(line)
paragraph = paragraph + 1
return line .. "\2" .. paragraph .. "\2\n"
end)
end
local imgs = {}
text = text:gsub("<img%s[^>]*>", function(tag)
local src = tag:match('src%s*=%s*"([^"]*)"') or tag:match("src%s*=%s*'([^']*)'")
src = src and src:gsub(",%s*{.*$", "")
if not src or src == "" or src:find("^data:image/svg") then return "" end
imgs[#imgs + 1] = '<img src="' .. Text.xmlEscape(imageUrl(Text.xmlDecode(src))) .. '"/>'
return "\1" .. #imgs .. "\1"
end)
local html = Text.chapterHtml(title, text)
if reviews then
html = html:gsub("<p>(.-)\2(%d+)\2</p>", function(body, paragraph)
body = Text.rtrim(body)
if body == "" then return "" end
return '<p id="moon-legado-paragraph-' .. paragraph .. '">' .. body .. "</p>"
end)
end
return (html:gsub("\1(%d+)\1", function(n) return imgs[tonumber(n)] end))
end
--- reader3 本地 EPUB 资源 → 正文片段;图片按章节 URL 解析并规范化属性,供公共 Assets 落地。
---@param title string
---@param raw string
---@param base string
---@param imageUrl fun(src: string, base: string): string
---@return string|nil
function Mapper.assetHtml(title, raw, base, imageUrl)
local inner = Text.htmlBodyFragment(raw)
:gsub("<script[^>]*>.-</script>", "")
:gsub("<style[^>]*>.-</style>", "")
local function svgToImg(block)
local href = block:match('xlink:href%s*=%s*"([^"]*)"')
or block:match("xlink:href%s*=%s*'([^']*)'")
or block:match('href%s*=%s*"([^"]*)"')
or block:match("href%s*=%s*'([^']*)'")
if not href or href == "" then return "" end
return '<img src="' .. Text.xmlEscape(Text.xmlDecode(href)) .. '"/>'
end
inner = inner:gsub("<svg[^>]*>.-</svg>", svgToImg)
:gsub("<image%s[^>]-/>", svgToImg)
inner = inner:gsub("<img%s+[^>]*>", function(tag)
return (tag:gsub("src%s*=%s*(['\"])(.-)%1", function(_quote, src)
if src == "" then return 'src=""' end
local url = Text.escapeUrl(imageUrl(Text.xmlDecode(src), base))
return 'src="' .. Text.xmlEscape(url) .. '"'
end, 1))
end)
if not inner:find("<img", 1, true) and Text.stripHtml(inner) == "" then return nil end
return "<h1>" .. Text.xmlEscape(title) .. "</h1>\n" .. inner
end
return Mapper
@@ -0,0 +1,129 @@
--[[--
阅读 App 段评映射。range 保存 { 段号, paraData },评论 id 保存同一上下文及原始 id;
分页位置保存 { page, cursor }。这些不透明键随公共段评缓存落盘,不依赖源实例的临时状态。
段落按章节里的 moon-legado-paragraph-N 标记定位,图片或被丢弃的空段不能改变源站段号。
@module koplugin.book.moonsource_legado.reviews
--]]
local JSON = require("json")
local Locate = require("book.review_locate")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_legado")
local Reviews = {}
---@param range string
---@param reply boolean|nil
---@return table|nil, string|nil
function Reviews.context(range, reply)
local ok, value = pcall(JSON.decode, range)
if not ok or type(value) ~= "table" or type(value[1]) ~= "number"
or (value[1] ~= -1 and (value[1] < 1 or value[1] % 1 ~= 0))
or type(value[2]) ~= "string"
or (reply and (type(value[3]) ~= "string" or value[3] == "")) then
return nil, _("阅读段评位置无效")
end
return value
end
---@param data table
---@return table[]|nil, string|nil
function Reviews.hotspots(data)
if type(data) ~= "table" or type(data.counts) ~= "table" or type(data.keys) ~= "table" then
return nil, _("阅读段评响应无效")
end
local out = {}
for key, count in pairs(data.counts) do
local paragraph = tonumber(key)
local value = data.keys[key]
if not paragraph or paragraph % 1 ~= 0 or type(count) ~= "number" or count < 0 or count % 1 ~= 0
or (value ~= nil and type(value) ~= "string") then
return nil, _("阅读段评响应无效")
end
if (paragraph > 0 or paragraph == -1) and count > 0 then
out[#out + 1] = {
range = JSON.encode({ paragraph, value and value ~= "" and value or tostring(paragraph) }),
paragraph = paragraph, text = "", total = count,
}
end
end
table.sort(out, function(a, b) return a.paragraph < b.paragraph end)
return out
end
---@param max_idx integer|string
---@return integer|nil, string|nil, string|nil
function Reviews.pagination(max_idx)
if max_idx == 0 then return 1 end
local ok, value = pcall(JSON.decode, max_idx)
if not ok or type(value) ~= "table" or type(value.page) ~= "number" or value.page < 1
or value.page % 1 ~= 0 or (value.cursor ~= nil and type(value.cursor) ~= "string") then
return nil, nil, _("阅读段评分页位置无效")
end
return value.page + 1, value.cursor
end
---@param data table
---@param context table
---@param page integer
---@return table|nil, string|nil
function Reviews.page(data, context, page)
if type(data) ~= "table" or type(data.items) ~= "table" or type(data.hasMore) ~= "boolean"
or (data.nextCursor ~= nil and type(data.nextCursor) ~= "string")
or (#data.items == 0 and next(data.items) ~= nil) then
return nil, _("阅读段评响应无效")
end
local items = {}
for _idx, row in ipairs(data.items) do
if type(row) ~= "table" or (row.content ~= nil and type(row.content) ~= "string")
or (row.name ~= nil and type(row.name) ~= "string")
or (row.id ~= nil and type(row.id) ~= "string") then
return nil, _("阅读段评响应无效")
end
local images = {}
if type(row.imageUrl) == "string" and row.imageUrl:match("^https?://") then
images[1] = { url = row.imageUrl, width = 0, height = 0 }
end
local has_id = row.id ~= nil and row.id ~= ""
items[#items + 1] = {
id = has_id and JSON.encode({ context[1], context[2], row.id }) or "",
author = row.name or "", content = Text.stripHtml(row.content or ""),
time = type(row.time) == "string" and row.time or "",
likes = tonumber(row.likeCount) or 0,
replies = has_id and (tonumber(row.replyCount) or 0) or 0,
reply_to = row.replyToName, images = images,
}
end
return {
items = items, total = #items == 0 and 0 or nil,
max_idx = JSON.encode({ page = page, cursor = data.nextCursor }),
more = #items > 0 and data.hasMore,
}
end
---@param hotspots table[]
---@param html string
---@return table[]
function Reviews.locate(hotspots, html)
local paras = {}
for tag, body in html:gmatch("(<p%s+[^>]*>)(.-)</p>") do
local paragraph = tag:match('id="moon%-legado%-paragraph%-(%d+)"')
if paragraph then paras[paragraph] = Text.stripHtml(body) end
end
if #hotspots > 0 and next(paras) == nil then
require("utils.log").warn("legado reviews: cached chapter has no paragraph anchors; download it again")
return {}
end
local numbered, ranges = {}, {}
for _idx, hotspot in ipairs(hotspots) do
local paragraph = tostring(hotspot.paragraph)
numbered[#numbered + 1] = { range = paragraph, total = hotspot.total }
ranges[paragraph] = hotspot.range
end
local spots = Locate.locate(paras, numbered, html)
for _idx, spot in ipairs(spots) do spot.range = ranges[spot.range] end
return spots
end
return Reviews
@@ -0,0 +1,189 @@
--[[--
手动扫描局域网里的阅读 App Web 服务。
阅读不广播自己。只扫本机所在的 IPv4 /24,只探已经保存的端口(没配过就是 1122),
端口通了再拉一次 /getBookshelf,回包长得像书架才算。
@module koplugin.book.moonsource_legado.scan
--]]
local Scan = {}
local DEFAULT_PORT = 1122
local PARALLEL = 32
local CONNECT_TIMEOUT = 0.6
local POLL = 0.05
-- 家用网段里阅读服务就一两台。端口全通是网关在假装连上,再打 HTTP 没有意义。
local MAX_OPEN = 8
---@param ip string
---@return string[]
function Scan.hosts(ip)
local a, b, c, d = ip:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
a, b, c, d = tonumber(a), tonumber(b), tonumber(c), tonumber(d)
if not a or a > 255 or b > 255 or c > 255 or d > 255 or a == 0 then return {} end
local prefix = string.format("%d.%d.%d.", a, b, c)
local hosts = {}
for octet = 1, 254 do
if octet ~= d then hosts[#hosts + 1] = prefix .. octet end
end
return hosts
end
--- 本机出口 IPv4。UDP setpeername 只查路由,不发包。
---@return string|nil
function Scan.localIP()
local udp = require("socket").udp()
if not udp then return nil end
local ip
if udp:setpeername("203.0.113.1", "53") then
ip = udp:getsockname()
end
udp:close()
if type(ip) ~= "string" or #Scan.hosts(ip) == 0 then return nil end
return ip
end
--- 已保存的阅读 App 端口;没配过或不是 App 地址就用默认端口。
---@return integer
local function savedPort()
local Client = require("moonsource_legado.client")
local base = Client.mode() == "app" and Client.base()
local port = tonumber(base and base:match("^https?://[^/:]+:(%d+)$"))
return port and port >= 1 and port <= 65535 and port or DEFAULT_PORT
end
--- `{ isSuccess, errorMsg, data: [] | [book, ...] }`。对象塞在 data 里不算书架。
---@param raw string|nil
---@return boolean
function Scan.isShelf(raw)
if type(raw) ~= "string" or raw == "" then return false end
local ok, wire = pcall(require("json").decode, raw)
if not ok or type(wire) ~= "table" or wire.isSuccess ~= true or type(wire.errorMsg) ~= "string" then
return false
end
if type(wire.data) ~= "table" then return false end
if wire.data[1] ~= nil then return type(wire.data[1]) == "table" end
return next(wire.data) == nil
end
---@param current table
local function abort(current)
current.cancelled = true
require("ui/uimanager"):unschedule(current.poll)
for _idx, item in ipairs(current.pending) do item.sock:close() end
for _idx, job in ipairs(current.jobs) do job.cancel() end
end
local function take(current)
local socket = current.socket
while #current.pending < PARALLEL and current.cursor <= #current.hosts do
local host = current.hosts[current.cursor]
current.cursor = current.cursor + 1
local sock = socket.tcp()
if not sock then
current.cursor = #current.hosts + 1
return
end
sock:settimeout(0)
local ok, err = sock:connect(host, current.port)
if ok or err == "already connected" then
sock:close()
current.open[#current.open + 1] = host
elseif err == "timeout" then
current.pending[#current.pending + 1] = {
sock = sock, host = host, deadline = socket.gettime() + CONNECT_TIMEOUT,
}
else
sock:close()
end
end
end
local function reap(current)
if #current.pending == 0 then return end
local socks = {}
for idx, item in ipairs(current.pending) do socks[idx] = item.sock end
local _recv, writable = current.socket.select({}, socks, 0)
if type(writable) ~= "table" then writable = {} end
local ready = {}
for _idx, sock in ipairs(writable) do ready[sock] = true end
local now = current.socket.gettime()
local left = {}
for _idx, item in ipairs(current.pending) do
if ready[item.sock] then
local ok, err = item.sock:connect(item.host, current.port)
item.sock:close()
if ok or err == "already connected" then
current.open[#current.open + 1] = item.host
end
elseif now >= item.deadline then
item.sock:close()
else
left[#left + 1] = item
end
end
current.pending = left
end
local function verify(current)
if #current.open == 0 or #current.open > MAX_OPEN then
current.cb({})
return
end
local Timeout = require("http.timeout")
local Request = require("http.request")
local left = #current.open
local found = {}
for _idx, host in ipairs(current.open) do
local address = "http://" .. host .. ":" .. current.port
current.jobs[#current.jobs + 1] = Request.get(address .. "/getBookshelf?refresh=0", {
accept = "application/json",
timeout = Timeout.net(0.1),
connect_timeout = Timeout.net(0.05),
}, function(raw)
if current.cancelled then return end
if Scan.isShelf(raw) then found[#found + 1] = address end
left = left - 1
if left == 0 then current.cb(found) end
end)
end
end
--- 扫完回调 `cb(addresses)` 或 `cb(nil, "no-ip")`。回调一定在返回之后;取消后不再回调。
---@param cb fun(found: string[]|nil, err: string|nil)
---@return { cancel: fun() }
function Scan.find(cb)
local UIManager = require("ui/uimanager")
local ip = Scan.localIP()
local current = {
cb = cb,
pending = {},
open = {},
jobs = {},
hosts = ip and Scan.hosts(ip) or {},
cursor = 1,
port = savedPort(),
socket = require("socket"),
}
function current.poll()
if current.cancelled then return end
reap(current)
take(current)
if #current.pending > 0 or current.cursor <= #current.hosts then
UIManager:scheduleIn(POLL, current.poll)
else
verify(current)
end
end
if ip then
UIManager:scheduleIn(POLL, current.poll)
else
UIManager:nextTick(function()
if not current.cancelled then cb(nil, "no-ip") end
end)
end
return { cancel = function() abort(current) end }
end
return Scan
@@ -0,0 +1,177 @@
--[[--
阅读(Legado)源设置:Web 服务地址。
在阅读 App「我的 → Web 服务」打开服务,把页面上的地址(如 http://192.168.1.8:1122)填进来;
手机 IP 会变,也可以扫本机所在网段,认端口上的阅读服务。
reader3 服务器版地址带 /reader3 后缀(如 http://host:8080/reader3)、轻阅读带 /api/5 后缀,
并填账号密码(后端类型按后缀判断);
保存时先拉一次书架校验,通过才落盘并重载源。
@module koplugin.book.moonsource_legado.setting
--]]
local _ = require("l10n").get("moonsource_legado")
local T = require("ffi/util").template
local SOURCE_ID = "legado"
local Setting = {}
---@return string, boolean
function Setting.rowStatus()
local on = require("moonsource_legado.client").base() ~= nil
return on and _("已配置") or _("未配置"), on
end
---@param address string
---@param user string
---@param password string
local function save(address, user, password)
local Toast = require("ui.themes.widgets.toast")
local settings = require("utils.settings")
local cfg = settings.getSource(SOURCE_ID)
local previous_user = cfg.username or ""
local next_cfg = { server_address = address, username = user ~= "" and user or nil,
password = password ~= "" and password or nil }
local function commit()
cfg.server_address, cfg.username, cfg.password = next_cfg.server_address, next_cfg.username, next_cfg.password
settings.saveSource(SOURCE_ID, cfg)
end
local Client = require("moonsource_legado.client")
local waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("开源阅读"), text = _("正在连接阅读服务…"), dismissable = false,
}
waiting:show()
Client.shelfAsync(function(rows, err)
waiting:close()
if not rows then
Toast:new{ text = err or _("连接失败"), timeout = 3 }:show()
return
end
-- 手机 IP 会变化,地址不是书籍身份;换账号也只准备同步,不清记录。
if previous_user ~= user then
if not require("source.logout").replaceLibrary(SOURCE_ID, commit) then
Toast:new{ text = _("准备本地同步失败"), timeout = 3 }:show()
return
end
else
if cfg.server_address ~= address then require("source.logout").abort(SOURCE_ID) end
commit()
require("source.registry").reload()
end
Toast:new{ text = T(_("已连接,书架共 %1 本"), #rows), timeout = 2 }:show()
end, next_cfg)
end
local scanning = false
local function scan()
if scanning then return end
local NetworkMgr = require("ui/network/manager")
NetworkMgr:runWhenConnected(function()
if scanning then return end
scanning = true
local waiting, handle, closed
waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("开源阅读"),
text = _("正在扫描局域网…"),
dismissable = false,
on_cancel = function()
-- 弹窗自己先关。这里只停扫描。
if closed then return end
closed = true
scanning = false
if handle then handle.cancel() end
end,
}
waiting:show()
handle = require("moonsource_legado.scan").find(function(found, err)
if closed then return end
closed = true
scanning = false
waiting:close()
local Toast = require("ui.themes.widgets.toast")
if type(found) ~= "table" or #found == 0 then
local text = err == "no-ip" and _("没有局域网地址") or _("没有找到阅读服务")
Toast:new{ text = text, timeout = 3 }:show()
return
end
local cfg = require("utils.settings").getSource(SOURCE_ID)
local user, password = cfg.username or "", cfg.password or ""
if #found == 1 then
save(found[1], user, password)
return
end
local items = {}
for _idx, address in ipairs(found) do
items[#items + 1] = { text = address, value = address }
end
require("ui.themes.widgets.list"):new{
title = _("选择阅读服务"),
items = items,
on_select = function(value) save(value, user, password) end,
}:show()
end)
end)
end
local function edit()
local cfg = require("utils.settings").getSource(SOURCE_ID)
require("ui.themes.widgets.input"):new{
title = _("阅读服务"),
fields = {
{ text = require("moonsource_legado.client").base() or "", hint = "http://192.168.1.8:1122" },
{ text = cfg.username or "", hint = _("账号(reader3 服务器版才需要)") },
{ text = cfg.password or "", hint = _("密码"), text_type = "password" },
},
ok_text = _("保存"),
callback = function(value, user, password)
local Text = require("utils.text")
local address = Text.stripWhitespace(value)
if address == "" then
require("source.logout").abort(SOURCE_ID)
cfg.server_address = nil
require("utils.settings").saveSource(SOURCE_ID, cfg)
require("source.registry").reload()
return
end
require("ui/network/manager"):runWhenConnected(function()
save(address, Text.stripWhitespace(user), password)
end)
end,
}:show()
end
---@param plugin table|nil
---@return table[]
function Setting.rows(plugin)
local rows = {
function(iw)
local status, status_on = Setting.rowStatus()
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true, kind = "nav", icon = "dns", title = _("阅读服务地址"),
status = require("moonsource_legado.client").base() or status, status_on = status_on,
callback = edit,
})
end,
function(iw)
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true, kind = "nav", icon = "wifi_find", title = _("扫描局域网"),
callback = scan,
})
end,
}
if require("moonsource_legado.client").mode() == "app" then
rows[#rows + 1] = require("source.review_setting").row(SOURCE_ID, plugin)
end
if require("moonsource_legado.client").base() ~= nil then
rows[#rows + 1] = require("source.logout").row(SOURCE_ID, _("确定退出开源阅读?"), function()
local settings = require("utils.settings")
local cfg = settings.getSource(SOURCE_ID)
cfg.server_address, cfg.username, cfg.password = nil, nil, nil
settings.saveSource(SOURCE_ID, cfg)
end)
end
return rows
end
return Setting
@@ -0,0 +1,381 @@
--[[--
阅读(Legado / 开源阅读)数据源。
直连阅读 App 的 Web 服务,或 reader3 服务器版(地址可带 /reader3 前缀,再配账号密码,setting.lua 配置)。书架只拉不加(书在阅读 App 里添加),
目录 / 正文按章落盘走公共 source/chapter;进度只到章,开书从书架行的 durChapterIndex 拉,
关书经 /saveBookProgress 上报。笔记和统计没有接口。
@module koplugin.book.moonsource_legado.source
--]]
local Client = require("moonsource_legado.client")
local Mapper = require("moonsource_legado.mapper")
local Text = require("utils.text")
local Request = require("http.request")
local Assets = require("source.assets")
local Paths = require("utils.paths")
local Shelf = require("source.shelf")
local SourceBase = require("source.base")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_legado")
local Legado = {}
---@return BookSourceMeta
function Legado.meta()
return require("moonsource_legado.loadmeta")()
end
---@class LegadoSource : SourceBase
local Source = setmetatable({}, { __index = SourceBase })
Source.__index = Source
---@return LegadoSource
function Legado.new()
local meta = Legado.meta()
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source)
end
---@return boolean
function Source:configured()
return Client.base() ~= nil
end
---@param rows table[]
---@param stable_id string
---@return table|nil
local function findRow(rows, stable_id)
for _idx, row in ipairs(rows) do
if row.bookUrl == stable_id then return row end
end
return nil
end
--- 书架远端:Shelf.syncAsync 要的三个冒号方法。书只能在阅读 App 里加,本地没有「加入」入口。
local Remote = {}
--- 书架 + 分组:分组取不到(旧版 App / 轻阅读)不影响同步,分类退回书源标签。
function Remote:shelfSyncAsync(cb)
local cancelled, job = false, nil
job = Client.shelfAsync(function(rows, err)
if cancelled then return end
if not rows then cb(nil, err); return end
job = Client.groupsAsync(function(groups)
if cancelled then return end
rows.groups = groups
cb(rows)
end)
end)
return { cancel = function()
cancelled = true
job.cancel()
end }
end
function Remote:addToShelfAsync(_stable_id, cb)
return SourceBase.defer(cb, nil, _("请在阅读 App 里添加书籍"))
end
--- 远端已经没有这本书就算删除完成。
function Remote:removeFromShelfAsync(stable_id, cb)
local cancelled, job = false, nil
job = Client.shelfAsync(function(rows, err)
if cancelled then return end
if not rows then cb(nil, err); return end
local row = findRow(rows, stable_id)
if not row then cb(true); return end
job = Client.deleteBookAsync(row, cb)
end)
return { cancel = function()
cancelled = true
job.cancel()
end }
end
function Source:syncBooksAsync(opts, cb)
if not self:configured() then return SourceBase.skipped(cb, "legado not configured") end
opts = opts or {}
local sync_opts = {}
for k, v in pairs(opts) do sync_opts[k] = v end
sync_opts.inserted_at_from_row = true
return Shelf.syncAsync(self.id, Remote, function(rows) return Mapper.shelfList(Client.coverUrl, rows) end, sync_opts, cb)
end
--- 取书架行再交给 fn(row, toc, done);没配置 / 不在书架上 / 目录空都走 cb 报错。
--- fn 要再发请求就返回它的句柄,取消会传过去;done 是取消后不再投递的 cb。
---@param identity BookIdentity
---@param cb function
---@param fn fun(row: table, toc: BookChapter[], done: function): { cancel: fun() }|nil
---@return { cancel: fun() }
function Source:withRow(identity, cb, fn)
if not self:configured() then return SourceBase.defer(cb, nil, _("未配置阅读服务器地址")) end
local cancelled, job = false, nil
local function done(...)
if not cancelled then cb(...) end
end
job = Client.shelfAsync(function(rows, err)
if cancelled then return end
if not rows then cb(nil, err); return end
local row = findRow(rows, identity.stable_id)
if not row then cb(nil, _("这本书不在阅读书架上")); return end
job = self:loadTocAsync(identity, function(toc, reason)
if cancelled then return end
if not toc then cb(nil, reason); return end
job = fn(row, toc, done) or job
end)
end)
return { cancel = function()
cancelled = true
job.cancel()
end }
end
function Source:getProgressAsync(identity, cb)
return self:withRow(identity, cb, function(row, toc)
local read = Mapper.readPos(row)
if not read then cb(nil, nil, { empty = true }); return end
local idx = math.min(read.index + 1, #toc)
cb({
chapter_idx = idx,
chapter_title = read.title or toc[idx].title,
fraction = (idx - 1) / #toc,
extra = { chapter_uid = toc[idx].uid, chapter_idx = idx },
})
end)
end
function Source:putProgressAsync(identity, pos, cb)
return self:withRow(identity, cb, function(row, toc, done)
local idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx)
local chapter = idx and toc[idx]
if not chapter then cb(nil, _("缺少阅读章节位置")); return end
local read = Mapper.readPos(row)
local same = read and read.index == idx - 1
return Client.saveProgressAsync(row, {
index = idx - 1,
title = chapter.title,
offset = same and read.offset or 0,
}, done)
end)
end
--- 书库里已有的元数据。
function Source:getDetailAsync(identity, cb)
return SourceBase.defer(cb, identity.book or require("book.books_db").get(self.id, identity.stable_id))
end
--- 强制拉目录并写回;失败由调用方继续用旧缓存。轻阅读按书源取,先从书架行查 origin。
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
---@return { cancel: fun() }
local function fetchTocAsync(self, identity, cb)
local cancelled, job = false, nil
local function fetch(origin)
job = Client.chaptersAsync(identity.stable_id, origin, function(rows, err)
if cancelled then return end
if not rows then cb(nil, err); return end
local toc = Mapper.toc(rows, origin)
if #toc == 0 then cb(nil, _("阅读目录为空")); return end
if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end
cb(toc)
end)
end
if Client.mode() ~= "qread" then
fetch(nil)
else
job = Client.shelfAsync(function(rows, err)
if cancelled then return end
local row = rows and findRow(rows, identity.stable_id)
if not row then cb(nil, err or _("这本书不在阅读书架上")); return end
fetch(row.origin)
end)
end
return { cancel = function()
cancelled = true
job.cancel()
end }
end
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
---@param force boolean|nil 真=跳过缓存强制拉
---@return { cancel: fun() }
function Source:loadTocAsync(identity, cb, force)
if not force then
local cached = Toc.read(self.id, identity.stable_id)
if cached and #cached > 0 then
return SourceBase.defer(cb, cached)
end
end
return fetchTocAsync(self, identity, cb)
end
Source.refreshTocAsync = fetchTocAsync
---@return ChapterFetchContent
local function contentFetcher(reviews)
return function(identity, chapter, done)
local cancelled = false
---@type { job: CancelHandle|nil }|nil
local active
---@param start fun(cb: function): CancelHandle|nil
---@param finish function
local function run(start, finish)
local stage = {}
active = stage
stage.job = start(function(...)
if cancelled or active ~= stage then return end
active = nil
finish(...)
end)
end
local function fetchAsset(path)
local url = Text.escapeUrl(Client.imageUrl(path))
run(function(cb)
return Request.get(url, { timeout = 20 }, cb)
end, function(raw, err)
if not raw or raw == "" then done(nil, err or _("阅读章节内容为空")); return end
local html = Mapper.assetHtml(chapter.title, raw, url, Client.imageUrl)
if not html then done(nil, _("阅读章节内容为空")); return end
local image_err
run(function(cb)
return Assets.localizeAsync(html, Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/images",
function(image_url, on_done)
return Request.get(image_url, { timeout = 45 }, function(data, reason)
if reason then image_err = tostring(reason) end
on_done(data, reason)
end)
end, cb)
end, function(localized)
if Text.hasRemoteImageSrc(localized) then
done(nil, image_err or _("阅读插图下载失败,请重试"))
return
end
done({ title = chapter.title, html = localized })
end)
end)
end
run(function(cb)
return Client.contentAsync(identity.stable_id, tonumber(chapter.uid), chapter.origin, cb)
end, function(text, err)
if not text then done(nil, err); return end
-- 只有 reader3 的明确资源前缀才是 EPUB 路径,不能按 .html 后缀猜正文类型。
if Client.mode() == "reader3" and text:find("^/book%-assets/") then
fetchAsset(text)
return
end
local html = Mapper.chapterHtml(chapter.title, text, Client.imageUrl, Client.mode() == "app")
-- 只有 <h1> 没有段落 = 服务器给的是空白正文,不能当成功落盘缓存。
if not html:find("<p", 1, true) then done(nil, _("阅读章节内容为空")); return end
done({ title = chapter.title,
html = reviews and require("book.review_locate").prepareChapterEnd(html) or html })
end)
return { cancel = function()
cancelled = true
local job = active and active.job
active = nil
if job then job.cancel() end
end }
end
end
function Source:openBookAsync(identity, opts, cb)
local Chapter = require("source.chapter")
local reviews = self:paragraphReviewsEnabled()
local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi
return open(self, identity, identity.book, opts, {
loadToc = function(ref, done) return self:loadTocAsync(ref, done) end,
fetchContent = contentFetcher(reviews),
reuse = reviews and require("book.review_locate").reuseChapterEnd or nil,
}, cb)
end
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
local reviews = self:paragraphReviewsEnabled()
return require("source.chapter").prefetchAsync(identity, identity.book, toc, from_idx, count, {
fetchContent = contentFetcher(reviews),
reuse = reviews and require("book.review_locate").reuseChapterEnd or nil,
}, cb)
end
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
return require("source.chapter").cacheAllAsync(self, identity, contentFetcher(self:paragraphReviewsEnabled()),
on_progress, cb, 0, range)
end
function Source:paragraphReviewsEnabled()
return Client.mode() == "app" and require("source.review_setting").enabled(self.id)
end
local function hotspotsAsync(self, identity, cb)
return require("book.review_cache").hotspotsAsync(identity, function(done)
return require("source.with_chapter_uid").run(self, identity, _("缺少阅读章节位置"), function(uid, finish)
return Client.reviewSummaryAsync(identity.stable_id, tonumber(uid), function(data, err)
if data == nil then finish(nil, err or _("阅读段评响应无效")); return end
finish(require("moonsource_legado.reviews").hotspots(data))
end)
end, done)
end, cb)
end
function Source:paragraphHotspotsAsync(identity, cb)
return hotspotsAsync(self, identity, function(list, err)
if not list then cb(nil, err); return end
local out = {}
for _idx, spot in ipairs(list) do
if spot.paragraph > 0 then out[#out + 1] = spot end
end
cb(out)
end)
end
function Source:chapterReviewHotspotsAsync(identity, cb)
return hotspotsAsync(self, identity, function(list, err)
if not list then cb(nil, err); return end
local out = {}
for _idx, spot in ipairs(list) do
if spot.paragraph == -1 then
out[#out + 1] = { range = spot.range, text = _("本章讨论"), total = spot.total,
badge = tostring(spot.total), heading = _("章节评论"),
anchor = require("book.review_locate").CHAPTER_ANCHOR }
end
end
cb(out)
end)
end
function Source:locateHotspots(hotspots, html)
return require("moonsource_legado.reviews").locate(hotspots, html)
end
local function reviewPageAsync(self, identity, range, max_idx, reply, cb)
local Reviews = require("moonsource_legado.reviews")
local context, err = Reviews.context(range, reply)
if not context then return SourceBase.defer(cb, nil, err) end
local page, cursor, reason = Reviews.pagination(max_idx)
if not page then return SourceBase.defer(cb, nil, reason) end
return require("book.review_cache").pageAsync(identity, (reply and "reply:" or "") .. range, max_idx, function(done)
return require("source.with_chapter_uid").run(self, identity, _("缺少阅读章节位置"), function(uid, finish)
local function onPage(data, error)
if data == nil then finish(nil, error or _("阅读段评响应无效")); return end
finish(Reviews.page(data, context, page))
end
if reply then
return Client.reviewRepliesAsync(identity.stable_id, tonumber(uid), context[1], context[2],
context[3], page, onPage)
end
return Client.reviewDetailAsync(identity.stable_id, tonumber(uid), context[1], context[2],
page, cursor, onPage)
end, done)
end, cb)
end
function Source:paragraphReviewPageAsync(identity, range, max_idx, cb)
return reviewPageAsync(self, identity, range, max_idx, false, cb)
end
function Source:paragraphReviewRepliesAsync(identity, review_id, max_idx, cb)
return reviewPageAsync(self, identity, review_id, max_idx, true, cb)
end
return Legado
@@ -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