✨ (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

+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_kanunu",
is_doc_only = false,
}
@@ -0,0 +1,12 @@
--[[--
月读第三方书源描述:努努书坊。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。
--]]
return {
api = 1,
provides = {
source = true,
},
meta = function() return require("moonsource_kanunu.source").meta() end,
new = function() return require("moonsource_kanunu.source").new() end,
}
@@ -0,0 +1,18 @@
# 努努书坊
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| 登录 | 不支持 | 全站公开可读,插件不保存 Cookie、不注册账号 |
| 书架拉取、新增、删除 | 不支持 | 网站没有账号书架,书架只在月读本机 |
| 搜索 | 不支持 | 站内搜索框是 Google 自定义检索,站点本身没有搜索接口 |
| 分类书库 | 支持 | 分类取自页面导航,分页按官网「下一页」链接走;每页约 200 本,默认聚合约 60 本 |
| 频道 | 支持 | 「最新更新」「热门点击」各一页,官网这两页不分页 |
| 详情 | 支持 | 书名、作者、简介;只有旧版书页有封面,新版没有封面 |
| 目录 | 支持 | 新版目录带卷名,旧版是带卷名的表格;短篇等单页作品算一章 |
| 正文 | 支持 | GBK / GB2312 转 UTF-8;每章一页,页尾翻页链接与广告不进正文 |
| 已购内容 | 不支持 | 全站免费公开,没有购买接口 |
| 书评、章评、段评、回复 | 不支持 | 当前 Web 协议未找到可验证接口,「书评」栏目是站内文章不是书评列表 |
| 进度、笔记、统计同步 | 不支持 | 只留在本机 |
| 离线与整本缓存 | 支持 | 打开过的章节留在本机;整本缓存逐章下载,站点响应慢(每章间隔 2 秒) |
| 账号切换 | 不支持 | 没有账号 |
| 可用性 | 有限制 | 站点在 Cloudflare 后面,偶发把请求判为爬虫(403)或连接超时;插件不绕过、不自动重试,只如实报错,失败章节可重下 |
@@ -0,0 +1,15 @@
--[[--
努努书坊元信息。
@module moonsource_kanunu._meta
--]]
local _ = require("l10n").get("moonsource_kanunu")
return {
id = "kanunu",
name = _("努努书坊"),
type = "chapter",
description = _("努努书坊,按章阅读公开书页"),
abilities = { _("分类书库"), _("最新更新"), _("在线阅读"), _("整本缓存") },
}
@@ -0,0 +1,82 @@
--[[--
努努书坊匿名 HTTP:只取站内页面,GBK / GB2312 统一转 UTF-8。
整站公开可读,没有账号,所以不带 Cookie、不登录。站点在 Cloudflare 后面,
偶发拦截(403)与瞬时断连;一律如实报错,不重试、不把失败包装成空列表。
@module moonsource_kanunu.client
--]]
local Charset = require("utils.charset")
local Request = require("http.request")
local Timeout = require("http.timeout")
local _ = require("l10n").get("moonsource_kanunu")
local BASE = "https://www.kanunu8.com"
local UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
---@class KanunuClient
local Client = {}
Client.__index = Client
Client.BASE = BASE
Client.UA = UA
---@return KanunuClient
function Client.new()
return setmetatable({}, Client)
end
--- GET 一个站内页面,回调转成 UTF-8 的正文。
---@param path string 站内路径(/ 开头)或本站完整 URL
---@param cb fun(html: string|nil, err: string|nil)
---@return { cancel: fun() }
function Client:get(path, cb)
local url = tostring(path or "")
if not url:find("^https?://") then url = BASE .. url end
if not url:match("^https://www%.kanunu8%.com/") then
return require("source.base").defer(cb, nil, _("响应无效"))
end
local pending, inner, cancelled, finished = true, nil, false, false
local function finish(html, err)
if cancelled or finished then return end
finished = true
cb(html, err)
end
local job = Request.get(url, {
headers = {
["User-Agent"] = UA,
Accept = "text/html,application/xhtml+xml",
["Accept-Language"] = "zh-CN,zh;q=0.9",
},
timeout = Timeout.net(1),
-- 站点偶尔对缺斜杠的路径回 301;跟着跳转是浏览器行为,本站无 Cookie / 凭证,跨跳不带任何凭据。
allow_redirects = true,
}, function(body, err, res)
pending = false
if cancelled or finished then return end
inner = nil
if not body then
if res and res.code == 403 then
finish(nil, _("努努书坊把这次请求当成了爬虫,请稍后再试"))
else
finish(nil, err or _("网络请求失败"))
end
return
end
local text, charset = Charset.toUtf8(body, Request.header(res, "content-type"))
if not text then
finish(nil, _("不支持的页面编码"))
return
end
finish(text, nil)
end)
if pending then inner = job end
return {
cancel = function()
cancelled = true
if inner then inner.cancel() end
end,
}
end
return Client
@@ -0,0 +1,20 @@
return {
["努努书坊"] = "Kanunu8",
["努努书坊,按章阅读公开书页"] = "Kanunu8, read the free public pages chapter by chapter",
["努努书坊把这次请求当成了爬虫,请稍后再试"] = "Kanunu8 treated this request as a crawler; try again later",
["发现"] = "Browse",
["响应无效"] = "Invalid response",
["分类"] = "Category",
["分类书库"] = "Categories",
["最新更新"] = "Latest updates",
["热门点击"] = "Most read",
["正文"] = "Text",
["在线阅读"] = "Read online",
["整本缓存"] = "Cache the book",
["不支持的页面编码"] = "Unsupported page encoding",
["章节目录保存失败"] = "Failed to save the chapter list",
["网络请求失败"] = "Network request failed",
["这一章没有正文"] = "This chapter has no text",
["无法解析书籍信息"] = "Unable to parse book information",
["章节列表为空"] = "The chapter list is empty",
}
@@ -0,0 +1,20 @@
return {
["努努书坊"] = "努努書坊",
["努努书坊,按章阅读公开书页"] = "努努書坊,按章閱讀公開頁",
["努努书坊把这次请求当成了爬虫,请稍后再试"] = "努努書坊把這次請求當成了爬蟲,請稍後再試",
["发现"] = "發現",
["响应无效"] = "回應無效",
["分类"] = "分類",
["分类书库"] = "分類書庫",
["最新更新"] = "最新更新",
["热门点击"] = "熱門點擊",
["正文"] = "正文",
["在线阅读"] = "線上閱讀",
["整本缓存"] = "整本快取",
["不支持的页面编码"] = "不支援的頁面編碼",
["章节目录保存失败"] = "章節目錄儲存失敗",
["网络请求失败"] = "網路請求失敗",
["这一章没有正文"] = "這一章沒有正文",
["无法解析书籍信息"] = "無法解析書籍資訊",
["章节列表为空"] = "章節清單為空",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_kanunu._meta")) do copy[k] = v end
return copy
end
@@ -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
@@ -0,0 +1,174 @@
--[[--
努努书坊书源:频道 / 分类浏览 + 按章在线阅读。
站点没有站内搜索(页面里只有 Google 自定义检索),也没有书架、进度、评论接口,
所以只接:频道与分类浏览、详情、目录、正文与整本缓存。
页面编码 GBK / GB2312 由 client 统一转 UTF-8。
@module moonsource_kanunu.source
--]]
local Browse = require("source.browse")
local Client = require("moonsource_kanunu.client")
local Mapper = require("moonsource_kanunu.mapper")
local SourceBase = require("source.base")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_kanunu")
local Kanunu = {}
-- 站点响应慢且在 Cloudflare 后面,逐章请求之间留间隔。
local FETCH_INTERVAL = 2
---@return BookSourceMeta
function Kanunu.meta()
return require("moonsource_kanunu.loadmeta")()
end
---@class KanunuSource : SourceBase
---@field client KanunuClient
local Source = setmetatable({}, { __index = SourceBase })
Source.__index = Source
---@return KanunuSource
function Kanunu.new()
local meta = Kanunu.meta()
return setmetatable({ id = meta.id, name = meta.name, type = meta.type, client = Client.new() }, Source)
end
function Source:configured()
return true
end
function Source:capabilities()
return { scrape = false, edit = false, stats_pull = false, shelf_cache = false, shelf_push = false }
end
--- 分页路径形式不统一(`2.html` / `29-2.html`),只按上一页的「下一页」链接走。
function Source:browseAsync(opts, cb)
opts = opts or {}
local node = Mapper.node(opts.node) or Mapper.DEFAULT_NODE
local pages, groups = {}, {}
return Browse.pages(function(page, page_cb)
local path = pages[page] or node
return self.client:get(path, function(html, err)
if not html then page_cb(nil, err) return end
local books = Mapper.list(html, path)
if not books then page_cb(nil, _("响应无效")) return end
groups = Mapper.groups(html, node) or groups
pages[page + 1] = Mapper.nextPath(html, path)
page_cb(books, nil, pages[page + 1] ~= nil)
end)
end, opts.limit or 60, {}, function(result, err)
if result then result.groups = groups end
cb(result, err)
end)
end
function Source:getDetailAsync(identity, cb)
return self.client:get("/" .. identity.stable_id, function(html, err)
if not html then cb(nil, err) return end
local row = Mapper.book(html, "/" .. identity.stable_id)
if not row then
cb(nil, _("无法解析书籍信息"))
return
end
local book = {
source_id = self.id,
stable_id = identity.stable_id,
title = row.title,
authors = row.authors,
intro = row.intro,
cover = row.cover,
}
cb(require("book.store").rememberDetail(book))
end)
end
function Source:loadTocAsync(identity, cb, force)
if force then return self:refreshTocAsync(identity, cb) end
local cancelled, active = false, nil
active = Toc.readAsync(self.id, identity.stable_id, function(cached, err)
if cancelled then return end
if cached and #cached > 0 then cb(cached); return end
if err then cb(nil, err); return end
active = self:refreshTocAsync(identity, cb)
end)
return { cancel = function()
cancelled = true
if active then active.cancel() end
end }
end
function Source:refreshTocAsync(identity, cb)
local cancelled, active, pending = false, nil, true
local request = self.client:get("/" .. identity.stable_id, function(html, err)
pending = false
if cancelled then return end
if not html then cb(nil, err) return end
active = Toc.parseAsync(self.id, identity.stable_id, function()
local toc = Mapper.toc(html, "/" .. identity.stable_id)
if #toc == 0 then return nil, _("章节列表为空") end
return toc
end, cb)
end)
if pending then active = request end
return { cancel = function()
cancelled = true
if active then active.cancel() end
end }
end
---@return ChapterFetchContent
local function contentFetcher(self)
return function(_ref, ch, done)
return self.client:get(ch.origin, function(page, err)
if not page then done(nil, err) return end
local html = Mapper.contentHtml(page)
if not html then done(nil, _("这一章没有正文")) return end
done({ title = ch.title, html = html, mark = Mapper.CONTENT_MARK })
end)
end
end
--- 离线保留旧缓存;在线重取未标记的旧版正文,失败不覆盖它。
---@param path string
---@return boolean
local function reuse(path)
if not require("ui/network/manager"):isConnected() then return true end
local file = assert(io.open(path, "rb"))
local head, err = file:read(64)
file:close()
assert(head, err)
return head:find(Mapper.CONTENT_MARK, 1, true) ~= nil
end
function Source:openBookAsync(identity, opts, cb)
local Chapter = require("source.chapter")
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(self),
reuse = reuse,
}, cb)
end
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
return require("source.chapter").prefetchAsync(identity, identity.book, toc, from_idx, count, {
fetchContent = contentFetcher(self),
interval_seconds = FETCH_INTERVAL,
reuse = reuse,
}, cb)
end
--- 缓存整本章节正文;已落盘章节由公共实现自动跳过。
---@param identity BookIdentity
---@param on_progress fun(done: integer, total: integer)|nil
---@param cb fun(ok: boolean, cached: integer, err: string|nil, total: integer, failed: integer)
---@return { cancel: fun() }
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
return require("source.chapter").cacheAllAsync(self, identity, contentFetcher(self), on_progress, cb,
FETCH_INTERVAL, range, reuse)
end
return Kanunu
@@ -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