--[[-- 书源规则求值器(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 = "