320 lines
12 KiB
Lua
320 lines
12 KiB
Lua
--[[--
|
||
已导入的 Legado 书源:解析导入文本、存库、读取、启停、换源映射,以及发现页入口(exploreUrl)解析。
|
||
书源存在月读的 book.sqlite3:legadorule_sources(规则 JSON 原文,用到时才读出解码);
|
||
书源身份是 bookSourceUrl 的短哈希,seq 是导入顺序。
|
||
|
||
@module moonsource_legadorule.sources
|
||
--]]
|
||
|
||
local DB = require("utils.db")
|
||
local Json = require("moonsource_legadorule.json")
|
||
local Unsupported = require("moonsource_legadorule.unsupported")
|
||
|
||
local Sources = {}
|
||
|
||
---@param url string bookSourceUrl
|
||
---@return string 8 位十六进制
|
||
function Sources.key(url)
|
||
local bit = require("bit")
|
||
local h = 5381
|
||
for i = 1, #url do h = bit.band(h * 33 + url:byte(i), 0x7fffffff) end
|
||
local g = 2166136261
|
||
for i = 1, #url do g = bit.band(bit.bxor(g, url:byte(i)) * 16777619, 0x7fffffff) end
|
||
return string.format("%04x%04x", bit.band(h, 0xffff), bit.band(g, 0xffff))
|
||
end
|
||
|
||
--- 导入文本:一个书源对象、书源数组,或每行一个对象。返回有效书源数组与被跳过的数量。
|
||
---@param text string
|
||
---@return table[] rules
|
||
---@return integer skipped
|
||
function Sources.parse(text)
|
||
text = text:gsub("^\239\187\191", "")
|
||
local rules, skipped = {}, 0
|
||
local function take(v)
|
||
if Json.isObject(v) and type(v.bookSourceUrl) == "string" and v.bookSourceUrl ~= "" then
|
||
rules[#rules + 1] = v
|
||
else
|
||
skipped = skipped + 1
|
||
end
|
||
end
|
||
local v = Json.decode(text)
|
||
if Json.isArray(v) then
|
||
for _idx, item in ipairs(v) do take(item) end
|
||
elseif v ~= nil then
|
||
take(v)
|
||
else
|
||
for line in text:gmatch("[^\r\n]+") do
|
||
local item = Json.decode(line)
|
||
if item ~= nil then take(item) else skipped = skipped + 1 end
|
||
end
|
||
end
|
||
return rules, skipped
|
||
end
|
||
|
||
DB.schema("legadorule_sources", function()
|
||
if DB.exec([[
|
||
CREATE TABLE IF NOT EXISTS legadorule_sources (
|
||
key TEXT PRIMARY KEY, url TEXT NOT NULL, name TEXT NOT NULL,
|
||
enabled INTEGER NOT NULL DEFAULT 1, json TEXT NOT NULL,
|
||
seq INTEGER NOT NULL,
|
||
reason TEXT, ms INTEGER, checked INTEGER
|
||
);
|
||
DROP TABLE IF EXISTS legadorule_subs;
|
||
]]) == nil then return false end
|
||
-- 早期建的表没有检查结果列:补上
|
||
local info, n = DB.query("PRAGMA table_info(legadorule_sources);")
|
||
local have = {}
|
||
for i = 1, n or 0 do have[info[2][i]] = true end
|
||
for _idx, col in ipairs({ { "reason", "TEXT" }, { "ms", "INTEGER" }, { "checked", "INTEGER" } }) do
|
||
if not have[col[1]] then
|
||
DB.exec("ALTER TABLE legadorule_sources ADD COLUMN " .. col[1] .. " " .. col[2] .. ";")
|
||
end
|
||
end
|
||
return true
|
||
end)
|
||
|
||
DB.schema("legadorule_alias", function()
|
||
return DB.exec([[
|
||
CREATE TABLE IF NOT EXISTS legadorule_alias (
|
||
stable_id TEXT PRIMARY KEY, key TEXT NOT NULL, book_url TEXT NOT NULL
|
||
);
|
||
]]) ~= nil
|
||
end)
|
||
|
||
local LIST = "SELECT key, url, name, enabled, reason, ms, checked FROM legadorule_sources"
|
||
|
||
local function entries(where, ...)
|
||
local result, n = DB.query(LIST .. (where or "") .. ";", ...)
|
||
local out = {}
|
||
for i = 1, n or 0 do
|
||
out[i] = { key = result[1][i], url = result[2][i], name = result[3][i],
|
||
enabled = tonumber(result[4][i]) == 1,
|
||
reason = result[5][i], ms = tonumber(result[6][i]), checked = tonumber(result[7][i]) }
|
||
end
|
||
return out
|
||
end
|
||
|
||
local function nextSeq(tbl)
|
||
return (tonumber(DB.rowexec("SELECT COALESCE(MAX(seq),0) FROM " .. tbl .. ";")) or 0) + 1
|
||
end
|
||
|
||
local function inList(keys)
|
||
local marks = {}
|
||
for i = 1, #keys do marks[i] = "?" end
|
||
return "(" .. table.concat(marks, ",") .. ")"
|
||
end
|
||
|
||
--- 全部已导入书源(不含规则原文):{ key, name, url, enabled, reason, ms(上次检查响应毫秒), checked(检查时间) },按导入顺序。
|
||
function Sources.all()
|
||
return entries(" ORDER BY seq ASC")
|
||
end
|
||
|
||
--- 分页查询:q 匹配名称或地址(不分大小写),status 为 "on" / "off" / nil。返回当页书源与符合条件的总数。
|
||
---@param q string|nil
|
||
---@param status string|nil
|
||
---@param page integer 从 1 起
|
||
---@param size integer
|
||
---@return table[] list
|
||
---@return integer total
|
||
function Sources.page(q, status, page, size)
|
||
local where, args = {}, {}
|
||
if q and q ~= "" then
|
||
local like = "%" .. q:gsub("[\\%%_]", "\\%0") .. "%"
|
||
where[#where + 1] = "(name LIKE ? ESCAPE '\\' OR url LIKE ? ESCAPE '\\')"
|
||
args[#args + 1] = like
|
||
args[#args + 1] = like
|
||
end
|
||
if status == "on" then where[#where + 1] = "enabled=1"
|
||
elseif status == "off" then where[#where + 1] = "enabled=0" end
|
||
local cond = #where > 0 and (" WHERE " .. table.concat(where, " AND ")) or ""
|
||
local total = tonumber(DB.rowexec("SELECT COUNT(*) FROM legadorule_sources" .. cond .. ";", unpack(args))) or 0
|
||
args[#args + 1] = size
|
||
args[#args + 1] = (page - 1) * size
|
||
return entries(cond .. " ORDER BY seq ASC LIMIT ? OFFSET ?", unpack(args)), total
|
||
end
|
||
|
||
---@return { all: integer, on: integer, off: integer }
|
||
function Sources.counts()
|
||
local all = tonumber(DB.rowexec("SELECT COUNT(*) FROM legadorule_sources;")) or 0
|
||
local on = Sources.enabledCount()
|
||
return { all = all, on = on, off = all - on }
|
||
end
|
||
|
||
function Sources.enabled()
|
||
return entries(" WHERE enabled=1 ORDER BY seq ASC")
|
||
end
|
||
|
||
---@return integer
|
||
function Sources.enabledCount()
|
||
return tonumber(DB.rowexec("SELECT COUNT(*) FROM legadorule_sources WHERE enabled=1;")) or 0
|
||
end
|
||
|
||
function Sources.find(key)
|
||
return entries(" WHERE key=?", key)[1]
|
||
end
|
||
|
||
local decoded = {}
|
||
|
||
--- 书源内容变更计数:解析器缓存据此失效。
|
||
Sources.version = 0
|
||
|
||
local function changed(key)
|
||
Sources.version = Sources.version + 1
|
||
if key then decoded[key] = nil else decoded = {} end
|
||
end
|
||
|
||
--- 取书源规则表(从库里读规则原文,解码一次)。
|
||
function Sources.rule(entry)
|
||
local rule = decoded[entry.key]
|
||
if not rule then
|
||
local text = DB.rowexec("SELECT json FROM legadorule_sources WHERE key=?;", entry.key)
|
||
rule = text and Json.decode(text)
|
||
decoded[entry.key] = rule
|
||
end
|
||
return rule
|
||
end
|
||
|
||
--- 读书必经的规则里是否含 JS / WebView 片段(静态判断,仅抓明显的 <js>、@js:、webView 选项)。
|
||
---@param rule table
|
||
---@return boolean ok
|
||
---@return string|nil reason
|
||
function Sources.supported(rule)
|
||
local parts = { tostring(rule.searchUrl or "") }
|
||
for _idx, f in ipairs({ "ruleSearch", "ruleBookInfo", "ruleToc", "ruleContent" }) do
|
||
if rule[f] ~= nil then parts[#parts + 1] = Json.encode(rule[f]) end
|
||
end
|
||
local text = table.concat(parts, "\n")
|
||
if Unsupported.isJsSnippet(text) or text:lower():find('webview"?%s*[:=]%s*"?true', 1) then
|
||
return false, Unsupported.MESSAGE
|
||
end
|
||
return true
|
||
end
|
||
|
||
--- 导入(同 bookSourceUrl 覆盖,保留原启停状态);含 JS / WebView 的书源导入即禁用。返回新增数量与被禁用数量。
|
||
function Sources.add(rules)
|
||
local added, disabled = 0, 0
|
||
DB.transaction(function()
|
||
local seq = nextSeq("legadorule_sources")
|
||
for _idx, rule in ipairs(rules) do
|
||
local key = Sources.key(rule.bookSourceUrl)
|
||
local name = tostring(rule.bookSourceName or rule.bookSourceUrl)
|
||
local text = Json.encode(rule)
|
||
changed(key)
|
||
local ok, why = Sources.supported(rule)
|
||
if not ok then disabled = disabled + 1 end
|
||
local exists = DB.rowexec("SELECT 1 FROM legadorule_sources WHERE key=?;", key)
|
||
if exists then
|
||
DB.exec("UPDATE legadorule_sources SET url=?, name=?, json=?, enabled=CASE WHEN ? THEN enabled ELSE 0 END, reason=?, ms=NULL, checked=NULL WHERE key=?;",
|
||
rule.bookSourceUrl, name, text, ok and 1 or 0, why, key)
|
||
else
|
||
DB.exec("INSERT INTO legadorule_sources(key,url,name,enabled,json,seq,reason) VALUES(?,?,?,?,?,?,?);",
|
||
key, rule.bookSourceUrl, name, ok and 1 or 0, text, seq, why)
|
||
seq = seq + 1
|
||
added = added + 1
|
||
end
|
||
end
|
||
return true
|
||
end)
|
||
return added, disabled
|
||
end
|
||
|
||
function Sources.setEnabled(key, enabled)
|
||
Sources.setEnabledMany({ key }, enabled)
|
||
end
|
||
|
||
---@param keys string[]
|
||
---@param enabled boolean
|
||
function Sources.setEnabledMany(keys, enabled)
|
||
if #keys == 0 then return end
|
||
DB.transaction(function()
|
||
for i = 1, #keys, 500 do
|
||
local chunk = { unpack(keys, i, math.min(i + 499, #keys)) }
|
||
DB.exec("UPDATE legadorule_sources SET enabled=?" .. (enabled and ", reason=NULL" or "") ..
|
||
" WHERE key IN " .. inList(chunk) .. ";",
|
||
enabled and 1 or 0, unpack(chunk))
|
||
end
|
||
return true
|
||
end)
|
||
end
|
||
|
||
--- 记录一次检查:响应毫秒与结果;无效(reason 非空)时同时禁用。
|
||
---@param key string
|
||
---@param ms integer|nil
|
||
---@param reason string|nil 无效原因,有效传 nil
|
||
function Sources.setCheck(key, ms, reason)
|
||
if reason then reason = reason:sub(1, 200) end
|
||
DB.exec("UPDATE legadorule_sources SET ms=?, reason=?, checked=?, enabled=CASE WHEN ? THEN 0 ELSE enabled END WHERE key=?;",
|
||
ms, reason, os.time(), reason and 1 or 0, key)
|
||
end
|
||
|
||
function Sources.remove(key)
|
||
Sources.removeMany({ key })
|
||
end
|
||
|
||
---@param keys string[]
|
||
---@return integer removed
|
||
function Sources.removeMany(keys)
|
||
local removed = 0
|
||
DB.transaction(function()
|
||
for i = 1, #keys, 500 do
|
||
local chunk = { unpack(keys, i, math.min(i + 499, #keys)) }
|
||
DB.exec("DELETE FROM legadorule_sources WHERE key IN " .. inList(chunk) .. ";", unpack(chunk))
|
||
removed = removed + (tonumber(DB.rowexec("SELECT changes();")) or 0)
|
||
for _idx, k in ipairs(chunk) do changed(k) end
|
||
end
|
||
return true
|
||
end)
|
||
return removed
|
||
end
|
||
|
||
--- 换源:书架里的书身份(stable_id)不变,改成从另一个书源的书地址读取。
|
||
---@param stable_id string
|
||
---@param key string 新书源 key
|
||
---@param bookUrl string 新书源里的书地址
|
||
function Sources.setAlias(stable_id, key, bookUrl)
|
||
DB.exec("INSERT OR REPLACE INTO legadorule_alias(stable_id,key,book_url) VALUES(?,?,?);", stable_id, key, bookUrl)
|
||
end
|
||
|
||
--- 该身份换过源则返回新的 key 与书地址。
|
||
---@param stable_id string
|
||
---@return string|nil key, string|nil bookUrl
|
||
function Sources.alias(stable_id)
|
||
local key, url = DB.rowexec("SELECT key, book_url FROM legadorule_alias WHERE stable_id=?;", stable_id)
|
||
return key, url
|
||
end
|
||
|
||
--- 发现入口:`标题::地址` 每行一条,或 [{title,url}] JSON。含 JS 的条目跳过。
|
||
---@param rule table
|
||
---@return { title: string, url: string }[]
|
||
function Sources.explore(rule)
|
||
local raw = rule.exploreUrl
|
||
local out = {}
|
||
local function add(title, url)
|
||
if type(title) == "string" and type(url) == "string" and url ~= "" and not Unsupported.isJsSnippet(url) then
|
||
out[#out + 1] = { title = title ~= "" and title or url, url = url }
|
||
end
|
||
end
|
||
if Json.isArray(raw) then
|
||
for _idx, item in ipairs(raw) do
|
||
if Json.isObject(item) then add(item.title, item.url) end
|
||
end
|
||
elseif type(raw) == "string" then
|
||
local text = raw:gsub("^%s+", "")
|
||
if Unsupported.isJsSnippet(text) then return out end
|
||
local arr = text:sub(1, 1) == "[" and Json.decode(text)
|
||
if Json.isArray(arr) then
|
||
for _idx, item in ipairs(arr) do
|
||
if Json.isObject(item) then add(item.title, item.url) end
|
||
end
|
||
else
|
||
for line in (text:gsub("&&", "\n") .. "\n"):gmatch("(.-)\r?\n") do
|
||
local title, url = line:match("^(.-)::(.+)$")
|
||
if title then add(title:gsub("^%s+", ""):gsub("%s+$", ""), url:gsub("^%s+", ""):gsub("%s+$", "")) end
|
||
end
|
||
end
|
||
end
|
||
return out
|
||
end
|
||
|
||
return Sources
|