✨ (kanunu): 接入努努书坊,频道与分类浏览、按章阅读、整本缓存
Release / release (push) Successful in 14s

This commit is contained in:
garfield committed 2026-12-02 09:17:14 +08:00
commit f50b9e7711
23 files changed
+2346

No files matched your search

@@ -0,0 +1,454 @@
--[[--
努努书坊页面解析:纯函数,无网络。
站点有三套模板:
- 书页(新版):`<div class="catalog">` 里 `<h1>` 书名、`.info` 作者、`.intro` 简介,
目录是 `<div class="mulu-title"><h2>卷名</h2></div>` + `<div class="mulu-list"><ul>`;
章链接可能是站内绝对路径(三体分册)也可能是同目录相对路径。
- 书页(旧版):`<h2><b>书名</b></h2>`、`作者:X 发布时间:…`、封面是内容区第一张非 logo 图,
目录是带 `colspan=3` 卷名的表格(`/files/<分类>/<年月>/<id>.html`、`/wuxia/<年月>/<id>.html`)。
- 单页作品(短篇):书页本身就是正文,没有目录。
列表页的书目链接在 `id="neirong"`(分类页)或 `class="mulu-list"`(最新更新、热门)区块里;
分页在 `<div class="book-nav">` 的「下一页」,路径形式不统一(`2.html` / `29-2.html`),只跟着链接走。
@module moonsource_kanunu.mapper
--]]
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_kanunu")
local BASE = "https://www.kanunu8.com"
local Mapper = {}
Mapper.BASE = BASE
Mapper.CONTENT_MARK = "moon:kanunu:complete"
--- 书城默认节点:官网「最新更新」。
Mapper.DEFAULT_NODE = "/book8/"
--- 当前页里的相对链接算成站内路径;外站、`..`、带 query 的一律拒绝。
---@param ref string|nil
---@param from string|nil 当前页路径(站内,/ 开头)
---@return string|nil path
local function sitePath(ref, from)
if type(ref) ~= "string" or ref == "" or ref:sub(1, 1) == "#" then return nil end
local url = Text.absoluteUrl(from and (BASE .. from) or BASE, ref)
local path = url and url:match("^https://www%.kanunu8%.com(/[^?#]*)$")
if not path or path:find("%.%.") then return nil end
return path
end
--- 作家页、专题合集、书评页不是可读书;列表里出现要跳过。
---@param path string
---@return boolean
local function skipped(path)
return path:find("^/zt/") ~= nil or path:find("^/zj/") ~= nil
or path:find("^/shuping/") ~= nil or path:find("^/files/writer/") ~= nil
or path:match("^/author%d*%.html$") ~= nil or path == "/genres.html"
end
--- 书目链接 → 书页路径。书页形态有两类:`/bookN/<名>`(含 `/book6/santi.html`、`/101/<名>/`)
--- 与旧版 `<区>/<子>/[<子>/]<名>.html`。
---@param ref string
---@param from string|nil
---@return string|nil
function Mapper.bookPath(ref, from)
local path = sitePath(ref, from)
if not path then return nil end
path = path:gsub("/index%.html$", "/"):gsub("/$", "")
if path == "" or skipped(path) then return nil end
-- 不带扩展名的是目录页:站点对缺斜杠的形式回 301(还会降级到 http),一律补回斜杠。
if not path:match("%.html$") then path = path .. "/" end
if path:match("^/book%d-/") or path:match("^/101/") then
-- 只有一层的才是书页,/book6/santi_1/11359.html 是章页。
if path:match("^/book%d-/[^/]+/?$") or path:match("^/101/[^/]+/?$") then return path end
return nil
end
local segments = 0
for _seg in path:gmatch("/([^/]+)") do segments = segments + 1 end
if segments >= 3 and segments <= 4 and path:match("%.html$") then return path end
return nil
end
--- 书城节点(分类页 / 频道页)。
---@param ref string|nil
---@return string|nil
function Mapper.node(ref)
local path = sitePath(ref)
if not path or skipped(path) then return nil end
if not (path:match("/$") or path:match("%.html$")) then return nil end
local segments = 0
for _seg in path:gmatch("/([^/]+)") do segments = segments + 1 end
if segments < 1 or segments > 2 then return nil end
return path
end
--- 目录里的章页:站内 .html,且不是书页自己、不是作品集链接。
---@param ref string
---@param from string
---@return string|nil
function Mapper.chapterPath(ref, from)
local path = sitePath(ref, from)
if not path or skipped(path) or not path:match("%.html$") then return nil end
if path == from or path:match("/index%.html$") then return nil end
return path
end
--- 取从 marker 起、到分页 / 页脚前的一段,避开导航与「看过此书的人还喜欢」。
---@param html string
---@param marker string
---@return string|nil
local function section(html, marker)
local from = html:find(marker, 1, true)
if not from then return nil end
local stop = #html + 1
for _idx, tail in ipairs({ '<div class="book-nav"', '<div class="footer"' }) do
local pos = html:find(tail, from + #marker, true)
if pos and pos < stop then stop = pos end
end
return html:sub(from, stop - 1)
end
--- nav 块只有一层 div,第一个 `</div>` 收尾;用 section 的截断规则会把后面的书列表吃进来。
---@param html string
---@param cls string
---@return string|nil
local function navSection(html, cls)
local from = html:find(cls, 1, true)
if not from then return nil end
local stop = html:find("</div>", from + #cls, true)
return html:sub(from, (stop or #html + 1) - 1)
end
---@param text string|nil
---@return string
local function clean(text)
local flat = Text.stripHtml(Text.trim(tostring(text or ""))):gsub("&nbsp;", " ")
return Text.trim(Text.xmlDecode(Text.trim(flat)))
end
-- 列表标题常写成「作者:书名」;冒号按整串找(`[::]` 会把全角冒号的字节切断)。
local SEPARATORS = { ":", ": ", ":" }
local NO_AUTHOR_MARKS = { "?", "!", "。", "," }
--- 前缀够短、且不是页面自带的分类名时才当作者,避免切书名里的冒号。
---@param title string
---@param labels string[]
---@return string title
---@return string|nil authors
local function splitAuthor(title, labels)
for _idx, sep in ipairs(SEPARATORS) do
local from, to = title:find(sep, 1, true)
if from then
local prefix, rest = Text.trim(title:sub(1, from - 1)), Text.trim(title:sub(to + 1))
if prefix == "" or rest == "" or Text.len(prefix) > 12 then return title, nil end
for _mark, mark in ipairs(NO_AUTHOR_MARKS) do
if prefix:find(mark, 1, true) then return title, nil end
end
-- 分类页的条目标题也写成「分类名:书名」,那不是作者。
for _label, label in ipairs(labels) do
if label == prefix or label == prefix .. "小说" then return title, nil end
end
return rest, prefix
end
end
return title, nil
end
--- 页面自带的分类名/栏目标题,用来区分「桐华:长相思」和「官场小说:驻京办主任」。
---@param html string
---@return string[]
local function categoryLabels(html)
local labels, seen = {}, {}
local function add(value)
local text = clean(value)
if text ~= "" and text:len() <= 24 and not seen[text] then
seen[text] = true
labels[#labels + 1] = text
end
end
for _idx, cls in ipairs({ '<div class="nav-top">', '<div class="nav-bottom">' }) do
local nav = navSection(html, cls)
if nav then
for _href, text in nav:gmatch('<a%s+[^>]-href=["\']([^"\']+)["\'][^>]*>(.-)</a>') do
add(text)
end
end
end
for _idx, title in html:gmatch("<h[12][^>]*>(.-)</h[12]>") do add(title) end
return labels
end
--- 分类页 / 频道页的一页书目。作家、专题链接跳过;认不出的链接说明模板不是预期的列表页。
---@param html string
---@param node string|nil 当前节点路径,用来解析相对链接
---@return Book[]|nil
function Mapper.list(html, node)
local block = section(html, 'id="neirong"') or section(html, 'class="mulu-list"')
if not block then return nil end
local books, seen = {}, {}
local labels = categoryLabels(html)
for href, text in block:gmatch('<a%s+[^>]-href=["\']([^"\']+)["\'][^>]*>(.-)</a>') do
local resolved = sitePath(href, node)
local path = resolved and Mapper.bookPath(href, node)
if not path and not (resolved and skipped(resolved)) then return nil end
local label = clean(text)
if path and label ~= "" and not seen[path] then
seen[path] = true
local title, authors = splitAuthor(label, labels)
books[#books + 1] = {
source_id = "kanunu",
stable_id = path:sub(2),
title = title,
authors = authors or "",
intro = "",
}
end
end
return books
end
--- 下一页:只认「下一页」链接本身,路径形式(`2.html` / `29-2.html`)由站点决定。
---@param html string
---@param node string
---@return string|nil
function Mapper.nextPath(html, node)
local nav = section(html, '<div class="book-nav"')
if not nav then return nil end
local href = nav:match('href=["\']([^"\']+)["\'][^>]*>%s*下一%s*页')
if not href then return nil end
return sitePath(href, node)
end
--- 频道与分类 chip;分类取自页面自带导航,不写死分类表。
---@param html string
---@param node string
---@return StoreChipGroup[]|nil
function Mapper.groups(html, node)
local chips, seen = {}, {}
for _idx, cls in ipairs({ '<div class="nav-top">', '<div class="nav-bottom">' }) do
local nav = navSection(html, cls)
if nav then
for href, text in nav:gmatch('<a%s+[^>]-href=["\']([^"\']+)["\'][^>]*>(.-)</a>') do
local path = sitePath(href)
if path and not skipped(path) and (path:match("/$") or path:match("%.html$"))
and not seen[path] then
seen[path] = true
chips[#chips + 1] = { id = path, title = _(clean(text)) }
end
end
end
end
if #chips == 0 then return nil end
local channels = {}
for _idx, channel in ipairs({ { Mapper.DEFAULT_NODE, _("最新更新") }, { "/hot.html", _("热门点击") } }) do
channels[#channels + 1] = { id = channel[1], title = channel[2] }
end
-- 当前节点(分类页本身或它的分页)对应的 chip 高亮;分页不算上层目录。
local function belongs(chip_id)
if node == chip_id then return true end
return node:sub(1, #chip_id) == chip_id and not node:sub(#chip_id + 1):find("/")
end
local inNav = false
for path in pairs(seen) do
if belongs(path) then inNav = true end
end
local found_active, category_active
if inNav then category_active = node else found_active = node end
return {
{ title = _("发现"), chips = channels, active = found_active },
{ title = _("分类"), chips = chips, active = category_active },
}
end
local LEAD_SEPARATORS = { ":", ":", "\227\128\128", " " }
local function stripLead(text)
local changed = true
while changed do
changed = false
for _idx, sep in ipairs(LEAD_SEPARATORS) do
if text:sub(1, #sep) == sep then
text = text:sub(#sep + 1)
changed = true
end
end
end
return text
end
--- 「作者:X」这类标签值:整串找标签,别用 `[::]`(会把全角冒号字节切断)。
---@param text string
---@param label string|nil 空表示文本已经只剩值
---@return string
local function afterLabel(text, label)
if label ~= "" then
local from, to = text:find(label, 1, true)
if not from then return text end
text = text:sub(to + 1)
end
return stripLead(text)
end
--- 书页元信息。新版在 `.catalog`,旧版在表格模板里。
---@param html string
---@param path string|nil 书页路径,用来算封面相对地址
---@return table|nil
function Mapper.book(html, path)
local title, authors, intro
if html:find('<div class="catalog"', 1, true) then
local head = html:match('<div class="catalog">(.-)<div class="mulu%-title"') or html
title = clean(head:match("<h1>(.-)</h1>"))
local info = head:match('<div class="info"[^>]*>(.-)</div>')
authors = info and clean(afterLabel(info, "作者")) or ""
intro = Text.trim(Text.xmlDecode(Text.trim(head:match('<div class="intro">(.-)</div>') or "")))
elseif html:find("<h2><b>", 1, true) then
title = clean(html:match("<h2><b>(.-)</b></h2>"))
local raw = html:match("作者(.-)发布时间") or html:match("作者([^<]-)<")
authors = raw and clean(Text.trim(afterLabel(raw, ""))) or ""
local cell = html:match('<td class="p10%-%d+">(.-)</td>')
intro = cell and Text.trim(Text.xmlDecode(Text.trim(cell:match("^(.-)<a") or cell))) or ""
else
-- 单页作品:书页即正文,官网上只有书名与作者,没有简介、没有封面。
title = clean(html:match("<h1>(.-)</h1>"))
local info = html:match('<div class="info"[^>]*>(.-)</div>')
authors = info and clean(afterLabel(info, "作者")) or ""
intro = ""
end
if title == "" then return nil end
local cover
for src in html:gmatch('src=["\']([^"\']+)["\']') do
if (src:match("%.jpg$") or src:match("%.png$") or src:match("%.gif$"))
and not src:match("/logo%.png$") then
cover = Text.absoluteUrl(BASE .. (path or "/"), src)
break
end
end
return { title = title, authors = authors, intro = intro, cover = cover }
end
--- 一段 HTML 里的章链接(旧版表格里可能混着作品集、系列其他书)。
---@param block string
---@param page string
---@param volume string|nil
---@param toc table[]
local function appendChapters(block, page, volume, toc)
for href, text in block:gmatch('<a%s+[^>]-href=["\']([^"\']+)["\'][^>]*>(.-)</a>') do
local path = Mapper.chapterPath(href, page)
local title = clean(text)
if path and title ~= "" then
toc[#toc + 1] = { idx = #toc + 1, uid = path, title = title, origin = path, volume = volume }
end
end
end
--- 新版目录:卷名 + `<ul>`;章 href 可能跨目录(三体分册)。
---@param html string
---@param page string
---@param toc table[]
local function modernToc(html, page, toc)
for head, list in html:gmatch('<div class="mulu%-title">(.-)</div>%s*<div class="mulu%-list">(.-)</ul>') do
local volume = clean(head:match("<h[23][^>]*>(.-)</h[23]>"))
appendChapters(list, page, volume ~= "" and volume ~= "正文" and volume or nil, toc)
end
end
--- 旧版目录:带 `colspan=3` 卷名的表格;整行没有链接就是卷名行。
---@param html string
---@param page string
---@param toc table[]
local function legacyToc(html, page, toc)
for table_html in html:gmatch("<table[^>]*>.-</table>") do
if table_html:match('colspan="?3"?') then
local volume
for row in table_html:gmatch("<tr[^>]*>.-</tr>") do
if row:find("<a", 1, true) then
appendChapters(row, page, volume, toc)
else
local name = clean(row)
if name ~= "" and name ~= "正文" then volume = name end
end
end
end
end
end
--- 正文区:新版目录站的文章在 `class="text"`,另有 `id="neirong"` / `id="content"`;到第一个 </div> 为止。
---@param html string
---@return string|nil
local function contentBlock(html)
for _idx, marker in ipairs({ 'id="neirong"', "id='neirong'", 'id="content"', "id='content'",
'class="text"', "class='text'" }) do
local from = html:find(marker, 1, true)
if from then
local start = html:find(">", from)
local stop = html:find("</div>", from, true)
if start and stop and stop > start then return html:sub(start + 1, stop - 1) end
end
end
return nil
end
--- 去掉段首缩进(&nbsp; / 全角空格),缩进由宿主 CSS 给。
local IDEOGRAPHIC_SPACE = "\227\128\128"
---@param line string
---@return string
local function trimIndent(line)
local text = line
while true do
local cut = text:gsub("^&nbsp;", " "):gsub("^&#160;", " "):gsub("^&emsp;", " ")
:gsub("^%s", ""):gsub("^" .. IDEOGRAPHIC_SPACE, "")
if cut == text then return text end
text = cut
end
end
--- 章节页尾部的翻页 / 回目录链接,不是正文。
local NAV_LINKS = {
["上一页"] = true, ["下一页"] = true, ["回目录"] = true, ["返回目录"] = true,
["本章完"] = true, ["开始阅读"] = true,
}
--- 正文:去掉脚本 / 广告 / 翻页链接,`<br>`、`<p>` 统一切成段落。
---@param html string
---@return string|nil
function Mapper.contentHtml(html)
local body = contentBlock(html)
if not body then return nil end
body = body:gsub("<script[^>]*>.-</script>", ""):gsub("<style[^>]*>.-</style>", "")
body = body:gsub("<!%-%-.-%-%->", ""):gsub("<ins[^>]*>.-</ins>", "")
body = body:gsub("<iframe[^>]*>.-</iframe>", "")
body = body:gsub("<a[^>]*>.-</a>", function(inner)
local label = Text.trim(Text.stripHtml(inner or "")):gsub(IDEOGRAPHIC_SPACE, "")
return NAV_LINKS[label] and "" or nil
end)
body = body:gsub("<p[^>]*>", "\n"):gsub("</p>", "\n")
body = body:gsub("<%s*br%s*/?%s*>", "\n")
local out, count = {}, 0
for line in body:gmatch("[^\n]+") do
local text = trimIndent(line):gsub("%s+$", ""):gsub(IDEOGRAPHIC_SPACE .. "$", "")
if Text.trim(text) ~= "" and Text.stripHtml(text) ~= "" then
count = count + 1
out[count] = "<p>" .. text .. "</p>"
end
end
if count == 0 then return nil end
return table.concat(out, "")
end
--- 目录(卷名只作展示,不占章序号)。单页作品返回一章,正文就在书页上。
---@param html string
---@param page string 书页路径
---@return table[] toc
function Mapper.toc(html, page)
local toc = {}
modernToc(html, page, toc)
if #toc == 0 then legacyToc(html, page, toc) end
if #toc == 0 and Mapper.contentHtml(html) then
local title = clean(html:match("<h1>(.-)</h1>") or html:match("<h2><b>(.-)</b></h2>"))
toc[1] = { idx = 1, uid = page, title = title ~= "" and title or _("正文"), origin = page }
end
return toc
end
return Mapper