✨ (switch): 书架换源,网页后台搜索并显示进度,书架记录与进度不变

This commit is contained in:
garfield committed 2026-12-04 00:33:36 +08:00
1 parent f0d737e68a
commit b8faeddda5
2 files changed
+362

No files matched your search

@@ -0,0 +1,205 @@
--[[--
开源阅读书源设置:导入 Legado 书源(地址 / 本地文件 / 粘贴 JSON)、启停与删除、书架换源。
@module moonsource_legadorule.setting
--]]
local _ = require("l10n").get("moonsource_legadorule")
local T = require("ffi/util").template
local Setting = {}
function Setting.rowIcon()
return "library_books"
end
---@return string, boolean
function Setting.rowStatus()
local Sources = require("moonsource_legadorule.sources")
local all, on = Sources.all(), #Sources.enabled()
if #all == 0 then return _("未导入"), false end
return T(_("%1 个,启用 %2 个"), #all, on), on > 0
end
local function toast(text)
require("ui.themes.widgets.toast"):new{ text = text, timeout = 3 }:show()
end
local function finishImport(text)
local Sources = require("moonsource_legadorule.sources")
local rules, skipped = Sources.parse(text)
if #rules == 0 then
toast(_("没有找到有效的书源"))
return
end
Sources.add(rules)
require("source.registry").reload()
toast(T(_("已导入 %1 个书源,跳过 %2 个无效项"), #rules, skipped))
end
local function import(value)
local Text = require("utils.text")
value = Text.trim(value)
if value:match("^https?://") then
require("ui/network/manager"):runWhenConnected(function()
local waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("导入书源"), text = _("正在导入…"), dismissable = false,
}
waiting:show()
require("http.request").get(value, { timeout = 60, allow_redirects = true }, function(body, err)
waiting:close()
if not body then toast(err or _("无法读取书源")) return end
finishImport(body)
end)
end)
elseif value:sub(1, 1) == "/" then
local f = io.open(value, "rb")
if not f then toast(_("无法读取书源")) return end
local body = f:read("*a")
f:close()
finishImport(body)
else
finishImport(value)
end
end
local function importDialog()
require("ui.themes.widgets.input"):new{
title = _("导入书源"),
fields = { { text = "", hint = _("书源地址、本地文件路径或 JSON") } },
ok_text = _("导入"),
callback = function(value) if value and value ~= "" then import(value) end end,
}:show()
end
local function manageOne(entry)
local Sources = require("moonsource_legadorule.sources")
require("ui.themes.widgets.list"):new{
title = entry.name,
items = {
{ text = entry.enabled and _("停用") or _("启用"), value = "toggle" },
{ text = _("删除"), value = "delete" },
},
on_select = function(value)
if value == "toggle" then
Sources.setEnabled(entry.key, not entry.enabled)
toast(entry.enabled and _("已停用") or _("已启用"))
else
Sources.remove(entry.key)
toast(_("已删除"))
end
require("source.registry").reload()
end,
}:show()
end
local function manage()
local Sources = require("moonsource_legadorule.sources")
local items = {}
for _idx, entry in ipairs(Sources.all()) do
items[#items + 1] = { text = (entry.enabled and "" or "✗ ") .. entry.name, value = entry }
end
if #items == 0 then toast(_("未导入")) return end
require("ui.themes.widgets.list"):new{
title = _("管理书源"), items = items, on_select = manageOne,
}:show()
end
-- ── 书架换源:书的身份、进度、阅读时间都不动,只把读取来源指向另一个书源 ──
local function bookKey(book)
return require("moonsource_legadorule.switch").keyOf(book.stable_id)
end
local function applySwitch(book, picked)
local ok, err = require("moonsource_legadorule.switch").apply(book.stable_id, picked.stable_id)
if ok then toast(T(_("已换到 %1"), picked.source_name or "")) else toast(tostring(err)) end
end
local function pickTarget(book, results)
local current = bookKey(book)
local items = {}
for _idx, row in ipairs(results) do
local key = require("moonsource_legadorule.mapper").splitStableId(row.stable_id)
if key ~= current then
local author = (row.authors and row.authors ~= "") and (" · " .. row.authors) or ""
items[#items + 1] = { text = row.title .. author .. " [" .. tostring(row.source_name) .. "]", value = row }
end
end
if #items == 0 then toast(_("其他书源里没有找到这本书")) return end
require("ui.themes.widgets.list"):new{
title = T(_("换源:%1"), book.title),
items = items,
on_select = function(row) applySwitch(book, row) end,
}:show()
end
local function searchTargets(book)
local source = require("source.registry").resolve("legadorule")
if not source then toast(_("书源不可用")) return end
require("ui/network/manager"):runWhenConnected(function()
local waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("换源"), text = T(_("正在其他书源里搜索《%1》…"), book.title), dismissable = false,
}
waiting:show()
source:searchAsync(book.title, function(res, err)
waiting:close()
if not res then toast(err or _("搜索失败")) return end
local exact, all = {}, res.data or {}
for _idx, row in ipairs(all) do
if row.title == book.title then exact[#exact + 1] = row end
end
pickTarget(book, #exact > 0 and exact or all)
end)
end)
end
local function switchSource()
local Sources = require("moonsource_legadorule.sources")
local alive = {}
for _idx, entry in ipairs(Sources.enabled()) do alive[entry.key] = true end
local items = {}
for _idx, book in ipairs(require("book.books_db").listLibrary()) do
if book.source_id == "legadorule" then
local broken = not alive[bookKey(book) or ""]
items[#items + 1] = { text = (broken and "✗ " or "") .. book.title, value = book, broken = broken }
end
end
if #items == 0 then toast(_("书架里还没有这个书源的书")) return end
-- 来源已失效的书排在前面
table.sort(items, function(a, b)
if a.broken ~= b.broken then return a.broken end
return a.text < b.text
end)
require("ui.themes.widgets.list"):new{
title = _("书架换源"), items = items, on_select = searchTargets,
}:show()
end
---@return table[]
function Setting.rows()
local Row = function() return require("ui.themes.widgets.row") end
return {
function(iw)
local status, on = Setting.rowStatus()
return Row().widget({
width = iw, chevron = true, kind = "nav", icon = "library_books", title = _("管理书源"),
status = status, status_on = on, callback = manage,
})
end,
function(iw)
return Row().widget({
width = iw, chevron = true, kind = "nav", icon = "download", title = _("导入书源"),
callback = importDialog,
})
end,
function(iw)
return Row().widget({
width = iw, chevron = true, kind = "nav", icon = "sync", title = _("书架换源"),
callback = switchSource,
})
end,
}
end
return Setting
@@ -0,0 +1,157 @@
--[[--
书架换源:书的身份(stable_id)、进度、阅读时间都不动,只把读取来源指向另一个书源。
搜索在后台逐个书源进行,进度和结果由 status() 读取;同时只跑一个任务,网页离开后回来仍能接上。
@module moonsource_legadorule.switch
--]]
local Sources = require("moonsource_legadorule.sources")
local Mapper = require("moonsource_legadorule.mapper")
local SOURCE_ID = "legadorule"
local PARALLEL = 6
local Switch = {}
local job = { running = false, total = 0, done = 0, results = {} }
--- 书当前实际读取的书源 key(换过源则是新书源)。
function Switch.keyOf(stable_id)
local key = Sources.alias(stable_id)
if key then return key end
return (Mapper.splitStableId(stable_id))
end
--- 书架里本书源的书;来源已停用或不存在的排在前面。
function Switch.books()
local alive = {}
for _idx, entry in ipairs(Sources.enabled()) do alive[entry.key] = true end
local out = {}
for _idx, book in ipairs(require("book.books_db").listLibrary()) do
if book.source_id == SOURCE_ID then
local key = Switch.keyOf(book.stable_id)
local entry = key and Sources.find(key)
out[#out + 1] = {
stable_id = book.stable_id,
title = book.title,
authors = book.authors or "",
source_name = entry and entry.name or key,
broken = not alive[key or ""],
switched = Sources.alias(book.stable_id) ~= nil,
}
end
end
table.sort(out, function(a, b)
if a.broken ~= b.broken then return a.broken end
return a.title < b.title
end)
return out
end
local function errMessage(err) return require("moonsource_legadorule.unsupported").message(err) end
--- 其他书源里同名的排前面,作者也一致的更靠前。
local function rank(rows, book)
local function score(r)
if r.title ~= book.title then return 0 end
if book.authors ~= "" and r.authors == book.authors then return 2 end
return 1
end
for _idx, r in ipairs(rows) do r.score = score(r) end
table.sort(rows, function(a, b)
if a.score ~= b.score then return a.score > b.score end
return false
end)
return rows
end
--- 在其他启用的书源里后台搜同名书;已有任务在跑则返回 false。
---@param book table { stable_id, title, authors }
function Switch.start(book)
if job.running then return false end
local current = Switch.keyOf(book.stable_id)
local entries = {}
for _idx, entry in ipairs(Sources.enabled()) do
if entry.key ~= current then entries[#entries + 1] = entry end
end
local state = { running = #entries > 0, stable_id = book.stable_id, title = book.title,
total = #entries, done = 0, results = {}, current = {} }
job = state
local nextIdx, active = 0, 0
local handles = {}
state.cancel = function()
state.running = false
for _idx, h in ipairs(handles) do pcall(h.cancel) end
end
local function settle(slot, name, rows)
if not state.running or slot.settled then return end
slot.settled = true
active = active - 1
state.done = state.done + 1
for _idx, r in ipairs(rows or {}) do state.results[#state.results + 1] = r end
rank(state.results, book)
if state.done >= state.total then state.running = false end
state.launch()
end
function state.launch()
while state.running and active < PARALLEL and nextIdx < #entries do
nextIdx = nextIdx + 1
local entry = entries[nextIdx]
local slot = {}
active = active + 1
local made, parser = pcall(function()
return require("moonsource_legadorule.parser").new(Sources.rule(entry))
end)
if not made then
settle(slot, entry.name, nil)
else
local ran, handle = pcall(parser.search, parser, book.title, 1, function(books)
local rows = {}
for _idx, b in ipairs(type(books) == "table" and books or {}) do
rows[#rows + 1] = Mapper.book(SOURCE_ID, entry.key, b, entry.name)
end
settle(slot, entry.name, rows)
end)
if ran then
handles[#handles + 1] = handle
else
settle(slot, entry.name, nil)
end
end
end
end
state.launch()
return true
end
function Switch.cancel()
if job.running and job.cancel then job.cancel() end
end
--- 进度与目前已找到的结果(排好序,最多 100 条)。
function Switch.status()
local rows = {}
for i, r in ipairs(job.results) do
if i > 100 then break end
rows[i] = { stable_id = r.stable_id, title = r.title, authors = r.authors, cover = r.cover,
source_name = r.source_name, score = r.score }
end
return { running = job.running, stable_id = job.stable_id, title = job.title,
total = job.total, done = job.done, results = rows }
end
--- 把 stable_id 这本书改读 picked(另一书源里的书的 stable_id)。
---@return boolean ok, string|nil err
function Switch.apply(stable_id, picked)
local key, url = Mapper.splitStableId(picked or "")
if not key or not url then return false, "目标书无效" end
if not Sources.find(key) then return false, "目标书源不存在" end
Sources.setAlias(stable_id, key, url)
-- 目录改用新书源:旧缓存作废,下次打开重新拉取
pcall(function() require("source.toc").drop(SOURCE_ID, stable_id) end)
return true
end
return Switch