--[[-- URL 层:相对地址补全(NetworkUtils)与书源 URL 规则解析(AnalyzeUrl)。 `{{key}}` `{{page+1}}` `` 翻页、`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