488 lines
16 KiB
Lua
488 lines
16 KiB
Lua
--[[--
|
|
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
|