diff --git a/moonsource-legadorule.koplugin/moonsource_legadorule/client.lua b/moonsource-legadorule.koplugin/moonsource_legadorule/client.lua
new file mode 100644
index 0000000..2b7f54a
--- /dev/null
+++ b/moonsource-legadorule.koplugin/moonsource_legadorule/client.lua
@@ -0,0 +1,93 @@
+--[[--
+书源 HTTP:按 url.build 产出的请求描述发请求,转 UTF-8,按书源 retry 重试。
+enabledCookieJar 时每个书源一个进程内 Cookie 罐。最终跳转地址取不到,用请求地址代替。
+
+@module moonsource_legadorule.client
+--]]
+
+local Charset = require("utils.charset")
+local Request = require("http.request")
+local Jar = require("http.cookie_jar")
+
+local UA = "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36"
+
+---@class LegadoRuleClient
+local Client = {}
+Client.__index = Client
+
+---@param rule table 书源 JSON
+function Client.new(rule)
+ return setmetatable({ jar = rule.enabledCookieJar and Jar.new() or nil }, Client)
+end
+
+local function copyHeaders(spec)
+ local headers = {}
+ for k, v in pairs(spec.headers or {}) do headers[k] = v end
+ local hasUA = false
+ for k in pairs(headers) do
+ if k:lower() == "user-agent" then hasUA = true end
+ end
+ if not hasUA then headers["User-Agent"] = UA end
+ return headers
+end
+
+local function decode(body, res, charset)
+ local ct = Request.header(res, "content-type")
+ if charset and charset ~= "" then ct = "text/html; charset=" .. charset end
+ local text = Charset.toUtf8(body, ct)
+ return text or body
+end
+
+--- 发一次请求描述。cb(res|nil, err|nil),res = { body, url, code }。返回 { cancel }。
+---@param spec table url.build 的结果
+---@param timeout number 秒
+---@param cb fun(res: table|nil, err: string|nil)
+function Client:fetch(spec, timeout, cb)
+ local attempts = (spec.retry or 0) + 1
+ local cancelled, inner = false, nil
+ local function attempt(n)
+ local opts = {
+ headers = copyHeaders(spec),
+ timeout = timeout,
+ allow_redirects = true,
+ jar = self.jar,
+ accept = "*/*",
+ }
+ local function done(body, err, res)
+ if cancelled then return end
+ inner = nil
+ local code = res and res.code
+ if body and body ~= "" or (res and not err) then
+ cb({ body = decode(body or "", res, spec.charset), url = spec.url, code = code }, nil)
+ elseif n < attempts then
+ attempt(n + 1)
+ else
+ cb(nil, string.format("获取网页内容失败: %s (%s)", spec.url, err or "empty"))
+ end
+ end
+ local pending = true
+ local job
+ if spec.method == "POST" then
+ opts.content_type = spec.contentType
+ job = Request.post(spec.url, spec.body or "", opts, function(...)
+ pending = false
+ done(...)
+ end)
+ else
+ job = Request.get(spec.url, opts, function(...)
+ pending = false
+ done(...)
+ end)
+ end
+ if pending then inner = job end
+ end
+ attempt(1)
+ return {
+ cancel = function()
+ cancelled = true
+ if inner then inner.cancel() end
+ end,
+ }
+end
+
+return Client
diff --git a/moonsource-legadorule.koplugin/moonsource_legadorule/css.lua b/moonsource-legadorule.koplugin/moonsource_legadorule/css.lua
new file mode 100644
index 0000000..0a8bc67
--- /dev/null
+++ b/moonsource-legadorule.koplugin/moonsource_legadorule/css.lua
@@ -0,0 +1,334 @@
+--[[--
+CSS 选择器(jsoup 方言):标签 / #id / .class / 属性 [a=v ^= $= *= ~=(正则) !=] / 组合符 空格 > + ~ /
+伪类 :contains :containsOwn :matches :has :not :first-child :last-child :nth-child :nth-of-type
+:eq :lt :gt :first :last :empty 等。
+
+@module moonsource_legadorule.css
+--]]
+
+local Html = require("moonsource_legadorule.html")
+local Regex = require("moonsource_legadorule.regex")
+
+local Css = {}
+
+local IDENT = "^[%w_%-\128-\255]+"
+
+local function elems(parent)
+ if parent.elems then return parent.elems end
+ local list = {}
+ for _, c in ipairs(parent.children) do
+ if c.type == "el" then
+ list[#list + 1] = c
+ c.eidx = #list
+ end
+ end
+ parent.elems = list
+ return list
+end
+
+local function position(el, ofType, fromEnd)
+ local parent = el.parent
+ if not parent then return 1, 1 end
+ local list = elems(parent)
+ local pos, total = 0, 0
+ for _, e in ipairs(list) do
+ if not ofType or e.tag == el.tag then
+ total = total + 1
+ if e == el then pos = total end
+ end
+ end
+ if fromEnd then return total - pos + 1, total end
+ return pos, total
+end
+
+local function nth(expr)
+ expr = expr:gsub("%s", ""):lower()
+ if expr == "odd" then return 2, 1 end
+ if expr == "even" then return 2, 0 end
+ local a, b = expr:match("^([+-]?%d*)n([+-]?%d*)$")
+ if a then
+ a = (a == "" or a == "+") and 1 or (a == "-" and -1 or tonumber(a))
+ return a, tonumber(b) or 0
+ end
+ return 0, tonumber(expr) or 0
+end
+
+local function nthMatch(pos, a, b)
+ if a == 0 then return pos == b end
+ local n = (pos - b) / a
+ return n >= 0 and n == math.floor(n)
+end
+
+local compileList
+
+local function pseudo(name, arg)
+ local function own(el) return Html.ownText(el):lower() end
+ if name == "contains" then
+ local t = arg:lower()
+ return function(el) return Html.text(el):lower():find(t, 1, true) ~= nil end
+ elseif name == "containsown" then
+ local t = arg:lower()
+ return function(el) return own(el):find(t, 1, true) ~= nil end
+ elseif name == "matches" then
+ return function(el) return Regex.test(arg, Html.text(el)) end
+ elseif name == "matchesown" then
+ return function(el) return Regex.test(arg, Html.ownText(el)) end
+ elseif name == "not" then
+ local inner = compileList(arg)
+ return function(el) return not Css.matches(el, inner) end
+ elseif name == "has" then
+ local inner = compileList(arg)
+ return function(el)
+ local found = false
+ local function walk(n)
+ for _, c in ipairs(n.children or {}) do
+ if found then return end
+ if c.type == "el" then
+ if Css.matches(c, inner) then found = true return end
+ walk(c)
+ end
+ end
+ end
+ walk(el)
+ return found
+ end
+ elseif name == "first-child" or name == "first" then
+ return function(el) return (position(el)) == 1 end
+ elseif name == "last-child" or name == "last" then
+ return function(el) return (position(el, false, true)) == 1 end
+ elseif name == "only-child" then
+ return function(el) local _, t = position(el); return t == 1 end
+ elseif name == "first-of-type" then
+ return function(el) return (position(el, true)) == 1 end
+ elseif name == "last-of-type" then
+ return function(el) return (position(el, true, true)) == 1 end
+ elseif name == "nth-child" or name == "nth-last-child" or name == "nth-of-type" or name == "nth-last-of-type" then
+ local a, b = nth(arg)
+ local ofType, fromEnd = name:find("of%-type") ~= nil, name:find("last") ~= nil
+ return function(el) return nthMatch((position(el, ofType, fromEnd)), a, b) end
+ elseif name == "eq" or name == "nth" then
+ local n = tonumber(arg) or 0
+ return function(el) return position(el) - 1 == n end
+ elseif name == "lt" then
+ local n = tonumber(arg) or 0
+ return function(el) return position(el) - 1 < n end
+ elseif name == "gt" then
+ local n = tonumber(arg) or 0
+ return function(el) return position(el) - 1 > n end
+ elseif name == "empty" then
+ return function(el)
+ for _, c in ipairs(el.children) do
+ if c.type == "el" or (c.type == "text" and c.text:find("%S")) then return false end
+ end
+ return true
+ end
+ elseif name == "root" then
+ return function(el) return el.parent and el.parent.type == "doc" end
+ end
+ error("selector: unsupported :" .. name, 0)
+end
+
+local function attrTest(body)
+ local name, op, value = body:match("^%s*([^%s=~^$*!|]+)%s*([~^$*!|]?=)%s*(.-)%s*$")
+ if not name then
+ return function(el) return el.attrs[(body:gsub("%s", ""):lower())] ~= nil end
+ end
+ name = name:lower()
+ value = value:gsub("^([\"'])(.*)%1$", "%2")
+ local lower = value:lower()
+ return function(el)
+ local v = el.attrs[name]
+ if v == nil then return op == "!=" end
+ local lv = v:lower()
+ if op == "=" then return lv == lower
+ elseif op == "^=" then return lv:sub(1, #lower) == lower
+ elseif op == "$=" then return lower == "" or lv:sub(-#lower) == lower
+ elseif op == "*=" then return lv:find(lower, 1, true) ~= nil
+ elseif op == "!=" then return lv ~= lower
+ elseif op == "|=" then return lv == lower or lv:sub(1, #lower + 1) == lower .. "-"
+ else return Regex.test(value, v) end
+ end
+end
+
+-- 读到与 open 配对的右括号,返回括号内文本与下一位置
+local function balanced(s, i, open, close)
+ local depth, j, q = 0, i, nil
+ while j <= #s do
+ local c = s:sub(j, j)
+ if q then
+ if c == q then q = nil end
+ elseif c == '"' or c == "'" then q = c
+ elseif c == open then depth = depth + 1
+ elseif c == close then
+ depth = depth - 1
+ if depth == 0 then return s:sub(i + 1, j - 1), j + 1 end
+ end
+ j = j + 1
+ end
+ error("selector: unbalanced " .. open, 0)
+end
+
+local function splitTop(s)
+ local out, depth, q, start = {}, 0, nil, 1
+ for i = 1, #s do
+ local c = s:sub(i, i)
+ if q then
+ if c == q then q = nil end
+ elseif c == '"' or c == "'" then q = c
+ elseif c == "(" or c == "[" then depth = depth + 1
+ elseif c == ")" or c == "]" then depth = depth - 1
+ elseif c == "," and depth == 0 then
+ out[#out + 1] = s:sub(start, i - 1)
+ start = i + 1
+ end
+ end
+ out[#out + 1] = s:sub(start)
+ return out
+end
+
+local function compileComplex(sel)
+ local parts, i, comb = {}, 1, " "
+ sel = sel:gsub("^%s+", ""):gsub("%s+$", "")
+ while i <= #sel do
+ local tests, tag = {}, nil
+ local start = i
+ while i <= #sel do
+ local c = sel:sub(i, i)
+ if c == "*" then
+ i = i + 1
+ elseif c == "#" then
+ local id = sel:match(IDENT, i + 1)
+ if not id then error("selector: bad #", 0) end
+ i = i + 1 + #id
+ tests[#tests + 1] = function(el) return el.attrs.id == id end
+ elseif c == "." then
+ local cls = sel:match(IDENT, i + 1)
+ if not cls then error("selector: bad .", 0) end
+ i = i + 1 + #cls
+ tests[#tests + 1] = function(el)
+ local v = el.attrs.class
+ return v ~= nil and (" " .. v:gsub("%s+", " ") .. " "):find(" " .. cls .. " ", 1, true) ~= nil
+ end
+ elseif c == "[" then
+ local body
+ body, i = balanced(sel, i, "[", "]")
+ tests[#tests + 1] = attrTest(body)
+ elseif c == ":" then
+ local name = sel:match("^[%w_%-]+", i + 1)
+ if not name then error("selector: bad :", 0) end
+ i = i + 1 + #name
+ local arg = ""
+ if sel:sub(i, i) == "(" then arg, i = balanced(sel, i, "(", ")") end
+ arg = arg:gsub("^%s+", ""):gsub("%s+$", "")
+ arg = arg:gsub("^([\"'])(.*)%1$", "%2")
+ tests[#tests + 1] = pseudo(name:lower(), arg)
+ else
+ local t = sel:match(IDENT, i)
+ if not t or i ~= start then break end
+ tag = t:lower()
+ i = i + #t
+ end
+ end
+ if i == start then error("selector: unexpected '" .. sel:sub(i, i) .. "'", 0) end
+ parts[#parts + 1] = { comb = comb, tag = tag, tests = tests }
+ -- 组合符
+ local ws = sel:match("^%s*", i)
+ i = i + #ws
+ local c = sel:sub(i, i)
+ if c == ">" or c == "+" or c == "~" then
+ comb = c
+ i = i + 1
+ i = i + #sel:match("^%s*", i)
+ elseif i <= #sel then
+ comb = " "
+ end
+ end
+ return parts
+end
+
+function compileList(sel)
+ local list = {}
+ for _, g in ipairs(splitTop(sel)) do
+ if g:find("%S") then list[#list + 1] = compileComplex(g) end
+ end
+ if #list == 0 then error("selector: empty", 0) end
+ return list
+end
+
+local function compoundMatch(el, part)
+ if el.type ~= "el" then return false end
+ if part.tag and el.tag ~= part.tag then return false end
+ for _, t in ipairs(part.tests) do
+ if not t(el) then return false end
+ end
+ return true
+end
+
+local function matchAt(el, parts, k)
+ if not compoundMatch(el, parts[k]) then return false end
+ if k == 1 then return true end
+ local comb = parts[k].comb
+ if comb == ">" then
+ local p = el.parent
+ return p ~= nil and p.type == "el" and matchAt(p, parts, k - 1)
+ elseif comb == " " then
+ local p = el.parent
+ while p and p.type == "el" do
+ if matchAt(p, parts, k - 1) then return true end
+ p = p.parent
+ end
+ return false
+ end
+ local parent = el.parent
+ if not parent then return false end
+ local list = elems(parent)
+ local idx = el.eidx or (elems(parent) and el.eidx)
+ if comb == "+" then
+ local prev = list[idx - 1]
+ return prev ~= nil and matchAt(prev, parts, k - 1)
+ end
+ for j = idx - 1, 1, -1 do
+ if matchAt(list[j], parts, k - 1) then return true end
+ end
+ return false
+end
+
+--- el 是否命中已编译选择器。
+function Css.matches(el, compiled)
+ for _, parts in ipairs(compiled) do
+ if matchAt(el, parts, #parts) then return true end
+ end
+ return false
+end
+
+local cache = {}
+
+--- 编译选择器;语法错误抛错(字符串)。
+function Css.compile(sel)
+ local c = cache[sel]
+ if not c then
+ c = compileList(sel)
+ cache[sel] = c
+ end
+ return c
+end
+
+--- root 的所有后代里命中 sel 的元素,文档顺序。
+function Css.select(root, sel)
+ local compiled = Css.compile(sel)
+ local out = {}
+ local function walk(n)
+ for _, c in ipairs(n.children or {}) do
+ if c.type == "el" then
+ if Css.matches(c, compiled) then out[#out + 1] = c end
+ walk(c)
+ end
+ end
+ end
+ -- jsoup 的 select 把根元素自己也算进候选
+ if root.type == "el" and Css.matches(root, compiled) then out[1] = root end
+ walk(root)
+ return out
+end
+
+return Css
diff --git a/moonsource-legadorule.koplugin/moonsource_legadorule/html.lua b/moonsource-legadorule.koplugin/moonsource_legadorule/html.lua
new file mode 100644
index 0000000..5a2ba8d
--- /dev/null
+++ b/moonsource-legadorule.koplugin/moonsource_legadorule/html.lua
@@ -0,0 +1,378 @@
+--[[--
+轻量 HTML DOM:解析、序列化、取文本,以及 Legado 的 HtmlFormatter(正文清洗)。
+节点:{type="el", tag, attrs, attrOrder, children, parent, order} / {type="text", text, parent, order} /
+根 {type="doc"}。标签与属性名小写。
+
+@module moonsource_legadorule.html
+--]]
+
+local Html = {}
+
+local NAMED = {
+ nbsp = "\194\160", amp = "&", lt = "<", gt = ">", quot = '"', apos = "'", copy = "©", reg = "®",
+ hellip = "…", mdash = "—", ndash = "–", ldquo = "“", rdquo = "”", lsquo = "‘", rsquo = "’",
+ middot = "·", times = "×", divide = "÷", laquo = "«", raquo = "»", bull = "•", trade = "™",
+ yen = "¥", pound = "£", euro = "€", cent = "¢", sect = "§", deg = "°", ensp = "\226\128\130",
+ emsp = "\226\128\131", thinsp = "\226\128\137", zwnj = "\226\128\140", zwj = "\226\128\141",
+}
+
+local function utf8(cp)
+ 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 / 0x1000), 0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
+ end
+ return string.char(0xF0 + math.floor(cp / 0x40000), 0x80 + math.floor(cp / 0x1000) % 64,
+ 0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
+end
+
+--- 解 HTML 实体。
+function Html.decode(s)
+ if not s:find("&", 1, true) then return s end
+ return (s:gsub("&(#?[%w]+);?", function(name)
+ local whole = name
+ if name:sub(1, 1) == "#" then
+ local cp = name:sub(2, 2):lower() == "x" and tonumber(name:sub(3), 16) or tonumber(name:sub(2))
+ if cp and cp > 0 and cp < 0x110000 then return utf8(cp) end
+ return nil
+ end
+ return NAMED[whole] or NAMED[whole:lower()]
+ end))
+end
+
+local VOID = {
+ area = 1, base = 1, br = 1, col = 1, embed = 1, hr = 1, img = 1, input = 1, link = 1, meta = 1,
+ param = 1, source = 1, track = 1, wbr = 1,
+}
+local RAW = { script = 1, style = 1, textarea = 1, title = 1 }
+local BLOCK = {
+ address = 1, article = 1, aside = 1, blockquote = 1, body = 1, br = 1, dd = 1, div = 1, dl = 1, dt = 1,
+ fieldset = 1, figure = 1, footer = 1, form = 1, h1 = 1, h2 = 1, h3 = 1, h4 = 1, h5 = 1, h6 = 1,
+ header = 1, hr = 1, li = 1, main = 1, nav = 1, ol = 1, p = 1, pre = 1, section = 1, table = 1, tbody = 1,
+ td = 1, th = 1, thead = 1, tr = 1, ul = 1,
+}
+Html.VOID, Html.BLOCK = VOID, BLOCK
+
+-- 新开标签 → 需要先隐式关闭的同级标签
+local CLOSES = {
+ li = { li = 1 }, dt = { dt = 1, dd = 1 }, dd = { dt = 1, dd = 1 }, option = { option = 1 },
+ td = { td = 1, th = 1 }, th = { td = 1, th = 1 }, tr = { tr = 1, td = 1, th = 1 },
+ thead = { tbody = 1, tfoot = 1 }, tbody = { thead = 1, tbody = 1, tfoot = 1, tr = 1, td = 1, th = 1 },
+}
+for tag in pairs(BLOCK) do
+ if tag ~= "br" and tag ~= "hr" and tag ~= "td" and tag ~= "th" and tag ~= "tr" and tag ~= "li" then
+ CLOSES[tag] = CLOSES[tag] or {}
+ CLOSES[tag].p = 1
+ end
+end
+
+local SCOPE = {
+ ul = 1, ol = 1, table = 1, div = 1, td = 1, th = 1, section = 1, article = 1, body = 1, html = 1,
+ blockquote = 1, dl = 1, form = 1, main = 1, nav = 1, header = 1, footer = 1, aside = 1,
+}
+
+local function parseAttrs(src)
+ local attrs, list = {}, {}
+ local i = 1
+ while true do
+ local s, e, name = src:find("^[%s/]*([^%s=/>]+)", i)
+ if not s then break end
+ i = e + 1
+ local value = ""
+ local s2, e2 = src:find("^%s*=%s*", i)
+ if s2 then
+ i = e2 + 1
+ local q = src:sub(i, i)
+ if q == '"' or q == "'" then
+ local close = src:find(q, i + 1, true) or #src + 1
+ value = src:sub(i + 1, close - 1)
+ i = close + 1
+ else
+ value = src:match("^[^%s>]*", i)
+ i = i + #value
+ end
+ end
+ name = name:lower()
+ if attrs[name] == nil then
+ list[#list + 1] = name
+ attrs[name] = Html.decode(value)
+ end
+ end
+ return attrs, list
+end
+
+--- 解析 HTML 片段 / 文档,返回根节点。
+function Html.parse(src)
+ local root = { type = "doc", children = {}, order = 0 }
+ local stack, top, order = { root }, root, 0
+ local function add(node)
+ order = order + 1
+ node.order, node.parent = order, top
+ top.children[#top.children + 1] = node
+ end
+ local i, len = 1, #src
+ while i <= len do
+ local lt = src:find("<", i, true)
+ if not lt then
+ add({ type = "text", text = Html.decode(src:sub(i)) })
+ break
+ end
+ if lt > i then add({ type = "text", text = Html.decode(src:sub(i, lt - 1)) }) end
+ if src:sub(lt, lt + 3) == "", lt + 4, true)
+ i = (e or len) + 1
+ elseif src:sub(lt, lt + 1) == "", lt, true) or len) + 1
+ elseif src:sub(lt, lt + 1) == "" then
+ local gt = src:find(">", lt, true) or len
+ local tag = src:match("^%s*([%w:_-]+)", lt)
+ i = gt + 1
+ if tag then
+ tag = tag:lower()
+ for k = #stack, 2, -1 do
+ if stack[k].tag == tag then
+ for _ = k, #stack do stack[#stack] = nil end
+ top = stack[#stack]
+ break
+ end
+ end
+ end
+ else
+ local tag = src:match("^<([%a][%w:_-]*)", lt)
+ if not tag then
+ add({ type = "text", text = "<" })
+ i = lt + 1
+ else
+ tag = tag:lower()
+ -- 找到不在引号里的 >
+ local j, q = lt + 1 + #tag, nil
+ while j <= len do
+ local c = src:sub(j, j)
+ if q then
+ if c == q then q = nil end
+ elseif c == '"' or c == "'" then
+ q = c
+ elseif c == ">" then
+ break
+ end
+ j = j + 1
+ end
+ local inner = src:sub(lt + 1 + #tag, j - 1)
+ local selfClose = inner:sub(-1) == "/"
+ local attrs, list = parseAttrs(inner)
+ i = j + 1
+ local closes = CLOSES[tag]
+ if closes then
+ local found
+ for k = #stack, 2, -1 do
+ local t = stack[k].tag
+ if closes[t] then
+ found = k
+ elseif SCOPE[t] then
+ break
+ end
+ end
+ if found then
+ for _ = found, #stack do stack[#stack] = nil end
+ top = stack[#stack]
+ end
+ end
+ local node = { type = "el", tag = tag, attrs = attrs, attrOrder = list, children = {} }
+ add(node)
+ if RAW[tag] and not selfClose then
+ local s, e = src:lower():find("" .. tag .. "%s*>", i)
+ local body = src:sub(i, (s or len + 1) - 1)
+ if body ~= "" then
+ order = order + 1
+ local raw = tag == "script" or tag == "style"
+ local t = { type = "text", text = raw and body or Html.decode(body),
+ order = order, parent = node, raw = raw }
+ node.children[1] = t
+ end
+ i = (e or len) + 1
+ elseif not VOID[tag] and not selfClose then
+ stack[#stack + 1] = node
+ top = node
+ end
+ end
+ end
+ end
+ return root
+end
+
+---------------------------------------------------------------- 序列化与取文本
+
+local function escapeText(s)
+ return (s:gsub("[&<>\194]", function(c)
+ if c == "&" then return "&" end
+ if c == "<" then return "<" end
+ if c == ">" then return ">" end
+ return c
+ end):gsub("\194\160", " "))
+end
+
+local function escapeAttr(s)
+ return (s:gsub('[&"]', { ["&"] = "&", ['"'] = """ }))
+end
+
+local function serialize(node, out)
+ if node.type == "text" then
+ out[#out + 1] = node.raw and node.text or escapeText(node.text)
+ elseif node.type == "el" then
+ out[#out + 1] = "<" .. node.tag
+ for _, name in ipairs(node.attrOrder) do
+ out[#out + 1] = " " .. name .. '="' .. escapeAttr(node.attrs[name]) .. '"'
+ end
+ out[#out + 1] = ">"
+ if not VOID[node.tag] then
+ for _, c in ipairs(node.children) do serialize(c, out) end
+ out[#out + 1] = "" .. node.tag .. ">"
+ end
+ else
+ for _, c in ipairs(node.children) do serialize(c, out) end
+ end
+end
+
+function Html.outer(node)
+ local out = {}
+ serialize(node, out)
+ return table.concat(out)
+end
+
+function Html.inner(node)
+ local out = {}
+ for _, c in ipairs(node.children or {}) do serialize(c, out) end
+ return table.concat(out)
+end
+
+local function collect(node, out)
+ if node.type == "text" then
+ if not node.raw then out[#out + 1] = node.text end
+ elseif node.type == "el" then
+ local block = BLOCK[node.tag]
+ if block then out[#out + 1] = " " end
+ for _, c in ipairs(node.children) do collect(c, out) end
+ if block then out[#out + 1] = " " end
+ else
+ for _, c in ipairs(node.children) do collect(c, out) end
+ end
+end
+
+local function collapse(s)
+ s = s:gsub("[ \t\r\n\f]+", " ")
+ return (s:gsub("^ ", ""):gsub(" $", ""))
+end
+Html.collapse = collapse
+
+--- jsoup text():连续空白折叠、块级元素之间留空格。
+function Html.text(node)
+ local out = {}
+ collect(node, out)
+ return collapse(table.concat(out))
+end
+
+--- 不含子元素的自有文本(jsoup ownText)。
+function Html.ownText(node)
+ local out = {}
+ for _, c in ipairs(node.children or {}) do
+ if c.type == "text" and not c.raw then out[#out + 1] = c.text end
+ end
+ return collapse(table.concat(out))
+end
+
+--- Legado textNodes:每个直接文本节点修剪后按行拼接。
+function Html.textNodes(node)
+ local out = {}
+ for _, c in ipairs(node.children or {}) do
+ if c.type == "text" and not c.raw then
+ local t = collapse(c.text)
+ if t ~= "" then out[#out + 1] = t end
+ end
+ end
+ return table.concat(out, "\n")
+end
+
+--- 原样拼接的文本内容(XPath string-value)。
+function Html.textContent(node)
+ if node.type == "text" then return node.text end
+ local out = {}
+ local function walk(n)
+ for _, c in ipairs(n.children or {}) do
+ if c.type == "text" then out[#out + 1] = c.text else walk(c) end
+ end
+ end
+ walk(node)
+ return table.concat(out)
+end
+
+--- Legado `html`:去掉 script / style 的 innerHTML。
+function Html.cleanInner(node)
+ local out = {}
+ local function walk(n)
+ if n.type == "el" and (n.tag == "script" or n.tag == "style") then return end
+ serialize(n, out)
+ end
+ for _, c in ipairs(node.children or {}) do walk(c) end
+ return table.concat(out)
+end
+
+---------------------------------------------------------------- HtmlFormatter
+
+local function lines(s)
+ local out = {}
+ for line in (s .. "\n"):gmatch("(.-)\r?\n") do
+ line = line:gsub("^[%s\194\160\227\128\128]+", ""):gsub("[%s\194\160\227\128\128]+$", "")
+ if line ~= "" then out[#out + 1] = line end
+ end
+ return table.concat(out, "\n")
+end
+
+local function stripBlocks(s)
+ s = s:gsub("<[sS][cC][rR][iI][pP][tT].-[sS][cC][rR][iI][pP][tT]>", "")
+ s = s:gsub("<[sS][tT][yY][lL][eE].-[sS][tT][yY][lL][eE]>", "")
+ return (s:gsub("", ""))
+end
+
+local function breaks(s)
+ s = s:gsub("<[bB][rR]%s*/?>", "\n"):gsub("<[hH][rR]%s*/?>", "\n")
+ s = s:gsub("[pP]>", "\n"):gsub("[dD][iI][vV]>", "\n"):gsub("[lL][iI]>", "\n")
+ s = s:gsub("[tT][rR]>", "\n"):gsub("[hH][1-6]>", "\n")
+ return (s:gsub("<[pP][%s>]", "\n%0"))
+end
+
+--- 取纯文本:块级换行、去标签、解实体、逐行修剪。
+function Html.format(s)
+ if not s or s == "" then return "" end
+ s = breaks(stripBlocks(s)):gsub("<[^>]*>", "")
+ return lines(Html.decode(s))
+end
+
+local IMG_ATTRS = { "src", "data-src", "data-original", "data-lazy-src" }
+
+--- 同 format,但保留图片:,纯图片 URL 也包成
。base 用来补全相对地址。
+function Html.formatKeepImg(s, absolute, base)
+ if not s or s == "" then return "" end
+ s = breaks(stripBlocks(s))
+ s = s:gsub("<[iI][mM][gG]([^>]*)>", function(attrs)
+ local a = parseAttrs(attrs)
+ for _, name in ipairs(IMG_ATTRS) do
+ local v = a[name]
+ if v and v ~= "" then
+ if absolute then v = absolute(base, v) end
+ return '\n
\n'
+ end
+ end
+ return ""
+ end)
+ local imgs = {}
+ s = s:gsub('
', function(tag)
+ imgs[#imgs + 1] = tag
+ return "\1" .. #imgs .. "\1"
+ end)
+ s = s:gsub("<[^>]*>", "")
+ s = lines(Html.decode(s))
+ s = s:gsub("\1(%d+)\1", function(n) return imgs[tonumber(n)] end)
+ return s
+end
+
+return Html
diff --git a/moonsource-legadorule.koplugin/moonsource_legadorule/json.lua b/moonsource-legadorule.koplugin/moonsource_legadorule/json.lua
new file mode 100644
index 0000000..d66934f
--- /dev/null
+++ b/moonsource-legadorule.koplugin/moonsource_legadorule/json.lua
@@ -0,0 +1,163 @@
+--[[--
+宽松 JSON:书源规则里的选项常写单引号、尾逗号、不加引号的键。数组与对象用元表区分,null 是 Json.null,
+JsonPath 因此能区分 [] / {} / null。
+
+@module moonsource_legadorule.json
+--]]
+
+local Json = {}
+local Arr, Obj = {}, {}
+Json.Arr, Json.Obj = Arr, Obj
+Json.null = setmetatable({}, { __tostring = function() return "null" end })
+
+function Json.isArray(v) return type(v) == "table" and getmetatable(v) == Arr end
+function Json.isObject(v) return type(v) == "table" and getmetatable(v) == Obj end
+function Json.newArray() return setmetatable({}, Arr) end
+function Json.newObject() return setmetatable({}, Obj) end
+
+local function utf8(cp)
+ 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 / 0x1000), 0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
+ end
+ return string.char(0xF0 + math.floor(cp / 0x40000), 0x80 + math.floor(cp / 0x1000) % 64,
+ 0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
+end
+
+local ESC = { n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", ["/"] = "/", ["\\"] = "\\", ['"'] = '"', ["'"] = "'" }
+
+local function fail(s, i, what) error("JSON " .. what .. " @" .. i, 0) end
+
+local function skip(s, i)
+ while true do
+ i = s:find("[^%s]", i) or #s + 1
+ if s:sub(i, i + 1) == "//" then
+ i = (s:find("\n", i, true) or #s) + 1
+ elseif s:sub(i, i + 1) == "/*" then
+ local _, e = s:find("*/", i + 2, true)
+ i = (e or #s) + 1
+ else
+ return i
+ end
+ end
+end
+
+local value
+
+local function str(s, i)
+ local q = s:sub(i, i)
+ local out, j = {}, i + 1
+ while true do
+ local k = s:find("[\\" .. q .. "]", j)
+ if not k then fail(s, i, "unterminated string") end
+ out[#out + 1] = s:sub(j, k - 1)
+ if s:sub(k, k) == q then return table.concat(out), k + 1 end
+ local c = s:sub(k + 1, k + 1)
+ if c == "u" then
+ local cp = tonumber(s:sub(k + 2, k + 5), 16) or 63
+ j = k + 6
+ if cp >= 0xD800 and cp < 0xDC00 and s:sub(j, j + 1) == "\\u" then
+ local lo = tonumber(s:sub(j + 2, j + 5), 16)
+ if lo and lo >= 0xDC00 and lo < 0xE000 then
+ cp = 0x10000 + (cp - 0xD800) * 0x400 + (lo - 0xDC00)
+ j = j + 6
+ end
+ end
+ out[#out + 1] = utf8(cp)
+ else
+ out[#out + 1] = ESC[c] or c
+ j = k + 2
+ end
+ end
+end
+
+function value(s, i)
+ i = skip(s, i)
+ local c = s:sub(i, i)
+ if c == "{" then
+ local obj = setmetatable({}, Obj)
+ i = skip(s, i + 1)
+ while s:sub(i, i) ~= "}" do
+ local key
+ local q = s:sub(i, i)
+ if q == '"' or q == "'" then
+ key, i = str(s, i)
+ else
+ key = s:match("^[%w_$%-]+", i)
+ if not key then fail(s, i, "bad key") end
+ i = i + #key
+ end
+ i = skip(s, i)
+ if s:sub(i, i) ~= ":" then fail(s, i, "expected :") end
+ obj[key], i = value(s, i + 1)
+ i = skip(s, i)
+ if s:sub(i, i) == "," then i = skip(s, i + 1) elseif s:sub(i, i) ~= "}" then fail(s, i, "expected }") end
+ end
+ return obj, i + 1
+ elseif c == "[" then
+ local arr = setmetatable({}, Arr)
+ i = skip(s, i + 1)
+ local n = 0
+ while s:sub(i, i) ~= "]" do
+ n = n + 1
+ arr[n], i = value(s, i)
+ i = skip(s, i)
+ if s:sub(i, i) == "," then i = skip(s, i + 1) elseif s:sub(i, i) ~= "]" then fail(s, i, "expected ]") end
+ end
+ return arr, i + 1
+ elseif c == '"' or c == "'" then
+ return str(s, i)
+ end
+ local num = s:match("^-?%d+%.?%d*[eE]?[+-]?%d*", i)
+ if num and num ~= "" and num ~= "-" then return tonumber(num) or fail(s, i, "bad number"), i + #num end
+ local word = s:match("^%a+", i)
+ if word == "true" then return true, i + 4 end
+ if word == "false" then return false, i + 5 end
+ if word == "null" then return Json.null, i + 4 end
+ fail(s, i, "unexpected token")
+end
+
+--- 解码;失败返回 nil, 错误。
+function Json.decode(s)
+ local ok, v, i = pcall(value, s, 1)
+ if not ok then return nil, v end
+ i = skip(s, i)
+ if i <= #s then return nil, "JSON trailing data" end
+ return v
+end
+
+local function quote(s)
+ return '"' .. s:gsub('[%c"\\]', function(c)
+ if c == '"' then return '\\"' end
+ if c == "\\" then return "\\\\" end
+ if c == "\n" then return "\\n" end
+ if c == "\r" then return "\\r" end
+ if c == "\t" then return "\\t" end
+ return string.format("\\u%04x", c:byte())
+ end) .. '"'
+end
+
+--- 编码;数组 / 对象按元表,未标记的表有 [1] 当数组。键序排序,输出稳定。
+function Json.encode(v)
+ local t = type(v)
+ if v == Json.null or v == nil then return "null" end
+ if t == "string" then return quote(v) end
+ if t == "number" then
+ if v == math.floor(v) and math.abs(v) < 1e15 then return string.format("%d", v) end
+ return tostring(v)
+ end
+ if t == "boolean" then return tostring(v) end
+ local out = {}
+ if getmetatable(v) == Arr or (getmetatable(v) ~= Obj and v[1] ~= nil) then
+ for k = 1, #v do out[k] = Json.encode(v[k]) end
+ return "[" .. table.concat(out, ",") .. "]"
+ end
+ local keys = {}
+ for k in pairs(v) do keys[#keys + 1] = k end
+ table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
+ for _, k in ipairs(keys) do out[#out + 1] = quote(tostring(k)) .. ":" .. Json.encode(v[k]) end
+ return "{" .. table.concat(out, ",") .. "}"
+end
+
+return Json
diff --git a/moonsource-legadorule.koplugin/moonsource_legadorule/jsonpath.lua b/moonsource-legadorule.koplugin/moonsource_legadorule/jsonpath.lua
new file mode 100644
index 0000000..cef9590
--- /dev/null
+++ b/moonsource-legadorule.koplugin/moonsource_legadorule/jsonpath.lua
@@ -0,0 +1,318 @@
+--[[--
+JsonPath(Jayway 常用子集):$ .key ['key'] [n] [-n] [*] .* ..key [a,b] [s:e:step] [?(@.k op v)] [?(@.k)]。
+
+@module moonsource_legadorule.jsonpath
+--]]
+
+local Json = require("moonsource_legadorule.json")
+
+local JsonPath = {}
+
+local null = Json.null
+
+local function isArr(v) return Json.isArray(v) end
+local function isObj(v) return Json.isObject(v) end
+
+local function children(v)
+ local out = {}
+ if isArr(v) then
+ for k = 1, #v do out[k] = v[k] end
+ elseif isObj(v) then
+ local keys = {}
+ for k in pairs(v) do keys[#keys + 1] = k end
+ table.sort(keys)
+ for _, k in ipairs(keys) do out[#out + 1] = v[k] end
+ end
+ return out
+end
+
+local function descend(v, out)
+ out[#out + 1] = v
+ for _, c in ipairs(children(v)) do descend(c, out) end
+end
+
+local function str(s, i)
+ local q = s:sub(i, i)
+ local j, out = i + 1, {}
+ while j <= #s do
+ local c = s:sub(j, j)
+ if c == "\\" then
+ out[#out + 1] = s:sub(j + 1, j + 1)
+ j = j + 2
+ elseif c == q then
+ return table.concat(out), j + 1
+ else
+ out[#out + 1] = c
+ j = j + 1
+ end
+ end
+ error("jsonpath: unterminated string", 0)
+end
+
+-- 过滤表达式 @.a.b op literal
+local function filterValue(s)
+ s = s:gsub("^%s+", ""):gsub("%s+$", "")
+ local q = s:sub(1, 1)
+ if q == "'" or q == '"' then return (str(s, 1)) end
+ if s == "true" then return true elseif s == "false" then return false elseif s == "null" then return null end
+ return tonumber(s) or s
+end
+
+local function walkAt(item, path)
+ local cur = item
+ for key in path:gmatch("[^%.]+") do
+ key = key:gsub("^%['(.-)'%]$", "%1")
+ if isObj(cur) then cur = cur[key]
+ elseif isArr(cur) and tonumber(key) then cur = cur[tonumber(key) + 1]
+ else return nil end
+ if cur == nil then return nil end
+ end
+ return cur
+end
+
+local function compileFilter(expr)
+ expr = expr:gsub("^%s*%(", ""):gsub("%)%s*$", "")
+ local function clause(c)
+ local path, op, rhs = c:match("^%s*@%.?([^%s=!<>~]*)%s*([=!<>~]+)%s*(.-)%s*$")
+ if not path then
+ local only = c:match("^%s*@%.?([^%s]*)%s*$")
+ if only then return function(item) return walkAt(item, only) ~= nil end end
+ local neg = c:match("^%s*!%s*@%.?([^%s]*)%s*$")
+ if neg then return function(item) return walkAt(item, neg) == nil end end
+ error("jsonpath: unsupported filter " .. c, 0)
+ end
+ local want = filterValue(rhs)
+ return function(item)
+ local v = path == "" and item or walkAt(item, path)
+ if v == nil then return false end
+ if op == "==" or op == "=" then return v == want or tostring(v) == tostring(want)
+ elseif op == "!=" then return tostring(v) ~= tostring(want)
+ elseif op == "=~" then
+ local pat = rhs:match("^/(.*)/[a-z]*$") or rhs
+ return require("moonsource_legadorule.regex").test(pat, tostring(v))
+ end
+ local a, b = tonumber(v), tonumber(want)
+ if not a or not b then return false end
+ if op == "<" then return a < b elseif op == ">" then return a > b
+ elseif op == "<=" then return a <= b else return a >= b end
+ end
+ end
+ local ors = {}
+ for part in (expr .. "||"):gmatch("(.-)||") do
+ local ands = {}
+ for c in (part .. "&&"):gmatch("(.-)&&") do ands[#ands + 1] = clause(c) end
+ ors[#ors + 1] = ands
+ end
+ return function(item)
+ for _, ands in ipairs(ors) do
+ local ok = true
+ for _, f in ipairs(ands) do if not f(item) then ok = false break end end
+ if ok then return true end
+ end
+ return false
+ end
+end
+
+--- 解析路径为步骤列表。
+local function parse(path)
+ local steps, i = {}, 1
+ path = path:gsub("^%s+", ""):gsub("%s+$", "")
+ if path:sub(1, 1) == "$" then i = 2 end
+ local definite = true
+ while i <= #path do
+ local c = path:sub(i, i)
+ if c == "." then
+ if path:sub(i + 1, i + 1) == "." then
+ steps[#steps + 1] = { t = "deep" }
+ definite = false
+ i = i + 2
+ if path:sub(i, i) == "[" or path:sub(i, i) == "*" then
+ -- ..[ ] / ..* 交给后续步骤
+ else
+ local key = path:match("^[^%.%[]+", i)
+ steps[#steps + 1] = { t = "key", key = key }
+ i = i + #key
+ end
+ else
+ i = i + 1
+ if path:sub(i, i) == "*" then
+ steps[#steps + 1] = { t = "all" }
+ definite = false
+ i = i + 1
+ else
+ local key = path:match("^[^%.%[]+", i)
+ if not key then error("jsonpath: bad path", 0) end
+ steps[#steps + 1] = { t = "key", key = key }
+ i = i + #key
+ end
+ end
+ elseif c == "[" then
+ local j = i + 1
+ local body
+ local q = path:sub(j, j)
+ if q == "?" then
+ local depth, k = 0, j + 1
+ while k <= #path do
+ local ch = path:sub(k, k)
+ if ch == "(" then depth = depth + 1
+ elseif ch == ")" then
+ depth = depth - 1
+ if depth == 0 then break end
+ elseif ch == "'" or ch == '"' then
+ local _, nk = str(path, k)
+ k = nk - 1
+ end
+ k = k + 1
+ end
+ steps[#steps + 1] = { t = "filter", f = compileFilter(path:sub(j + 1, k)) }
+ definite = false
+ i = path:find("]", k, true) + 1
+ else
+ local depth, k = 0, j
+ while k <= #path do
+ local ch = path:sub(k, k)
+ if ch == "'" or ch == '"' then
+ local _, nk = str(path, k)
+ k = nk - 1
+ elseif ch == "]" then
+ break
+ end
+ k = k + 1
+ end
+ body = path:sub(j, k - 1)
+ i = k + 1
+ if body == "*" then
+ steps[#steps + 1] = { t = "all" }
+ definite = false
+ elseif body:find("^%s*['\"]") then
+ local keys, p = {}, 1
+ while p <= #body do
+ local ch = body:sub(p, p)
+ if ch == "'" or ch == '"' then
+ local s2
+ s2, p = str(body, p)
+ keys[#keys + 1] = s2
+ else
+ p = p + 1
+ end
+ end
+ if #keys == 1 then
+ steps[#steps + 1] = { t = "key", key = keys[1] }
+ else
+ steps[#steps + 1] = { t = "keys", keys = keys }
+ definite = false
+ end
+ elseif body:find(":") then
+ local a, b, s = body:match("^%s*(-?%d*)%s*:%s*(-?%d*)%s*:?%s*(-?%d*)%s*$")
+ steps[#steps + 1] = { t = "slice", a = tonumber(a), b = tonumber(b), step = tonumber(s) or 1 }
+ definite = false
+ elseif body:find(",") then
+ local idxs = {}
+ for n in body:gmatch("-?%d+") do idxs[#idxs + 1] = tonumber(n) end
+ steps[#steps + 1] = { t = "idxs", idxs = idxs }
+ definite = false
+ else
+ local n = tonumber(body)
+ if not n then error("jsonpath: bad index", 0) end
+ steps[#steps + 1] = { t = "idx", n = n }
+ end
+ end
+ else
+ error("jsonpath: unexpected '" .. c .. "'", 0)
+ end
+ end
+ return steps, definite
+end
+
+local function byIndex(v, n)
+ if not isArr(v) then return nil end
+ if n < 0 then n = #v + n end
+ return v[n + 1]
+end
+
+local function apply(step, v, out)
+ local t = step.t
+ if t == "key" then
+ if isObj(v) then
+ if v[step.key] ~= nil then out[#out + 1] = v[step.key] end
+ elseif isArr(v) and step.key == "length()" then
+ out[#out + 1] = #v
+ end
+ elseif t == "keys" then
+ if isObj(v) then
+ for _, k in ipairs(step.keys) do if v[k] ~= nil then out[#out + 1] = v[k] end end
+ end
+ elseif t == "idx" then
+ local x = byIndex(v, step.n)
+ if x ~= nil then out[#out + 1] = x end
+ elseif t == "idxs" then
+ for _, n in ipairs(step.idxs) do
+ local x = byIndex(v, n)
+ if x ~= nil then out[#out + 1] = x end
+ end
+ elseif t == "all" then
+ for _, c in ipairs(children(v)) do out[#out + 1] = c end
+ elseif t == "slice" and isArr(v) then
+ local n = #v
+ local a, b = step.a or 0, step.b or n
+ if a < 0 then a = n + a end
+ if b < 0 then b = n + b end
+ a, b = math.max(a, 0), math.min(b, n)
+ for k = a, b - 1, step.step > 0 and step.step or 1 do out[#out + 1] = v[k + 1] end
+ elseif t == "filter" then
+ for _, c in ipairs(children(v)) do
+ if step.f(c) then out[#out + 1] = c end
+ end
+ end
+end
+
+local cache = {}
+
+--- 读取。返回 values(命中数组), definite(路径是否确定到单值)。路径错误抛字符串。
+function JsonPath.read(root, path)
+ local c = cache[path]
+ if not c then
+ local steps, definite = parse(path)
+ c = { steps = steps, definite = definite }
+ cache[path] = c
+ end
+ local current = { root }
+ local i = 1
+ while i <= #c.steps do
+ local step = c.steps[i]
+ local nextList = {}
+ if step.t == "deep" then
+ local all = {}
+ for _, v in ipairs(current) do descend(v, all) end
+ local nxt = c.steps[i + 1]
+ i = i + 1
+ if nxt then
+ for _, v in ipairs(all) do apply(nxt, v, nextList) end
+ else
+ nextList = all
+ end
+ else
+ for _, v in ipairs(current) do apply(step, v, nextList) end
+ end
+ current = nextList
+ i = i + 1
+ end
+ return current, c.definite
+end
+
+--- 把 JSON 值转成 Legado 风格字符串:字符串原样,null 为空,对象 / 数组序列化。
+function JsonPath.stringify(v)
+ if v == nil or v == null then return "" end
+ local t = type(v)
+ if t == "string" then return v end
+ if t == "boolean" then return tostring(v) end
+ if t == "number" then return Json.encode(v) end
+ if Json.isArray(v) then
+ local out = {}
+ for i, item in ipairs(v) do out[i] = JsonPath.stringify(item) end
+ return table.concat(out, "\n")
+ end
+ return Json.encode(v)
+end
+
+return JsonPath
diff --git a/moonsource-legadorule.koplugin/moonsource_legadorule/parser.lua b/moonsource-legadorule.koplugin/moonsource_legadorule/parser.lua
new file mode 100644
index 0000000..05a777d
--- /dev/null
+++ b/moonsource-legadorule.koplugin/moonsource_legadorule/parser.lua
@@ -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
diff --git a/moonsource-legadorule.koplugin/moonsource_legadorule/regex.lua b/moonsource-legadorule.koplugin/moonsource_legadorule/regex.lua
new file mode 100644
index 0000000..b9357a3
--- /dev/null
+++ b/moonsource-legadorule.koplugin/moonsource_legadorule/regex.lua
@@ -0,0 +1,540 @@
+--[[--
+Java 风格正则(回溯匹配,按 Unicode 码点)。Legado 规则里的 ## 替换、: 正则规则、$1 取组都走这里。
+支持:字符类(含 \uXXXX、汉字区间)、分组(捕获 / 非捕获 / 命名)、| 、* + ? {n,m} 及惰性、^ $ \b \A \z、
+前后向断言、反向引用、\d\w\s、(?i)(?s)(?m)。不支持 Unicode 属性类与集合交集。
+
+@module moonsource_legadorule.regex
+--]]
+
+local Regex = {}
+
+local function decode(s)
+ local cps, pos, n, i, len = {}, {}, 0, 1, #s
+ local byte = string.byte
+ while i <= len do
+ local c, l, cp = byte(s, i), 1, nil
+ if c < 0x80 then
+ cp = c
+ elseif c >= 0xF0 then
+ cp = (c % 8) * 0x40000 + ((byte(s, i + 1) or 128) % 64) * 0x1000
+ + ((byte(s, i + 2) or 128) % 64) * 64 + (byte(s, i + 3) or 128) % 64
+ l = 4
+ elseif c >= 0xE0 then
+ cp = (c % 16) * 0x1000 + ((byte(s, i + 1) or 128) % 64) * 64 + (byte(s, i + 2) or 128) % 64
+ l = 3
+ elseif c >= 0xC0 then
+ cp = (c % 32) * 64 + (byte(s, i + 1) or 128) % 64
+ l = 2
+ else
+ cp = c
+ end
+ n = n + 1
+ cps[n], pos[n] = cp, i
+ i = i + l
+ end
+ pos[n + 1] = len + 1
+ return cps, pos, n
+end
+
+local function encode(cp)
+ 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 / 0x1000), 0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
+ end
+ return string.char(0xF0 + math.floor(cp / 0x40000), 0x80 + math.floor(cp / 0x1000) % 64,
+ 0x80 + math.floor(cp / 64) % 64, 0x80 + cp % 64)
+end
+
+local function isDigit(c) return c >= 48 and c <= 57 end
+local function isWord(c)
+ return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
+end
+local function isSpace(c) return c == 32 or (c >= 9 and c <= 13) or c == 0xA0 or c == 0x3000 end
+local function fold(c) if c >= 65 and c <= 90 then return c + 32 end return c end
+
+local CLASS = {
+ d = isDigit, w = isWord, s = isSpace,
+ D = function(c) return not isDigit(c) end,
+ W = function(c) return not isWord(c) end,
+ S = function(c) return not isSpace(c) end,
+}
+
+---------------------------------------------------------------- 解析
+
+local Parser = {}
+Parser.__index = Parser
+
+local function perr(msg) error("regex: " .. msg, 0) end
+
+function Parser:peek() return self.p[self.i] end
+
+function Parser:escape()
+ local c = self.p[self.i]
+ self.i = self.i + 1
+ if not c then perr("dangling backslash") end
+ local ch = encode(c)
+ if CLASS[ch] then return { class = CLASS[ch] } end
+ if ch == "n" then return { cp = 10 } end
+ if ch == "t" then return { cp = 9 } end
+ if ch == "r" then return { cp = 13 } end
+ if ch == "f" then return { cp = 12 } end
+ if ch == "u" then
+ local hex = ""
+ for _ = 1, 4 do hex = hex .. encode(self.p[self.i] or 48); self.i = self.i + 1 end
+ return { cp = tonumber(hex, 16) or 0 }
+ end
+ if ch == "x" then
+ local hex = ""
+ for _ = 1, 2 do hex = hex .. encode(self.p[self.i] or 48); self.i = self.i + 1 end
+ return { cp = tonumber(hex, 16) or 0 }
+ end
+ return { cp = c, esc = ch }
+end
+
+function Parser:set()
+ local neg = false
+ if self:peek() == 94 then neg = true; self.i = self.i + 1 end
+ local items, first = {}, true
+ while true do
+ local c = self:peek()
+ if not c then perr("unclosed [") end
+ self.i = self.i + 1
+ if c == 93 and not first then break end
+ first = false
+ local item
+ if c == 92 then
+ item = self:escape()
+ if item.esc == "b" then item = { cp = 8 } end
+ elseif c == 91 then
+ -- 嵌套集合按并集处理
+ local inner = self:set()
+ item = { class = inner.test }
+ else
+ item = { cp = c }
+ end
+ if item.cp and self:peek() == 45 and self.p[self.i + 1] and self.p[self.i + 1] ~= 93 then
+ self.i = self.i + 1
+ local hi = self:peek()
+ self.i = self.i + 1
+ if hi == 92 then hi = self:escape().cp end
+ items[#items + 1] = { lo = item.cp, hi = hi }
+ elseif item.cp then
+ items[#items + 1] = { lo = item.cp, hi = item.cp }
+ else
+ items[#items + 1] = { class = item.class }
+ end
+ end
+ local icase = self.flags.i
+ local function raw(c)
+ for k = 1, #items do
+ local it = items[k]
+ if it.class then
+ if it.class(c) then return true end
+ elseif c >= it.lo and c <= it.hi then
+ return true
+ end
+ end
+ return false
+ end
+ local function test(c)
+ local hit = raw(c)
+ if not hit and icase then
+ if c >= 97 and c <= 122 then hit = raw(c - 32) elseif c >= 65 and c <= 90 then hit = raw(c + 32) end
+ end
+ return hit ~= neg
+ end
+ return { type = "set", test = test }
+end
+
+function Parser:int()
+ local s = ""
+ while self:peek() and isDigit(self:peek()) do s = s .. encode(self:peek()); self.i = self.i + 1 end
+ return tonumber(s)
+end
+
+function Parser:atom()
+ local c = self.p[self.i]
+ self.i = self.i + 1
+ if c == 40 then -- (
+ local node
+ if self:peek() == 63 then
+ self.i = self.i + 1
+ local d = self:peek()
+ self.i = self.i + 1
+ if d == 58 then
+ node = { type = "group", n = self:alt() }
+ elseif d == 61 or d == 33 then
+ node = { type = "look", neg = d == 33, n = self:alt() }
+ elseif d == 60 and (self:peek() == 61 or self:peek() == 33) then
+ local neg = self:peek() == 33
+ self.i = self.i + 1
+ node = { type = "lookbehind", neg = neg, n = self:alt() }
+ elseif d == 60 or d == 80 then
+ if d == 80 then self.i = self.i + 1 end
+ local name = ""
+ while self:peek() and self:peek() ~= 62 do name = name .. encode(self:peek()); self.i = self.i + 1 end
+ self.i = self.i + 1
+ self.ngroups = self.ngroups + 1
+ local idx = self.ngroups
+ self.names[name] = idx
+ node = { type = "cap", idx = idx, n = self:alt() }
+ else
+ -- 行内标志 (?i) (?s:...)
+ self.i = self.i - 1
+ local on = true
+ while self:peek() and self:peek() ~= 41 and self:peek() ~= 58 do
+ local f = encode(self:peek())
+ if f == "-" then on = false else self.flags[f] = on or nil end
+ self.i = self.i + 1
+ end
+ if self:peek() == 41 then
+ self.i = self.i + 1
+ return { type = "empty" }
+ end
+ self.i = self.i + 1
+ node = { type = "group", n = self:alt() }
+ end
+ else
+ self.ngroups = self.ngroups + 1
+ local idx = self.ngroups
+ node = { type = "cap", idx = idx, n = self:alt() }
+ end
+ if self:peek() ~= 41 then perr("unclosed (") end
+ self.i = self.i + 1
+ return node
+ elseif c == 91 then
+ return self:set()
+ elseif c == 46 then
+ return { type = "any", dotall = self.flags.s }
+ elseif c == 94 then
+ return { type = "bol", multi = self.flags.m }
+ elseif c == 36 then
+ return { type = "eol", multi = self.flags.m }
+ elseif c == 92 then
+ local e = self:escape()
+ if e.class then return { type = "set", test = e.class } end
+ local ch = e.esc
+ if ch == "b" then return { type = "wordb" } end
+ if ch == "B" then return { type = "wordb", neg = true } end
+ if ch == "A" then return { type = "bol" } end
+ if ch == "z" or ch == "Z" then return { type = "eol" } end
+ if ch and isDigit(e.cp) and ch ~= "0" then return { type = "backref", idx = tonumber(ch), icase = self.flags.i } end
+ return { type = "char", cp = e.cp, icase = self.flags.i }
+ end
+ return { type = "char", cp = c, icase = self.flags.i }
+end
+
+function Parser:quant(node)
+ local c = self:peek()
+ local min, max
+ if c == 42 then min, max = 0, math.huge
+ elseif c == 43 then min, max = 1, math.huge
+ elseif c == 63 then min, max = 0, 1
+ elseif c == 123 then
+ local save = self.i
+ self.i = self.i + 1
+ local a = self:int()
+ local b = a
+ if a and self:peek() == 44 then
+ self.i = self.i + 1
+ b = self:int() or math.huge
+ end
+ if not a or self:peek() ~= 125 then
+ self.i = save
+ return node
+ end
+ min, max = a, b
+ else
+ return node
+ end
+ self.i = self.i + 1
+ local lazy = false
+ if self:peek() == 63 then lazy = true; self.i = self.i + 1 elseif self:peek() == 43 then self.i = self.i + 1 end
+ return self:quant({ type = "rep", n = node, min = min, max = max, lazy = lazy })
+end
+
+function Parser:seq()
+ local list = {}
+ while true do
+ local c = self:peek()
+ if not c or c == 124 or c == 41 then break end
+ local atom = self:atom()
+ if c == 42 or c == 43 or c == 63 then perr("dangling quantifier") end
+ list[#list + 1] = self:quant(atom)
+ end
+ return { type = "seq", list = list }
+end
+
+function Parser:alt()
+ local branches = { self:seq() }
+ while self:peek() == 124 do
+ self.i = self.i + 1
+ branches[#branches + 1] = self:seq()
+ end
+ if #branches == 1 then return branches[1] end
+ return { type = "alt", list = branches }
+end
+
+---------------------------------------------------------------- 编译成闭包
+
+local compile
+
+local function single(node)
+ local t = node.type
+ if t == "char" then
+ local cp = node.cp
+ if node.icase then
+ local f = fold(cp)
+ return function(c) return fold(c) == f end
+ end
+ return function(c) return c == cp end
+ elseif t == "any" then
+ if node.dotall then return function() return true end end
+ return function(c) return c ~= 10 and c ~= 13 end
+ elseif t == "set" then
+ return node.test
+ end
+end
+
+function compile(node, nxt)
+ local t = node.type
+ local test = single(node)
+ if test then
+ return function(S, i)
+ local c = S.c[i]
+ if c and test(c) then return nxt(S, i + 1) end
+ end
+ elseif t == "empty" then
+ return nxt
+ elseif t == "seq" then
+ local m = nxt
+ for k = #node.list, 1, -1 do m = compile(node.list[k], m) end
+ return m
+ elseif t == "group" then
+ return compile(node.n, nxt)
+ elseif t == "alt" then
+ local ms = {}
+ for k, b in ipairs(node.list) do ms[k] = compile(b, nxt) end
+ return function(S, i)
+ for k = 1, #ms do
+ local r = ms[k](S, i)
+ if r then return r end
+ end
+ end
+ elseif t == "cap" then
+ local idx = node.idx
+ local inner = compile(node.n, function(S, i)
+ local os, oe = S.s[idx], S.e[idx]
+ S.s[idx], S.e[idx] = S.ts[idx], i
+ local r = nxt(S, i)
+ if not r then S.s[idx], S.e[idx] = os, oe end
+ return r
+ end)
+ return function(S, i)
+ local old = S.ts[idx]
+ S.ts[idx] = i
+ local r = inner(S, i)
+ if not r then S.ts[idx] = old end
+ return r
+ end
+ elseif t == "rep" then
+ local min, max, lazy = node.min, node.max, node.lazy
+ local one = single(node.n)
+ if one then
+ return function(S, i)
+ local c, n = S.c, 0
+ if lazy then
+ while n < min do
+ local x = c[i + n]
+ if not (x and one(x)) then return end
+ n = n + 1
+ end
+ while true do
+ local r = nxt(S, i + n)
+ if r then return r end
+ local x = c[i + n]
+ if n >= max or not (x and one(x)) then return end
+ n = n + 1
+ end
+ end
+ while n < max do
+ local x = c[i + n]
+ if not (x and one(x)) then break end
+ n = n + 1
+ end
+ while n >= min do
+ local r = nxt(S, i + n)
+ if r then return r end
+ n = n - 1
+ end
+ end
+ end
+ local body = compile(node.n, function(S, j)
+ local k = S.ks[S.kn]
+ S.kn = S.kn - 1
+ local r = k(S, j)
+ S.kn = S.kn + 1
+ S.ks[S.kn] = k
+ return r
+ end)
+ local function try(S, i, count)
+ local function more()
+ if count >= max then return end
+ local k = function(S2, j)
+ if j == i and count >= min then return end
+ return try(S2, j, count + 1)
+ end
+ S.kn = S.kn + 1
+ S.ks[S.kn] = k
+ local r = body(S, i)
+ if not r then S.kn = S.kn - 1 end
+ return r
+ end
+ if lazy then
+ if count >= min then
+ local r = nxt(S, i)
+ if r then return r end
+ end
+ return more()
+ end
+ local r = more()
+ if r then return r end
+ if count >= min then return nxt(S, i) end
+ end
+ return function(S, i) return try(S, i, 0) end
+ elseif t == "bol" then
+ return function(S, i)
+ if i == 1 or (node.multi and S.c[i - 1] == 10) then return nxt(S, i) end
+ end
+ elseif t == "eol" then
+ return function(S, i)
+ local n = S.n
+ if i == n + 1 or (i == n and S.c[i] == 10) or (node.multi and S.c[i] == 10) then return nxt(S, i) end
+ end
+ elseif t == "wordb" then
+ return function(S, i)
+ local a = i > 1 and isWord(S.c[i - 1])
+ local b = S.c[i] and isWord(S.c[i])
+ if ((a and not b) or (b and not a)) ~= (node.neg or false) then return nxt(S, i) end
+ end
+ elseif t == "backref" then
+ local idx = node.idx
+ return function(S, i)
+ local s, e = S.s[idx], S.e[idx]
+ if not s then return end
+ local len = e - s
+ for k = 0, len - 1 do
+ local a, b = S.c[s + k], S.c[i + k]
+ if not b or (a ~= b and not (node.icase and fold(a) == fold(b))) then return end
+ end
+ return nxt(S, i + len)
+ end
+ elseif t == "look" then
+ local sub = compile(node.n, function(_, i) return i end)
+ return function(S, i)
+ if (sub(S, i) ~= nil) ~= node.neg then return nxt(S, i) end
+ end
+ elseif t == "lookbehind" then
+ local sub = compile(node.n, function(S, j) if j == S.target then return j end end)
+ return function(S, i)
+ local hit = false
+ local old = S.target
+ S.target = i
+ for st = i, 1, -1 do
+ if sub(S, st) then hit = true; break end
+ end
+ S.target = old
+ if hit ~= node.neg then return nxt(S, i) end
+ end
+ end
+ error("regex: bad node " .. tostring(t))
+end
+
+---------------------------------------------------------------- 对外接口
+
+local cache = {}
+
+--- 编译;同一 pattern 缓存。语法错误抛错。
+function Regex.compile(pattern)
+ local hit = cache[pattern]
+ if hit then return hit end
+ local p = decode(pattern)
+ local parser = setmetatable({ p = p, i = 1, flags = {}, ngroups = 0, names = {} }, Parser)
+ local ast = parser:alt()
+ if parser.i <= #p then perr("unmatched )") end
+ local re = {
+ ngroups = parser.ngroups,
+ names = parser.names,
+ run = compile(ast, function(_, i) return i end),
+ }
+ cache[pattern] = re
+ return re
+end
+
+local function exec(re, subject, from)
+ local S = subject
+ for st = from, S.n + 1 do
+ S.s, S.e, S.ts, S.ks, S.kn = {}, {}, {}, {}, 0
+ local stop = re.run(S, st)
+ if stop then
+ local m = { s = S.pos[st], e = S.pos[stop], cs = st, ce = stop }
+ m[0] = S.str:sub(m.s, m.e - 1)
+ for g = 1, re.ngroups do
+ if S.s[g] then m[g] = S.str:sub(S.pos[S.s[g]], S.pos[S.e[g]] - 1) end
+ end
+ return m
+ end
+ end
+end
+
+local function prepare(str)
+ local cps, pos, n = decode(str)
+ return { c = cps, pos = pos, n = n, str = str }
+end
+
+--- 首个匹配;返回 m(m[0] 整体,m[1..] 各组,m.s/m.e 为字节区间 [s,e)),无匹配返回 nil。
+function Regex.find(pattern, str)
+ return exec(Regex.compile(pattern), prepare(str), 1)
+end
+
+--- 所有不重叠匹配。
+function Regex.all(pattern, str)
+ local re, S, out, from = Regex.compile(pattern), prepare(str), {}, 1
+ while from <= S.n + 1 do
+ local m = exec(re, S, from)
+ if not m then break end
+ out[#out + 1] = m
+ from = m.ce > m.cs and m.ce or m.ce + 1
+ end
+ return out
+end
+
+--- 展开替换串里的 $n;\$ 取字面量。
+local function expand(repl, m)
+ return (repl:gsub("(\\?)%$(%d)", function(esc, d)
+ if esc == "\\" then return "$" .. d end
+ return m[tonumber(d)] or ""
+ end))
+end
+
+--- 替换(只首个或全部)。replacement 里 $1 引用组。
+function Regex.replace(pattern, str, repl, first)
+ local ms = first and { Regex.find(pattern, str) } or Regex.all(pattern, str)
+ if #ms == 0 then return str end
+ local out, last = {}, 1
+ for _, m in ipairs(ms) do
+ out[#out + 1] = str:sub(last, m.s - 1)
+ out[#out + 1] = expand(repl, m)
+ last = m.e
+ end
+ out[#out + 1] = str:sub(last)
+ return table.concat(out)
+end
+
+--- 是否整串之内含匹配。
+function Regex.test(pattern, str)
+ return Regex.find(pattern, str) ~= nil
+end
+
+return Regex
diff --git a/moonsource-legadorule.koplugin/moonsource_legadorule/rule.lua b/moonsource-legadorule.koplugin/moonsource_legadorule/rule.lua
new file mode 100644
index 0000000..6e33b2e
--- /dev/null
+++ b/moonsource-legadorule.koplugin/moonsource_legadorule/rule.lua
@@ -0,0 +1,990 @@
+--[[--
+书源规则求值器(Legado AnalyzeRule 的移植):默认 JSoup 风格、@CSS:、XPath、JsonPath、`:` 正则列表模式,
+加上 @put / @get、`{{ }}` 取值、`$1` 组引用与 `##正则##替换`。含 JS 的规则抛 Unsupported。
+
+内容(content)可以是 HTML / JSON 文本、DOM 节点、JSON 值或正则行(含 [0..n] 的表)。
+
+@module moonsource_legadorule.rule
+--]]
+
+local Regex = require("moonsource_legadorule.regex")
+local Json = require("moonsource_legadorule.json")
+local Html = require("moonsource_legadorule.html")
+local Css = require("moonsource_legadorule.css")
+local XPath = require("moonsource_legadorule.xpath")
+local JsonPath = require("moonsource_legadorule.jsonpath")
+local Url = require("moonsource_legadorule.url")
+local Unsupported = require("moonsource_legadorule.unsupported")
+
+local Rule = {}
+Rule.__index = Rule
+
+local MODE_DEFAULT, MODE_XPATH, MODE_JSON, MODE_REGEX = "default", "xpath", "json", "regex"
+
+local function trim(s) return (s:gsub("^%s+", ""):gsub("%s+$", "")) end
+
+local function isDom(v) return type(v) == "table" and (v.type == "el" or v.type == "doc") end
+
+local function explode(s, sep)
+ local out, start = {}, 1
+ while true do
+ local i, e = s:find(sep, start, true)
+ if not i then break end
+ out[#out + 1] = s:sub(start, i - 1)
+ start = e + 1
+ end
+ out[#out + 1] = s:sub(start)
+ return out
+end
+
+---------------------------------------------------------------- 规则切分(RuleAnalyzer)
+
+--- 在不处于 [] () 与其中引号内的位置,按 seps 切分;以首个出现的分隔符为准。
+--- 返回 parts, 分隔符(没出现为 "")。
+local function splitTop(s, seps)
+ local parts, start, etype = {}, 1, ""
+ local stack, quote = 0, nil
+ local i, n = 1, #s
+ while i <= n do
+ local c = s:sub(i, i)
+ if quote then
+ if c == "\\" then i = i + 1 elseif c == quote then quote = nil end
+ elseif stack > 0 then
+ if c == "'" or c == '"' then quote = c
+ elseif c == "[" or c == "(" then stack = stack + 1
+ elseif c == "]" or c == ")" then stack = stack - 1
+ elseif c == "\\" then i = i + 1 end
+ elseif c == "[" or c == "(" then
+ stack = 1
+ else
+ for _, sep in ipairs(seps) do
+ if (etype == "" or etype == sep) and s:sub(i, i + #sep - 1) == sep then
+ etype = sep
+ parts[#parts + 1] = s:sub(start, i - 1)
+ i = i + #sep - 1
+ start = i + 1
+ break
+ end
+ end
+ end
+ i = i + 1
+ end
+ parts[#parts + 1] = s:sub(start)
+ return parts, etype
+end
+
+local function merge(results, etype)
+ local out = {}
+ if etype == "%%" then
+ for i = 1, #(results[1] or {}) do
+ for _, list in ipairs(results) do
+ if list[i] ~= nil then out[#out + 1] = list[i] end
+ end
+ end
+ else
+ for _, list in ipairs(results) do
+ for _, item in ipairs(list) do out[#out + 1] = item end
+ end
+ end
+ return out
+end
+
+---------------------------------------------------------------- JSoup 默认模式
+
+local function cssSelect(node, selector)
+ local ok, list = pcall(Css.select, node, selector)
+ return ok and list or {}
+end
+
+local function children(node)
+ local out = {}
+ for _, c in ipairs(node.children or {}) do
+ if c.type == "el" then out[#out + 1] = c end
+ end
+ return out
+end
+
+local function descendants(node)
+ local out = {}
+ local function walk(n)
+ for _, c in ipairs(n.children or {}) do
+ if c.type == "el" then
+ out[#out + 1] = c
+ walk(c)
+ end
+ end
+ end
+ walk(node)
+ return out
+end
+
+-- jsoup 的 getElementsBy* 把根元素自己也算进去
+local function withSelf(node)
+ local out = descendants(node)
+ if node.type == "el" then table.insert(out, 1, node) end
+ return out
+end
+
+--- 解析 `name.0` `name!0` `name[0,-1]` `name[1:3:2]` `name[!0]` 这类尾部下标。
+local function findIndexSet(rule)
+ local rus = trim(rule)
+ local len = #rus
+ local curMinus, curList, l = false, {}, ""
+ local indexDefault, indexes = {}, {}
+ local split, beforeRule = " ", rus
+ local function ch(i) return rus:sub(i + 1, i + 1) end
+ local isDigit = function(c) return c ~= "" and c >= "0" and c <= "9" end
+
+ if len > 0 and ch(len - 1) == "]" then
+ len = len - 1
+ while true do
+ len = len - 1
+ if len < -1 then break end
+ local rl = len >= 0 and ch(len) or "["
+ if rl == " " and len >= 0 then
+ -- skip
+ elseif len >= 0 and isDigit(rl) then
+ l = rl .. l
+ elseif len >= 0 and rl == "-" then
+ curMinus = true
+ else
+ local curInt = false
+ if l ~= "" then curInt = curMinus and -tonumber(l) or tonumber(l) end
+ local done = false
+ if rl == ":" then
+ curList[#curList + 1] = curInt
+ else
+ if #curList == 0 then
+ if curInt == false then break end
+ indexes[#indexes + 1] = curInt
+ else
+ indexes[#indexes + 1] = {
+ s = curInt or nil, e = curList[#curList] or nil,
+ step = #curList == 2 and curList[1] or 1,
+ }
+ curList = {}
+ end
+ if rl == "!" then
+ split = "!"
+ repeat
+ len = len - 1
+ rl = len >= 0 and ch(len) or "["
+ until not (len > 0 and rl == " ")
+ end
+ if rl == "[" then
+ return rus:sub(1, math.max(0, len)), split, indexDefault, indexes
+ end
+ if rl ~= "," then done = true end
+ end
+ if done then break end
+ l, curMinus = "", false
+ end
+ end
+ else
+ while true do
+ len = len - 1
+ if len < 0 then break end
+ local rl = ch(len)
+ if rl == " " then
+ -- skip
+ elseif isDigit(rl) then
+ l = rl .. l
+ elseif rl == "-" then
+ curMinus = true
+ elseif rl == "!" or rl == "." or rl == ":" then
+ if l == "" then break end
+ indexDefault[#indexDefault + 1] = curMinus and -tonumber(l) or tonumber(l)
+ if rl ~= ":" then
+ return rus:sub(1, len), rl, indexDefault, indexes
+ end
+ l, curMinus = "", false
+ else
+ break
+ end
+ end
+ split, beforeRule = " ", rus
+ end
+ return beforeRule, split, indexDefault, indexes
+end
+
+local function elementsSingle(node, rule)
+ local beforeRule, split, indexDefault, indexes = findIndexSet(rule)
+ local elements
+ if beforeRule == "" then
+ elements = children(node)
+ else
+ local rules = explode(beforeRule, ".")
+ local head, arg = rules[1], rules[2] or ""
+ if head == "children" then
+ elements = children(node)
+ elseif head == "class" then
+ elements = {}
+ for _, el in ipairs(withSelf(node)) do
+ local v = el.attrs.class
+ if v and (" " .. v:gsub("%s+", " ") .. " "):find(" " .. arg .. " ", 1, true) then
+ elements[#elements + 1] = el
+ end
+ end
+ elseif head == "tag" then
+ elements = {}
+ arg = arg:lower()
+ for _, el in ipairs(withSelf(node)) do
+ if el.tag == arg then elements[#elements + 1] = el end
+ end
+ elseif head == "id" then
+ elements = {}
+ for _, el in ipairs(withSelf(node)) do
+ if el.attrs.id == arg then elements[#elements + 1] = el end
+ end
+ elseif head == "text" then
+ elements = {}
+ for _, el in ipairs(withSelf(node)) do
+ if Html.ownText(el):find(arg, 1, true) then elements[#elements + 1] = el end
+ end
+ else
+ elements = cssSelect(node, beforeRule)
+ end
+ end
+
+ local count = #elements
+ local order, set = {}, {}
+ local function add(i)
+ if not set[i] then set[i] = true; order[#order + 1] = i end
+ end
+ local function addIndex(it)
+ if it >= 0 and it < count then add(it)
+ elseif it < 0 and count >= -it then add(it + count) end
+ end
+ if #indexes == 0 then
+ for k = #indexDefault, 1, -1 do addIndex(indexDefault[k]) end
+ else
+ for k = #indexes, 1, -1 do
+ local item = indexes[k]
+ if type(item) == "table" then
+ local start = item.s or 0
+ if start < 0 then start = start + count end
+ local stop = item.e or (count - 1)
+ if stop < 0 then stop = stop + count end
+ if not ((start < 0 and stop < 0) or (start >= count and stop >= count)) then
+ start = math.min(math.max(start, 0), count - 1)
+ stop = math.min(math.max(stop, 0), count - 1)
+ local step = item.step
+ if step <= 0 then step = (step < 0 and -step < count) and step + count or 1 end
+ if start == stop or step >= count then
+ add(start)
+ elseif stop > start then
+ for i = start, stop, step do add(i) end
+ else
+ for i = start, stop, -step do add(i) end
+ end
+ end
+ else
+ addIndex(item)
+ end
+ end
+ end
+
+ if split == " " then return elements end
+ if split == "!" then
+ table.sort(order, function(a, b) return a > b end)
+ for _, i in ipairs(order) do table.remove(elements, i + 1) end
+ return elements
+ end
+ local out = {}
+ for _, i in ipairs(order) do
+ if elements[i + 1] then out[#out + 1] = elements[i + 1] end
+ end
+ return out
+end
+
+local function resultLast(elements, lastRule)
+ local out = {}
+ if lastRule == "text" then
+ for _, el in ipairs(elements) do
+ local t = Html.text(el)
+ if t ~= "" then out[#out + 1] = t end
+ end
+ elseif lastRule == "textNodes" then
+ for _, el in ipairs(elements) do
+ local t = Html.textNodes(el)
+ if t ~= "" then out[#out + 1] = t end
+ end
+ elseif lastRule == "ownText" then
+ for _, el in ipairs(elements) do
+ local t = Html.ownText(el)
+ if t ~= "" then out[#out + 1] = t end
+ end
+ elseif lastRule == "html" then
+ local buf = {}
+ for _, el in ipairs(elements) do buf[#buf + 1] = el.type == "el" and "<" .. el.tag .. ">" == nil and "" or Html.cleanInner(el) end
+ local joined = table.concat(buf)
+ if joined ~= "" then out[1] = joined end
+ elseif lastRule == "all" then
+ local buf = {}
+ for _, el in ipairs(elements) do buf[#buf + 1] = Html.outer(el) end
+ local joined = table.concat(buf)
+ if joined ~= "" then out[1] = joined end
+ else
+ local attr = lastRule:sub(1, 4) == "abs:" and lastRule:sub(5) or lastRule
+ local seen = {}
+ for _, el in ipairs(elements) do
+ local v = el.type == "el" and el.attrs[attr] or nil
+ if v and v ~= "" and not seen[v] then
+ seen[v] = true
+ out[#out + 1] = v
+ end
+ end
+ end
+ return out
+end
+
+local function parseSourceRule(ruleStr)
+ if ruleStr:sub(1, 5):lower() == "@css:" then return true, trim(ruleStr:sub(6)) end
+ return false, ruleStr
+end
+
+local getElementsOf
+
+local function getResultList(node, ruleStr)
+ if ruleStr == "" then return nil end
+ local rules = splitTop((ruleStr:gsub("^[@%s]+", "")), { "@" })
+ local elements = { node }
+ for i = 1, #rules - 1 do
+ local es = {}
+ for _, el in ipairs(elements) do
+ for _, item in ipairs(elementsSingle(el, rules[i])) do es[#es + 1] = item end
+ end
+ elements = es
+ end
+ if #elements == 0 then return nil end
+ return resultLast(elements, rules[#rules])
+end
+
+local function jsoupStringList(node, ruleStr)
+ if ruleStr == "" then return {} end
+ local isCss, rule = parseSourceRule(ruleStr)
+ if rule == "" then return { Html.textContent(node) } end
+ local parts, etype = splitTop(rule, { "&&", "||", "%%" })
+ local results = {}
+ for _, part in ipairs(parts) do
+ local temp
+ if isCss then
+ local at
+ for i = #part, 1, -1 do
+ if part:sub(i, i) == "@" then at = i break end
+ end
+ if not at then
+ temp = resultLast(cssSelect(node, part), "text")
+ else
+ temp = resultLast(cssSelect(node, part:sub(1, at - 1)), part:sub(at + 1))
+ end
+ else
+ temp = getResultList(node, part)
+ end
+ if temp and #temp > 0 then
+ results[#results + 1] = temp
+ if etype == "||" then break end
+ end
+ end
+ return merge(results, etype)
+end
+
+function getElementsOf(node, rule)
+ if rule == "" then return {} end
+ local isCss, body = parseSourceRule(rule)
+ local parts, etype = splitTop(body, { "&&", "||", "%%" })
+ local lists = {}
+ for _, part in ipairs(parts) do
+ local el
+ if isCss then
+ el = cssSelect(node, part)
+ else
+ local rs = splitTop((part:gsub("^[@%s]+", "")), { "@" })
+ if #rs > 1 then
+ el = { node }
+ for _, rl in ipairs(rs) do
+ local es = {}
+ for _, et in ipairs(el) do
+ for _, item in ipairs(getElementsOf(et, rl)) do es[#es + 1] = item end
+ end
+ el = es
+ end
+ else
+ el = elementsSingle(node, part)
+ end
+ end
+ lists[#lists + 1] = el
+ if #el > 0 and etype == "||" then break end
+ end
+ return merge(lists, etype)
+end
+
+---------------------------------------------------------------- XPath
+
+local function xpathQuery(node, expr)
+ expr = trim(expr)
+ if node.type == "el" and expr:sub(1, 2) == "//" then expr = "." .. expr end
+ local ok, v, isNodes = pcall(XPath.evaluate, node, expr)
+ if not ok then return nil end
+ return v, isNodes
+end
+
+local function nodeString(n)
+ if n.type == "attr" then return n.value end
+ if n.type == "text" then return n.text end
+ return trim(Html.textContent(n))
+end
+
+local function xpathElements(node, xpath)
+ if xpath == "" then return {} end
+ local rules, etype = splitTop(xpath, { "&&", "||", "%%" })
+ if #rules == 1 then
+ local v, isNodes = xpathQuery(node, rules[1])
+ if not isNodes then return {} end
+ local out = {}
+ for k, n in ipairs(v) do out[k] = n end
+ return out
+ end
+ local lists = {}
+ for _, rl in ipairs(rules) do
+ local temp = xpathElements(node, rl)
+ if #temp > 0 then
+ lists[#lists + 1] = temp
+ if etype == "||" then break end
+ end
+ end
+ return merge(lists, etype)
+end
+
+local function xpathValues(node, expr)
+ local v, isNodes = xpathQuery(node, expr)
+ if v == nil then return {} end
+ local out = {}
+ if isNodes then
+ for _, n in ipairs(v) do out[#out + 1] = nodeString(n) end
+ elseif type(v) == "boolean" then
+ out[1] = tostring(v)
+ else
+ local s = XPath.toStr(v)
+ if s ~= "" then out[1] = s end
+ end
+ return out
+end
+
+local function xpathString(node, rule)
+ local rules, etype = splitTop(rule, { "&&", "||" })
+ if #rules == 1 then
+ local vals = xpathValues(node, rule)
+ if #vals == 0 then return nil end
+ return table.concat(vals, "\n")
+ end
+ local out = {}
+ for _, rl in ipairs(rules) do
+ local temp = xpathString(node, rl)
+ if temp and temp ~= "" then
+ out[#out + 1] = temp
+ if etype == "||" then break end
+ end
+ end
+ return table.concat(out, "\n")
+end
+
+---------------------------------------------------------------- JsonPath
+
+local function jsonRead(data, path)
+ path = trim(path)
+ if path == "" or path == "$" then return data end
+ if path:sub(1, 1) ~= "$" then path = "$." .. path end
+ local ok, values, definite = pcall(JsonPath.read, data, path)
+ if not ok then return nil end
+ if definite then return values[1] end
+ local arr = Json.newArray()
+ for k, v in ipairs(values) do arr[k] = v end
+ return arr
+end
+
+local function innerRuleCode(rule, fn)
+ local out, start, pos = {}, 1, 1
+ local found = false
+ while true do
+ local s = rule:find("{$.", pos, true)
+ if not s then break end
+ local depth, i, quote = 0, s, nil
+ local closeAt
+ while i <= #rule do
+ local c = rule:sub(i, i)
+ if quote then
+ if c == "\\" then i = i + 1 elseif c == quote then quote = nil end
+ elseif c == "'" or c == '"' then quote = c
+ elseif c == "{" then depth = depth + 1
+ elseif c == "}" then
+ depth = depth - 1
+ if depth == 0 then closeAt = i break end
+ end
+ i = i + 1
+ end
+ local value = closeAt and fn(rule:sub(s + 1, closeAt - 1))
+ if value and value ~= "" then
+ out[#out + 1] = rule:sub(start, s - 1) .. value
+ start, pos, found = closeAt + 1, closeAt + 1, true
+ else
+ pos = s + 3
+ end
+ end
+ if not found then return "" end
+ return table.concat(out) .. rule:sub(start)
+end
+
+local jsonString, jsonStringList
+
+function jsonString(data, rule)
+ if rule == "" then return nil end
+ local rules, etype = splitTop(rule, { "&&", "||" })
+ if #rules == 1 then
+ local embedded = innerRuleCode(rule, function(inner) return jsonString(data, inner) end)
+ if embedded ~= "" then return embedded end
+ return JsonPath.stringify(jsonRead(data, rule))
+ end
+ local list = {}
+ for _, rl in ipairs(rules) do
+ local temp = jsonString(data, rl)
+ if temp and temp ~= "" then
+ list[#list + 1] = temp
+ if etype == "||" then break end
+ end
+ end
+ return table.concat(list, "\n")
+end
+
+local function jsonList(data, rule)
+ if rule == "" then return {} end
+ local rules, etype = splitTop(rule, { "&&", "||", "%%" })
+ if #rules == 1 then
+ local val = jsonRead(data, rules[1])
+ if val == nil or val == Json.null then return {} end
+ if Json.isArray(val) then
+ local out = {}
+ for k, v in ipairs(val) do out[k] = v end
+ return out
+ end
+ return { val }
+ end
+ local lists = {}
+ for _, rl in ipairs(rules) do
+ local temp = jsonList(data, rl)
+ if #temp > 0 then
+ lists[#lists + 1] = temp
+ if etype == "||" then break end
+ end
+ end
+ return merge(lists, etype)
+end
+
+---------------------------------------------------------------- 正则列表模式
+
+local function regexRow(m, ngroups)
+ local row = { [0] = m[0] }
+ for g = 1, ngroups do row[g] = m[g] or "" end
+ return row
+end
+
+local function regexElements(res, regs, index)
+ index = index or 1
+ local pat = regs[index]
+ if not pat or pat == "" then return {} end
+ local ok, ms = pcall(Regex.all, pat, res)
+ if not ok or #ms == 0 then return {} end
+ if index == #regs then
+ local re = Regex.compile(pat)
+ local rows = {}
+ for k, m in ipairs(ms) do rows[k] = regexRow(m, re.ngroups) end
+ return rows
+ end
+ local all = {}
+ for _, m in ipairs(ms) do all[#all + 1] = m[0] end
+ return regexElements(table.concat(all), regs, index + 1)
+end
+
+---------------------------------------------------------------- SourceRule
+
+local function splitRegexPart(sr, ruleStr)
+ local first = explode(ruleStr, "##")[1]
+ local start = 1
+ local ms = Regex.all("\\$\\d{1,2}", first)
+ if #ms > 0 then
+ sr.mode = MODE_REGEX
+ for _, m in ipairs(ms) do
+ if m.s > start then
+ sr.types[#sr.types + 1] = 0
+ sr.params[#sr.params + 1] = ruleStr:sub(start, m.s - 1)
+ end
+ sr.types[#sr.types + 1] = tonumber(m[0]:sub(2))
+ sr.params[#sr.params + 1] = m[0]
+ start = m.e
+ end
+ end
+ if #ruleStr >= start then
+ sr.types[#sr.types + 1] = 0
+ sr.params[#sr.params + 1] = ruleStr:sub(start)
+ end
+end
+
+local GET_RULE, JS_RULE = -2, -1
+
+local function newSourceRule(ruleStr, mode, isJSON)
+ local sr = { mode = mode, putMap = {}, params = {}, types = {}, replaceRegex = "", replacement = "", replaceFirst = false }
+ local low5, low7, low6 = ruleStr:sub(1, 5):lower(), ruleStr:sub(1, 7):lower(), ruleStr:sub(1, 6):lower()
+ if mode == MODE_REGEX then
+ sr.rule = ruleStr
+ elseif low5 == "@css:" then
+ sr.mode, sr.rule = MODE_DEFAULT, ruleStr
+ elseif ruleStr:sub(1, 2) == "@@" then
+ sr.mode, sr.rule = MODE_DEFAULT, ruleStr:sub(3)
+ elseif low7 == "@xpath:" then
+ sr.mode, sr.rule = MODE_XPATH, ruleStr:sub(8)
+ elseif low6 == "@json:" then
+ sr.mode, sr.rule = MODE_JSON, ruleStr:sub(7)
+ elseif isJSON or ruleStr:sub(1, 2) == "$." or ruleStr:sub(1, 2) == "$[" then
+ sr.mode, sr.rule = MODE_JSON, ruleStr
+ elseif ruleStr:sub(1, 1) == "/" then
+ sr.mode, sr.rule = MODE_XPATH, ruleStr
+ else
+ sr.rule = ruleStr
+ end
+
+ sr.rule = sr.rule:gsub("@[Pp][Uu][Tt]:(%b{})", function(body)
+ local obj = Json.decode(body)
+ if Json.isObject(obj) then
+ for k, v in pairs(obj) do sr.putMap[k] = type(v) == "string" and v or tostring(v) end
+ end
+ return ""
+ end)
+
+ local rule, start = sr.rule, 1
+ for _, m in ipairs(Regex.all("(?i)@get:\\{[^}]+?\\}|@get:[A-Za-z0-9_]+|\\{\\{[\\s\\S]*?\\}\\}", rule)) do
+ if m.s > start then splitRegexPart(sr, rule:sub(start, m.s - 1)) end
+ local tmp = m[0]
+ if tmp:sub(1, 5):lower() == "@get:" then
+ sr.types[#sr.types + 1] = GET_RULE
+ sr.params[#sr.params + 1] = (tmp:sub(6):gsub("^[{}%s]+", ""):gsub("[{}%s]+$", ""))
+ else
+ sr.types[#sr.types + 1] = JS_RULE
+ sr.params[#sr.params + 1] = tmp:sub(3, #tmp - 2)
+ end
+ start = m.e
+ end
+ if #rule >= start then splitRegexPart(sr, rule:sub(start)) end
+ return sr
+end
+
+local function makeUpRule(sr, result, analyze)
+ if #sr.params > 0 then
+ local info = ""
+ for index = #sr.params, 1, -1 do
+ local t = sr.types[index]
+ if t > 0 then
+ local v = type(result) == "table" and result[t]
+ if type(v) == "string" or type(v) == "number" then
+ info = tostring(v) .. info
+ else
+ info = sr.params[index] .. info
+ end
+ elseif t == JS_RULE then
+ local expr = sr.params[index]
+ if not Unsupported.isSelectorRule(expr) then Unsupported.throwIfJsExpression(expr) end
+ info = analyze:getString(expr) .. info
+ elseif t == GET_RULE then
+ info = analyze:get(sr.params[index]) .. info
+ else
+ info = sr.params[index] .. info
+ end
+ end
+ sr.rule = info
+ end
+ local parts = explode(sr.rule, "##")
+ sr.rule = trim(parts[1])
+ if #parts > 1 then sr.replaceRegex = parts[2] end
+ if #parts > 2 then sr.replacement = parts[3] end
+ if #parts > 3 then sr.replaceFirst = true end
+end
+
+---------------------------------------------------------------- AnalyzeRule
+
+function Rule.new()
+ return setmetatable({ vars = {}, ruleCache = {}, isRegex = false, isJSON = false }, Rule)
+end
+
+local function detectJson(content)
+ if type(content) == "string" then
+ local c = content:match("^%s*(.)")
+ return c == "{" or c == "["
+ end
+ return type(content) == "table" and not isDom(content)
+end
+
+function Rule:setContent(content, baseUrl)
+ assert(content ~= nil, "内容不可空")
+ if type(content) == "table" and content.type == "attr" then content = content.value end
+ if type(content) == "table" and content.type == "text" then content = content.text end
+ self.content = content
+ local isJSON = detectJson(content)
+ if isJSON ~= self.isJSON then self.ruleCache = {} end
+ self.isJSON = isJSON
+ if baseUrl then self.baseUrl = baseUrl end
+ self.domCache, self.jsonCache = nil, nil
+ return self
+end
+
+function Rule:setBaseUrl(url)
+ if url then self.baseUrl = url end
+ return self
+end
+
+function Rule:setRedirectUrl(url)
+ if url:sub(1, 5):lower() ~= "data:" then self.redirectUrl = url end
+ return self
+end
+
+function Rule:setBook(name) self.bookName = name; return self end
+function Rule:setChapter(title) self.chapterTitle = title; return self end
+
+function Rule:put(key, value)
+ self.vars[key] = value
+ return value
+end
+
+function Rule:get(key)
+ if key == "bookName" and self.bookName and self.bookName ~= "" then return self.bookName end
+ if key == "title" and self.chapterTitle and self.chapterTitle ~= "" then return self.chapterTitle end
+ local v = self.vars[key]
+ if v and v ~= "" then return v end
+ return ""
+end
+
+function Rule:putRule(map)
+ for k, v in pairs(map) do self:put(k, self:getString(v)) end
+end
+
+function Rule:splitSourceRule(ruleStr, allInOne)
+ if not ruleStr or ruleStr == "" then return {} end
+ Unsupported.throwIfJsSnippet(ruleStr)
+ local mode, start = MODE_DEFAULT, 1
+ if allInOne and ruleStr:sub(1, 1) == ":" then
+ mode, self.isRegex, start = MODE_REGEX, true, 2
+ elseif self.isRegex then
+ mode = MODE_REGEX
+ end
+ local tmp = trim(ruleStr:sub(start))
+ if tmp == "" then return {} end
+ return { newSourceRule(tmp, mode, self.isJSON) }
+end
+
+function Rule:splitCached(ruleStr)
+ local c = self.ruleCache[ruleStr]
+ if not c then
+ c = self:splitSourceRule(ruleStr)
+ self.ruleCache[ruleStr] = c
+ end
+ return c
+end
+
+-- 把当前内容整理成对应模式要用的对象
+function Rule:asDom(o, xpath)
+ if isDom(o) then return o end
+ local s = type(o) == "string" and o or tostring(o)
+ if o == self.content and self.domCache and self.domCache.xpath == xpath then return self.domCache.node end
+ local src = s
+ if xpath then
+ local tail = src:gsub("%s+$", "")
+ if tail:sub(-5) == "" then src = "