✨ (engine): 在本机直接执行 Legado 书源规则(CSS/XPath/JSONPath/正则/URL 构造)

This commit is contained in:
garfield committed 2026-12-04 00:33:36 +08:00
1 parent 485d0160a1
commit f73f9c4f39
13 files changed
+4503

No files matched your search

@@ -0,0 +1,549 @@
--[[--
单个 Legado 书源的解析流程:搜索 / 发现 / 详情 / 目录 / 正文(Parser.php 的移植)。
全部异步:cb(result|nil, err|nil),返回 { cancel }。含 JS / WebView 的规则抛 Unsupported,
在这里转成 err 文字。
书:{ name, author, kind, wordCount, latest, intro, cover, bookUrl, tocUrl }
章:{ title, url, baseUrl, isVolume, isVip, isPay, tag }
@module moonsource_legadorule.parser
--]]
local Regex = require("moonsource_legadorule.regex")
local Json = require("moonsource_legadorule.json")
local Html = require("moonsource_legadorule.html")
local Rule = require("moonsource_legadorule.rule")
local Url = require("moonsource_legadorule.url")
local Unsupported = require("moonsource_legadorule.unsupported")
local Client = require("moonsource_legadorule.client")
---@class LegadoRuleParser
local Parser = {}
Parser.__index = Parser
local function trim(s) return (s:gsub("^%s+", ""):gsub("%s+$", "")) end
local function str(v)
if type(v) == "string" then return v end
if type(v) == "number" or type(v) == "boolean" then return tostring(v) end
return ""
end
local function section(rule, key)
local v = rule[key]
return type(v) == "table" and v or {}
end
local function field(t, key) return str(t[key]) end
function Parser.new(rule, client)
return setmetatable({ rule = rule, client = client or Client.new(rule), pageCache = {} }, Parser)
end
function Parser.formatName(s)
s = trim(s)
return trim((Regex.replace("^(书名|名称)[::\\s]+", s, "", true)))
end
function Parser.formatAuthor(s)
s = trim(s)
return trim((Regex.replace("^(作者|作家)[::\\s]+", s, "", true)))
end
function Parser.isTrue(v)
v = trim(v):lower()
if v == "" then return false end
for _, no in ipairs({ "false", "0", "no", "n", "off", "否", "假", "null", "undefined" }) do
if v == no then return false end
end
return true
end
function Parser.matchesPattern(url, pattern)
pattern = trim(pattern)
if pattern == "" then return false end
local ok, hit = pcall(Regex.test, "^(?:" .. pattern .. ")$", url)
return ok and hit
end
---------------------------------------------------------------- 任务 / 抓取
local function newTask()
local task = { cancelled = false }
-- 月读用 h.cancel() 点调用,不带 self
function task.cancel()
task.cancelled = true
if task.inner then task.inner.cancel() end
end
return task
end
local function errText(err) return Unsupported.message(err) end
-- 取一个页面:cb(res, err);取消后不回调。
function Parser:load(task, mUrl, ctx, timeout, cb)
local ok, spec = pcall(Url.build, mUrl, {
sourceUrl = self.rule.bookSourceUrl,
header = str(self.rule.header),
key = ctx.key,
page = ctx.page,
baseUrl = ctx.baseUrl,
rule = ctx.rule,
})
if not ok then
cb(nil, errText(spec))
return
end
local finished = false
local job = self.client:fetch(spec, timeout, function(res, err)
finished = true
task.inner = nil
if task.cancelled then return end
if res then res.spec = spec end
cb(res, err)
end)
if not finished then task.inner = job end
end
-- 在 pcall 里跑解析函数,错误转成文字。
local function guard(fn, ...)
local ok, a, b = pcall(fn, ...)
if ok then return a, b end
return nil, errText(a)
end
---------------------------------------------------------------- 解析:书
local function newBook(self)
return { name = "", author = "", kind = "", wordCount = "", latest = "", intro = "", cover = "", bookUrl = "", tocUrl = "" }
end
local function normalizeKind(list)
local out, seen = {}, {}
for _, k in ipairs(list) do
k = trim(k)
if k ~= "" and not seen[k] then
seen[k] = true
out[#out + 1] = k
end
end
return table.concat(out, ",")
end
local function try(fn, ...)
local ok, v = pcall(fn, ...)
if ok then return v end
if type(v) == "table" and v.unsupported then error(v, 0) end
return nil
end
local function searchItem(self, an, item, baseUrl, set)
local book = newBook(self)
an:setBook(nil)
an:setContent(item)
book.name = Parser.formatName(an:getString(field(set, "name")))
if book.name == "" then return nil end
an:setBook(book.name)
book.author = Parser.formatAuthor(an:getString(field(set, "author")))
book.kind = normalizeKind(try(an.getStringList, an, field(set, "kind")) or {})
book.wordCount = trim(try(an.getString, an, field(set, "wordCount")) or "")
book.latest = try(an.getString, an, field(set, "lastChapter")) or ""
book.intro = Html.format(try(an.getString, an, field(set, "intro")) or "")
local cover = try(an.getString, an, field(set, "coverUrl")) or ""
if cover ~= "" then book.cover = Url.absolute(baseUrl, cover) end
book.bookUrl = an:getString(field(set, "bookUrl"), nil, true)
if book.bookUrl == "" then book.bookUrl = baseUrl end
return book
end
function Parser:analyzeInfo(book, baseUrl, redirectUrl, body, canReName, an)
local info = section(self.rule, "ruleBookInfo")
an = an or Rule.new()
an:setBook(book.name ~= "" and book.name or nil)
an:setContent(body, baseUrl)
an:setBaseUrl(baseUrl)
an:setRedirectUrl(redirectUrl)
local init = trim(field(info, "init"))
if init ~= "" then
local el = an:getElement(init)
if el ~= nil then an:setContent(el) end
end
local rename = canReName and trim(field(info, "canReName")) ~= ""
local name = Parser.formatName(an:getString(field(info, "name")))
if name ~= "" and (rename or book.name == "") then book.name = name end
local author = Parser.formatAuthor(an:getString(field(info, "author")))
if author ~= "" and (rename or book.author == "") then book.author = author end
local kind = normalizeKind(try(an.getStringList, an, field(info, "kind")) or {})
if kind ~= "" then book.kind = kind end
local wc = trim(try(an.getString, an, field(info, "wordCount")) or "")
if wc ~= "" then book.wordCount = wc end
local last = try(an.getString, an, field(info, "lastChapter")) or ""
if last ~= "" then book.latest = last end
local intro = Html.format(try(an.getString, an, field(info, "intro")) or "")
if intro ~= "" then book.intro = intro end
local cover = try(an.getString, an, field(info, "coverUrl")) or ""
if cover ~= "" then book.cover = Url.absolute(redirectUrl, cover) end
local tocUrl = an:getStringList(field(info, "tocUrl"))[1] or ""
if trim(tocUrl) ~= "" then
book.tocUrl = Url.absolute(redirectUrl, tocUrl)
elseif book.tocUrl == "" then
book.tocUrl = baseUrl
end
if book.tocUrl == baseUrl then self.pageCache[book.tocUrl] = body end
end
function Parser:bookList(task, mUrl, key, page, isSearch, timeout, cb)
local rule = self.rule
self:load(task, mUrl, { key = key, page = page, baseUrl = rule.bookSourceUrl }, timeout, function(res, err)
if not res then return cb(nil, err) end
if res.body == "" then return cb(nil, "获取网页内容失败: " .. mUrl) end
cb(guard(function()
local body, baseUrl = res.body, res.url
local an = Rule.new():setContent(body, baseUrl)
an:setBaseUrl(baseUrl):setRedirectUrl(baseUrl)
local pattern = str(rule.bookUrlPattern)
local function infoItem()
local book = newBook(self)
book.bookUrl = res.spec.url ~= "" and res.spec.url or baseUrl
self:analyzeInfo(book, baseUrl, baseUrl, body, false, an)
if book.name == "" then return nil end
self.pageCache[book.bookUrl] = body
return book
end
if isSearch and trim(pattern) ~= "" and Parser.matchesPattern(baseUrl, pattern) then
local book = infoItem()
return { book }
end
local set = isSearch and section(rule, "ruleSearch")
or (trim(field(section(rule, "ruleExplore"), "bookList")) == "" and section(rule, "ruleSearch")
or section(rule, "ruleExplore"))
local listRule = field(set, "bookList")
local reverse = false
if listRule:sub(1, 1) == "-" then reverse, listRule = true, listRule:sub(2) end
if listRule:sub(1, 1) == "+" then listRule = listRule:sub(2) end
local items = an:getElements(listRule)
local books = {}
if #items == 0 and trim(pattern) == "" then
local book = infoItem()
if book then books[1] = book end
return books
end
local seen = {}
for _, item in ipairs(items) do
local book = searchItem(self, an, item, baseUrl, set)
if book then
if baseUrl == book.bookUrl then self.pageCache[book.bookUrl] = body end
local k = book.bookUrl ~= "" and book.bookUrl or (book.name .. "|" .. book.author)
if not seen[k] then
seen[k] = true
books[#books + 1] = book
end
end
end
if reverse then
local n = #books
for i = 1, math.floor(n / 2) do books[i], books[n - i + 1] = books[n - i + 1], books[i] end
end
return books
end))
end)
end
function Parser:search(keyword, page, cb)
local task = newTask()
local url = str(self.rule.searchUrl)
if trim(url) == "" then
cb(nil, "搜索url不能为空")
return task
end
self:bookList(task, url, keyword, page or 1, true, 15, cb)
return task
end
function Parser:explore(url, page, cb)
local task = newTask()
if trim(url) == "" then
cb(nil, "发现url不能为空")
return task
end
self:bookList(task, url, nil, page or 1, false, 30, cb)
return task
end
function Parser:detail(bookUrl, seed, cb)
local task = newTask()
local book = newBook(self)
for k, v in pairs(seed or {}) do book[k] = v end
if bookUrl ~= "" then book.bookUrl = bookUrl end
self:load(task, book.bookUrl, { baseUrl = self.rule.bookSourceUrl }, 30, function(res, err)
if not res then return cb(nil, err) end
if res.body == "" then return cb(nil, "获取网页内容失败: " .. book.bookUrl) end
cb(guard(function()
self.pageCache[res.url] = res.body
self.pageCache[book.bookUrl] = res.body
self:analyzeInfo(book, book.bookUrl, res.url, res.body, true)
return book
end))
end)
return task
end
---------------------------------------------------------------- 目录
function Parser:chapterPage(book, baseUrl, redirectUrl, body, tocRule, listRule, getNext)
local an = Rule.new():setBook(book.name)
an:setContent(body, baseUrl)
an:setBaseUrl(baseUrl):setRedirectUrl(redirectUrl)
local elements = an:getElements(listRule)
local nexts = {}
local nextRule = field(tocRule, "nextTocUrl")
if getNext and nextRule ~= "" then
for _, u in ipairs(an:getStringList(nextRule, nil, true)) do
if u ~= redirectUrl then nexts[#nexts + 1] = u end
end
end
local chapters = {}
for index, item in ipairs(elements) do
an:setContent(item)
local ch = { baseUrl = redirectUrl }
ch.title = an:getString(field(tocRule, "chapterName"))
an:setChapter(ch.title)
local raw = an:getString(field(tocRule, "chapterUrl"))
ch.url = raw ~= "" and Url.absolute(redirectUrl, raw) or ""
local tag = an:getString(field(tocRule, "updateTime"))
ch.tag = tag ~= "" and tag or nil
ch.isVolume = Parser.isTrue(an:getString(field(tocRule, "isVolume")))
if ch.url == "" then ch.url = ch.isVolume and (ch.title .. (index - 1)) or baseUrl end
if ch.title ~= "" then
ch.isVip = Parser.isTrue(an:getString(field(tocRule, "isVip")))
ch.isPay = Parser.isTrue(an:getString(field(tocRule, "isPay")))
chapters[#chapters + 1] = ch
end
end
return chapters, nexts
end
function Parser:chapters(book, cb)
local task = newTask()
local rule = self.rule
local tocRule = section(rule, "ruleToc")
if trim(field(tocRule, "preUpdateJs")) ~= "" then
cb(nil, Unsupported.MESSAGE)
return task
end
local tocUrl = book.tocUrl ~= "" and book.tocUrl or book.bookUrl
if tocUrl == "" then
cb(nil, "目录链接为空")
return task
end
local listRule = field(tocRule, "chapterList")
local reverse = false
if listRule:sub(1, 1) == "-" then reverse, listRule = true, listRule:sub(2) end
if listRule:sub(1, 1) == "+" then listRule = listRule:sub(2) end
local all, seen = {}, {}
local function finish()
local out, keys = {}, {}
for _, ch in ipairs(all) do
local k = ch.url ~= "" and ch.url or ch.title
if not keys[k] then
keys[k] = true
out[#out + 1] = ch
end
end
if #out == 0 then return cb(nil, "目录列表为空") end
if reverse then
local n = #out
for i = 1, math.floor(n / 2) do out[i], out[n - i + 1] = out[n - i + 1], out[i] end
end
for i, ch in ipairs(out) do ch.index = i end
cb(out)
end
local function parsePage(baseUrl, redirectUrl, body, getNext)
local ok, chapters, nexts = pcall(self.chapterPage, self, book, baseUrl, redirectUrl, body, tocRule, listRule, getNext)
if not ok then return nil, errText(chapters) end
for _, ch in ipairs(chapters) do all[#all + 1] = ch end
return nexts
end
local function followOne(url)
if url == "" or seen[url] then return finish() end
seen[url] = true
self:load(task, url, { baseUrl = book.bookUrl }, 60, function(res, err)
if not res then return cb(nil, err) end
local nexts, perr = parsePage(url, res.url, res.body, true)
if not nexts then return cb(nil, perr) end
followOne(nexts[1] or "")
end)
end
local function followMany(urls, i)
local url = urls[i]
if not url then return finish() end
if seen[url] then return followMany(urls, i + 1) end
seen[url] = true
self:load(task, url, { baseUrl = book.bookUrl }, 60, function(res, err)
if not res then return cb(nil, err) end
local nexts, perr = parsePage(url, res.url, res.body, false)
if not nexts then return cb(nil, perr) end
followMany(urls, i + 1)
end)
end
local function first(body, redirectUrl)
seen[redirectUrl] = true
local nexts, perr = parsePage(tocUrl, redirectUrl, body, true)
if not nexts then return cb(nil, perr) end
if #nexts == 1 then
followOne(nexts[1])
elseif #nexts > 1 then
followMany(nexts, 1)
else
finish()
end
end
local cached = self.pageCache[tocUrl]
if cached then
first(cached, tocUrl)
else
self:load(task, tocUrl, { baseUrl = book.bookUrl }, 60, function(res, err)
if not res then return cb(nil, err) end
if res.body == "" then return cb(nil, "获取网页内容失败: " .. tocUrl) end
first(res.body, res.url)
end)
end
return task
end
---------------------------------------------------------------- 正文
function Parser:contentPage(book, chapter, baseUrl, redirectUrl, body, nextChapterUrl, contentRule, getNext)
local an = Rule.new():setBook(book.name)
an:setChapter(chapter.title)
an:setContent(body, baseUrl)
an:setRedirectUrl(redirectUrl)
local titleRule = trim(field(contentRule, "title"))
if titleRule ~= "" then
local title = try(an.getString, an, titleRule) or ""
if title ~= "" then chapter.title = title end
end
local content = an:getString(field(contentRule, "content"), nil, false, false)
content = Html.formatKeepImg(content, Url.absolute, redirectUrl)
if content:find("&", 1, true) then content = Html.decode(content) end
local nexts = {}
local nextRule = field(contentRule, "nextContentUrl")
if getNext and nextRule ~= "" then
for _, u in ipairs(an:getStringList(nextRule, nil, true)) do nexts[#nexts + 1] = u end
end
return content, nexts
end
function Parser:finishContent(book, chapter, baseUrl, redirectUrl, body, contentRule, parts)
local text = table.concat(parts, "\n")
local replace = field(contentRule, "replaceRegex")
if replace ~= "" then
local an = Rule.new():setBook(book.name)
an:setChapter(chapter.title)
an:setContent(body, baseUrl)
an:setRedirectUrl(redirectUrl)
local lines = {}
for line in (text .. "\n"):gmatch("(.-)\r?\n") do lines[#lines + 1] = trim(line) end
text = an:getString(replace, table.concat(lines, "\n"))
local out = {}
for line in (text .. "\n"):gmatch("(.-)\r?\n") do
if line ~= "" and not line:find("<[iI][mM][gG]") and not line:match("^https?://") then
line = "  " .. line
end
out[#out + 1] = line
end
text = table.concat(out, "\n")
end
return text
end
--- cb({ title, text }) 或 cb(nil, err)。
function Parser:content(chapter, book, nextChapterUrl, cb)
local task = newTask()
local contentRule = section(self.rule, "ruleContent")
if trim(field(contentRule, "webJs")) ~= "" then
cb(nil, Unsupported.MESSAGE)
return task
end
if trim(field(contentRule, "content")) == "" then
cb({ title = chapter.title, text = chapter.url })
return task
end
if chapter.isVolume and chapter.url ~= "" and chapter.url:sub(1, #chapter.title) == chapter.title then
cb({ title = chapter.title, text = chapter.tag or "" })
return task
end
local chapterUrl = chapter.url
if chapterUrl == "" then
chapterUrl = chapter.baseUrl
elseif not Url.splitOption(chapterUrl):match("^https?://") then
chapterUrl = Url.absolute(chapter.baseUrl, chapterUrl)
end
local refBase = book.tocUrl ~= "" and book.tocUrl or book.bookUrl
local parts, seen = {}, {}
local function done(baseUrl, redirectUrl, body)
local text, err = guard(self.finishContent, self, book, chapter, baseUrl, redirectUrl, body, contentRule, parts)
if not text then return cb(nil, err) end
if not chapter.isVolume and trim(text) == "" then return cb(nil, "章节内容为空") end
cb({ title = chapter.title, text = text })
end
local function isNextChapter(redirectUrl, nextUrl)
if not nextChapterUrl or nextChapterUrl == "" then return false end
local a = Url.absolute(redirectUrl, nextUrl)
return a ~= "" and a == Url.absolute(redirectUrl, nextChapterUrl)
end
local function followOne(nextUrl, redirectUrl, body)
if nextUrl == "" or seen[nextUrl] or isNextChapter(redirectUrl, nextUrl) then
return done(chapterUrl, redirectUrl, body)
end
seen[nextUrl] = true
self:load(task, nextUrl, { baseUrl = book.bookUrl }, 60, function(res, err)
if not res then return cb(nil, err) end
local pack = { guard(self.contentPage, self, book, chapter, nextUrl, res.url, res.body, nextChapterUrl, contentRule, true) }
if pack[1] == nil then return cb(nil, pack[2]) end
local content, nexts = pack[1], pack[2]
parts[#parts + 1] = content
followOne(nexts[1] or "", redirectUrl, body)
end)
end
local function followMany(urls, i, redirectUrl, body)
local url = urls[i]
if not url then return done(chapterUrl, redirectUrl, body) end
self:load(task, url, { baseUrl = book.bookUrl }, 60, function(res, err)
if not res then return cb(nil, err) end
local content, perr = guard(self.contentPage, self, book, chapter, url, res.url, res.body, nextChapterUrl, contentRule, false)
if not content then return cb(nil, perr) end
parts[#parts + 1] = content
followMany(urls, i + 1, redirectUrl, body)
end)
end
self:load(task, chapterUrl, { baseUrl = refBase }, 60, function(res, err)
if not res then return cb(nil, err) end
if res.body == "" then return cb(nil, "获取网页内容失败: " .. chapterUrl) end
local content, nexts = guard(self.contentPage, self, book, chapter, chapterUrl, res.url, res.body, nextChapterUrl, contentRule, true)
if not content then return cb(nil, nexts) end
parts[1] = content
seen[res.url] = true
if #nexts == 1 then
followOne(nexts[1], res.url, res.body)
elseif #nexts > 1 then
followMany(nexts, 1, res.url, res.body)
else
done(chapterUrl, res.url, res.body)
end
end)
return task
end
return Parser