✨ (reader): 整本阅读并按 CFI 回写进度

EPUB 和 TXT 下载后整本打开。阅读位置换算成官网 CFI 才上传。
This commit is contained in:
Garfield committed 2026-11-27 00:51:41 +08:00
1 parent 285d4cc487
commit e108b75c57
2 files changed
+798

No files matched your search

@@ -0,0 +1,487 @@
--[[--
KOReader xpointer → LinguoLand 阅读器使用的 EPUB CFI。
官网(foliate-js)只有拿到 `epubcfi(...)` 才保存进度。这里按它的
`getCFI` 生成:spine 固定 `/6/((序号+1)*2)`,章内下标按它的子节点槽位
(元素间的空隙也占一格),不是把 xpointer 字符串换个写法。
对不上就返回 nil。调用方不得改用假 CFI。
@module moonsource_linguoland.cfi
--]]
local Cfi = {}
local function utf8_char(cp)
if not cp or cp < 0 or cp > 0x10FFFF then return "\239\191\189" end
if cp < 0x80 then return string.char(cp) end
if cp < 0x800 then
return string.char(0xC0 + math.floor(cp / 64), 0x80 + cp % 64)
end
if cp < 0x10000 then
return string.char(0xE0 + math.floor(cp / 4096), 0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
end
return string.char(
0xF0 + math.floor(cp / 262144),
0x80 + math.floor(cp / 4096) % 64,
0x80 + math.floor(cp / 64) % 64,
0x80 + cp % 64)
end
local function decode_entities(s)
local out, i = {}, 1
while i <= #s do
local amp = s:find("&", i, true)
if not amp then
out[#out + 1] = s:sub(i)
break
end
out[#out + 1] = s:sub(i, amp - 1)
local semi = s:find(";", amp + 1, true)
local body = semi and semi - amp <= 12 and s:sub(amp + 1, semi - 1) or nil
local hex = body and (body:match("^#x(%x+)$") or body:match("^#X(%x+)$"))
local dec = body and body:match("^#(%d+)$")
local ch
if hex then ch = utf8_char(tonumber(hex, 16))
elseif dec then ch = utf8_char(tonumber(dec))
elseif body == "amp" then ch = "&"
elseif body == "lt" then ch = "<"
elseif body == "gt" then ch = ">"
elseif body == "quot" then ch = '"'
elseif body == "apos" then ch = "'"
end
if ch then
out[#out + 1] = ch
i = semi + 1
else
out[#out + 1] = "&"
i = amp + 1
end
end
return table.concat(out)
end
local function char_len(s)
local n, i = 0, 1
while i <= #s do
local b = s:byte(i)
local w = 1
if b >= 0xF0 then w = 4
elseif b >= 0xE0 then w = 3
elseif b >= 0xC0 then w = 2
end
i = i + w
n = n + 1
end
return n
end
local function local_name(name)
return (name:match(":([^:]+)$") or name):lower()
end
local function parse_attrs(raw)
local attrs, i = {}, 1
while i <= #raw do
local start, finish, name = raw:find("([%w_.:%-]+)%s*=%s*", i)
if not start then break end
i = finish + 1
local quote = raw:sub(i, i)
if quote ~= '"' and quote ~= "'" then break end
local close = raw:find(quote, i + 1, true)
if not close then break end
local key = local_name(name)
attrs[key] = decode_entities(raw:sub(i + 1, close - 1))
i = close + 1
end
return attrs
end
--- 只接受良构 XML。坏了返回 nil,不按 HTML 猜测补标签。
---@param s string
---@return table|nil
local function parse_xml(s)
if s:sub(1, 3) == "\239\187\191" then s = s:sub(4) end
local root = { kind = "doc", children = {} }
local stack = { root }
local i, n = 1, #s
local function add_text(text)
if text == "" then return end
local parent = stack[#stack]
parent.children[#parent.children + 1] = { kind = "text", text = text, parent = parent }
end
while i <= n do
if s:sub(i, i) ~= "<" then
local next_tag = s:find("<", i, true) or (n + 1)
add_text(decode_entities(s:sub(i, next_tag - 1)))
i = next_tag
elseif s:sub(i, i + 3) == "<!--" then
local close = s:find("-->", i + 4, true)
if not close then return nil end
i = close + 3
elseif s:sub(i, i + 8) == "<![CDATA[" then
local close = s:find("]]>", i + 9, true)
if not close then return nil end
add_text(s:sub(i + 9, close - 1))
i = close + 3
elseif s:sub(i, i + 1) == "<?" then
local close = s:find("?>", i + 2, true)
if not close then return nil end
i = close + 2
elseif s:sub(i, i + 1) == "<!" then
local j, depth = i + 2, 0
while j <= n do
local c = s:sub(j, j)
if c == "[" then depth = depth + 1
elseif c == "]" then depth = math.max(0, depth - 1)
elseif c == ">" and depth == 0 then break end
j = j + 1
end
if j > n then return nil end
i = j + 1
else
local closing = s:sub(i + 1, i + 1) == "/"
local name_at = closing and (i + 2) or (i + 1)
local name = s:match("^([%w_.:%-]+)", name_at)
if not name then return nil end
local j = name_at + #name
local quote, slash = nil, false
while j <= n do
local c = s:sub(j, j)
if quote then
if c == quote then quote = nil end
elseif c == '"' or c == "'" then
quote = c
slash = false
elseif c == "/" then
slash = true
elseif c == ">" then
break
elseif not c:match("%s") then
slash = false
end
j = j + 1
end
if j > n or s:sub(j, j) ~= ">" then return nil end
local tag = local_name(name)
if closing then
local top = stack[#stack]
if not top or top.tag ~= tag then return nil end
stack[#stack] = nil
else
local raw = s:sub(name_at + #name, slash and (j - 2) or (j - 1))
local parent = stack[#stack]
local node = {
kind = "el",
tag = tag,
attrs = parse_attrs(raw),
children = {},
parent = parent,
}
if node.attrs.id and node.attrs.id ~= "" then node.id = node.attrs.id end
parent.children[#parent.children + 1] = node
if not slash then stack[#stack + 1] = node end
end
i = j + 1
end
end
if #stack ~= 1 then return nil end
return root
end
local function find_el(node, tag)
if node.kind == "el" then
if node.tag == tag then return node end
for _, child in ipairs(node.children) do
if child.kind == "el" then
local found = find_el(child, tag)
if found then return found end
end
end
elseif node.kind == "doc" then
for _, child in ipairs(node.children) do
if child.kind == "el" then
local found = find_el(child, tag)
if found then return found end
end
end
end
end
--- foliate 的子节点槽:文本和元素都算,相邻元素之间补一格。
---@param parent table
---@return table
local function slots(parent)
local list = {}
for _, child in ipairs(parent.children) do
if child.kind == "text" or child.kind == "el" then
local prev = list[#list]
if not prev then
list[#list + 1] = child
elseif child.kind == "text" then
if prev.kind == "texts" then
prev.nodes[#prev.nodes + 1] = child
elseif prev.kind == "text" then
list[#list] = { kind = "texts", nodes = { prev, child } }
else
list[#list + 1] = child
end
elseif prev.kind == "el" then
list[#list + 1] = "null"
list[#list + 1] = child
else
list[#list + 1] = child
end
end
end
if list[1] and list[1].kind == "el" then
table.insert(list, 1, "first")
end
local last = list[#list]
if last and last.kind == "el" then
list[#list + 1] = "last"
end
table.insert(list, 1, "before")
list[#list + 1] = "after"
return list
end
local function slot_index(parent, node, offset)
local list = slots(parent)
for i, item in ipairs(list) do
local hit = item == node
if not hit and item.kind == "texts" then
local acc = 0
for _, part in ipairs(item.nodes) do
if part == node then
hit = true
offset = acc + (offset or 0)
break
end
acc = acc + char_len(part.text)
end
end
if hit then return i - 1, offset end
end
end
local function escape_id(id)
return (id:gsub("[%[%]%^%(%)%,%;%=]", "^%0"))
end
local function serialize(steps)
local parts = {}
for i, step in ipairs(steps) do
local piece = "/" .. step.index
if step.id then piece = piece .. "[" .. escape_id(step.id) .. "]" end
-- 偏移 0 也要写上。Lua 里 0 为假,不能拿它当有没有偏移。
if i == #steps and step.index % 2 == 1 and step.offset ~= nil then
piece = piece .. ":" .. step.offset
end
parts[#parts + 1] = piece
end
return table.concat(parts)
end
--- xpointer 的 `DocFragment[D]` 是 1 起的 spine;元素下标只数同名元素。
---@param xp string
---@return table|nil
local function parse_xpointer(xp)
if type(xp) ~= "string" or not xp:find("DocFragment", 1, true) then return nil end
local numbered = xp:match("DocFragment%[(%d+)%]")
local spine = numbered and (tonumber(numbered) - 1) or 0
if spine < 0 then return nil end
local rest = xp:match("DocFragment%[[^%]]+%](.*)") or xp:match("DocFragment(.*)")
rest = rest and rest:match("^/body(.*)")
if not rest then return nil end
local steps, text_index, offset = {}, nil, nil
for seg in rest:gmatch("([^/]+)") do
if seg ~= "" then
local text_n, text_off = seg:match("^text%(%)%[(%d+)%]%.(%d+)$")
if not text_n then
text_off = seg:match("^text%(%)%.(%d+)$")
if text_off then text_n = "1" end
end
if not text_n then
text_n = seg:match("^text%(%)%[(%d+)%]$")
if text_n then text_off = "0" end
end
if not text_n and seg == "text()" then
text_n, text_off = "1", "0"
end
if text_n then
text_index = tonumber(text_n)
offset = tonumber(text_off)
else
local name, index = seg:match("^([%w_.:%-]+)%[(%d+)%]$")
if not name then
name = seg:match("^([%w_.:%-]+)$")
index = "1"
end
if not name or text_index then return nil end
steps[#steps + 1] = { tag = local_name(name), index = tonumber(index) }
end
end
end
if not text_index or text_index < 1 or not offset or offset < 0 then return nil end
return { spine = spine, steps = steps, text_index = text_index, offset = offset }
end
local function child_el(parent, tag, index)
local seen = 0
for _, child in ipairs(parent.children) do
if child.kind == "el" and child.tag == tag then
seen = seen + 1
if seen == index then return child end
end
end
end
local function child_text(parent, index)
local seen = 0
for _, child in ipairs(parent.children) do
if child.kind == "text" then
seen = seen + 1
if seen == index then return child end
end
end
end
---@param html string
---@param loc table
---@return string|nil
local function cfi_from_html(html, loc)
local tree = parse_xml(html)
local body = tree and find_el(tree, "body")
if not body then return nil end
local node = body
for _, step in ipairs(loc.steps) do
node = child_el(node, step.tag, step.index)
if not node then return nil end
end
local text = child_text(node, loc.text_index)
if not text or loc.offset > char_len(text.text) then return nil end
local steps, current, off = {}, text, loc.offset
while true do
local parent = current.parent
if not parent or parent.kind == "doc" then return nil end
local index, used = slot_index(parent, current, off)
if not index then return nil end
table.insert(steps, 1, {
index = index,
id = current.kind == "el" and current.id or nil,
offset = used,
})
if parent.parent and parent.parent.kind == "doc" then break end
current = parent
off = nil
end
local tail = steps[#steps]
if not tail or tail.index % 2 ~= 1 then return nil end
return string.format("epubcfi(/6/%d!%s)", (loc.spine + 1) * 2, serialize(steps))
end
---@param html string
---@param xpointer string
---@return string|nil
function Cfi.fromHtml(html, xpointer)
local loc = parse_xpointer(xpointer)
if not loc or type(html) ~= "string" then return nil end
return cfi_from_html(html, loc)
end
local function url_decode(s)
return (s:gsub("%%(%x%x)", function(hex)
return string.char(tonumber(hex, 16))
end))
end
local function join_path(dir, href)
href = url_decode(href:match("^[^#]+") or href)
if href:find("^%a[%w+.-]*:") then return nil end
local path = href:sub(1, 1) == "/" and href:sub(2) or (dir == "" and href or (dir .. "/" .. href))
local parts = {}
for seg in path:gmatch("[^/]+") do
if seg == ".." then
parts[#parts] = nil
elseif seg ~= "." and seg ~= "" then
parts[#parts + 1] = seg
end
end
return table.concat(parts, "/")
end
local function each_el(node, fn)
if node.kind ~= "el" and node.kind ~= "doc" then return end
if node.kind == "el" then fn(node) end
for _, child in ipairs(node.children) do
if child.kind == "el" then each_el(child, fn) end
end
end
---@param read fun(name: string): string|nil
---@param xpointer string
---@return string|nil
function Cfi.fromArchive(read, xpointer)
local loc = parse_xpointer(xpointer)
if not loc then return nil end
local container = parse_xml(read("META-INF/container.xml") or "")
local opf_path
if container then
each_el(container, function(node)
if not opf_path and node.tag == "rootfile" and node.attrs["full-path"] then
opf_path = node.attrs["full-path"]
end
end)
end
if not opf_path then return nil end
local opf = parse_xml(read(opf_path) or "")
if not opf then return nil end
local manifest, spine = {}, nil
each_el(opf, function(node)
if node.tag == "item" and node.attrs.id and node.attrs.href and not manifest[node.attrs.id] then
manifest[node.attrs.id] = node.attrs.href
elseif not spine and node.tag == "spine" then
spine = node
end
end)
if not spine then return nil end
local refs = {}
for _, child in ipairs(spine.children) do
if child.kind == "el" and child.tag == "itemref" and child.attrs.idref then
refs[#refs + 1] = child.attrs.idref
end
end
local href = manifest[refs[loc.spine + 1]]
if not href then return nil end
local dir = opf_path:match("^(.*)/") or ""
local full = join_path(dir, href)
if not full then return nil end
local html = read(full)
if not html then return nil end
return cfi_from_html(html, loc)
end
---@param path string
---@param xpointer string
---@return string|nil
function Cfi.fromFile(path, xpointer)
local reader = require("ffi/archiver").Reader:new()
if not reader:open(path) then return nil end
local names = {}
for entry in reader:iterate() do
if entry.mode == "file" and type(entry.path) == "string" then
names[entry.path:gsub("^%./", ""):gsub("^/", "")] = entry.path
end
end
local function read(name)
local stored = names[name]
if not stored then return nil end
return reader:extractToMemory(stored)
end
local cfi = Cfi.fromArchive(read, xpointer)
reader:close()
return cfi
end
return Cfi
@@ -0,0 +1,311 @@
--[[--
LinguoLand 书源核心。
LinguoLand 的书是整本 EPUB 或 TXT,地址在 meta.source.storage_ref。
书架列表不带这份元数据,开书时从书库行补上,下载到工作目录再交给阅读器。
登录:邮箱密码、邮箱验证码、手机短信,或浏览器 localStorage 里的 JWT。
书架:书城书可加入、可删除,经公共书架同步。自己导入的 EPUB 没有 catalog,不进这套。
进度:拉取只取全书比例。上传只在本地 xpointer 能换算成官网 EPUB CFI 时发生。
@module moonsource_linguoland.source
--]]
local Browse = require("source.browse")
local Cfi = require("moonsource_linguoland.cfi")
local Client = require("moonsource_linguoland.client")
local Mapper = require("moonsource_linguoland.mapper")
local SourceBase = require("source.base")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_linguoland")
local Linguoland = {}
---@return BookSourceMeta
function Linguoland.meta()
return require("moonsource_linguoland.loadmeta")()
end
---@class LinguolandSource : SourceBase
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
Source.__index = Source
---@return LinguolandSource
function Linguoland.new()
local meta = Linguoland.meta()
return setmetatable({
id = meta.id,
name = meta.name,
type = meta.type,
}, Source)
end
--- 未登录仍可搜索和读书城。书架和进度需要登录。
---@return boolean
function Source:configured()
return Client.isLoggedIn()
end
function Source:syncBooksAsync(opts, cb)
if not self:configured() then return SourceBase.skipped(cb, "linguoland not logged in") end
return require("source.shelf").syncAsync(self.id, Client, nil, opts, cb)
end
---@param keyword string
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
function Source:searchAsync(keyword, cb)
local cancelled, job = false, nil
job = Client.searchAsync(keyword, function(books, err)
if cancelled then return end
if not books then cb(nil, err or _("请求失败")); return end
cb({ data = books })
end)
return { cancel = function()
cancelled = true
if job and job.cancel then job:cancel() end
end }
end
--- 书城浏览:支持按合集分类筛选
---@param opts { node?: string, limit?: integer }|nil
---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil)
function Source:browseAsync(opts, cb)
local collectionId = opts and opts.node or ""
local cancelled, job, pending = false, nil, true
local function fetchBooks(done)
if collectionId == "" then
job = Client.getCatalogAsync(function(books, err)
if cancelled then return end
if not books then done(nil, err); return end
done(books)
end)
else
job = Client.getCollectionBooksAsync(tonumber(collectionId), function(books, err)
if cancelled then return end
if not books then done(nil, err); return end
done(books)
end)
end
end
local function handleResult(books, err)
pending = false
if cancelled then return end
if err then cb(nil, err); return end
if not books then cb(nil, _("请求失败")); return end
cb({ data = books })
end
if collectionId == "" then
local initial = Client.getCollectionsAsync(function(collections, err)
pending = false
if cancelled then return end
if not collections then cb(nil, err); return end
local groups = { Browse.group(Mapper.collectionsToGroups(collections), collectionId or "") }
job = Browse.pages(function(page, done)
fetchBooks(function(books, fetchErr)
done(books, fetchErr, false)
end)
end, opts and opts.limit or 60, groups, handleResult)
end)
if pending then job = initial end
else
job = Browse.pages(function(page, done)
fetchBooks(function(books, fetchErr)
done(books, fetchErr, false)
end)
end, opts and opts.limit or 60, {}, handleResult)
end
return { cancel = function()
cancelled = true
if job and job.cancel then job:cancel() end
end }
end
function Source:getDetailAsync(identity, cb)
local row = identity.book or require("book.books_db").get(self.id, identity.stable_id)
if row then cb(row); return end
cb(nil, _("暂无书籍详情"))
end
--- 书架列表行没有 meta。有地址就用手里的,没有再读库。
---@param identity BookIdentity
---@return string url
---@return table|nil book
local function fileOf(self, identity)
local function pick(row)
if type(row and row._epub_url) == "string" and row._epub_url ~= "" then return row._epub_url end
local source = row and row.meta and row.meta.source
if type(source) == "table" and type(source.storage_ref) == "string" and source.storage_ref ~= "" then
return source.storage_ref
end
end
local book = identity.book
local url = pick(book)
if url then return url, book end
local row = require("book.books_db").get(self.id, identity.stable_id)
url = pick(row)
if url and book and row and row.meta then book.meta = row.meta end
return url or "", row or book
end
---@param url string
---@param format string|nil
---@return string
local function fileExt(url, format)
local path = url:match("^[^?#]+") or url
local ext = path:match("%.([%a%d]+)$")
if ext then
ext = ext:lower()
if ext == "epub" or ext == "txt" or ext == "pdf" or ext == "fb2" or ext == "html" then return ext end
end
if type(format) == "string" and format ~= "" then return format:lower() end
return "epub"
end
---@param identity BookIdentity
---@return integer|nil
local function shelfEntryId(identity)
local book = identity.book
local source = book and book.meta and book.meta.source
return source and tonumber(source.shelf_entry_id)
end
function Source:openBookAsync(identity, _opts, cb)
local url, book = fileOf(self, identity)
local lfs = require("libs/libkoreader-lfs")
local saved = book and book.path
if type(saved) == "string" and saved ~= "" and lfs.attributes(saved, "mode") == "file" then
return SourceBase.defer(cb, saved)
end
if not url:find("^https?://") then
return SourceBase.defer(cb, nil, _("书籍文件地址无效"))
end
if not require("ui/network/manager"):isConnected() then
return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi"))
end
local Paths = require("utils.paths")
local format = book and book.meta and book.meta.source and book.meta.source.format
Paths.ensureBookWork(identity.stable_id, self.id)
local dest = Paths.bookWorkDir(identity.stable_id, self.id) .. "/book." .. fileExt(url, format)
if lfs.attributes(dest, "mode") == "file" then
local ok, err = require("book.store").touch(dest, identity)
return SourceBase.defer(cb, ok and dest or nil, err)
end
local cancelled, dialog, job = false, nil, nil
require("ui/uimanager"):nextTick(function()
if cancelled then return end
dialog = require("ui.themes.widgets.progress_dialog"):new{
title = book and book.title or identity.stable_id,
dismissable = false,
}
dialog:show()
dialog:set(_("正在下载…"))
job = require("http.request").download({
url = url,
timeout = require("http.timeout").net(6),
on_progress = function(bytes, total)
if dialog and total and total > 0 then dialog:bytes(bytes, total) end
end,
}, dest, function(ok, err)
if dialog then dialog:close(); dialog = nil end
if cancelled then return end
if not ok then cb(nil, err or _("下载失败")); return end
local registered, rerr = require("book.store").touch(dest, identity)
cb(registered and dest or nil, rerr)
end)
end)
return { cancel = function()
cancelled = true
if job and job.cancel then job:cancel() end
if dialog then dialog:close() end
end }
end
--- 官网进度是全书比例。不带章内比、不把 EPUB CFI 放进 locator:
--- CFI 和 KOReader 的 xpointer 对不上,放进去每次开书都是假冲突。
---@param identity BookIdentity
---@param progress { percent: number }
---@return ProgressPosition
local function positionFromPercent(source_id, identity, progress)
local fraction = progress.percent or 0
local pos = { fraction = fraction }
local toc = Toc.read(source_id, identity.stable_id)
if toc and #toc > 0 then
local idx = math.floor(fraction * #toc) + 1
if idx < 1 then idx = 1 end
if idx > #toc then idx = #toc end
pos.chapter_idx = idx
pos.chapter_title = toc[idx] and toc[idx].title or nil
end
return pos
end
function Source:getProgressAsync(identity, cb)
if not self:configured() then
return SourceBase.defer(cb, nil, nil, { empty = true })
end
local entry_id = shelfEntryId(identity)
if not entry_id then
return SourceBase.defer(cb, nil, nil, { empty = true })
end
local cancelled, job = false, nil
job = Client.getProgressAsync(entry_id, function(progress, err)
if cancelled then return end
if err then cb(nil, err); return end
if not progress then cb(nil, nil, { empty = true }); return end
cb(positionFromPercent(self.id, identity, progress))
end)
return { cancel = function()
cancelled = true
if job and job.cancel then job:cancel() end
end }
end
--- 书架条目和本地文件。列表行没有 meta 时回书库补。
---@param identity BookIdentity
---@return integer|nil, string|nil
local function progressTarget(self, identity)
local book = identity.book
local source = book and book.meta and book.meta.source
local entry = source and tonumber(source.shelf_entry_id)
local path = book and book.path
if entry and type(path) == "string" and path ~= "" then return entry, path end
local row = require("book.books_db").get(self.id, identity.stable_id)
if row then
if not entry then
local stored = row.meta and row.meta.source
entry = stored and tonumber(stored.shelf_entry_id)
end
if type(path) ~= "string" or path == "" then path = row.path end
end
if type(path) ~= "string" or path == "" then path = nil end
return entry, path
end
function Source:putProgressAsync(identity, pos, cb)
local entry, path = progressTarget(self, identity)
if not entry then
return SourceBase.defer(cb, nil, _("缺少书架条目 ID"), { permanent = true })
end
local locator = pos and pos.locator
if type(locator) ~= "string" or not locator:find("DocFragment", 1, true) then
return SourceBase.defer(cb, nil, _("没有可换算的阅读位置"), { permanent = true })
end
local lfs = require("libs/libkoreader-lfs")
if not path or lfs.attributes(path, "mode") ~= "file" then
return SourceBase.defer(cb, nil, _("书籍文件还没下载"))
end
if not path:lower():match("%.epub$") then
return SourceBase.defer(cb, nil, _("这个格式没有 CFI"), { permanent = true })
end
local cfi = Cfi.fromFile(path, locator)
if type(cfi) ~= "string" then
return SourceBase.defer(cb, nil, _("位置换算失败"), { permanent = true })
end
return Client.putProgressAsync(entry, cfi, pos.fraction, cb)
end
return Linguoland