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) == "", lt, true) or len + local tag = src:match("^ + 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("", 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] = "" + 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].-", "") + s = s:gsub("<[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("", "\n"):gsub("", "\n"):gsub("", "\n") + s = s:gsub("", "\n"):gsub("", "\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 = "" .. src .. ""; tail = src end + if tail:sub(-5) == "" or tail:sub(-8) == "" then src = "" .. src .. "
" end + end + local node = Html.parse(src) + if o == self.content then self.domCache = { xpath = xpath, node = node } end + return node +end + +function Rule:asJson(o) + if type(o) ~= "string" then return o end + if o == self.content and self.jsonCache ~= nil then return self.jsonCache end + local v = Json.decode(o) + if v == nil then v = o end + if o == self.content then self.jsonCache = v end + return v +end + +local function evalRule(self, sr, result, isUrl) + local rule = sr.rule + if sr.mode == MODE_JSON then + return jsonString(self:asJson(result), rule) + elseif sr.mode == MODE_XPATH then + return xpathString(self:asDom(result, true), rule) + elseif sr.mode == MODE_REGEX then + return rule + end + local list = jsoupStringList(self:asDom(result), rule) + if #list == 0 then return nil end + if isUrl then return list[1] end + return table.concat(list, "\n") +end + +local function evalRuleList(self, sr, result) + local rule = sr.rule + if sr.mode == MODE_REGEX then + local regs = {} + for part in (rule .. "&&"):gmatch("(.-)&&") do + if part ~= "" then regs[#regs + 1] = part end + end + return regexElements(type(result) == "string" and result or tostring(result), regs) + elseif sr.mode == MODE_JSON then + return jsonList(self:asJson(result), rule) + elseif sr.mode == MODE_XPATH then + return xpathElements(self:asDom(result, true), rule) + end + return getElementsOf(self:asDom(result), rule) +end + +local function stringifyValue(v) + if type(v) == "table" then return JsonPath.stringify(v) end + return tostring(v) +end + +function Rule:replaceRegex(result, sr) + if sr.replaceRegex == "" then return result end + local ok, out + if sr.replaceFirst then + ok, out = pcall(function() + local m = Regex.find(sr.replaceRegex, result) + if not m then return "" end + return Regex.replace(sr.replaceRegex, m[0], sr.replacement, true) + end) + else + ok, out = pcall(Regex.replace, sr.replaceRegex, result, sr.replacement) + end + if ok then return out end + -- 正则写错时按字面串替换,和 Legado 的兜底一致 + local lit = sr.replaceRegex + local s, e = result:find(lit, 1, true) + if sr.replaceFirst then return s and sr.replacement or "" end + local parts, start = {}, 1 + while s do + parts[#parts + 1] = result:sub(start, s - 1) + start = e + 1 + s, e = result:find(lit, start, true) + end + parts[#parts + 1] = result:sub(start) + return table.concat(parts, sr.replacement) +end + +--- 取字符串。isUrl 时补全为绝对地址;规则为空返回 baseUrl(isUrl)或 ""。 +function Rule:getString(ruleStr, mContent, isUrl, unescape) + if unescape == nil then unescape = true end + if not ruleStr or ruleStr == "" then + if isUrl then return self.baseUrl or "" end + return "" + end + local list = self:splitCached(ruleStr) + local result + local content = mContent + if content == nil then content = self.content end + if content ~= nil and #list > 0 then + result = content + for _, sr in ipairs(list) do + self:putRule(sr.putMap) + makeUpRule(sr, result, self) + if result ~= nil then + if sr.rule ~= "" or sr.replaceRegex == "" then result = evalRule(self, sr, result, isUrl) end + if result ~= nil and sr.replaceRegex ~= "" then + result = self:replaceRegex(stringifyValue(result), sr) + end + end + end + end + local str = result == nil and "" or stringifyValue(result) + if unescape and str:find("&", 1, true) then str = Html.decode(str) end + if isUrl then + if trim(str) == "" then return self.baseUrl or "" end + return Url.absolute(self.redirectUrl or self.baseUrl, str) + end + return str +end + +--- 取字符串列表(按行拆)。isUrl 时去重并补全。 +function Rule:getStringList(ruleStr, mContent, isUrl) + if not ruleStr or ruleStr == "" then return {} end + local list = self:splitCached(ruleStr) + local result + local content = mContent + if content == nil then content = self.content end + if content ~= nil and #list > 0 then + result = content + for _, sr in ipairs(list) do + self:putRule(sr.putMap) + makeUpRule(sr, result, self) + if result ~= nil then + if sr.rule ~= "" then result = evalRule(self, sr, result, false) end + if sr.replaceRegex ~= "" then + if Json.isArray(result) then + local nl = {} + for _, item in ipairs(result) do nl[#nl + 1] = self:replaceRegex(stringifyValue(item), sr) end + result = nl + elseif result ~= nil then + result = self:replaceRegex(stringifyValue(result), sr) + end + end + end + end + end + if result == nil then return {} end + local lines + if type(result) == "string" then + lines = explode(result, "\n") + elseif Json.isArray(result) or (type(result) == "table" and not isDom(result) and result[1] ~= nil) then + lines = {} + for k, v in ipairs(result) do lines[k] = stringifyValue(v) end + else + lines = { stringifyValue(result) } + end + if isUrl then + local out, seen = {}, {} + for _, u in ipairs(lines) do + local abs = Url.absolute(self.redirectUrl or self.baseUrl, u) + if abs ~= "" and not seen[abs] then + seen[abs] = true + out[#out + 1] = abs + end + end + return out + end + return lines +end + +--- 取元素列表(DOM 节点、JSON 值或正则行)。 +function Rule:getElements(ruleStr) + local result = self.content + local list = self:splitSourceRule(ruleStr, true) + if result ~= nil then + for _, sr in ipairs(list) do + self:putRule(sr.putMap) + makeUpRule(sr, result, self) + result = evalRuleList(self, sr, result) + if type(result) ~= "table" or isDom(result) then return {} end + end + end + if type(result) == "table" and not isDom(result) and Json.isObject(result) == false then + local out = {} + for k, v in ipairs(result) do out[k] = v end + return out + end + return {} +end + +--- 取单个元素(列表第一项);无结果返回 nil。 +function Rule:getElement(ruleStr) + return self:getElements(ruleStr)[1] +end + +Rule.splitTop = splitTop +Rule.explode = explode + +return Rule diff --git a/moonsource-legadorule.koplugin/moonsource_legadorule/unsupported.lua b/moonsource-legadorule.koplugin/moonsource_legadorule/unsupported.lua new file mode 100644 index 0000000..77401bf --- /dev/null +++ b/moonsource-legadorule.koplugin/moonsource_legadorule/unsupported.lua @@ -0,0 +1,50 @@ +--[[-- +JS / WebView 规则一律拒绝:抛出带固定提示的错误表,由 parser 转成用户可见的错误。 + +@module moonsource_legadorule.unsupported +--]] + +local Regex = require("moonsource_legadorule.regex") + +local Unsupported = {} + +Unsupported.MESSAGE = "该书源需要 JS/WebView,暂不支持" + +local ErrMeta = { __tostring = function(e) return e.message end } + +function Unsupported.fail() + error(setmetatable({ message = Unsupported.MESSAGE, unsupported = true }, ErrMeta), 0) +end + +--- pcall 抛出的错误转成文字。 +function Unsupported.message(err) + if type(err) == "table" and err.message then return err.message end + return tostring(err) +end + +function Unsupported.isJsSnippet(text) + return Regex.test("(?i)` 翻页、`url,{选项JSON}`、GET 查询参数 / POST 表单的百分号编码(含 GBK)。 +JS 选项与 webView 一律拒绝。只产出请求描述,网络由 client 发。 + +@module moonsource_legadorule.url +--]] + +local Regex = require("moonsource_legadorule.regex") +local Json = require("moonsource_legadorule.json") +local Unsupported = require("moonsource_legadorule.unsupported") + +local Url = {} + +local function trim(s) return (s:gsub("^%s+", ""):gsub("%s+$", "")) end + +--- 切开 `url,{...}`:返回 url 与选项(含逗号前的原样文本,没有为 "")。 +function Url.splitOption(url) + local m = Regex.find("\\s*,\\s*(?=\\{)", url) + if m then return trim(url:sub(1, m.s - 1)), url:sub(m.s) end + return trim(url), "" +end + +local function parse(url) + local scheme, rest = url:match("^(%a[%w+.-]*)://(.*)$") + if not scheme then return nil end + local authority, tail = rest:match("^([^/?#]*)(.*)$") + local hostport = authority:gsub("^.*@", "") + local host, port = hostport:match("^(.-):(%d+)$") + host = host or hostport + local hash = tail:match("#.*$") or "" + local noHash = hash ~= "" and tail:sub(1, #tail - #hash) or tail + local query = noHash:match("%?(.*)$") + local path = noHash:match("^([^?]*)") + return { scheme = scheme:lower(), host = host, port = port, path = path ~= "" and path or "/", query = query } +end + +local function normalizePath(path) + local hash, query = "", "" + local hp = path:find("#", 1, true) + if hp then hash = path:sub(hp); path = path:sub(1, hp - 1) end + local qp = path:find("?", 1, true) + if qp then query = path:sub(qp); path = path:sub(1, qp - 1) end + local parts = {} + for seg in (path .. "/"):gmatch("(.-)/") do parts[#parts + 1] = seg end + local stack = {} + for i, part in ipairs(parts) do + if part == "" and i ~= 1 then + if i == #parts then stack[#stack + 1] = "" end + elseif part == "." then + -- skip + elseif part == ".." then + if #stack > 1 then stack[#stack] = nil end + else + stack[#stack + 1] = part + end + end + local norm = table.concat(stack, "/") + if norm:sub(1, 1) ~= "/" then norm = "/" .. norm end + return norm .. query .. hash +end + +--- 以 base 为基准补全 relative;javascript: 返回 "",保留 `,{选项}` 后缀。 +function Url.absolute(base, relative) + relative = trim(relative or "") + if base and base ~= "" then base = Url.splitOption(base) end + local rel, option = Url.splitOption(relative) + local low = rel:lower() + if rel == "" or low:sub(1, 10) == "javascript" then return "" end + if low:sub(1, 5) == "data:" or low:match("^https?://") then return rel .. option end + if not base or base == "" then return rel .. option end + local p = parse(base) + if rel:sub(1, 2) == "//" then return (p and p.scheme or "http") .. ":" .. rel .. option end + if not p or p.host == "" then return rel .. option end + local origin = p.scheme .. "://" .. p.host .. (p.port and (":" .. p.port) or "") + local first = rel:sub(1, 1) + if first == "/" then return origin .. rel .. option end + if first == "?" then return origin .. p.path .. rel .. option end + if first == "#" then return origin .. p.path .. (p.query and ("?" .. p.query) or "") .. rel .. option end + local basePath = p.path + if basePath:sub(-1) ~= "/" then basePath = basePath:match("^(.*/)") or "/" end + return origin .. normalizePath(basePath .. rel) .. option +end + +--- scheme://host[:port],不是 http(s) 返回 nil。 +function Url.base(url) + if not url or not url:lower():match("^https?://") then return nil end + local pos = url:find("/", 9, true) + return pos and url:sub(1, pos - 1) or url +end + +function Url.domain(url) + local p = parse(url) + return p and p.host or url +end + +-- 与 Java NetworkUtils.isEncoded 一致:已是合法百分号编码就不再编码 +local function isEncoded(s, query) + local allowed = query and "[%w!$&()*+,%-./:;=?@%[%]\\^_`{|}~]" or "[%w*%-._]" + local i = 1 + while i <= #s do + local c = s:sub(i, i) + if c:find(allowed) then + i = i + 1 + elseif c == "%" and s:sub(i + 1, i + 2):match("^%x%x$") then + i = i + 3 + else + return false + end + end + return true +end + +---------------------------------------------------------------- GBK 反查 + +local gbkRev +local function gbkReverse() + if gbkRev ~= nil then return gbkRev end + gbkRev = false + local ok, path = pcall(package.searchpath, "utils.charset", package.path) + if not ok or not path then return gbkRev end + local f = io.open(path:gsub("[^/]+$", "gbk.bin"), "rb") + if not f then return gbkRev end + local map = f:read("*a") + f:close() + local rev = {} + for lead = 0x81, 0xFE do + for trail = 0x40, 0xFE do + local pos = ((lead - 0x81) * 191 + (trail - 0x40)) * 2 + 1 + local cp = map:byte(pos) + map:byte(pos + 1) * 256 + if cp > 0 and not rev[cp] then rev[cp] = string.char(lead, trail) end + end + end + gbkRev = rev + return rev +end + +local function percent(bytes) + return (bytes:gsub("[^%w%-_.~]", function(c) return string.format("%%%02X", c:byte()) end)) +end + +local function encodeValue(value, charset) + local lower = charset and charset:lower() + local rev = lower and (lower == "gbk" or lower == "gb2312" or lower == "gb18030" or lower == "x-gbk") + and gbkReverse() + if not rev then return percent(value) end + local out, pos = {}, 1 + while pos <= #value do + local c = value:byte(pos) + local len = c < 0x80 and 1 or c >= 0xF0 and 4 or c >= 0xE0 and 3 or 2 + local ch = value:sub(pos, pos + len - 1) + local cp + if len == 2 then + cp = (c % 32) * 64 + (value:byte(pos + 1) or 128) % 64 + elseif len == 3 then + cp = (c % 16) * 4096 + ((value:byte(pos + 1) or 128) % 64) * 64 + (value:byte(pos + 2) or 128) % 64 + end + out[#out + 1] = percent(cp and rev[cp] or ch) + pos = pos + len + end + return table.concat(out) +end + +local function encodeParams(params, charset, isQuery) + local hasCharset = charset and charset ~= "" + if isQuery and not hasCharset and isEncoded(params, true) then return params end + local enc = hasCharset and charset:lower() ~= "escape" and charset or "UTF-8" + local function one(v) + if not hasCharset and isEncoded(v, isQuery) then return v end + -- 已是 %XX 形式的字面量(如 GBK 预编码)不再二次编码 + if hasCharset and v:find("%%%x%x") and not v:find("[^%w%-_.~%%+]") then return v end + return encodeValue(v, enc) + end + local parts = {} + for pair in (params .. "&"):gmatch("(.-)&") do + if pair ~= "" then + local eq = pair:find("=", 1, true) + if eq then + parts[#parts + 1] = one(pair:sub(1, eq - 1)) .. "=" .. one(pair:sub(eq + 1)) + else + parts[#parts + 1] = one(pair) + end + end + end + return table.concat(parts, "&") +end + +---------------------------------------------------------------- 请求头 + +--- 书源 header 文本 → 表。支持 JSON(可多个对象)与 `Key: Value` 行。含 JS / webView 抛 Unsupported。 +function Url.parseHeaders(text) + text = (text or ""):gsub("\226\128[\139-\141]", ""):gsub("\239\187\191", ""):gsub("\194\160", "") + text = trim(text) + if text == "" then return {} end + Unsupported.throwIfJsSnippet(text) + local out = {} + if text:sub(1, 1) == "{" then + local rest, parts = text, {} + while true do + local m = Regex.find("\\}\\s*,\\s*\\{", rest) + if not m then break end + parts[#parts + 1] = rest:sub(1, m.s) + rest = "{" .. rest:sub(m.e) + end + parts[#parts + 1] = rest + local found = false + for _, chunk in ipairs(parts) do + local obj = Json.decode(chunk) + if Json.isObject(obj) then + found = true + for k, v in pairs(obj) do + if k:lower() == "webview" and v and v ~= "false" and v ~= Json.null then Unsupported.fail() end + if type(v) == "string" or type(v) == "number" or type(v) == "boolean" then out[k] = tostring(v) end + end + end + end + if found then return out end + end + for line in (text .. "\n"):gmatch("(.-)\r?\n") do + line = trim(line) + local c = line:sub(1, 1) + if line ~= "" and c ~= "{" and c ~= "}" and c ~= "," and c ~= '"' and c ~= "'" then + local k, v = line:match("^([^:]+):(.*)$") + if k and trim(k) ~= "" then out[trim(k)] = trim(v) end + end + end + return out +end + +local function headerValue(map, name) + for k, v in pairs(map) do + if k:lower() == name:lower() then return v end + end + return "" +end + +---------------------------------------------------------------- AnalyzeUrl + +local function evalMustache(expr, ctx) + expr = trim(expr) + local compact = expr:gsub("%s+", "") + local low = compact:lower() + if low == "key" or low == "keyword" then return ctx.key or "" end + local op, n = low:match("^page([+%-*/%%])(%d+)$") + if low == "page" or op then + local page = ctx.page or 1 + n = tonumber(n) + if op == "+" then page = page + n + elseif op == "-" then page = page - n + elseif op == "*" then page = page * n + elseif op == "/" then if n ~= 0 then page = math.floor(page / n) end + elseif op == "%" then if n ~= 0 then page = page % n end end + return tostring(page) + end + if Unsupported.isSelectorRule(expr) then + return ctx.rule and ctx.rule:getString(expr) or "" + end + Unsupported.throwIfJsExpression(expr) + return "" +end + +--- 解析一条书源 URL。ctx = { sourceUrl, header, key, page, baseUrl, rule }。 +--- 返回 { url, method, body, headers, charset, retry, ruleUrl };含 JS 抛 Unsupported。 +function Url.build(mUrl, ctx) + local baseUrl = ctx.baseUrl or "" + baseUrl = Url.splitOption(baseUrl) + if baseUrl == "" then baseUrl = ctx.sourceUrl or "" end + local spec = { method = "GET", headers = Url.parseHeaders(ctx.header), retry = 0, ruleUrl = mUrl } + + Unsupported.throwIfJsSnippet(mUrl) + local ruleUrl = mUrl + if ruleUrl:find("{{", 1, true) and ruleUrl:find("}}", 1, true) then + local replaced = ruleUrl:gsub("{{(.-)}}", function(expr) return evalMustache(expr, ctx) end) + if replaced ~= "" then ruleUrl = replaced end + end + if ctx.page then + for _, m in ipairs(Regex.all("<(.*?)>", ruleUrl)) do + local pages = {} + for p in (m[1] .. ","):gmatch("(.-),") do pages[#pages + 1] = p end + local repl = trim(ctx.page <= #pages and pages[ctx.page] or pages[#pages]) + local s, e = ruleUrl:find(m[0], 1, true) + if s then ruleUrl = ruleUrl:sub(1, s - 1) .. repl .. ruleUrl:sub(e + 1) end + end + end + spec.ruleUrl = ruleUrl + + local noOption, option = Url.splitOption(ruleUrl) + spec.url = Url.absolute(baseUrl, noOption) + if option ~= "" then + local opt = Json.decode((option:gsub("^[%s,]+", ""))) + if Json.isObject(opt) then + if type(opt.method) == "string" and opt.method:upper() == "POST" then spec.method = "POST" end + if type(opt.charset) == "string" and opt.charset ~= "" then spec.charset = opt.charset end + if opt.body ~= nil and opt.body ~= Json.null then + spec.body = type(opt.body) == "string" and opt.body or Json.encode(opt.body) + end + local headers = opt.headers + if type(headers) == "string" then + local decoded = Json.decode(headers) + headers = Json.isObject(decoded) and decoded or Url.parseHeaders(headers) + end + if type(headers) == "table" then + for k, v in pairs(headers) do + if type(v) == "string" or type(v) == "number" or type(v) == "boolean" then + spec.headers[tostring(k)] = tostring(v) + end + end + end + if tonumber(opt.retry) then spec.retry = tonumber(opt.retry) end + local web = opt.webView + if web == nil then web = opt.webview end + if web ~= nil and web ~= "" and web ~= false and web ~= "false" and web ~= Json.null then Unsupported.fail() end + for _, k in ipairs({ "webJs", "js" }) do + local v = opt[k] + if v and v ~= "" and v ~= Json.null then Unsupported.fail() end + end + end + end + + -- 路径里的中文、空格等字节也要转义(保留已有的 %XX 和 URL 分隔符) + do + local q = spec.url:find("?", 1, true) + local base = q and spec.url:sub(1, q - 1) or spec.url + base = base:gsub("[%z\1-\32\127-\255]", function(c) return string.format("%%%02X", c:byte()) end) + spec.url = q and (base .. spec.url:sub(q)) or base + end + + if spec.method == "GET" then + local q = spec.url:find("?", 1, true) + if q then + spec.url = spec.url:sub(1, q - 1) .. "?" .. encodeParams(spec.url:sub(q + 1), spec.charset, true) + end + elseif spec.body and spec.body ~= "" then + local trimmed = spec.body:gsub("^%s+", "") + local c = trimmed:sub(1, 1) + if headerValue(spec.headers, "Content-Type") == "" and c ~= "{" and c ~= "[" and c ~= "<" then + spec.body = encodeParams(spec.body, spec.charset, false) + end + end + if spec.method == "POST" then + local ct = headerValue(spec.headers, "Content-Type") + local body = spec.body or "" + if ct == "" then + local c = body:gsub("^%s+", ""):sub(1, 1) + ct = (c == "{" or c == "[") and "application/json" or "application/x-www-form-urlencoded" + end + spec.contentType = ct + end + return spec +end + +return Url diff --git a/moonsource-legadorule.koplugin/moonsource_legadorule/xpath.lua b/moonsource-legadorule.koplugin/moonsource_legadorule/xpath.lua new file mode 100644 index 0000000..196a923 --- /dev/null +++ b/moonsource-legadorule.koplugin/moonsource_legadorule/xpath.lua @@ -0,0 +1,581 @@ +--[[-- +XPath 1.0 子集解释器(跑在 html.lua 的 DOM 上):路径 / // . .. @attr * text() node()、 +child descendant self parent ancestor following-sibling preceding-sibling attribute 等轴、 +谓词、and/or/比较/加减乘除/并集 |,以及常用函数(contains starts-with not count position last +normalize-space concat substring* translate string-length name 等)。 + +@module moonsource_legadorule.xpath +--]] + +local Html = require("moonsource_legadorule.html") + +local XPath = {} + +---------------------------------------------------------------- 词法 + +local function tokenize(src) + local toks, i = {}, 1 + local function push(t, v) toks[#toks + 1] = { t = t, v = v } end + while i <= #src do + local c = src:sub(i, i) + if c:find("%s") then + i = i + 1 + elseif c == '"' or c == "'" then + local e = src:find(c, i + 1, true) + if not e then error("xpath: unterminated string", 0) end + push("str", src:sub(i + 1, e - 1)) + i = e + 1 + elseif c:find("%d") or (c == "." and src:sub(i + 1, i + 1):find("%d")) then + local n = src:match("^%d*%.?%d*", i) + push("num", tonumber(n)) + i = i + #n + elseif src:sub(i, i + 1) == "//" then push("//"); i = i + 2 + elseif src:sub(i, i + 1) == ".." then push(".."); i = i + 2 + elseif src:sub(i, i + 1) == "::" then push("::"); i = i + 2 + elseif src:sub(i, i + 1) == "!=" or src:sub(i, i + 1) == "<=" or src:sub(i, i + 1) == ">=" then + push(src:sub(i, i + 1)); i = i + 2 + elseif c:find("[/%.@%(%)%[%],|=<>%+%-%*]") then + push(c); i = i + 1 + elseif c:find("[%a_]") or c:byte() >= 128 then + local name = src:match("^[%w_%-\128-\255]+:?[%w_%-\128-\255]*", i) + -- 轴名后面是 ::,不能吞进名字 + local axis = src:match("^([%a%-]+)::", i) + if axis then name = axis end + push("name", name) + i = i + #name + else + error("xpath: unexpected '" .. c .. "'", 0) + end + end + push("eof") + return toks +end + +---------------------------------------------------------------- 语法 + +local P = {} +P.__index = P + +function P:peek(k) return self.toks[self.i + (k or 0)] end +function P:next() self.i = self.i + 1; return self.toks[self.i - 1] end +function P:accept(t) + if self:peek().t == t then return self:next() end +end +function P:expect(t) + if not self:accept(t) then error("xpath: expected " .. t, 0) end +end +function P:isOp(name) return self:peek().t == "name" and self:peek().v == name end + +local AXES = { + child = 1, descendant = 1, ["descendant-or-self"] = 1, self = 1, parent = 1, ancestor = 1, + ["ancestor-or-self"] = 1, ["following-sibling"] = 1, ["preceding-sibling"] = 1, attribute = 1, + following = 1, preceding = 1, +} + +function P:step() + if self:accept(".") then return { axis = "self", test = { kind = "node" }, preds = {} } end + if self:accept("..") then return { axis = "parent", test = { kind = "node" }, preds = {} } end + local axis = "child" + if self:accept("@") then + axis = "attribute" + elseif self:peek().t == "name" and self:peek(1).t == "::" then + axis = self:next().v + if not AXES[axis] then error("xpath: unknown axis " .. axis, 0) end + self:next() + end + local test + if self:accept("*") then + test = { kind = "name", name = "*" } + else + local t = self:next() + if t.t ~= "name" then error("xpath: bad step", 0) end + if self:peek().t == "(" and (t.v == "text" or t.v == "node" or t.v == "comment") then + self:next() + self:expect(")") + test = { kind = t.v } + else + test = { kind = "name", name = t.v:lower() } + end + end + local preds = {} + while self:accept("[") do + preds[#preds + 1] = self:expr() + self:expect("]") + end + return { axis = axis, test = test, preds = preds } +end + +local DOS = { axis = "descendant-or-self", test = { kind = "node" }, preds = {} } + +function P:path() + local steps, absolute = {}, false + if self:peek().t == "/" then + self:next() + absolute = true + local t = self:peek().t + if t ~= "name" and t ~= "*" and t ~= "@" and t ~= "." and t ~= ".." then + return { type = "path", absolute = true, steps = steps } + end + elseif self:accept("//") then + absolute = true + steps[1] = DOS + end + steps[#steps + 1] = self:step() + while true do + if self:accept("/") then + steps[#steps + 1] = self:step() + elseif self:accept("//") then + steps[#steps + 1] = DOS + steps[#steps + 1] = self:step() + else + break + end + end + return { type = "path", absolute = absolute, steps = steps } +end + +function P:primary() + local t = self:peek() + if t.t == "str" then self:next(); return { type = "lit", v = t.v } end + if t.t == "num" then self:next(); return { type = "lit", v = t.v } end + if t.t == "(" then + self:next() + local e = self:expr() + self:expect(")") + return e + end + if t.t == "name" and self:peek(1).t == "(" and t.v ~= "text" and t.v ~= "node" and t.v ~= "comment" then + self:next(); self:next() + local args = {} + if not self:accept(")") then + repeat args[#args + 1] = self:expr() until not self:accept(",") + self:expect(")") + end + return { type = "call", name = t.v, args = args } + end + return nil +end + +function P:filtered() + local prim = self:primary() + if not prim then return self:path() end + local preds = {} + while self:accept("[") do + preds[#preds + 1] = self:expr() + self:expect("]") + end + local node = prim + if #preds > 0 then node = { type = "filter", base = prim, preds = preds } end + if self:peek().t == "/" or self:peek().t == "//" then + local steps = {} + while true do + if self:accept("/") then + steps[#steps + 1] = self:step() + elseif self:accept("//") then + steps[#steps + 1] = DOS + steps[#steps + 1] = self:step() + else + break + end + end + return { type = "path", base = node, steps = steps } + end + return node +end + +function P:union() + local left = self:filtered() + while self:accept("|") do left = { type = "union", a = left, b = self:filtered() } end + return left +end + +function P:unary() + if self:accept("-") then return { type = "neg", e = self:unary() } end + return self:union() +end + +function P:mul() + local left = self:unary() + while true do + if self:accept("*") then left = { type = "bin", op = "*", a = left, b = self:unary() } + elseif self:isOp("div") then self:next(); left = { type = "bin", op = "/", a = left, b = self:unary() } + elseif self:isOp("mod") then self:next(); left = { type = "bin", op = "%", a = left, b = self:unary() } + else return left end + end +end + +function P:add() + local left = self:mul() + while true do + if self:accept("+") then left = { type = "bin", op = "+", a = left, b = self:mul() } + elseif self:accept("-") then left = { type = "bin", op = "-", a = left, b = self:mul() } + else return left end + end +end + +function P:rel() + local left = self:add() + while true do + local t = self:peek().t + if t == "<" or t == ">" or t == "<=" or t == ">=" then + self:next() + left = { type = "cmp", op = t, a = left, b = self:add() } + else return left end + end +end + +function P:eq() + local left = self:rel() + while true do + local t = self:peek().t + if t == "=" or t == "!=" then + self:next() + left = { type = "cmp", op = t, a = left, b = self:rel() } + else return left end + end +end + +function P:andExpr() + local left = self:eq() + while self:isOp("and") do self:next(); left = { type = "and", a = left, b = self:eq() } end + return left +end + +function P:expr() + local left = self:andExpr() + while self:isOp("or") do self:next(); left = { type = "or", a = left, b = self:andExpr() } end + return left +end + +---------------------------------------------------------------- 求值 + +local function docOf(n) + while n.parent do n = n.parent end + return n +end + +local function attrNode(el, name) + el.attrNodes = el.attrNodes or {} + local a = el.attrNodes[name] + if not a then + local idx = 0 + for k, nm in ipairs(el.attrOrder) do if nm == name then idx = k end end + a = { type = "attr", name = name, value = el.attrs[name], parent = el, order = el.order + idx / 10000 } + el.attrNodes[name] = a + end + return a +end + +local function stringValue(n) + if n.type == "attr" then return n.value end + return Html.textContent(n) +end + +local function isNodeset(v) return type(v) == "table" and v.nodeset end + +local function toStr(v) + if isNodeset(v) then return v[1] and stringValue(v[1]) or "" end + if type(v) == "number" then + if v == math.floor(v) and math.abs(v) < 1e15 then return string.format("%d", v) end + return tostring(v) + end + if type(v) == "boolean" then return tostring(v) end + return v +end + +local function toNum(v) + if type(v) == "number" then return v end + if type(v) == "boolean" then return v and 1 or 0 end + return tonumber((toStr(v):gsub("^%s+", ""):gsub("%s+$", ""))) or 0 / 0 +end + +local function toBool(v) + if isNodeset(v) then return #v > 0 end + if type(v) == "string" then return v ~= "" end + if type(v) == "number" then return v ~= 0 and v == v end + return v +end + +local function nodeset(list) + list.nodeset = true + return list +end + +local function sortUnique(list) + local seen, out = {}, {} + for _, n in ipairs(list) do + if not seen[n] then seen[n] = true; out[#out + 1] = n end + end + table.sort(out, function(a, b) return a.order < b.order end) + return nodeset(out) +end + +local function axisNodes(axis, n, out) + if axis == "child" then + for _, c in ipairs(n.children or {}) do out[#out + 1] = c end + elseif axis == "descendant" or axis == "descendant-or-self" then + if axis == "descendant-or-self" then out[#out + 1] = n end + local function walk(x) + for _, c in ipairs(x.children or {}) do + out[#out + 1] = c + walk(c) + end + end + walk(n) + elseif axis == "self" then + out[#out + 1] = n + elseif axis == "parent" then + if n.parent then out[#out + 1] = n.parent end + elseif axis == "ancestor" or axis == "ancestor-or-self" then + if axis == "ancestor-or-self" then out[#out + 1] = n end + local p = n.parent + while p do out[#out + 1] = p; p = p.parent end + elseif axis == "following-sibling" or axis == "preceding-sibling" then + local parent = n.parent + if parent and n.type ~= "attr" then + local sibs, idx = parent.children, 0 + for k, s in ipairs(sibs) do if s == n then idx = k end end + if axis == "following-sibling" then + for k = idx + 1, #sibs do out[#out + 1] = sibs[k] end + else + for k = idx - 1, 1, -1 do out[#out + 1] = sibs[k] end + end + end + elseif axis == "attribute" then + if n.type == "el" then + for _, name in ipairs(n.attrOrder) do out[#out + 1] = attrNode(n, name) end + end + elseif axis == "following" or axis == "preceding" then + local all = {} + axisNodes("descendant", docOf(n), all) + for _, x in ipairs(all) do + if axis == "following" and x.order > n.order then + local anc, p = false, x.parent + while p do if p == n then anc = true end p = p.parent end + if not anc then out[#out + 1] = x end + elseif axis == "preceding" and x.order < n.order then + local anc, p = false, n.parent + while p do if p == x then anc = true end p = p.parent end + if not anc then out[#out + 1] = x end + end + end + end +end + +local function testNode(test, axis, n) + if test.kind == "node" then return true end + if test.kind == "text" then return n.type == "text" end + if test.kind == "comment" then return false end + if axis == "attribute" then + return n.type == "attr" and (test.name == "*" or n.name == test.name) + end + return n.type == "el" and (test.name == "*" or n.tag == test.name) +end + +local eval + +local function applyPreds(list, preds, ctx) + for _, pred in ipairs(preds) do + local kept, size = {}, #list + for k, n in ipairs(list) do + local v = eval(pred, { node = n, pos = k, size = size, root = ctx.root }) + local ok + if type(v) == "number" then ok = v == k else ok = toBool(v) end + if ok then kept[#kept + 1] = n end + end + list = kept + end + return list +end + +local function runSteps(start, steps, ctx) + local current = start + for _, step in ipairs(steps) do + local gathered = {} + for _, n in ipairs(current) do + local cand = {} + axisNodes(step.axis, n, cand) + local filtered = {} + for _, c in ipairs(cand) do + if testNode(step.test, step.axis, c) then filtered[#filtered + 1] = c end + end + filtered = applyPreds(filtered, step.preds, ctx) + for _, c in ipairs(filtered) do gathered[#gathered + 1] = c end + end + current = sortUnique(gathered) + end + return current +end + +local function compare(op, a, b) + local function cmp(x, y) + if op == "=" or op == "!=" then + local r + if type(x) == "number" or type(y) == "number" then r = toNum(x) == toNum(y) + elseif type(x) == "boolean" or type(y) == "boolean" then r = toBool(x) == toBool(y) + else r = toStr(x) == toStr(y) end + if op == "=" then return r end + return not r + end + local nx, ny = toNum(x), toNum(y) + if op == "<" then return nx < ny elseif op == ">" then return nx > ny + elseif op == "<=" then return nx <= ny else return nx >= ny end + end + local sa, sb = isNodeset(a), isNodeset(b) + if sa and sb then + for _, x in ipairs(a) do for _, y in ipairs(b) do + if cmp(stringValue(x), stringValue(y)) then return true end + end end + return false + elseif sa then + if type(b) == "boolean" then return cmp(#a > 0, b) end + for _, x in ipairs(a) do if cmp(stringValue(x), b) then return true end end + return false + elseif sb then + if type(a) == "boolean" then return cmp(a, #b > 0) end + for _, y in ipairs(b) do if cmp(a, stringValue(y)) then return true end end + return false + end + return cmp(a, b) +end + +local function normalize(s) return (s:gsub("%s+", " "):gsub("^ ", ""):gsub(" $", "")) end + +local FN = { + last = function(ctx) return ctx.size end, + position = function(ctx) return ctx.pos end, + count = function(_, v) return #v end, + ["not"] = function(_, v) return not toBool(v) end, + ["true"] = function() return true end, + ["false"] = function() return false end, + boolean = function(_, v) return toBool(v) end, + string = function(ctx, v) if v == nil then return stringValue(ctx.node) end return toStr(v) end, + number = function(ctx, v) if v == nil then return toNum(stringValue(ctx.node)) end return toNum(v) end, + ["normalize-space"] = function(ctx, v) + return normalize(v == nil and stringValue(ctx.node) or toStr(v)) + end, + ["string-length"] = function(ctx, v) + local s = v == nil and stringValue(ctx.node) or toStr(v) + return select(2, s:gsub("[^\128-\191]", "")) + end, + contains = function(_, a, b) return toStr(a):find(toStr(b), 1, true) ~= nil end, + ["starts-with"] = function(_, a, b) local t = toStr(b); return toStr(a):sub(1, #t) == t end, + ["ends-with"] = function(_, a, b) local t = toStr(b); return t == "" or toStr(a):sub(-#t) == t end, + ["substring-before"] = function(_, a, b) + local s, t = toStr(a), toStr(b) + local i = s:find(t, 1, true) + return i and s:sub(1, i - 1) or "" + end, + ["substring-after"] = function(_, a, b) + local s, t = toStr(a), toStr(b) + local i, e = s:find(t, 1, true) + return i and s:sub(e + 1) or "" + end, + substring = function(_, a, b, c) + local s = toStr(a) + local from = math.floor(toNum(b) + 0.5) + local to = c and from + math.floor(toNum(c) + 0.5) - 1 or #s + return s:sub(math.max(from, 1), to) + end, + concat = function(_, ...) + local out = {} + for k, v in ipairs({ ... }) do out[k] = toStr(v) end + return table.concat(out) + end, + translate = function(_, a, b, c) + local s, from, to = toStr(a), toStr(b), toStr(c) + return (s:gsub(".", function(ch) + local i = from:find(ch, 1, true) + if not i then return nil end + return to:sub(i, i) + end)) + end, + name = function(ctx, v) + local n = v and v[1] or ctx.node + return n.tag or n.name or "" + end, + sum = function(_, v) + local t = 0 + for _, n in ipairs(v) do t = t + toNum(stringValue(n)) end + return t + end, + floor = function(_, v) return math.floor(toNum(v)) end, + ceiling = function(_, v) return math.ceil(toNum(v)) end, + round = function(_, v) return math.floor(toNum(v) + 0.5) end, +} +FN["local-name"] = FN.name + +function eval(e, ctx) + local t = e.type + if t == "lit" then return e.v end + if t == "path" then + local start + if e.base then + start = eval(e.base, ctx) + if not isNodeset(start) then error("xpath: path on non-nodeset", 0) end + elseif e.absolute then + start = nodeset({ docOf(ctx.node) }) + else + start = nodeset({ ctx.node }) + end + return runSteps(start, e.steps, ctx) + elseif t == "filter" then + local base = eval(e.base, ctx) + return nodeset(applyPreds(base, e.preds, ctx)) + elseif t == "union" then + local a, b = eval(e.a, ctx), eval(e.b, ctx) + local all = {} + for _, n in ipairs(a) do all[#all + 1] = n end + for _, n in ipairs(b) do all[#all + 1] = n end + return sortUnique(all) + elseif t == "and" then + return toBool(eval(e.a, ctx)) and toBool(eval(e.b, ctx)) + elseif t == "or" then + return toBool(eval(e.a, ctx)) or toBool(eval(e.b, ctx)) + elseif t == "cmp" then + return compare(e.op, eval(e.a, ctx), eval(e.b, ctx)) + elseif t == "neg" then + return -toNum(eval(e.e, ctx)) + elseif t == "bin" then + local a, b = toNum(eval(e.a, ctx)), toNum(eval(e.b, ctx)) + if e.op == "+" then return a + b elseif e.op == "-" then return a - b + elseif e.op == "*" then return a * b elseif e.op == "/" then return a / b end + return a % b + elseif t == "call" then + local fn = FN[e.name] + if not fn then error("xpath: unsupported function " .. e.name, 0) end + local args = {} + for k, a in ipairs(e.args) do args[k] = eval(a, ctx) end + return fn(ctx, unpack(args, 1, #e.args)) + end + error("xpath: bad node", 0) +end + +local cache = {} + +local function compile(src) + local ast = cache[src] + if ast then return ast end + local p = setmetatable({ toks = tokenize(src), i = 1 }, P) + ast = p:expr() + if p:peek().t ~= "eof" then error("xpath: trailing tokens", 0) end + cache[src] = ast + return ast +end + +--- 求值。返回 nodes(节点数组,含属性 / 文本节点)或标量(字符串 / 数字 / 布尔)。 +--- 表达式语法错误抛字符串错误。 +function XPath.evaluate(context, src) + local v = eval(compile(src), { node = context, pos = 1, size = 1 }) + if isNodeset(v) then return v, true end + return v, false +end + +--- 节点转字符串:属性取值、文本取文本、元素取 textContent。 +function XPath.string(n) + return stringValue(n) +end + +XPath.toStr = toStr + +return XPath diff --git a/tests/legadorule/parser_spec.lua b/tests/legadorule/parser_spec.lua new file mode 100644 index 0000000..36b194a --- /dev/null +++ b/tests/legadorule/parser_spec.lua @@ -0,0 +1,79 @@ +--[[-- +moonsource_legadorule.parser 离线用例:搜索、详情、目录翻页、正文翻页与取消,http 走脚本化桩。 + +@module tests.legadorule.parser_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch + +local Assert = require("support.assert") + +local pages, calls = {}, {} +package.preload["http.request"] = function() + local function respond(url, cb) + calls[#calls + 1] = url + local body = pages[url] + if body == nil then return cb(nil, "HTTP 404", { code = 404 }) end + cb(body, nil, { code = 200 }) + end + return { + header = function() return nil end, + get = function(url, _opts, cb) respond(url, cb) return { cancel = function() end } end, + post = function(url, _body, _opts, cb) respond(url, cb) return { cancel = function() end } end, + } +end +package.preload["http.cookie_jar"] = function() return { new = function() return {} end } end + +local Parser = require("moonsource_legadorule.parser") +local Client = require("moonsource_legadorule.client") + +local rule = { + bookSourceUrl = "https://a.com", + searchUrl = "/s?q={{key}}", + ruleSearch = { bookList = ".r li", name = "a@text", bookUrl = "a@href", author = "span@text##作者:" }, + ruleBookInfo = { name = "h1@text", intro = ".intro@text", tocUrl = ".toc@href" }, + ruleToc = { chapterList = ".c a", chapterName = "text", chapterUrl = "href", nextTocUrl = ".next@href" }, + ruleContent = { content = "#t@html", nextContentUrl = ".np@href" }, +} + +local function wait(fn) + local a, b + fn(function(x, y) a, b = x, y end) + return a, b +end + +pages["https://a.com/s?q=%E6%96%97"] = '' +pages["https://a.com/b/1"] = '

斗破

简介
目录' +pages["https://a.com/t/1"] = '
一二
' +pages["https://a.com/t/2"] = '
三
' +pages["https://a.com/c/1"] = '
第一段
第二段
下页' +pages["https://a.com/c/1_2"] = '
第三段
下章' + +local P = Parser.new(rule, Client.new(rule)) + +-- 搜索:书名前缀、作者前缀被清理,同书地址去重。 +local books, err = wait(function(cb) P:search("斗", 1, cb) end) +Assert.is_nil(err) +Assert.len(books, 2) +Assert.eq(books[1].name, "斗破") +Assert.eq(books[1].author, "天蚕") +Assert.eq(books[1].bookUrl, "https://a.com/b/1") + +-- 详情 → 目录:跟随 nextTocUrl,遇到回环停止。 +local book = wait(function(cb) P:detail(books[1].bookUrl, books[1], cb) end) +Assert.eq(book.tocUrl, "https://a.com/t/1") +Assert.eq(book.intro, "简介") +local chapters = wait(function(cb) P:chapters(book, cb) end) +Assert.len(chapters, 3) +Assert.eq(chapters[3].url, "https://a.com/c/3") + +-- 正文:拼接分页,遇到下一章地址停止。 +local content = wait(function(cb) P:content(chapters[1], book, chapters[2].url, cb) end) +Assert.eq(content.text, "第一段\n第二段\n第三段") + +-- 错误如实上报:404 与 JS 规则。 +local _, e = wait(function(cb) P:content({ title = "x", url = "https://a.com/none", baseUrl = "https://a.com", isVolume = false }, book, nil, cb) end) +Assert.matches(e, "获取网页内容失败") +local js = Parser.new({ bookSourceUrl = "https://a.com", searchUrl = "/s?q={{java.md5(key)}}" }, Client.new({})) +local _r, e2 = wait(function(cb) js:search("x", 1, cb) end) +Assert.matches(e2, "JS/WebView") diff --git a/tests/legadorule/rule_spec.lua b/tests/legadorule/rule_spec.lua new file mode 100644 index 0000000..2ecb837 --- /dev/null +++ b/tests/legadorule/rule_spec.lua @@ -0,0 +1,76 @@ +--[[-- +moonsource_legadorule.rule / url 离线用例:各规则模式、@put/@get、正则替换、JS 拒绝、URL 补全与构造。 + +@module tests.legadorule.rule_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch + +local Assert = require("support.assert") +local Rule = require("moonsource_legadorule.rule") +local Url = require("moonsource_legadorule.url") +local Unsupported = require("moonsource_legadorule.unsupported") + +local HTML = '
' + +-- 默认 JSoup 模式:列表、文本、绝对链接、下标、正则替换。 +do + local an = Rule.new():setContent(HTML, "http://x.com/") + local items = an:getElements(".lis li") + Assert.len(items, 2) + local item = Rule.new():setContent(items[1], "http://x.com/") + Assert.eq(item:getString("a@text"), "书一") + Assert.eq(item:getString("a@href", nil, true), "http://x.com/b/1") + Assert.eq(an:getString("li.1@a@text"), "书二") + Assert.eq(an:getString("li.0@a@text##书##本"), "本一") + Assert.eq(an:getString("tag.a!0@text"), "书二") +end + +-- XPath 与 JsonPath。 +do + local an = Rule.new():setContent(HTML, "http://x.com/") + Assert.len(an:getElements("//li"), 2) + Assert.eq(an:getString("//li[2]/a/text()"), "书二") + local js = Rule.new():setContent('{"a":{"list":[{"n":"x","v":1},{"n":"y","v":2}],"t":"hi"}}', "http://x.com/") + Assert.eq(js:getString("$.a.t"), "hi") + Assert.eq(js:getString("$.a.list[-1].v"), "2") + local rows = js:getElements("$.a.list[?(@.v>1)]") + Assert.len(rows, 1) + Assert.eq(Rule.new():setContent(rows[1]):getString("$.n"), "y") + Assert.eq(js:getString("$..n"), "x\ny") +end + +-- 正则列表模式与 $n 组引用;@put / @get。 +do + local an = Rule.new():setContent("a1:一;a2:二;", "http://x.com/") + local rows = an:getElements(":a(\\d):(.)") + Assert.len(rows, 2) + Assert.eq(Rule.new():setContent(rows[2]):getString("$1-$2"), "2-二") + local put = Rule.new():setContent(HTML) + put:getString("li.0@a@text@put:{k:\"li.1@a@text\"}") + Assert.eq(put:get("k"), "书二") +end + +-- JS / WebView 规则一律拒绝。 +do + Assert.errors(function() Rule.new():setContent(HTML):getString("@js:result") end) + local ok, err = pcall(Rule.new():setContent(HTML).getString, Rule.new():setContent(HTML), "1") + Assert.is_false(ok) + Assert.eq(Unsupported.message(err), Unsupported.MESSAGE) +end + +-- URL 补全与构造。 +do + Assert.eq(Url.absolute("https://a.com/x/y.html", "../z.html"), "https://a.com/z.html") + Assert.eq(Url.absolute("https://a.com/x/", "//b.com/p"), "https://b.com/p") + Assert.eq(Url.absolute("https://a.com/x/", "javascript:void(0)"), "") + local spec = Url.build('/s,{"body":"kw={{key}}&p={{page}}","method":"POST"}', { sourceUrl = "https://a.com/", key = "你好", page = 2 }) + Assert.eq(spec.url, "https://a.com/s") + Assert.eq(spec.method, "POST") + Assert.eq(spec.body, "kw=%E4%BD%A0%E5%A5%BD&p=2") + Assert.eq(Url.build("/search/{{key}}", { sourceUrl = "https://a.com/", key = "我的 书" }).url, + "https://a.com/search/%E6%88%91%E7%9A%84%20%E4%B9%A6") + Assert.eq(Url.build("/s/%E6%88%91?q=我", { sourceUrl = "https://a.com/" }).url, "https://a.com/s/%E6%88%91?q=%E6%88%91") + Assert.eq(Url.build("/l/.html", { sourceUrl = "https://a.com/", page = 9 }).url, "https://a.com/l/c.html") + Assert.errors(function() Url.build('/s,{"webView":true}', { sourceUrl = "https://a.com/" }) end) + Assert.errors(function() Url.build("/s?q={{java.get('x')}}", { sourceUrl = "https://a.com/" }) end) +end