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

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

No files matched your search

@@ -0,0 +1,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