Files
Garfield 93c0413424 🐛 修复目录倒序导致开书落到未购买章
ep_list 最新话在前,startIndex 默认取第一项于是开书总落在锁定章弹「本章未购买」。改为按 ord 升序排、加 toc_version 强制旧缓存重拉;首话 title 为空时回落 short_title。
2026-11-27 08:49:17 +08:00

359 lines
12 KiB
Lua

local SourceBase = require("source.base")
local Client = require("moonsource_bilimanga.client")
local Mapper = require("moonsource_bilimanga.mapper")
local Chapter = require("moonsource_bilimanga.chapter")
local Toc = require("source.toc")
local _ = require("moonsource_bilimanga.l10n")
local BiliManga = setmetatable({}, { __index = SourceBase })
BiliManga.__index = BiliManga
local SOURCE_ID
function BiliManga.meta()
return require("moonsource_bilimanga.loadmeta")()
end
function BiliManga.new()
local meta = BiliManga.meta()
SOURCE_ID = meta.id
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, BiliManga)
end
function BiliManga:configured()
return Client.hasAccount()
end
function BiliManga:searchAsync(keyword, cb)
return Client.searchAsync(keyword, 1, 20, function(wire, err)
if err then cb(nil, err); return end
local books = Mapper.searchResults(wire)
if not books or #books == 0 then
cb(nil, _("无搜索结果"))
return
end
cb({ data = books })
end)
end
function BiliManga:getDetailAsync(identity, cb)
local existing = identity.book
or require("book.books_db").get(identity.source_id or SOURCE_ID, identity.stable_id)
if existing then
cb(require("book.store").rememberDetail(existing))
return
end
return Client.comicDetailAsync(identity.stable_id, function(info, err)
if err then cb(nil, err); return end
local book = Mapper.book(info)
require("book.store").rememberDetail(book)
cb(book)
end)
end
--- 当前格式的缓存目录;旧格式(倒序)当作没有。
---@param identity BookIdentity
---@return table[]|nil
local function cachedToc(identity)
local toc = Toc.read(identity.source_id or SOURCE_ID, identity.stable_id)
if toc and toc[1] and toc[1].toc_version == Mapper.TOC_VERSION then return toc end
return nil
end
function BiliManga:loadTocAsync(identity, cb, force)
if not force then
local cached = cachedToc(identity)
if cached then
return SourceBase.defer(cb, cached)
end
end
return self:refreshTocAsync(identity, cb)
end
function BiliManga:refreshTocAsync(identity, cb)
return Client.comicDetailAsync(identity.stable_id, function(info, err)
if err then cb(nil, err); return end
local chapters = Mapper.chapters(info)
if not chapters or #chapters == 0 then
cb(nil, _("加载目录失败"))
return
end
Toc.put(identity.source_id or SOURCE_ID, identity.stable_id, chapters)
if identity.book and not identity.book._toc_fetched then
info._toc_fetched = true
end
cb(chapters)
end)
end
--- 起始章:调用方指定的章 > 本地待推进度 > 第一章。
---@param identity BookIdentity
---@param opts table
---@param toc table[]
---@return integer
local function startIndex(identity, opts, toc)
local idx = opts.chapter_idx
if not idx then
local pending = require("book.progress_db").get(identity.source_id, identity.stable_id)
idx = pending and (pending.chapter_idx or math.floor((pending.fraction or 0) * #toc) + 1)
end
return math.max(1, math.min(#toc, idx or 1))
end
function BiliManga:openBookAsync(identity, opts, cb)
opts = opts or {}
local function finish(path, idx)
local ok, err = require("book.store").touch(path, identity, {
chapter_idx = idx,
book = identity.book,
})
cb(ok and path or nil, err)
end
local toc = cachedToc(identity)
if toc then
local idx = startIndex(identity, opts, toc)
local path = Chapter.existing(identity, toc[idx])
if path then return SourceBase.defer(finish, path, idx) end
end
if not require("ui/network/manager"):isConnected() then
return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi"))
end
local cancelled, active, dialog = false, nil, nil
local function closeDialog()
if dialog then dialog:close(); dialog = nil end
end
require("ui/uimanager"):nextTick(function()
if cancelled then return end
dialog = require("ui.themes.widgets.progress_dialog"):new{
title = identity.book and identity.book.title or identity.stable_id,
dismissable = false,
}
dialog:show()
dialog:set(_("正在准备漫画…"))
local loaded = false
local toc_job = self:loadTocAsync(identity, function(fresh, err)
loaded = true
active = nil
if cancelled then return end
if not fresh then closeDialog(); cb(nil, err or _("加载目录失败")); return end
local idx = startIndex(identity, opts, fresh)
local materialized = false
local chapter_job = Chapter.materializeAsync(identity, fresh[idx], function(done, total)
if dialog and total > 0 then dialog:update(_("正在准备漫画…"), done, total) end
end, function(path, materialize_err)
materialized = true
active = nil
closeDialog()
if cancelled then return end
if not path then cb(nil, materialize_err or _("章节图片解析失败")); return end
finish(path, idx)
end)
if not materialized then active = chapter_job end
end)
if not loaded then active = toc_job end
end)
return { cancel = function()
cancelled = true
if active then active.cancel() end
closeDialog()
end }
end
function BiliManga:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
return require("source.chapter").prefetchAsync(
identity, identity.book, toc, from_idx, count, {
fetchContent = Chapter.fetcher(self),
interval_seconds = 1.0,
}, cb)
end
function BiliManga:cacheAllChaptersAsync(identity, on_progress, cb, range)
return require("source.chapter").cacheAllAsync(
self, identity,
Chapter.fetcher(self),
on_progress, cb, 1.0, range)
end
function BiliManga:getProgressAsync(identity, cb)
local cfg = require("utils.settings").getSource("bilimanga")
if not cfg.cookie or cfg.cookie == "" then
return SourceBase.defer(cb, nil, nil, { empty = true })
end
local remote = Client.newSync and Client.newSync(false) or { cancelled = false, cancel = function() end }
Client.getUserInfoAsync(function(wire, err)
if remote.cancelled then return end
if err then cb(nil, err); return end
Client.listHistoryAsync(1, 50, function(hist_wire, hist_err)
if remote.cancelled then return end
if hist_err then cb(nil, hist_err); return end
local item = Mapper.historyItem(hist_wire, identity.stable_id)
if not item then
cb(nil, nil, { empty = true })
return
end
local last_ep_id = item.last_ep_id or item.ep_id
if not last_ep_id then
cb(nil, nil, { empty = true })
return
end
local function afterToc(toc, toc_err)
if remote.cancelled then return end
if not toc then cb(nil, toc_err); return end
for i, ch in ipairs(toc) do
if ch.uid == tostring(last_ep_id) then
cb({
chapter_idx = i,
chapter_title = ch.title,
fraction = (i - 1) / #toc,
})
return
end
end
cb(nil, nil, { empty = true })
end
local existing = cachedToc(identity)
if existing then
afterToc(existing)
else
self:refreshTocAsync(identity, afterToc)
end
end)
end)
return {
cancel = function()
remote.cancelled = true
end,
}
end
function BiliManga:putProgressAsync(identity, pos, cb)
local cfg = require("utils.settings").getSource("bilimanga")
if not cfg.cookie or cfg.cookie == "" then
cb(nil, _("未登录"))
return
end
self:loadTocAsync(identity, function(toc, toc_err)
if toc_err then cb(nil, toc_err); return end
local idx = pos.chapter_idx or identity.chapter_idx or 1
if not toc[idx] then cb(nil, _("章节不存在")); return end
Client.addHistoryAsync(identity.stable_id, toc[idx].uid, function(wire, err)
if err then cb(nil, err); return end
cb(true)
end)
end)
return { cancel = function() end }
end
BiliManga.shelf_add = true
--- 收藏夹即远端书架:Shelf.syncAsync 要的 shelfSyncAsync / addToShelfAsync / removeFromShelfAsync。
local Favorites = {}
Favorites.__index = Favorites
local FAVORITE_PAGE = 50
--- "2026-11-27 00:40:55"(北京时间)→ 时间戳;空串 / 格式不对为 0。
---@param text any
---@return integer
local function beijingTime(text)
local y, mo, d, h, mi, s = tostring(text or ""):match("^(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)$")
if not y then return 0 end
local as_local = os.time({ year = tonumber(y), month = tonumber(mo), day = tonumber(d),
hour = tonumber(h), min = tonumber(mi), sec = tonumber(s) })
local local_offset = os.time(os.date("*t", as_local)) - os.time(os.date("!*t", as_local))
return as_local + local_offset - 8 * 3600
end
--- 整个收藏夹(逐页拉,接口的 total 不可靠,按满页判断还有没有下一页)。
---@param cb fun(books: Book[]|nil, err: string|nil)
function Favorites:shelfSyncAsync(cb)
local books, page = {}, 1
local function nextPage()
self.job = Client.listFavoriteAsync(page, FAVORITE_PAGE, function(wire, err)
self.job = nil
if self.cancelled then return end
local items = wire and Mapper.favoriteItems(wire)
if not items then cb(nil, err or _("响应无效")); return end
for _idx, item in ipairs(items) do
local book = Mapper.bookFromItem(item)
if not book then cb(nil, _("响应无效")); return end
book.read_at = beijingTime(item.latest_read_time)
books[#books + 1] = book
end
if #items < FAVORITE_PAGE then cb(books); return end
page = page + 1
nextPage()
end)
end
nextPage()
return self
end
function Favorites:addToShelfAsync(stable_id, cb)
self.job = Client.addFavoriteAsync(stable_id, cb)
return self
end
function Favorites:removeFromShelfAsync(stable_id, cb)
self.job = Client.deleteFavoriteAsync(stable_id, cb)
return self
end
function Favorites:cancel()
self.cancelled = true
if self.job then self.job.cancel() end
end
function BiliManga:syncBooksAsync(opts, cb)
if not Client.hasAccount() then return SourceBase.skipped(cb, "not_logged_in") end
local remote = setmetatable({ cancelled = false }, Favorites)
local job = require("source.shelf").syncAsync(self.id, remote, nil, opts, cb)
return { cancel = function()
remote:cancel()
job:cancel()
end }
end
function BiliManga:browseAsync(opts, cb)
opts = opts or {}
local limit = opts.limit or 60
local state = { cancelled = false, job = nil }
state.job = Client.allLabelAsync(function(wire, err)
if state.cancelled then return end
local labels = Mapper.labels(wire)
if err or not labels then cb(nil, err or _("响应无效")); return end
local order, style = Mapper.storeChoice(opts.node, labels)
local groups = Mapper.storeGroups(labels, order, style)
state.job = require("source.browse").pages(function(page, done)
return Client.classPageAsync({ order = order, style_id = style }, page, function(rows, page_err)
if state.cancelled then return end
if page_err then done(nil, page_err); return end
local books = Mapper.books(rows)
if not books then done(nil, _("响应无效")); return end
done(books, nil, #books == 15)
end)
end, limit, groups, function(result, reason)
state.job = nil
if not state.cancelled then cb(result, reason) end
end)
end)
return { cancel = function()
state.cancelled = true
if state.job and state.job.cancel then state.job.cancel() end
end }
end
return BiliManga