1655 lines
66 KiB
Lua
1655 lines
66 KiB
Lua
--[[--
|
||
微信读书数据源门面(仅异步网络)
|
||
|
||
eink.lua 管扫码会话与 App 接口,auth.lua 管网页会话。
|
||
进度与时长都走 App ``/book/read``:进度带本地坐标和还没报的时长。
|
||
跨小时,或补报离线积压,改走 ``/book/batchUploadProgress``。
|
||
时长单独上报只发生在进度已同步、书也没开着的时候,坐标用上次报上去的本地位置。
|
||
划线经 notes.lua / annotations.lua 与网页 range 互定位。
|
||
|
||
@module moonsource_weread
|
||
--]]
|
||
|
||
local Auth = require("moonsource_weread.auth")
|
||
local Client = require("moonsource_weread.client")
|
||
local Mapper = require("moonsource_weread.mapper")
|
||
local WChapter = require("moonsource_weread.chapter")
|
||
local Notes = require("moonsource_weread.notes")
|
||
local NotesPush = require("moonsource_weread.notes_push")
|
||
local Toc = require("moonsource_weread.toc")
|
||
local Reviews = require("moonsource_weread.reviews")
|
||
local ReviewCache = require("book.review_cache")
|
||
local Browse = require("source.browse")
|
||
local SourceBase = require("source.base")
|
||
local Shelf = require("source.shelf")
|
||
local Progress = require("book.progress")
|
||
local App = require("moonsource_weread.app")
|
||
local Eink = require("moonsource_weread.eink")
|
||
local logger = require("utils.log")
|
||
local Text = require("utils.text")
|
||
local _ = require("l10n").get("moonsource_weread")
|
||
|
||
local WeChat = {}
|
||
|
||
--- 返回微信读书源元信息。
|
||
---@return BookSourceMeta
|
||
function WeChat.meta()
|
||
return require("moonsource_weread.loadmeta")()
|
||
end
|
||
|
||
---@class WechatSource : SourceBase
|
||
---@field cfg table
|
||
---@field _client table
|
||
---@field _covers table<string, string>
|
||
---@field _page_sync_timer function|nil
|
||
---@field _page_sync_job table|nil
|
||
---@field _page_sync_again boolean|nil
|
||
---@field _presence table|nil
|
||
local Source = setmetatable({}, { __index = SourceBase })
|
||
Source.__index = Source
|
||
|
||
--- 构造微信读书源实例。
|
||
---@return WechatSource
|
||
function WeChat.new()
|
||
local cfg = require("utils.settings").getSource("weread")
|
||
local meta = WeChat.meta()
|
||
---@type WechatSource
|
||
return setmetatable({
|
||
id = meta.id,
|
||
name = meta.name,
|
||
type = meta.type,
|
||
cfg = cfg,
|
||
_client = Client,
|
||
_covers = {},
|
||
_page_sync_timer = nil,
|
||
_page_sync_job = nil,
|
||
_page_sync_again = false,
|
||
_presence = nil,
|
||
}, Source)
|
||
end
|
||
|
||
--- 缓存书籍封面 URL(仅接受 http(s))。
|
||
---@param self WechatSource
|
||
---@param stable_id string
|
||
---@param url string
|
||
local function rememberCover(self, stable_id, url)
|
||
if url:find("^https?://") then
|
||
self._covers[stable_id] = url
|
||
end
|
||
end
|
||
|
||
--- 返回微信读书源能力集。
|
||
---@return SourceCapabilities
|
||
function Source:capabilities()
|
||
return {
|
||
scrape = false,
|
||
edit = true,
|
||
stats_pull = true,
|
||
shelf_add = true,
|
||
}
|
||
end
|
||
|
||
--- 是否已登录微信读书。
|
||
---@return boolean
|
||
function Source:configured()
|
||
return Auth.hasSession()
|
||
end
|
||
|
||
local PAGE_PROGRESS_SYNC_DELAY = 5
|
||
|
||
---@param session ReaderSessionSnapshot|nil
|
||
---@param identity BookIdentity
|
||
---@return boolean
|
||
local function isCurrentBook(session, identity)
|
||
local id = session and session.identity
|
||
return id ~= nil and id.source_id == identity.source_id and id.stable_id == identity.stable_id
|
||
end
|
||
|
||
local schedulePageProgressSync
|
||
|
||
---@param self WechatSource
|
||
---@param identity BookIdentity
|
||
local function pushPageProgress(self, identity)
|
||
if self._page_sync_job then
|
||
self._page_sync_again = true
|
||
return
|
||
end
|
||
if not self:configured() or not require("ui/network/manager"):isConnected() then return end
|
||
|
||
local job
|
||
job = self:syncProgressAsync({ identity = identity, dirty_only = true }, function(result)
|
||
require("ui/uimanager"):nextTick(function()
|
||
if self._page_sync_job ~= job then return end
|
||
self._page_sync_job = nil
|
||
if not self._page_sync_again then return end
|
||
self._page_sync_again = false
|
||
if not result or (result.pushed or 0) == 0 then return end
|
||
|
||
local row = require("book.progress_db").get(self.id, identity.stable_id)
|
||
if not row or row.sync_status ~= 0 or not self:configured()
|
||
or not require("ui/network/manager"):isConnected() then
|
||
return
|
||
end
|
||
local current = require("reader.session").current()
|
||
if not current or not isCurrentBook(current, identity) then
|
||
pushPageProgress(self, identity)
|
||
elseif require("book.progress").canPush(identity) then
|
||
schedulePageProgressSync(self, identity)
|
||
end
|
||
end)
|
||
end)
|
||
self._page_sync_job = job
|
||
end
|
||
|
||
---@param self WechatSource
|
||
---@param identity BookIdentity
|
||
schedulePageProgressSync = function(self, identity)
|
||
if self._page_sync_timer then return end
|
||
|
||
local timer
|
||
timer = function()
|
||
if self._page_sync_timer ~= timer then return end
|
||
self._page_sync_timer = nil
|
||
local Session = require("reader.session")
|
||
local session = Session.current()
|
||
if not isCurrentBook(session, identity) or not require("book.progress").canPush(identity)
|
||
or not require("ui/network/manager"):isConnected() then
|
||
return
|
||
end
|
||
if self._presence and self._presence.busy then
|
||
schedulePageProgressSync(self, session.identity)
|
||
return
|
||
end
|
||
pushPageProgress(self, session.identity)
|
||
end
|
||
self._page_sync_timer = timer
|
||
require("ui/uimanager"):scheduleIn(PAGE_PROGRESS_SYNC_DELAY, timer)
|
||
end
|
||
|
||
---@param self WechatSource
|
||
local function stopPageProgressSync(self)
|
||
if self._page_sync_timer then
|
||
require("ui/uimanager"):unschedule(self._page_sync_timer)
|
||
self._page_sync_timer = nil
|
||
end
|
||
self._page_sync_again = self._page_sync_job ~= nil
|
||
end
|
||
|
||
local PRESENCE_INTERVAL = 30
|
||
|
||
---@param self WechatSource
|
||
local function stopPresence(self)
|
||
local presence = self._presence
|
||
self._presence = nil
|
||
if not presence then return end
|
||
if presence.timer then require("ui/uimanager"):unschedule(presence.timer) end
|
||
if presence.job then presence.job.cancel() end
|
||
end
|
||
|
||
---@param self WechatSource
|
||
---@param presence table
|
||
---@param position table
|
||
---@param cb fun(data: table|nil, err: string|nil)
|
||
local function reportPresence(self, presence, position, cb)
|
||
local Protocol = require("moonsource_weread.protocol")
|
||
local web_position = {}
|
||
for key, value in pairs(position) do web_position[key] = value end
|
||
web_position.psvts = presence.session.psvts
|
||
web_position.pclts = presence.session.pclts
|
||
web_position.token = presence.session.token
|
||
local referer = Protocol.readerUrl(web_position.book_id)
|
||
|
||
local function sendRead()
|
||
web_position.elapsed_seconds = 0
|
||
local finished = false
|
||
local job = self._client:reportReadAsync(Protocol.makeReadPayload(web_position), referer,
|
||
function(data, err)
|
||
finished = true
|
||
cb(data, err)
|
||
end)
|
||
if not finished and self._presence == presence then presence.job = job end
|
||
end
|
||
|
||
if presence.session.entered then
|
||
sendRead()
|
||
return
|
||
end
|
||
local finished = false
|
||
local job = self._client:reportReadAsync(Protocol.makeEnterReadPayload(web_position), referer,
|
||
function(data, err)
|
||
finished = true
|
||
if not data then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
presence.session.entered = true
|
||
sendRead()
|
||
end)
|
||
if not finished and self._presence == presence then presence.job = job end
|
||
end
|
||
|
||
---@param self WechatSource
|
||
---@param presence table
|
||
local function beatPresence(self, presence)
|
||
if self._presence ~= presence then return end
|
||
presence.timer = nil
|
||
local function schedule(delay)
|
||
if self._presence ~= presence or presence.timer then return end
|
||
local timer
|
||
timer = function()
|
||
if self._presence ~= presence or presence.timer ~= timer then return end
|
||
presence.timer = nil
|
||
beatPresence(self, presence)
|
||
end
|
||
presence.timer = timer
|
||
require("ui/uimanager"):scheduleIn(delay or PRESENCE_INTERVAL, timer)
|
||
end
|
||
if presence.busy or not require("ui/network/manager"):isConnected() then
|
||
schedule()
|
||
return
|
||
end
|
||
local session = require("reader.session").current()
|
||
if not isCurrentBook(session, presence.identity) then
|
||
stopPresence(self)
|
||
return
|
||
end
|
||
if not require("book.progress").canPush(presence.identity) then
|
||
schedule()
|
||
return
|
||
end
|
||
if self._page_sync_timer or self._page_sync_job then
|
||
schedule(PAGE_PROGRESS_SYNC_DELAY)
|
||
return
|
||
end
|
||
|
||
local identity, pos = presence.identity, presence.position
|
||
local chapter_idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx)
|
||
local chapter_uid = chapter_idx and Toc.uid(identity.source_id, identity.stable_id, chapter_idx)
|
||
if not chapter_idx or not chapter_uid then
|
||
schedule()
|
||
return
|
||
end
|
||
local row = require("book.progress_db").get(self.id, identity.stable_id)
|
||
local bridge = row and row.extra
|
||
local offset = bridge and tonumber(bridge.chapter_idx) == chapter_idx
|
||
and tonumber(bridge.chapter_offset) or 0
|
||
local position = {
|
||
book_id = identity.stable_id,
|
||
chapter_uid = chapter_uid,
|
||
chapter_idx = Toc.sourceIndex(identity.source_id, identity.stable_id, chapter_idx) or chapter_idx,
|
||
chapter_offset = offset,
|
||
summary = pos.chapter_title or "",
|
||
progress = math.floor(Progress.clampFraction(pos.fraction) * 100 + 0.5),
|
||
}
|
||
|
||
schedule()
|
||
presence.busy = true
|
||
local function attempt(force)
|
||
if self._presence ~= presence then return end
|
||
local finished = false
|
||
local job = require("moonsource_weread.context").sessionAsync(self._client,
|
||
identity.stable_id, force, function(report_session, err)
|
||
finished = true
|
||
if self._presence ~= presence then return end
|
||
if not report_session then
|
||
presence.busy = false
|
||
logger.warn("wechat presence session failed", identity.stable_id, err)
|
||
return
|
||
end
|
||
presence.session = report_session
|
||
reportPresence(self, presence, position, function(data, report_err)
|
||
if self._presence ~= presence then return end
|
||
if not data and not force then
|
||
presence.job = nil
|
||
attempt(true)
|
||
return
|
||
end
|
||
presence.busy = false
|
||
presence.job = nil
|
||
if not data then
|
||
logger.warn("wechat presence heartbeat failed", identity.stable_id, report_err)
|
||
end
|
||
end)
|
||
end)
|
||
if not finished and self._presence == presence then presence.job = job end
|
||
end
|
||
attempt(false)
|
||
end
|
||
|
||
---@param self WechatSource
|
||
---@param identity BookIdentity
|
||
---@param position ProgressPosition|nil
|
||
local function touchPresence(self, identity, position)
|
||
if not self:configured() then return end
|
||
local presence = self._presence
|
||
if presence and (presence.identity.source_id ~= identity.source_id
|
||
or presence.identity.stable_id ~= identity.stable_id) then
|
||
stopPresence(self)
|
||
presence = nil
|
||
end
|
||
if not presence then
|
||
presence = { identity = identity, position = position or {}, busy = false }
|
||
self._presence = presence
|
||
beatPresence(self, presence)
|
||
return
|
||
end
|
||
presence.identity = identity
|
||
presence.position = position or presence.position
|
||
end
|
||
|
||
--- 开章补报已落库时长;阅读中按页节流推送进度,开书冲突决议前不推。
|
||
---@param event string
|
||
---@param payload table|nil
|
||
function Source:onEvent(event, payload)
|
||
if event == "page_changed" then
|
||
local identity = payload and payload.identity
|
||
local session = require("reader.session").current()
|
||
if not identity or identity.source_id ~= self.id or not isCurrentBook(session, identity)
|
||
or not self:configured() then
|
||
return
|
||
end
|
||
if self._presence then touchPresence(self, identity, payload.position) end
|
||
require("reader.session.progress").save(session, function(ok)
|
||
if ok and require("book.progress").canPush(identity)
|
||
and require("ui/network/manager"):isConnected() then
|
||
schedulePageProgressSync(self, identity)
|
||
end
|
||
end)
|
||
return
|
||
end
|
||
if event == "reading_stopped" then
|
||
stopPageProgressSync(self)
|
||
stopPresence(self)
|
||
return
|
||
end
|
||
if event == "reading_resumed" then
|
||
if payload and payload.identity and payload.identity.source_id == self.id then
|
||
touchPresence(self, payload.identity, payload.position)
|
||
end
|
||
return
|
||
end
|
||
if event == "reading_started" then
|
||
if payload and payload.identity and payload.identity.source_id == self.id then
|
||
touchPresence(self, payload.identity, payload.position)
|
||
end
|
||
return
|
||
end
|
||
if event == "chapter_changed" then
|
||
if payload and payload.identity and payload.identity.source_id == self.id then
|
||
touchPresence(self, payload.identity, payload.position)
|
||
end
|
||
-- 上一章的时长这时已落库:有网就顺手补报(Stats.push 自带在飞去重,没网留作脏行)。
|
||
if self:configured() and require("ui/network/manager"):isConnected() then
|
||
require("book.stats").push(self)
|
||
end
|
||
return
|
||
end
|
||
if event == "book_meta_changed" and self:configured() then
|
||
self:pushCategoryAsync(payload.identity.stable_id)
|
||
return
|
||
end
|
||
return SourceBase.onEvent(self, event, payload)
|
||
end
|
||
|
||
--- 把本地分类上行成书架分组:同名分组加入,没有就新建;分类清空则退出所有分组。
|
||
--- 仅在「使用自定义分组代替分类」打开时上行;关着时分类是题材,不能写进分组。
|
||
--- 新书不带分组,只有用户改分类才会走到这里。失败只记日志,分类留在本地。
|
||
---@param stable_id string
|
||
---@return { cancel: fun() }|nil
|
||
function Source:pushCategoryAsync(stable_id)
|
||
if not require("source.category_setting").enabled(self.id) then return nil end
|
||
local row = require("book.books_db").get(self.id, stable_id)
|
||
local category = row and row.category or nil
|
||
local client = self._client
|
||
return client:shelfSyncAsync(function(wire, err)
|
||
if not wire then
|
||
logger.warn("wechat group sync failed", err)
|
||
return
|
||
end
|
||
local steps = {}
|
||
local target, joined
|
||
for _idx, archive in ipairs(type(wire.archive) == "table" and wire.archive or {}) do
|
||
local ids, has = {}, false
|
||
for _i, id in ipairs(archive.bookIds or {}) do
|
||
if tostring(id) == stable_id then has = true else ids[#ids + 1] = tostring(id) end
|
||
end
|
||
if archive.name == category then
|
||
target = archive
|
||
joined = has
|
||
elseif has then
|
||
steps[#steps + 1] = { archive.archiveId, archive.name, ids }
|
||
end
|
||
end
|
||
if category and not joined then
|
||
local ids = {}
|
||
for _i, id in ipairs(target and target.bookIds or {}) do
|
||
if tostring(id) ~= stable_id then ids[#ids + 1] = tostring(id) end
|
||
end
|
||
ids[#ids + 1] = stable_id
|
||
steps[#steps + 1] = { target and target.archiveId or os.time(), category, ids }
|
||
end
|
||
local function run(index)
|
||
local step = steps[index]
|
||
if not step then return end
|
||
client:saveArchiveAsync(step[1], step[2], step[3], function(data, push_err)
|
||
if not data then
|
||
logger.warn("wechat group push failed", push_err)
|
||
return
|
||
end
|
||
run(index + 1)
|
||
end)
|
||
end
|
||
run(1)
|
||
end)
|
||
end
|
||
|
||
--- 关闭这个实例:清实例自己的封面表。Context(psvts)与 Toc 是进程级的,
|
||
--- 换源时关旧实例若把它们一起清了,正在阅读那本书的上报会报「请先打开该章节」。
|
||
function Source:close()
|
||
stopPresence(self)
|
||
self._covers = {}
|
||
end
|
||
|
||
--- 构造微信封面请求。
|
||
---@param identity BookIdentity
|
||
---@return BookCoverRequest|nil, string|nil
|
||
function Source:coverRequest(identity)
|
||
local url = identity.cover_url or identity.cover or self._covers[identity.stable_id]
|
||
if type(url) ~= "string" or url == "" then
|
||
local stored = require("book.books_db").get(self.id, identity.stable_id)
|
||
local cover = stored and stored.cover
|
||
if type(cover) ~= "string" or cover == "" then
|
||
return nil, _("无封面")
|
||
end
|
||
url = cover
|
||
end
|
||
return {
|
||
url = url,
|
||
headers = Auth.sessionHeaders(),
|
||
}
|
||
end
|
||
|
||
--- 本进程是否已清过旧版同步进书库的公众号行(Mp.dropLegacyBooks)。
|
||
local legacy_mp_dropped = false
|
||
|
||
--- 书架增量游标(跟账号走:vid 对不上直接作废,换账号 / 重登自动回全量)。
|
||
---@param self WechatSource
|
||
---@return number|nil
|
||
local function shelfCursor(self)
|
||
local saved = self.cfg.shelf_cursor
|
||
if type(saved) == "table" and tostring(saved.vid) == tostring(self.cfg.wr_vid) then
|
||
return tonumber(saved.synckey)
|
||
end
|
||
return nil
|
||
end
|
||
|
||
---@param self WechatSource
|
||
---@param synckey number|nil
|
||
local function saveShelfCursor(self, synckey)
|
||
if not synckey then return end
|
||
self.cfg.shelf_cursor = { vid = self.cfg.wr_vid, synckey = synckey }
|
||
Eink.save({ shelf_cursor = self.cfg.shelf_cursor })
|
||
end
|
||
|
||
---@param opts { dirty_only?: boolean, force?: boolean, on_progress?: fun(text: string, done: integer|nil, total: integer|nil) }|nil
|
||
---@param cb fun(result: SyncResult|nil, err: any)
|
||
---@return table
|
||
function Source:syncBooksAsync(opts, cb)
|
||
-- 旧版缺省为关,书架分类是题材。缺省改开后,增量会把非空本地分类当成分组名留住,
|
||
-- 必须清一次游标走全量,分组名才能写进来。写上 true,避免之后每次同步都清游标。
|
||
if self.cfg.category_as_group == nil then
|
||
self.cfg.category_as_group = true
|
||
self.cfg.shelf_cursor = nil
|
||
require("utils.settings").saveSource(self.id)
|
||
end
|
||
if not legacy_mp_dropped then
|
||
legacy_mp_dropped = true
|
||
require("moonsource_weread.mp").dropLegacyBooks(require("book.books_db"))
|
||
end
|
||
opts = opts or {}
|
||
local report = opts.on_progress or function(...) end
|
||
|
||
local client = self._client
|
||
local remote = {
|
||
shelfSyncAsync = function(_, done)
|
||
return client:shelfSyncAsync(done, true, opts.force == true)
|
||
end,
|
||
addToShelfAsync = function(_, id, done) return client:addToShelfAsync(id, done) end,
|
||
removeFromShelfAsync = function(_, id, done) return client:removeFromShelfAsync(id, done) end,
|
||
}
|
||
|
||
-- 本地脏书架只推加删,不拉全量快照。
|
||
if opts.dirty_only then return Shelf.syncAsync(self.id, remote, nil, opts, cb) end
|
||
|
||
-- 全量路(手动强刷 / 首次 / 增量对不齐回退):行为与原来一致,顺带存下游标。
|
||
local function fullPull()
|
||
local synckey
|
||
return Shelf.syncAsync(self.id, remote, function(wire)
|
||
synckey = tonumber(wire.synckey) or synckey
|
||
return Mapper.shelfList(wire, function(id, url) rememberCover(self, id, url) end).data
|
||
end, opts, function(result, err)
|
||
if result then saveShelfCursor(self, synckey) end
|
||
cb(result, err)
|
||
end)
|
||
end
|
||
|
||
if opts.force then return fullPull() end
|
||
local pending_import = require("moonsource_weread.shelf_import")
|
||
if pending_import.size() then
|
||
return SourceBase.defer(cb, {
|
||
pulled = 0, pushed = 0, hidden = 0, conflicts = 0,
|
||
skipped = true, reason = "pending_import",
|
||
})
|
||
end
|
||
local cursor = shelfCursor(self)
|
||
if not cursor then return fullPull() end
|
||
|
||
-- 增量路:推删 → 拉 id 增量 → 变更补详情、其余用本地行拼完整快照 → 加架上行 → reconcile。
|
||
-- 快照语义不变,reconcile 照旧是权威;任何一步对不齐就回退全量(慢一次,不出错)。
|
||
local BookDB = require("book.books_db")
|
||
local cancelled, job, delete_job, push_job = false, nil, nil, nil
|
||
local handle = { cancel = function()
|
||
cancelled = true
|
||
for _idx, j in ipairs({ job, delete_job, push_job }) do
|
||
if j and j.cancel then j.cancel() end
|
||
end
|
||
end }
|
||
|
||
local function removeOne(stable_id, done)
|
||
return self._client:removeFromShelfAsync(stable_id, function(wire, err)
|
||
if not wire then logger.warn("wechat shelf delete push failed", stable_id, err) end
|
||
done(wire)
|
||
end)
|
||
end
|
||
|
||
delete_job = Shelf.pushDeletes(self.id, removeOne, report, function(deleted_n)
|
||
if cancelled then return end
|
||
-- 本地已同步在架 id(待加架的脏行是本地独有的,不进远端计数对账)
|
||
local local_set = {}
|
||
for _idx, id in ipairs(BookDB.libraryStableIdsBySource(self.id)) do local_set[id] = true end
|
||
for _idx, id in ipairs(BookDB.pendingShelfAddIds(self.id)) do local_set[id] = nil end
|
||
local local_count = 0
|
||
for _id in pairs(local_set) do local_count = local_count + 1 end
|
||
|
||
report(_("正在拉取书架…"))
|
||
job = self._client:shelfSyncIdsAsync(cursor, local_count, function(wire, err)
|
||
if cancelled then return end
|
||
if not wire then job = fullPull(); return end
|
||
-- 分组 / 专辑增量的形状没有抓包样本,不猜:任一非空就回退全量。
|
||
if #(wire.archive or {}) > 0 or #(wire.removedArchive or {}) > 0
|
||
or #(wire.albumRemoved or {}) > 0 then
|
||
job = fullPull()
|
||
return
|
||
end
|
||
local removed = {}
|
||
for _idx, item in ipairs(type(wire.removed) == "table" and wire.removed or {}) do
|
||
local id = type(item) == "table" and (item.bookId or item.id) or item
|
||
if id ~= nil then removed[tostring(id)] = true end
|
||
end
|
||
local changed_ids, changed_set = {}, {}
|
||
for _idx, item in ipairs(type(wire.bookIds) == "table" and wire.bookIds or {}) do
|
||
local id = type(item) == "table" and (item.bookId or item.id) or item
|
||
local typ = type(item) == "table" and item.type or nil
|
||
if id == nil or (typ ~= nil and tonumber(typ) ~= 0) then
|
||
job = fullPull()
|
||
return
|
||
end
|
||
id = tostring(id)
|
||
if id:sub(1, 7) ~= "MP_WXS_" and not changed_set[id] then
|
||
changed_set[id] = true
|
||
changed_ids[#changed_ids + 1] = id
|
||
end
|
||
end
|
||
-- 最终集合与服务端总数对账:对不齐(本地被外力改过、口径差)一律回退全量。
|
||
local final_set, final_count = {}, 0
|
||
for id in pairs(local_set) do
|
||
if not removed[id] then final_set[id] = true end
|
||
end
|
||
for id in pairs(changed_set) do final_set[id] = true end
|
||
for _id in pairs(final_set) do final_count = final_count + 1 end
|
||
local expected = tonumber(wire.bookCount) or tonumber(wire.pureBookCount)
|
||
if expected and final_count ~= expected then
|
||
job = fullPull()
|
||
return
|
||
end
|
||
|
||
--- 本地行拼快照(删掉 removed、变更用新行)→ 加架上行 → reconcile,成功才推进游标。
|
||
---@param changed table<string, Book>
|
||
local function reconcileIncremental(changed)
|
||
local all_ids = BookDB.libraryStableIdsBySource(self.id)
|
||
local locals = BookDB.getMany(self.id, all_ids)
|
||
local snapshot = {}
|
||
for _idx, id in ipairs(all_ids) do
|
||
if not removed[id] then
|
||
snapshot[#snapshot + 1] = changed[id] or locals[id]
|
||
end
|
||
end
|
||
for id, book in pairs(changed) do
|
||
if not locals[id] then snapshot[#snapshot + 1] = book end
|
||
end
|
||
push_job = Shelf.pushAdded(self.id, self._client, final_set, report, function(pushed)
|
||
if cancelled then return end
|
||
local result, rerr = Shelf.reconcile(self.id, snapshot, opts.force)
|
||
if result then
|
||
result.pushed = deleted_n + pushed
|
||
saveShelfCursor(self, tonumber(wire.synckey))
|
||
end
|
||
cb(result, rerr)
|
||
end)
|
||
end
|
||
|
||
if #changed_ids == 0 then
|
||
reconcileIncremental({})
|
||
return
|
||
end
|
||
job = self._client:shelfSyncBooksAsync(changed_ids, function(detail, derr)
|
||
if cancelled then return end
|
||
if not detail or #(detail.emptyInfoIds or {}) > 0 then
|
||
job = fullPull()
|
||
return
|
||
end
|
||
local prog = Mapper.progressByBookId(detail)
|
||
local changed = {}
|
||
for _idx, row in ipairs(detail.books or {}) do
|
||
local b, cover = Mapper.book(row)
|
||
if b then
|
||
Mapper.applyProgress(b, prog[b.stable_id])
|
||
if cover then rememberCover(self, b.stable_id, cover) end
|
||
changed[b.stable_id] = b
|
||
end
|
||
end
|
||
for _idx, album in ipairs(detail.albums or {}) do
|
||
local b, cover = Mapper.albumBook(album)
|
||
if b then
|
||
if cover then rememberCover(self, b.stable_id, cover) end
|
||
changed[b.stable_id] = b
|
||
end
|
||
end
|
||
-- 分组变更已经回退全量。留在增量路说明分组没变:旧书沿用本地分类(含没进组),
|
||
-- 新书不在任何分组里。详情里的题材一律不写。
|
||
if require("source.category_setting").enabled(self.id) then
|
||
local locals = BookDB.getMany(self.id, changed_ids)
|
||
for id, b in pairs(changed) do
|
||
local old = locals[id]
|
||
local kept = old and old.category
|
||
b.category = (type(kept) == "string" and kept ~= "") and kept or nil
|
||
end
|
||
end
|
||
reconcileIncremental(changed)
|
||
end)
|
||
end)
|
||
end)
|
||
return handle
|
||
end
|
||
|
||
--- 拉取书籍详情并缓存封面 URL;映射不出书籍时按「详情为空」失败。
|
||
---@param identity BookIdentity
|
||
---@param cb fun(book: Book|nil, err: string|nil)
|
||
---@return { cancel: fun() }|nil
|
||
function Source:getDetailAsync(identity, cb)
|
||
return self._client:bookInfoAsync(identity.stable_id, function(wire, err)
|
||
if not wire then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
local row = wire.book or wire.data or wire
|
||
local b, cover = Mapper.book(row)
|
||
if not b then
|
||
cb(nil, _("书籍详情为空"))
|
||
return
|
||
end
|
||
if cover then rememberCover(self, b.stable_id, cover) end
|
||
local existing = require("book.books_db").get(self.id, b.stable_id)
|
||
if existing then
|
||
b.deleted = existing.deleted
|
||
end
|
||
local progress = require("book.progress_db").get(self.id, b.stable_id)
|
||
if progress then
|
||
b.percent = require("book.progress").clampPercent(progress.fraction, false, true)
|
||
end
|
||
require("book.store").rememberMany({ b })
|
||
cb(b)
|
||
end)
|
||
end
|
||
|
||
--- 旧目录没有章内 anchors,阅读会话必须重新拉取后再展示。
|
||
---@param toc BookChapter[]|nil
|
||
---@return boolean
|
||
function Source:isTocCurrent(toc)
|
||
return Toc.isCurrent(toc)
|
||
end
|
||
|
||
--- 强制拉取目录并写回缓存;失败时调用方继续使用旧缓存。
|
||
---@param self WechatSource
|
||
---@param identity BookIdentity
|
||
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||
---@return { cancel: fun() }|nil
|
||
local function fetchTocAsync(self, identity, cb)
|
||
return self._client:chapterInfosAsync(identity.stable_id, function(wire, err)
|
||
if not wire then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
local chapters = Mapper.chapters(wire, identity.stable_id)
|
||
if not chapters then
|
||
cb(nil, _("章节列表为空"))
|
||
return
|
||
end
|
||
if not Toc.put(identity.source_id, identity.stable_id, chapters) then
|
||
cb(nil, _("章节目录保存失败"))
|
||
return
|
||
end
|
||
cb(chapters)
|
||
end)
|
||
end
|
||
|
||
--- 取目录:命中本地 toc 缓存则下一个 tick 直接回调,
|
||
--- 未命中才拉章节信息并写回缓存。也是阅读会话目录恢复入口。
|
||
---@param identity BookIdentity
|
||
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||
---@return { cancel: fun() }|nil
|
||
function Source:loadTocAsync(identity, cb)
|
||
local cached = Toc.read(identity.source_id, identity.stable_id)
|
||
if cached and #cached > 0 then
|
||
local cancelled = false
|
||
require("ui/uimanager"):nextTick(require("ui.guard").wrap("wechat callback", function()
|
||
if not cancelled then cb(cached) end
|
||
end))
|
||
return { cancel = function() cancelled = true end }
|
||
end
|
||
return fetchTocAsync(self, identity, cb)
|
||
end
|
||
|
||
Source.refreshTocAsync = fetchTocAsync
|
||
|
||
--- 目录缓存缺失时先拉 toc,再解析 chapter_uid。
|
||
---@param self WechatSource
|
||
---@param identity BookIdentity
|
||
---@param chapter_idx integer|nil
|
||
---@param cb fun(uid: string|nil, err: string|nil)
|
||
---@return { cancel: fun() }|nil
|
||
local function resolveChapterUidAsync(self, identity, chapter_idx, cb)
|
||
-- chapter_idx 从 1 起;0 是「整本文件」哨兵,在 Lua 里为真值,必须归一成 nil,
|
||
-- 否则会拿 idx=0 去拉一份注定查不到的目录。
|
||
local idx = tonumber(chapter_idx) or tonumber(identity.chapter_idx)
|
||
if idx and idx < 1 then
|
||
idx = nil
|
||
end
|
||
-- 查不到不能回退到当前章的 uid:会配上目标章的 ci/co 把进度报到错误章节。
|
||
local uid = idx and Toc.uid(identity.source_id, identity.stable_id, idx)
|
||
if uid then
|
||
require("ui/uimanager"):nextTick(function() cb(uid) end)
|
||
return nil
|
||
end
|
||
if not idx then
|
||
require("ui/uimanager"):nextTick(function() cb(nil, _("缺少章节信息")) end)
|
||
return nil
|
||
end
|
||
return self:loadTocAsync(identity, function(toc, err)
|
||
if not toc then
|
||
cb(nil, err or _("缺少章节信息"))
|
||
return
|
||
end
|
||
uid = Toc.uid(identity.source_id, identity.stable_id, idx)
|
||
if uid then
|
||
cb(uid)
|
||
else
|
||
cb(nil, _("缺少章节信息"))
|
||
end
|
||
end)
|
||
end
|
||
|
||
---@param r BookIdentity
|
||
---@param chapter BookChapter
|
||
---@param done fun(payload: ChapterContentPayload|nil, err: any)
|
||
local function fetchContent(r, chapter, done)
|
||
return WChapter.fetchContentAsync(r.stable_id, chapter, done)
|
||
end
|
||
|
||
--- 用户点开的章取不到正文:进入一页临时提示文档(不当缓存,下次打开重新拉),不挡在阅读器外面。
|
||
--- 没登录不算(要走登录流程);预取 / 整本缓存不用它,照常失败。
|
||
---@param r BookIdentity
|
||
---@param chapter BookChapter
|
||
---@param done fun(payload: ChapterContentPayload|nil, err: any)
|
||
local function openContent(r, chapter, done)
|
||
return WChapter.fetchContentAsync(r.stable_id, chapter, function(payload, err)
|
||
if payload or not Auth.hasSession() then
|
||
done(payload, err)
|
||
return
|
||
end
|
||
local title = chapter.title or ""
|
||
local notice = string.format(_("这一章暂时无法加载:%s\n请稍后重试。"), tostring(err))
|
||
done({ title = title, html = Text.chapterHtml(title, notice), temporary = true })
|
||
end)
|
||
end
|
||
|
||
--- 按章打开:目录与正文都交给 source.chapter 的带 UI 流程。
|
||
---@param identity BookIdentity
|
||
---@param opts table|nil 可含 chapter_idx 指定章节
|
||
---@param cb fun(path: string|nil, err: string|nil)
|
||
---@return { cancel: fun() }
|
||
function Source:openBookAsync(identity, opts, cb)
|
||
return require("source.chapter").openWithUi(self, identity, identity.book, opts, {
|
||
loadToc = function(r, done) return self:loadTocAsync(r, done) end,
|
||
fetchContent = openContent,
|
||
}, cb)
|
||
end
|
||
|
||
--- 阅读中后台预取后续章节。
|
||
---@param identity BookIdentity
|
||
---@param toc BookChapter[]
|
||
---@param from_idx integer
|
||
---@param count integer
|
||
---@param cb fun()|nil
|
||
---@return { cancel: fun() }
|
||
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
|
||
-- 阅读中预取也按官方五章一批(带样式 0);offline=0,与单章在线一致。
|
||
return WChapter.prefetchBatchedAsync(identity, toc, from_idx, count, {
|
||
fetchContent = fetchContent,
|
||
book = identity.book,
|
||
offline = false,
|
||
}, cb)
|
||
end
|
||
|
||
--- 缓存整本章节正文;目录只拉一次,正文按官方五章一批(offline=1)下载。
|
||
---@param identity BookIdentity
|
||
---@param on_progress fun(done: integer, total: integer)|nil
|
||
---@param cb fun(ok: boolean, cached: integer, err: string|nil, total: integer, failed: integer)
|
||
---@return { cancel: fun() }
|
||
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
|
||
return WChapter.cacheAllBatchedAsync(self, identity, on_progress, cb, range)
|
||
end
|
||
|
||
--- 拉取云端进度并补齐本地需要的坐标。
|
||
--- 云端只给 chapter_uid 时回查目录换算章节序号;只给章内位置时按目录长度折算全书百分比;
|
||
--- 章节坐标写进 pos.extra 供后续 push 复用。
|
||
---@param identity BookIdentity
|
||
---@param cb fun(pos: ProgressPosition|nil, err: string|nil)
|
||
---@return { cancel: fun() }
|
||
function Source:getProgressAsync(identity, cb)
|
||
local cancelled = false
|
||
local first, second, position_job
|
||
first = self._client:getProgressAsync(identity.stable_id, function(wire, err)
|
||
if cancelled then return end
|
||
if not wire then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
local pos, chapter_uid = Mapper.progress(wire)
|
||
local function reply()
|
||
if pos.chapter_idx and (pos.fraction == nil or pos.fraction == 0) then
|
||
pos.fraction = Toc.wholeFraction(
|
||
identity.source_id, identity.stable_id, pos.chapter_idx, pos.chapter_fraction
|
||
) or pos.fraction
|
||
end
|
||
cb(pos)
|
||
end
|
||
local function finish()
|
||
-- 章节坐标随进度一起存本地:目录缓存过期后 push 可直接复用,免一轮请求。
|
||
-- 必须带上 chapter_idx,否则读者翻章后会拿旧 uid 把进度报到错误章节。
|
||
if chapter_uid and pos.chapter_idx then
|
||
pos.extra.chapter_uid, pos.extra.chapter_idx = chapter_uid, pos.chapter_idx
|
||
end
|
||
if not chapter_uid or not pos.chapter_idx or pos.extra.chapter_offset == nil then
|
||
reply()
|
||
return
|
||
end
|
||
local entry = (Toc.read(identity.source_id, identity.stable_id) or {})[pos.chapter_idx]
|
||
local chapter = { idx = pos.chapter_idx, uid = tostring(chapter_uid),
|
||
title = entry and entry.title or pos.chapter_title or "" }
|
||
local Position = require("moonsource_weread.progress")
|
||
-- 精确定位要拿到章节正文(可能要联网);拿不到或对不上就退回章级位置,
|
||
-- 远端给的 chapter_idx + chapter_fraction 仍是有效进度,不能整条丢掉。
|
||
position_job = Position.loadAsync(identity, chapter, function(source, format)
|
||
if cancelled then return end
|
||
local ok, map_err = nil, format
|
||
if source then ok, map_err = Position.localize(identity, chapter, pos, source, format) end
|
||
if not ok then
|
||
logger.warn("wechat progress position fallback to chapter", identity.stable_id, map_err)
|
||
end
|
||
reply()
|
||
end)
|
||
end
|
||
-- wire 的 chapterIdx 是云端索引空间,本地目录过滤掉了 wordCount=0 与「封面」,
|
||
-- 两边序号并不相等(差几章就跳到错误的章节)。只要有 uid 就一律回查目录换算成
|
||
-- 本地 idx;没有 uid 时才不得不沿用 wire 序号。
|
||
if not chapter_uid then
|
||
finish()
|
||
return
|
||
end
|
||
local mapped = Toc.index(identity.source_id, identity.stable_id, chapter_uid)
|
||
if mapped then
|
||
pos.chapter_idx = mapped
|
||
finish()
|
||
return
|
||
end
|
||
second = self:loadTocAsync(identity, function()
|
||
if cancelled then return end
|
||
pos.chapter_idx = Toc.index(identity.source_id, identity.stable_id, chapter_uid)
|
||
or pos.chapter_idx
|
||
finish()
|
||
end)
|
||
end)
|
||
return { cancel = function()
|
||
cancelled = true
|
||
if first then first.cancel() end
|
||
if second then second.cancel() end
|
||
if position_job and position_job.cancel then position_job:cancel() end
|
||
end }
|
||
end
|
||
|
||
--- 未完结连载(按章购买,或公众号)。App 的 progress 封顶 99,读完标记另走 markstatus。
|
||
---@param source_id string
|
||
---@param stable_id string
|
||
---@return boolean
|
||
local function openSerial(source_id, stable_id)
|
||
local book = require("book.books_db").get(source_id, stable_id)
|
||
local meta = book and book.meta
|
||
local data = meta and meta.source and meta.source["weread"]
|
||
local pay = tonumber(data and data.pay_type or meta and meta.weread_pay) or 0
|
||
local typ = tonumber(data and data.book_type or meta and meta.weread_type)
|
||
local ended = data and data.ended
|
||
if ended == nil then ended = meta and meta.weread_ended end
|
||
ended = ended == true
|
||
local serial = math.floor(pay / 2) % 2 == 1 or typ == 3
|
||
or tostring(stable_id):sub(1, 7) == "MP_WXS_"
|
||
return serial and not ended
|
||
end
|
||
|
||
--- 这本书还没确认的阅读时长。和进度同一次 /book/read 报上去,服务端才肯改坐标。
|
||
---@param source_id string
|
||
---@param stable_id string
|
||
---@return WechatAppHour[], integer[]
|
||
local function pendingHours(source_id, stable_id)
|
||
local rows, ids = {}, {}
|
||
for _idx, row in ipairs(require("book.stats_db").unsyncedBySource(source_id, 500)) do
|
||
if row.stable_id == stable_id and (tonumber(row.duration) or 0) > 0 then
|
||
rows[#rows + 1] = row
|
||
ids[#ids + 1] = row.id
|
||
end
|
||
end
|
||
return App.hours(rows, App.timeZone()), ids
|
||
end
|
||
|
||
--- 上报阅读进度:需要 chapter_uid,优先复用 pos.extra 缓存的坐标,否则回查目录解析。
|
||
--- 同一条请求带上这本书还没报的时长,成功后确认这些统计行,并把编码出的坐标写回 pos.extra。
|
||
---@param identity BookIdentity
|
||
---@param pos ProgressPosition|nil 缺省视为空位置
|
||
---@param cb fun(ok: boolean|nil, err: string|nil, meta?: { permanent?: boolean })
|
||
---@return { cancel: fun() }
|
||
function Source:putProgressAsync(identity, pos, cb)
|
||
pos = pos or {}
|
||
local reported = pos
|
||
local frac = Progress.clampFraction(pos.fraction)
|
||
local progress = math.max(0, math.min(100, math.floor(frac * 100 + 0.5)))
|
||
local chapter_idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx) or 0
|
||
local cancelled = false
|
||
local explicit_finish = false
|
||
local resolve_job, push_job, position_job
|
||
-- 只有 extra 记录的章与本次上报的章一致时才复用 uid,避免翻章后报错位置。
|
||
local extra = pos.extra
|
||
local chapter_uid = extra and tonumber(extra.chapter_idx) == chapter_idx
|
||
and extra.chapter_uid or nil
|
||
---@param uid string 章节 uid
|
||
local function startPush(uid)
|
||
local source_idx = Toc.sourceIndex(identity.source_id, identity.stable_id, chapter_idx)
|
||
or chapter_idx
|
||
local function send(offset, summary, fraction)
|
||
local hours, hour_ids = pendingHours(self.id, identity.stable_id)
|
||
local serial = openSerial(self.id, identity.stable_id)
|
||
local mark_finished = explicit_finish or (progress == 100 and not serial)
|
||
push_job = self._client:putProgressAsync(identity.stable_id, {
|
||
progress = serial and math.min(progress, 99) or progress,
|
||
current_progress = progress,
|
||
chapter_uid = uid, chapter_idx = source_idx,
|
||
chapter_offset = offset, chapter_fraction = fraction, summary = summary,
|
||
book_version = extra and extra.book_version,
|
||
hours = hours,
|
||
}, function(wire, push_err, meta)
|
||
if cancelled then return end
|
||
if wire and #hour_ids > 0 then
|
||
if not require("book.stats_db").markSynced(hour_ids) then
|
||
logger.warn("wechat read hours confirm failed", identity.stable_id, #hour_ids)
|
||
end
|
||
end
|
||
if wire then
|
||
local bridge = reported.extra
|
||
if type(bridge) ~= "table" then
|
||
bridge = {}
|
||
reported.extra = bridge
|
||
end
|
||
bridge.chapter_uid = tonumber(uid) or uid
|
||
bridge.chapter_idx = chapter_idx
|
||
bridge.chapter_offset = offset
|
||
if type(summary) == "string" and summary ~= "" then bridge.summary = summary end
|
||
end
|
||
if not wire or not mark_finished then
|
||
cb(wire and true or nil, push_err, meta)
|
||
return
|
||
end
|
||
-- 时长已经在上面确认。读完接口失败只重推进度,小时桶不会再报一遍。
|
||
push_job = self._client:markFinishedAsync(identity.stable_id, function(marked, mark_err)
|
||
if cancelled then return end
|
||
cb(marked and true or nil, mark_err)
|
||
end)
|
||
end)
|
||
end
|
||
if not pos.locator and pos.chapter_fraction == 0 then
|
||
send(0, "", 0)
|
||
return
|
||
end
|
||
local chapter = { idx = chapter_idx, uid = tostring(uid), title = pos.chapter_title or "" }
|
||
local Position = require("moonsource_weread.progress")
|
||
position_job = Position.loadAsync(identity, chapter, function(source, format)
|
||
if cancelled then return end
|
||
if not source then cb(nil, format); return end
|
||
local offset, summary, fraction, map_err = Position.encode(identity, chapter, pos, source, format)
|
||
-- offset=0 是章首合法坐标。正文已加载时 encode 会回退到章级比例,一般不再返回 nil;
|
||
-- 若仍为空(防御),保留脏行待重试,不能把未上传的进度标成已同步。
|
||
if offset == nil then
|
||
cb(nil, map_err or _("无法定位阅读进度"))
|
||
return
|
||
end
|
||
send(offset, summary, fraction)
|
||
end)
|
||
end
|
||
local missing = _("缺少章节信息")
|
||
if chapter_uid then
|
||
startPush(chapter_uid)
|
||
elseif not (tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx)) then
|
||
-- 手动标已读写入的 100% 行没有章节:按末章读完上报;其余没有章节的行永远推不上,标为永久失败让同步丢弃。
|
||
if frac < 1 then
|
||
require("ui/uimanager"):nextTick(function()
|
||
if not cancelled then cb(nil, missing, { permanent = true }) end
|
||
end)
|
||
else
|
||
explicit_finish = true
|
||
resolve_job = self:loadTocAsync(identity, function(toc)
|
||
if cancelled then return end
|
||
local last = type(toc) == "table" and #toc or 0
|
||
local uid = last > 0 and Toc.uid(identity.source_id, identity.stable_id, last) or nil
|
||
if not uid then
|
||
cb(nil, missing, { permanent = true })
|
||
return
|
||
end
|
||
chapter_idx, progress = last, 100
|
||
pos = { fraction = 1, chapter_fraction = 1 }
|
||
startPush(uid)
|
||
end)
|
||
end
|
||
else
|
||
resolve_job = resolveChapterUidAsync(self, identity, chapter_idx, function(uid, err)
|
||
if cancelled then return end
|
||
if not uid then
|
||
cb(nil, err or missing)
|
||
return
|
||
end
|
||
startPush(uid)
|
||
end)
|
||
end
|
||
return { cancel = function()
|
||
cancelled = true
|
||
if resolve_job and resolve_job.cancel then resolve_job.cancel() end
|
||
if push_job and push_job.cancel then push_job.cancel() end
|
||
if position_job and position_job.cancel then position_job:cancel() end
|
||
end }
|
||
end
|
||
|
||
--- 这本书的时长先别报:进度还是脏的,或者书正开着。交给 putProgress 和本地坐标一次报。
|
||
---@param source_id string
|
||
---@param stable_id string
|
||
---@return boolean
|
||
local function holdHours(source_id, stable_id)
|
||
local snap = require("reader.session").current()
|
||
local id = snap and snap.identity
|
||
if id and id.source_id == source_id and id.stable_id == stable_id then return true end
|
||
local row = require("book.progress_db").get(source_id, stable_id)
|
||
return row ~= nil and row.sync_status == 0
|
||
end
|
||
|
||
--- 上次进度确认时落下的本地坐标。没有章节 uid / 偏移,或目录对不上源章节序号,就返回 nil。
|
||
---@param source_id string
|
||
---@param stable_id string
|
||
---@return table|nil
|
||
local function savedPosition(source_id, stable_id)
|
||
local row = require("book.progress_db").get(source_id, stable_id)
|
||
local bridge = row and row.extra
|
||
local uid = bridge and tonumber(bridge.chapter_uid)
|
||
local offset = bridge and tonumber(bridge.chapter_offset)
|
||
if not row or row.sync_status == 0 or not uid or offset == nil then return nil end
|
||
local local_idx = tonumber(bridge.chapter_idx) or tonumber(row.chapter_idx) or 0
|
||
local source_idx = Toc.sourceIndex(source_id, stable_id, local_idx)
|
||
if source_idx == nil then return nil end
|
||
local percent = math.max(0, math.min(100, math.floor((tonumber(row.fraction) or 0) * 100 + 0.5)))
|
||
return {
|
||
chapter_uid = uid,
|
||
chapter_idx = source_idx,
|
||
chapter_offset = offset,
|
||
chapter_progress = math.max(0, math.min(100,
|
||
math.floor((tonumber(row.chapter_fraction) or 0) * 100 + 0.5))),
|
||
current_progress = percent,
|
||
summary = bridge.summary or "",
|
||
book_version = bridge.book_version or 0,
|
||
}
|
||
end
|
||
|
||
--- 补报离线积压的阅读时长:全部书一次 ``POST /book/batchUploadProgress``,每本 isResendReadingInfo=1。
|
||
--- 进度还没推,或者书正开着:这些行不报也不确认,留给 putProgress 带上本地坐标。
|
||
--- 进度已同步:用上次写入的本地坐标;没有这份坐标才退回云端位置。
|
||
--- 不能用页比例伪造 chapterOffset。整批成功才确认,失败一本都不确认。
|
||
---@param rows table[]|nil
|
||
---@param cb fun(data: table|nil, err: string|nil)
|
||
---@return { cancel: fun() }|nil
|
||
function Source:pushStatsAsync(rows, cb)
|
||
local order, books = {}, {}
|
||
for _idx, row in ipairs(rows or {}) do
|
||
local book = books[row.stable_id]
|
||
if not book then
|
||
book = { id = row.stable_id, rows = {} }
|
||
books[row.stable_id] = book
|
||
order[#order + 1] = book
|
||
end
|
||
book.rows[#book.rows + 1] = row
|
||
end
|
||
local pending = {}
|
||
for _idx, book in ipairs(order) do
|
||
if not holdHours(self.id, book.id) then pending[#pending + 1] = book end
|
||
end
|
||
if #pending == 0 then
|
||
cb({ ok = true, synced_ids = {} })
|
||
return { cancel = function() end }
|
||
end
|
||
local synced = {}
|
||
local cancelled, job = false, nil
|
||
local function finish(err)
|
||
if #synced == 0 and err then
|
||
cb(nil, err)
|
||
else
|
||
cb({ ok = true, synced_ids = synced })
|
||
end
|
||
end
|
||
local function confirm(book)
|
||
for _idx, row in ipairs(book.rows) do synced[#synced + 1] = row.id end
|
||
end
|
||
local token_job = self._client:guestTokenAsync(function(token, token_err)
|
||
if cancelled then return end
|
||
if not token then
|
||
finish(token_err)
|
||
return
|
||
end
|
||
local creds = Eink.credentials()
|
||
if not creds then
|
||
finish(_("请先扫码登录微信读书墨水屏"))
|
||
return
|
||
end
|
||
local index, bodies = 0, {}
|
||
local function flush()
|
||
job = self._client:reportBatchAsync(bodies, function(data, err)
|
||
if cancelled then return end
|
||
if not data then
|
||
logger.warn("wechat app batch report failed", #bodies, err)
|
||
finish(err)
|
||
return
|
||
end
|
||
for _idx, book in ipairs(pending) do confirm(book) end
|
||
logger.info("wechat app batch report ok", "books", #bodies)
|
||
finish()
|
||
end)
|
||
end
|
||
local function nextBook()
|
||
index = index + 1
|
||
local book = pending[index]
|
||
if not book then
|
||
flush()
|
||
return
|
||
end
|
||
local function spanEnd(rows)
|
||
local at = 0
|
||
for _idx, row in ipairs(rows) do
|
||
local end_at = (tonumber(row.start_time) or 0) + (tonumber(row.duration) or 0)
|
||
if end_at > at then at = end_at end
|
||
end
|
||
return at > 0 and at or nil
|
||
end
|
||
local function take(where)
|
||
local current = where.current_progress
|
||
local serial = openSerial(self.id, book.id)
|
||
local book_progress = current
|
||
if serial and tonumber(current) then book_progress = math.min(current, 99) end
|
||
bodies[#bodies + 1] = App.readBody({
|
||
vid = creds.vid,
|
||
device_id = creds.device_id,
|
||
install_id = Eink.installId(),
|
||
guest_token = token,
|
||
book_id = book.id,
|
||
chapter_uid = where.chapter_uid,
|
||
chapter_idx = where.chapter_idx,
|
||
chapter_offset = where.chapter_offset,
|
||
chapter_progress = where.chapter_progress,
|
||
progress = book_progress,
|
||
current_progress = current,
|
||
summary = where.summary or "",
|
||
book_version = where.book_version or 0,
|
||
hours = App.hours(book.rows, App.timeZone()),
|
||
read_update = spanEnd(book.rows),
|
||
resend = 1,
|
||
})
|
||
nextBook()
|
||
end
|
||
local where = savedPosition(self.id, book.id)
|
||
if where then
|
||
take(where)
|
||
return
|
||
end
|
||
job = self._client:getProgressAsync(book.id, function(wire, progress_err)
|
||
if cancelled then return end
|
||
if not wire then finish(progress_err); return end
|
||
local node = wire.book or wire
|
||
if not tonumber(node.chapterUid) or node.chapterOffset == nil then
|
||
finish(_("缺少章节信息"))
|
||
return
|
||
end
|
||
take({
|
||
chapter_uid = tonumber(node.chapterUid),
|
||
chapter_idx = node.chapterIdx,
|
||
chapter_offset = node.chapterOffset,
|
||
chapter_progress = node.chapterProgress or 0,
|
||
current_progress = node.progress,
|
||
summary = node.summary or "",
|
||
book_version = node.bookVersion or 0,
|
||
})
|
||
end)
|
||
end
|
||
nextBook()
|
||
end)
|
||
if token_job then job = token_job end
|
||
return { cancel = function()
|
||
cancelled = true
|
||
if job and job.cancel then job.cancel() end
|
||
end }
|
||
end
|
||
|
||
--- 每次统计同步最多补拉 readinfo 的书数;首次同步整个书架分几轮补齐。
|
||
local READINFO_BATCH = 20
|
||
|
||
--- 拉取累计总量,再按年定位月份、按月拉取真实日明细;
|
||
--- 最后对书架里云端累计有变化的书逐本拉 readinfo 按日明细。
|
||
---@param cb fun(result: BookStatsRow[]|BookStatsPullResult|nil, err: string|nil)
|
||
---@return { cancel: fun() }|nil
|
||
function Source:pullStatsAsync(cb)
|
||
local cancelled, jobs = false, {}
|
||
local function track(job)
|
||
jobs[#jobs + 1] = job
|
||
end
|
||
local function request(mode, base_time, done)
|
||
track(self._client:readStatsAsync(mode, base_time, done))
|
||
end
|
||
--- 单书明细是尽力而为:书架或某本书失败只跳过,不连累账户级统计;
|
||
--- 没拉到的书快照不变,下次同步仍判为有变化而重试。
|
||
local function collectBooks(done)
|
||
track(self._client:shelfSyncAsync(function(shelf, err)
|
||
if cancelled then return end
|
||
if not shelf then
|
||
logger.warn("wechat book stats shelf failed", err)
|
||
done({})
|
||
return
|
||
end
|
||
local pending = require("moonsource_weread.stats").changedBooks(
|
||
shelf.bookProgress, require("book.stats_db").bookTotals(self.id), READINFO_BATCH
|
||
)
|
||
local results, index = {}, 1
|
||
local function nextBook()
|
||
if cancelled then return end
|
||
local book = pending[index]
|
||
index = index + 1
|
||
if not book then
|
||
done(results)
|
||
return
|
||
end
|
||
track(self._client:readInfoAsync(book.id, function(wire, rerr)
|
||
if cancelled then return end
|
||
if wire then
|
||
book.wire = wire
|
||
results[#results + 1] = book
|
||
else
|
||
logger.warn("wechat readinfo failed", book.id, rerr)
|
||
end
|
||
nextBook()
|
||
end))
|
||
end
|
||
nextBook()
|
||
end))
|
||
end
|
||
local function collect(mode, bases, done)
|
||
local results, index = {}, 1
|
||
local function nextPeriod()
|
||
if cancelled then return end
|
||
local base_time = bases[index]
|
||
index = index + 1
|
||
if not base_time then
|
||
done(results)
|
||
return
|
||
end
|
||
request(mode, base_time, function(wire, err)
|
||
if cancelled then return end
|
||
if not wire then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
results[#results + 1] = wire
|
||
nextPeriod()
|
||
end)
|
||
end
|
||
nextPeriod()
|
||
end
|
||
request("overall", nil, function(overall, err)
|
||
if cancelled then return end
|
||
if not overall then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
local StatsMapper = require("moonsource_weread.stats")
|
||
collect("annually", StatsMapper.annualBaseTimes(overall), function(annuals)
|
||
local monthly_bases = {}
|
||
for _idx, annual in ipairs(annuals) do
|
||
for _idx, base_time in ipairs(StatsMapper.monthlyBaseTimes(annual)) do
|
||
monthly_bases[#monthly_bases + 1] = base_time
|
||
end
|
||
end
|
||
collect("monthly", monthly_bases, function(monthlies)
|
||
collectBooks(function(book_details)
|
||
cb(StatsMapper.fromWires(
|
||
self.id, overall, annuals, monthlies, book_details, os.time()
|
||
))
|
||
end)
|
||
end)
|
||
end)
|
||
end)
|
||
return { cancel = function()
|
||
cancelled = true
|
||
for _idx, job in ipairs(jobs) do job:cancel() end
|
||
end }
|
||
end
|
||
|
||
--- 解析本章 chapter_uid 后再发请求;取消同时覆盖两段。
|
||
---@param self WechatSource
|
||
---@param identity BookIdentity
|
||
---@param cb fun(data: any, err: string|nil)
|
||
---@param start fun(chapter_uid: string, cb: fun(data: any, err: string|nil)): { cancel: fun() }|nil
|
||
---@return { cancel: fun() }
|
||
local function withChapterUid(self, identity, cb, start)
|
||
local job
|
||
local cancelled = false
|
||
job = resolveChapterUidAsync(self, identity, nil, function(chapter_uid, err)
|
||
if cancelled then return end
|
||
if not chapter_uid then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
job = start(chapter_uid, cb)
|
||
end)
|
||
return { cancel = function()
|
||
cancelled = true
|
||
if job then job.cancel() end
|
||
end }
|
||
end
|
||
|
||
--- 拉取某本书的划线与想法,合并成 KOReader 注解数组。
|
||
--- 想法接口失败只记日志不算错:划线本身已经可用。
|
||
---@param identity BookIdentity
|
||
---@param cb fun(annotations: table[]|nil, err: string|nil, meta: table|nil)
|
||
---@return { cancel: fun() }|nil
|
||
function Source:pullNotesAsync(identity, cb)
|
||
if not self:configured() then
|
||
cb(nil, _("请先扫码登录微信读书"))
|
||
return nil
|
||
end
|
||
local cancelled = false
|
||
local job
|
||
-- 章节号按 uid 查本地目录,缓存过期时查不到:先确保目录在。目录拉不到照样拉笔记,章节号留空。
|
||
local toc_job = self:loadTocAsync(identity, function()
|
||
if cancelled then return end
|
||
job = self._client:bookmarkListAsync(identity.stable_id, function(wire, err)
|
||
if cancelled then return end
|
||
if not wire then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
-- 想法拉不到不算失败:划线本身已经可用。
|
||
job = self._client:myReviewsAsync(identity.stable_id, function(reviews, rerr)
|
||
if cancelled then return end
|
||
if not reviews then
|
||
logger.warn("wechat my reviews failed", identity.stable_id, rerr)
|
||
end
|
||
local annotations = Notes.toAnnotations(
|
||
wire, nil, reviews, identity.source_id, identity.stable_id
|
||
)
|
||
if not reviews then
|
||
local local_items = {}
|
||
for _idx, row in ipairs(require("book.note_db").all(identity.source_id, identity.stable_id)) do
|
||
for _j, item in ipairs((require("book.note.normalize").decode(row.payload)) or {}) do
|
||
item.chapter_idx = item.chapter_idx or (row.chapter_idx > 0 and row.chapter_idx or nil)
|
||
local_items[#local_items + 1] = item
|
||
end
|
||
end
|
||
Notes.keepLocalReviews(annotations, local_items)
|
||
end
|
||
cb(annotations, nil, { authoritative = Notes.reviewsComplete(reviews) })
|
||
end)
|
||
end)
|
||
end)
|
||
return { cancel = function()
|
||
cancelled = true
|
||
if toc_job then toc_job.cancel() end
|
||
if job then job.cancel() end
|
||
end }
|
||
end
|
||
|
||
--- 开章后把通用注解转为 KOReader 可读坐标。
|
||
---@param document table|nil
|
||
---@param annotations table[]
|
||
---@param html_path string|nil
|
||
---@param current table[]|nil
|
||
---@return table[]
|
||
function Source:localizeAnnotations(document, annotations, html_path, current)
|
||
return Notes.localizeAnnotations(document, annotations, html_path, current)
|
||
end
|
||
|
||
function Source:cleanAnnotations(items, total_pages)
|
||
return Notes.cleanAnnotations(items, total_pages)
|
||
end
|
||
|
||
function Source:prepareLocalAnnotations(previous, current)
|
||
return Notes.prepareLocalAnnotations(previous, current)
|
||
end
|
||
|
||
function Source:mergeAnnotations(remote, current, paging, authoritative)
|
||
return Notes.mergeAnnotations(remote, current, paging, authoritative)
|
||
end
|
||
|
||
--- 上传当前章的划线与想法。
|
||
--- 微信读书的划线坐标依赖章节 HTML,因此只能按章推送:identity 必须带 chapter_idx,
|
||
--- 且该章正文已落盘(缺 HTML 时无法定位划线区间)。无可推送内容直接回调成功。
|
||
---@param annotations table[] KOReader 注解数组,就地改写
|
||
---@return table[]
|
||
function Source:resetAccountAnnotations(annotations)
|
||
for index = #annotations, 1, -1 do
|
||
local item = annotations[index]
|
||
if item.wr_deleted then
|
||
table.remove(annotations, index)
|
||
else
|
||
item.wr_bookmark_id, item.wr_review_id = nil, nil
|
||
item.wr_delete_review, item.wr_update_review, item.wr_update_bookmark = nil, nil, nil
|
||
end
|
||
end
|
||
return annotations
|
||
end
|
||
|
||
---@param identity BookIdentity
|
||
---@param annotations table[] KOReader 注解数组,就地改写
|
||
---@param cb fun(ok: boolean|nil, err: string|nil, meta: table|nil)
|
||
---@return { cancel: fun() }|nil
|
||
function Source:pushNotesAsync(identity, annotations, cb)
|
||
if not self:configured() then
|
||
cb(nil, _("请先扫码登录微信读书"))
|
||
return nil
|
||
end
|
||
if not Notes.preparePush(annotations) then
|
||
cb(true)
|
||
return nil
|
||
end
|
||
local chapter_idx = tonumber(identity.chapter_idx)
|
||
if not chapter_idx then
|
||
cb(nil, _("按章书籍请打开章节后同步划线"))
|
||
return nil
|
||
end
|
||
local local_html
|
||
local f = io.open(require("utils.paths").chapterPath(identity.stable_id, chapter_idx, identity.source_id), "rb")
|
||
if f then
|
||
local_html = f:read("*a")
|
||
f:close()
|
||
end
|
||
return withChapterUid(self, identity, cb, function(chapter_uid, done)
|
||
return NotesPush.run(self._client, identity, chapter_uid, local_html, annotations, done)
|
||
end)
|
||
end
|
||
|
||
--- 阅读页是否显示他人段评(设置页开关,默认关)。
|
||
---@return boolean
|
||
function Source:paragraphReviewsEnabled()
|
||
return require("source.review_setting").enabled(self.id)
|
||
end
|
||
|
||
--- 按书名搜索微信读书书目(关联本地书看段评用)。
|
||
---@param keyword string
|
||
---@param cb fun(books: WechatSearchBook[]|nil, err: string|nil)
|
||
---@return { cancel: fun() }|nil
|
||
function Source:searchBooksAsync(keyword, cb)
|
||
return self._client:searchAsync(keyword, function(wire, err)
|
||
if not wire then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
cb(Mapper.searchBooks(wire))
|
||
end)
|
||
end
|
||
|
||
--- 书城搜索:回包形状同 listStoreAsync。
|
||
---@param keyword string
|
||
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
|
||
---@return { cancel: fun() }|nil
|
||
function Source:searchAsync(keyword, cb)
|
||
return self._client:searchAsync(keyword, function(wire, err)
|
||
if not wire then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
cb({ data = Mapper.searchList(wire) })
|
||
end)
|
||
end
|
||
|
||
--- 书城浏览:三行 chip(榜单 / 分类 / 所选分类的子分类)+ 所选节点的书,节点是榜单或分类 id,缺省是第一个榜单。
|
||
--- 目录树与榜单书每次都调 client,新鲜度由数据获取层缓存(source.store_cache)管,源不留实例缓存。
|
||
---@param opts { node?: string, limit?: integer }
|
||
---@param cb fun(res: { data: Book[], groups: table[] }|nil, err: string|nil)
|
||
---@return { cancel: fun() }
|
||
function Source:browseAsync(opts, cb)
|
||
local handle = {}
|
||
-- 回调同步完成时 load 已换上在途句柄,外层赋值不能再覆盖(同 jdread 的 mine 记法)。
|
||
local step = 0
|
||
local function load(tree)
|
||
step = step + 1
|
||
local node = opts.node or (tree.rankings[1] and tree.rankings[1].id)
|
||
if not node then
|
||
cb(nil, _("没有可浏览的榜单"))
|
||
return
|
||
end
|
||
local ranking, top
|
||
for _idx, row in ipairs(tree.rankings) do
|
||
if row.id == node then ranking = row end
|
||
end
|
||
for _idx, cat in ipairs(tree.categories) do
|
||
if cat.id == node then top = cat end
|
||
for _idx2, sub in ipairs(cat.subs) do
|
||
if sub.id == node then top = cat end
|
||
end
|
||
end
|
||
local groups = {
|
||
{ chips = tree.rankings, active = ranking and node },
|
||
{ chips = tree.categories, active = top and top.id },
|
||
}
|
||
if top then
|
||
local subs = { { id = top.id, title = _("全部") } }
|
||
for _idx, sub in ipairs(top.subs) do subs[#subs + 1] = sub end
|
||
groups[3] = { chips = subs, active = node }
|
||
end
|
||
handle.inner = Browse.pages(function(page, done)
|
||
return self._client:storeBooksAsync(node, (page - 1) * 20, ranking ~= nil, function(wire, err)
|
||
if not wire then
|
||
done(nil, err)
|
||
return
|
||
end
|
||
done(Mapper.searchList(wire), nil, wire.hasMore == 1)
|
||
end)
|
||
end, opts.limit or 60, groups, cb)
|
||
end
|
||
local first = self._client:storeCategoriesAsync(function(wire, err)
|
||
if not wire then
|
||
cb(nil, err)
|
||
return
|
||
end
|
||
load(Mapper.storeTree(wire))
|
||
end)
|
||
if step == 0 then handle.inner = first end
|
||
function handle.cancel()
|
||
if handle.inner then handle.inner:cancel() end
|
||
end
|
||
return handle
|
||
end
|
||
|
||
--- 本章有段评的热点原句(未定位)。
|
||
---@param identity BookIdentity 微信书身份,chapter_idx 为微信目录序号
|
||
---@param cb fun(hotspots: WechatReviewHotspot[]|nil, err: string|nil)
|
||
---@return { cancel: fun() }
|
||
function Source:paragraphHotspotsAsync(identity, cb)
|
||
return ReviewCache.hotspotsAsync(identity, function(done)
|
||
return withChapterUid(self, identity, done, function(chapter_uid, finish)
|
||
return Reviews.hotspotsAsync(self._client, identity.stable_id, chapter_uid, finish)
|
||
end)
|
||
end, cb)
|
||
end
|
||
|
||
--- 热点按原句定位到 html(xpointer 以该 HTML 的根为起点);定位不了的丢弃。
|
||
---@param hotspots WechatReviewHotspot[]
|
||
---@param html string
|
||
---@return WechatReviewSpot[]
|
||
function Source:locateHotspots(hotspots, html)
|
||
return Reviews.locate(hotspots, html)
|
||
end
|
||
|
||
--- 某句的一页段评。
|
||
---@param identity BookIdentity
|
||
---@param range string 热点的 range
|
||
---@param max_idx integer 首页 0,之后用上一页回传的 max_idx
|
||
---@param cb fun(page: WechatReviewPage|nil, err: string|nil)
|
||
---@return { cancel: fun() }
|
||
function Source:paragraphReviewPageAsync(identity, range, max_idx, cb)
|
||
return ReviewCache.pageAsync(identity, range, max_idx, function(done)
|
||
return withChapterUid(self, identity, done, function(chapter_uid, finish)
|
||
return Reviews.pageAsync(self._client, identity.stable_id, chapter_uid, range, max_idx, finish)
|
||
end)
|
||
end, cb)
|
||
end
|
||
|
||
--- 某条想法的一页回复。不走段评缓存:点开才拉,失败当场返回。
|
||
---@param _identity BookIdentity
|
||
---@param review_id string
|
||
---@param max_idx integer
|
||
---@param cb fun(page: WechatReviewPage|nil, err: string|nil)
|
||
---@return { cancel: fun() }|nil
|
||
function Source:paragraphReviewRepliesAsync(_identity, review_id, max_idx, cb)
|
||
return Reviews.commentsAsync(self._client, review_id, max_idx, cb)
|
||
end
|
||
|
||
return WeChat
|