commit ed44254f1cbc05d0bb932e2ca519b5ef476f1743 Author: Garfield Date: Mon Nov 16 12:07:59 2026 +0800 ✨ 初始提交:月读第三方书源插件集合 每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> diff --git a/moonsource-weread.koplugin/README.md b/moonsource-weread.koplugin/README.md new file mode 100644 index 0000000..e7e4dc6 --- /dev/null +++ b/moonsource-weread.koplugin/README.md @@ -0,0 +1,18 @@ +# 微信读书 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 微信扫码登录与续期 | 支持 | 使用官方扫码及登录令牌流程 | +| 书架拉取 | 支持 | 全量/增量同步、分组、变更详情补齐;大快照支持浏览器分批导入 | +| 书架新增与移出 | 支持 | 本地先生效,联网后推送;真实账号端到端回读未完成本次验证 | +| 详情与目录 | 支持 | App 接口读取书籍和章节元数据 | +| 正文下载与阅读 | 支持 | EPUB/TXT 包本机解包,受账号阅读权限限制 | +| 搜索与分类书城 | 支持 | App 搜索、公开 Web 分类和分类书单;不是完整 App 书城复刻 | +| 阅读进度同步 | 支持 | 开书比较云端位置;本地先落盘,阅读中合并推送,离线保留待同步数据 | +| 阅读时长同步 | 支持 | 上传本地采集时长及补报数据 | +| 维持官网「在读」状态 | 已实现,未实测 | 零时长 Web 心跳,不重复增加阅读时长 | +| 划线与想法同步 | 支持 | 走属主书籍的注解接口 | +| 整书书评与独立章评 | 不支持 | 未接入可验证接口,不能把其他书籍的想法当作属主书评 | +| 段评与回复 | 支持 | 按章节及文本范围定位,使用公共评论标记和列表 | +| 离线阅读 | 支持 | 已下载内容和本地记录可用;联网后再同步 | +| 账号切换 | 部分支持 | 游标按账号作废;旧本地书架不自动清理,不是完整账号分区 | diff --git a/moonsource-weread.koplugin/_meta.lua b/moonsource-weread.koplugin/_meta.lua new file mode 100644 index 0000000..a1b286f --- /dev/null +++ b/moonsource-weread.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:微信读书"), + description = _("给月读增加「微信读书」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-weread.koplugin/main.lua b/moonsource-weread.koplugin/main.lua new file mode 100644 index 0000000..04755d6 --- /dev/null +++ b/moonsource-weread.koplugin/main.lua @@ -0,0 +1,9 @@ +--[[-- +KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。 +--]] +local WidgetContainer = require("ui/widget/container/widgetcontainer") + +return WidgetContainer:extend{ + name = "moonsource_weread", + is_doc_only = false, +} diff --git a/moonsource-weread.koplugin/moon_source.lua b/moonsource-weread.koplugin/moon_source.lua new file mode 100644 index 0000000..4e9d9d3 --- /dev/null +++ b/moonsource-weread.koplugin/moon_source.lua @@ -0,0 +1,18 @@ +--[[-- +月读第三方书源描述:微信读书。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。 +--]] + +-- 接入订阅页公众号、书架导入页、借段评等通用挂点 +require("moonsource_weread.extras") + +local function lazy(module) + return setmetatable({}, { __index = function(_, key) return require(module)[key] end }) +end + +return { + api = 1, + provides = { source = true }, + meta = function() return require("moonsource_weread.source").meta() end, + new = function() return require("moonsource_weread.source").new() end, + setting = lazy("moonsource_weread.setting"), +} diff --git a/moonsource-weread.koplugin/moonsource_weread/_meta.lua b/moonsource-weread.koplugin/moonsource_weread/_meta.lua new file mode 100644 index 0000000..9eb0369 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/_meta.lua @@ -0,0 +1,15 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +@module moonsource_weread._meta +--]] + +local _ = require("l10n").get("moonsource_weread") + +return { + id = "ext.weread", + name = _("微信读书"), + type = "chapter", + description = _("微信读书书架与在线阅读"), + abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("笔记同步"), _("统计同步"), _("他人段评") }, +} diff --git a/moonsource-weread.koplugin/moonsource_weread/app.lua b/moonsource-weread.koplugin/moonsource_weread/app.lua new file mode 100644 index 0000000..6749cbd --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/app.lua @@ -0,0 +1,228 @@ +--[[-- +微信读书手机 App 协议(``POST /book/read``):按小时分桶的阅读时长上报。 + +与 Web 的 ``/web/book/read``(每 30 秒心跳、rt)不同,App 把时长按 ``hours`` 分桶, +``timestamp`` 是发送时刻,历史时间只存在于 ``hours[].startOfHour``,所以离线攒下的 +时长可以事后补报。签名来自 App 内 ``libencrypt.so`` 的 ``GenSignature`` +(输入逐字节过替换表 → 加盐排序拼接 → 按异或值循环移位 → sha256,连做两轮), +用 HAR 抓包的真实请求核对过。 + +@module koplugin.book.moonsource_weread.app +--]] + +local bit = require("bit") +local sha256 = require("ffi/sha2").sha256 + +local App = {} + +local SALT = "5a6f1" + +local REMAP = { + 52, 202, 85, 64, 29, 182, 147, 198, 49, 48, 41, 53, 50, 167, 184, 17, + 194, 181, 22, 250, 139, 177, 36, 164, 16, 144, 4, 233, 8, 248, 59, 138, + 156, 140, 68, 249, 188, 92, 105, 226, 161, 218, 210, 211, 117, 137, 247, 30, + 45, 80, 86, 215, 114, 83, 191, 34, 251, 32, 15, 1, 46, 69, 135, 110, + 102, 72, 242, 224, 205, 254, 103, 169, 67, 244, 148, 81, 206, 165, 74, 238, + 19, 38, 142, 204, 170, 51, 20, 93, 14, 57, 187, 207, 145, 43, 129, 77, + 234, 153, 236, 26, 44, 133, 197, 217, 54, 116, 75, 24, 225, 241, 61, 157, + 65, 159, 180, 23, 13, 214, 76, 190, 220, 175, 151, 40, 119, 240, 98, 255, + 113, 193, 200, 39, 143, 108, 104, 168, 155, 230, 89, 28, 27, 18, 9, 152, + 78, 63, 6, 55, 0, 186, 31, 10, 25, 47, 201, 213, 208, 87, 73, 111, + 253, 37, 228, 97, 12, 66, 203, 150, 100, 95, 219, 173, 96, 35, 141, 154, + 109, 195, 196, 94, 62, 185, 146, 106, 189, 91, 7, 127, 118, 149, 237, 79, + 171, 132, 122, 128, 231, 120, 199, 229, 235, 115, 131, 107, 252, 56, 70, 125, + 71, 101, 179, 82, 99, 58, 5, 209, 239, 163, 166, 222, 158, 60, 2, 174, + 178, 123, 160, 246, 243, 42, 192, 172, 134, 3, 90, 84, 11, 245, 130, 212, + 126, 227, 223, 176, 216, 221, 33, 232, 124, 136, 162, 121, 88, 112, 183, 21, +} + +--- 逐字节比较,不走 strcoll:区域设置会改变高位字节的顺序。 +---@param a string +---@param b string +---@return boolean +local function byteLess(a, b) + local n = math.min(#a, #b) + for i = 1, n do + local x, y = a:byte(i), b:byte(i) + if x ~= y then return x < y end + end + return #a < #b +end + +--- 全部字节异或后取 mod 11 作偏移,整体循环移位。 +---@param s string +---@return string +local function rotate(s) + local x = 0 + for i = 1, #s do x = bit.bxor(x, s:byte(i)) end + local k, n = x % 11, #s + local out = {} + for i = 0, n - 1 do out[(k + i) % n + 1] = s:sub(i + 1, i + 1) end + return table.concat(out) +end + +--- App 防重放签名。 +---@param items string[] guest_token、random、timestamp、payload +---@return string +function App.sign(items) + local list = {} + for _idx, item in ipairs(items) do + list[#list + 1] = (item:gsub(".", function(c) return string.char(REMAP[c:byte() + 1]) end)) + end + list[#list + 1] = SALT + table.sort(list, byteLess) + local first = sha256(rotate(table.concat(list))) --[[@as string]] + return sha256(rotate(first)) --[[@as string]] +end + +--- 本机时区,形如 ``+08:00``。 +---@return string +function App.timeZone() + local z = os.date("%z") --[[@as string]] + return z:sub(1, 3) .. ":" .. z:sub(4, 5) +end + +---@class WechatAppHour +---@field startOfHour integer 整点 Unix 时间戳 +---@field readingTime integer 秒 +---@field timeZone string +---@field ttsTime integer + +--- 把 [start, start+duration) 的阅读区间按整点切进小时桶(跨整点就拆开)。 +---@param spans { start_time: integer, duration: integer }[] +---@param zone string +---@return WechatAppHour[] 按整点升序 +function App.hours(spans, zone) + local buckets = {} + for _idx, span in ipairs(spans) do + local at, left = span.start_time, span.duration + while left > 0 do + local hour = at - at % 3600 + local part = math.min(left, hour + 3600 - at) + local bucket = buckets[hour] + if not bucket then + bucket = { startOfHour = hour, readingTime = 0, timeZone = zone, ttsTime = 0 } + buckets[hour] = bucket + end + bucket.readingTime = bucket.readingTime + part + at, left = at + part, left - part + end + end + local out = {} + for _hour, bucket in pairs(buckets) do out[#out + 1] = bucket end + table.sort(out, function(a, b) return a.startOfHour < b.startOfHour end) + return out +end + +--- signature 的 payload:vid_deviceId_appId_bookId_risk_时区_readingTime_ttsTime_各小时桶。 +---@param vid string +---@param body table +---@return string +local function signPayload(vid, body) + local parts = { + vid, body.deviceId, body.appId, body.bookId, tostring(body.risk), + body.recordCreateTimeZone, tostring(body.readingTime), tostring(body.ttsTime), + } + for _idx, hour in ipairs(body.hours) do + parts[#parts + 1] = hour.startOfHour .. "_" .. hour.timeZone .. "_" .. hour.readingTime .. "_" .. hour.ttsTime + end + local payload = table.concat(parts, "_") + -- App 在 ttsTime 后面固定再拼一个 _。有小时桶时它就是分隔符;没有小时桶时 payload 以 _ 结尾。 + if #body.hours == 0 then payload = payload .. "_" end + return payload +end + +---@class WechatAppReadOpts +---@field vid string +---@field device_id string +---@field install_id string +---@field guest_token string +---@field book_id string +---@field chapter_uid integer +---@field chapter_idx integer +---@field chapter_offset integer 章节原文字符偏移(EPUB 包含 HTML 标签) +---@field chapter_progress integer 章内百分比 0..100 +---@field hours WechatAppHour[] +---@field progress integer|nil 书架进度。未完结连载封顶 99,和当前位置不是同一个数 +---@field current_progress integer|nil 当前位置的百分比 0..100 +---@field summary string|nil 当前位置摘要 +---@field book_version integer|nil +---@field read_update integer|nil 进度落在本地的时间(秒)。只进批量体 +---@field resend integer|nil 离线批量才带:0 实时跨小时,1 补报积压 + +--- 组装已签名的 ``/book/read`` 请求体。 +---@param opts WechatAppReadOpts +---@return table +function App.readBody(opts) + local total = 0 + for _idx, hour in ipairs(opts.hours) do total = total + hour.readingTime end + local current = opts.current_progress + local progress = opts.progress + if progress == nil then progress = current end + local body = { + appId = opts.device_id, + autoTime = 0, + bookId = opts.book_id, + bookVersion = opts.book_version or 0, + chapterIdx = opts.chapter_idx, + chapterOffset = opts.chapter_offset, + chapterProgress = opts.chapter_progress, + chapterUid = opts.chapter_uid, + currentProgress = current, + progress = progress, + deviceId = opts.device_id, + hours = opts.hours, + installId = opts.install_id, + isLecture = 0, + isStoryFeed = 0, + lectureTextTime = 0, + lectureTime = 0, + novalTime = 0, + random = math.random(0, 999), + readingTime = total, + recordCreateTimeZone = App.timeZone(), + reviewId = "", + risk = 0, + sourceModule = "unknown", + summary = opts.summary or "", + timestamp = os.time(), + ttsTime = 0, + voiceType = -1, + wordCount = 0, + } + if opts.resend ~= nil then + -- 单本 /book/read 不带这两个字段。离线批量才有:实时跨小时 resend=0,补报积压是 1。 + body.isResendReadingInfo = opts.resend + body.readUpdateTime = opts.read_update or body.timestamp + end + body.signature = App.sign({ + opts.guest_token, tostring(body.random), tostring(body.timestamp), signPayload(opts.vid, body), + }) + return body +end + +--- 离线批量的外层签名:sha256(timestamp + ``/config`` token + random),不是单本的 guest 签名。 +---@param token string +---@param timestamp integer +---@param random integer +---@return string +function App.batchSignature(token, timestamp, random) + return sha256(tostring(timestamp) .. token .. tostring(random)) --[[@as string]] +end + +--- ``POST /book/batchUploadProgress``。books 里每本仍是已签名的 /book/read 体。 +---@param books table[] +---@param token string +---@return table +function App.batchBody(books, token) + local timestamp, random = os.time(), math.random(0, 999) + return { + books = books, + timestamp = timestamp, + random = random, + recordCreateTimeZone = App.timeZone(), + signature = App.batchSignature(token, timestamp, random), + } +end + +return App diff --git a/moonsource-weread.koplugin/moonsource_weread/assets.lua b/moonsource-weread.koplugin/moonsource_weread/assets.lua new file mode 100644 index 0000000..70b969d --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/assets.lua @@ -0,0 +1,372 @@ +--[[-- +微信读书章节资源本地化:插图(tar 资源包 + 远程 img)、脚注图标、整书样式表。 + +只改资源引用(img src、link href),正文其余字节不动。 + +@module koplugin.book.moonsource_weread.assets +--]] + +local Auth = require("moonsource_weread.auth") +local Shared = require("source.assets") +local Paths = require("utils.paths") +local Text = require("utils.text") +local logger = require("utils.log") + +local Assets = {} + +local WEB = "https://weread.qq.com" +local DIR = debug.getinfo(1, "S").source:match("^@(.*)/[^/]+$") +-- 原书脚注图只在 EPUB 里,服务端不给;网页端换成「注」图标,这里用插件自带的同一张。 +local STYLE_NAME = "stylesheets.css" + +-- 原书样式拉不到时的兜底:微信 EPUB 正文几乎都靠 .content 的 text-indent:2em。 +-- 没有这层,CRE 只按默认 p 排,段首顶格、靠段间距分段落——正是用户反馈的「没缩进」。 +local FALLBACK_STYLE = "" + +--- 官方章 HTML 里脚注图标路径不统一(``note.png`` / ``Images/note.png`` / ``../Images/note.png``)。 +--- 服务端 tar 通常不含这张图;正文带 qqreader-footnote 或任意 note.png 引用时, +--- 把插件自带的「注」图标按 basename 挂进 src_map,rewriteImageSources 即可命中所有变体。 +---@param html string +---@return boolean +local function needsBundledFootnote(html) + return html:find("qqreader-footnote", 1, true) ~= nil + or html:find("[\"'/]note%.png") ~= nil +end + +--- 脚注图标落到 images/,返回相对 href。 +---@param images_dir string +---@return string|nil +local function footnoteHref(images_dir) + local f = assert(io.open(DIR .. "/note.png", "rb")) + local data = f:read("*a") + f:close() + return Shared.materializeImage(images_dir, data) +end + +--- 整份写完再 rename,避免半截文件被当成已缓存。 +---@param path string +---@param data string +---@return boolean +local function writeFile(path, data) + local tmp = path .. ".part" + local w = io.open(tmp, "wb") + if not w then return false end + local wrote = w:write(data) + local closed = w:close() + if not wrote or not closed or not os.rename(tmp, path) then + os.remove(tmp) + return false + end + return true +end + +--- 相对路径的 css link 一律指向工作目录里的整书样式表(e_2 st=1 回的就是全部样式)。 +---@param html string +---@return string rewritten +---@return integer count +local function rewriteStyleLinks(html) + local count = 0 + local out = html:gsub("(]-href=)([\"'])([^\"']-%.css)%2", function(prefix, quote, href) + if href:match("^%a[%w+.-]*:") or href:match("^//") then return nil end + count = count + 1 + return prefix .. quote .. STYLE_NAME .. quote + end) + return out, count +end + +-- KOReader 默认样式让每个 h1 另起一页;原书把「第/一/章」拆成连续三个 h1 竖排成一页, +-- 不放开就会分成三页。 +-- 章首页用 body.bgimg-1 铺满页的背景图(样式表里 cover),crengine 会把它拉伸到整个文档高度; +-- 改成只包住标题的一页高容器(vh = 视口高度),背景图随之只铺这一页。 +local TITLE_CSS = "" + +--- body.bgimg-1 的章:丢掉开头垫底的透明出血图,把紧跟着的连续 h1 包进整页容器。 +---@param html string +---@return string +local function wrapTitlePage(html) + local head, rest = html:match('^(.-%s*)(.*)$') + if not head then return html end + rest = rest:gsub('^

.-

%s*', "", 1) + local pos = 1 + while true do + local _s, e = rest:find("^]*>.-%s*", pos) + if not e then break end + pos = e + 1 + end + if pos == 1 then return head .. rest end + return head .. '
' .. rest:sub(1, pos - 1) .. "
" .. rest:sub(pos) +end + +--- 相对 css link 解不到文件时 CRE 不会应用 .content 缩进;去掉坏相对 link,换上兜底样式。 +---@param html string +---@return string +local function withFallbackStyle(html) + html = html:gsub("(]-href=)([\"'])([^\"']-%.css)%2([^>]*>)", function(prefix, quote, href, suffix) + if href:match("^%a[%w+.-]*:") or href:match("^//") then + return prefix .. quote .. href .. quote .. suffix + end + return "" + end) + if html:find("", 1, true) then + return (html:gsub("", FALLBACK_STYLE .. "", 1)) + end + return FALLBACK_STYLE .. html +end + +--- 样式表每本书只拉一次;拉不到就去掉坏 link、注入兜底缩进,下一章仍会再试整书包。 +---@param work_dir string +---@param html string +---@param fetch_style fun(done: fun(css: string|nil)): { cancel: fun() }|nil +---@param cb fun(html: string) +---@return { cancel: fun() }|nil +local function localizeStyleAsync(work_dir, html, fetch_style, cb) + html = wrapTitlePage(html):gsub("", function() return TITLE_CSS .. "" end, 1) + local rewritten, count = rewriteStyleLinks(html) + if count == 0 then + cb(html) + return nil + end + local path = work_dir .. "/" .. STYLE_NAME + local f = io.open(path, "rb") + if f then + f:close() + cb(rewritten) + return nil + end + return fetch_style(function(css) + if css and writeFile(path, (css:gsub("%.%./Images/", "images/"))) then + cb(rewritten) + else + cb(withFallbackStyle(html)) + end + end) +end + +---@param value string|nil +---@return string +local function trimNulls(value) + return (tostring(value or ""):gsub("%z.*$", ""):gsub("%s+$", "")) +end + +---@param data string +---@return table[] +local function tarEntries(data) + local entries = {} + local offset = 1 + while offset + 511 <= #data do + local header = data:sub(offset, offset + 511) + if header:match("^%z+$") then + break + end + local name = trimNulls(header:sub(1, 100)) + local size_text = trimNulls(header:sub(125, 136)):gsub("%s", "") + local size = tonumber(size_text, 8) or 0 + local typeflag = header:sub(157, 157) + local body_start = offset + 512 + local body_end = body_start + size - 1 + if name ~= "" and (typeflag == "0" or typeflag == "" or typeflag == "\0") and size > 0 then + entries[#entries + 1] = { + name = name, + data = data:sub(body_start, body_end), + } + end + offset = body_start + math.ceil(size / 512) * 512 + end + return entries +end + +---@param tar string +---@return string +local function absTarUrl(tar) + if tar:match("^//") then + return "https:" .. tar + end + if tar:match("^/") then + return WEB .. tar + end + return tar +end + +---@param url string +---@param referer string|nil +---@param cb fun(data: string|nil, err: any) +---@return table|nil +local function downloadBinaryAsync(url, referer, cb) + return Auth.webGetAsync(url, { + accept = "image/avif,image/webp,image/apng,image/*,*/*;q=0.8", + headers = { + ["Referer"] = referer or (WEB .. "/"), + }, + timeout = require("http.timeout").net(3), + allow_redirects = true, + -- CDN 403 不是会话失效,禁止走 renewal 误判。 + skip_auth_retry = true, + }, function(raw, err) + if not raw or raw == "" then + logger.dbg("wechat image download failed", url, err) + cb(nil, err) + else + cb(raw) + end + end) +end + +--- 单张公众号图片上限:降到 640 档后一般几十到几百 KB,超过的多半是动图,不落地。 +local MAX_ARTICLE_IMAGE = 2 * 1024 * 1024 + +--- 公众号文章图(mmbiz CDN):不带微信读书会话 Cookie,Referer 用公众号站点(CDN 防盗链认它)。 +---@param url string +---@param cb fun(data: string|nil) +---@return table|nil +local function downloadArticleImageAsync(url, cb) + local Request = require("http.request") + local chunks, size, too_big, code = {}, 0, false, nil + local function abort() + too_big, chunks = true, {} + end + local job + job = Request.stream({ + url = url, + headers = { + ["Accept"] = "image/jpeg,image/png,image/gif,image/*;q=0.8", + ["Referer"] = "https://mp.weixin.qq.com/", + }, + timeout = require("http.timeout").net(3), + allow_redirects = true, + }, { + on_headers = function(status, headers) + code = tonumber(status) + local len = tonumber((Request.header({ headers = headers }, "Content-Length"))) + if len and len > MAX_ARTICLE_IMAGE then abort(); if job and job.cancel then job:cancel() end end + end, + on_data = function(chunk) + if too_big then return end + size = size + #chunk + if size > MAX_ARTICLE_IMAGE then + abort() + if job and job.cancel then job:cancel() end + return + end + chunks[#chunks + 1] = chunk + end, + on_done = function(err) + if too_big or not code or code ~= 200 then + logger.dbg("wechat mp image skipped", url, err or code, size) + cb(nil) + return + end + local body = table.concat(chunks) + cb(body ~= "" and body or nil) + end, + }) + return job +end + +--- 公众号文章正文里的远程图逐张落到 images_dir(打开该篇时才下),改写成相对路径。 +---@param images_dir string +---@param html string +---@param cb fun(html: string) +---@return { cancel: fun() } +function Assets.localizeArticleAsync(images_dir, html, cb) + return Shared.localizeAsync(html, images_dir, downloadArticleImageAsync, cb) +end + +--- 下载章节 tar 包,提取图片写入 images/ 并返回 src 映射。 +---@param tar string +---@param referer string|nil +---@param images_dir string +---@param cb fun(src_map: table|nil, err: any) +---@return table|nil +local function downloadTarAsync(tar, referer, images_dir, cb) + return downloadBinaryAsync(absTarUrl(tar), referer, function(raw, err) + if not raw then + cb(nil, err) + return + end + local src_map = {} + for _idx, entry in ipairs(tarEntries(raw)) do + local href = Shared.materializeImage(images_dir, entry.data) + if href then + local name = Text.basename(entry.name) + src_map[name] = href + local stem = name:gsub("%.[^%.]+$", "") + if stem ~= "" and stem ~= name then + src_map[stem] = href + end + end + end + cb(src_map) + end) +end + +--- 把章节引用的插图、脚注图标、样式表落到书籍工作目录,并把引用改写为相对路径。 +---@param book_id string +---@param chapter BookChapter +---@param html string +---@param referer string|nil +---@param fetch_style fun(done: fun(css: string|nil)): { cancel: fun() }|nil 拉整书样式表 +---@param cb fun(html: string) +---@return { cancel: fun() } +function Assets.localizeAsync(book_id, chapter, html, referer, fetch_style, cb) + local cancelled = false + local jobs = {} + local work_dir = Paths.bookWorkDir(book_id, "ext.weread") + local images_dir = work_dir .. "/images" + + --- 图片落地后再补样式表;已取消则丢弃。 + ---@param out string + local function afterImages(out) + if cancelled then return end + local job = localizeStyleAsync(work_dir, out, fetch_style, function(final) + if not cancelled then cb(final) end + end) + if job then jobs[#jobs + 1] = job end + end + + --- tar 资源包处理完后,先按包内映射改写 src,再补下仍指向 http(s) 的图片。 + ---@param src_map table 原始 src → 本地相对路径 + local function afterTar(src_map) + if cancelled then return end + if not src_map["note.png"] and needsBundledFootnote(html) then + local href = footnoteHref(images_dir) + if href then + src_map["note.png"] = href + end + end + local rewritten = Shared.rewriteImageSources(html, src_map) + local job = Shared.localizeAsync(rewritten, images_dir, function(url, done) + return downloadBinaryAsync(url, WEB .. "/", done) + end, afterImages) + jobs[#jobs + 1] = job + end + + if type(chapter.tar) == "string" and chapter.tar ~= "" then + local job = downloadTarAsync(chapter.tar, referer, images_dir, function(src_map, err) + if cancelled then return end + if not src_map then + logger.dbg("wechat tar assets failed", book_id, chapter.uid, err) + src_map = {} + end + afterTar(src_map) + end) + if job then jobs[#jobs + 1] = job end + else + afterTar({}) + end + + return { cancel = function() + cancelled = true + for _idx, job in ipairs(jobs) do + if job.cancel then job:cancel() end + end + end } +end + +return Assets diff --git a/moonsource-weread.koplugin/moonsource_weread/auth.lua b/moonsource-weread.koplugin/moonsource_weread/auth.lua new file mode 100644 index 0000000..8da8117 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/auth.lua @@ -0,0 +1,304 @@ +--[[-- +微信读书会话:Eink 扫码拿到的 vid/accessToken 即网页会话(wr_vid/wr_skey Cookie)。 + +登录与续期在 ``moonsource_weread.eink``;这里只负责把会话拼成网页请求头, +以及带鉴权失效自动续期 + 单次重试的网页请求。 +只有网页会话、没有 Eink refresh_token 的旧登录视为未登录,需要重新扫码。 + +网络仅异步:Request.request。 + +@module koplugin.book.moonsource_weread.auth +--]] + +local Json = require("utils.json") +local logger = require("utils.log") +local Request = require("http.request") +local Header = require("http.request.header") +local Protocol = require("moonsource_weread.protocol") +local Eink = require("moonsource_weread.eink") +local Context = require("moonsource_weread.context") +local _ = require("l10n").get("moonsource_weread") + +local Auth = {} + +local WEB = "https://weread.qq.com" + +--- 微信会话失效 errcode(对齐 weread.koplugin)。 +local AUTH_ERRCODES = { + [-2012] = true, + [-2041] = true, +} + +--- 自动续期冷却(秒):WAF 403 / 误判的失效回包不能每个请求都打一次 /login。 +local RENEW_COOLDOWN = 600 +--- 上次自动续期的发起时间(不论成败)。 +local renewed_at = 0 + +--- 合并浏览器默认请求头(UA 与 protocol.webAppId 保持一致,阅读时长上报 appId 依赖 UA)。 +---@param extra table|nil +---@return table +local function browserHeaders(extra) + return Header.merge(extra, { + ["User-Agent"] = Protocol.USER_AGENT, + ["Accept-Language"] = "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6", + ["Referer"] = WEB .. "/", + ["Origin"] = WEB, + ["Sec-Ch-Ua"] = '"Microsoft Edge";v="147", "Not.A/Brand";v="8", "Chromium";v="147"', + ["Sec-Ch-Ua-Mobile"] = "?0", + ["Sec-Ch-Ua-Platform"] = '"Windows"', + }) +end + +--- 会话请求头:Eink 令牌即网页会话,Cookie 只需 wr_vid / wr_skey。 +--- 旧网页登录残留的 wr_gid / wr_fp / wr_rt 属于已失效会话,不再发送。 +--- 未登录(封面等匿名请求)只带浏览器头。 +---@param extra table|nil +---@return table +function Auth.sessionHeaders(extra) + local creds = Eink.credentials() + if not creds then + return browserHeaders(extra) + end + return browserHeaders(Header.merge(extra, { + ["Cookie"] = "wr_vid=" .. creds.vid .. "; wr_skey=" .. creds.access_token .. "; wr_ql=0", + ["X-Vid"] = creds.vid, + ["X-Skey"] = creds.access_token, + })) +end + +--- 是否已登录:必须是 Eink 扫码会话(能续期);旧网页会话不算。 +Auth.hasSession = Eink.hasSession + +--- 展示用用户标签(昵称优先,否则 user_id)。 +---@return string|nil +function Auth.userLabel() + local c = Eink.config() + if c.user_name and c.user_name ~= "" then + return c.user_name + end + if c.user_id and c.user_id ~= "" then + return tostring(c.user_id) + end + return nil +end + +--- 清除本地会话;wr_gid/wr_fp/wr_rt/cookie 是旧网页登录、api_key/skill_version 是已废弃 +--- Skills 网关的残留,一并清掉。 +function Auth.clearSession() + Eink.save({ + cookie = "", + wr_vid = "", + wr_skey = "", + wr_rt = "", + wr_gid = "", + wr_fp = "", + wr_ql = "", + user_id = "", + user_name = "", + -- 表构造器里 nil 值键不存在,pairs 看不到,必须置空串才真正清掉 + api_key = "", + skill_version = "", + }) + Eink.clearSession() + Context.clear() +end + +--- 会话失效探针:只有带 errcode/errmsg 的 JSON 才值得解码。 +--- +--- 章节正文分片、reader 页 HTML 与图片都会走同一条请求路径,动辄几百 KB 且必然不是 +--- JSON;无条件 decode 一遍纯属白烧 CPU。 +---@param raw string +---@return boolean +local function mayCarryErrCode(raw) + if raw:sub(1, 1) ~= "{" then + return false + end + return raw:find("errcode", 1, true) ~= nil or raw:find("errCode", 1, true) ~= nil + or raw:find("errmsg", 1, true) ~= nil or raw:find("errMsg", 1, true) ~= nil +end + +--- 解码 JSON 文本为 table;不是 JSON 对象返回 nil。 +---@param raw string +---@return table|nil +local function decodeJson(raw) + local ok, data = pcall(Json.decode, raw) + return ok and type(data) == "table" and data or nil +end + +--- 判断响应是否属于会话失效(应尝试 renewal)。 +---@param data table|nil +---@param http_code number|nil +---@return boolean +local function isAuthFailure(data, http_code) + if type(data) == "table" then + local code = tonumber(data.errcode or data.errCode) + if code and AUTH_ERRCODES[code] then + return true + end + local msg = tostring(data.errmsg or data.errMsg or "") + if msg:find("登录", 1, true) then + return true + end + end + local code = tonumber(http_code) + return code == 401 or code == 403 +end + +--- 自动续期;冷却内不再打 /login,直接让调用方用现有令牌重试一次。 +--- 单飞由 Eink.refreshAsync 负责:续期在飞时后来的请求排进同一次 /login 等结果,不能拿旧令牌立刻重试 +--- (否则旧令牌必然再回失效 errcode,被当成「续期救不回来」而误判登录失效),所以在飞时不看冷却。 +---@param cb fun(ok: boolean, err: string|nil, rejected: boolean|nil) +local function renewAsync(cb) + if Eink.refreshing() then + Eink.refreshAsync(cb) + return + end + local now = os.time() + if now - renewed_at < RENEW_COOLDOWN then + cb(true) + return + end + renewed_at = now + Eink.refreshAsync(cb) +end + +--- 当前令牌(判断请求发出后令牌是否已被别的请求续期换掉)。 +---@return string|nil +local function currentToken() + local creds = Eink.credentials() + return creds and creds.access_token +end + +---@class WechatRequestOpts +---@field headers table|nil +---@field accept string|nil +---@field content_type string|nil POST 缺省 application/json +---@field timeout number|nil 缺省 45 秒 +---@field allow_redirects boolean|nil +---@field skip_auth_retry boolean|nil 不把 401/403 当会话失效(CDN 图片等) +---@field no_expire boolean|nil 续期重试后仍被拒也不判登录失效(公众号接口会因风控回失效 errcode,而书架等接口照常可用) + +--- 带会话失效自动 renewal + 单次重试的 HTTP 请求。 +---@param method string +---@param url string 完整 URL +---@param body string|nil +---@param opts WechatRequestOpts|nil +---@param cb fun(raw: string|nil, err: string|nil, res: table|nil) 失败时 raw 为 nil,res 是原始响应 +---@return { cancel: fun() }|nil +local function sessionRequest(method, url, body, opts, cb) + opts = opts or {} + if not Auth.hasSession() then + cb(nil, _("请先扫码登录微信读书")) + return nil + end + -- 续期后重试换了请求:句柄跟着换,取消要能杀掉当前这一次。 + local cancelled, job = false, nil + local function attempt(retried) + local sent_token = currentToken() + local headers = Auth.sessionHeaders(opts.headers) + if opts.accept then + headers["Accept"] = opts.accept + end + if method == "POST" then + headers["Content-Type"] = opts.content_type or "application/json" + end + job = Request.request({ + url = url, + method = method, + body = body, + headers = headers, + timeout = opts.timeout or require("http.timeout").net(1.5), + allow_redirects = opts.allow_redirects, + }, function(res, err) + if cancelled then return end + if err then + cb(nil, err, res) + return + end + local code = res and res.code + local raw = res and res.body or "" + -- 只解一次:带 errcode 的 JSON 解出来既判失效、也经 res.json 交给调用方,免得再解一遍。 + local data = mayCarryErrCode(raw) and decodeJson(raw) or nil + if not opts.skip_auth_retry and not retried and isAuthFailure(data, code) then + logger.dbg("wechat auth failure", url:match("^[^?]*"), code, #raw < 200 and raw or #raw) + -- 请求在飞期间别的请求已续期换了令牌:直接用新令牌重试,不再打 /login + if sent_token ~= currentToken() then + attempt(true) + return + end + renewAsync(function(renewed, renew_err, rejected) + if cancelled then return end + if renewed then + attempt(true) + elseif rejected then + if renew_err then logger.warn("wechat auth renew rejected", renew_err) end + cb(nil, require("source.auth").expire("ext.weread", _("点这个提示上的「重新登录」。二维码出来以后,打开手机微信,点右上角「+」,再点「扫一扫」,对准屏幕上的二维码,在手机上点确认。")), res) + else + cb(nil, renew_err or _("请求失败"), res) + end + end) + return + end + -- 续期重试后回包仍明确是会话失效 errcode:静默续期救不回来。 + -- 裸 401/403(WAF 拦截等)不算,免得误判暂停同步。 + if retried and not opts.skip_auth_retry and data and isAuthFailure(data, nil) then + logger.warn("wechat auth failure after renew", url:match("^[^?]*"), #raw < 200 and raw or #raw) + if opts.no_expire then + cb(nil, _("微信读书拒绝了请求,请稍后再试"), res) + else + cb(nil, require("source.auth").expire("ext.weread", _("点这个提示上的「重新登录」。二维码出来以后,打开手机微信,点右上角「+」,再点「扫一扫」,对准屏幕上的二维码,在手机上点确认。")), res) + end + return + end + if not Request.ok(code) then + cb(nil, "HTTP " .. tostring(code), res) + return + end + if not opts.skip_auth_retry then require("source.auth").ok("ext.weread") end + if res then res.json = data end + cb(raw, nil, res) + end) + end + attempt(false) + return { cancel = function() + cancelled = true + if job then job:cancel() end + end } +end + +--- 带会话 Cookie 的异步 GET;遇鉴权失效会自动续期后重试一次。 +---@param url string 完整 URL +---@param opts WechatRequestOpts|nil +---@param cb fun(raw: string|nil, err: string|nil, res: table|nil) +---@return { cancel: fun() }|nil +function Auth.webGetAsync(url, opts, cb) + return sessionRequest("GET", url, nil, opts, cb) +end + +--- 带会话 Cookie 的异步 POST;同 webGetAsync。 +---@param url string 完整 URL +---@param body string|nil 已编码的请求体 +---@param opts WechatRequestOpts|nil +---@param cb fun(raw: string|nil, err: string|nil, res: table|nil) +---@return { cancel: fun() }|nil +function Auth.webPostAsync(url, body, opts, cb) + return sessionRequest("POST", url, body, opts, cb) +end + +--- 扫码登录后补拉昵称;取不到不算失败,会话本身已可用。 +---@param cb fun(user: { user_id: string, user_name: string }) +---@return { cancel: fun() }|nil +function Auth.fetchUserAsync(cb) + local vid = Eink.config().wr_vid + return Auth.webGetAsync(WEB .. "/api/userInfo?userVid=" .. vid, nil, function(raw) + local data = raw and decodeJson(raw) + local name = data and type(data.name) == "string" and data.name or "" + if name ~= "" then + Eink.save({ user_name = name }) + end + logger.info("weread login ok", vid, name) + cb({ user_id = vid, user_name = name }) + end) +end + +return Auth diff --git a/moonsource-weread.koplugin/moonsource_weread/chapter.lua b/moonsource-weread.koplugin/moonsource_weread/chapter.lua new file mode 100644 index 0000000..eb8bb93 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/chapter.lua @@ -0,0 +1,722 @@ +--[[-- +微信读书章节正文:只走官方 App 的 /book/chapterdownload。 +EPUB 使用加密 ZIP,TXT 可能以 TAR 或 ZIP 返回(bookType 与书架 format 一致)。 +EPUB 章节交出服务端 XHTML 原文,除资源本地化(插图、脚注图标、整书样式表)和脚注接弹窗外不改一个字节; +不写盘、不打 EPUB。个人划线通过 bookmarklist 同步为 KOReader 原生注解。 + +@module koplugin.book.moonsource_weread.chapter +--]] + +local JSON = require("json") +local logger = require("utils.log") +local Auth = require("moonsource_weread.auth") +local Protocol = require("moonsource_weread.protocol") +local Eink = require("moonsource_weread.eink") +local Job = require("workers.job") +local Package = require("moonsource_weread.package") +local Request = require("http.request") +local Assets = require("moonsource_weread.assets") +local Text = require("utils.text") +local Paths = require("utils.paths") +local Toc = require("moonsource_weread.toc") +local Client = require("moonsource_weread.client") +local Mem = require("utils.mem") +local Context = require("moonsource_weread.context") +local Mapper = require("moonsource_weread.mapper") +local _ = require("l10n").get("moonsource_weread") + +local Chapter = {} + +--- 解包前预检:不够则弹窗(Kindle 可改走 no-framework)并失败,不 fork。 +---@param need number +---@param fail fun(err: string) +---@return boolean ok +local function affordPackage(need, fail) + local ok, err, detail = Mem.canAfford(need) + if ok then return true end + logger.warn("book.mem insufficient", "weread_chapter_package", err) + logger.flushSync() + Mem.promptInsufficient({ + what = Mem.chapterUnpackWhat(), + needed = detail.needed, + available = detail.available, + }) + fail(err) + return false +end + +--- App 章节包:chapters 填章 uid("0" 是整书资源:样式表、公共图片)。 +--- EPUB 是加密 zip,口令在响应头 encryptKey;TXT 支持 tar 和 zip。 +--- bookVersion 用书籍版本;-2063 按回包的新版本或刷新详情后最多重试一次。 +--- opts.offline:缓存全书 / 批量预取用 1(对齐官方);单章在线阅读用 0。 +--- opts.batch:pick 返回整表,cb(result, err);否则 cb(text, err, style)。 +---@param bookId string +---@param chapters string +---@param book_type '"epub"'|'"txt"' +---@param pick fun(files: table): any, string|nil +---@param cb function +---@param opts { offline?: boolean, batch?: boolean }|nil +---@return { cancel: fun() } +local function downloadPackageAsync(bookId, chapters, book_type, pick, cb, opts) + opts = opts or {} + local offline = opts.offline and "1" or "0" + local cancelled, call, job = false, nil, nil + local download + local function fail(err) + if opts.batch then cb(nil, err) else cb(nil, err) end + end + local function fetchVersion(attempt) + local fired = false + local next_call = Client:bookInfoAsync(bookId, function(wire, err) + fired = true + if cancelled then return end + if not wire then + fail(err) + return + end + local version = Mapper.bookVersion(wire) + if not version then + fail(_("缺少书籍版本")) + return + end + Context.rememberBookVersion(bookId, version) + download(attempt, version) + end) + if not fired then call = next_call end + end + download = function(attempt, version) + local fired = false + local next_call = Eink.callAsync("GET", "/book/chapterdownload", { + raw = true, + query = { + bookId = bookId, chapters = chapters, + pf = "wechat_wx-2001-android-100-weread", pfkey = "pfKey", zoneId = "1", + bookVersion = version, bookType = book_type, quote = "", release = "1", + stopAutoPayWhenBNE = "1", preload = "0", preview = "0", offline = offline, + giftPayingCard = "0", enVersion = "10.2.2", modernVersion = "10.2.2", teenmode = "0", + }, + }, function(res, err, meta) + fired = true + if cancelled then return end + if not res and attempt == 1 and meta and meta.errcode == -2063 then + local info = meta.body and meta.body.info + local next_version = type(info) == "table" and tonumber(info.bookVersion) + logger.warn("weread chapter book version expired", bookId, version, next_version) + if next_version and next_version > 0 and next_version ~= version then + Context.rememberBookVersion(bookId, next_version) + download(2, next_version) + else + fetchVersion(2) + end + return + end + if not res then + fail(err) + return + end + local body = res.body or "" + if body:sub(258, 262) == "ustar" then + -- tar 通常一章;正文从已在内存的包里抽出,按 2× 包长估计额外峰值。 + if not affordPackage(2 * #body, fail) then return end + job = Job.run(function() + -- tar 包通常一章;chapters 可能是 "12" 或批量串,取第一个数字 uid。 + local uid = tostring(chapters):match("(%d+)") or chapters + local text, terr = Package.chapterText(body, bookId, uid) + return { text = text, err = terr } + end, { + name = "weread_chapter_package", + kind = "light", + timeout = 60, + on_done = function(out) + if cancelled then return end + if opts.batch then cb(out, out.err) else cb(out.text, out.err) end + end, + on_failed = function(jerr) if not cancelled then fail(tostring(jerr)) end end, + on_cancelled = function() end, + }) + return + end + local key = Request.header(res, "encryptKey") + local password = key and Package.password(Eink.credentials().vid, key) + if not password then + fail("chapterdownload: no encryptKey") + return + end + -- 解密 + 解压是逐字节纯 Lua,放子进程;包里的图片在 pick 里就地落盘(JSON 帧装不下二进制)。 + -- 样式表是文本,随章包顺手带回,避免整书 Styles/ 缺失时正文失去 text-indent。 + if not affordPackage(Package.unzipNeed(body), fail) then return end + job = Job.run(function() + local files, zerr = Package.unzip(body, password) + if not files then return { err = zerr } end + if opts.batch then + local payload = pick(files) or {} + if payload.err then return payload end + if payload.style == nil then payload.style = Package.pickStyle(files) end + return payload + end + local text, perr = pick(files) + return { text = text, err = perr, style = Package.pickStyle(files) } + end, { + name = "weread_chapter_package", + kind = "light", + timeout = 60, + on_done = function(out) + if cancelled then return end + if opts.batch then cb(out, out and out.err) else cb(out.text, out.err, out.style) end + end, + on_failed = function(jerr) if not cancelled then fail(tostring(jerr)) end end, + on_cancelled = function() end, + }) + end) + -- 同步回调可能已经发出了重试或解包,不能拿旧请求覆盖当前句柄。 + if not fired then call = next_call end + end + local version = Context.bookVersion(bookId) + if version then download(1, version) else fetchVersion(1) end + return { cancel = function() + cancelled = true + if call then call:cancel() end + if job then job:cancel() end + end } +end + +--- 批量包解出的章:key 为 uid 字符串。单章打开不经此表。 +---@type table +local primed = {} + +local function primedKey(bookId, uid) + return bookId .. "\0" .. tostring(uid) +end + +--- 把官方一批(最多 5 章 + 样式 0)打进 primed,供随后的 fetchHtmlAsync 直接取。 +---@param bookId string +---@param chapters BookChapter[] +---@param opts { offline?: boolean }|nil +---@param cb fun(ok: boolean, err: any) +---@return { cancel: fun() } +function Chapter.primeBatchAsync(bookId, chapters, opts, cb) + opts = opts or {} + if type(chapters) ~= "table" or #chapters == 0 then + cb(true) + return { cancel = function() end } + end + local uids, book_type = {}, "epub" + for _idx, ch in ipairs(chapters) do + uids[#uids + 1] = ch.uid + if ch.format == "txt" then book_type = "txt" end + end + local param = Package.formatChaptersParam(uids) + return downloadPackageAsync(bookId, param, book_type, function(files) + local work_dir = Paths.bookWorkDir(bookId, "ext.weread") + Paths.ensureDir(work_dir .. "/images") + for name, data in pairs(files) do + local base = name:match("^Images/([^/]+)$") + if base then + local f = assert(io.open(work_dir .. "/images/" .. base, "wb")) + f:write(data) + f:close() + end + end + local extracted, style = Package.extractChapters(files, bookId, uids, book_type) + return { chapters = extracted, style = style } + end, function(out, err) + if not out or err then + cb(false, err or _("下载失败")) + return + end + local style = out.style + for _idx, uid in ipairs(uids) do + local row = out.chapters and out.chapters[tostring(uid)] + if row and row.text then + primed[primedKey(bookId, uid)] = { + text = row.text, format = row.format or "html", style = style, + } + end + end + cb(true) + end, { offline = opts.offline == true, batch = true }) +end + +--- 整书样式表(章节 link 指向 Styles/stylesheets.css 或 stylesheet.css)。 +--- 包里没有就回 nil;调用方可改用章包里顺手带回的样式,或注入兜底缩进。 +---@param bookId string +---@param _uid string +---@param work_dir string 整书公共图(样式表里 ../Images/ 引用的背景等)落到它的 images/ +---@param done fun(css: string|nil) +---@return { cancel: fun() }|nil +local function fetchStyleAsync(bookId, _uid, work_dir, done) + Paths.ensureDir(work_dir .. "/images") + return downloadPackageAsync(bookId, "0", "epub", function(files) + for name, data in pairs(files) do + local base = name:match("^Images/([^/]+)$") + if base then + local f = assert(io.open(work_dir .. "/images/" .. base, "wb")) + f:write(data) + f:close() + end + end + return Package.pickStyle(files) + end, function(css, err) + if not css then logger.warn("weread stylesheet app fetch", bookId, err) end + done(css) + end) +end + +--- 异步拉取章节正文。失败就是失败,不再改走网页阅读接口。 +--- 第三、四个回调参数是划线 range 的坐标原文与格式:EPUB 为包内 xhtml,TXT 为包内纯文本 +--- (format 分别为 "html" / "txt");不能用清理或段落化后的正文,否则 range 整体偏移。 +--- 第五个是章包里顺带解出的样式表(有就有,没有为 nil)。 +---@param bookId string +---@param chapter BookChapter +---@param cb fun(html: string|nil, err: any, range_source: string|nil, format: '"html"'|'"txt"'|nil, style: string|nil) +---@return { cancel: fun() } +function Chapter.fetchHtmlAsync(bookId, chapter, cb) + local uid = chapter.uid + if type(uid) ~= "string" or uid == "" then + cb(nil, _("章节缺少 uid")) + return { cancel = function() end } + end + local hit = primed[primedKey(bookId, uid)] + if hit then + primed[primedKey(bookId, uid)] = nil + local text, format, style = hit.text, hit.format, hit.style + if format == "txt" then + cb(Text.textToBody(text), nil, text, "txt", style) + elseif not Text.stripBom(text):find("^%s*<") then + cb(nil, _("试读结束")) + else + cb(text, nil, text, "html", style) + end + return { cancel = function() end } + end + local book_type = chapter.format == "txt" and "txt" or "epub" + return downloadPackageAsync(bookId, uid, book_type, function(files) + if book_type == "txt" then + -- 部分 TXT 章节以 ZIP 返回,正文条目可直接按书和章节定位。 + local text = Package.chapterZipText(files, bookId, uid) + if not text then return nil, "zip: chapter " .. uid .. " not in package" end + return text + end + return Package.chapterHtml(files, uid) + end, function(text, err, style) + if not text then + logger.warn("weread chapter app fetch", bookId, chapter.idx, err) + cb(nil, err) + return + end + if book_type == "txt" then + cb(Text.textToBody(text), nil, text, "txt") + return + end + -- 付费章的包里不是 xhtml,是几百字试读片段。官方阅读器这时开的是购买页,标题「试读结束」。 + if not Text.stripBom(text):find("^%s*<") then + cb(nil, _("试读结束")) + return + end + cb(text, nil, text, "html", style) + end) +end + +--- 把脚注 aside 块放到 body 末尾(空块原样返回)。 +--- 必须带 ``epub:type="footnote"``:KOReader 默认「页内 EPUB 脚注」靠它抽到当前页底部;脚注弹窗也认。 +--- 不加外层样式 div:页内脚注把 aside 抽走后,空壳分割线会留在章末。 +---@param html string +---@param block string +---@return string +local function appendBlock(html, block) + if block == "" then return html end + block = block .. "\n" + local last = html:match(".*()") + if not last then return html .. block end + return html:sub(1, last - 1) .. block .. html:sub(last) +end + +--- 原书脚注是 ``注文``,注文只在 alt 里,点了没东西可弹。 +--- 图标原样包进 noteref 链接,注文放进 body 末尾的 footnote aside,交给 KOReader(页底或弹窗由设置决定)。 +--- 不加 ``

``、不动正文文字:段落序号与字偏移不变,划线 range 照旧对得上。 +--- 图标尺寸写成行内 style:整书样式表拉取失败 / 缺规则时 CRE 会按 PNG 原始像素×DPI 画成两行高的大方块。 +local FOOTNOTE_STYLE = "height:0.8em;width:auto;vertical-align:super;border:0" +local function iconSized(tag) + return (tag:gsub('%sstyle="[^"]*"', ""):gsub("%s*/?>$", ' style="' .. FOOTNOTE_STYLE .. '" />')) +end +---@param html string +---@return string +local function linkFootnotes(html) + if not html:find("qqreader-footnote", 1, true) then return html end + local notes = {} + html = html:gsub("]*>", function(tag) + local class = tag:match('class="([^"]*)"') or "" + local alt = tag:match('alt="([^"]*)"') or "" + if not class:find("qqreader-footnote", 1, true) then return nil end + tag = iconSized(tag) + if alt == "" then return tag end + notes[#notes + 1] = alt + local n = #notes + return string.format('%s', n, n, tag) + end) + if #notes == 0 then return html end + local asides = {} + for i, alt in ipairs(notes) do + -- alt 已是属性转义过的文本,直接当元素内容合法。 + asides[i] = string.format( + '

', + i, i, alt, i) + end + return appendBlock(html, table.concat(asides, "\n")) +end + +--- 原书链接带原文件名(``part0012.html#note_1``、``../Text/zhushi.xhtml#zhu116``),章节落盘后文件名变了, +--- KOReader 报「无效或外部链接」。锚点就在本章文档里的,改写成纯 ``#锚点``;跨章的留给 linkCrossNotes。 +---@param html string +---@return string +local function localizeAnchors(html) + return (html:gsub('href="([^"#:]+)#([^"]+)"', function(_file, frag) + if html:find('id="' .. frag .. '"', 1, true) or html:find('name="' .. frag .. '"', 1, true) then + return 'href="#' .. frag .. '"' + end + return nil + end)) +end + +--- 注释章里「锚点 id → 注文」:``

[116]注文

``。 +--- 注文保留原样转义(不解实体),直接当元素内容合法。 +---@param html string +---@return table +local function noteTexts(html) + local map = {} + for para in html:gmatch("].-

") do + local id = para:match(']-id="([^"]+)"') + local text = id and Text.trim((para:gsub("<[^>]+>", ""):gsub("^%s*%[%d+%]", ""))) + if text and text ~= "" then map[id] = text end + end + return map +end + +Chapter._noteTexts = noteTexts + +--- 注释章按目录标题认:标题带「注」(注释 / 注解 / 脚注 / 尾注)。 +---@param bookId string +---@return string[] uids +local function noteChapterUids(bookId) + local uids = {} + for _idx, ch in ipairs(Toc.read("ext.weread", bookId) or {}) do + if tostring(ch.title or ""):find("注", 1, true) then uids[#uids + 1] = ch.uid end + end + return uids +end + +local note_files = {} + +--- 注释章注文落盘在书工作目录:重启后不必再下一次加密包(下载 + 逐字节解密很慢)。只存取到的,没取到的不落盘。 +---@param bookId string +---@return string +local function notesPath(bookId) + return Paths.bookWorkDir(bookId, "ext.weread") .. "/notes.json" +end + +---@param bookId string +---@return table> +local function loadNotes(bookId) + local f = io.open(notesPath(bookId), "rb") + if not f then return {} end + local data = f:read("*a") + f:close() + local ok, map = pcall(JSON.decode, data) + return ok and type(map) == "table" and map or {} +end + +---@param bookId string +---@param base string +---@param map table +local function saveNotes(bookId, base, map) + local all = loadNotes(bookId) + all[base] = map + local f = assert(io.open(notesPath(bookId), "wb")) + f:write(JSON.encode(all)) + f:close() +end + +--- 跨章链接(本章里找不到锚点)的目标文件 → 在注释章里取注文,做成脚注弹窗;取不到的去掉链接壳只留文字。 +--- 每个目标文件在内存里只取一次(书内常驻,注释章通常很小)。 +---@param bookId string +---@param html string +---@param cb fun(html: string) +---@return { cancel: fun() } +local function linkCrossNotes(bookId, html, cb) + local pending, order = {}, {} + for file in html:gmatch(']-href="([^"#:]+)#[^"]+"') do + local base = Text.basename(file) + if not pending[base] then + pending[base] = true + order[#order + 1] = base + end + end + local cancelled, job = false, nil + local uids = noteChapterUids(bookId) + local function finish() + local notes = {} + html = html:gsub(']-)href="([^"#:]+)#([^"]+)"([^>]*)>(.-)', function(pre, file, frag, post, inner) + local text = (note_files[bookId .. "\0" .. Text.basename(file)] or {})[frag] + inner = inner:gsub("]*>", iconSized) + if not text then return inner end + notes[#notes + 1] = { text = text, label = Text.trim((inner:gsub("<[^>]+>", ""))) } + return string.format('%s', pre, #notes, #notes, post, inner) + end) + local asides = {} + for i, note in ipairs(notes) do + asides[i] = string.format( + '', + i, note.label, note.text, i) + end + cb(appendBlock(html, table.concat(asides, "\n"))) + end + local function nextFile(i) + if cancelled then return end + local base = order[i] + if not base then return finish() end + local key = bookId .. "\0" .. base + note_files[key] = note_files[key] or loadNotes(bookId)[base] + if note_files[key] or #uids == 0 then + note_files[key] = note_files[key] or {} + return nextFile(i + 1) + end + local function try(n) + if n > #uids then + note_files[key] = {} + return nextFile(i + 1) + end + job = downloadPackageAsync(bookId, uids[n], "epub", function(files) + for name, body in pairs(files) do + if Text.basename(name) == base then return body end + end + return nil, "no " .. base + end, function(body) + if cancelled then return end + if body then + note_files[key] = noteTexts(body) + saveNotes(bookId, base, note_files[key]) + return nextFile(i + 1) + end + try(n + 1) + end) + end + try(1) + end + nextFile(1) + return { cancel = function() + cancelled = true + if job then job:cancel() end + end } +end + +--- 章节载荷:EPUB 是服务端 XHTML 原文(只把图片 / 样式表引用换成本地文件、脚注接上弹窗),TXT 是段落化正文。 +---@param bookId string +---@param chapter BookChapter +---@param cb fun(payload: ChapterContentPayload|nil, err: any) +---@return { cancel: fun() } +function Chapter.fetchContentAsync(bookId, chapter, cb) + if not Auth.hasSession() then + cb(nil, _("请先扫码登录微信读书")) + return { cancel = function() end } + end + local title = chapter.title or string.format(_("第 %d 章"), tonumber(chapter.idx) or 0) + local cancelled, asset_job, note_job = false, nil, nil + local reader_url = Protocol.readerUrl(bookId, chapter.uid) + local fetch_job = Chapter.fetchHtmlAsync(bookId, chapter, function(html, err, source, format, style) + if cancelled then return end + if not html then + logger.warn("weread chapter fetch", bookId, chapter.idx, err) + cb(nil, err) + return + end + -- 进度定位缓存写不进去(磁盘满)只影响下次进度换算,正文已到手,照常交出去。 + local cached, cache_err = require("moonsource_weread.progress").remember(bookId, chapter, source, format) + if not cached then logger.warn("wechat chapter position cache failed", bookId, chapter.uid, cache_err) end + if format == "txt" then + -- TXT 正文不含章名(EPUB 原文自带标题),补一个,翻到新章才看得到章名。 + cb({ title = title, html = "

" .. Text.xmlEscape(title) .. "

" .. html }) + return + end + local work_dir = Paths.bookWorkDir(bookId, "ext.weread") + asset_job = Assets.localizeAsync(bookId, chapter, html, reader_url, function(done) + -- 章包里已有样式就不再打整书包;整书包才带公共背景图。 + if type(style) == "string" and style ~= "" then + done(style) + return { cancel = function() end } + end + return fetchStyleAsync(bookId, chapter.uid, work_dir, done) + end, function(localized) + if cancelled then return end + note_job = linkCrossNotes(bookId, linkFootnotes(localizeAnchors(localized)), function(document) + cb({ title = title, document = document }) + end) + end) + end) + return { cancel = function() + cancelled = true + fetch_job:cancel() + if asset_job then asset_job:cancel() end + if note_job then note_job:cancel() end + end } +end + + +local BATCH = 5 + +---@class WechatPrefetchOps +---@field fetchContent fun(identity: BookIdentity, chapter: BookChapter, cb: function): { cancel: fun() } +---@field progress? fun(done: integer, total: integer) +---@field offline boolean|nil +---@field interval_seconds number|nil +---@field persist_book boolean|nil +---@field book Book|nil +---@field reuse? fun(path: string): boolean +---@field volatile boolean|nil + +--- 阅读预取 / 缓存全书:按官方五章一批(chapters 带 0)。 +---@param identity BookIdentity +---@param toc BookChapter[] +---@param from_idx integer +---@param count integer +---@param ops WechatPrefetchOps +---@param cb fun(cached: integer, total: integer, failed: integer, err: any, failed_idx: integer[]|nil)|nil +---@return { cancel: fun() } +function Chapter.prefetchBatchedAsync(identity, toc, from_idx, count, ops, cb) + from_idx = tonumber(from_idx) or 0 + count = tonumber(count) or 0 + local Shared = require("source.chapter") + local lfs = require("libs/libkoreader-lfs") + local cancelled, active = false, nil + local cached_count, failed_count, last_error, failed_idx = 0, 0, nil, {} + local total = 0 + if count > 0 and type(toc) == "table" then + total = math.max(0, math.min(count, #toc - from_idx)) + end + if total == 0 then + require("ui/uimanager"):nextTick(require("ui.guard").wrap("chapter callback", function() + if not cancelled and cb then cb(0, 0, 0) end + end)) + return { cancel = function() cancelled = true end } + end + + local offset = 0 + local interval = math.max(0, tonumber(ops.interval_seconds) or 0) + local function soon(fn) + local UIManager = require("ui/uimanager") + if interval > 0 then + UIManager:scheduleIn(interval, require("ui.guard").wrap("wechat batch", fn)) + else + UIManager:nextTick(require("ui.guard").wrap("wechat batch", fn)) + end + end + + local function chapterReady(chapter) + local path = Paths.chapterPath(identity.stable_id, chapter.idx, identity.source_id) + if ops.reuse then return ops.reuse(path) end + local attr = lfs.attributes(path) + return attr and attr.mode == "file" and (attr.size or 0) > 0 + end + + local function step() + if cancelled then return end + if offset >= total then + if cb then cb(cached_count, total, failed_count, last_error, failed_idx) end + return + end + local n = math.min(BATCH, total - offset) + local need = {} + for j = 1, n do + local chapter = toc[from_idx + offset + j] + if chapter and not chapterReady(chapter) then + need[#need + 1] = chapter + end + end + local function runSlice() + if cancelled then return end + active = Shared.prefetchAsync(identity, ops.book, toc, from_idx + offset, n, { + fetchContent = ops.fetchContent, + persist_book = ops.persist_book, + volatile = ops.volatile, + reuse = ops.reuse, + interval_seconds = 0, + }, function(cached, _t, failed, err, idxs) + active = nil + if cancelled then return end + cached_count = cached_count + (cached or 0) + failed_count = failed_count + (failed or 0) + last_error = err or last_error + if type(idxs) == "table" then + for _i, idx in ipairs(idxs) do failed_idx[#failed_idx + 1] = idx end + end + offset = offset + n + if ops.progress then ops.progress(cached_count + failed_count, total) end + soon(step) + end) + end + if #need == 0 then + runSlice() + return + end + active = Chapter.primeBatchAsync(identity.stable_id, need, { offline = ops.offline == true }, function(ok, err) + active = nil + if cancelled then return end + if not ok then logger.warn("weread batch prime failed", identity.stable_id, err) end + runSlice() + end) + end + + if require("ui/network/manager"):isConnected() then + soon(step) + else + require("ui/uimanager"):nextTick(require("ui.guard").wrap("chapter callback", function() + if not cancelled and cb then + cb(0, total, total, _("网络不可用,请先连接 Wi-Fi")) + end + end)) + end + return { cancel = function() + cancelled = true + if active and active.cancel then active.cancel() end + end } +end + +--- 缓存全书(或 range):offline=1,五章一批。 +---@param source BookSource +---@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, failed_idx: integer[]|nil) +---@param range table|nil +---@return { cancel: fun() } +function Chapter.cacheAllBatchedAsync(source, identity, on_progress, cb, range) + local cancelled, active = false, nil + active = source:loadTocAsync(identity, function(toc, err) + if cancelled then return end + if not toc then + cb(false, 0, err or _("章节列表为空"), 0, 0) + return + end + local Shared = require("source.chapter") + local from_idx, count = Shared.cacheRange(toc, range) + active = Chapter.prefetchBatchedAsync(identity, toc, from_idx, count, { + fetchContent = function(r, chapter, done) + return Chapter.fetchContentAsync(r.stable_id, chapter, done) + end, + progress = on_progress, + offline = true, + persist_book = false, + -- 批次之间歇一下;批内已是一次请求。 + interval_seconds = 1.5, + }, function(cached, total, failed, last_err, failed_idx) + if not cancelled then + cb(failed == 0, cached, last_err, total, failed, failed_idx) + end + end) + end) + return { cancel = function() + cancelled = true + if active and active.cancel then active.cancel() end + end } +end + + +return Chapter diff --git a/moonsource-weread.koplugin/moonsource_weread/client.lua b/moonsource-weread.koplugin/moonsource_weread/client.lua new file mode 100644 index 0000000..8f03baf --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/client.lua @@ -0,0 +1,671 @@ +--[[-- +微信读书协议客户端:只返回 wire,不做领域转换(仅异步)。 + +书架、章节、想法、划线、搜索、进度与统计走 Eink ``i.weread.qq.com``(App 协议)。 +进度与时长都是 ``POST /book/read``。跨了多个小时,或补报离线积压,改走 ``POST /book/batchUploadProgress``。 + +@module koplugin.book.moonsource_weread.client +--]] + +local JSON = require("json") +local logger = require("utils.log") +local Auth = require("moonsource_weread.auth") +local Eink = require("moonsource_weread.eink") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_weread") + +local WEB = "https://weread.qq.com" +-- 本人想法每页条数与翻页上限(hasMore=1 时按回包 maxIdx 续拉) +local MY_REVIEWS_PAGE = 100 +local MY_REVIEWS_MAX_PAGES = 20 + +--- 无状态:方法保留冒号形式,模块表本身就是 ``source.shelf`` 要的远端。 +---@class WechatClient +local Client = {} + +--- 回包解码并校验 errcode。 +--- 不是 JSON 一律按失败:登录页 HTML 与 WAF 拦截页都长这样,当成功会静默丢数据。 +---@param url string 仅用于日志 +---@param cb fun(data: table|nil, err: string|nil) +---@return fun(raw: string|nil, err: string|nil) +local function webWire(url, cb) + return function(raw, err) + if not raw then + cb(nil, err) + return + end + local ok, data = pcall(require("utils.json").decode, raw) + if not ok or type(data) ~= "table" then + logger.warn("weread web: unexpected response", url, raw:sub(1, 120)) + cb(nil, _("返回非 JSON")) + return + end + local errcode = tonumber(data.errcode or data.errCode) + if errcode and errcode ~= 0 then + cb(nil, Eink.userMessage(errcode, data.errmsg or data.errMsg)) + return + end + cb(data) + end +end + +---@param path string 以 /web 开头 +---@param query table +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +local function getWebAsync(path, query, cb) + local url = WEB .. path .. "?" .. Text.formEncode(query) + return Auth.webGetAsync(url, nil, webWire(url, cb)) +end + +---@param path string 以 /web 开头 +---@param body table 请求体,以 JSON 发出 +---@param referer string|nil 缺省用站点首页 +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +local function postWebAsync(path, body, referer, cb) + local url = WEB .. path + return Auth.webPostAsync(url, JSON.encode(body), referer and { headers = { Referer = referer } } or nil, + webWire(url, cb)) +end + +--- 书城搜索(App ``GET /store/search``)。回包书在 ``data[]``,每条 ``bookInfo``;补成 ``books[]`` 交给 mapper。 +---@param keyword string +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:searchAsync(keyword, cb) + return Eink.callAsync("GET", "/store/search", { + query = { + keyword = keyword, author = "", authorVids = "", categoryId = "", + count = 20, maxIdx = 0, type = 0, v = 2, outer = 0, fromBookId = "", + scope = 0, scene = 0, filterType = 0, filterField = "", queryUid = "", isQueryWord = 0, + }, + }, function(data, err) + if not data then + cb(nil, err) + return + end + if type(data.books) ~= "table" then + data.books = type(data.data) == "table" and data.data or {} + end + cb(data) + end) +end + +--- 书城榜单与分类目录:``data[]`` 分组,``categories[]`` 里 CategoryId / title / sublist(公开接口,无需登录)。 +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:storeCategoriesAsync(cb) + return getWebAsync("/web/categories", {}, cb) +end + +--- 榜单 / 分类下的书:``books[]`` 同搜索(bookInfo),一次 20 本,maxIndex 是偏移,hasMore=1 还有。 +---@param category_id string +---@param offset integer +---@param ranking boolean 榜单必须带 rank=1,分类带了反而是空 +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:storeBooksAsync(category_id, offset, ranking, cb) + local query = { maxIndex = offset, rank = ranking and 1 or nil } + return getWebAsync("/web/bookListInCategory/" .. Text.urlEncode(category_id), query, cb) +end + +--- 全量拉取书架(synckey=0 表示不做增量)。/shelf/sync 无分页参数、服务端一发全量。 +--- bookCount 含专辑、公众号等不在 books 里的条目,不能拿它卡这次同步。 +--- spill:回包超过 ShelfImport.LIMIT 时不解码,原文落盘交给网页端分批导入,cb 收到 nil + 说明。 +---@param cb fun(data: table|nil, err: string|nil) 原始 wire 数据 +---@param spill boolean|nil +---@param open_import boolean|nil 是否打开导入页(仅用户主动刷新) +---@return { cancel: fun() }|nil +function Client:shelfSyncAsync(cb, spill, open_import) + local ShelfImport = require("moonsource_weread.shelf_import") + -- 待导入快照保留到用户明确完成或丢弃;后台同步不重复弹导入页。 + if spill and ShelfImport.size() then + if open_import then + require("utils.extension").call("web.open_page", ShelfImport.PAGE, _("微信书架导入"), ShelfImport.TOO_LARGE) + end + return require("source.base").defer(cb, nil, ShelfImport.TOO_LARGE) + end + local Awake = require("utils.awake") + -- 大书架下载 + 落盘要几分钟,期间别让设备睡下去;回调或取消时放开。 + Awake.hold("wechat_shelf", true) + local handle = Eink.callAsync("GET", "/shelf/sync", { + query = { synckey = 0, teenmode = 0, album = 1, onlyBookid = 0, localBookCount = 0 }, + max_body = spill and ShelfImport.LIMIT or nil, + }, function(data, err, meta) + if meta and meta.oversize then + local ok, werr = ShelfImport.stash(data.body) + Awake.hold("wechat_shelf", false) + if ok and open_import then + require("utils.extension").call("web.open_page", ShelfImport.PAGE, _("微信书架导入"), ShelfImport.TOO_LARGE) + end + cb(nil, ok and ShelfImport.TOO_LARGE or werr) + return + end + Awake.hold("wechat_shelf", false) + cb(data, err) + end) + if not handle then + Awake.hold("wechat_shelf", false) + return nil + end + return { cancel = function() + Awake.hold("wechat_shelf", false) + handle.cancel() + end } +end + +--- 增量拉书架索引:自 synckey 以来删了哪些(removed)、变了哪些(bookIds,只要 id)、 +--- 分组与专辑变更(archive / albumRemoved)、服务端总数(bookCount)与新 synckey。 +--- onlyBookid=1 不带元数据,变更的书再用 shelfSyncBooksAsync 按 id 补。 +---@param synckey number 上次同步保存的游标 +---@param local_count integer 本地在架书数(服务端据此判断两边是否对得齐) +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:shelfSyncIdsAsync(synckey, local_count, cb) + return Eink.callAsync("GET", "/shelf/sync", { + query = { synckey = synckey, teenmode = 0, album = 1, onlyBookid = 1, localBookCount = local_count }, + }, cb) +end + +--- 按 id 补拉书架行(增量里变更的书):回包 { books, bookProgress, albums, emptyInfoIds }。 +---@param book_ids string[] +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:shelfSyncBooksAsync(book_ids, cb) + return Eink.callAsync("POST", "/shelf/syncbook", { + body = { bookIds = book_ids, albumIds = {} }, + }, cb) +end + +--- 加入微信读书书架。 +---@param bookId string +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:addToShelfAsync(bookId, cb) + return Eink.callAsync("POST", "/shelf/add", { body = { bookIds = { bookId }, albumIds = {} } }, cb) +end + +--- 从微信读书书架删除。 +---@param bookId string +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:removeFromShelfAsync(bookId, cb) + return Eink.callAsync("POST", "/shelf/delete", { + body = { bookIds = { bookId }, albumIds = {}, archiveIds = {} }, + }, cb) +end + +--- 写分组:同一 archiveId 带完整 bookIds 即整体替换成员;新分组的 archiveId 由客户端取秒级时间戳。 +---@param archive_id integer +---@param name string +---@param book_ids string[] +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:saveArchiveAsync(archive_id, name, book_ids, cb) + return Eink.callAsync("POST", "/shelf/archive", { + body = { albumIds = {}, archiveId = archive_id, bookIds = book_ids, name = name }, + }, cb) +end + +--- 拉取书籍详情(含书籍版本号)。 +---@param bookId string 微信读书 bookId,即 stable_id +---@param cb fun(data: table|nil, err: string|nil) 原始 wire 数据 +---@return { cancel: fun() }|nil +function Client:bookInfoAsync(bookId, cb) + return Eink.callAsync("GET", "/book/info", { + query = { bookId = bookId, myzy = 1, source = "reading", teenmode = 0 }, + }, cb) +end + +--- 拉取整本书的章节目录。 +---@param bookId string 微信读书 bookId,即 stable_id +---@param cb fun(data: table|nil, err: string|nil) 原始 wire 数据 +---@return { cancel: fun() }|nil +function Client:chapterInfosAsync(bookId, cb) + return Eink.callAsync("POST", "/book/chapterInfos", { + body = { bookIds = { bookId }, synckeys = { 0 }, teenmode = 0 }, + idempotent = true, + }, cb) +end + +--- 拉取云端阅读进度;带毫秒时间戳参数避开中间层缓存。 +---@param bookId string 微信读书 bookId,即 stable_id +---@param cb fun(data: table|nil, err: string|nil) 原始 wire 数据 +---@return { cancel: fun() }|nil +function Client:getProgressAsync(bookId, cb) + return Eink.callAsync("GET", "/book/getProgress", { + query = { bookId = bookId, t = os.time() * 1000 + math.random(0, 999) }, + }, cb) +end + +--- 上报阅读进度:App ``POST /book/read``,本地坐标,可带尚未上报的小时桶。不下载网页阅读页。 +---@param bookId string +---@param opts { progress: number, current_progress?: number, chapter_uid: string|number, chapter_idx?: number, chapter_offset?: number, chapter_fraction?: number, summary?: string, book_version?: integer, hours?: WechatAppHour[] } +---@param cb fun(data: table|nil, err: any, meta?: { permanent?: boolean }) +---@return { cancel: fun() } +function Client:putProgressAsync(bookId, opts, cb) + if not Eink.credentials() then + require("ui/uimanager"):nextTick(function() cb(nil, _("请先扫码登录微信读书墨水屏")) end) + return { cancel = function() end } + end + local cancelled, current = false, nil + local function bind(next_job) + if next_job then current = next_job end + end + bind(self:guestTokenAsync(function(token, err) + if cancelled then return end + if not token then + cb(nil, err) + return + end + local creds = Eink.credentials() + if not creds then + cb(nil, _("请先扫码登录微信读书墨水屏")) + return + end + local function percentOf(value) + return math.max(0, math.min(100, math.floor(tonumber(value) or 0))) + end + local current_raw = opts.current_progress + if current_raw == nil then current_raw = opts.progress end + local current = percentOf(current_raw) + local hours = type(opts.hours) == "table" and opts.hours or {} + local body = require("moonsource_weread.app").readBody({ + vid = creds.vid, + device_id = creds.device_id, + install_id = Eink.installId(), + guest_token = token, + book_id = bookId, + chapter_uid = tonumber(opts.chapter_uid) or 0, + chapter_idx = opts.chapter_idx or 0, + chapter_offset = opts.chapter_offset or 0, + chapter_progress = math.max(0, math.min(100, + math.floor((tonumber(opts.chapter_fraction) or 0) * 100 + 0.5))), + progress = percentOf(opts.progress), + current_progress = current, + summary = opts.summary, + book_version = opts.book_version, + hours = hours, + -- 一个小时以内走 /book/read。跨小时走批量,resend=0。 + resend = #hours > 1 and 0 or nil, + }) + local function done(data, push_err) + if cancelled then return end + if not data then return cb(nil, push_err) end + cb({ ok = true }) + end + if body.isResendReadingInfo ~= nil then + bind(self:reportBatchAsync({ body }, done)) + else + bind(self:reportAppReadAsync(body, done)) + end + end)) + return { cancel = function() + cancelled = true + if current and current.cancel then current.cancel() end + end } +end + +--- 标记读完。App 读到结尾走 ``POST /book/markstatus``,书架的 finishReading 从这里来。 +---@param bookId string +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:markFinishedAsync(bookId, cb) + return Eink.callAsync("POST", "/book/markstatus", { + body = { bookId = tostring(bookId), status = 4, finishInfo = 0, isCancel = 0, auto = 1 }, + }, cb) +end + +--- App 防重放签名用的 guest_token(``/feature`` 配置里的同名项),进程内缓存。 +---@type string|nil +local guest_token + +--- 离线批量签名用的 token(``GET /config?token=1``)。只留在进程里,-2054 作废。 +---@type string|nil +local read_trouble + +---@param cb fun(token: string|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:guestTokenAsync(cb) + if guest_token then + cb(guest_token) + return nil + end + return Eink.callAsync("GET", "/feature", { query = { synckey = 0 } }, function(data, err) + if not data then + cb(nil, err) + return + end + -- 万一拿不到就用空串签,由服务端决定收不收。 + local token = type(data.feature) == "table" and data.feature.guest_token + guest_token = type(token) == "string" and token or "" + if guest_token ~= "" then Eink.setGuestToken(guest_token) end + cb(guest_token) + end) +end + +--- 离线批量的外层 token。空串不缓存,下次再取。 +---@param cb fun(token: string|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:encryptTokenAsync(cb) + if read_trouble and read_trouble ~= "" then + cb(read_trouble) + return nil + end + return Eink.callAsync("GET", "/config", { query = { token = 1 } }, function(data, err) + local token = data and data.token + if type(token) ~= "string" or token == "" then + cb(nil, err or _("上报响应异常")) + return + end + read_trouble = token + cb(token) + end) +end + +--- 上报阅读时长(App ``/book/read``,按小时分桶,可补报离线时段)。 +--- 写请求不自动重放:续期后由调用方下一轮重推(未确认的行仍是脏行)。 +---@param body table 已签名的请求体 +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:reportAppReadAsync(body, cb) + return Eink.callAsync("POST", "/book/read", { body = body }, function(data, err) + if not data then + cb(nil, err) + return + end + if tonumber(data.succ) ~= 1 then + logger.warn("weread app report not accepted") + cb(nil, _("上报响应异常")) + return + end + cb(data) + end) +end + +--- 读取网页阅读器会话参数;仅用于维持网页端「在读」状态。 +---@param bookId string +---@param cb fun(state: { psvts: string, pclts: string|nil, token: string|nil }|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:readerStateAsync(bookId, cb) + local url = require("moonsource_weread.protocol").readerUrl(bookId) + return Auth.webGetAsync(url, { headers = { Referer = url } }, function(raw, err) + if not raw then + cb(nil, err) + return + end + local psvts = raw:match([["psvts"%s*:%s*"([^"]+)"]]) + if not psvts then + logger.warn("weread reader page without psvts", raw:sub(1, 120)) + cb(nil, "reader.psvts not found") + return + end + cb({ + psvts = psvts, + pclts = raw:match([["pclts"%s*:%s*"([^"]+)"]]), + token = raw:match([["token"%s*:%s*"([^"]+)"]]), + }) + end) +end + +--- 上报网页阅读状态;调用方固定传 ``rt=0``,阅读时长只由 App 小时桶上报。 +---@param body table 已签名的请求体 +---@param referer string +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:reportReadAsync(body, referer, cb) + return postWebAsync("/web/book/read", body, referer, function(data, err) + if not data then + cb(nil, err) + return + end + if not (data.succ == true or tonumber(data.succ) == 1 or data.synckey ~= nil) then + logger.warn("weread web presence not accepted") + cb(nil, _("上报响应异常")) + return + end + cb(data) + end) +end + +--- 离线上报(App ``POST /book/batchUploadProgress``)。 +--- books 是已经签过名的单本体。外层签名用 /config 的 token;-2054 丢掉 token 再签一次。 +---@param books table[] +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:reportBatchAsync(books, cb) + local cancelled, current = false, nil + local function bind(next_job) + if next_job then current = next_job end + end + local function attempt(n) + bind(self:encryptTokenAsync(function(token, err) + if cancelled then return end + if not token then + cb(nil, err) + return + end + local body = require("moonsource_weread.app").batchBody(books, token) + bind(Eink.callAsync("POST", "/book/batchUploadProgress", { body = body }, function(data, post_err, meta) + if cancelled then return end + if n == 1 and type(meta) == "table" and meta.errcode == -2054 then + read_trouble = nil + attempt(2) + return + end + if not data or tonumber(data.succ) ~= 1 then + logger.warn("weread app batch report not accepted") + cb(nil, post_err or _("上报响应异常")) + return + end + cb(data) + end)) + end)) + end + attempt(1) + return { cancel = function() + cancelled = true + if current and current.cancel then current.cancel() end + end } +end + +--- 拉取阅读统计明细(Eink ``/readdata/detail``)。 +---@param mode string|nil 统计口径,缺省 "monthly" +---@param base_time number|nil 基准时间戳(秒),大于 0 才带上 +---@param cb fun(data: table|nil, err: string|nil) 原始 wire 数据 +---@return { cancel: fun() }|nil +function Client:readStatsAsync(mode, base_time, cb) + local query = { mode = mode or "monthly" } + if base_time and base_time > 0 then + query.baseTime = base_time + end + return Eink.callAsync("GET", "/readdata/detail", { query = query }, cb) +end + +--- 单书阅读详情(Eink ``/book/readinfo``,``readDetail.data`` 为按日 ``{ readDate, readTime }``)。 +--- +--- 不能走 Web:``/web/book/readinfo`` 对部分书恒回 ``showDetail=0``、不给按日明细。 +---@param bookId string +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:readInfoAsync(bookId, cb) + return Eink.callAsync("GET", "/book/readinfo", { + query = { bookId = bookId, readingDetail = 1 }, + }, cb) +end + +--- 个人划线列表(Eink ``/book/bookmarklist``,回 ``updated`` + ``chapters``)。 +--- +--- 不能走 Web:Web 会话打 ``/web/book/bookmarklist`` 恒返回 ``{}``(无 errcode)。 +---@param bookId string +---@param cb fun(data: table|nil, err: any) +---@return { cancel: fun() }|nil +function Client:bookmarkListAsync(bookId, cb) + return Eink.callAsync("GET", "/book/bookmarklist", { + query = { bookId = bookId, synckey = 0 }, + }, cb) +end + +--- 本人在该书的想法与点评(含划线想法的 ``range``)。 +--- +--- Eink ``/review/list`` 会混入别的书的想法(实测按 range 挂进当前书造成串书), +--- 回包里 ``bookId`` 不是这本书的条目剔掉;totalCount 保持原值,全量判定仍按服务端口径。 +--- ``hasMore=1`` 时带回包 ``maxIdx`` 续拉并按 reviewId 去重;中途失败交回已拿到的部分(hasMore 仍为 1)。 +---@param bookId string +---@param cb fun(data: table|nil, err: any) +---@return { cancel: fun() }|nil +function Client:myReviewsAsync(bookId, cb) + local own, seen, first, job = {}, {}, nil, nil + local cancelled = false + local function fetch(max_idx, pages, legacy) + -- 部分书(含 CB_ 自传书)用 App 同款参数会被回 -2003;首页失败时改用社区通用的 listType=11 再试一次。 + local query = legacy and { + bookId = bookId, listType = 11, listMode = 0, mine = 1, synckey = 0, + } or { + bookId = bookId, + listType = 1, + listMode = 0, + mine = 1, + synckey = 0, + count = MY_REVIEWS_PAGE, + maxIdx = max_idx > 0 and max_idx or nil, + } + job = Eink.callAsync("GET", "/review/list", { query = query }, function(data, err) + if cancelled then return end + if type(data) ~= "table" or type(data.reviews) ~= "table" then + if not first and not legacy then + fetch(0, 1, true) + return + end + -- 翻页失败时交回已拿到的部分,hasMore 保持 1,全量判定不会误判 + if first then cb(first) else cb(data, err) end + return + end + first = first or data + local added = 0 + for _idx, entry in ipairs(data.reviews) do + local review = type(entry) == "table" and (entry.review or entry) or nil + local owner = type(review) == "table" and review.bookId + local id = type(review) == "table" and (review.reviewId or entry.reviewId) + if (owner == nil or tostring(owner) == bookId) and not (id and seen[id]) then + if id then seen[id] = true end + own[#own + 1] = entry + end + added = added + 1 + end + first.reviews, first.hasMore = own, data.hasMore + local next_idx = tonumber(data.maxIdx) + if tonumber(data.hasMore) == 1 and added > 0 and next_idx and next_idx ~= max_idx + and pages < MY_REVIEWS_MAX_PAGES then + fetch(next_idx, pages + 1) + return + end + cb(first) + end) + end + fetch(0, 1) + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 发表划线下想法。 +---@param body table +---@param cb fun(data: table|nil, err: any) +---@return { cancel: fun() }|nil +function Client:addReviewAsync(body, cb) + return Eink.callAsync("POST", "/review/add", { body = body }, cb) +end + +--- 修改划线下想法。 +---@param body table +---@param cb fun(data: table|nil, err: any) +---@return { cancel: fun() }|nil +function Client:editReviewAsync(body, cb) + return Eink.callAsync("POST", "/review/useredit", { body = body }, cb) +end + +--- 删除想法。 +---@param review_id string|number +---@param cb fun(data: table|nil, err: any) +---@return { cancel: fun() }|nil +function Client:deleteReviewAsync(review_id, cb) + return Eink.callAsync("POST", "/review/delete", { body = { reviewId = tostring(review_id) } }, cb) +end + +--- 更新划线样式和颜色。 +---@param body table +---@param cb fun(data: table|nil, err: any) +---@return { cancel: fun() }|nil +function Client:updateBookmarkAsync(body, cb) + return Eink.callAsync("POST", "/book/updateBookmark", { body = body }, cb) +end + +--- 删除划线。 +---@param bookmark_id string|number +---@param cb fun(data: table|nil, err: any) +---@return { cancel: fun() }|nil +function Client:removeBookmarkAsync(bookmark_id, cb) + return Eink.callAsync("POST", "/book/removeBookmark", { + body = { bookmarkIds = { tostring(bookmark_id) } }, + }, cb) +end + +--- 上传单条划线。 +---@param bookId string +---@param chapter_uid string|number +---@param body table +---@param cb fun(data: table|nil, err: any) +---@return { cancel: fun() }|nil +function Client:addBookmarkAsync(bookId, chapter_uid, body, cb) + return Eink.callAsync("POST", "/book/addBookmark", { body = body }, cb) +end + +--- 本章热门划线与段评锚点:``underlines[]`` 每条 ``{ range, count, type }``(type 0 = 只有段评)。 +---@param bookId string +---@param chapter_uid string|number +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:underlinesAsync(bookId, chapter_uid, cb) + return Eink.callAsync("GET", "/book/underlines", { + query = { bookId = bookId, chapterUid = chapter_uid }, + }, cb) +end + +--- 按 range 批量拉段评:``reviews[]`` 每条 ``{ range, totalCount, maxIdx, hasMore, pageReviews[] }``。 +--- 分页把上一页回包的 ``maxIdx`` 原样带回。 +---@param bookId string +---@param chapter_uid string|number +---@param reviews { range: string, maxIdx: integer, count: integer, synckey: integer }[] +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:readReviewsAsync(bookId, chapter_uid, reviews, cb) + return Eink.callAsync("POST", "/book/readreviews", { body = { + bookId = bookId, + chapterUid = tonumber(chapter_uid) or chapter_uid, + cht2sMode = "", + reviews = reviews, + } }, cb) +end + +--- 一条想法及其评论。commentsCount 是本页条数,commentsMaxIdx 用上一页回包续拉(首页 0)。 +--- likesCount 置 0:只要评论,不拉点赞用户列表。 +---@param review_id string +---@param max_idx integer +---@param count integer +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Client:reviewSingleAsync(review_id, max_idx, count, cb) + return Eink.callAsync("GET", "/review/single", { query = { + reviewId = tostring(review_id), + synckey = 0, + commentsCount = count, + commentsDirection = 0, + commentsMaxIdx = max_idx, + likesCount = 0, + } }, cb) +end + +return Client diff --git a/moonsource-weread.koplugin/moonsource_weread/context.lua b/moonsource-weread.koplugin/moonsource_weread/context.lua new file mode 100644 index 0000000..5bbb6db --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/context.lua @@ -0,0 +1,104 @@ +--[[-- +微信读书阅读上下文缓存:按章记住本地 reader 状态(psvts / pclts),以及书籍版本号。 + +App 进度与时长走 App ``POST /book/read``;Web 在读状态用独立的网页会话。 + +@module koplugin.book.moonsource_weread.context +--]] + +local Protocol = require("moonsource_weread.protocol") + +local Context = {} + +local READER_TTL = 15 * 60 + +---@class WechatReaderState +---@field psvts string +---@field pclts string +---@field at integer 生成时间 +---@field entered boolean|nil 本会话已发过进入阅读上报 + +---@type table +local readers = {} +---@type table +local sessions = {} +---@type table +local book_version_by_id = {} + +---@class WechatReportSession +---@field psvts string +---@field pclts string +---@field token string|nil +---@field built_at integer +---@field entered boolean|nil + +local function key(book_id, chapter_uid) + return tostring(book_id) .. "\31" .. tostring(chapter_uid) +end + +--- 该章未过期的 reader 状态,缺失或过期就地生成。 +--- psvts 模拟服务端出页时间,pclts 模拟稍后的页面初始化时间;两者在会话内固定:进入阅读与后续时长上报必须共用同一个 pc,每次现算会让服务端不认 rt。 +---@param book_id string +---@param chapter_uid string|number +---@return WechatReaderState +function Context.reader(book_id, chapter_uid) + local k = key(book_id, chapter_uid) + local state = readers[k] + local now = os.time() + if state and now - state.at < READER_TTL then return state end + state = { psvts = Protocol.encode(now - 1), pclts = Protocol.encode(now), at = now } + readers[k] = state + return state +end + +--- 获取网页阅读会话;真实 psvts / pclts / token 只用于在读心跳,不用于累计时长。 +---@param client WechatClient +---@param book_id string +---@param force boolean|nil +---@param cb fun(session: WechatReportSession|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Context.sessionAsync(client, book_id, force, cb) + local session = sessions[book_id] + if session and not force and os.time() - session.built_at < READER_TTL then + cb(session) + return nil + end + return client:readerStateAsync(book_id, function(state, err) + if not state then + cb(nil, err) + return + end + local now = os.time() + sessions[book_id] = { + psvts = state.psvts, + pclts = state.pclts or Protocol.encode(now), + token = state.token, + built_at = now, + } + cb(sessions[book_id]) + end) +end + +---@param book_id string +---@param version number|string|nil +function Context.rememberBookVersion(book_id, version) + version = tonumber(version) + if version then + book_version_by_id[book_id] = version + end +end + +---@param book_id string +---@return number|nil +function Context.bookVersion(book_id) + return book_version_by_id[book_id] +end + +--- 清空进程内缓存的 reader 状态与书籍版本号(换账号或登出后必须调)。 +function Context.clear() + readers = {} + sessions = {} + book_version_by_id = {} +end + +return Context diff --git a/moonsource-weread.koplugin/moonsource_weread/eink.lua b/moonsource-weread.koplugin/moonsource_weread/eink.lua new file mode 100644 index 0000000..45e1ae0 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/eink.lua @@ -0,0 +1,590 @@ +--[[-- +微信读书 App 协议(手机 App 10.2.2 身份)客户端 API:扫码登录、令牌续期与 ``i.weread.qq.com`` 请求。 + +协议移植自 weread-omni(profile.ts / device-ua.ts / auth/qrlogin.ts / auth/token.ts / api/mobile.ts): + GET /wxticket → 微信 qrconnect 取 uuid → 长轮询 long.open.weixin.qq.com 拿 wx_code + → POST /login(wx_code 换 accessToken/refreshToken);过期后 POST /login 带 refreshToken 续期。 +请求头固定为 ``vid`` / ``accessToken`` 加 App 版本头。vid/accessToken 同时就是网页会话 +(当 wr_vid/wr_skey Cookie 可用),直接落在这两个字段;``eink`` 字段只存 refresh_token 与 device_id。 +网络仅异步:Request.request。 + +@module koplugin.book.moonsource_weread.eink +--]] + +local JSON = require("json") +local logger = require("utils.log") +local Request = require("http.request") +local Header = require("http.request.header") +local Text = require("utils.text") +local App = require("moonsource_weread.app") +local sha256 = require("ffi/sha2").sha256 +local _ = require("l10n").get("moonsource_weread") + +local Eink = {} + +local API = "https://i.weread.qq.com" +local WX_APPID = "wxab9b71ad2b90ff34" +local WX_SCOPE = "snsapi_userinfo,snsapi_timeline,snsapi_friend" +local DEVICE_NAME = "Xiaomi" +local DEVICE_TYPE = 1 +local QR_DEADLINE = 5 * 60 +local QR_POLL_TIMEOUT = 65 + +-- 官方手机 App 10.2.2 的身份(抓包取得);/book/read 的防重放签名只有这个渠道会下发 guest_token。 +local VERSION_HEADERS = { + ["User-Agent"] = "WeRead/10.2.2 WRBrand/xiaomi Dalvik/2.1.0 (Linux; U; Android 17; 25128PNA1C Build/CP2A.260605.016)", + baseapi = "37", + appver = "10.2.2.10167650", + basever = "10.2.2.10167650", + osver = "17", + channelId = "12", +} + +---@class WechatEinkCredentials +---@field vid string +---@field access_token string +---@field refresh_token string +---@field device_id string + +--- wechat 源配置(会话字段与用户信息都在这里)。 +---@return table +function Eink.config() + return require("utils.settings").getSource("ext.weread") +end + +---@param patch table 合并进 wechat 源配置并落盘 +function Eink.save(patch) + local MoonSettings = require("utils.settings") + local c = MoonSettings.getSource("ext.weread") + for k, v in pairs(patch) do c[k] = v end + MoonSettings.saveSource("ext.weread", c) +end + +--- 令牌就是网页会话(wr_vid/wr_skey 当 Cookie 可用),只落一份;eink 表只放续期要的两项。 +---@param vid string +---@param access_token string +---@param refresh_token string +---@param device_id string +---@return boolean +local function saveSession(vid, access_token, refresh_token, device_id) + local current = Eink.config() + local function commit() + local eink = current.eink or {} + eink.refresh_token, eink.device_id = refresh_token, device_id + Eink.save({ + wr_vid = vid, + wr_skey = access_token, + user_id = vid, + user_name = current.wr_vid ~= vid and "" or current.user_name, + eink = eink, + }) + end + if current.wr_vid ~= vid then + return require("source.logout").replaceLibrary("ext.weread", commit) + end + commit() + return true +end + +---@param n integer +---@return string +local function digits(n) + local out = {} + for i = 1, n do out[i] = tostring(math.random(0, 9)) end + return table.concat(out) +end + +--- 设备 ID:App 的是 38 位数字串,首位非零。 +---@return string +function Eink.newDeviceId() + return tostring(math.random(1, 9)) .. digits(37) +end + +--- 已落盘设备 ID;没有就生成并落盘。重新登录沿用同一设备,避免在账号里堆设备。 +--- 墨水屏时代的 "eink…" 前缀 ID 配手机渠道,续期会被风控回 -2041,登录时换成数字 ID。 +---@return string +function Eink.deviceId() + local eink = Eink.config().eink or {} + if type(eink.device_id) == "string" and eink.device_id:match("^%d+$") then + return eink.device_id + end + eink.device_id = Eink.newDeviceId() + Eink.save({ eink = eink }) + return eink.device_id +end + +--- 已落盘安装 ID(App 上报时长要带);没有就生成并落盘。 +---@return string +function Eink.installId() + local eink = Eink.config().eink or {} + if type(eink.install_id) ~= "string" or eink.install_id == "" then + eink.install_id = "31" .. digits(26) + Eink.save({ eink = eink }) + end + return eink.install_id +end + +--- 登录与续期共用的签名:sha256(毫秒时间戳 .. deviceId .. random)。 +---@param timestamp number 毫秒 +---@param device_id string +---@param random integer +---@return string +function Eink.signature(timestamp, device_id, random) + return sha256(string.format("%.0f", timestamp) .. device_id .. tostring(random)) --[[@as string]] +end + +---@return number +local function nowMs() + return os.time() * 1000 + math.random(0, 999) +end + +---@return WechatEinkCredentials|nil +function Eink.credentials() + local c = Eink.config() + local eink = c.eink + if type(eink) ~= "table" or type(eink.refresh_token) ~= "string" or eink.refresh_token == "" + or type(c.wr_skey) ~= "string" or c.wr_skey == "" then + return nil + end + return { vid = c.wr_vid, access_token = c.wr_skey, refresh_token = eink.refresh_token, device_id = eink.device_id } +end + +---@return boolean +function Eink.hasSession() + return Eink.credentials() ~= nil +end + +--- 清除续期令牌,保留设备 ID;网页会话字段由 Auth.clearSession 负责。 +function Eink.clearSession() + Eink.save({ eink = { device_id = (Eink.config().eink or {}).device_id } }) +end + +---@param extra table|nil +---@return table +local function versionHeaders(extra) + return Header.merge(extra, VERSION_HEADERS) +end + +---@param raw string|nil +---@return table|nil +local function decode(raw) + if type(raw) ~= "string" or raw == "" then return nil end + local ok, data = pcall(require("utils.json").decode, raw) + if ok and type(data) == "table" then return data end + return nil +end + +---@param data table|nil +---@return number|nil +local function errCode(data) + if type(data) ~= "table" then return nil end + return tonumber(data.errCode or data.errcode) +end + +---@param data table|nil +---@return string +local function errMsg(data) + if type(data) ~= "table" then return "" end + return tostring(data.errMsg or data.errmsg or "") +end + +-- 官方 10.2.2 真正展示给用户的固定句(资源名 / 调用点): +-- -2030 reader_load_chapter_soldout,阅读页下架 +-- -2112 BookFragment toast +-- -2202/-2228 pay_buy_chapters_all_paid_already +-- -2204 pay_buy_sold_out_book +-- -2281 阅读器 refreshChapterPrice(购买接口另有「支付失败,书籍价格已更新,请重新购买」) +-- 没有固定句的业务码(-2024/-2025/-2063 等)官方进阅读错误页,正文是 reader_load_chapter_fail「加载失败」。 +-- -2223 与 HTTP 402 官方不进错误页,打开购买页,页标题是「试读结束」。 +local OFFICIAL_ERR = { + [-2030] = "本书已下架", + [-2112] = "余额不足", + [-2202] = "章节已经购买过,请勿重复购买", + [-2204] = "本书已下架,部分内容不再支持购买", + [-2228] = "章节已经购买过,请勿重复购买", + [-2281] = "章节价格已更新,请重新购买", +} + +--- 业务错误的用户可见句。服务端 errmsg 是说明而不是错误码数字时原样用。 +---@param code number|nil +---@param msg string|nil +---@param http number|nil +---@return string +function Eink.userMessage(code, msg, http) + if type(msg) ~= "string" then msg = "" end + if msg ~= "" and msg ~= tostring(code) and not msg:match("^%-?%d+$") then + return msg + end + local key = code and OFFICIAL_ERR[code] + if key then return _(key) end + if http == 402 or code == -2223 then return _("试读结束") end + if code ~= nil then return _("加载失败") end + if http then return "HTTP " .. tostring(http) end + return _("加载失败") +end + +--- POST /login 回包 → 凭据;缺令牌按失败。续期回包可不带 refreshToken,表示沿用旧的。 +---@param res table|nil +---@param err any +---@param old_refresh string|nil 续期时传入当前 refreshToken +---@return table|nil data, string|nil err +local function loginResult(res, err, old_refresh) + if err then return nil, tostring(err) end + local data = decode(res and res.body) + if data and data.refreshToken == nil then data.refreshToken = old_refresh end + if not res or not Request.ok(res.code) or not data + or type(data.accessToken) ~= "string" or data.accessToken == "" + or type(data.refreshToken) ~= "string" or data.refreshToken == "" then + return nil, _("登录失败") .. " " .. tostring(errCode(data) or (res and res.code)) .. " " .. errMsg(data) + end + return data +end + +---@param body table +---@param cb fun(res: table|nil, err: any) +---@return HttpJob +local function postLogin(body, cb) + return Request.request({ + url = API .. "/login", + method = "POST", + body = JSON.encode(body), + headers = versionHeaders({ ["Content-Type"] = "application/json; charset=UTF-8" }), + timeout = require("http.timeout").net(1), + }, cb) +end + +--- 申请二维码:/wxticket 取票据,再向微信开放平台换 uuid。 +---@param cb fun(info: { uid: string, qr_payload: string }|nil, err: string|nil) +---@return { cancel: fun() } +function Eink.beginQrLoginAsync(cb) + local cancelled, job = false, nil + job = Request.request({ + url = API .. "/wxticket?nonceStr=weread", + method = "GET", + headers = versionHeaders(), + timeout = require("http.timeout").net(1), + }, function(res, err) + if cancelled then return end + local ticket = not err and res and Request.ok(res.code) and decode(res.body) or nil + if not ticket or type(ticket.signature) ~= "string" or ticket.timeStamp == nil then + cb(nil, _("获取二维码票据失败")) + return + end + job = Request.request({ + url = "https://open.weixin.qq.com/connect/sdk/qrconnect?" .. Text.formEncode({ + appid = WX_APPID, + noncestr = "weread", + timestamp = tostring(ticket.timeStamp), + scope = WX_SCOPE, + signature = ticket.signature, + }), + method = "GET", + headers = { ["User-Agent"] = VERSION_HEADERS["User-Agent"] }, + timeout = require("http.timeout").net(1), + }, function(res2, err2) + if cancelled then return end + local qr = not err2 and res2 and Request.ok(res2.code) and decode(res2.body) or nil + if not qr or tonumber(qr.errcode) ~= 0 or type(qr.uuid) ~= "string" or qr.uuid == "" then + cb(nil, _("获取二维码失败")) + return + end + cb({ + uid = qr.uuid, + qr_payload = "https://open.weixin.qq.com/connect/confirm?uuid=" .. Text.urlEncode(qr.uuid), + }) + end) + end) + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 长轮询扫码状态:408 继续等、404 已扫码继续等、405 确认拿 wx_code、402/403 失败。 +---@param uuid string +---@param cb fun(info: { wx_code: string }|nil, err: string|nil, status: string) +---@return { cancel: fun() } +function Eink.waitQrLoginAsync(uuid, cb) + local cancelled, job, last = false, nil, nil + local deadline = os.time() + QR_DEADLINE + local function poll() + if cancelled then return end + local remaining = deadline - os.time() + if remaining <= 0 then + cb(nil, _("二维码已失效,请重新登录"), "error") + return + end + local query = { f = "json", uuid = uuid, last = last } + job = Request.request({ + url = "https://long.open.weixin.qq.com/connect/l/qrconnect?" .. Text.formEncode(query), + method = "GET", + headers = { ["User-Agent"] = "Mozilla/5.0" }, + timeout = math.min(QR_POLL_TIMEOUT, remaining), + }, function(res, err) + if cancelled then return end + if err then + if os.time() < deadline then + require("ui/uimanager"):scheduleIn(3, poll) + else + cb(nil, tostring(err), "error") + end + return + end + local data = res and Request.ok(res.code) and decode(res.body) or nil + local code = data and tonumber(data.wx_errcode) + if code == 405 and type(data.wx_code) == "string" and data.wx_code ~= "" then + cb({ wx_code = data.wx_code }, nil, "ok") + elseif code == 404 or code == 408 then + last = code + poll() + elseif code == 403 then + cb(nil, _("已在微信中拒绝登录"), "error") + else + cb(nil, _("二维码已失效,请重新登录"), "error") + end + end) + end + poll() + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- wx_code 换令牌并落盘。 +---@param info { wx_code: string } +---@param cb fun(user: { user_id: string, user_name: string }|nil, err: string|nil) +---@return HttpJob +function Eink.completeQrLoginAsync(info, cb) + local device_id = Eink.deviceId() + local timestamp, random = nowMs(), math.random(0, 999) + return postLogin({ + appFirstInstall = 1, + code = info.wx_code, + deviceId = device_id, + deviceName = DEVICE_NAME, + installId = Eink.installId(), + isAutoLogout = 0, + isFromQrcode = 1, + random = random, + signature = Eink.signature(timestamp, device_id, random), + timestamp = timestamp, + trackId = "", + deviceType = DEVICE_TYPE, + }, function(res, err) + local data, login_err = loginResult(res, err) + if not data then + cb(nil, login_err) + return + end + local vid = tostring(data.vid) + if not saveSession(vid, data.accessToken, data.refreshToken, device_id) then + cb(nil, _("准备本地同步失败")) + return + end + -- 可能换了账号:上一个账号的 entered 状态留着,新账号的时长会因缺「进入阅读」不计。 + require("moonsource_weread.context").clear() + logger.info("weread eink login ok", vid) + cb({ user_id = vid, user_name = "" }) + end) +end + +--- 在飞续期的等待者;同一种续期合并成一次 /login。 +---@type (fun(ok: boolean, err: string|nil, rejected: boolean|nil))[]|nil +local mint_waiters +--- 在飞这次带不带 wxToken。普通续期是 0;公众号授权是 1。 +local mint_wx = 0 +--- 普通续期在飞时来了公众号续期:等这次落盘后再打 wxToken=1,不能共用同一次 /login。 +---@type { ref: string, waiters: (fun(ok: boolean, err: string|nil, rejected: boolean|nil))[] }|nil +local mint_follow + +--- 是否有续期在飞(调用方据此排队而不是另起 / 走冷却)。 +---@return boolean +function Eink.refreshing() + return mint_waiters ~= nil +end + +--- App 防重放签名用的 guest_token(``/feature`` 配置同名项),落 cfg.eink.guest_token。 +---@param token string +function Eink.setGuestToken(token) + local eink = Eink.config().eink or {} + eink.guest_token = token + Eink.save({ eink = eink }) +end + +---@param creds WechatEinkCredentials +---@param cb fun(token: string) +local function withGuestToken(creds, cb) + local cached = (Eink.config().eink or {}).guest_token + if type(cached) == "string" and cached ~= "" then + cb(cached) + return + end + Request.request({ + url = API .. "/feature?synckey=0", + method = "GET", + headers = versionHeaders({ vid = creds.vid, accessToken = creds.access_token }), + timeout = require("http.timeout").net(1), + }, function(res, err) + local data = not err and res and Request.ok(res.code) and decode(res.body) or nil + local token = data and type(data.feature) == "table" and data.feature.guest_token + if type(token) == "string" and token ~= "" then + Eink.setGuestToken(token) + cb(token) + else + cb("") + end + end) +end + +--- 用 refreshToken 换新 accessToken 并落盘。 +--- 普通续期 wxToken=0。公众号授权过期时 App 对带 NeedWxToken 的接口再续一次,wxToken=1, +--- refCgi 是这次失败的地址。rejected 只在服务器明确拒绝(有回包且非 5xx)时为真。 +---@param cb fun(ok: boolean, err: string|nil, rejected: boolean|nil) +---@param opts { wxToken: integer|nil, refCgi: string|nil }|nil +function Eink.refreshAsync(cb, opts) + opts = opts or {} + local wx = opts.wxToken == 1 and 1 or 0 + local ref = type(opts.refCgi) == "string" and opts.refCgi or "" + if mint_waiters then + -- wxToken=1 在飞时,普通续期直接等这次结果。反过来不行:0 续不了公众号授权。 + if wx == 0 or mint_wx == 1 then + mint_waiters[#mint_waiters + 1] = cb + return + end + mint_follow = mint_follow or { ref = ref, waiters = {} } + mint_follow.ref = ref + mint_follow.waiters[#mint_follow.waiters + 1] = cb + return + end + local creds = Eink.credentials() + if not creds then + cb(false, _("请先扫码登录微信读书墨水屏")) + return + end + mint_waiters = { cb } + mint_wx = wx + local timestamp, random = nowMs(), math.random(0, 999) + -- App 续期的防重放签名要 guest_token;没缓存时取一次(拿不到就空串,由服务端决定)。 + withGuestToken(creds, function(guest_token) + postLogin({ + deviceId = creds.device_id, + deviceName = DEVICE_NAME, + inBackground = 0, + kickType = 1, + random = random, + refCgi = ref, + refreshToken = creds.refresh_token, + signature = App.sign({ + guest_token, creds.device_id, string.format("%.0f", timestamp), tostring(random), creds.refresh_token, + }), + timestamp = timestamp, + trackId = "", + wxToken = wx, + }, function(res, err) + local data, login_err = loginResult(res, err, creds.refresh_token) + if data then + if not saveSession(data.vid ~= nil and tostring(data.vid) or creds.vid, + data.accessToken, data.refreshToken, creds.device_id) then + data, login_err = nil, _("准备本地同步失败") + end + else + logger.warn("weread eink refresh failed", login_err) + end + local waiters = mint_waiters + local follow = mint_follow + mint_waiters, mint_follow = nil, nil + local rejected = data == nil and not err and res ~= nil and (tonumber(res.code) or 0) < 500 + for _idx, waiter in ipairs(waiters) do waiter(data ~= nil, login_err, rejected) end + if follow then Eink.refreshAsync(function(ok, follow_err, follow_rejected) + for _idx, waiter in ipairs(follow.waiters) do waiter(ok, follow_err, follow_rejected) end + end, { wxToken = 1, refCgi = follow.ref }) end + end) + end) +end + +---@class WechatEinkCallMeta +---@field status integer|nil HTTP 状态码 +---@field errcode number|nil 业务 errCode +---@field body table|nil 解码后的回包 + +--- 调 Eink API。401 / -2012 先续期:GET 或 ``opts.idempotent`` 重放一次; +--- 写请求只续期不重放(可能已落地,重放会重复写)。-2041 是人机验证,直接失败。 +---@param method string +---@param path string 以 / 开头,相对 i.weread.qq.com +---@param opts { query: table|nil, body: table|nil, idempotent: boolean|nil, raw: boolean|nil, max_body: integer|nil }|nil raw:2xx 非 JSON 回包(zip)原样交给 cb(data = res),错误仍按 JSON 解码;max_body:2xx 回包超过这个字节数不解码(解码后内存是原文数倍),原样交给 cb(data = res,meta.oversize = true) +---@param cb fun(data: table|nil, err: string|nil, meta: WechatEinkCallMeta) +---@return { cancel: fun() } +function Eink.callAsync(method, path, opts, cb) + opts = opts or {} + local replayable = opts.idempotent == true or method == "GET" + local cancelled, job = false, nil + local url = API .. path + if opts.query then url = url .. "?" .. Text.formEncode(opts.query) end + local function attempt(n) + local creds = Eink.credentials() + if not creds then + cb(nil, _("请先扫码登录微信读书墨水屏"), {}) + return + end + local headers = versionHeaders({ vid = creds.vid, accessToken = creds.access_token }) + if opts.body then headers["Content-Type"] = "application/json; charset=UTF-8" end + job = Request.request({ + url = url, + method = method, + body = opts.body and JSON.encode(opts.body) or nil, + headers = headers, + timeout = require("http.timeout").net(1), + }, function(res, err) + if cancelled then return end + if err then + cb(nil, tostring(err), {}) + return + end + if opts.raw and Request.ok(res.code) + and (res.body:sub(1, 2) == "PK" or res.body:sub(258, 262) == "ustar") then + cb(res, nil, { status = res.code }) + return + end + if opts.max_body and Request.ok(res.code) and #res.body > opts.max_body then + cb(res, nil, { status = res.code, oversize = true }) + return + end + local data = decode(res.body) + local code = errCode(data) + local meta = { status = res.code, errcode = code, body = data } + if n == 1 and (res.code == 401 or code == -2012) then + Eink.refreshAsync(function(ok, refresh_err) + if cancelled then return end + if ok and replayable then + attempt(2) + else + cb(nil, refresh_err or _("鉴权失败,请求结果未知"), meta) + end + end) + return + end + if code == -2041 then + cb(nil, _("打开手机上的微信读书 App,按它的提示完成人机验证。验证完回到月读,把这一章再打开一次。") .. " (-2041)", meta) + return + end + if not Request.ok(res.code) or (code ~= nil and code ~= 0) or not data then + local raw = errMsg(data) + local shown = Eink.userMessage(code, raw, res.code) + if shown ~= raw then + logger.warn("weread api", method, path, res.code, code, raw ~= "" and raw or nil) + end + cb(nil, shown, meta) + return + end + cb(data, nil, meta) + end) + end + attempt(1) + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +return Eink diff --git a/moonsource-weread.koplugin/moonsource_weread/extras.lua b/moonsource-weread.koplugin/moonsource_weread/extras.lua new file mode 100644 index 0000000..0771bc4 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/extras.lua @@ -0,0 +1,61 @@ +--[[-- +微信读书插件接入月读通用挂点:书架大快照导入页(web.routes)、订阅页公众号来源(desktop.account_feeds)、 +给本地书借段评(reader.paragraph_lender)。由 moon_source.lua 在加载时 require 一次;所有重模块都在回调里才加载。 + +@module moonsource_weread.extras +--]] + +local Ext = require("utils.extension") +local L = require("l10n").get("moonsource_weread") + +local PREFIX = "moonsource_weread." +local here = debug.getinfo(1, "S").source:match("^@(.+)/[^/]+$") or "." + +local function keepAwake() + require("utils.awake").poke() +end + +-- 导入要几分钟,设备自动休眠会停掉远程管理:每个请求算一次操作,导入结束请求停了自然恢复休眠计时。 +Ext.add("web.routes", { + name = "wechat_import", + dir = here .. "/web", + assets = { "wechat_import.html", "wechat_import.js" }, + l10n = PREFIX .. "l10n.web", + download = function(action) + keepAwake() + local ShelfImport = require(PREFIX .. "shelf_import") + if action ~= "file" or not ShelfImport.size() then return nil end + return { ctype = "application/json; charset=utf-8", filename = "wechat_shelf.json", path = ShelfImport.path() } + end, + handle = function(method, action, params, cb) + keepAwake() + local ShelfImport = require(PREFIX .. "shelf_import") + if method == "GET" and action == "status" then + cb(200, { size = ShelfImport.size() }) + elseif method == "POST" and action == "batch" then + local ids, err = ShelfImport.ingest(params) + if ids then cb(200, { ids = ids }) else cb(500, { error = err }) end + elseif method == "POST" and action == "commit" then + local hidden, err = ShelfImport.commit(params.ids or {}, tonumber(params.synckey)) + if hidden then cb(200, { hidden = hidden }) else cb(500, { error = err }) end + elseif method == "POST" and action == "discard" then + ShelfImport.discard() + cb(200, {}) + else + cb(404, { error = "unknown action" }) + end + end, +}) + +Ext.add("desktop.account_feeds", { + label = L("微信读书公众号"), + busy = L("正在读取微信读书书架…"), + login_hint = L("请先登录微信读书"), + empty = L("微信读书书架里没有公众号"), + mp = function() return require(PREFIX .. "mp") end, + client = function() return require(PREFIX .. "client") end, +}) + +Ext.add("reader.paragraph_lender", { id = "ext.weread", label = L("微信读书") }) + +return {} diff --git a/moonsource-weread.koplugin/moonsource_weread/l10n/en.lua b/moonsource-weread.koplugin/moonsource_weread/l10n/en.lua new file mode 100644 index 0000000..ac8dea7 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/l10n/en.lua @@ -0,0 +1,72 @@ +return { + ["完结"] = "Completed", + ["连载"] = "Ongoing", + ["已完结"] = "Completed", + ["上报响应异常"] = "Invalid upload response", + ["书籍详情为空"] = "Empty book details", + ["二维码已失效,请重新登录"] = "QR code expired, sign in again", + ["点这个提示上的「重新登录」。二维码出来以后,打开手机微信,点右上角「+」,再点「扫一扫」,对准屏幕上的二维码,在手机上点确认。"] = "Tap Sign in again on this message. When the QR code appears, open WeChat, tap + at the top right, tap Scan, point it at the code, and confirm on the phone.", + ["想法列表暂不可用,稍后重试"] = "Review list unavailable, will retry later", + ["划线上传后未在远端确认"] = "Uploaded highlight was not confirmed remotely", + ["划线上传失败"] = "Failed to upload highlight", + ["合并本地阅读时长"] = "Merge local reading time", + ["关闭时以云端为准;打开后每天取云端与本地中较大的,补上离线阅读。只影响月读里的统计"] = "Off: use the cloud numbers. On: take the larger of cloud and local for each day to include offline reading. Only affects stats in Moon Reader", + ["确定退出微信读书账号?"] = "Sign out of WeChat Read?", + ["已登录:%1"] = "Signed in: %1", + ["已续期"] = "Cookie renewed", + ["微信扫码登录"] = "WeChat QR login", + ["微信读书账号"] = "WeChat Read account", + ["本书已下架"] = "This book is no longer available", + ["余额不足"] = "Insufficient balance", + ["章节已经购买过,请勿重复购买"] = "These chapters are already purchased", + ["本书已下架,部分内容不再支持购买"] = "This book is no longer available. Some content can no longer be purchased", + ["章节价格已更新,请重新购买"] = "The chapter price has changed. Purchase again", + ["试读结束"] = "Trial ended", + ["想法上传失败"] = "Failed to upload note", + ["想法上传成功但缺少 reviewId"] = "Note upload succeeded without a reviewId", + ["按章书籍请打开章节后同步划线"] = "Open a chapter first to sync highlights", + ["无法定位划线范围"] = "Cannot locate highlight range", + ["无法开始登录"] = "Cannot start login", + ["无法确认划线上传结果"] = "Cannot confirm highlight upload", + ["无法获取章节坐标"] = "Cannot fetch chapter coordinates", + ["无法预检远端划线"] = "Cannot check remote highlights", + ["未登录 · 点此扫码"] = "Not signed in · tap to scan", + ["正在获取二维码…"] = "Fetching QR code…", + ["章节目录保存失败"] = "Failed to save chapter list", + ["章节缺少 uid"] = "Chapter missing uid", + ["第 %d 章"] = "Chapter %d", + ["续期会话"] = "Renew session", + ["续期失败"] = "Renew failed", + ["缺少书籍版本"] = "Missing book version", + ["缺少本地章节正文,无法定位划线"] = "Local chapter content is missing; cannot locate highlight", + ["缺少章节信息"] = "Missing chapter info", + ["返回非 JSON"] = "Non-JSON response", + ["无法定位阅读进度"] = "Cannot locate the reading position", + ["远端划线未确认,不能上传想法"] = "Remote highlight is unconfirmed; cannot upload note", + ["已在微信中拒绝登录"] = "Login declined in WeChat", + ["获取二维码票据失败"] = "Failed to get QR ticket", + ["请先扫码登录微信读书墨水屏"] = "Please scan to log in to WeRead e-ink first", + ["鉴权失败,请求结果未知"] = "Authentication failed; request result unknown", + ["打开手机上的微信读书 App,按它的提示完成人机验证。验证完回到月读,把这一章再打开一次。"] = "Open the WeRead app on your phone and finish the human verification it shows. Then come back to 月读 and open this chapter again.", + ["阅读时给有他人段评的句子画线,点按查看;需联网"] = "Underline sentences that other readers reviewed; tap to view. Requires network", + ["无法获取段评"] = "Failed to load reviews", + ["公众号授权已失效,请在微信读书 App 中打开任意公众号重新授权后再试"] = "WeRead official account access has expired. Open any official account in the WeRead app to re-authorize, then try again", + ["微信读书拒绝了请求,请稍后再试"] = "WeRead rejected the request, please try again later", + ["微信读书要求验证,请稍后再试"] = "WeRead asks for verification, please try again later", + ["这一章暂时无法加载:%s\n请稍后重试。"] = "This chapter can't be loaded right now: %s\nPlease try again later.", + ["没有可浏览的榜单"] = "No rankings available", + ["书架同步"] = "Shelf sync", + ["微信读书书架与在线阅读"] = "WeRead shelf and online reading", + ["搜索与发现"] = "Search and discover", + ["笔记同步"] = "Notes sync", + ["统计同步"] = "Statistics sync", + ["进度同步"] = "Progress sync", + ["书架数据太大,设备无法直接处理。已开启远程管理,请扫码在浏览器点「开始导入」完成同步。"] = "The shelf is too large for the device to process. Remote Management is on; scan the QR code and tap \"Start import\" in the browser to finish the sync.", + ["微信读书错误 "] = "WeChat Read error ", + ["微信读书公众号"] = "WeRead official accounts", + ["正在读取微信读书书架…"] = "Reading the WeRead shelf…", + ["请先登录微信读书"] = "Please log in to WeRead first", + ["微信读书书架里没有公众号"] = "No official accounts on the WeRead shelf", + ["微信读书"] = "WeRead", + ["请先扫码登录微信读书"] = "Scan QR to sign in to WeChat Read first", +} diff --git a/moonsource-weread.koplugin/moonsource_weread/l10n/web/en.lua b/moonsource-weread.koplugin/moonsource_weread/l10n/web/en.lua new file mode 100644 index 0000000..a7b5c1f --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/l10n/web/en.lua @@ -0,0 +1,21 @@ +-- 微信书架导入网页文案(经 web.routes 的 l10n 合入远程管理 /api/i18n)。 +return { + ["微信书架导入"] = "WeChat shelf import", + ["微信书架导入 - 远程管理"] = "WeChat shelf import - Remote", + ["微信书架分批导入"] = "WeChat shelf batch import", + ["书架太大、设备无法直接同步时,用浏览器解码后分批导入。"] = "When the shelf is too large for the device, decode it in the browser and import in batches.", + ["设备上没有待导入的书架数据。请先在设备上对微信读书执行一次全量同步(强制刷新书架)。"] = "Nothing to import. Run a full sync (force refresh) of WeChat Reading on the device first.", + ["待导入书架数据 %1 KB"] = "Shelf data to import: %1 KB", + ["开始导入"] = "Start import", + ["丢弃数据"] = "Discard", + ["正在下载…"] = "Downloading…", + ["正在下载 %1 / %2 KB"] = "Downloading %1 / %2 KB", + ["正在解析…"] = "Parsing…", + ["正在导入 %1 / %2"] = "Importing %1 / %2", + ["导入完成:%1 本,下架 %2 本"] = "Done: %1 books imported, %2 removed from shelf", + ["下载"] = "download", + ["收尾"] = "finalize", + ["第 %1 / %2 批上传"] = "uploading batch %1 / %2", + ["导入失败:%1"] = "Import failed: %1", + ["已丢弃"] = "Discarded", +} diff --git a/moonsource-weread.koplugin/moonsource_weread/l10n/web/zh_TW.lua b/moonsource-weread.koplugin/moonsource_weread/l10n/web/zh_TW.lua new file mode 100644 index 0000000..17658bc --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/l10n/web/zh_TW.lua @@ -0,0 +1,21 @@ +-- 微信書架匯入網頁文案(經 web.routes 的 l10n 合入遠端管理 /api/i18n)。 +return { + ["微信书架导入"] = "微信書架匯入", + ["微信书架导入 - 远程管理"] = "微信書架匯入 - 遠端管理", + ["微信书架分批导入"] = "微信書架分批匯入", + ["书架太大、设备无法直接同步时,用浏览器解码后分批导入。"] = "書架太大、裝置無法直接同步時,用瀏覽器解碼後分批匯入。", + ["设备上没有待导入的书架数据。请先在设备上对微信读书执行一次全量同步(强制刷新书架)。"] = "裝置上沒有待匯入的書架資料。請先在裝置上對微信讀書執行一次全量同步(強制重新整理書架)。", + ["待导入书架数据 %1 KB"] = "待匯入書架資料 %1 KB", + ["开始导入"] = "開始匯入", + ["丢弃数据"] = "丟棄資料", + ["正在下载…"] = "正在下載…", + ["正在下载 %1 / %2 KB"] = "正在下載 %1 / %2 KB", + ["正在解析…"] = "正在解析…", + ["正在导入 %1 / %2"] = "正在匯入 %1 / %2", + ["导入完成:%1 本,下架 %2 本"] = "匯入完成:%1 本,下架 %2 本", + ["下载"] = "下載", + ["收尾"] = "收尾", + ["第 %1 / %2 批上传"] = "第 %1 / %2 批上傳", + ["导入失败:%1"] = "匯入失敗:%1", + ["已丢弃"] = "已丟棄", +} diff --git a/moonsource-weread.koplugin/moonsource_weread/l10n/zh_TW.lua b/moonsource-weread.koplugin/moonsource_weread/l10n/zh_TW.lua new file mode 100644 index 0000000..0f4de8a --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/l10n/zh_TW.lua @@ -0,0 +1,72 @@ +return { + ["完结"] = "完結", + ["连载"] = "連載", + ["已完结"] = "已完結", + ["上报响应异常"] = "上報回應異常", + ["书籍详情为空"] = "書籍詳情為空", + ["二维码已失效,请重新登录"] = "二維碼已失效,請重新登入", + ["点这个提示上的「重新登录」。二维码出来以后,打开手机微信,点右上角「+」,再点「扫一扫」,对准屏幕上的二维码,在手机上点确认。"] = "點這個提示上的「重新登入」。二維碼出來以後,打開手機微信,點右上角「+」,再點「掃一掃」,對準螢幕上的二維碼,在手機上點確認。", + ["想法列表暂不可用,稍后重试"] = "想法列表暫不可用,稍後重試", + ["划线上传后未在远端确认"] = "劃線上傳後未在遠端確認", + ["划线上传失败"] = "劃線上傳失敗", + ["合并本地阅读时长"] = "合併本機閱讀時長", + ["关闭时以云端为准;打开后每天取云端与本地中较大的,补上离线阅读。只影响月读里的统计"] = "關閉時以雲端為準;開啟後每天取雲端與本機中較大的,補上離線閱讀。只影響月讀裡的統計", + ["确定退出微信读书账号?"] = "確定登出微信讀書帳號?", + ["已登录:%1"] = "已登入:%1", + ["已续期"] = "已續期", + ["微信扫码登录"] = "微信掃碼登入", + ["微信读书账号"] = "微信讀書帳號", + ["本书已下架"] = "本書已下架", + ["余额不足"] = "餘額不足", + ["章节已经购买过,请勿重复购买"] = "章節已經購買過,請勿重複購買", + ["本书已下架,部分内容不再支持购买"] = "本書已下架,部分內容不再支援購買", + ["章节价格已更新,请重新购买"] = "章節價格已更新,請重新購買", + ["试读结束"] = "試讀結束", + ["想法上传失败"] = "想法上傳失敗", + ["想法上传成功但缺少 reviewId"] = "想法上傳成功但缺少 reviewId", + ["按章书籍请打开章节后同步划线"] = "分章書籍請開啟章節後再同步劃線", + ["无法定位划线范围"] = "無法定位劃線範圍", + ["无法开始登录"] = "無法開始登入", + ["无法确认划线上传结果"] = "無法確認劃線上傳結果", + ["无法获取章节坐标"] = "無法取得章節座標", + ["无法预检远端划线"] = "無法預檢遠端劃線", + ["未登录 · 点此扫码"] = "未登入 · 點此掃碼", + ["正在获取二维码…"] = "正在取得二維碼…", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["章节缺少 uid"] = "章節缺少 uid", + ["第 %d 章"] = "第 %d 章", + ["续期会话"] = "續期工作階段", + ["续期失败"] = "續期失敗", + ["缺少书籍版本"] = "缺少書籍版本", + ["缺少本地章节正文,无法定位划线"] = "缺少本機章節正文,無法定位劃線", + ["缺少章节信息"] = "缺少章節資訊", + ["返回非 JSON"] = "回傳非 JSON", + ["无法定位阅读进度"] = "無法定位閱讀進度", + ["远端划线未确认,不能上传想法"] = "遠端劃線未確認,不能上傳想法", + ["已在微信中拒绝登录"] = "已在微信中拒絕登入", + ["获取二维码票据失败"] = "取得 QR 碼票據失敗", + ["请先扫码登录微信读书墨水屏"] = "請先掃碼登入微信讀書墨水屏", + ["鉴权失败,请求结果未知"] = "驗證失敗,請求結果未知", + ["打开手机上的微信读书 App,按它的提示完成人机验证。验证完回到月读,把这一章再打开一次。"] = "打開手機上的微信讀書 App,按它的提示完成人機驗證。驗證完回到月讀,把這一章再打開一次。", + ["阅读时给有他人段评的句子画线,点按查看;需联网"] = "閱讀時為有他人段評的句子畫線,點按查看;需連網", + ["无法获取段评"] = "無法取得段評", + ["公众号授权已失效,请在微信读书 App 中打开任意公众号重新授权后再试"] = "公眾號授權已失效,請在微信讀書 App 中打開任意公眾號重新授權後再試", + ["微信读书拒绝了请求,请稍后再试"] = "微信讀書拒絕了請求,請稍後再試", + ["微信读书要求验证,请稍后再试"] = "微信讀書要求驗證,請稍後再試", + ["这一章暂时无法加载:%s\n请稍后重试。"] = "這一章暫時無法載入:%s\n請稍後重試。", + ["没有可浏览的榜单"] = "沒有可瀏覽的榜單", + ["书架同步"] = "書架同步", + ["微信读书书架与在线阅读"] = "微信讀書書架與線上閱讀", + ["搜索与发现"] = "搜尋與發現", + ["笔记同步"] = "筆記同步", + ["统计同步"] = "統計同步", + ["进度同步"] = "進度同步", + ["书架数据太大,设备无法直接处理。已开启远程管理,请扫码在浏览器点「开始导入」完成同步。"] = "書架資料太大,裝置無法直接處理。已開啟遠端管理,請掃碼在瀏覽器點「開始匯入」完成同步。", + ["微信读书错误 "] = "微信讀書錯誤 ", + ["微信读书公众号"] = "微信讀書公眾號", + ["正在读取微信读书书架…"] = "正在讀取微信讀書書架…", + ["请先登录微信读书"] = "請先登入微信讀書", + ["微信读书书架里没有公众号"] = "微信讀書書架裡沒有公眾號", + ["微信读书"] = "微信讀書", + ["请先扫码登录微信读书"] = "請先掃碼登入微信讀書", +} diff --git a/moonsource-weread.koplugin/moonsource_weread/loadmeta.lua b/moonsource-weread.koplugin/moonsource_weread/loadmeta.lua new file mode 100644 index 0000000..95800de --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_weread._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-weread.koplugin/moonsource_weread/mapper.lua b/moonsource-weread.koplugin/moonsource_weread/mapper.lua new file mode 100644 index 0000000..9c74513 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/mapper.lua @@ -0,0 +1,445 @@ +--[[-- +微信 wire → 领域对象 + +@module koplugin.book.moonsource_weread.mapper +--]] + +local Progress = require("book.progress") +local Catalog = require("book.catalog") +local Text = require("utils.text") + +local Mapper = {} + +local SOURCE_ID = "ext.weread" + +--- 从嵌套 book/bookInfo 行解出书籍对象。 +---@param row table|nil +---@return table|nil +local function unwrapBookRow(row) + if type(row) ~= "table" then + return nil + end + local inner = row.book + if type(inner) == "table" and (inner.bookId or inner.title or inner.id) then + -- 进度与已读标记可能挂在外层,内层没有时补上。 + local patch = {} + if inner.progress == nil then patch.progress = row.progress end + if inner.finishReading == nil then patch.finishReading = row.finishReading end + return next(patch) and setmetatable(patch, { __index = inner }) or inner + end + if type(row.bookInfo) == "table" and (row.bookInfo.bookId or row.bookInfo.title) then + return row.bookInfo + end + return row +end + +--- 判断用户是否已读完(勿与作品完结 finished 混淆)。 +---@param row table|nil +---@return boolean +local function userFinished(row) + if type(row) ~= "table" then + return false + end + if row.finishReading == 1 or row.finishReading == true then + return true + end + if row.isFinishReading == 1 or row.isFinishReading == true then + return true + end + if row.hasReadTag == true or row.hasReadTag == 1 then + return true + end + -- 注意:微信作品完结 finished=1 不是用户读完 + return false +end + +--- 微信书籍行 → Book(及封面 URL)。 +---@param row table|nil +---@return Book|nil, string|nil cover_url +function Mapper.book(row) + local book = unwrapBookRow(row) + if type(book) ~= "table" then + return nil + end + local id = book.id or book.bookId or book.book_id + if id == nil then + return nil + end + id = tostring(id) + if id == "" then + return nil + end + local finished = userFinished(book) + local cover = type(book.cover) == "string" and book.cover ~= "" and book.cover or nil + -- 搜索 / 榜单给的是 s_ 缩略图(70x100),同路径 t7_ 是 285x406 + cover = cover and cover:gsub("/s_([^/]+)$", "/t7_%1") + local out = { + source_id = SOURCE_ID, stable_id = id, + title = book.title or book.bookName or book.name, + authors = book.authors or book.author, + percent = Progress.clampPercent( + book.percent or book.progress or book.progressPercent or book.readProgress, + finished + ), + category = book.category, + series = book.series, + cover = cover, + read_at = tonumber(book.readUpdateTime), + -- publishTime 形如 "2022-01-01 00:00:00";newRating 是千分制推荐值(955 = 95.5%)。 + -- 规范化(只留年月、10 分制一位小数)在 BookDB 入库时做。 + meta = { + publisher = book.publisher, + published = book.publishTime, + isbn = book.isbn, + language = book.language, + words = book.totalWords, + status = (book.finished == 1 or book.finished == true) and "完结" + or (book.finished == 0 or book.finished == false) and "连载" or nil, + rating = { score = (tonumber(book.newRating) or 0) / 100, by = "weread" }, + source = { + [SOURCE_ID] = { + pay_type = tonumber(book.payType), + book_type = tonumber(book.type), + ended = book.finished ~= nil and (book.finished == 1 or book.finished == true) or nil, + }, + }, + }, + } + local intro = book.intro or book.description or book.summary + if type(intro) == "string" and intro ~= "" then + out.intro = Text.stripHtml(intro) + end + return out, cover +end + +--- 书籍详情 wire → bookVersion(addBookmark 必填)。 +---@param wire table|nil +---@return number|nil +function Mapper.bookVersion(wire) + if type(wire) ~= "table" then + return nil + end + local book = wire.book or wire.data or wire + if type(book) ~= "table" then + return nil + end + return tonumber(book.version or book.bookVersion or wire.version or wire.bookVersion) +end + +--- 微信专辑 → Book(及封面 URL)。 +---@param album table +---@return Book|nil, string|nil +function Mapper.albumBook(album) + if type(album) ~= "table" then + return nil + end + local info = album.albumInfo or album + if type(info) ~= "table" then + return nil + end + local id = info.albumId or album.albumId + if not id then + return nil + end + local cover = type(info.cover) == "string" and info.cover ~= "" and info.cover or nil + local finished = info.finish == 1 or info.finish == true or info.finishStatus == "已完结" + return { + source_id = SOURCE_ID, stable_id = tostring(id), + title = info.name or info.title, + authors = info.authorName or info.author, + percent = Progress.clampPercent(0, finished), + cover = cover, + }, cover +end + +--- 把书架进度写回 Book。 +---@param book Book +---@param p table|nil +---@return Book +function Mapper.applyProgress(book, p) + if type(p) ~= "table" then + return book + end + local prog = tonumber(p.progress) + if prog then + book.percent = Progress.clampPercent(prog, false) + end + if p.finishReading == 1 or p.finishReading == true then + book.percent = 100 + end + -- bookProgress.updateTime:任一设备最近一次读这本书的时间(秒) + local at = tonumber(p.updateTime) + if at and at > (tonumber(book.read_at) or 0) then book.read_at = at end + return book +end + +--- 从书架提取 bookId→进度表。 +---@param shelf table|nil +---@return table +function Mapper.progressByBookId(shelf) + local map = {} + if type(shelf) ~= "table" or type(shelf.bookProgress) ~= "table" then + return map + end + for _idx, p in ipairs(shelf.bookProgress) do + local id = p and p.bookId + if id ~= nil then + map[tostring(id)] = p + end + end + return map +end + +--- 书架 archive(用户自建分组)→ bookId→分组名;一本书在多个分组时取第一个。 +---@param shelf table|nil +---@return table +function Mapper.groupByBookId(shelf) + local map = {} + for _idx, archive in ipairs(type(shelf) == "table" and type(shelf.archive) == "table" and shelf.archive or {}) do + if type(archive) == "table" and type(archive.name) == "string" and type(archive.bookIds) == "table" then + for _i, id in ipairs(archive.bookIds) do map[tostring(id)] = map[tostring(id)] or archive.name end + end + end + return map +end + +--- 合并书架各列表并按 bookId 去重。 +---@param into table[] +---@param seen table +---@param rows table|nil +local function appendShelfRows(into, seen, rows) + if type(rows) ~= "table" then + return + end + for _idx, row in ipairs(rows) do + local book = unwrapBookRow(row) + if type(book) == "table" then + local id = book.bookId or book.id or book.book_id + -- 公众号只走订阅导入(features.subscribe 直接读书架 wire),不进书库。 + if id ~= nil and tostring(id):sub(1, 7) ~= "MP_WXS_" then + id = tostring(id) + if not seen[id] then + seen[id] = true + into[#into + 1] = row + end + end + end + end +end + +--- 书架 wire → BookListResult。 +--- 分类口径见 source.category_setting:开 = 只用自定义分组,关 = 只用题材,不再混合。 +---@param shelf table +---@param on_cover fun(stable_id: string, url: string)|nil +---@return BookListResult +function Mapper.shelfList(shelf, on_cover) + local CategorySetting = require("source.category_setting") + local prog_map = Mapper.progressByBookId(shelf) + local groups = Mapper.groupByBookId(shelf) + local books = {} + local list, seen = {}, {} + appendShelfRows(list, seen, shelf.books) + appendShelfRows(list, seen, shelf.recentBooks) + appendShelfRows(list, seen, shelf.finishReadBooks) + appendShelfRows(list, seen, shelf.data and shelf.data.books) + for _idx, row in ipairs(list) do + local b, cover = Mapper.book(row) + if b then + Mapper.applyProgress(b, prog_map[b.stable_id]) + b.category = CategorySetting.apply(SOURCE_ID, b.category, groups[b.stable_id]) + b.category_authoritative = true + if cover and on_cover then + on_cover(b.stable_id, cover) + end + books[#books + 1] = b + end + end + for _idx, album in ipairs(shelf.albums or {}) do + local b, cover = Mapper.albumBook(album) + if b then + if cover and on_cover then + on_cover(b.stable_id, cover) + end + books[#books + 1] = b + end + end + return Catalog.listResult(books) +end + +--- 章名已以「第…章」开头(序号部分不含空白、不超过 8 个汉字)。 +---@param title string +---@return boolean +local function numbered(title) + local head = title:match("^第(.-)章") + return head ~= nil and #head <= 24 and not head:find("%s") +end + +--- 章节列表 wire → BookChapter[]。 +---@param data table +---@param bookId string +---@return BookChapter[]|nil, string|nil +function Mapper.chapters(data, bookId) + local records = data.data or data + if type(records) ~= "table" then + return nil, "empty" + end + if records.bookId or records.updated then + records = { records } + end + local entry + for _idx, rec in ipairs(records) do + if tostring(rec.bookId or "") == bookId or not entry then + entry = rec + if tostring(rec.bookId or "") == bookId then + break + end + end + end + if type(entry) ~= "table" then + return nil, "empty" + end + local chapters_raw = entry.updated or entry.chapterInfos or entry.chapters or {} + -- 网文(format=txt)的章名不带序号,微信客户端按 chapterIdx 拼「第 N 章」;出版书原样。 + -- 同一份 format 跟到每一章:拉正文时 bookType 用它,不再猜。 + local txt = type(entry.book) == "table" and entry.book.format == "txt" + local chapters = {} + for _idx, ch in ipairs(chapters_raw) do + local wc = tonumber(ch.wordCount or 0) or 0 + local title = tostring(ch.title or "") + if wc > 0 and title ~= "封面" then + local depth = math.max(1, math.floor(tonumber(ch.level) or 1)) + local anchors = {} + for _idx, anchor in ipairs(ch.anchors or {}) do + local anchor_title = tostring(anchor.title or "") + local anchor_depth = math.max(1, math.floor(tonumber(anchor.level) or (depth + 1))) + -- 微信给每章挂一个同名同层的自锚点(就是章首),不是章内小节; + -- 收下会让阅读目录一章出两行同名节点,只留真小节。 + if anchor_title ~= "" and not (anchor_title == title and anchor_depth <= depth) then + anchors[#anchors + 1] = { title = anchor_title, depth = anchor_depth } + end + end + local source_idx = ch.chapterIdx or ch.idx + local uid = ch.chapterUid or ch.uid + chapters[#chapters + 1] = { + depth = depth, + anchors = #anchors > 0 and anchors or nil, + source_idx = source_idx ~= nil and tostring(source_idx) or nil, + uid = uid ~= nil and tostring(uid) or nil, + title = title, + words = wc, + tar = type(ch.tar) == "string" and ch.tar ~= "" and ch.tar or nil, + format = txt and "txt" or nil, + } + end + end + table.sort(chapters, function(a, b) + return (tonumber(a.source_idx) or 0) < (tonumber(b.source_idx) or 0) + end) + for i, ch in ipairs(chapters) do + ch.idx = i + local number = "第" .. (ch.source_idx or tostring(i)) .. "章" + if ch.title == "" then + ch.title = number + elseif txt and not numbered(ch.title) then + ch.title = number .. " " .. ch.title + end + end + if #chapters == 0 then + return nil, "empty" + end + chapters[1].toc_version = require("moonsource_weread.toc").FORMAT_VERSION + return chapters +end + +---@class WechatSearchBook +---@field book_id string +---@field title string +---@field author string +---@field publisher string + +--- 搜索 wire → 书目(只留带 bookId 的书,公众号等其它条目没有 bookInfo)。 +---@param data table +---@return WechatSearchBook[] +function Mapper.searchBooks(data) + local out = {} + for _idx, entry in ipairs(data.books or {}) do + local info = entry.bookInfo + if type(info) == "table" and info.bookId then + out[#out + 1] = { + book_id = tostring(info.bookId), + title = info.title or "", + author = info.author or "", + publisher = info.publisher or "", + } + end + end + return out +end + +--- 搜索 wire → Book[](书城用;公众号等没有 bookInfo 的条目被 Mapper.book 滤掉)。 +---@param data table +---@return Book[] +function Mapper.searchList(data) + local out = {} + for _idx, entry in ipairs(data.books or {}) do + if type(entry.bookInfo) == "table" then + local book = Mapper.book(entry) + if book then out[#out + 1] = book end + end + end + return out +end + +--- 榜单 / 分类目录 wire → 精简树,原始 JSON 带大量封面字段,不留。 +--- 榜单是 ranklist=1 的项;分类是其余带子分类的项(讲书榜、有声榜等无子分类的不要)。 +---@param data table +---@return { rankings: { id: string, title: string }[], categories: { id: string, title: string, subs: { id: string, title: string }[] }[] } +function Mapper.storeTree(data) + local tree = { rankings = {}, categories = {} } + for _idx, group in ipairs(data.data or {}) do + for _idx2, row in ipairs(group.categories or {}) do + local id = row.CategoryId and tostring(row.CategoryId) + if id and type(row.title) == "string" then + if row.ranklist == 1 then + tree.rankings[#tree.rankings + 1] = { id = id, title = row.title } + elseif #(row.sublist or {}) > 0 then + local subs = {} + for _idx3, sub in ipairs(row.sublist) do + subs[#subs + 1] = { id = tostring(sub.CategoryId), title = sub.title } + end + tree.categories[#tree.categories + 1] = { id = id, title = row.title, subs = subs } + end + end + end + end + return tree +end + +--- 进度 wire → ProgressPosition(getProgress 的进度在 book 子对象里)。 +---@param data table +---@return ProgressPosition, string|nil chapter_uid +function Mapper.progress(data) + local root = type(data.data) == "table" and data.data or data + local node = unwrapBookRow(root) + if node == root and type(root.book) == "table" then node = root.book end + local finished = userFinished(node) or userFinished(root) + local chapter_idx = tonumber(node.chapter_idx or node.chapterIdx) + local offset = tonumber(node.chapterOffset) + local chapter_fraction = tonumber(node.chapter_fraction) + if chapter_fraction then chapter_fraction = Progress.clampFraction(chapter_fraction) end + local percent = tonumber(node.percent or node.progress or node.progressPercent or node.readingProgress) + local fraction = 0 + if percent and (percent > 0 or not chapter_idx) then + fraction = Progress.clampFraction(Progress.clampPercent(percent, finished) / 100) + end + local chapter_uid = node.chapter_uid or node.chapterUid + return { + fraction = fraction, + chapter_idx = chapter_idx, + chapter_fraction = chapter_fraction, + locator = node.locator, + extra = { chapter_offset = offset, summary = node.summary, book_version = node.bookVersion }, + }, chapter_uid +end + +return Mapper diff --git a/moonsource-weread.koplugin/moonsource_weread/mp.lua b/moonsource-weread.koplugin/moonsource_weread/mp.lua new file mode 100644 index 0000000..3186746 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/mp.lua @@ -0,0 +1,442 @@ +--[[-- +微信读书公众号(订阅页用):公众号列表、文章分页、文章页 → 正文。 + +列表走 App ``GET /mp/chapters``(一页 ``count`` 篇),正文走 ``/web/mp/content`` 的文章页 HTML, +普通图文取 ``#js_content``,图片 / 纯文字消息取脚本里的正文。 + +@module koplugin.book.moonsource_weread.mp +--]] + +local Auth = require("moonsource_weread.auth") +local Assets = require("moonsource_weread.assets") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_weread") + +local Mp = {} + +local WEB = "https://weread.qq.com" +--- 公众号 CDN 的宽度档位(URL 末段),640 够墨水屏看清,原图(0)动辄几 MB。 +local IMAGE_WIDTH = "640" +--- 公众号接口回 -2041 时的提示(订阅刷新据此弹窗,网页端作为源的错误显示)。 +Mp.AUTH_EXPIRED = "公众号授权已失效,请在微信读书 App 中打开任意公众号重新授权后再试" +--- 每页篇数(服务端实测最多回 20)。 +Mp.PAGE = 20 + +--- 是否公众号 bookId。 +---@param book_id string|nil +---@return boolean +function Mp.isMp(book_id) + return tostring(book_id or ""):sub(1, 7) == "MP_WXS_" +end + +--- 旧版本把书架上的公众号同步进了书库:撕掉这些 books 行(连同依附记录)。 +--- 公众号只属于订阅;书架映射(mapper.shelfList)已不再产出,这里只清历史遗留,幂等。 +---@param BookDB table book.books_db +---@return integer removed +function Mp.dropLegacyBooks(BookDB) + local n = 0 + for _idx, id in ipairs(BookDB.stableIdsBySource("ext.weread") or {}) do + if Mp.isMp(id) then + BookDB.remove("ext.weread", id) + n = n + 1 + end + end + return n +end + +--- 文章列表(新到旧)。App ``/mp/chapters`` 是 ``data[] = { reviewId, createTime, mpInfo }``; +--- 旧网页回包是 ``reviews[].subReviews[]``,两种都认。 +---@param data table +---@return { guid: string, title: string, time: integer }[] +function Mp.articles(data) + local out, seen = {}, {} + local function add(uid, time, title) + uid = tostring(uid or "") + if uid == "" or seen[uid] then return end + seen[uid] = true + time = tonumber(time) or 0 + if type(title) ~= "string" or title == "" then title = os.date("%Y-%m-%d", time) end + out[#out + 1] = { guid = uid, title = title, time = time } + end + local rows = type(data) == "table" and type(data.data) == "table" and data.data or nil + if rows and type(rows[1]) == "table" and rows[1].reviewId ~= nil then + for _idx, ch in ipairs(rows) do + if type(ch) == "table" then + local info = type(ch.mpInfo) == "table" and ch.mpInfo or {} + add(ch.reviewId, ch.createTime, info.title) + end + end + table.sort(out, function(a, b) return a.time > b.time end) + return out + end + for _g, group in ipairs(type(data) == "table" and type(data.reviews) == "table" and data.reviews or {}) do + for _s, sub in ipairs(type(group) == "table" and type(group.subReviews) == "table" and group.subReviews or {}) do + local review = type(sub) == "table" and (type(sub.review) == "table" and sub.review or sub) or {} + local info = type(review.mpInfo) == "table" and review.mpInfo or {} + add(review.reviewId or sub.reviewId, review.createTime or group.createTime, info.title) + end + end + table.sort(out, function(a, b) return a.time > b.time end) + return out +end + +--- 书架 wire 里的公众号 → ``{ id, title, group }``;group 取用户自建分组(archive)名。 +--- 公众号可能在 books 行里,也可能在 mp / mpBook / officialAccounts(mp 实测是 ``{ book = 单个对象 }``)。 +---@param shelf table +---@return { id: string, title: string, group: string }[] +function Mp.accounts(shelf) + shelf = type(shelf) == "table" and shelf or {} + local groups = require("moonsource_weread.mapper").groupByBookId(shelf) + local out, seen = {}, {} + local function add(rows) + if type(rows) ~= "table" then return end + if rows.book ~= nil then rows = rows.book end + if rows.bookId ~= nil then rows = { rows } end + for _idx, row in ipairs(rows) do + local book = type(row) == "table" and (type(row.bookInfo) == "table" and row.bookInfo + or type(row.book) == "table" and row.book or row) or {} + local id = tostring(book.bookId or "") + if Mp.isMp(id) and not seen[id] then + seen[id] = true + out[#out + 1] = { id = id, title = tostring(book.title or id), group = groups[id] or "" } + end + end + end + for _idx, wire in ipairs({ shelf, type(shelf.data) == "table" and shelf.data or {} }) do + for _i, key in ipairs({ "books", "mp", "mpBook", "officialAccounts" }) do add(wire[key]) end + end + return out +end + +--- 公众号图片:懒加载地址换成 src,宽度降到 640 档、去掉 webp 转码参数;超出上限的图去掉。 +--- 标签重建成只剩 src:原标签的固定宽高 / 内联样式在墨水屏上只会撑破版面。 +---@param html string +---@return string +local function rewriteImages(html) + return (html:gsub("]*>", function(tag) + local _q, src = tag:match('data%-src=(["\'])(.-)%1') + if not src then _q, src = tag:match('%ssrc=(["\'])(.-)%1') end + if not src or src == "" then return "" end + -- QQ 表情是透明占位图 + CSS 雪碧背景,下载下来只是空白:去掉,留 alt(如「[微笑]」) + if src:find("pic_blank.gif", 1, true) then + local _qa, alt = tag:match('%salt=(["\'])(.-)%1') + return alt or "" + end + src = src:gsub("&", "&") + if src:find("mmbiz.qpic.cn", 1, true) then + src = src:gsub("/0([%?#])", "/" .. IMAGE_WIDTH .. "%1"):gsub("/0$", "/" .. IMAGE_WIDTH) + :gsub("([%?&])tp=webp&?", "%1"):gsub("[%?&]$", "") + end + return '' + end)) +end + +--- 码点 → UTF-8(含 BMP 以外的 emoji)。 +---@param code integer +---@return string +local function utf8Char(code) + if code < 0x80 then return string.char(code) end + if code < 0x800 then return string.char(0xC0 + math.floor(code / 64), 0x80 + code % 64) end + if code < 0x10000 then + return string.char(0xE0 + math.floor(code / 4096), 0x80 + math.floor(code / 64) % 64, 0x80 + code % 64) + end + return string.char(0xF0 + math.floor(code / 0x40000), 0x80 + math.floor(code / 4096) % 64, + 0x80 + math.floor(code / 64) % 64, 0x80 + code % 64) +end + +local ESCAPES = { n = "\n", r = "", t = "\t" } + +--- 页面脚本里 ``key: '…'`` 的单引号 JS 字符串,解开 \xHH / \uXXXX / \n 等转义;没有返回 nil。 +---@param html string +---@param key string +---@return string|nil +local function jsString(html, key) + local _s, e = html:find(key .. "%s*:%s*'") + if not e then return nil end + local out, i = {}, e + 1 + while true do + local j = html:find("[\\']", i) + if not j then return nil end + out[#out + 1] = html:sub(i, j - 1) + if html:sub(j, j) == "'" then break end + local c = html:sub(j + 1, j + 1) + local hex = c == "x" and html:sub(j + 2, j + 3):match("^%x%x$") + local uni = c == "u" and html:sub(j + 2, j + 5):match("^%x%x%x%x$") + if hex then + out[#out + 1], i = string.char(tonumber(hex, 16)), j + 4 + elseif uni then + local code = tonumber(uni, 16) + -- emoji 在 JS 里是代理对「\uD83D\uDE00」:两半合成一个码点,分开编码会成非法 UTF-8(显示为空 / 乱码) + local low = code >= 0xD800 and code < 0xDC00 and html:sub(j + 6, j + 7) == "\\u" + and tonumber(html:sub(j + 8, j + 11):match("^%x%x%x%x$") or "", 16) + if low and low >= 0xDC00 and low < 0xE000 then + out[#out + 1], i = utf8Char(0x10000 + (code - 0xD800) * 0x400 + (low - 0xDC00)), j + 12 + else + out[#out + 1], i = utf8Char(code), j + 6 + end + else + out[#out + 1], i = ESCAPES[c] or c, j + 2 + end + end + return table.concat(out) +end + +--- 图片 / 纯文字消息(item_show_type 8、10)没有 ``#js_content``: +--- 正文在脚本里的 ``content_noencode``(纯文字或 HTML),图片在 ``picture_page_info_list`` 的 ``cdn_url``。 +---@param html string +---@return string|nil +local function scriptBody(html) + local text = jsString(html, "content_noencode") + local parts = {} + if text and not text:match("^%s*$") then + parts[1] = text:find("<", 1, true) and text or Text.textToBody(text) + end + local list = html:find("picture_page_info_list%s*:%s*%[") + if list then + local stop = html:find("}%s*%]", list) or #html + for url in html:sub(list, stop):gmatch("cdn_url%s*:%s*'([^']+)'") do + -- 地址是 JS 字符串:「\x26amp;」解成「&」(属性里正好是转义后的 &) + url = url:gsub("\\x(%x%x)", function(h) return string.char(tonumber(h, 16)) end) + parts[#parts + 1] = '

' + end + end + if #parts == 0 then return nil end + return table.concat(parts) +end + +--- 文章页 HTML → 正文片段:普通图文取 ``#js_content``,图片 / 纯文字消息取脚本里的正文与图片; +--- 去脚本、样式、svg,剥掉内联字号(字号交回阅读器设置)。 +---@param html string +---@return string|nil +function Mp.extractBody(html) + html = tostring(html or "") + -- 先按 id 定位再切片:页面前面几 MB 的脚本 / 样式不进后面的匹配与 gsub。 + local at = html:find('id="js_content"', 1, true) + local start = at and html:sub(math.max(1, at - 512), at):match(".*()]*>(.-)%s*]*>(.*)') + end + if not body or body:match("^%s*$") then body = scriptBody(html) end + if not body or body:match("^%s*$") then return nil end + body = body:gsub("", ""):gsub("", "") + :gsub("", ""):gsub("]*/>", "") + body = body:gsub("(%sstyle=)([\"'])(.-)%2", function(prefix, quote, css) + css = css:gsub("font%-size%s*:[^;]*;?", "") + if css:match("^%s*$") then return "" end + return prefix .. quote .. css .. quote + end) + -- emoji 一律去掉:KOReader 字体画不出(只会成方块)。旧版雪碧图空 span 直接删,正文里的码点交给 stripEmoji。 + body = body:gsub(']-class="emoji emoji%x+"[^>]*>%s*', "") + return Text.stripEmoji(rewriteImages(body)) +end + +--- 网页端 /web/login/renewal 回包头里的公众号凭据(x-wr-ticket / x-wrpa-0):缺了会被风控回 -2041 或「验证」页。 +--- 只在内存里留。网页续期之后仍是 -2041,说明微信侧授权过期:再按 App 的 NeedWxToken 续一次(wxToken=1)。 +local mp_headers = {} + +local function dropMpHeaders() + for key in pairs(mp_headers) do mp_headers[key] = nil end +end + +--- 网页凭据续过仍被拒:清掉旧头,用 wxToken=1 续登录,再拿一次网页头。失败回调 false。 +---@param url string 这次失败的地址,App 把它放进 refCgi +---@param cb fun(ok: boolean) +---@return { cancel: fun() }|nil +local function refreshWxAsync(url, cb) + dropMpHeaders() + local current + current = require("moonsource_weread.eink").refreshAsync(function(ok) + if not ok then + cb(false) + return + end + current = Mp.renewAsync(function() cb(true) end) + end, { wxToken = 1, refCgi = url }) + return { cancel = function() + if current and current.cancel then current.cancel() end + end } +end + +--- 续期公众号凭据并记下回包里的 ticket / wrpa 头;失败也回调(调用方照旧重试,由重试结果判生死)。 +---@param cb fun() +---@return { cancel: fun() }|nil +function Mp.renewAsync(cb) + return Auth.webPostAsync(WEB .. "/web/login/renewal", '{"rq":"%2Fweb%2Fbook%2Fread","ql":false}', + { skip_auth_retry = true }, function(_raw, _err, res) + for _idx, name in ipairs({ "x-wr-ticket", "x-wrpa-0" }) do + local value = Request.header(res, name) + if value and value ~= "" then mp_headers[name] = value end + end + cb() + end) +end + +--- 一页文章列表(App ``GET /mp/chapters``)。offset / 第三个回调都是篇数,满一页才继续翻。 +--- -2041 用 wxToken=1 续一次登录再拉;还是 -2041 就是公众号授权失效。 +---@param book_id string MP_WXS_ 开头 +---@param offset integer 已拉到的篇数 +---@param cb fun(items: table[]|nil, err: any, count: integer|nil) +---@return { cancel: fun() } +function Mp.fetchArticlesAsync(book_id, offset, cb) + local Eink = require("moonsource_weread.eink") + local query = { bookId = book_id, count = Mp.PAGE, offset = offset or 0 } + local ref = "https://i.weread.qq.com/mp/chapters?" .. Text.formEncode(query) + local cancelled, job = false, nil + local function go(stage) + job = Eink.callAsync("GET", "/mp/chapters", { query = query }, function(data, err, meta) + if cancelled then return end + if meta and tonumber(meta.errcode) == -2041 then + if stage == 0 then + job = refreshWxAsync(ref, function(ok) + if cancelled then return end + if not ok then + cb(nil, _(Mp.AUTH_EXPIRED)) + return + end + go(1) + end) + return + end + cb(nil, _(Mp.AUTH_EXPIRED)) + return + end + if type(data) ~= "table" then + cb(nil, err or _("返回非 JSON")) + return + end + local items = Mp.articles(data) + cb(items, nil, #items) + end) + end + go(0) + return { cancel = function() + cancelled = true + if job and job.cancel then job.cancel() end + end } +end + +--- 文章页遇「验证」页时的最多请求次数。 +Mp.VERIFY_TRIES = 3 + +--- 延迟执行(测试可替换)。 +---@param sec number +---@param fn fun() +function Mp.later(sec, fn) + require("ui/uimanager"):scheduleIn(sec, fn) +end + +--- 流式拉公众号文章页。 +---@param url string +---@param cb fun(raw: string|nil, err: any) +---@return { cancel: fun() } +local function mpStreamGet(url, cb) + local Auth = require("moonsource_weread.auth") + local cancelled, inner = false, nil + local function go(stage) + local headers = Auth.sessionHeaders({ + ["Accept"] = "text/html,application/xhtml+xml,*/*", + ["Referer"] = WEB .. "/", + }) + for k, v in pairs(mp_headers) do headers[k] = v end + local chunks = {} + inner = Request.stream({ + url = url, + headers = headers, + timeout = require("http.timeout").net(3), + }, { + on_data = function(chunk) chunks[#chunks + 1] = chunk end, + on_done = function(err) + if cancelled then return end + if err then return cb(nil, err) end + local raw = table.concat(chunks) + chunks = nil + -- -2041:先续网页头,还不行再 wxToken=1 + if raw:find("2041", 1, true) then + local ok, data = pcall(require("utils.json").decode, raw) + if ok and type(data) == "table" and tonumber(data.errcode or data.errCode) == -2041 then + if stage == 0 then + inner = Mp.renewAsync(function() if not cancelled then go(1) end end) + return + end + if stage == 1 then + inner = refreshWxAsync(url, function(wx_ok) + if cancelled then return end + if not wx_ok then + cb(nil, _(Mp.AUTH_EXPIRED)) + return + end + go(2) + end) + return + end + cb(nil, _(Mp.AUTH_EXPIRED)) + return + end + end + cb(raw) + end, + }) + end + go(0) + return { cancel = function() + cancelled = true + if inner and inner.cancel then inner:cancel() end + end } +end + +--- 一篇文章的正文片段:拉文章页、抽正文;images_dir 非 nil 时图片落地(不带会话 Cookie)。 +---@param review_id string +---@param images_dir string|nil +---@param cb fun(html: string|nil, err: any) +---@return { cancel: fun() } +function Mp.fetchContentAsync(review_id, images_dir, cb) + local cancelled, job, tries = false, nil, 0 + local fetch + fetch = function() + tries = tries + 1 + job = mpStreamGet(WEB .. "/web/mp/content?reviewId=" .. Text.urlEncode(tostring(review_id or "")), + function(raw, err) + if cancelled then return end + if not raw then + cb(nil, err or _("正文获取失败")) + return + end + local body = Mp.extractBody(raw) + -- 短时间连着拉文章页会返回「验证」反爬页:退避几秒再拉,最多 VERIFY_TRIES 次。 + local verify = not body and raw:find("%s*验证%s*") ~= nil + raw = nil + if verify and tries < Mp.VERIFY_TRIES then + local function retry() Mp.later(2 * tries, function() if not cancelled then fetch() end end) end + if tries == 1 then + job = Mp.renewAsync(retry) + else + job = nil + retry() + end + return + end + if not body then + cb(nil, verify and _("微信读书要求验证,请稍后再试") or _("正文解析失败")) + return + end + if not images_dir then + cb(body) + return + end + job = Assets.localizeArticleAsync(images_dir, body, function(localized) + if not cancelled then cb(localized) end + end) + end) + end + fetch() + return { cancel = function() + cancelled = true + if job and job.cancel then job:cancel() end + end } +end + +return Mp diff --git a/moonsource-weread.koplugin/moonsource_weread/note.png b/moonsource-weread.koplugin/moonsource_weread/note.png new file mode 100644 index 0000000..ebbd3df Binary files /dev/null and b/moonsource-weread.koplugin/moonsource_weread/note.png differ diff --git a/moonsource-weread.koplugin/moonsource_weread/notes.lua b/moonsource-weread.koplugin/moonsource_weread/notes.lua new file mode 100644 index 0000000..fe44ac2 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/notes.lua @@ -0,0 +1,822 @@ +--[[-- +微信读书划线/想法 ↔ KOReader 注解与 HTML 注入。 + +@module koplugin.book.moonsource_weread.notes +--]] + +local Text = require("utils.text") +local Annotations = require("book.annotations") +local Toc = require("moonsource_weread.toc") +local Normalize = require("book.note.normalize") + +local Notes = {} + +local COLOR_STYLE = { + blue = 1, + green = 2, + yellow = 3, + purple = 4, + orange = 5, + lightgray = 5, + gray = 5, + cyan = 1, + red = 5, + pink = 4, +} + +local LOCAL_COLOR = { + [1] = "blue", + [2] = "green", + [3] = "yellow", + [4] = "purple", + [5] = "orange", +} + +local WR_FIELDS = { + "wr_range", "wr_bookmark_id", "wr_review_id", "wr_review_only", + "wr_delete_review", "wr_update_review", "wr_update_bookmark", +} + +--- 阅读器注解条目(KOReader annotations + 微信扩展字段)。 +---@class WechatAnnotation +---@field pos0 string|nil +---@field pos1 string|nil +---@field page string|number|nil +---@field pageno number|nil +---@field text string|nil +---@field wr_bookmark_id string|number|nil +---@field wr_range string|nil +---@field wr_review_id string|number|nil +---@field wr_deleted boolean|nil +---@field chapter_idx number|nil +---@field datetime string|nil +---@field [any] any + +--- 删除墓碑:只留远端 id,等上行删掉远端后出列。 +---@param item table 被删的注解 +---@param bookmark_id string|number|nil +---@param review_id string|number|nil +---@return table +local function tombstone(item, bookmark_id, review_id) + return { + datetime = item.datetime or os.date("%Y-%m-%d %H:%M:%S"), + chapter_idx = item.chapter_idx, + wr_bookmark_id = bookmark_id, + wr_review_id = review_id, + wr_range = item.wr_range, + wr_deleted = true, + } +end + +--- 想法列表条目有的包一层 ``review``,有的直接是想法本身。 +---@param entry any +---@return table|nil +local function unwrapReview(entry) + local review = type(entry) == "table" and (entry.review or entry) or nil + return type(review) == "table" and review or nil +end + +---@param items table[]|nil +---@param total_pages integer|nil +---@return table[] +function Notes.cleanAnnotations(items, total_pages) + local out = {} + for _idx, item in ipairs(items or {}) do + if type(item) == "table" and item.wr_deleted + and (item.wr_bookmark_id or item.wr_review_id) then + out[#out + 1] = tombstone(item, item.wr_bookmark_id, item.wr_review_id) + elseif type(item) == "table" then + local placeholder = not item.page and not item.pageref and item.wr_range + local source = item + if placeholder then + source = {} + for k, v in pairs(item) do source[k] = v end + source.page = placeholder + end + local clean = Normalize.clean({ source }, total_pages)[1] + if clean then + if placeholder then clean.page = nil end + for _idx, field in ipairs(WR_FIELDS) do clean[field] = item[field] end + out[#out + 1] = clean + end + end + end + return (Normalize.unique(out)) +end + +---@param previous table[]|nil +---@param current table[] +---@return table[] +function Notes.prepareLocalAnnotations(previous, current) + local by_bookmark, by_review = {}, {} + for _idx, item in ipairs(current) do + if item.wr_bookmark_id then by_bookmark[tostring(item.wr_bookmark_id)] = item end + if item.wr_review_id then by_review[tostring(item.wr_review_id)] = item end + end + for _idx, old in ipairs(previous or {}) do + if type(old) == "table" and old.wr_deleted then + local keep_bookmark = old.wr_bookmark_id + and not by_bookmark[tostring(old.wr_bookmark_id)] + local keep_review = old.wr_review_id + and not by_review[tostring(old.wr_review_id)] + if keep_bookmark or keep_review then + current[#current + 1] = tombstone(old, + keep_bookmark and old.wr_bookmark_id or nil, + keep_review and old.wr_review_id or nil) + end + elseif type(old) == "table" then + local bookmark_id, review_id = old.wr_bookmark_id, old.wr_review_id + local current_item = bookmark_id + and by_bookmark[tostring(bookmark_id)] or nil + current_item = current_item or (review_id + and by_review[tostring(review_id)] or nil) + if current_item and (old.color ~= current_item.color + or old.drawer ~= current_item.drawer) then + current_item.wr_update_bookmark = true + end + if review_id and current_item and old.note and old.note ~= "" + and current_item.note and current_item.note ~= "" + and old.note ~= current_item.note then + current_item.wr_update_review = true + end + if review_id and current_item and old.note and old.note ~= "" + and (not current_item.note or current_item.note == "") then + current_item.wr_review_id = review_id + current_item.wr_delete_review = true + else + local delete_bookmark = bookmark_id + and not by_bookmark[tostring(bookmark_id)] + local delete_review = review_id + and not by_review[tostring(review_id)] + if delete_bookmark or delete_review then + current[#current + 1] = tombstone(old, + delete_bookmark and bookmark_id or nil, + delete_review and review_id or nil) + end + end + end + end + return current +end + +--- 是否为个人划线(bookmarklist ``updated`` 条目;排除 type=0 书签位)。 +---@param row table +---@return boolean +function Notes.isHighlightRow(row) + if type(row) ~= "table" then + return false + end + local kind = tonumber(row.type) + if kind == 0 then + return false + end + return tostring(row.range or "") ~= "" +end + +--- 微信划线 → 可在阅读器内显示的原生注解(按段落偏移直算 xpointer)。 +---@param document table|nil +---@param annotations table[] +---@param html_path string|nil 章节 HTML 路径 +---@param current table[]|nil 阅读器已有注解;同一远端 id 优先复用已验证的 xpointer +---@return table[] +function Notes.localizeAnnotations(document, annotations, html_path, current) + if type(annotations) ~= "table" then + return {} + end + ---@param item table + ---@return boolean + local function needsLocate(item) + if item.pos0 then return false end + local text = item.text + local range = item.wr_range + return (type(text) == "string" and text ~= "") + or (type(range) == "string" and range ~= "") + end + local unresolved = {} + for _idx, item in ipairs(annotations) do + if type(item) == "table" and needsLocate(item) then + unresolved[#unresolved + 1] = item + end + end + -- 没有待定位的划线就不必读整章 HTML;开书若再 apply 一次,已定位条目会走这条快路径。 + if #unresolved == 0 then + return annotations + end + local html + if type(html_path) == "string" and html_path ~= "" then + local f = io.open(html_path, "rb") + if f then + html = f:read("*a") + f:close() + end + end + if not html then + return annotations + end + -- rune 流只随 HTML 变,整章建一次给所有划线复用。 + local flow = Annotations.flow(html) + ---@type table + local positioned = {} + for _idx, item in ipairs(current or {}) do + if type(item) == "table" and item.wr_bookmark_id and item.pos0 and item.pos1 then + positioned[tostring(item.wr_bookmark_id)] = item + end + end + local located = Annotations.locateBatch(flow, unresolved) + local out = {} + for _idx, item in ipairs(annotations) do + local ann = item + if type(item) == "table" and not item.pos0 then + ---@type WechatAnnotation|nil + local saved = item.wr_bookmark_id and positioned[tostring(item.wr_bookmark_id)] or nil + local location = located[item] + if saved or location then + ann = {} + for k, v in pairs(item) do ann[k] = v end + -- 当前章节文本能唯一确定时以重算结果为准,避免错位坐标; + -- 只有仍然歧义时才保留同 bookmarkId 的既有原生位置。 + if location then + ann.pos0, ann.pos1, ann.page = location.pos0, location.pos1, location.pos0 + ann.pageno = nil + elseif saved then + ann.pos0, ann.pos1 = saved.pos0, saved.pos1 + ann.page, ann.pageno = saved.page or saved.pos0, saved.pageno + end + if not ann.pageno and document and type(document.getPageFromXPointer) == "function" then + local ok, pageno = pcall(document.getPageFromXPointer, document, ann.pos0) + if ok and pageno then + ann.pageno = pageno + end + end + end + end + if type(ann) == "table" then + out[#out + 1] = ann + end + end + return out +end + +---@param remote table[] +---@param local_items table[] +---@param paging boolean|nil +---@param authoritative boolean|nil +---@return table[] merged +---@return integer dropped 权威快照里远端已不存在的本地条目数 +---@return integer deduped 因 id / range / 坐标 / 内容键重复被折叠的条数 +function Notes.mergeAnnotations(remote, local_items, paging, authoritative) + local function rangeKey(item) + if type(item.text) ~= "string" or item.text == "" + or not item.wr_range or item.wr_range == "" then return nil end + return table.concat({ item.text, tostring(item.wr_range) }, "\31") + end + local function noteKey(item) + if type(item.text) ~= "string" or item.text == "" + or type(item.note) ~= "string" or item.note == "" then + return nil + end + return table.concat({ item.text, item.note }, "\31") + end + -- 本地新划线上传后确认没回来(超时、断网)就没有 id / range,下次拉取时只能靠坐标认出它就是远端那条。 + local function posKey(item) + if type(item.pos0) ~= "string" or type(item.pos1) ~= "string" then return nil end + return table.concat({ item.pos0, item.pos1 }, "\31") + end + local function samePosition(item, other) + if not other then return false end + local pos, other_pos = posKey(item), posKey(other) + if pos or other_pos then return pos ~= nil and pos == other_pos end + return item.page == other.page + end + ---@param item table + ---@param seen table + local function mark(item, seen) + if item.wr_bookmark_id then seen["bookmark:" .. tostring(item.wr_bookmark_id)] = item end + if item.wr_review_id then seen["review:" .. tostring(item.wr_review_id)] = item end + local range_key, note_key, pos_key = rangeKey(item), noteKey(item), posKey(item) + if range_key then seen["range:" .. range_key] = item end + if note_key then seen["note:" .. note_key] = item end + if pos_key then seen["pos:" .. pos_key] = item end + -- 没有 id / 原文的位置记录(纯书签或误写入的进度残片)只能靠坐标内容去重; + -- 漏掉这一层时,历史快照里的几千份拷贝会在每次开书合并时再翻倍。 + local content_key = Normalize.contentKey(item) + if content_key then seen["content:" .. content_key] = item end + end + ---@param item table + ---@param seen table + ---@return boolean + local function isDup(item, seen) + local range_key, note_key, pos_key = rangeKey(item), noteKey(item), posKey(item) + local content_key = Normalize.contentKey(item) + return (item.wr_bookmark_id and seen["bookmark:" .. tostring(item.wr_bookmark_id)] ~= nil) + or (item.wr_review_id and seen["review:" .. tostring(item.wr_review_id)] ~= nil) + or (range_key and samePosition(item, seen["range:" .. range_key])) + or (note_key and samePosition(item, seen["note:" .. note_key])) + or (not item.wr_bookmark_id and pos_key and seen["pos:" .. pos_key] ~= nil) + or (content_key and seen["content:" .. content_key] ~= nil) + or false + end + authoritative = authoritative == true + local merged, seen, dropped, deduped = {}, {}, 0, 0 + for _idx, item in ipairs(remote or {}) do + if type(item) == "table" + and Normalize.renderable(item, paging) then + -- 同文同 range 的多条远端划线是同一处(重复上传留下的),手机端也只显示一条。 + if isDup(item, seen) then + deduped = deduped + 1 + else + mark(item, seen) + merged[#merged + 1] = item + end + end + end + for _idx, item in ipairs(local_items or {}) do + if type(item) == "table" then + local duplicate = isDup(item, seen) + local deleted_remote = authoritative and not duplicate + and (item.wr_bookmark_id or item.wr_review_id) + if deleted_remote then + dropped = dropped + 1 + elseif duplicate then + deduped = deduped + 1 + elseif Normalize.renderable(item, paging) then + mark(item, seen) + merged[#merged + 1] = item + end + end + end + return merged, dropped, deduped +end + +--- bookmarklist 的 markText 可能是 base64。 +---@return string +function Notes.decodeMarkText(value) + local raw = tostring(value or "") + if raw == "" then + return "" + end + if raw:match("^[%w%+/]+=*$") and #raw % 4 == 0 then + local decoded = Text.base64Decode(raw) + if type(decoded) == "string" and decoded ~= "" and Text.isValidUtf8(decoded) then + return decoded + end + end + return raw +end + +---@param color string|nil +---@return integer +function Notes.colorStyle(color) + return COLOR_STYLE[color] or 5 +end + +---@return string|nil +function Notes.localColor(style) + return LOCAL_COLOR[tonumber(style)] +end + +--- ``/review/list/mine`` wire → 按 ``range`` 索引的划线想法。 +--- +--- 想法条目形如 ``{ review = { range, content, reviewId } }``;无 ``range`` 的是 +--- 整本书评或章节点评,不挂到划线上。 +---@param wire table|nil +---@return table +function Notes.reviewsByRange(wire) + local out = {} + if type(wire) ~= "table" then + return out + end + for _idx, entry in ipairs(wire.reviews or {}) do + local review = unwrapReview(entry) + if review then + local range = tostring(review.range or "") + local content = review.content + if range ~= "" and type(content) == "string" and content ~= "" then + out[range] = review + end + end + end + return out +end + +---@param wire table|nil +---@return table +function Notes.reviewIds(wire) + local out = {} + for _idx, entry in ipairs(type(wire) == "table" and wire.reviews or {}) do + local review = unwrapReview(entry) + local id = review and (review.reviewId or entry.reviewId) or nil + if id then out[tostring(id)] = true end + end + return out +end + +--- 用完整远端想法快照回填 reviewId;新增请求已成功但本地未确认时可避免重复提交。 +---@param annotations table[] +---@param wire table|nil +---@return table +function Notes.reconcileReviews(annotations, wire) + local by_id, by_key, by_semantic = {}, {}, {} + for _idx, entry in ipairs(type(wire) == "table" and wire.reviews or {}) do + local review = unwrapReview(entry) + if review then + local id = review.reviewId or entry.reviewId + if id then by_id[tostring(id)] = review end + local range = tostring(review.range or "") + local content = review.content + local abstract = review.abstract or review.contextAbstract + if range ~= "" and type(content) == "string" and type(abstract) == "string" then + local key = table.concat({ range, abstract, content }, "\31") + if by_key[key] == nil then by_key[key] = review else by_key[key] = false end + local semantic = table.concat({ abstract, content }, "\31") + if by_semantic[semantic] == nil then + by_semantic[semantic] = review + else + by_semantic[semantic] = false + end + end + end + end + local confirmed = {} + for _idx, item in ipairs(annotations or {}) do + if type(item) == "table" and not item.wr_deleted + and type(item.note) == "string" and item.note ~= "" then + local review = item.wr_review_id and by_id[tostring(item.wr_review_id)] or nil + if not review and not item.wr_review_id and item.wr_range and item.text then + review = by_key[table.concat({ + tostring(item.wr_range), item.text, item.note, + }, "\31")] + end + if not review and not item.wr_review_id and item.text then + review = by_semantic[table.concat({ item.text, item.note }, "\31")] + end + if review then + item.wr_review_id = review.reviewId + confirmed[item] = true + end + end + end + return confirmed +end + +---@param wire table|nil +---@param chapter_uid string|number +---@return table +function Notes.bookmarkIds(wire, chapter_uid) + local out = {} + for _idx, row in ipairs(type(wire) == "table" and wire.updated or {}) do + if type(row) == "table" + and tostring(row.chapterUid or row.chapter_uid or "") == tostring(chapter_uid) + and Notes.isHighlightRow(row) then + local id = row.bookmarkId or row.id + if id then out[tostring(id)] = true end + end + end + return out +end + +--- bookmarklist wire → 通用 KOReader 注解(``chapter_idx`` 用于按章分片落库)。 +---@param wire table +---@param chapter_uid string|nil 非 nil 时只返回该章 +---@param reviews table|nil ``/review/list/mine`` wire +---@param source_id string|nil +---@param stable_id string|nil +---@return table[] +function Notes.toAnnotations(wire, chapter_uid, reviews, source_id, stable_id) + local items = (type(wire) == "table" and wire.updated) or {} + --- 划线行与想法条目共用的注解骨架。 + --- bookmarklist 的 chapterIdx 是微信原始序号;本地目录过滤过封面和空章, + --- 只能按 uid 映射,映射不到就留空,不能把原始序号当本地章节号。 + --- page/pos0/pos1 留空:开章后由 localizeAnnotations 按 wr_range 补 + --- xpointer。数字占位会让 KOReader 误判整份注解为 mupdf 格式。 + local function skeleton(row, uid) + local idx = source_id and stable_id and Toc.index(source_id, stable_id, uid) or nil + local ts = tonumber(row.createTime or row.updateTime) or os.time() + return { + datetime = os.date("%Y-%m-%d %H:%M:%S", ts), + datetime_updated = os.date("%Y-%m-%d %H:%M:%S", ts), + drawer = "lighten", + color = Notes.localColor(row.colorStyle), + chapter = row.chapterTitle or "", + chapter_idx = idx, + } + end + local review_by_range = Notes.reviewsByRange(reviews) + local matched_reviews = {} + local out = {} + for _idx, row in ipairs(items) do + if type(row) == "table" and Notes.isHighlightRow(row) then + local uid = tostring(row.chapterUid or row.chapter_uid or "") + if not chapter_uid or uid == tostring(chapter_uid) then + local range = tostring(row.range or "") + local review = review_by_range[range] + if review then matched_reviews[review] = true end + local ann = skeleton(row, uid) + ann.text = Notes.decodeMarkText(row.markText or row.bookmarkText or row.text or "") + ann.note = review and review.content or nil + ann.wr_range = range ~= "" and range or nil + ann.wr_bookmark_id = row.bookmarkId or row.id + ann.wr_review_id = review and review.reviewId or nil + out[#out + 1] = ann + end + end + end + -- 有想法不等于 bookmarklist 必有同 range 划线。微信允许直接发表选中文本想法; + -- 这种条目也必须映射为 KOReader 原生高亮+笔记,不能静默丢掉。 + for _idx, entry in ipairs(type(reviews) == "table" and reviews.reviews or {}) do + local review = unwrapReview(entry) + if review and not matched_reviews[review] then + local uid = tostring(review.chapterUid or review.chapter_uid or "") + local range = tostring(review.range or "") + local text = review.abstract or review.contextAbstract + local content = review.content + if range ~= "" and type(text) == "string" and text ~= "" + and type(content) == "string" and content ~= "" + and (not chapter_uid or uid == tostring(chapter_uid)) then + local ann = skeleton(review, uid) + ann.text = text + ann.note = content + ann.wr_range = range + ann.wr_review_id = review.reviewId or entry.reviewId + ann.wr_review_only = true + out[#out + 1] = ann + end + end + end + return out +end + +--- 想法列表没拿到时,拉回来的划线都不带想法:把本地快照里已有的想法接回去, +--- 否则远端快照覆盖本地、想法丢失,下一轮上行还会把它当成「用户删了想法」去删云端。 +---@param annotations table[] toAnnotations 的结果(就地改) +---@param local_items table[] 本地快照里的条目 +---@return table[] +function Notes.keepLocalReviews(annotations, local_items) + local by_bookmark, known = {}, {} + for _idx, ann in ipairs(annotations) do + if ann.wr_bookmark_id then by_bookmark[tostring(ann.wr_bookmark_id)] = ann end + if ann.wr_review_id then known[tostring(ann.wr_review_id)] = true end + end + for _idx, old in ipairs(local_items) do + if type(old) == "table" and old.wr_review_id and not known[tostring(old.wr_review_id)] then + local ann = old.wr_bookmark_id and by_bookmark[tostring(old.wr_bookmark_id)] or nil + if ann then + ann.note, ann.wr_review_id = old.note, old.wr_review_id + elseif old.wr_review_only then + annotations[#annotations + 1] = old + end + end + end + return annotations +end + +---@param item table +---@return boolean +local function hasNote(item) + return type(item.note) == "string" and item.note ~= "" +end + +--- 上行前整理:KOReader 原生 note 对应微信想法,标 wr_review_only,不先制造一条远端 bookmark。 +--- 返回有没有要推的(删除、改样式、改想法、新划线、新想法)。 +---@param annotations table[] 就地改写 +---@return boolean +function Notes.preparePush(annotations) + local has_work = false + for _idx, item in ipairs(annotations) do + local note = hasNote(item) + if note and not item.wr_bookmark_id and not item.wr_review_id then + item.wr_review_only = true + end + if item.wr_deleted or item.wr_delete_review or item.wr_update_bookmark or item.wr_update_review + or (item.drawer and not item.wr_bookmark_id and not note) + or (note and not item.wr_review_id) then + has_work = true + end + end + return has_work +end + +--- 需要取章节坐标的条目:待传新划线,加上还没确认远端划线的待传想法。 +---@param annotations table[] +---@param confirmed table 本轮已在远端确认的条目 +---@return table[] +function Notes.rangeItems(annotations, confirmed) + local out = Notes.pushCandidates(annotations) + for _idx, item in ipairs(annotations) do + if hasNote(item) and not item.wr_review_id + and (item.wr_review_only or (item.wr_bookmark_id and not confirmed[item])) then + out[#out + 1] = item + end + end + return out +end + +--- 想法列表只取一页;只有确认是全量时,“不在列表里”才等于“云端已删”。 +---@param reviews table|nil +---@return boolean +function Notes.reviewsComplete(reviews) + if type(reviews) ~= "table" then return false end + local total_count = tonumber(reviews.totalCount) + return tonumber(reviews.hasMore or 0) ~= 1 + and (not total_count or total_count <= #(reviews.reviews or {})) +end + +--- 待上传的划线想法(划线已登记远端 id)。 +---@param annotations table[] +---@return table[] +function Notes.notePushCandidates(annotations) + local out = {} + for _idx, item in ipairs(annotations) do + if hasNote(item) + and ((item.wr_review_id and item.wr_update_review) + or (not item.wr_review_id + and (item.wr_bookmark_id or item.wr_review_only) + and type(item.wr_range) == "string" and item.wr_range ~= "")) then + out[#out + 1] = item + end + end + return out +end + +---@param annotations table[] +---@return table[] +function Notes.deleteCandidates(annotations) + local out = {} + for _idx, item in ipairs(annotations) do + if item.wr_deleted or item.wr_delete_review then + out[#out + 1] = item + end + end + return out +end + +---@param annotations table[] +---@return table[] +function Notes.bookmarkUpdateCandidates(annotations) + local out = {} + for _idx, item in ipairs(annotations) do + if not item.wr_deleted and item.wr_bookmark_id and item.wr_update_bookmark then + out[#out + 1] = item + end + end + return out +end + +---@param annotation table +---@return table +function Notes.toBookmarkUpdateBody(annotation) + return { + bookmarkId = tostring(annotation.wr_bookmark_id), + style = 1, + colorStyle = Notes.colorStyle(annotation.color), + } +end + +--- KOReader 注解 → ``/web/review/add`` 请求体。 +---@param book_id string +---@param chapter_uid string|number +---@param annotation table +---@return table|nil body +---@return string|nil err +function Notes.toReviewBody(book_id, chapter_uid, annotation) + local content = annotation.note + if type(content) ~= "string" or content == "" then + return nil, "empty note" + end + local range = annotation.wr_range + if type(range) ~= "string" or range == "" then + return nil, "missing range" + end + local abstract = annotation.text + if type(abstract) ~= "string" or abstract == "" then + return nil, "missing highlight text" + end + return { + bookId = tostring(book_id), + content = content, + type = 1, + range = range, + abstract = abstract, + chapterUid = tonumber(chapter_uid) or chapter_uid, + }, nil +end + +--- KOReader 注解 → ``/web/review/edit`` 请求体。 +---@param book_id string +---@param chapter_uid string|number +---@param annotation table +---@return table|nil body +---@return string|nil err +function Notes.toReviewEditBody(book_id, chapter_uid, annotation) + local review_id = annotation.wr_review_id + if type(review_id) ~= "string" and type(review_id) ~= "number" then + return nil, "missing review id" + end + local body, err = Notes.toReviewBody(book_id, chapter_uid, annotation) + if not body then return nil, err end + body.reviewId = tostring(review_id) + return body, nil +end + +--- 待上传的本地划线(跳过已登记远端 id)。 +---@param annotations table[] +---@return table[] +function Notes.pushCandidates(annotations) + local out = {} + for _idx, item in ipairs(annotations) do + if item.drawer and type(item.text) == "string" and item.text ~= "" and not hasNote(item) + and not item.wr_bookmark_id and not item.wr_review_id then + out[#out + 1] = item + end + end + return out +end + +--- 用 bookmarklist 的 canonical 字段回填本地注解。 +--- 已有 id 优先;无 id 时只接受 ``text + 当前 wire range`` 精确匹配,避免同文句串线。 +--- 按 range 找远端划线 id:只有想法的条目没记过 bookmarkId,删除时靠它连带删掉划线。 +---@param wire table|nil +---@param chapter_uid string|number +---@param range string +---@return string|number|nil +function Notes.bookmarkIdByRange(wire, chapter_uid, range) + for _idx, row in ipairs(type(wire) == "table" and wire.updated or {}) do + if type(row) == "table" + and tostring(row.chapterUid or row.chapter_uid or "") == tostring(chapter_uid) + and tostring(row.range or "") == range and Notes.isHighlightRow(row) then + return row.bookmarkId or row.id + end + end +end + +---@param annotations table[] +---@param wire table|nil +---@param chapter_uid string|number +---@return table confirmed +function Notes.reconcileBookmarks(annotations, wire, chapter_uid) + local by_id, by_key = {}, {} + for _idx, row in ipairs(type(wire) == "table" and wire.updated or {}) do + local uid = tostring(row.chapterUid or row.chapter_uid or "") + if uid == tostring(chapter_uid) and Notes.isHighlightRow(row) then + local id = row.bookmarkId or row.id + local range = tostring(row.range or "") + local text = Notes.decodeMarkText(row.markText or row.bookmarkText or row.text or "") + if id then by_id[tostring(id)] = row end + if text ~= "" and range ~= "" then + local key = text .. "\31" .. range + if by_key[key] == nil then + by_key[key] = row + else + by_key[key] = false + end + end + end + end + local confirmed = {} + for _idx, item in ipairs(annotations or {}) do + if type(item) == "table" then + local row = item.wr_bookmark_id and by_id[tostring(item.wr_bookmark_id)] or nil + if not row and not item.wr_bookmark_id and item.text and item.wr_range then + row = by_key[item.text .. "\31" .. tostring(item.wr_range)] + end + if row then + item.wr_bookmark_id = row.bookmarkId or row.id + item.wr_range = tostring(row.range) + confirmed[item] = true + end + end + end + return confirmed +end + +--- KOReader 注解 → addBookmark 请求体。 +---@param book_id string +---@param chapter_uid string|number +---@param chapter_idx integer +---@param book_version number +---@param annotation table +---@return table|nil body +---@return string|nil err +function Notes.toBookmarkBody(book_id, chapter_uid, chapter_idx, book_version, annotation) + local text = annotation.text + if type(text) ~= "string" or text == "" then + return nil, "empty highlight" + end + local range = annotation.wr_range + if type(range) ~= "string" or range == "" then + return nil, "无法定位划线范围" + end + return { + bookId = tostring(book_id), + chapterUid = tonumber(chapter_uid) or chapter_uid, + chapterIdx = chapter_idx, + bookVersion = book_version, + type = 1, + style = 1, + colorStyle = Notes.colorStyle(annotation.color), + range = range, + markText = text, + }, nil +end + +return Notes diff --git a/moonsource-weread.koplugin/moonsource_weread/notes_push.lua b/moonsource-weread.koplugin/moonsource_weread/notes_push.lua new file mode 100644 index 0000000..a86882b --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/notes_push.lua @@ -0,0 +1,413 @@ +--[[-- +微信读书单章注解上行:删除 → 预检 → 取坐标 → 提交划线 → 回查确认 → 同步样式 → 推想法。 + +全程串行,任何一步失败整轮失败(已成功的远端 id 已回填到注解上,下轮 preflight 认回)。 +注解条目就地改写(wr_* 字段、删除墓碑出列),由调用方落库。 + +@module koplugin.book.moonsource_weread.notes_push +--]] + +local logger = require("utils.log") +local Notes = require("moonsource_weread.notes") +local Annotations = require("book.annotations") +local Toc = require("moonsource_weread.toc") +local Position = require("moonsource_weread.progress") +local Context = require("moonsource_weread.context") +local Mapper = require("moonsource_weread.mapper") +local _ = require("l10n").get("moonsource_weread") + +---@class WechatNotesPush +---@field client WechatClient +---@field identity BookIdentity +---@field book_id string +---@field chapter_idx integer +---@field chapter_uid string +---@field local_html string|nil +---@field annotations table[] +---@field confirmed table 已在远端确认的条目 +---@field preflight_wire table|nil +---@field job { cancel: fun() }|nil 在途请求 +---@field cancelled boolean +---@field finished boolean +---@field cb fun(ok: boolean|nil, err: string|nil) +local Push = {} +Push.__index = Push + +local NotesPush = {} + +---@param ok boolean|nil +---@param err string|nil +function Push:finish(ok, err) + if self.cancelled or self.finished then return end + self.finished = true + self.cb(ok, err) +end + +---@param seen table +function Push:confirm(seen) + for item in pairs(seen) do self.confirmed[item] = true end +end + +--- 发一个请求:失败整轮失败,成功把回包交给 ok。 +---@param start fun(done: fun(wire: table|nil, err: string|nil)): { cancel: fun() }|nil +---@param fail_msg string|nil 回包没给错误时的提示 +---@param ok fun(wire: table) +function Push:call(start, fail_msg, ok) + self.seq = (self.seq or 0) + 1 + local seq = self.seq + local handle = start(function(wire, err) + self.job = nil + if self.cancelled then return end + if not wire then + self:finish(nil, err or fail_msg) + return + end + ok(wire) + end) + -- 回调同步触发时已发出下一个请求,不能用旧句柄覆盖它(同 http/mirror)。 + if self.seq == seq then self.job = handle end +end + +--- 逐个串行处理:step 完成后调 next 进下一个,全部完成调 done;step 失败不调 next 即中止。 +---@param items table[] +---@param step fun(item: table, next: fun()) +---@param done fun() +function Push:each(items, step, done) + local index = 0 + local function nextItem() + if self.cancelled then return end + index = index + 1 + local item = items[index] + if not item then + done() + return + end + step(item, nextItem) + end + nextItem() +end + +--- 删除墓碑推完即出列。 +---@param item table +function Push:forget(item) + if not item.wr_deleted then return end + for i = #self.annotations, 1, -1 do + if self.annotations[i] == item then + table.remove(self.annotations, i) + return + end + end +end + +--- 先提交本地删除(想法先于划线),再预检。 +function Push:deletes() + local client = self.client + self:each(Notes.deleteCandidates(self.annotations), function(item, next) + local function removeBookmark() + self:call(function(done) + return client:removeBookmarkAsync(item.wr_bookmark_id, done) + end, _("划线上传失败"), function() + item.wr_bookmark_id = nil + self:forget(item) + next() + end) + end + local function dropBookmark() + if not item.wr_deleted then + self:forget(item) + next() + elseif item.wr_bookmark_id then + removeBookmark() + elseif item.wr_range then + -- 只有想法的条目没记过划线 id;远端划线与想法同 range,删想法不会连带删它。 + self:call(function(done) + return client:bookmarkListAsync(self.book_id, done) + end, _("无法预检远端划线"), function(wire) + item.wr_bookmark_id = Notes.bookmarkIdByRange(wire, self.chapter_uid, item.wr_range) + if item.wr_bookmark_id then + removeBookmark() + else + self:forget(item) + next() + end + end) + else + self:forget(item) + next() + end + end + if not item.wr_review_id then + item.wr_delete_review = nil + dropBookmark() + return + end + self:call(function(done) + return client:deleteReviewAsync(item.wr_review_id, done) + end, _("想法上传失败"), function() + item.wr_review_id, item.wr_delete_review = nil, nil + dropBookmark() + end) + end, function() self:preflight() end) +end + +--- 拉远端划线与想法:清掉远端已不存在的 id,认回上轮已成功但本地未确认的条目。 +function Push:preflight() + self:call(function(done) + return self.client:bookmarkListAsync(self.book_id, done) + end, _("无法预检远端划线"), function(wire) + self.preflight_wire = wire + local bookmark_ids = Notes.bookmarkIds(wire, self.chapter_uid) + for _idx, item in ipairs(self.annotations) do + if not item.wr_deleted and item.wr_bookmark_id + and not bookmark_ids[tostring(item.wr_bookmark_id)] then + item.wr_bookmark_id = nil + end + end + self:confirm(Notes.reconcileBookmarks(self.annotations, wire, self.chapter_uid)) + -- 想法列表被服务端拒绝(如 -2003)不能拖死划线上传:按「只拿到一页」处理,保留已有 id。 + local job = self.client:myReviewsAsync(self.book_id, function(reviews) + self.job = nil + if self.cancelled then return end + if type(reviews) ~= "table" then + -- 没有远端想法清单就认不回上轮已成功的想法,新想法此轮不推(否则重复)。 + self.reviews_unknown = true + reviews = { reviews = {}, hasMore = 1 } + end + -- 只拿到一页时保留 id:误清会让 addReviewAsync 在云端重建重复想法。 + if Notes.reviewsComplete(reviews) then + local review_ids = Notes.reviewIds(reviews) + for _idx, item in ipairs(self.annotations) do + if not item.wr_deleted and item.wr_review_id + and not review_ids[tostring(item.wr_review_id)] then + item.wr_review_id = nil + end + end + end + Notes.reconcileReviews(self.annotations, reviews) + -- 远端 id 被清掉的想法要重新标 wr_review_only,否则既不定位也不推送。 + Notes.preparePush(self.annotations) + self:locate() + end) + if self.job == nil and not self.cancelled then self.job = job end + end) +end + +--- 需要坐标的条目取一次当前章节 range 原文,所有 wr_range 在首个写请求前算完。 +function Push:locate() + local range_items = Notes.rangeItems(self.annotations, self.confirmed) + if #range_items == 0 then + self:updates() + return + end + if not self.local_html then + self:finish(nil, _("缺少本地章节正文,无法定位划线")) + return + end + local toc = Toc.read(self.identity.source_id, self.identity.stable_id) + local chapter = toc and toc[self.chapter_idx] + if not chapter then + self:finish(nil, _("缺少章节信息")) + return + end + -- range 原文用开书下载时记住的那份(Position 缓存):每条划线都重拉整章包 + -- 既慢,重拉到的还可能与本地在读章节不是同一通道 / 版本,可见文本相同、 + -- 校验照样通过,但标签长度不同会让 range 整体漂移(手机端错位)。 + local fired = false + local job = Position.loadAsync(self.identity, chapter, function(range_source, format_or_err) + fired = true + self.job = nil + if self.cancelled then return end + if not range_source then + self:finish(nil, format_or_err or _("无法获取章节坐标")) + return + end + local wire = Annotations.rangeMapping(range_source, format_or_err) + local flow = Annotations.flow(self.local_html) + -- 定位不了的条目只跳过它自己:失败不落库,整章中止会让同一条每轮都卡住其余划线。 + for _idx, item in ipairs(range_items) do + local range, range_err = Annotations.toWireRange(wire, flow, item.text, item.pos0, item.pos1) + if range then + item.wr_range = range + else + logger.warn("wechat highlight range skipped", self.book_id, self.chapter_idx, range_err) + end + end + self:confirm(Notes.reconcileBookmarks(self.annotations, self.preflight_wire, self.chapter_uid)) + local candidates = {} + for _idx, item in ipairs(Notes.pushCandidates(self.annotations)) do + if item.wr_range then candidates[#candidates + 1] = item end + end + if #candidates == 0 then + self:updates() + return + end + -- 服务端若在正文中加入标记,后面的区间先提交不会推移前面的坐标。 + -- 正确性仍由 postflight 确认,不依赖这个顺序。 + table.sort(candidates, function(a, b) + return (tonumber(a.wr_range:match("^(%d+)")) or 0) > (tonumber(b.wr_range:match("^(%d+)")) or 0) + end) + self:withBookVersion(candidates) + end) + -- 缓存命中时回调已同步跑完并可能发出了下一个请求,不能用旧句柄覆盖它。 + if not fired then self.job = job end +end + +--- addBookmark 必须带书籍版本号;进程内没有就拉一次详情。 +---@param candidates table[] +function Push:withBookVersion(candidates) + local version = Context.bookVersion(self.book_id) + if version then + self:bookmarks(version, candidates) + return + end + self:call(function(done) + return self.client:bookInfoAsync(self.book_id, done) + end, nil, function(wire) + version = Mapper.bookVersion(wire) + if not version then + self:finish(nil, _("缺少书籍版本")) + return + end + Context.rememberBookVersion(self.book_id, version) + self:bookmarks(version, candidates) + end) +end + +--- 串行提交新划线,提交完回查一次确认 canonical id/range。 +---@param version number +---@param candidates table[] +function Push:bookmarks(version, candidates) + local source_idx = Toc.sourceIndex(self.identity.source_id, self.identity.stable_id, self.chapter_idx) + or self.chapter_idx + local submitted = {} + self:each(candidates, function(item, next) + local body, body_err = Notes.toBookmarkBody(self.book_id, self.chapter_uid, source_idx, version, item) + if not body then + self:finish(nil, body_err) + return + end + self:call(function(done) + return self.client:addBookmarkAsync(self.book_id, self.chapter_uid, body, done) + end, _("划线上传失败"), function(wire) + item.wr_range = body.range + item.wr_bookmark_id = wire.bookmarkId or wire.id + submitted[#submitted + 1] = item + next() + end) + end, function() self:postflight(submitted) end) +end + +---@param submitted table[] +function Push:postflight(submitted) + self:call(function(done) + return self.client:bookmarkListAsync(self.book_id, done) + end, _("无法确认划线上传结果"), function(wire) + self:confirm(Notes.reconcileBookmarks(self.annotations, wire, self.chapter_uid)) + for _idx, item in ipairs(submitted) do + if not item.wr_bookmark_id or not self.confirmed[item] then + self:finish(nil, _("划线上传后未在远端确认")) + return + end + end + self:updates() + end) +end + +--- 已确认的远端划线同步样式和颜色。 +function Push:updates() + local items = {} + for _idx, item in ipairs(Notes.bookmarkUpdateCandidates(self.annotations)) do + if self.confirmed[item] then items[#items + 1] = item end + end + self:each(items, function(item, next) + self:call(function(done) + return self.client:updateBookmarkAsync(Notes.toBookmarkUpdateBody(item), done) + end, _("划线上传失败"), function() + item.wr_update_bookmark = nil + next() + end) + end, function() self:reviews() end) +end + +--- 串行推想法:已有 reviewId 走 edit,否则 add。 +function Push:reviews() + local deferred = false + self:each(Notes.notePushCandidates(self.annotations), function(item, next) + if not item.wr_review_id and self.reviews_unknown then + deferred = true + next() + return + end + if not item.wr_review_id and not self.confirmed[item] and not item.wr_review_only then + self:finish(nil, _("远端划线未确认,不能上传想法")) + return + end + if item.wr_review_id then + local body, body_err = Notes.toReviewEditBody(self.book_id, self.chapter_uid, item) + if not body then + self:finish(nil, body_err) + return + end + self:call(function(done) + return self.client:editReviewAsync(body, done) + end, _("想法上传失败"), function() + item.wr_update_review = nil + next() + end) + return + end + local body, body_err = Notes.toReviewBody(self.book_id, self.chapter_uid, item) + if not body then + self:finish(nil, body_err) + return + end + self:call(function(done) + return self.client:addReviewAsync(body, done) + end, _("想法上传失败"), function(wire) + local review_id = wire.reviewId or (type(wire.data) == "table" and wire.data.reviewId) + if not review_id then + self:finish(nil, _("想法上传成功但缺少 reviewId")) + return + end + item.wr_review_id = review_id + next() + end) + end, function() + if deferred then + self:finish(nil, _("想法列表暂不可用,稍后重试")) + else + self:finish(true) + end + end) +end + +--- 推送一章注解。 +---@param client WechatClient +---@param identity BookIdentity 章会话身份(chapter_idx 必填) +---@param chapter_uid string +---@param local_html string|nil 本地章节正文;有新划线 / 新想法要定位时必需 +---@param annotations table[] 就地改写 +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return { cancel: fun() } +function NotesPush.run(client, identity, chapter_uid, local_html, annotations, cb) + local self = setmetatable({ + client = client, + identity = identity, + book_id = identity.stable_id, + chapter_idx = tonumber(identity.chapter_idx), + chapter_uid = chapter_uid, + local_html = local_html, + annotations = annotations, + confirmed = {}, + cancelled = false, + finished = false, + cb = cb, + }, Push) + self:deletes() + return { cancel = function() + self.cancelled = true + if self.job then self.job:cancel() end + end } +end + +return NotesPush diff --git a/moonsource-weread.koplugin/moonsource_weread/package.lua b/moonsource-weread.koplugin/moonsource_weread/package.lua new file mode 100644 index 0000000..52f9022 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/package.lua @@ -0,0 +1,329 @@ +--[[-- +微信读书 App 章节下载包(GET /book/chapterdownload)解包。 + +响应头 encryptKey 是 base64 的 AES-128-CBC(PKCS7) 密文,明文即 zip 的 ZipCrypto 口令。 +解密用的 key/iv 来自 vid:十进制字符串循环铺满 32 字节,逐字节过 REMAP 表,前 16 字节为 key、后 16 字节为 iv +(移植自官方 App libencrypt.so 的 nativeDecryptHeaderKey,抓包样本验证)。 + +@module koplugin.book.moonsource_weread.package +--]] + +local bit = require("bit") +local ffi = require("ffi") +local JSON = require("json") +local Aes = require("crypto.aes") +local Inflate = require("utils.inflate") +local Text = require("utils.text") + +local Package = {} + +local REMAP = Aes.from_hex( + "34ca55401db693c63130293532a7b811c2b516fa8bb124a4109004e908f83b8a" + .. "9c8c44f9bc5c69e2a1dad2d37589f71e2d5056d77253bf22fb200f012e45876e" + .. "6648f2e0cdfe67a943f49451cea54aee13268eccaa33145d0e39bbcf912b814d" + .. "ea99ec1a2c85c5d936744b18e1f13d9d419fb4170dd64cbedcaf972877f062ff" + .. "71c1c8278f6c68a89be6591c1b1209984e3f063700ba1f0a192fc9d5d057496f" + .. "fd25e4610c42cb96645fdbad60238d9a6dc3c45e3eb9926abd5b077f7695ed4f" + .. "ab847a80e778c7e5eb73836bfc38467d4765b352633a05d1efa3a6de9e3c02ae" + .. "b27ba0f6f32ac0ac86035a540bf582d47ee3dfb0d8dd21e87c88a2795870b715") + +--- 由 vid 与响应头 encryptKey 算出 zip 口令。 +---@param vid string +---@param encrypt_key string base64 +---@return string|nil password +---@return string|nil err +function Package.password(vid, encrypt_key) + if not vid:match("^%d+$") then return nil, "bad vid" end + local raw = vid:rep(math.ceil(32 / #vid)):sub(1, 32) + local kiv = raw:gsub(".", function(c) return string.char(REMAP:byte(c:byte() + 1)) end) + local ok, plain = pcall(Aes.cbc_decrypt, Text.base64Decode(encrypt_key), kiv:sub(1, 16), kiv:sub(17, 32)) + if not ok then return nil, "encryptKey decrypt failed" end + return plain +end + +local CRC = {} +for i = 0, 255 do + local c = i + for _bit = 1, 8 do + c = bit.band(c, 1) == 1 and bit.bxor(0xEDB88320, bit.rshift(c, 1)) or bit.rshift(c, 1) + end + CRC[i] = c +end + +local function crcUpdate(crc, byte) + return bit.bxor(CRC[bit.band(bit.bxor(crc, byte), 0xff)], bit.rshift(crc, 8)) +end + +--- 32 位乘法取低 32 位(LuaJIT 的 double 装不下 32×27 位乘积)。 +local function mul32(a, b) + local lo, hi = b % 65536, math.floor(b / 65536) + return (a * lo + (a * hi % 65536) * 65536) % 4294967296 +end + +--- 传统 ZipCrypto 解密:data 含开头 12 字节随机头。 +---@param data string +---@param password string +---@return string +local function zipDecrypt(data, password) + local k0, k1, k2 = 0x12345678, 0x23456789, 0x34567890 + local function update(c) + k0 = crcUpdate(k0, c) % 4294967296 + k1 = (mul32((k1 + bit.band(k0, 0xff)) % 4294967296, 134775813) + 1) % 4294967296 + k2 = crcUpdate(k2, bit.rshift(k1, 24)) % 4294967296 + end + for i = 1, #password do update(password:byte(i)) end + local size = math.max(0, #data - 12) + local out = ffi.new("uint8_t[?]", size) + for i = 1, #data do + local t = bit.bor(k2, 2) % 65536 + local c = bit.bxor(data:byte(i), bit.band(bit.rshift(t * bit.bxor(t, 1), 8), 0xff)) + update(c) + if i > 12 then out[i - 13] = c end + end + return ffi.string(out, size) +end + +local function u16(s, p) local a, b = s:byte(p, p + 1) return a + b * 256 end +local function u32(s, p) local a, b, c, d = s:byte(p, p + 3) return a + b * 256 + c * 65536 + d * 16777216 end + +--- 解压峰值增量(字节):正文分块与拼接各一份;密文切片、解密缓冲与解密字符串各一份最大压缩块。 +--- `data` 已在内存里,MemAvailable 已包含它;预检只问额外还要多少。 +--- 另留 64KB 给 inflate 输出缓冲;解析失败时沿用 3× 包长估计。 +---@param data string +---@return number +function Package.unzipNeed(data) + data = data or "" + local fallback = 3 * #data + local eocd + for p = #data - 21, math.max(1, #data - 65557), -1 do + if u32(data, p) == 0x06054b50 then eocd = p break end + end + if not eocd then return fallback end + local sum_un, max_c, p = 0, 0, u32(data, eocd + 16) + 1 + for _entry = 1, u16(data, eocd + 10) do + if u32(data, p) ~= 0x02014b50 then return fallback end + local csize, usize = u32(data, p + 20), u32(data, p + 24) + local nlen, elen, clen = u16(data, p + 28), u16(data, p + 30), u16(data, p + 32) + sum_un = sum_un + usize + if csize > max_c then max_c = csize end + p = p + 46 + nlen + elen + clen + end + return 2 * sum_un + 3 * max_c + 65536 +end + +--- 解开整个 zip(走中央目录,数据描述符模式也能用)。 +---@param data string +---@param password string|nil +---@return table|nil files 文件名 → 内容 +---@return string|nil err +function Package.unzip(data, password) + local eocd + for p = #data - 21, math.max(1, #data - 65557), -1 do + if u32(data, p) == 0x06054b50 then eocd = p break end + end + if not eocd then return nil, "zip: no end record" end + local files, p = {}, u32(data, eocd + 16) + 1 + for _entry = 1, u16(data, eocd + 10) do + if u32(data, p) ~= 0x02014b50 then return nil, "zip: bad central directory" end + local flags, method, csize = u16(data, p + 8), u16(data, p + 10), u32(data, p + 20) + local nlen, elen, clen, lho = u16(data, p + 28), u16(data, p + 30), u16(data, p + 32), u32(data, p + 42) + 1 + local name = data:sub(p + 46, p + 45 + nlen) + p = p + 46 + nlen + elen + clen + if u32(data, lho) ~= 0x04034b50 then return nil, "zip: bad local header" end + local start = lho + 30 + u16(data, lho + 26) + u16(data, lho + 28) + local body = data:sub(start, start + csize - 1) + if bit.band(flags, 1) == 1 then + if not password then return nil, "zip: password required" end + body = zipDecrypt(body, password) + end + if method == 8 then + local out, err = Inflate.raw(body) + if not out then return nil, "zip: " .. name .. " " .. tostring(err) end + body = out + elseif method ~= 0 then + return nil, "zip: unsupported method " .. method + end + files[name] = body + end + return files +end + +--- 整书 / 章包里的样式表。常见 ``Styles/stylesheets.css``,也有书只用 ``stylesheet.css``。 +---@param files table Package.unzip 的结果 +---@return string|nil css +function Package.pickStyle(files) + local css = files["Styles/stylesheets.css"] or files["Styles/stylesheet.css"] + if css then return css end + local names = {} + for name in pairs(files) do + if name:match("^Styles/[^/]+%.css$") then + names[#names + 1] = name + end + end + table.sort(names) + return names[1] and files[names[1]] or nil +end + +--- 官方 /book/chapterdownload 的 chapters 参数。 +--- 连续 uid 写成 a-b;缓存/批量时带上 0(整书样式)。第一批若从 1 起连续,合并成 0-n(如 0-5); +--- 其后是 0,a-b(如 0,6-10)。非数字 uid 退回 0,u1,u2,…。 +---@param uids (string|number)[] 本章批次的 chapterUid(不含 0) +---@return string +function Package.formatChaptersParam(uids) + uids = uids or {} + if #uids == 0 then return "0" end + local nums = {} + for i, u in ipairs(uids) do + local n = tonumber(u) + if not n then + local parts = { "0" } + for _idx, x in ipairs(uids) do parts[#parts + 1] = tostring(x) end + return table.concat(parts, ",") + end + nums[i] = n + end + local contiguous = true + for i = 2, #nums do + if nums[i] ~= nums[i - 1] + 1 then contiguous = false; break end + end + if contiguous then + local a, b = nums[1], nums[#nums] + if a == 1 then return "0-" .. tostring(b) end + if a == b then return "0," .. tostring(a) end + return "0," .. tostring(a) .. "-" .. tostring(b) + end + local parts = { "0" } + for _idx, n in ipairs(nums) do parts[#parts + 1] = tostring(n) end + return table.concat(parts, ",") +end + +--- 从已解包的 zip 按 uid 列表抽出各章正文(及可选样式)。 +---@param files table +---@param book_id string +---@param uids (string|number)[] +---@param book_type '"epub"'|'"txt"' +---@return table +---@return string|nil style +function Package.extractChapters(files, book_id, uids, book_type) + local out = {} + for _idx, uid in ipairs(uids) do + local key = tostring(uid) + if book_type == "txt" then + local text = Package.chapterZipText(files, book_id, uid) + if text then + out[key] = { text = text, format = "txt" } + else + out[key] = { err = "zip: chapter " .. key .. " not in package", format = "txt" } + end + else + local html, err = Package.chapterHtml(files, uid) + if html then + out[key] = { text = html, format = "html" } + else + out[key] = { err = err or ("package: chapter " .. key .. " not in package"), format = "html" } + end + end + end + return out, Package.pickStyle(files) +end + +--- 取某章的 xhtml:章节由主文件(标题 / 插图)加若干 _000N 续篇组成,续篇 body 依次并入主文件 body 末尾。 +---@param files table Package.unzip 的结果 +---@param uid string|number +---@return string|nil xhtml +---@return string|nil err +function Package.chapterHtml(files, uid) + local info = files["info.txt"] and JSON.decode(files["info.txt"]) + for _idx, chapter in ipairs(info and info.chapters or {}) do + if tostring(chapter.chapterUid) == tostring(uid) then + if type(chapter.files) ~= "table" or type(chapter.files[1]) ~= "string" then + return nil, "package: no HTML files for chapter " .. tostring(uid) + end + local html = files[chapter.files[1]] + if not html then return nil, "package: missing " .. tostring(chapter.files[1]) end + for i = 2, #chapter.files do + local part = files[chapter.files[i]] + local inner = part and part:match("]*>(.*)") + if not inner then return nil, "package: bad part " .. tostring(chapter.files[i]) end + local last = html:match(".*()") + if not last then return nil, "package: no body" end + html = html:sub(1, last - 1) .. inner .. html:sub(last) + end + return html + end + end + return nil, "package: chapter " .. tostring(uid) .. " not in package" +end + +--- 解开 ustar。只取普通文件。 +---@param data string +---@return { name: string, data: string }[]|nil +---@return string|nil err +local function untar(data) + if data:sub(258, 262) ~= "ustar" then return nil, "tar: not ustar" end + local entries, offset = {}, 1 + while offset + 511 <= #data do + local header = data:sub(offset, offset + 511) + if header:match("^%z+$") then break end + local name = (header:sub(1, 100):gsub("%z.*$", "")) + local size = tonumber((header:sub(125, 136):gsub("%z.*$", ""):gsub("%s", "")), 8) or 0 + local typeflag = header:sub(157, 157) + local body_start = offset + 512 + if name ~= "" and (typeflag == "0" or typeflag == "" or typeflag == "\0") and size > 0 then + entries[#entries + 1] = { name = name, data = data:sub(body_start, body_start + size - 1) } + end + offset = body_start + math.ceil(size / 512) * 512 + end + return entries +end + +--- TXT 章节包:条目名是 ``bookId_uid``,续篇是 ``bookId_uid_...``。info.txt 是目录,不是正文。 +---@param entries { name: string, data: string }[] +---@param book_id string +---@param uid string|number +---@return string|nil text +local function readTextEntries(entries, book_id, uid) + local prefix = book_id .. "_" .. tostring(uid) + local parts = {} + for _idx, entry in ipairs(entries) do + local name = entry.name:match("([^/]+)$") + if name ~= "info.txt" and (name == prefix or name:sub(1, #prefix + 1) == prefix .. "_") then + parts[#parts + 1] = entry + end + end + -- TAR 主文件是 bookId_uid;ZIP 主文件常见 bookId_uid_o。二者都排在 _000N 续篇前。 + local function rank(entry) + local name = entry.name:match("([^/]+)$") + if name == prefix or name == prefix .. "_o" then return "" end + return name:sub(#prefix + 2) + end + table.sort(parts, function(a, b) + local ra, rb = rank(a), rank(b) + if ra ~= rb then return ra < rb end + return a.name < b.name + end) + if #parts == 0 then return nil end + local chunks = {} + for i, entry in ipairs(parts) do + chunks[i] = Text.stripBom(entry.data) + end + return table.concat(chunks) +end + +function Package.chapterText(data, book_id, uid) + local entries, err = untar(data) + if not entries then return nil, err end + local text = readTextEntries(entries, book_id, uid) + if text then return text end + return nil, "tar: chapter " .. tostring(uid) .. " not in package" +end + +function Package.chapterZipText(files, book_id, uid) + local entries = {} + for name, data in pairs(files) do + entries[#entries + 1] = { name = name, data = data } + end + return readTextEntries(entries, book_id, uid) +end + +return Package diff --git a/moonsource-weread.koplugin/moonsource_weread/progress.lua b/moonsource-weread.koplugin/moonsource_weread/progress.lua new file mode 100644 index 0000000..8c43acb --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/progress.lua @@ -0,0 +1,192 @@ +--[[-- +微信进度坐标:chapterOffset 是章节原文的字符偏移,EPUB 含 HTML 标签,TXT 按纯文本计。 +原文随章节缓存,离线进度仍只保存本地 XPointer;联网推送时转换,不把页比例当成字符坐标。 + +localize 得到的字符比例只进 extra.chapter_char_fraction,**不写** ProgressPosition.chapter_fraction: +后者是阅读器章内页比例(DocumentToc),混进同一字段会让开书比对假冲突、静默跟云端、 +以及 locator 失效时把字符比当成页比例 gotoFraction —— 体感就是进度跳来跳去。 + +@module koplugin.book.moonsource_weread.progress +--]] + +local Annotations = require("book.annotations") +local JSON = require("json") +local Paths = require("utils.paths") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_weread") + +local Position = {} + +local function cachePath(book_id, idx) + return Paths.bookWorkDir(book_id, "ext.weread") .. "/" .. idx .. ".position.json" +end + +---@param book_id string +---@param chapter BookChapter +---@param source string +---@param format '"html"'|'"txt"' +---@return boolean|nil, string|nil +function Position.remember(book_id, chapter, source, format) + local path = cachePath(book_id, chapter.idx) + local ok, err = Paths.ensureDir(path:match("(.+)/[^/]+$")) + if not ok then return nil, err end + local f + f, err = io.open(path .. ".part", "wb") + if not f then return nil, err end + local written, write_err = f:write(JSON.encode({ uid = chapter.uid, source = source, format = format })) + local closed, close_err = f:close() + if not written or not closed then + os.remove(path .. ".part") + return nil, write_err or close_err + end + local renamed, rename_err = os.rename(path .. ".part", path) + if not renamed then os.remove(path .. ".part"); return nil, rename_err end + return true +end + +---@param identity BookIdentity +---@param chapter BookChapter +---@param cb fun(source: string|nil, format_or_error: string|nil) +---@return { cancel: fun() }|nil +function Position.loadAsync(identity, chapter, cb) + local f = io.open(cachePath(identity.stable_id, chapter.idx), "rb") + if f then + local raw = f:read("*a") + f:close() + local data = JSON.decode(raw) + if data.uid == chapter.uid then + cb(data.source, data.format) + return nil + end + end + return require("moonsource_weread.chapter").fetchHtmlAsync(identity.stable_id, chapter, + function(_html, err, source, format) + if not source then cb(nil, err); return end + local ok, cache_err = Position.remember(identity.stable_id, chapter, source, format) + if not ok then cb(nil, cache_err); return end + cb(source, format) + end) +end + +local function localHtml(identity, chapter, source, format) + local f = io.open(Paths.chapterPath(identity.stable_id, chapter.idx, identity.source_id), "rb") + if f then + local html = f:read("*a") + f:close() + return html + end + if format == "html" then return source end + return require("source.chapter").render({ + title = chapter.title, + html = "

" .. Text.xmlEscape(chapter.title or "") .. "

" .. Text.textToBody(source), + }) +end + +---@param identity BookIdentity +---@param chapter BookChapter +---@param pos ProgressPosition +---@param source string +---@param format '"html"'|'"txt"' +---@return boolean|nil, string|nil +function Position.localize(identity, chapter, pos, source, format) + local wire = Annotations.rangeMapping(source, format) + local flow = Annotations.flow(localHtml(identity, chapter, source, format)) + local locator, fraction = Annotations.fromWireOffset(wire, flow, pos.extra.chapter_offset) + if not locator then return nil, _("无法定位阅读进度") end + pos.locator = locator + pos.extra.chapter_char_fraction = fraction + -- 有精确定位就不填页比例字段;打开文档后由 Toc.chapterFraction 重算。 + pos.chapter_fraction = nil + return true +end + +--- 统计 UTF-8 rune 数(纯图章回退时按原文 HTML 长度比例换算偏移)。 +---@param str string +---@return integer +local function countRunes(str) + str = Text.stripBom(tostring(str or "")) + local count, i, len = 0, 1, #str + while i <= len do + local byte = str:byte(i) + i = i + (byte < 0x80 and 1 or byte < 0xe0 and 2 or byte < 0xf0 and 3 or 4) + count = count + 1 + end + return count +end + +--- 定位失败或没有 locator 时的章级坐标:优先章内页比例,其次同章旧偏移,否则章首。 +---@param wire WechatWireMapping +---@param chapter BookChapter +---@param pos ProgressPosition +---@param source string +---@return integer offset +---@return string summary +---@return number fraction +local function fallbackPosition(wire, chapter, pos, source) + local function atFraction(frac) + if frac <= 0 then + return 0, "", 0 + end + if wire.count > 0 then + local last = wire.ends[wire.count] or 0 + if frac >= 1 then + return last, "", 1 + end + return math.floor(frac * last + 0.5), "", frac + end + local total = countRunes(source) + local offset = 0 + if frac >= 1 then + offset = total + elseif total > 0 then + offset = math.floor(frac * total + 0.5) + end + return offset, "", frac + end + local frac = tonumber(pos.chapter_fraction) + if frac ~= nil then + return atFraction(frac) + end + local extra = pos.extra + local cached = extra and tonumber(extra.chapter_offset) + if cached and tonumber(extra.chapter_idx) == tonumber(chapter.idx) then + local last + if wire.count > 0 then + last = wire.ends[wire.count] or 0 + else + last = countRunes(source) + end + local fraction = last > 0 and math.max(0, math.min(1, cached / last)) or 0 + return cached, "", fraction + end + return 0, "", 0 +end + +---@param identity BookIdentity +---@param chapter BookChapter +---@param pos ProgressPosition +---@param source string +---@param format '"html"'|'"txt"' +---@return integer|nil offset +---@return string|nil summary +---@return number|nil fraction +---@return string|nil err +function Position.encode(identity, chapter, pos, source, format) + local wire = Annotations.rangeMapping(source, format) + if pos.locator then + local flow = Annotations.flow(localHtml(identity, chapter, source, format)) + local offset, summary, fraction = Annotations.toWirePosition( + wire, flow, pos.locator, format == "html" and source or nil) + if offset ~= nil then + -- 纯图章没有可见正文摘要;章内页比例比 HTML 字节比例更贴近实际翻页位置。 + if flow.count == 0 and pos.chapter_fraction ~= nil then + return offset, summary or "", pos.chapter_fraction + end + return offset, summary, fraction + end + -- 路径对不上时按章级坐标上报,避免脏同步无限重试。 + end + return fallbackPosition(wire, chapter, pos, source) +end + +return Position diff --git a/moonsource-weread.koplugin/moonsource_weread/protocol.lua b/moonsource-weread.koplugin/moonsource_weread/protocol.lua new file mode 100644 index 0000000..0fc30e9 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/protocol.lua @@ -0,0 +1,372 @@ +--[[-- +微信读书 Web Reader 协议(编码 / 签名 / 正文分片解码)。 + +算法来自微信读书网页端公开逆向(与 cookie 会话配套), +独立实现,不依赖第三方插件源码。 + +@module koplugin.book.moonsource_weread.protocol +--]] + +local bit = require("bit") +local sha2 = require("ffi/sha2") +local md5 = sha2.md5 +local sha256_hex = sha2.sha256 +local Text = require("utils.text") + +local Protocol = {} + +Protocol.USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 Edg/147.0.0.0" +Protocol.DEFAULT_READER_TOKEN = "3c5c8717f3daf09iop3423zafeqoi" + +--- 判断字符串是否全为数字。 +---@return boolean +local function isDigitString(s) + return tostring(s):match("^%d+$") ~= nil +end + +--- 对参数值做 URL 编码(微信侧布尔/nil 字面量 coercion 保留在本层)。 +---@return string +local function urlencode(value) + if value == true then + value = "true" + elseif value == false then + value = "false" + elseif value == nil then + value = "null" + end + return Text.urlEncode(value) +end + +--- 把字符串每个字节编成十六进制拼接。 +---@param s string +---@return string +local function byteHex(s) + local out = {} + for i = 1, #s do + out[i] = string.format("%x", s:byte(i)) + end + return table.concat(out) +end + +--- 微信读书 ID/时间戳混淆(reader URL、正文参数 b/c/pc)。 +---@return string +function Protocol.encode(value) + local s = tostring(value) + local h = md5(s) + local result = h:sub(1, 3) + local chunks = {} + local type_flag + if isDigitString(s) then + type_flag = "3" + local i = 1 + while i <= #s do + local part = s:sub(i, i + 8) + chunks[#chunks + 1] = string.format("%x", tonumber(part)) + i = i + 9 + end + else + type_flag = "4" + chunks[1] = byteHex(s) + end + result = result .. type_flag .. "2" .. h:sub(-2) + for i, chunk in ipairs(chunks) do + result = result .. string.format("%02x", #chunk) .. chunk + if i < #chunks then + result = result .. "g" + end + end + if #result < 20 then + result = result .. h:sub(1, 20 - #result) + end + return result .. md5(result):sub(1, 3) +end + +--- 按键排序拼 query(排除签名字段 s)。 +---@param params table +---@return string +function Protocol.sortedQuery(params) + local keys = {} + for key in pairs(params) do + if key ~= "s" then + keys[#keys + 1] = key + end + end + table.sort(keys) + local parts = {} + for _idx, key in ipairs(keys) do + parts[#parts + 1] = key .. "=" .. urlencode(params[key]) + end + return table.concat(parts, "&") +end + +--- 计算微信读书 Web 请求签名。 +---@param query string +---@return string +function Protocol.sign(query) + local a = 0x15051505 + local b = a + local length = #query + local i = length + while i > 1 do + a = bit.band(bit.bxor(a, bit.lshift(query:byte(i), ((length - i + 1) % 30))), 0x7fffffff) + b = bit.band(bit.bxor(b, bit.lshift(query:byte(i - 1), ((i - 1) % 30))), 0x7fffffff) + i = i - 2 + end + return string.format("%x", a + b):lower() +end + +--- 构造 reader 页 URL。 +---@param book_id string|number +---@param chapter_uid string|number|nil +---@return string +function Protocol.readerUrl(book_id, chapter_uid) + local url = "https://weread.qq.com/web/reader/" .. Protocol.encode(book_id) + if chapter_uid then + url = url .. "k" .. Protocol.encode(chapter_uid) + end + return url +end + +--- 正文分片 POST body。 +---@param book_id string|number +---@param chapter_uid string|number +---@param psvts string +---@param opts { sc: number|nil, style: boolean|nil }|nil +---@return table +function Protocol.contentParams(book_id, chapter_uid, psvts, opts) + opts = opts or {} + local ct = os.time() + if Protocol.encode(ct) == psvts then + ct = ct + 1 + end + local params = { + b = Protocol.encode(book_id), + c = Protocol.encode(chapter_uid), + r = tostring(math.random(0, 9999) ^ 2), + ct = tostring(ct), + ps = psvts, + pc = Protocol.encode(ct), + sc = opts.sc or 1, + prevChapter = false, + st = opts.style and 1 or 0, + } + params.s = Protocol.sign(Protocol.sortedQuery(params)) + return params +end + +-- --- 分片解码(响应:32 字节 MD5 头 + 混淆 body;去掉首字符后反交换再 base64)--- + +--- 从混淆串推导交换位置列表。 +---@param encoded string +---@return number[] +local function swapPositions(encoded) + local length = #encoded + if length < 4 then + return {} + end + if length < 11 then + return { 0, 2 } + end + local n = math.min(4, math.floor((length + 9) / 10)) + local tmp = {} + for i = length, length - n + 1, -1 do + local byte = encoded:byte(i) + local bin = {} + repeat + table.insert(bin, 1, tostring(byte % 2)) + byte = math.floor(byte / 2) + until byte == 0 + tmp[#tmp + 1] = tostring(tonumber(table.concat(bin), 4) or 0) + end + local packed = table.concat(tmp) + local result = {} + local m = length - n - 2 + local step = #tostring(m) + local i = 1 + while #result < 10 and i + step - 1 < #packed do + result[#result + 1] = (tonumber(packed:sub(i, i + step - 1)) or 0) % m + local end2 = math.min(i + step, #packed) + if i + 1 <= #packed then + result[#result + 1] = (tonumber(packed:sub(i + 1, end2)) or 0) % m + end + i = i + step + end + return result +end + +--- 按位置列表反向交换还原混淆串。 +--- +--- positions 最多 10 项即最多 20 次单字符交换,而 encoded 是整章 base64(数百 KB)。 +--- 只把被动过的下标记进稀疏表,最后一次线性重拼,不逐字符建数组。 +---@param encoded string +---@param positions number[] +---@return string +local function reverseSwaps(encoded, positions) + local patch = {} + ---@param at integer 1-based + ---@return string + local function charAt(at) + return patch[at] or encoded:sub(at, at) + end + for i = #positions, 1, -2 do + for k = 1, 0, -1 do + local left = positions[i] + k + 1 + local right = positions[i - 1] + k + 1 + patch[left], patch[right] = charAt(right), charAt(left) + end + end + if not next(patch) then + return encoded + end + -- 按下标排序后分段拼接:未受影响的区间整段复制。 + local touched = {} + for at in pairs(patch) do + touched[#touched + 1] = at + end + table.sort(touched) + local parts, cursor = {}, 1 + for _idx, at in ipairs(touched) do + if at > cursor then + parts[#parts + 1] = encoded:sub(cursor, at - 1) + end + parts[#parts + 1] = patch[at] + cursor = at + 1 + end + parts[#parts + 1] = encoded:sub(cursor) + return table.concat(parts) +end + +--- 校验分片 MD5 头并返回 body。 +---@param response_text string|nil +---@return string|nil, string|nil +local function checkedBody(response_text) + if not response_text or #response_text <= 32 then + return nil, "shard too short" + end + local expected = response_text:sub(1, 32) + local body = response_text:sub(33) + if md5(body):upper() ~= expected then + return nil, "shard md5 mismatch" + end + return body +end + +--- 解码已通过校验的混淆 body 为明文。 +---@param body string|nil +---@return string +local function decodeEncodedBody(body) + if not body or #body == 0 then + return "" + end + local encoded = body:sub(2) + return Text.base64Decode(reverseSwaps(encoded, swapPositions(encoded))) +end + +--- 从 UA 推导 Web appId(阅读时长上报用)。 +---@param user_agent string +---@return string +function Protocol.webAppId(user_agent) + local prefix = {} + local count = 0 + for part in user_agent:gmatch("%S+") do + count = count + 1 + if count > 12 then break end + prefix[#prefix + 1] = tostring(#part % 10) + end + local hash = 0 + for i = 1, #user_agent do + hash = bit.band(0x83 * hash + user_agent:byte(i), 0x7fffffff) + end + return "wb" .. table.concat(prefix) .. "h" .. tostring(hash) +end + +--- UTF-8 前缀截断(最多 max_chars 个码点,遇非法首字节即止)。 +---@param value string|nil +---@param max_chars integer +---@return string +local function utf8Prefix(value, max_chars) + local text = value or "" + local pos = 1 + for _i = 1, max_chars do + local _start, stop = text:find("^" .. Text.UTF8_CHAR, pos) + if not stop then break end + pos = stop + 1 + end + return text:sub(1, pos - 1) +end + +--- 组装 web/book/read 的位置字段(进入阅读与时长上报共用的基础部分)。 +--- 书籍 id 与章节 uid 走 Protocol.encode 混淆,摘要截到 20 个字符,进度夹到 0..100; +--- pc 缺失时用当前时间编码兜底。返回的表尚未签名,由调用方补 s 字段。 +---@param opts table 含 book_id / chapter_uid / chapter_idx / chapter_offset / summary / progress / psvts / pclts +---@return table +local function readPositionPayload(opts) + local now = os.time() + local pc = opts.pclts + if pc == nil or pc == "" or tonumber(pc) == 0 then + pc = Protocol.encode(now) + end + local progress = math.floor(tonumber(opts.progress) or 0) + progress = math.max(0, math.min(100, progress)) + return { + appId = Protocol.webAppId(Protocol.USER_AGENT), + b = Protocol.encode(opts.book_id), + c = Protocol.encode(opts.chapter_uid or 0), + ci = math.floor(tonumber(opts.chapter_idx) or 0), + co = math.max(0, math.floor(tonumber(opts.chapter_offset) or 0)), + sm = utf8Prefix(opts.summary, 20), + pr = progress, + ct = now, + ps = opts.psvts or "", + pc = pc, + } +end + +--- 进入阅读会话 payload(web/book/read 首次)。 +---@param opts table +---@return table +function Protocol.makeEnterReadPayload(opts) + opts = opts or {} + local params = readPositionPayload(opts) + params.s = Protocol.sign(Protocol.sortedQuery(params)) + return params +end + +--- 周期性阅读时长 payload(web/book/read)。 +---@param opts table +---@return table +function Protocol.makeReadPayload(opts) + opts = opts or {} + local params = readPositionPayload(opts) + local ts = params.ct * 1000 + math.random(0, 999) + local rn = math.random(0, 999) + params.rt = math.max(0, math.floor(tonumber(opts.elapsed_seconds) or 0)) + params.ts = ts + params.rn = rn + params.sg = sha256_hex(tostring(ts) .. tostring(rn) .. (opts.token or Protocol.DEFAULT_READER_TOKEN)) + params.s = Protocol.sign(Protocol.sortedQuery(params)) + return params +end + +--- 拼接 e0+e1+e3(或 t0+t1)并解码为明文。 +---@param ... string +---@return string|nil text, string|nil err +function Protocol.decodeShards(...) + local parts = {} + for i = 1, select("#", ...) do + local raw = select(i, ...) + if raw and raw ~= "" then + local body, err = checkedBody(raw) + if not body then + return nil, err + end + parts[#parts + 1] = body + end + end + if #parts == 0 then + return nil, "empty shards" + end + return decodeEncodedBody(table.concat(parts)) +end + +return Protocol diff --git a/moonsource-weread.koplugin/moonsource_weread/reviews.lua b/moonsource-weread.koplugin/moonsource_weread/reviews.lua new file mode 100644 index 0000000..8dd1c2f --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/reviews.lua @@ -0,0 +1,260 @@ +--[[-- +微信读书段评(他人在本章某句下的点评):本章热点与按句分页。 + +热点 = ``/web/book/underlines`` 的全部 range,分批并发 ``readReviews``(每句只要 1 条)换回原句 +``abstract`` 与段评总数,缓存由 `book.review_cache` 统一做。拉取与定位分开:章会话在本章 HTML 上定位,关联书按页查找原句。 +原句经 ``Annotations.locateBatch`` 落到 HTML 的 xpointer,定位不了(找不到 / 重复无法消歧)的直接丢弃,不画错位置。 + +@module koplugin.book.moonsource_weread.reviews +--]] + +local Annotations = require("book.annotations") +local _ = require("l10n").get("moonsource_weread") + +local PAGE_SIZE = 30 +local COMMENT_PAGE = 20 +-- 服务端按 range 逐个查,整批 3 秒超时(errCode -10100);实测每个约 30ms,一章常有 150~300 个。 +local BATCH_SIZE = 40 +-- 同时在飞的批数:串行时一章 8 批要 10 秒以上。 +local CONCURRENCY = 3 + +local Reviews = {} + +--- 未定位的热点。 +---@class WechatReviewHotspot +---@field chapter_idx integer|nil 归属章序号 +---@field badge string|nil 标记文案 +---@field heading string|nil 独立分隔区的标题 +---@field anchor string|nil 正文末尾预留区的 HTML id +---@field range string wire range,翻页时原样带回 +---@field text string 原句 +---@field total integer 段评总数 + +--- 已定位的热点。 +---@class WechatReviewSpot: WechatReviewHotspot +---@field pos0 string +---@field pos1 string + +---@class WechatReview +---@field id string +---@field author string +---@field content string +---@field inline_images table }>|nil 正文内表情占位符 +---@field likes integer +---@field replies integer 二级回复条数;0 表示没有,列表上不给入口 +---@field reply_preview WechatReview[]|nil 主评论附带的有限回复预览,不代表完整回复列表 +---@field reply_to string|nil 这条是在回复谁(楼中楼),空则不是 +---@field images { url: string, width?: integer, height?: integer, headers?: table }[]|nil 评论配图 +---@field time integer 秒 + +---@class WechatReviewPage +---@field items WechatReview[] +---@field total integer +---@field max_idx integer|string 下一页请求带回 +---@field more boolean + +--- readReviews 回包 → 有段评的热点(未定位)。 +---@param wire table ``{ reviews = [{ range, totalCount, pageReviews[] }] }`` +---@return WechatReviewHotspot[] +function Reviews.hotspots(wire) + local out = {} + for _idx, entry in ipairs(wire.reviews or {}) do + local first = entry.pageReviews and entry.pageReviews[1] + local total = tonumber(entry.totalCount) or 0 + if first and total > 0 then + out[#out + 1] = { range = entry.range, text = first.review.abstract, total = total } + end + end + return out +end + +--- 热点按原句定位到 html;xpointer 以该 HTML 的根为起点。 +---@param hotspots WechatReviewHotspot[] +---@param html string +---@return WechatReviewSpot[] +function Reviews.locate(hotspots, html) + local items = {} + for i, spot in ipairs(hotspots) do items[i] = { text = spot.text, wr_range = spot.range, spot = spot } end + local located = Annotations.locateBatch(html, items) + local out = {} + for _idx, item in ipairs(items) do + local hit = located[item] + if hit then + local spot = item.spot + out[#out + 1] = { range = spot.range, text = spot.text, total = spot.total, pos0 = hit.pos0, pos1 = hit.pos1 } + end + end + return out +end + +--- 单条 pageReviews → 展示项。 +---@param entry table +---@return WechatReview +function Reviews.item(entry) + local review = entry.review + return { + id = entry.reviewId, + author = type(review.author) == "table" and review.author.name or "", + content = review.content, + likes = tonumber(entry.likesCount) or 0, + replies = tonumber(entry.commentsCount) or tonumber(review.commentsCount) or 0, + time = tonumber(review.createTime) or 0, + } +end + +--- ``/review/single`` 的一条评论。楼中楼只带被回复者,展平在同一页。 +---@param entry table +---@return WechatReview +function Reviews.commentItem(entry) + local comment = type(entry.comment) == "table" and entry.comment or entry + local author = type(comment.author) == "table" and comment.author or entry.author + local reply_user = type(entry.replyUser) == "table" and entry.replyUser + or (type(comment.replyUser) == "table" and comment.replyUser or nil) + return { + id = tostring(entry.commentId or comment.commentId or ""), + author = type(author) == "table" and author.name or "", + content = tostring(comment.content or entry.content or ""), + likes = tonumber(entry.likesCount or comment.likesCount) or 0, + replies = 0, + reply_to = type(reply_user) == "table" and reply_user.name or nil, + time = tonumber(comment.createTime or entry.createTime) or 0, + } +end + +--- 想法评论回包 → 一页。游标没前进就停,避免 hasMore 粘住时翻页死循环。 +--- 声称有评论却给空列表:当失败,不当成「0 条回复」。 +---@param wire table +---@param max_idx integer +---@return WechatReviewPage|nil +---@return string|nil +function Reviews.comments(wire, max_idx) + local list = wire.comments + local total = tonumber(wire.commentsCount) or 0 + if list == nil and total == 0 then list = {} end + if type(list) ~= "table" then return nil, _("无法获取回复") end + local items = {} + for _idx, entry in ipairs(list) do + if type(entry) == "table" then items[#items + 1] = Reviews.commentItem(entry) end + end + if #items == 0 and total > 0 then return nil, _("无法获取回复") end + local next_idx = tonumber(wire.commentsMaxIdx) + local more = tonumber(wire.commentsHasMore) == 1 or wire.commentsHasMore == true + if not next_idx or next_idx == max_idx then more = false end + return { + items = items, + total = total > 0 and total or #items, + max_idx = next_idx or max_idx, + more = more and #items > 0, + } +end + +--- 拉本章热点:underlines → 并发分批 readReviews。 +---@param client WechatClient +---@param book_id string +---@param chapter_uid string +---@param cb fun(hotspots: WechatReviewHotspot[]|nil, err: string|nil) +---@return { cancel: fun() } +function Reviews.hotspotsAsync(client, book_id, chapter_uid, cb) + local cancelled = false + local jobs = {} + local function cancel() + cancelled = true + for _key, job in pairs(jobs) do job.cancel() end + end + jobs.underlines = client:underlinesAsync(book_id, chapter_uid, function(data, err) + jobs.underlines = nil + if cancelled then return end + if not data then + cb(nil, err) + return + end + local batches = {} + local underlines = data.underlines or {} + for from = 1, #underlines, BATCH_SIZE do + local batch = {} + for i = from, math.min(from + BATCH_SIZE - 1, #underlines) do + batch[#batch + 1] = { range = underlines[i].range, maxIdx = 0, count = 1, synckey = 0 } + end + batches[#batches + 1] = batch + end + local results, next_batch, pending = {}, 1, 0 + local function finish() + local collected = {} + for _idx, reviews in ipairs(results) do + for _entry_idx, entry in ipairs(reviews) do collected[#collected + 1] = entry end + end + local hotspots = Reviews.hotspots({ reviews = collected }) + cb(hotspots) + end + local function launch() + while next_batch <= #batches and pending < CONCURRENCY do + local i = next_batch + next_batch, pending = next_batch + 1, pending + 1 + jobs[i] = client:readReviewsAsync(book_id, chapter_uid, batches[i], function(wire, review_err) + jobs[i], pending = nil, pending - 1 + if cancelled then return end + if not wire then + cancel() + cb(nil, review_err) + return + end + results[i] = wire.reviews or {} + if next_batch > #batches and pending == 0 then finish() else launch() end + end) + end + end + if #batches == 0 then finish() else launch() end + end) + return { cancel = cancel } +end + +--- 拉某句的一页段评。 +---@param client WechatClient +---@param book_id string +---@param chapter_uid string +---@param range string +---@param max_idx integer 首页 0,之后用上一页的 max_idx +---@param cb fun(page: WechatReviewPage|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Reviews.pageAsync(client, book_id, chapter_uid, range, max_idx, cb) + return client:readReviewsAsync(book_id, chapter_uid, { + { range = range, maxIdx = max_idx, count = PAGE_SIZE, synckey = 0 }, + }, function(wire, err) + local entry = wire and wire.reviews and wire.reviews[1] + if not entry then + cb(nil, err or _("无法获取段评")) + return + end + local items = {} + for _idx, review in ipairs(entry.pageReviews or {}) do + -- 已删除的段评只剩 reviewId,没有 review 体。 + if type(review) == "table" and type(review.review) == "table" then + items[#items + 1] = Reviews.item(review) + end + end + cb({ + items = items, + total = tonumber(entry.totalCount) or #items, + max_idx = tonumber(entry.maxIdx) or max_idx, + more = tonumber(entry.hasMore) == 1, + }) + end) +end + +--- 某条想法的一页回复。max_idx 首页 0,之后用上一页的 commentsMaxIdx。 +---@param client WechatClient +---@param review_id string +---@param max_idx integer +---@param cb fun(page: WechatReviewPage|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Reviews.commentsAsync(client, review_id, max_idx, cb) + return client:reviewSingleAsync(review_id, max_idx, COMMENT_PAGE, function(wire, err) + if not wire then + cb(nil, err or _("无法获取回复")) + return + end + cb(Reviews.comments(wire, max_idx)) + end) +end + +return Reviews diff --git a/moonsource-weread.koplugin/moonsource_weread/setting.lua b/moonsource-weread.koplugin/moonsource_weread/setting.lua new file mode 100644 index 0000000..c627c08 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/setting.lua @@ -0,0 +1,176 @@ +--[[-- +微信读书源设置 UI(扫码登录由本模块自绘)。 +读写:utils.settings.getSource / saveSource("ext.weread") + +@module koplugin.book.moonsource_weread.setting +--]] + +local _ = require("l10n").get("moonsource_weread") +local T = require("ffi/util").template + +local SOURCE_ID = "ext.weread" + +local Setting = {} + +--- 设置行状态文案与高亮开关。 +---@return string status, boolean status_on +function Setting.rowStatus() + local Auth = require("moonsource_weread.auth") + if Auth.hasSession() then + return Auth.userLabel() or _("已登录"), true + end + return _("未登录 · 点此扫码"), false +end + +--- 展示扫码登录流程(Eink 扫码;换到的 accessToken 同时是网页会话,再经网页接口补拉昵称)。 +local function showQrLogin() + local Auth = require("moonsource_weread.auth") + local Eink = require("moonsource_weread.eink") + local NetworkMgr = require("ui/network/manager") + local QR = require("ui.themes.widgets.qr") + local Toast = require("ui.themes.widgets.toast") + + NetworkMgr:runWhenConnected(function() + local cancelled = false + local dialog + local begin_job, wait_job + + --- 代码主动关窗:先摘掉引用,close_callback 就不会当成用户取消。 + local function closeDialog() + local d = dialog + dialog = nil + if d then d:close() end + end + + -- 点框内外、返回键都走这里,否则后台轮询会一直跑到超时。 + local function cancel() + cancelled = true + if begin_job then + begin_job.cancel() + begin_job = nil + end + if wait_job then + wait_job.cancel() + wait_job = nil + end + end + + --- 换上新的登录窗;用户关掉它即取消整个登录。 + ---@param d table 未显示的主题弹窗 + local function showDialog(d) + closeDialog() + d.close_callback = function() + if dialog ~= d then return end + dialog = nil + cancel() + end + dialog = d + d:show() + end + + showDialog(require("ui.themes.widgets.progress_dialog"):new{ + title = _("微信扫码登录"), text = _("正在获取二维码…"), dismissable = false, + }) + + --- 展示二维码并长连接等待扫码结果。 + ---@param uid string + ---@param qr_payload string + local function startWait(uid, qr_payload) + showDialog(QR:new{ title = _("微信扫码登录"), text = qr_payload }) + wait_job = Eink.waitQrLoginAsync(uid, function(info, err, status) + wait_job = nil + if cancelled then + return + end + closeDialog() + if status ~= "ok" or not info then + Toast:new{ text = err or _("二维码已失效,请重新登录") }:show() + return + end + Eink.completeQrLoginAsync(info, function(ok, e2) + if cancelled then + return + end + if not ok then + Toast:new{ text = e2 or _("登录失败") }:show() + return + end + Auth.fetchUserAsync(function(user) + Toast:new{ + text = T(_("已登录:%1"), user.user_name ~= "" and user.user_name or user.user_id), + timeout = 2, + }:show() + require("source.registry").reload() + end) + end) + end) + end + + begin_job = Eink.beginQrLoginAsync(function(started, err) + begin_job = nil + if cancelled then + return + end + if started then + startWait(started.uid, started.qr_payload) + return + end + closeDialog() + Toast:new{ text = err or _("无法开始登录") }:show() + end) + end) +end + +--- 设置页行:账号(扫码)、阅读选项;已登录时追加续期、退出。 +---@param plugin table|nil +---@return table[] +function Setting.rows(plugin) + local Row = require("ui.themes.widgets.row") + local Auth = require("moonsource_weread.auth") + local Toast = require("ui.themes.widgets.toast") + local rows = { + function(iw) + local status, status_on = Setting.rowStatus() + return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "account_circle", title = _("微信读书账号"), + status = status, status_on = status_on, + callback = showQrLogin }) + end, + } + local Settings = require("utils.settings") + --- 布尔开关行;default 为未设置时的取值。 + local function toggle(key, default, icon, title, subtitle) + rows[#rows + 1] = function(iw) + local cfg = Settings.getSource(SOURCE_ID) + local on = cfg[key] == nil and default or cfg[key] == true + return Row.widget({ width = iw, chevron = false, kind = "toggle", icon = icon, title = title, + subtitle = subtitle, status = on and _("开") or _("关"), status_on = on, + callback = function() + cfg[key] = not on + Settings.saveSource(SOURCE_ID, cfg) + if plugin and plugin.desktop then plugin.desktop:updateView() end + end }) + end + end + toggle("merge_local_stats", false, "history", _("合并本地阅读时长"), + _("关闭时以云端为准;打开后每天取云端与本地中较大的,补上离线阅读。只影响月读里的统计")) + toggle("show_paragraph_reviews", false, "forum", _("显示段评"), _("阅读时给有他人段评的句子画线,点按查看;需联网")) + rows[#rows + 1] = require("source.category_setting").row(SOURCE_ID, plugin) + if not Auth.hasSession() then return rows end + rows[#rows + 1] = function(iw) + return Row.widget({ width = iw, chevron = false, kind = "action", icon = "autorenew", title = _("续期会话"), + callback = function() + require("ui/network/manager"):runWhenConnected(function() + require("moonsource_weread.eink").refreshAsync(function(ok, err) + Toast:new{ text = ok and _("已续期") or (err or _("续期失败")), timeout = 2 }:show() + end) + end) + end }) + end + rows[#rows + 1] = require("source.logout").row(SOURCE_ID, _("确定退出微信读书账号?"), Auth.clearSession) + return rows +end + +--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。 +Setting.login = showQrLogin + +return Setting diff --git a/moonsource-weread.koplugin/moonsource_weread/shelf_import.lua b/moonsource-weread.koplugin/moonsource_weread/shelf_import.lua new file mode 100644 index 0000000..2ff4f76 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/shelf_import.lua @@ -0,0 +1,97 @@ +--[[-- +微信书架全量快照的分批导入。 + +/shelf/sync 全量回包过大时,设备端解码会爆内存:原文不解码直接落盘(`stash`), +由远程管理网页下载、在浏览器里解码,再把书切成小批回传(`ingest`),最后 `commit` 对账并存游标。 +设备端从头到尾不持有整份 wire;无状态,批与批之间不留内存。 + +@module koplugin.book.moonsource_weread.shelf_import +--]] + +local Paths = require("utils.paths") +local _ = require("l10n").get("moonsource_weread") + +local SOURCE_ID = "ext.weread" + +local ShelfImport = {} + +--- 回包超过这个字节数就不在设备上解码(解码后内存是原文数倍)。 +ShelfImport.LIMIT = 1024 * 1024 + +ShelfImport.TOO_LARGE = _("书架数据太大,设备无法直接处理。已开启远程管理,请扫码在浏览器点「开始导入」完成同步。") +ShelfImport.PAGE = "/wechat_import.html" + +---@return string +function ShelfImport.path() + return Paths.sourceCacheDir(SOURCE_ID) .. "/shelf_full.json" +end + +--- 原文落盘,覆盖上一份。 +---@param body string +---@return boolean ok +---@return string|nil err +function ShelfImport.stash(body) + Paths.ensureDir(Paths.sourceCacheDir(SOURCE_ID)) + local path = ShelfImport.path() + local file, err = io.open(path .. ".part", "wb") + if not file then return false, tostring(err) end + local ok, werr = file:write(body) + file:close() + if ok then ok, werr = os.rename(path .. ".part", path) end + if not ok then + os.remove(path .. ".part") + return false, tostring(werr) + end + return true +end + +--- 待导入文件的字节数;没有返回 nil。 +---@return integer|nil +function ShelfImport.size() + local file = io.open(ShelfImport.path(), "rb") + if not file then return nil end + local size = file:seek("end") + file:close() + return size +end + +function ShelfImport.discard() + os.remove(ShelfImport.path()) +end + +--- 一批书入库。batch 是缩小版书架 wire:books / bookProgress / archive / albums, +--- 只含这批书相关的进度与分组(浏览器切好),字段口径与 Mapper.shelfList 一致。 +---@param batch table +---@return string[]|nil ids 入库的 stable_id +---@return string|nil err +function ShelfImport.ingest(batch) + local rows = require("moonsource_weread.mapper").shelfList(batch).data + local BookDB = require("book.books_db") + local ids = {} + for _idx, row in ipairs(rows) do + row.source_id = SOURCE_ID + row.deleted = 0 + ids[#ids + 1] = row.stable_id + end + if not BookDB.upsertRemoteMany(rows) then return nil, "failed to save books" end + return ids +end + +--- 收尾:快照外的在架行下架,存增量游标,删原文件。ids 是各批 ingest 返回的全部 stable_id。 +---@param ids string[] +---@param synckey number|nil +---@return integer|nil hidden +---@return string|nil err +function ShelfImport.commit(ids, synckey) + local hidden = require("book.books_db").hideMissing(SOURCE_ID, ids) + if not hidden then return nil, "failed to reconcile books" end + if synckey then + local Eink = require("moonsource_weread.eink") + local cfg = require("utils.settings").getSource(SOURCE_ID) + Eink.save({ shelf_cursor = { vid = cfg.wr_vid, synckey = synckey } }) + end + ShelfImport.discard() + return hidden +end + +return ShelfImport diff --git a/moonsource-weread.koplugin/moonsource_weread/source.lua b/moonsource-weread.koplugin/moonsource_weread/source.lua new file mode 100644 index 0000000..ef4d35b --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/source.lua @@ -0,0 +1,1654 @@ +--[[-- +微信读书数据源门面(仅异步网络) + +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 +---@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("ext.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 + 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["ext.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 diff --git a/moonsource-weread.koplugin/moonsource_weread/stats.lua b/moonsource-weread.koplugin/moonsource_weread/stats.lua new file mode 100644 index 0000000..4c36173 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/stats.lua @@ -0,0 +1,194 @@ +--[[-- +微信读书阅读统计:累计总量、账户日桶与单书明细 wire → reading_stats 领域行。 + +账户级日桶 ``__wr:day:``;权威累计时长 ``__wr:total``,不参与日历分桶求和。 +单书(stable_id 即 bookId):``book_total`` 为书架 ``readingTime`` 快照(start_time=拉取时间), +``book_day`` 为 readinfo 按日明细(start_time=当天零点)。云端按日求和本就不等于累计,两者不互推。 +日桶 / book_day 的 last_time 记拉取时间:展示时补上拉取之后本地新读的时长。 +入库前按各合成前缀的时间窗口、按书精确替换旧记录,避免重复累计。 + +@module koplugin.book.moonsource_weread.stats +--]] + +local Stats = {} + +local DAY_PREFIX = "__wr:day:" +local TOTAL_ID = "__wr:total" +--- 旧版周排行合成行(record_type=book),已由单书按日取代;每次拉取顺手清掉。 +local LEGACY_WEEK_PREFIX = "__wr:week:" + +local function field(wire, key) + if type(wire) ~= "table" then return nil end + if wire[key] ~= nil then return wire[key] end + return type(wire.data) == "table" and wire.data[key] or nil +end + +--- 合成 reading_stats 行;云端没有页坐标,page/total_pages 恒为 0。 +local function statsRow(source_id, stable_id, record_type, start_time, duration, last_time) + return { + source_id = source_id, + stable_id = stable_id, + record_type = record_type, + page = 0, + start_time = start_time, + duration = duration, + total_pages = 0, + last_time = last_time, + } +end + +local function appendTimes(rows, source_id, read_times, fetched_at) + if type(read_times) ~= "table" then return end + for ts_str, seconds in pairs(read_times) do + local ts = tonumber(ts_str) + local duration = tonumber(seconds) + if ts and duration and duration > 0 then + rows[#rows + 1] = statsRow(source_id, DAY_PREFIX .. tostring(ts), "day", ts, duration, fetched_at) + end + end +end + +local function yearRange(wire) + local base_time = tonumber(field(wire, "baseTime")) or os.time() + local year = assert(tonumber(os.date("%Y", base_time))) + ---@cast year integer + local from_ts = os.time({ year = year, month = 1, day = 1, hour = 0 }) + local to_ts = os.time({ year = year + 1, month = 1, day = 1, hour = 0 }) - 1 + return from_ts, to_ts +end + +--- 从 overall 年桶得到需要逐年拉取的基准时间,始终包含当前年。 +---@param overall table +---@return number[] +function Stats.annualBaseTimes(overall) + local by_year = {} + local read_times = field(overall, "readTimes") + if type(read_times) == "table" then + for ts_str in pairs(read_times) do + local ts = tonumber(ts_str) + if ts and ts > 0 then + by_year[tonumber(os.date("%Y", ts))] = ts + end + end + end + local current_year = assert(tonumber(os.date("%Y"))) + ---@cast current_year integer + by_year[current_year] = by_year[current_year] + or os.time({ year = current_year, month = 1, day = 1, hour = 0 }) + local years = {} + for year in pairs(by_year) do years[#years + 1] = year end + table.sort(years) + local out = {} + for _idx, year in ipairs(years) do out[#out + 1] = by_year[year] end + return out +end + +--- 年度无日明细时,从月桶找出需要继续拉取的月份。 +---@param annual table +---@return number[] +function Stats.monthlyBaseTimes(annual) + local daily = field(annual, "dailyReadTimes") + if type(daily) == "table" and next(daily) ~= nil then return {} end + local out = {} + local read_times = field(annual, "readTimes") + if type(read_times) == "table" then + for ts_str, seconds in pairs(read_times) do + local ts = tonumber(ts_str) + if ts and ts > 0 and (tonumber(seconds) or 0) > 0 then + out[#out + 1] = ts + end + end + end + table.sort(out) + return out +end + +--- 书架 ``bookProgress`` 里云端累计与本地快照不同的书(即某台设备读过),最近更新的在前。 +---@param progresses table[]|nil 书架 wire 的 bookProgress +---@param stored table 本地 book_total 快照:bookId → 秒 +---@param limit integer 本轮最多拉取的书数,其余留给下次同步 +---@return { id: string, reading_time: number, wire: table|nil }[] +function Stats.changedBooks(progresses, stored, limit) + local changed = {} + for _idx, p in ipairs(type(progresses) == "table" and progresses or {}) do + local seconds = tonumber(p.readingTime) or 0 + local id = p.bookId ~= nil and tostring(p.bookId) or nil + if id and seconds ~= (stored[id] or 0) then + changed[#changed + 1] = { + id = id, reading_time = seconds, updated_at = tonumber(p.updateTime) or 0, + } + end + end + table.sort(changed, function(a, b) return a.updated_at > b.updated_at end) + local out = {} + for i = 1, math.min(limit, #changed) do + out[i] = { id = changed[i].id, reading_time = changed[i].reading_time } + end + return out +end + +--- 单书:书架累计快照 + readinfo 按日明细。 +local function appendBook(rows, source_id, book, fetched_at) + if book.reading_time > 0 then + rows[#rows + 1] = statsRow(source_id, book.id, "book_total", fetched_at, book.reading_time) + end + local detail = field(book.wire, "readDetail") + local days = type(detail) == "table" and detail.data or nil + for _idx, day in ipairs(type(days) == "table" and days or {}) do + local ts = tonumber(day.readDate) + local seconds = tonumber(day.readTime) + if ts and seconds and seconds > 0 then + rows[#rows + 1] = statsRow(source_id, book.id, "book_day", ts, seconds, fetched_at) + end + end +end + +--- 合并总体权威总量、账户日桶与单书明细。 +---@param source_id string +---@param overall table +---@param annuals table[] +---@param monthlies table[]|nil +---@param books { id: string, reading_time: number, wire: table }[]|nil 已拉到 readinfo 的书 +---@param fetched_at number|nil 拉取时间 +---@return BookStatsPullResult +function Stats.fromWires(source_id, overall, annuals, monthlies, books, fetched_at) + fetched_at = fetched_at or os.time() + local rows = {} + local total = tonumber(field(overall, "totalReadTime")) + if total and total > 0 then + rows[#rows + 1] = statsRow(source_id, TOTAL_ID, "total", 0, total, fetched_at) + end + local ranges = { + { stable_prefix = TOTAL_ID, from_ts = 0, to_ts = 0 }, + { stable_prefix = LEGACY_WEEK_PREFIX, from_ts = 0, to_ts = fetched_at }, + } + for _idx, annual in ipairs(annuals or {}) do + -- 年度回包有真实日明细时直接使用;没有时由月度请求补齐。 + appendTimes(rows, source_id, field(annual, "dailyReadTimes"), fetched_at) + local from_ts, to_ts = yearRange(annual) + ranges[#ranges + 1] = { + stable_prefix = DAY_PREFIX, from_ts = from_ts, to_ts = to_ts, + } + end + for _idx, monthly in ipairs(monthlies or {}) do + -- 月度 ``readTimes`` 的粒度是日,可以直接落日桶。 + appendTimes(rows, source_id, field(monthly, "readTimes"), fetched_at) + end + local book_ids = {} + for _idx, book in ipairs(books or {}) do + appendBook(rows, source_id, book, fetched_at) + book_ids[#book_ids + 1] = book.id + end + return { + rows = rows, + replace = { + mode = "ranges", + ranges = ranges, + books = book_ids, + }, + } +end + +Stats.TOTAL_ID = TOTAL_ID + +return Stats diff --git a/moonsource-weread.koplugin/moonsource_weread/toc.lua b/moonsource-weread.koplugin/moonsource_weread/toc.lua new file mode 100644 index 0000000..c05f395 --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/toc.lua @@ -0,0 +1,21 @@ +--[[-- +微信读书目录缓存:共用 ``source.toc``,只多一个目录格式判断。 + +@module koplugin.book.moonsource_weread.toc +--]] + +local Toc = setmetatable({}, { __index = require("source.toc") }) + +--- 目录格式版本,Mapper.chapters 写在首章。3:网文章名补「第 N 章」;5:anchors 去掉同名同层的自锚点。 +Toc.FORMAT_VERSION = 5 + +--- 当前目录是否为最新格式;旧缓存返回 false,触发源重新拉取。 +---@param list BookChapter[]|nil +---@return boolean +function Toc.isCurrent(list) + return type(list) == "table" + and type(list[1]) == "table" + and tonumber(list[1].toc_version) == Toc.FORMAT_VERSION +end + +return Toc diff --git a/moonsource-weread.koplugin/moonsource_weread/web/wechat_import.html b/moonsource-weread.koplugin/moonsource_weread/web/wechat_import.html new file mode 100644 index 0000000..294a58e --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/web/wechat_import.html @@ -0,0 +1,36 @@ + + + + + + +微信书架导入 - 远程管理 + + + + + + +
+
+
+

微信书架分批导入

+

+

+ + +

+
+

+
+
+ + + + diff --git a/moonsource-weread.koplugin/moonsource_weread/web/wechat_import.js b/moonsource-weread.koplugin/moonsource_weread/web/wechat_import.js new file mode 100644 index 0000000..07498eb --- /dev/null +++ b/moonsource-weread.koplugin/moonsource_weread/web/wechat_import.js @@ -0,0 +1,154 @@ +/* 微信书架分批导入:下载设备落盘的 /shelf/sync 原文 → 浏览器解码 → 切批回传 → 收尾对账。接口 /api/wechat_import/*。 */ +(function () { + var BATCH = 50; + var MAX_BYTES = 512 * 1024; + var API = '/api/wechat_import/'; + var LISTS = ['books', 'recentBooks', 'finishReadBooks']; + var busy = false; + + function post(action, body) { + return jfetch(API + action, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body || {}), + }); + } + + function bookId(row) { + var b = row.book || row.bookInfo || row; + var id = b.bookId || b.id || b.book_id; + return id == null ? null : String(id); + } + + function progress(ratio) { + el('bar').style.width = Math.round(Math.min(1, Math.max(0, ratio)) * 100) + '%'; + } + + var pinger = null; + + /* 导入期间定时请求设备,让它别自动休眠(休眠会停掉远程管理)。 */ + function setBusy(on) { + busy = on; + clearInterval(pinger); + pinger = on ? setInterval(function () { jfetch(API + 'status', { cache: 'no-store' }).catch(function () {}); }, 15000) : null; + el('start').disabled = on; + el('discard').disabled = on; + } + + /* 流式读:按已收字节更新进度(总量取设备落盘大小),读完再解码。 */ + function download(total) { + return fetch(API + 'file', { cache: 'no-store' }).then(function (r) { + if (r.status === 401) return pair().then(function () { return fetch(API + 'file', { cache: 'no-store' }); }); + return r; + }).then(function (r) { + if (!r.ok) throw new Error('HTTP ' + r.status); + var reader = r.body.getReader(); + var chunks = [], got = 0; + function pump() { + return reader.read().then(function (res) { + if (res.done) return new Blob(chunks).text(); + chunks.push(res.value); + got += res.value.length; + setState(el('info'), t('正在下载 %1 / %2 KB', Math.ceil(got / 1024), Math.ceil(total / 1024))); + progress(got / total); + return pump(); + }); + } + return pump(); + }).then(function (text) { + setState(el('info'), t('正在解析…')); + return JSON.parse(text); + }); + } + + function refresh() { + return jfetch(API + 'status', { cache: 'no-store' }).then(function (s) { + var has = !!s.size; + setState(el('info'), has ? t('待导入书架数据 %1 KB', Math.ceil(s.size / 1024)) + : t('设备上没有待导入的书架数据。请先在设备上对微信读书执行一次全量同步(强制刷新书架)。')); + el('start').disabled = !has; + el('discard').disabled = !has; + }); + } + + /* 一批:只带这批书相关的进度与分组,保证请求体远小于设备的 1MB 上限。 */ + function slice(wire, list, rows) { + var ids = {}; + rows.forEach(function (row) { var id = bookId(row); if (id) ids[id] = true; }); + var batch = { bookProgress: (wire.bookProgress || []).filter(function (p) { return ids[String(p.bookId)]; }) }; + batch[list] = rows; + batch.archive = (wire.archive || []).map(function (a) { + return { archiveId: a.archiveId, name: a.name, bookIds: (a.bookIds || []).filter(function (id) { return ids[String(id)]; }) }; + }).filter(function (a) { return a.bookIds.length; }); + return batch; + } + + /* 请求体超过设备上限会被直接断连(浏览器只看到 Failed to fetch),超了就对半切。 */ + function fit(wire, list, rows, out) { + var batch = slice(wire, list, rows); + if (rows.length > 1 && JSON.stringify(batch).length > MAX_BYTES) { + var half = rows.length >> 1; + fit(wire, list, rows.slice(0, half), out); + fit(wire, list, rows.slice(half), out); + } else { + out.push(batch); + } + } + + function batches(wire) { + var out = []; + LISTS.forEach(function (list) { + var rows = wire[list] || []; + for (var i = 0; i < rows.length; i += BATCH) fit(wire, list, rows.slice(i, i + BATCH), out); + }); + for (var j = 0; j < (wire.albums || []).length; j += BATCH) { + out.push({ albums: wire.albums.slice(j, j + BATCH) }); + } + return out; + } + + function run() { + setBusy(true); + el('log').textContent = ''; + say('正在下载…'); + progress(0); + var ids = []; + var stage = '下载'; + jfetch(API + 'status', { cache: 'no-store' }).then(function (s) { + return download(s.size); + }).then(function (wire) { + var list = batches(wire); + var chain = Promise.resolve(); + list.forEach(function (batch, i) { + chain = chain.then(function () { + stage = t('第 %1 / %2 批上传', i + 1, list.length); + return post('batch', batch).then(function (res) { + ids = ids.concat(res.ids); + el('info').textContent = t('正在导入 %1 / %2', i + 1, list.length); + progress((i + 1) / list.length); + }); + }); + }); + return chain.then(function () { stage = '收尾'; return post('commit', { ids: ids, synckey: wire.synckey }); }); + }).then(function (res) { + var msg = t('导入完成:%1 本,下架 %2 本', ids.length, res.hidden); + say(msg); + setState(el('info'), msg, 'ok'); + setBusy(false); + el('start').disabled = true; + el('discard').disabled = true; + }).catch(function (e) { + var msg = t('导入失败:%1', t(stage) + ' - ' + (e && e.message || e)); + say(msg); + setState(el('info'), msg, 'err'); + setBusy(false); + }); + } + + el('start').onclick = run; + el('discard').onclick = function () { + if (busy) return; + post('discard').then(function () { say('已丢弃'); return refresh(); }); + }; + refresh(); +})(); diff --git a/tests/weread/app_spec.lua b/tests/weread/app_spec.lua new file mode 100644 index 0000000..5109fc5 --- /dev/null +++ b/tests/weread/app_spec.lua @@ -0,0 +1,69 @@ +--[[-- +moonsource_weread.app 离线用例:签名对照官方 App 抓包,小时分桶。 + +@module tests.wechat.app_spec +--]] +---@diagnostic disable: undefined-field + +local Assert = require("support.assert") +local App = require("moonsource_weread.app") + +-- HAR 里官方 App 的一条 /book/read:同样的输入必须得到同样的 signature。 +local payload = table.concat({ + "393727764", "35645832171399234841676621530100678335", "35645832171399234841676621530100678335", + "CB_00K1XI1aSDlZ76f75hG9n7JG", "0", "+08:00", "81", "0", +}, "_") .. "_1792317600_+08:00_81_0" +Assert.eq( + App.sign({ "5ecdcfd7f", "821", "1792318161", payload }), + "dfd6f2ceb1e4a5d1152c6d19fd9c9f84115cad69989ee799faec377d05d8a833" +) + +-- 跨整点的区间拆进两个小时桶,按整点升序。 +local hours = App.hours({ + { start_time = 7300, duration = 10 }, + { start_time = 3590, duration = 20 }, +}, "+08:00") +Assert.len(hours, 3) +Assert.eq(hours[1].startOfHour, 0) +Assert.eq(hours[1].readingTime, 10) +Assert.eq(hours[2].startOfHour, 3600) +Assert.eq(hours[2].readingTime, 10) +Assert.eq(hours[3].startOfHour, 7200) +Assert.eq(hours[3].readingTime, 10) + +-- 离线批量的外层签名是 sha256(timestamp + token + random),不是单本 guest 签名。 +local sha256 = require("ffi/sha2").sha256 +local batch = App.batchBody({ { bookId = "1" } }, "trouble") +Assert.eq(batch.books[1].bookId, "1") +Assert.eq(batch.recordCreateTimeZone, App.timeZone()) +Assert.eq(batch.signature, sha256(tostring(batch.timestamp) .. "trouble" .. tostring(batch.random))) + +-- 没有小时桶时 payload 以 _ 结尾,和 App generatePayLoad 一致。有小时桶时这个 _ 就是分隔符,不能再多一个。 +local old_time, old_random = os.time, math.random +os.time = function() return 1700000000 end +math.random = function() return 7 end +local empty = App.readBody({ + vid = "1", device_id = "d", install_id = "i", guest_token = "gt", + book_id = "b", chapter_uid = 1, chapter_idx = 1, chapter_offset = 0, + chapter_progress = 0, current_progress = 0, progress = 0, hours = {}, +}) +local empty_payload = table.concat({ "1", "d", "d", "b", "0", App.timeZone(), "0", "0" }, "_") .. "_" +Assert.eq(empty.signature, App.sign({ "gt", "7", "1700000000", empty_payload })) +Assert.is_nil(empty.readUpdateTime) +Assert.is_nil(empty.isResendReadingInfo) +local spanned = App.readBody({ + vid = "1", device_id = "d", install_id = "i", guest_token = "gt", + book_id = "b", chapter_uid = 1, chapter_idx = 1, chapter_offset = 0, + chapter_progress = 0, current_progress = 40, progress = 99, + hours = { { startOfHour = 3600, readingTime = 5, timeZone = "+08:00", ttsTime = 0 } }, + resend = 1, read_update = 1699990000, +}) +local spanned_payload = table.concat({ + "1", "d", "d", "b", "0", App.timeZone(), "5", "0", "3600", "+08:00", "5", "0", +}, "_") +Assert.eq(spanned.signature, App.sign({ "gt", "7", "1700000000", spanned_payload })) +Assert.eq(spanned.progress, 99) +Assert.eq(spanned.currentProgress, 40) +Assert.eq(spanned.readUpdateTime, 1699990000) +Assert.eq(spanned.isResendReadingInfo, 1) +os.time, math.random = old_time, old_random diff --git a/tests/weread/assets_spec.lua b/tests/weread/assets_spec.lua new file mode 100644 index 0000000..60a13e3 --- /dev/null +++ b/tests/weread/assets_spec.lua @@ -0,0 +1,236 @@ +--[[-- +moonsource_weread.assets 离线用例 + +@module tests.moonsource_weread.assets_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") + +package.preload["moonsource_weread.assets"] = nil +package.loaded["moonsource_weread.assets"] = nil +package.preload["moonsource_weread.auth"] = nil +package.loaded["moonsource_weread.auth"] = nil + +local Assets = require("moonsource_weread.assets") + +local function noStyle() + error("不该拉样式表") +end + +do + local html = '' + local out = require("source.assets").rewriteImageSources(html, { + ["foo.jpg"] = "images/aaa.png", + ["https://cdn/x.png"] = "images/bbb.png", + }) + Assert.matches(out, 'src="images/aaa.png"') + Assert.matches(out, 'src="images/bbb.png"') +end + +local function tarHeader(name, size) + local h = string.rep("\0", 512) + local function poke(off, s) + h = h:sub(1, off - 1) .. s .. h:sub(off + #s) + end + poke(1, name:sub(1, 100)) + poke(125, string.format("%011o", size)) + poke(157, "0") + poke(258, "ustar\x00") + poke(264, "00") + local sum = 0 + for i = 1, 512 do + sum = sum + h:byte(i) + end + poke(149, string.format("%06o\0 ", sum)) + return h +end + +local function makeTar(name, data) + local padded = data .. string.rep("\0", (512 - (#data % 512)) % 512) + return tarHeader(name, #data) .. padded .. string.rep("\0", 1024) +end + +do + local png = "\137PNG\r\n\026\n" .. string.rep("x", 32) + local tar = makeTar("pic.png", png) + package.preload["moonsource_weread.auth"] = function() + return { + webGetAsync = function(url, _opts, cb) + if url:find("/tar/", 1, true) then + cb(tar) + else + cb(nil, "unexpected url") + end + end, + } + end + package.loaded["moonsource_weread.auth"] = nil + package.loaded["moonsource_weread.assets"] = nil + Assets = require("moonsource_weread.assets") + + local done, html_out = false, nil + Assets.localizeAsync("book-1", { + uid = "u1", + tar = "/web/book/chapter/tar/abc", + }, '', "https://weread.qq.com/web/reader/1/u1", noStyle, function(html) + done = true + html_out = html + end) + Assert.is_true(done) + Assert.matches(html_out, 'src="images/[0-9a-f]+%.png"') +end + +do + local png = "\137PNG\r\n\026\n" .. string.rep("y", 16) + local remote = "https://res.weread.qq.com/wrepub/CB_test.png" + package.preload["moonsource_weread.auth"] = function() + return { + webGetAsync = function(url, opts, cb) + Assert.eq(url, remote) + Assert.is_true(opts.skip_auth_retry) + Assert.is_true(opts.allow_redirects) + Assert.eq(opts.headers["Referer"], "https://weread.qq.com/") + cb(png) + end, + } + end + package.loaded["moonsource_weread.auth"] = nil + package.loaded["moonsource_weread.assets"] = nil + Assets = require("moonsource_weread.assets") + + local sample = string.format( + '
', + remote + ) + local done, html_out = false, nil + Assets.localizeAsync("book-2", { uid = "u2" }, sample, "https://weread.qq.com/web/reader/2/u2", noStyle, + function(html) + done = true + html_out = html + end) + Assert.is_true(done) + Assert.matches(html_out, 'src="images/[0-9a-f]+%.png"') + Assert.is_false(require("utils.text").hasRemoteImageSrc(html_out)) +end + +-- 脚注图标 + 整书样式表:只改 src / href,其余字节原样;样式表每本书只拉一次。 +-- 拉不到时去掉坏相对 link,注入 .content 兜底缩进(否则段首顶格)。 +do + local Paths = require("utils.paths") + local work_dir = Paths.bookWorkDir("book-3", "ext.weread") + os.remove(work_dir .. "/stylesheets.css") + local head = '' + local link = '' + local abs = '' + local fix = "" + local fallback = "" + local body = '

正文注文

' + local sample = head .. link .. abs .. body + + local fetches = 0 + local function fetchStyle(css) + return function(done) + fetches = fetches + 1 + done(css) + return { cancel = function() end } + end + end + local function run(fetch) + local out + Assets.localizeAsync("book-3", { uid = "u3" }, sample, nil, fetch, function(html) out = html end) + return out + end + + local failed = run(fetchStyle(nil)) + Assert.eq(fetches, 1) + Assert.is_nil(failed:find(link, 1, true), "拉不到样式表去掉坏相对 link") + Assert.is_true(failed:find(abs, 1, true) ~= nil, "绝对 css link 保留") + Assert.is_true(failed:find("text-indent:2em", 1, true) ~= nil, "注入兜底缩进") + Assert.is_true(failed:find(fallback, 1, true) ~= nil, "兜底样式整段写入") + Assert.is_nil(io.open(work_dir .. "/stylesheets.css", "rb")) + + local out = run(fetchStyle(".content{text-indent:2em}")) + Assert.eq(fetches, 2) + local icon = out:match('src="(images/[0-9a-f]+%.png)"') + Assert.is_true(icon ~= nil, "脚注图标落地") + local f = assert(io.open(work_dir .. "/" .. icon, "rb")) + Assert.eq(f:read(4), "\137PNG") + f:close() + Assert.eq(out, head .. '' .. abs .. fix + .. body:gsub("%.%./Images/note%.png", icon)) + f = assert(io.open(work_dir .. "/stylesheets.css", "rb")) + Assert.eq(f:read("*a"), ".content{text-indent:2em}") + f:close() + + Assert.eq(run(fetchStyle("不该再拉")), out, "已缓存直接改链接") + Assert.eq(fetches, 2) +end + +-- 章首页:body.bgimg-1 的开头出血图丢掉,连续 h1 包进整页容器;样式表里 ../Images/ 改指工作目录 images/ +do + local Paths = require("utils.paths") + local work_dir = Paths.bookWorkDir("book-4", "ext.weread") + Paths.ensureDir(work_dir) + os.remove(work_dir .. "/stylesheets.css") + local src = '' + .. '\n

\n' + .. '

第

\n

一

\n

正文

' + local out + Assets.localizeAsync("book-4", { uid = "u4" }, src, nil, function(done) + done("a{background:url(../Images/bq.jpg)}") + return { cancel = function() end } + end, function(html) out = html end) + Assert.is_true(out:find('\n

第

\n' + .. '

一

\n

正文

', 1, true) ~= nil, out) + Assert.is_nil(out:find("bleed-pic", 1, true)) + local f = assert(io.open(work_dir .. "/stylesheets.css", "rb")) + Assert.eq(f:read("*a"), "a{background:url(images/bq.jpg)}") + f:close() +end + +-- 脚注图标路径不统一:qqreader-footnote 或任意 note.png 都注入自带「注」标,不要求写成 ../Images/note.png +do + local Paths = require("utils.paths") + local cases = { + { book = "book-fn-bare", src = "note.png" }, + { book = "book-fn-images", src = "Images/note.png" }, + { book = "book-fn-parent", src = "../Images/note.png" }, + { book = "book-fn-noclass", src = "note.png", plain = true }, + } + local icons = {} + for _, case in ipairs(cases) do + local html + if case.plain then + html = string.format('

注文

', case.src) + else + html = string.format( + '

注文

', + case.src + ) + end + local out + Assets.localizeAsync(case.book, { uid = "u" }, html, nil, noStyle, function(result) + out = result + end) + local icon = out:match('src="(images/[0-9a-f]+%.png)"') + Assert.is_true(icon ~= nil, "脚注图标落地: " .. case.src) + Assert.is_nil(out:find(case.src, 1, true), "原路径被改写: " .. case.src) + local work_dir = Paths.bookWorkDir(case.book, "ext.weread") + local f = assert(io.open(work_dir .. "/" .. icon, "rb")) + Assert.eq(f:read(4), "\137PNG") + f:close() + icons[#icons + 1] = icon + end + for i = 2, #icons do + Assert.eq(icons[i], icons[1], "同一自带图标,内容寻址复用") + end +end diff --git a/tests/weread/auth_spec.lua b/tests/weread/auth_spec.lua new file mode 100644 index 0000000..bb5839b --- /dev/null +++ b/tests/weread/auth_spec.lua @@ -0,0 +1,537 @@ +--[[-- +moonsource_weread.auth 离线用例:会话请求头 / 登录门禁 / 自动续期重试。 + +每个用例用 freshAuth() 重 require 隔离。 +登录态 = Eink 会话(wr_skey + eink.refresh_token),扫码与续期细节见 eink_spec。 + +@module tests.wechat_auth_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") + +local original_json_preload = package.preload["json"] + +-- 可变测试状态:settings / Request.request / json.decode 全部走这里 +local state = { + cfg = {}, + saved = nil, + request_impl = nil, + json_map = {}, +} + +package.preload["utils.settings"] = function() + return { + getSource = function() + return state.cfg + end, + saveSource = function(_id, c) + state.saved = c + end, + } +end + +package.preload["http.request"] = function() + return { + -- 语义对齐 http/request.lua 的 Request.ok + ok = function(code) + local n = tonumber(code) + return n ~= nil and n >= 200 and n < 300 + end, + header = function(res, name) + local headers = res and res.headers + if not headers then + return nil + end + return headers[name] or headers[name:lower()] + end, + request = function(opts, cb) + return state.request_impl(opts, cb) + end, + } +end + +package.preload["json"] = function() + return { + encode = function() + return "{}" + end, + -- 罐装映射:未登记的串视为非法 JSON(与真实 decode 报错同路径) + decode = function(s) + local v = state.json_map[s] + if v == nil then + error("invalid json") + end + return v + end, + } +end + +-- http.header 用真实模块(纯 Lua,header_spec 已验证可独立加载) + +-- 全量跑时前面的 spec 可能已把 stub 版 json/http.request 留在 package.loaded, +-- 这里强制清掉,让上面的 package.preload 生效 +for _, name in ipairs({ "json", "http.request", "utils.settings" }) do + package.loaded[name] = nil +end + +--- 重 require auth,重置包级续期状态;eink 为 nil 时用真实 moonsource_weread.eink。 +---@param cfg table|nil +---@param eink table|nil +---@return table +local function freshAuth(cfg, eink) + state.cfg = cfg or {} + state.saved = nil + package.loaded["moonsource_weread.auth"] = nil + if eink and not eink.refreshing then + -- 真实 Eink.refreshAsync 自带单飞(并发续期共用一次 /login);桩照此包一层。 + local raw, waiters = eink.refreshAsync, nil + eink.refreshing = function() return waiters ~= nil end + eink.refreshAsync = function(cb) + if waiters then waiters[#waiters + 1] = cb return end + waiters = { cb } + raw(function(ok, err, rejected) + local list = waiters + waiters = nil + for _idx, w in ipairs(list) do w(ok, err, rejected) end + end) + end + end + package.loaded["moonsource_weread.eink"] = eink + return require("moonsource_weread.auth") +end + +--- Eink 扫码会话:wr_skey + refresh_token 才算登录。 +---@param extra table|nil +---@return table +local function loggedIn(extra) + local cfg = { wr_vid = "1", wr_skey = "s", eink = { refresh_token = "rt", device_id = "dev" } } + for k, v in pairs(extra or {}) do cfg[k] = v end + return cfg +end + +------------------------------------------------------------------------ +-- Auth.sessionHeaders:Cookie 只拼 Eink 会话的 wr_vid / wr_skey;旧网页残留字段不发 +------------------------------------------------------------------------ + +do + local auth = freshAuth(loggedIn({ wr_vid = "88", wr_skey = "sk", wr_gid = "g", wr_fp = "f", wr_rt = "r" })) + local h = auth.sessionHeaders({ ["X-Custom"] = "c" }) + Assert.eq(h["Cookie"], "wr_vid=88; wr_skey=sk; wr_ql=0") + Assert.eq(h["X-Vid"], "88") + Assert.eq(h["X-Skey"], "sk") + Assert.eq(h["X-Custom"], "c") + -- 浏览器默认头 + Assert.eq(h["Referer"], "https://weread.qq.com/") + Assert.not_nil(h["User-Agent"]) + + -- extra 覆盖默认 Referer + local h2 = auth.sessionHeaders({ ["Referer"] = "https://example.com/" }) + Assert.eq(h2["Referer"], "https://example.com/") + + -- 无 Eink 会话(含旧网页会话):只有浏览器头 + for _, cfg in ipairs({ {}, { wr_vid = "1", wr_skey = "s", wr_gid = "g" } }) do + local h3 = freshAuth(cfg).sessionHeaders() + Assert.is_nil(h3["Cookie"]) + Assert.is_nil(h3["X-Vid"]) + Assert.is_nil(h3["X-Skey"]) + Assert.not_nil(h3["User-Agent"]) + end +end + +------------------------------------------------------------------------ +-- hasSession / userLabel +------------------------------------------------------------------------ + +do + Assert.is_true(freshAuth(loggedIn()).hasSession()) + -- 只有网页会话(旧网页扫码登录)不算:必须重新 Eink 扫码 + Assert.is_false(freshAuth({ wr_skey = "s", wr_vid = "1" }).hasSession(), "旧网页会话需重新登录") + Assert.is_false(freshAuth(loggedIn({ wr_skey = "" })).hasSession()) + Assert.is_false(freshAuth({ cookie = "wr_gid=1; wr_skey=abc" }).hasSession(), "整段 cookie 串不算会话") + Assert.is_false(freshAuth({}).hasSession()) + + Assert.eq(freshAuth({ user_name = "阿明", user_id = "9" }).userLabel(), "阿明") + -- user_name 空 → 回退 user_id + Assert.eq(freshAuth({ user_name = "", user_id = 9 }).userLabel(), "9") + Assert.is_nil(freshAuth({}).userLabel()) +end + +------------------------------------------------------------------------ +-- clearSession +------------------------------------------------------------------------ + +do + local cfg = { + wr_vid = "v", wr_skey = "s", wr_rt = "r", + wr_gid = "g", wr_fp = "f", wr_ql = "1", + user_id = "u", user_name = "n", + api_key = "k", skill_version = "sv", cookie = "c", other = "keep", + } + local auth = freshAuth(cfg) + auth.clearSession() + for _, k in ipairs({ + "wr_vid", "wr_skey", "wr_rt", + "wr_gid", "wr_fp", "wr_ql", "user_id", "user_name", + "api_key", "skill_version", "cookie", + }) do + Assert.eq(cfg[k], "") + end + -- 无关字段不动 + Assert.eq(cfg.other, "keep") + -- 已落盘 + Assert.eq(state.saved, cfg) +end + +-- Eink 扫码会话:退出同时清 refresh_token,设备 ID 保留(重登沿用同一设备) +do + local cfg = loggedIn() + freshAuth(cfg).clearSession() + Assert.is_nil(cfg.eink.refresh_token) + Assert.eq(cfg.eink.device_id, "dev") +end + +-- 退出清掉进程内 reader 状态:否则换号后同章不再发进入阅读,时长不计。 +do + local auth = freshAuth(loggedIn()) + local Context = require("moonsource_weread.context") + Context.reader("b1", "c1").entered = true + auth.clearSession() + Assert.is_nil(Context.reader("b1", "c1").entered) +end + +------------------------------------------------------------------------ +-- webGetAsync:会话门禁 / 原文透传 / HTTP 错误 +-- +-- JSON 解码与 errcode 判定在 client 层,这里只确认回包原样透传。 +------------------------------------------------------------------------ + +do + -- 未登录:直接回调错误,不发请求 + local auth = freshAuth({}) + state.request_impl = function() + error("request must not be called") + end + local data, err + auth.webGetAsync("https://weread.qq.com/web/test", nil, function(d, e) + data, err = d, e + end) + Assert.is_nil(data) + Assert.eq(err, "请先扫码登录微信读书") + + -- 已登录:URL 拼接 + JSON 成功 + auth = freshAuth(loggedIn()) + local got_url + state.json_map = { ['{"errcode":0,"ok":1}'] = { errcode = 0, ok = 1 } } + state.request_impl = function(opts, cb) + got_url = opts.url + cb({ code = 200, body = '{"errcode":0,"ok":1}' }) + return { cancel = function() end } + end + data, err = nil, nil + auth.webGetAsync("https://weread.qq.com/web/test?x=1", nil, function(d, e) + data, err = d, e + end) + Assert.is_nil(err) + Assert.eq(got_url, "https://weread.qq.com/web/test?x=1") + Assert.eq(data, '{"errcode":0,"ok":1}') + + -- HTTP 非 2xx + state.request_impl = function(_opts, cb) + cb({ code = 500, body = "x" }) + return { cancel = function() end } + end + data, err = nil, nil + auth.webGetAsync("https://weread.qq.com/web/t", nil, function(d, e) + data, err = d, e + end) + Assert.is_nil(data) + Assert.eq(err, "HTTP 500") + + -- 网络错误透传 + state.request_impl = function(_opts, cb) + cb(nil, "timeout") + return { cancel = function() end } + end + data, err = nil, nil + auth.webGetAsync("https://weread.qq.com/web/t", nil, function(d, e) + data, err = d, e + end) + Assert.is_nil(data) + Assert.eq(err, "timeout") +end + +------------------------------------------------------------------------ +-- webPostAsync:Content-Type 默认 +------------------------------------------------------------------------ + +do + local auth = freshAuth(loggedIn()) + local got_opts + state.json_map = { ['{"errcode":0}'] = { errcode = 0 } } + state.request_impl = function(opts, cb) + got_opts = opts + cb({ code = 200, body = '{"errcode":0}' }) + return { cancel = function() end } + end + local data, err + auth.webPostAsync("https://weread.qq.com/web/sync", "{}", nil, function(d, e) + data, err = d, e + end) + Assert.is_nil(err) + Assert.not_nil(data) + Assert.eq(got_opts.method, "POST") + Assert.eq(got_opts.url, "https://weread.qq.com/web/sync") + Assert.eq(got_opts.headers["Content-Type"], "application/json") +end + +------------------------------------------------------------------------ +-- 会话失效自动续期(Eink refreshToken)+ 重试一次,重试用新 Cookie +------------------------------------------------------------------------ + +do + local refreshed = 0 + local auth = freshAuth(loggedIn({ wr_skey = "old" }), { + hasSession = function() return true end, + credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end, + refreshAsync = function(cb) + refreshed = refreshed + 1 + state.cfg.wr_skey = "newkey" + cb(true) + end, + }) + local cookies = {} + state.json_map = { + ['{"errcode":-2012,"errmsg":"登录态失效"}'] = { errcode = -2012, errmsg = "登录态失效" }, + ['{"errcode":0,"ok":1}'] = { errcode = 0, ok = 1 }, + } + state.request_impl = function(opts, cb) + cookies[#cookies + 1] = opts.headers["Cookie"] + if #cookies == 1 then + cb({ code = 200, body = '{"errcode":-2012,"errmsg":"登录态失效"}' }) + else + cb({ code = 200, body = '{"errcode":0,"ok":1}' }) + end + return { cancel = function() end } + end + local data, err, resp + auth.webGetAsync("https://weread.qq.com/web/retry", nil, function(d, e, r) + data, err, resp = d, e, r + end) + Assert.is_nil(err) + Assert.eq(data, '{"errcode":0,"ok":1}') + Assert.eq(resp.json.ok, 1, "判失效时解过的 JSON 经 res.json 交给调用方,不必再解") + Assert.eq(refreshed, 1) + Assert.eq(#cookies, 2) + Assert.is_true(cookies[1]:find("wr_skey=old", 1, true) ~= nil) + Assert.is_true(cookies[2]:find("wr_skey=newkey", 1, true) ~= nil) +end + +-- 续期冷却:冷却内再遇失效回包(如 WAF 403)不再打 /login,只用现有令牌重试一次。 +do + local refreshed = 0 + local auth = freshAuth(loggedIn(), { + hasSession = function() return true end, + credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end, + refreshAsync = function(cb) + refreshed = refreshed + 1 + cb(true) + end, + }) + local requests = 0 + state.json_map = {} + state.request_impl = function(_opts, cb) + requests = requests + 1 + cb({ code = 403, body = "blocked" }) + return { cancel = function() end } + end + local errs = {} + for _i = 1, 3 do + auth.webGetAsync("https://weread.qq.com/web/x", nil, function(_raw, e) errs[#errs + 1] = e end) + end + Assert.eq(refreshed, 1, "冷却内只续期一次") + Assert.eq(requests, 6, "每个请求仍各重试一次") + Assert.eq(errs[3], "HTTP 403") +end + +-- 错误信息只含「超时」不是会话失效,不续期。 +do + local refreshed = 0 + local auth = freshAuth(loggedIn(), { + hasSession = function() return true end, + credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end, + refreshAsync = function(cb) + refreshed = refreshed + 1 + cb(true) + end, + }) + state.json_map = { ['{"errcode":-1,"errmsg":"请求超时"}'] = { errcode = -1, errmsg = "请求超时" } } + state.request_impl = function(_opts, cb) + cb({ code = 200, body = '{"errcode":-1,"errmsg":"请求超时"}' }) + return { cancel = function() end } + end + auth.webGetAsync("https://weread.qq.com/web/t", nil, function() end) + Assert.eq(refreshed, 0) +end + +-- 续期等待中取消:不再发重试请求,也不回调;取消落到当前这次请求上。 +do + local finish_refresh + local auth = freshAuth(loggedIn({ wr_skey = "old" }), { + hasSession = function() return true end, + credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end, + refreshAsync = function(cb) finish_refresh = cb end, + }) + state.json_map = { + ['{"errcode":-2012,"errmsg":"登录态失效"}'] = { errcode = -2012, errmsg = "登录态失效" }, + } + local requests = 0 + state.request_impl = function(_opts, cb) + requests = requests + 1 + cb({ code = 200, body = '{"errcode":-2012,"errmsg":"登录态失效"}' }) + return { cancel = function() end } + end + local called = false + local job = auth.webGetAsync("https://weread.qq.com/web/cancel", nil, function() called = true end) + job.cancel() + finish_refresh(true) + Assert.eq(requests, 1) + Assert.is_false(called) +end + +-- 续期失败:不重试,Eink 的续期错误原样回给调用方。 +do + local auth = freshAuth(loggedIn(), { + hasSession = function() return true end, + credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end, + refreshAsync = function(cb) cb(false, "登录失败 -2013") end, + }) + state.json_map = { + ['{"errcode":-2012,"errmsg":"登录态失效"}'] = { errcode = -2012, errmsg = "登录态失效" }, + } + local requests = 0 + state.request_impl = function(_opts, cb) + requests = requests + 1 + cb({ code = 200, body = '{"errcode":-2012,"errmsg":"登录态失效"}' }) + return { cancel = function() end } + end + local data, err + auth.webGetAsync("https://weread.qq.com/web/fail", nil, function(d, e) data, err = d, e end) + Assert.eq(requests, 1) + Assert.is_nil(data) + Assert.eq(err, "登录失败 -2013") +end + +-- 只有真失效才判登录失效:记下 expire 调用(替身,用完还原) +local real_source_auth = package.loaded["source.auth"] +local expired = {} +package.loaded["source.auth"] = { + expire = function(id, msg) expired[#expired + 1] = id; return msg end, + ok = function() end, +} +local AUTH_FAIL = '{"errcode":-2012,"errmsg":"登录态失效"}' + +-- 续期失败的归因:服务器明确拒绝才判登录失效;超时 / 断网只回错误。 +for _idx, case in ipairs({ { rejected = true, expect = 1 }, { rejected = nil, expect = 0 } }) do + expired = {} + local auth = freshAuth(loggedIn({ wr_skey = "old" }), { + hasSession = function() return true end, + credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end, + refreshAsync = function(cb) cb(false, "boom", case.rejected) end, + }) + state.json_map = { [AUTH_FAIL] = { errcode = -2012, errmsg = "登录态失效" } } + state.request_impl = function(_opts, cb) + cb({ code = 200, body = AUTH_FAIL }) + return { cancel = function() end } + end + local err + auth.webGetAsync("https://weread.qq.com/web/x", nil, function(_d, e) err = e end) + -- 明确拒绝:中文失效文案(接口原文 boom 只打日志);超时/断网原样回错误。 + if case.rejected then Assert.matches(err, "扫一扫") else Assert.eq(err, "boom") end + Assert.len(expired, case.expect) +end + +-- 并发竞态(日志 22:14:17):A 回失效触发续期,续期在飞时 B 也回失效。 +-- B 必须等续期结果再用新令牌重试;以前冷却直接让 B 拿旧令牌重试 → 再失效 → 误判登录失效。 +do + local finish, refreshed = nil, 0 + local auth = freshAuth(loggedIn({ wr_skey = "old" }), { + hasSession = function() return true end, + credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end, + refreshAsync = function(cb) refreshed = refreshed + 1; finish = cb end, + }) + state.json_map = { [AUTH_FAIL] = { errcode = -2012, errmsg = "登录态失效" } } + local cookies = {} + state.request_impl = function(opts, cb) + cookies[#cookies + 1] = opts.headers["Cookie"] + cb({ code = 200, body = opts.headers["Cookie"]:find("wr_skey=old", 1, true) and AUTH_FAIL or "ok" }) + return { cancel = function() end } + end + local got = {} + auth.webGetAsync("https://weread.qq.com/web/shelf/sync", nil, function(d, e) got[#got + 1] = d or e end) + auth.webGetAsync("https://weread.qq.com/web/mp/articles", nil, function(d, e) got[#got + 1] = d or e end) + Assert.eq(refreshed, 1, "只续期一次") + Assert.len(got, 0, "B 在等续期,没有拿旧令牌重试") + state.cfg.wr_skey = "newkey" + finish(true) + Assert.eq(table.concat(got, ","), "ok,ok") + Assert.len(cookies, 4) + Assert.len(expired, 0, "没有误判登录失效") +end + +-- 请求在飞时令牌已被别的请求续期换掉:回失效就直接用新令牌重试,不再打 /login +do + local refreshed = 0 + local auth = freshAuth(loggedIn({ wr_skey = "old" }), { + hasSession = function() return true end, + credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end, + refreshAsync = function(cb) refreshed = refreshed + 1; cb(true) end, + }) + state.json_map = { [AUTH_FAIL] = { errcode = -2012, errmsg = "登录态失效" } } + local pending = {} + state.request_impl = function(opts, cb) + pending[#pending + 1] = { cookie = opts.headers["Cookie"], cb = cb } + return { cancel = function() end } + end + local data + auth.webGetAsync("https://weread.qq.com/web/x2", nil, function(d) data = d end) + state.cfg.wr_skey = "rotated" + pending[1].cb({ code = 200, body = AUTH_FAIL }) + Assert.eq(refreshed, 0) + Assert.is_true(pending[2].cookie:find("wr_skey=rotated", 1, true) ~= nil) + pending[2].cb({ code = 200, body = "fine" }) + Assert.eq(data, "fine") +end + +-- no_expire(公众号接口):续期重试后仍回失效 errcode → 只回错误,不判整个微信读书登录失效 +do + local auth = freshAuth(loggedIn(), { + hasSession = function() return true end, + credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end, + refreshAsync = function(cb) cb(true) end, + }) + state.json_map = { [AUTH_FAIL] = { errcode = -2012, errmsg = "登录态失效" } } + state.request_impl = function(_opts, cb) + cb({ code = 200, body = AUTH_FAIL }) + return { cancel = function() end } + end + local err + auth.webGetAsync("https://weread.qq.com/web/mp/articles", { no_expire = true }, function(_d, e) err = e end) + Assert.eq(err, "微信读书拒绝了请求,请稍后再试") + Assert.len(expired, 0) + -- 普通接口照旧判失效 + auth.webGetAsync("https://weread.qq.com/web/shelf/sync", nil, function(_d, e) err = e end) + Assert.matches(err, "扫一扫") + Assert.eq(table.concat(expired, ","), "ext.weread") +end +package.loaded["source.auth"] = real_source_auth + +------------------------------------------------------------------------ +-- 清理:恢复本文件改动的 preload / loaded,避免污染同进程后续用例 +------------------------------------------------------------------------ + +for _, name in ipairs({ "utils.settings", "http.request", "json", "moonsource_weread.auth", "moonsource_weread.eink" }) do + package.preload[name] = nil + package.loaded[name] = nil +end +package.preload["json"] = original_json_preload diff --git a/tests/weread/chapter_spec.lua b/tests/weread/chapter_spec.lua new file mode 100644 index 0000000..7f25b28 --- /dev/null +++ b/tests/weread/chapter_spec.lua @@ -0,0 +1,510 @@ +--[[-- +微信章节正文的 range 坐标原文与 reader 状态回归测试。 + +@module tests.moonsource_weread.chapter_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") + +package.preload["json"] = function() + return { + encode = require("support.json_stub").encode, + decode = require("support.json_stub").decode, + } +end + +local queries = {} +local app_err = nil +local trial = false +local bom = false +local txt_zip = false +local zip_text_missing = false +local info_requests = {} +local app_response + +package.preload["workers.job"] = function() + return { + run = function(fn, opts) + opts.on_done(fn()) + return { cancel = function() end } + end, + } +end + +package.preload["http.request"] = function() + return { + header = function() return "encrypt-key" end, + ok = function(code) return type(code) == "number" and code >= 200 and code < 300 end, + } +end + +package.preload["moonsource_weread.eink"] = function() + return { + credentials = function() return { vid = "42" } end, + callAsync = function(method, path, opts, cb) + if path == "/book/info" then + info_requests[#info_requests + 1] = opts.query + else + queries[#queries + 1] = opts.query + end + if app_response then return app_response(method, path, opts, cb) end + if path == "/book/info" then + cb({ book = { version = 7 } }) + return { cancel = function() end } + end + if app_err then + cb(nil, app_err) + else + local body + if opts.query.bookType == "txt" and not txt_zip then + body = string.rep("\0", 257) .. "ustar" + else + body = "PK" + end + cb({ body = body, code = 200 }) + end + return { cancel = function() end } + end, + } +end + +package.preload["moonsource_weread.auth"] = function() + return { + hasSession = function() return true end, + webPostAsync = function() error("chapter download must not fall back to the web reader") end, + webGetAsync = function() error("chapter download must not fall back to the web reader") end, + } +end + +local FULL = '' + .. '' + .. '

1

正文' + .. '注

' + .. '\n' + .. '

第二段文档

' +local PLAIN = "\239\187\191第一行 \n 第二行" +local TRIAL = "“第四路,已过浔阳!”\n这是李善德发明的脚程格眼。..." + +package.preload["moonsource_weread.protocol"] = function() + return { + readerUrl = function() return "https://weread.qq.com/web/reader/id" end, + } +end + +package.preload["moonsource_weread.package"] = function() + return { + password = function() return "pw" end, + unzipNeed = function() return 0 end, + formatChaptersParam = function(uids) + uids = uids or {} + if #uids == 0 then return "0" end + local nums = {} + for i, u in ipairs(uids) do + local n = tonumber(u) + if not n then + local parts = { "0" } + for _idx, x in ipairs(uids) do parts[#parts + 1] = tostring(x) end + return table.concat(parts, ",") + end + nums[i] = n + end + local ok = true + for i = 2, #nums do if nums[i] ~= nums[i - 1] + 1 then ok = false break end end + if ok then + local a, b = nums[1], nums[#nums] + if a == 1 then return "0-" .. b end + if a == b then return "0," .. a end + return "0," .. a .. "-" .. b + end + local parts = { "0" } + for _idx, n in ipairs(nums) do parts[#parts + 1] = tostring(n) end + return table.concat(parts, ",") + end, + extractChapters = function(files, _book, uids, book_type) + local out, style = {}, files["Styles/stylesheets.css"] + for _idx, uid in ipairs(uids) do + local html = FULL + if trial then html = TRIAL elseif bom then html = "98791" .. FULL end + -- keep real BOM via bytes below in separate fix + out[tostring(uid)] = { text = html, format = book_type == "txt" and "txt" or "html" } + end + return out, style + end, + unzip = function() + local q = queries[#queries] + local ch = tostring(q.chapters or "") + if ch == "0" or ch:find("^0%-") or ch:find("^0,") then + return { ["Styles/stylesheets.css"] = ".content{text-indent:2em}", dummy = true } + end + return { dummy = true } + end, + pickStyle = function(files) + return files["Styles/stylesheets.css"] or files["Styles/stylesheet.css"] + end, + chapterHtml = function() + if txt_zip then error("TXT ZIP with text entry must not fall back to chapterHtml") end + if trial then return TRIAL end + if bom then return "\239\187\191" .. FULL end + return FULL + end, + chapterText = function() return PLAIN end, + chapterZipText = function() + if txt_zip and not zip_text_missing then return PLAIN end + return nil + end, + } +end + +package.preload["moonsource_weread.assets"] = function() + return { + localizeAsync = function(_book, _chapter, html, _referer, fetch_style, cb) + return fetch_style(function(css) + Assert.eq(css, ".content{text-indent:2em}") + cb((html:gsub("https://res%.weread%.qq%.com/x%.png", "images/x.png"))) + end) + end, + } +end + +for _, name in ipairs({ + "workers.job", "http.request", "moonsource_weread.eink", "moonsource_weread.package", "moonsource_weread.chapter", +}) do + package.loaded[name] = nil +end +local Chapter = require("moonsource_weread.chapter") +local Context = require("moonsource_weread.context") +Context.clear() +Context.rememberBookVersion("book", 7) + +do + -- EPUB:解码后的 xhtml 原样交出,不抽 body、不删虚线 / title、不改脚注;range 坐标原文同一份。 + local html_out, range_source, format + Chapter.fetchHtmlAsync("book", { uid = "chapter" }, function(html, err, raw, fmt) + Assert.is_nil(err) + html_out, range_source, format = html, raw, fmt + end) + Assert.eq(html_out, FULL) + Assert.eq(range_source, FULL) + Assert.eq(format, "html") + Assert.eq(#queries, 1) + Assert.eq(queries[1].bookType, "epub") + Assert.eq(queries[1].chapters, "chapter") + Assert.eq(queries[1].bookVersion, 7) + Assert.eq(queries[1].offline, "0", "单章在线阅读 offline=0") +end + +do + -- TXT:bookType=txt,range 按包内纯文本逐 rune 计,段落化后的 HTML 只用于显示。 + local body, range_source, format + Chapter.fetchHtmlAsync("book", { uid = "c2", format = "txt" }, function(html, err, raw, fmt) + Assert.is_nil(err) + body, range_source, format = html, raw, fmt + end) + Assert.eq(range_source, PLAIN) + Assert.eq(format, "txt") + Assert.is_true(body:find("

", 1, true) ~= nil) + -- 段首空白只在显示用 HTML 里剥掉,缩进统一由 CSS 给。 + Assert.is_true(body:find("

第二行

", 1, true) ~= nil) + Assert.eq(queries[#queries].bookType, "txt") + Assert.eq(queries[#queries].chapters, "c2") +end + +do + -- 交给宿主:EPUB 是整份 document,只改资源引用;TXT 仍是 html 片段走外壳。 + local payload + local before = #queries + Chapter.fetchContentAsync("book", { idx = 1, uid = "chapter", title = "第一章" }, function(p) payload = p end) + -- 正文一次,样式表一次(chapters=0),没有网页分片。 + Assert.eq(queries[before + 1].chapters, "chapter") + Assert.eq(queries[before + 1].bookType, "epub") + Assert.eq(queries[before + 2].chapters, "0") + Assert.is_nil(payload.html) + local note = '注' + local expected = FULL:gsub("https://res%.weread%.qq%.com/x%.png", "images/x.png") + :gsub(note:gsub("%p", "%%%0"), '' + .. '注') + -- 两份拼接文档:aside 进最后一个 body;epub:type 让 KOReader 页内脚注 / 弹窗都能认。 + :gsub("

第二段文档

", + '

第二段文档

\n') + Assert.eq(payload.document, expected) + -- 脚注图标尺寸不依赖整书样式表:行内 style 压到 0.8em 上标,原有 style 被替换。 + Assert.is_true(payload.document:find('height:0.8em', 1, true) ~= nil) + + Chapter.fetchContentAsync("book", { idx = 2, uid = "c2", format = "txt", title = "第2章 想<整>我" }, function(p) payload = p end) + Assert.is_nil(payload.document) + -- TXT 正文不带章名:章首补 h1(转义),EPUB 原文自带标题不补。 + local heading = "

第2章 想<整>我

" + Assert.eq(payload.html:sub(1, #heading), heading) + Assert.is_true(payload.html:find("

", 1, true) ~= nil) +end + +do + -- 脚注链接带原文件名:锚点在本章里就改成 #锚点,不在的(跨章)只留文字 + local saved = FULL + FULL = FULL:gsub("\n<%?xml", '

[1][2]

' + .. '

注文

\n[1]', 1, true) ~= nil) + Assert.is_nil(payload.document:find("zhushi", 1, true)) + Assert.is_true(payload.document:find("[2]", 1, true) ~= nil) +end + +do + -- 跨章注释链接里的图标:找不到注文也要限制尺寸,否则样式表缺规则时显示成大方块 + local saved = FULL + FULL = FULL:gsub("\n<%?xml", '

总之

\n[116]当时多用沙子&吸干墨迹。

' + .. '

无锚点

[117]

') + Assert.eq(notes.zhu116, "当时多用沙子&吸干墨迹。") + Assert.is_nil(notes.zhu117) +end + +do + -- 无权阅读的付费章:EPUB 通道回纯文本试读片段,必须报错,不能当正文落盘。 + trial = true + local payload, err = "untouched", nil + Chapter.fetchContentAsync("book", { idx = 2, uid = "paid", title = "第二章" }, function(p, e) payload, err = p, e end) + trial = false + Assert.is_nil(payload) + Assert.matches(err, "试读") +end + +do + -- 服务端给 XHTML 带 UTF-8 BOM:是正文,不能当试读片段拒掉。 + bom = true + local payload, err = nil, nil + Chapter.fetchContentAsync("book", { idx = 1, uid = "bom", title = "第一章" }, function(p, e) payload, err = p, e end) + bom = false + Assert.is_nil(err) + Assert.is_true(payload ~= nil) +end + +do + -- App 通道失败就结束,不再改走网页。 + app_err = "加载失败" + local n = #queries + local html_out, err + Chapter.fetchHtmlAsync("book", { uid = "flaky" }, function(h, e) html_out, err = h, e end) + app_err = nil + Assert.is_nil(html_out) + Assert.eq(err, "加载失败") + Assert.eq(#queries, n + 1) +end + +do + -- 部分 TXT 章回包是加密 ZIP(非 ustar):走 chapterZipText,不按 HTML 清单解析。 + txt_zip = true + local body, range_source, format, err + Chapter.fetchHtmlAsync("book", { uid = "1595", format = "txt" }, function(html, e, raw, fmt) + body, err, range_source, format = html, e, raw, fmt + end) + txt_zip = false + Assert.is_nil(err) + Assert.eq(range_source, PLAIN) + Assert.eq(format, "txt") + Assert.is_true(body:find("

", 1, true) ~= nil) + Assert.eq(queries[#queries].bookType, "txt") +end + +do + -- 未缓存的书先拿真实版本,下一章直接复用,不把 0 当通用版本。 + local before = #info_requests + Chapter.fetchHtmlAsync("fresh-book", { uid = "1" }, function(html, err) + Assert.is_nil(err) + Assert.eq(html, FULL) + end) + Assert.eq(queries[#queries].bookVersion, 7) + Chapter.fetchHtmlAsync("fresh-book", { uid = "2" }, function(html, err) + Assert.is_nil(err) + Assert.eq(html, FULL) + end) + Assert.eq(#info_requests, before + 1) +end + +do + -- -2063 的 info.bookVersion 直接用于唯一一次重试,不额外拉详情。 + local attempts, callbacks, before = 0, 0, #info_requests + Context.rememberBookVersion("updated-book", 3) + app_response = function(_method, path, opts, cb) + Assert.eq(path, "/book/chapterdownload") + attempts = attempts + 1 + if attempts == 1 then + Assert.eq(opts.query.bookVersion, 3) + cb(nil, "version expired", { errcode = -2063, body = { info = { bookVersion = "8" } } }) + else + Assert.eq(opts.query.bookVersion, 8) + cb({ body = "PK", code = 200 }) + end + return { cancel = function() end } + end + Chapter.fetchHtmlAsync("updated-book", { uid = "1" }, function(html, err) + callbacks = callbacks + 1 + Assert.is_nil(err) + Assert.eq(html, FULL) + end) + app_response = nil + Assert.eq(attempts, 2) + Assert.eq(callbacks, 1) + Assert.eq(#info_requests, before) + Assert.eq(Context.bookVersion("updated-book"), 8) +end + +do + -- 回包没有可用新版本(包括 0)时刷新详情;第二次过期直接失败。 + for i, info in ipairs({ {}, { bookVersion = "0" }, { bookVersion = "bad" }, { bookVersion = "4" } }) do + local book_id = "expired-book-" .. i + local attempts, details, callbacks = 0, 0, 0 + Context.rememberBookVersion(book_id, 4) + app_response = function(_method, path, opts, cb) + if path == "/book/info" then + details = details + 1 + cb({ book = { version = 9 } }) + else + attempts = attempts + 1 + Assert.eq(opts.query.bookVersion, attempts == 1 and 4 or 9) + cb(nil, "version expired", { errcode = -2063, body = { info = info } }) + end + return { cancel = function() end } + end + Chapter.fetchHtmlAsync(book_id, { uid = "1" }, function(html, err) + callbacks = callbacks + 1 + Assert.is_nil(html) + Assert.eq(err, "version expired") + end) + app_response = nil + Assert.eq(attempts, 2) + Assert.eq(details, 1) + Assert.eq(callbacks, 1) + end +end + +do + -- 获取版本失败或详情缺字段,必须交出错误,不能假装成功或盲发版本 0。 + for i, reply in ipairs({ { err = "network failed" }, { wire = {}, err = "缺少书籍版本" } }) do + local before = #queries + app_response = function(_method, path, _opts, cb) + Assert.eq(path, "/book/info") + cb(reply.wire, reply.wire and nil or reply.err) + return { cancel = function() end } + end + Chapter.fetchHtmlAsync("bad-info-" .. i, { uid = "1" }, function(html, err) + Assert.is_nil(html) + Assert.eq(err, reply.err) + end) + app_response = nil + Assert.eq(#queries, before) + end +end + +do + -- 详情获取与过期恢复都能取消;迟来的回调不能继续下载或通知结果。 + for _idx, phase in ipairs({ "initial-info", "retry-download", "refresh-info" }) do + local book_id = "cancel-" .. phase + local pending, cancelled_path, callbacks + callbacks = 0 + if phase ~= "initial-info" then Context.rememberBookVersion(book_id, 4) end + local attempts = 0 + app_response = function(_method, path, _opts, cb) + if path == "/book/chapterdownload" then + attempts = attempts + 1 + if attempts == 1 then + local info = phase == "retry-download" and { bookVersion = 9 } or {} + cb(nil, "version expired", { errcode = -2063, body = { info = info } }) + return { cancel = function() error("cancelled stale request") end } + end + end + pending = cb + return { cancel = function() cancelled_path = path end } + end + local handle = Chapter.fetchHtmlAsync(book_id, { uid = "1" }, function() callbacks = callbacks + 1 end) + Assert.not_nil(pending) + handle:cancel() + Assert.eq(cancelled_path, phase == "retry-download" and "/book/chapterdownload" or "/book/info") + local before = #queries + if phase == "retry-download" then pending({ body = "PK", code = 200 }) + else pending({ book = { version = 9 } }) end + Assert.eq(#queries, before) + Assert.eq(callbacks, 0) + app_response = nil + end +end + +do + -- 已开始解包也能取消,Job 的迟到完成/失败不能再交出结果。 + local Job = require("workers.job") + local run = Job.run + for _idx, format in ipairs({ "epub", "txt" }) do + local pending, cancelled, callbacks = nil, false, 0 + Job.run = function(_fn, opts) + pending = opts + return { cancel = function() cancelled = true end } + end + local handle = Chapter.fetchHtmlAsync("book", { uid = "1", format = format }, function() + callbacks = callbacks + 1 + end) + Assert.not_nil(pending) + handle:cancel() + Assert.is_true(cancelled) + pending.on_done({ text = format == "txt" and PLAIN or FULL }) + pending.on_failed("late failure") + Assert.eq(callbacks, 0) + end + Job.run = run +end + +do + -- TXT ZIP 缺正文就报包错误,不能退回 EPUB 清单。 + txt_zip, zip_text_missing = true, true + Chapter.fetchHtmlAsync("book", { uid = "1595", format = "txt" }, function(html, err) + Assert.is_nil(html) + Assert.matches(err, "zip: chapter 1595 not in package") + end) + txt_zip, zip_text_missing = false, false +end + +do + -- 批量:prime 五章 offline=1、chapters=0-5;随后 fetchHtml 不再打网。 + Context.rememberBookVersion("batch-book", 7) + local before = #queries + local chapters = {} + for i = 1, 5 do chapters[i] = { uid = tostring(i), idx = i } end + local ok_out, err_out + Chapter.primeBatchAsync("batch-book", chapters, { offline = true }, function(ok, err) + ok_out, err_out = ok, err + end) + Assert.is_true(ok_out) + Assert.is_nil(err_out) + Assert.eq(queries[before + 1].chapters, "0-5") + Assert.eq(queries[before + 1].offline, "1") + local after_prime = #queries + local html_out + Chapter.fetchHtmlAsync("batch-book", { uid = "3" }, function(html, err) + Assert.is_nil(err) + html_out = html + end) + Assert.eq(#queries, after_prime, "primed 章不得再次请求 chapterdownload") + Assert.eq(html_out, FULL) +end diff --git a/tests/weread/client_spec.lua b/tests/weread/client_spec.lua new file mode 100644 index 0000000..138391c --- /dev/null +++ b/tests/weread/client_spec.lua @@ -0,0 +1,446 @@ +--[[-- +moonsource_weread.client 离线用例:各接口的 URL 与请求体 + +@module tests.moonsource_weread.client_spec +--]] + +local Assert = require("support.assert") + +local captured = {} +local posted = {} + +package.preload["json"] = function() + return { + encode = require("support.json_stub").encode, + decode = require("support.json_stub").decode, + } +end +package.loaded["json"] = nil + +-- 网页接口回原始 JSON 串:解码与 errcode 校验在 client 里真跑 +local web_replies = {} +package.preload["moonsource_weread.auth"] = function() + local decode = require("support.json_stub").decode + return { + webGetAsync = function(url, _opts, cb) + captured[#captured + 1] = url + for pattern, raw in pairs(web_replies) do + if url:find(pattern, 1, true) then + cb(raw) + return { cancel = function() end } + end + end + if url:find("/web/shelf/sync", 1, true) then + cb('{"pureBookCount":1,"bookCount":1,"synckey":0}') + elseif url:find("/web/book/getProgress", 1, true) then + cb('{"bookId":"42","book":{"chapterUid":1,"progress":10}}') + elseif url:find("/web/book/underlines", 1, true) then + cb('{"underlines":[]}') + end + return { cancel = function() end } + end, + webPostAsync = function(url, body, opts, cb) + posted.url = url + posted.raw = body + posted.referer = opts and opts.headers and opts.headers.Referer + local ok, decoded = pcall(decode, body) + posted.body = ok and decoded or nil + if url:find("/review/add", 1, true) then + cb('{"reviewId":"rv-1"}') + elseif url:find("/web/book/read", 1, true) then + cb(posted.web_read_reply or '{"succ":1}') + else + cb('{"succ":1}') + end + return { cancel = function() end } + end, + } +end +package.preload["moonsource_weread.eink"] = function() + return { + callAsync = function(method, path, opts, cb) + posted.eink = { method = method, path = path, query = opts.query, body = opts.body } + if path == "/shelf/sync" then + cb(posted.shelf_reply or { books = {}, archive = {} }) + elseif path == "/book/getProgress" then + cb({ bookId = "42", book = { chapterUid = 1, progress = 10 } }) + elseif path == "/book/underlines" then + cb({ underlines = {} }) + elseif path == "/review/add" then + cb({ reviewId = "rv-1" }) + elseif path == "/feature" then + cb({ feature = { guest_token = "gt" } }) + elseif path == "/book/read" then + cb(posted.read_reply or { succ = 1 }) + elseif path:find("^/book/%a+[Bb]ookmark$") or path:find("^/shelf/") or path == "/review/useredit" + or path == "/review/delete" then + cb({ succ = 1 }) + elseif path == "/book/bookmarklist" then + cb({ + synckey = 1, + updated = { + { chapterUid = 4, range = "303-332", markText = "原文", type = 1 }, + }, + chapters = { { chapterUid = 4, chapterIdx = 4 } }, + }) + elseif path == "/review/list" and opts.query.bookId == "77" then + -- 翻页:hasMore=1 带 maxIdx 续拉,重复 reviewId 去重 + if opts.query.maxIdx == nil then + cb({ totalCount = 2, hasMore = 1, maxIdx = 5, + reviews = { { review = { reviewId = "a", range = "1-2", content = "甲" } } } }) + else + cb({ hasMore = 0, reviews = { + { review = { reviewId = "a", range = "1-2", content = "甲" } }, + { review = { reviewId = "b", range = "3-4", content = "乙" } }, + } }) + end + elseif path == "/review/list" and opts.query.bookId == "88" then + -- App 同款参数被拒(-2003),listType=11 能通 + if opts.query.listType == 1 then + cb(nil, "-2003 参数格式错误") + else + cb({ hasMore = 0, reviews = { { review = { reviewId = "c", content = "丙" } } } }) + end + elseif path == "/store/search" then + cb(posted.search_reply or { data = { { bookInfo = { bookId = "9", title = "三体" } } } }) + elseif path == "/review/list" then + cb({ + totalCount = 3, + reviews = { + { review = { bookId = "99", range = "1-2", content = "本书" } }, + { review = { bookId = "3300107657", range = "464-466", content = "别的书" } }, + { review = { range = "5-6", content = "无 bookId 保留" } }, + }, + }) + else + cb({ + readLongest = { + { book = { bookId = "1" }, readTime = 3600 }, + }, + }) + end + return { cancel = function() end } + end, + } +end +package.loaded["moonsource_weread.eink"] = nil +package.preload["moonsource_weread.client"] = nil +package.loaded["moonsource_weread.client"] = nil + +local client = require("moonsource_weread.client") + +do + -- 书架 / 进度 / 详情 / 目录 / 想法 / 划线全走 App 协议 + local function call(fn, ...) + posted = {} + fn(...) + return posted.eink + end + local wire + local req = call(client.shelfSyncAsync, client, function(d) wire = d end) + Assert.eq(req.method .. req.path, "GET/shelf/sync") + Assert.eq(req.query.album, 1) + Assert.not_nil(wire) + + -- 增量索引:带游标与本地计数,只要 id 不要元数据 + req = call(client.shelfSyncIdsAsync, client, 100, 18, function(d) wire = d end) + Assert.eq(req.method .. req.path, "GET/shelf/sync") + Assert.eq(req.query.synckey, 100) + Assert.eq(req.query.onlyBookid, 1) + Assert.eq(req.query.localBookCount, 18) + + -- 变更补详情:POST /shelf/syncbook 带 bookIds + req = call(client.shelfSyncBooksAsync, client, { "b1", "b2" }, function() end) + Assert.eq(req.method .. req.path, "POST/shelf/syncbook") + Assert.eq(req.body.bookIds[1], "b1") + Assert.eq(req.body.bookIds[2], "b2") + + req = call(client.getProgressAsync, client, "42", function(d) wire = d end) + Assert.eq(req.path, "/book/getProgress") + Assert.eq(req.query.bookId, "42") + Assert.eq(wire.book.progress, 10) + + req = call(client.chapterInfosAsync, client, "42", function() end) + Assert.eq(req.path, "/book/chapterInfos") + Assert.eq(req.body.synckeys[1], 0) + Assert.eq(req.body.bookIds[1], "42") + + req = call(client.bookInfoAsync, client, "42", function() end) + Assert.eq(req.path, "/book/info") + Assert.eq(req.query.bookId, "42") + + req = call(client.addToShelfAsync, client, "123", function() end) + Assert.eq(req.path, "/shelf/add") + Assert.eq(req.body.bookIds[1], "123") + req = call(client.removeFromShelfAsync, client, "123", function() end) + Assert.eq(req.path, "/shelf/delete") + Assert.eq(req.body.bookIds[1], "123") + + req = call(client.saveArchiveAsync, client, 7, "科幻", { "1", "2" }, function() end) + Assert.eq(req.path, "/shelf/archive") + Assert.eq(req.body.archiveId, 7) + Assert.eq(req.body.name, "科幻") + Assert.eq(req.body.bookIds[2], "2") + + req = call(client.addReviewAsync, client, { bookId = "99", content = "想法", range = "1-2" }, + function(d) wire = d end) + Assert.eq(req.path, "/review/add") + Assert.eq(wire.reviewId, "rv-1") + req = call(client.editReviewAsync, client, { reviewId = "rv-1", content = "修改" }, function() end) + Assert.eq(req.path, "/review/useredit") + req = call(client.deleteReviewAsync, client, "rv-1", function() end) + Assert.eq(req.path, "/review/delete") + Assert.eq(req.body.reviewId, "rv-1") + + req = call(client.addBookmarkAsync, client, "99", 8, { bookId = "99", range = "1-6" }, function() end) + Assert.eq(req.path, "/book/addBookmark") + Assert.eq(req.body.range, "1-6") + req = call(client.updateBookmarkAsync, client, { bookmarkId = "bm-1" }, function() end) + Assert.eq(req.path, "/book/updateBookmark") + req = call(client.removeBookmarkAsync, client, "bm-1", function() end) + Assert.eq(req.path, "/book/removeBookmark") + Assert.eq(req.body.bookmarkIds[1], "bm-1", "App 版删除接收 bookmarkIds 数组") + + req = call(client.underlinesAsync, client, "3300055092", "4", function(d) wire = d end) + Assert.eq(req.path, "/book/underlines") + Assert.eq(req.query.chapterUid, "4") + Assert.eq(#wire.underlines, 0) + req = call(client.readReviewsAsync, client, "3300055092", "4", + { { range = "386-407", maxIdx = 0, count = 1, synckey = 0 } }, function() end) + Assert.eq(req.path, "/book/readreviews") + Assert.eq(req.body.chapterUid, 4) + Assert.eq(req.body.reviews[1].range, "386-407") + + req = call(client.searchAsync, client, "三体", function(d) wire = d end) + Assert.eq(req.path, "/store/search") + Assert.eq(req.query.keyword, "三体") + Assert.eq(req.query.v, 2) + Assert.eq(req.query.type, 0) + Assert.eq(wire.books[1].bookInfo.bookId, "9") +end + +do + -- 个人划线走 Eink:Web 会话打 /web/book/bookmarklist 恒返回 {} + captured = {} + posted = {} + local wire + client:bookmarkListAsync("99", function(data) wire = data end) + Assert.eq(#captured, 0) + Assert.eq(posted.eink.method, "GET") + Assert.eq(posted.eink.path, "/book/bookmarklist") + Assert.eq(posted.eink.query.bookId, "99") + Assert.eq(posted.eink.query.synckey, 0) + Assert.eq(#wire.updated, 1) + Assert.eq(wire.chapters[1].chapterIdx, 4) +end + +do + posted = {} + local wire + client:myReviewsAsync("99", function(data) wire = data end) + Assert.eq(posted.eink.path, "/review/list") + Assert.eq(posted.eink.query.bookId, "99") + Assert.eq(posted.eink.query.mine, 1) + Assert.eq(posted.eink.query.listType, 1) + -- 别的书的想法剔掉,否则会按 range 挂进这本书(串书) + Assert.eq(#wire.reviews, 2) + Assert.eq(wire.reviews[1].review.content, "本书") + Assert.eq(wire.reviews[2].review.content, "无 bookId 保留") + Assert.eq(wire.totalCount, 3, "全量判定保留服务端口径") + Assert.not_nil(wire) + + client:myReviewsAsync("77", function(data) wire = data end) + Assert.eq(posted.eink.query.maxIdx, 5, "hasMore=1 时按回包 maxIdx 续拉") + Assert.eq(#wire.reviews, 2) + Assert.eq(wire.reviews[2].review.content, "乙") + Assert.eq(wire.hasMore, 0) + + client:myReviewsAsync("88", function(data) wire = data end) + Assert.eq(posted.eink.query.listType, 11, "首页被拒改用 listType=11 重试") + Assert.eq(wire.reviews[1].review.content, "丙") +end + +do + captured = {} + posted = {} + local wire, err + client:readStatsAsync("monthly", nil, function(data, e) wire, err = data, e end) + Assert.is_nil(err) + Assert.eq(posted.eink.path, "/readdata/detail") + Assert.eq(posted.eink.query.mode, "monthly") + Assert.is_nil(posted.eink.query.baseTime) + Assert.eq(#(wire.readLongest or {}), 1) +end + +do + -- 进度走 App /book/read:本地坐标,阅读时长为 0。时长在统计上报里,不在这里重计。 + local Eink = require("moonsource_weread.eink") + local orig_call = Eink.callAsync + Eink.credentials = function() return { vid = "1", device_id = "d", refresh_token = "r" } end + Eink.installId = function() return "i" end + Eink.setGuestToken = function() end + local fail_read = false + Eink.callAsync = function(method, path, opts, cb) + posted.eink = { method = method, path = path, body = opts and opts.body, query = opts and opts.query } + if path == "/feature" then + cb({ feature = { guest_token = "gt" } }) + elseif path == "/book/read" then + cb(fail_read and { succ = 0 } or { succ = 1 }) + else + cb({}) + end + return { cancel = function() end } + end + posted = {} + local ok, err + client:putProgressAsync("99", { + progress = 50, chapter_uid = 8, chapter_idx = 3, chapter_offset = 24000, chapter_fraction = 0.5, + }, function(data, e) ok, err = data, e end) + Assert.eq(posted.eink.path, "/book/read") + Assert.eq(posted.eink.method, "POST") + Assert.eq(posted.eink.body.bookId, "99") + Assert.eq(posted.eink.body.chapterUid, 8) + Assert.eq(posted.eink.body.chapterIdx, 3) + Assert.eq(posted.eink.body.chapterOffset, 24000) + Assert.eq(posted.eink.body.chapterProgress, 50) + Assert.eq(posted.eink.body.progress, 50) + Assert.eq(posted.eink.body.currentProgress, 50) + Assert.eq(posted.eink.body.readingTime, 0) + Assert.eq(#posted.eink.body.hours, 0) + Assert.is_nil(posted.eink.body.readUpdateTime, "单条 /book/read 不带进度时间") + Assert.is_nil(posted.eink.body.isResendReadingInfo) + Assert.not_nil(posted.eink.body.signature) + Assert.not_nil(ok) + Assert.is_nil(err) + Assert.is_nil(posted.url, "进度不再打网页阅读接口") + + client:putProgressAsync("99", { + progress = 50, chapter_uid = 8, chapter_idx = 3, chapter_offset = 24000, + chapter_fraction = 0.5, + hours = { { startOfHour = 3600, readingTime = 15, timeZone = "+08:00", ttsTime = 0 } }, + }, function(data, e) ok, err = data, e end) + Assert.eq(posted.eink.body.readingTime, 15, "时长随进度一起报,服务端才改坐标") + Assert.eq(posted.eink.body.hours[1].startOfHour, 3600) + Assert.eq(posted.eink.body.chapterOffset, 24000) + Assert.not_nil(ok) + + fail_read = true + ok, err = nil, nil + client:putProgressAsync("99", { progress = 50, chapter_uid = 8 }, + function(data, e) ok, err = data, e end) + Assert.is_nil(ok) + Assert.not_nil(err) + + -- 跨小时走离线批量。-2054 丢掉 /config token,换新 token 再签一次。 + local sha256 = require("ffi/sha2").sha256 + local configs, batches, reject = 0, {}, true + Eink.callAsync = function(method, path, opts, cb) + posted.eink = { method = method, path = path, body = opts and opts.body, query = opts and opts.query } + if path == "/feature" then + cb({ feature = { guest_token = "gt" } }) + elseif path == "/config" then + configs = configs + 1 + cb({ token = "t" .. configs }) + elseif path == "/book/batchUploadProgress" then + batches[#batches + 1] = opts.body + if reject then + reject = false + cb(nil, "expired", { errcode = -2054 }) + else + cb({ succ = 1 }) + end + elseif path == "/book/read" then + cb({ succ = 1 }) + else + cb({}) + end + return { cancel = function() end } + end + ok, err = nil, nil + client:putProgressAsync("99", { + progress = 50, chapter_uid = 8, chapter_idx = 3, chapter_offset = 24000, + hours = { + { startOfHour = 0, readingTime = 10, timeZone = "+08:00", ttsTime = 0 }, + { startOfHour = 3600, readingTime = 15, timeZone = "+08:00", ttsTime = 0 }, + }, + }, function(data, e) ok, err = data, e end) + Assert.not_nil(ok) + Assert.is_nil(err) + Assert.eq(configs, 2, "-2054 之后重新取 token") + Assert.eq(#batches, 2) + Assert.eq(posted.eink.path, "/book/batchUploadProgress") + Assert.eq(posted.eink.query, nil) + Assert.eq(batches[1].books[1].isResendReadingInfo, 0, "实时跨小时不是补报积压") + Assert.eq(batches[1].books[1].readingTime, 25) + Assert.eq(#batches[1].books[1].hours, 2) + Assert.eq(batches[1].books[1].chapterOffset, 24000) + Assert.eq(batches[1].books[1].readUpdateTime, batches[1].books[1].timestamp) + Assert.eq(#batches[1].books[1].signature, 64, "每本仍用 guest 签名") + local function outer(batch, token) + return sha256(tostring(batch.timestamp) .. token .. tostring(batch.random)) + end + Assert.eq(batches[1].signature, outer(batches[1], "t1")) + Assert.eq(batches[2].signature, outer(batches[2], "t2")) + Assert.is_true(batches[1].signature ~= batches[2].signature) + + local marked + Eink.callAsync = function(_method, path, opts, cb) + if path == "/book/markstatus" then + marked = opts.body + cb({ status = 4 }) + else + cb(nil, "no") + end + return { cancel = function() end } + end + ok, err = nil, nil + client:markFinishedAsync("99", function(data, e) ok, err = data, e end) + Assert.eq(marked.bookId, "99") + Assert.eq(marked.status, 4) + Assert.eq(marked.finishInfo, 0) + Assert.eq(marked.isCancel, 0) + Assert.eq(marked.auto, 1) + Assert.eq(ok.status, 4) + Assert.is_nil(err) + Eink.callAsync = orig_call +end + +-- bookCount 大于 books 条数也原样交回(专辑、公众号不在这三份列表里) +do + local data, err + posted = { shelf_reply = { bookCount = 3, books = { { bookId = "1" }, { bookId = "2" } }, archive = {} } } + client:shelfSyncAsync(function(d, e) data, err = d, e end) + Assert.is_nil(err) + Assert.eq(data.bookCount, 3) + Assert.eq(#data.books, 2) + posted = {} +end + +-- Web reader session supplies the token for a zero-duration presence heartbeat only. +do + web_replies["/web/reader/"] = '{"psvts":"ps","pclts":"pc","token":"tk"}' + local state, state_err + client:readerStateAsync("99", function(value, err) state, state_err = value, err end) + Assert.eq(state.psvts, "ps") + Assert.eq(state.pclts, "pc") + Assert.eq(state.token, "tk") + Assert.is_nil(state_err) + Assert.is_true(captured[#captured]:find("/web/reader/", 1, true) ~= nil) + + posted.web_read_reply = '{"succ":1}' + local result, report_err + client:reportReadAsync({ rt = 0 }, "https://weread.qq.com/web/reader/99", + function(value, err) result, report_err = value, err end) + Assert.eq(posted.url, "https://weread.qq.com/web/book/read") + Assert.eq(posted.body.rt, 0) + Assert.eq(posted.referer, "https://weread.qq.com/web/reader/99") + Assert.not_nil(result) + Assert.is_nil(report_err) + + posted.web_read_reply = "{}" + result, report_err = nil, nil + client:reportReadAsync({ rt = 0 }, nil, function(value, err) result, report_err = value, err end) + Assert.is_nil(result) + Assert.not_nil(report_err) + web_replies["/web/reader/"] = nil +end diff --git a/tests/weread/context_spec.lua b/tests/weread/context_spec.lua new file mode 100644 index 0000000..be83254 --- /dev/null +++ b/tests/weread/context_spec.lua @@ -0,0 +1,81 @@ +--[[-- +moonsource_weread.context 离线用例:reader 状态本地生成、会话内固定、过期重建 + +@module tests.wechat_context_spec +--]] + +local Assert = require("support.assert") +local Protocol = require("moonsource_weread.protocol") +local Context = require("moonsource_weread.context") + +local real_time = os.time +local now = 1700000000 +os.time = function(t) return t and real_time(t) or now end + +-- 未缓存:按当前时间生成;psvts 模拟更早的出页时间,不能与 pclts 相同。 +do + Context.clear() + local reader = Context.reader("b1", "c1") + Assert.eq(reader.psvts, Protocol.encode(now - 1)) + Assert.eq(reader.pclts, Protocol.encode(now)) +end + +-- 会话内固定:进入阅读与之后的时长上报必须共用同一个 pc,entered 标记也要留住。 +do + Context.clear() + local reader = Context.reader("b1", "c1") + reader.entered = true + local enter = Protocol.makeEnterReadPayload({ + book_id = "b1", chapter_uid = "c1", psvts = reader.psvts, pclts = reader.pclts, + }) + now = now + 45 + local again = Context.reader("b1", "c1") + Assert.is_true(again == reader, "TTL 内复用同一状态") + local read = Protocol.makeReadPayload({ + book_id = "b1", chapter_uid = "c1", psvts = again.psvts, pclts = again.pclts, + elapsed_seconds = 45, + }) + Assert.eq(enter.pc, read.pc, "enter 与时长上报的 pc 必须一致") + Assert.eq(enter.ps, read.ps) +end + +-- 按章隔离;过 TTL 重建,entered 清掉以重新发进入阅读。 +do + Context.clear() + local c1 = Context.reader("b1", "c1") + c1.entered = true + Assert.is_nil(Context.reader("b1", "c2").entered) + now = now + 15 * 60 + local fresh = Context.reader("b1", "c1") + Assert.is_nil(fresh.entered) + Assert.eq(fresh.pclts, Protocol.encode(now)) +end + +-- 在读会话按书缓存真实网页参数;强制刷新后必须重新 enter。 +do + Context.clear() + local fetches = 0 + local client = { + readerStateAsync = function(_, book_id, cb) + Assert.eq(book_id, "b1") + fetches = fetches + 1 + cb({ psvts = "ps" .. fetches, pclts = "pc" .. fetches, token = "token" }) + return { cancel = function() end } + end, + } + local first + Context.sessionAsync(client, "b1", false, function(session) first = session end) + first.entered = true + local cached + Context.sessionAsync(client, "b1", false, function(session) cached = session end) + Assert.is_true(cached == first) + Assert.eq(fetches, 1) + + local fresh + Context.sessionAsync(client, "b1", true, function(session) fresh = session end) + Assert.eq(fetches, 2) + Assert.eq(fresh.psvts, "ps2") + Assert.is_nil(fresh.entered) +end + +os.time = real_time diff --git a/tests/weread/eink_spec.lua b/tests/weread/eink_spec.lua new file mode 100644 index 0000000..6505702 --- /dev/null +++ b/tests/weread/eink_spec.lua @@ -0,0 +1,276 @@ +--[[-- +moonsource_weread.eink 离线用例:设备 ID、登录签名与请求体、版本/鉴权请求头、 +401 / -2012 续期重放语义、-2041 不重试、令牌落网页会话字段(wr_vid/wr_skey)。 + +@module tests.wechat_eink_spec +--]] + +local Assert = require("support.assert") +local JsonStub = require("support.json_stub") +local sha256 = require("ffi/sha2").sha256 + +local state = { cfg = {}, requests = {}, responder = nil } +local switches = 0 +require("source.logout").replaceLibrary = function(id, commit) + Assert.eq(id, "ext.weread") + switches = switches + 1 + commit() + return true +end + +package.preload["utils.settings"] = function() + return { + getSource = function() return state.cfg end, + saveSource = function(_, c) state.cfg = c end, + } +end +package.preload["http.request"] = function() + return { + ok = function(code) return code ~= nil and code >= 200 and code < 300 end, + request = function(opts, cb) + state.requests[#state.requests + 1] = opts + local res = state.responder(opts) + cb(res) + return { cancel = function() end } + end, + } +end +package.preload["json"] = function() + return { encode = JsonStub.encode, decode = JsonStub.decode } +end +for _, name in ipairs({ "json", "http.request", "utils.settings", "moonsource_weread.eink" }) do + package.loaded[name] = nil +end + +local Eink = require("moonsource_weread.eink") + +local function reply(code, body) + return { code = code, body = JsonStub.encode(body) } +end + +local function reset(cfg) + state.cfg = cfg or {} + state.requests = {} +end + +local function logged_in() + reset({ wr_vid = "42", wr_skey = "at-1", eink = { refresh_token = "rt-1", device_id = "dev-1", guest_token = "gt" } }) +end + +-- 设备 ID:前缀 + 19 位数字,首次生成后落盘并复用。 +do + reset() + local id = Eink.deviceId() + Assert.matches(id, "^[1-9]%d+$") + Assert.eq(#id, 38) + Assert.eq(Eink.deviceId(), id, "设备 ID 落盘后复用") + Assert.eq(state.cfg.eink.device_id, id) +end + +-- 旧版 "eink…" 设备 ID 登录时换成数字 ID(手机渠道配它续期会被风控)。 +do + reset({ eink = { device_id = "eink3346912251234" } }) + local id = Eink.deviceId() + Assert.matches(id, "^[1-9]%d+$") + Assert.eq(state.cfg.eink.device_id, id) +end + +-- 签名 = sha256(毫秒时间戳 .. deviceId .. random),时间戳不能出现科学计数法。 +do + Assert.eq(Eink.signature(1790000000123, "dev", 7), sha256("1790000000123dev7")) +end + +-- 扫码换令牌:请求体字段与签名自洽,令牌落 wr_vid/wr_skey,续期令牌落 cfg.eink。 +do + reset({ eink = { device_id = "99" } }) + state.responder = function() + return reply(200, { vid = 1001, accessToken = "at", refreshToken = "rt" }) + end + local Context = require("moonsource_weread.context") + Context.reader("b1", "c1").entered = true + local user + Eink.completeQrLoginAsync({ wx_code = "code-1" }, function(u) user = u end) + Assert.is_nil(Context.reader("b1", "c1").entered, "登录可能换号:清掉上个账号的进入阅读状态") + local req = state.requests[1] + Assert.eq(req.url, "https://i.weread.qq.com/login") + Assert.eq(req.method, "POST") + Assert.eq(req.headers.basever, "10.2.2.10167650") + Assert.matches(req.headers["User-Agent"], "WeRead/10.2.2") + local body = JsonStub.decode(req.body) + Assert.eq(body.code, "code-1") + Assert.eq(body.deviceId, "99") + Assert.eq(body.deviceType, 1) + Assert.eq(body.isFromQrcode, 1) + Assert.eq(body.signature, Eink.signature(body.timestamp, "99", body.random)) + Assert.eq(user.user_id, "1001") + Assert.eq(state.cfg.wr_skey, "at") + Assert.eq(state.cfg.wr_vid, "1001") + Assert.eq(state.cfg.user_id, "1001") + Assert.eq(state.cfg.eink.refresh_token, "rt") + Assert.eq(state.cfg.eink.device_id, "99") + Assert.eq(switches, 1) + Assert.eq(Eink.credentials().access_token, "at") +end + +-- 登录回包缺令牌按失败,不落盘。 +do + reset({ eink = { device_id = "99" } }) + state.responder = function() return reply(200, { errCode = -1, errMsg = "bad" }) end + local user, err + Eink.completeQrLoginAsync({ wx_code = "c" }, function(u, e) user, err = u, e end) + Assert.is_nil(user) + Assert.matches(err, "bad") + Assert.is_nil(state.cfg.wr_skey) + Assert.is_false(Eink.hasSession()) +end + +-- 正常调用:带 vid/accessToken 与版本头,query 拼进 URL。 +do + logged_in() + state.responder = function() return reply(200, { books = {} }) end + local data, err, meta + Eink.callAsync("GET", "/shelf/sync", { query = { synckey = 0 } }, function(d, e, m) + data, err, meta = d, e, m + end) + local req = state.requests[1] + Assert.eq(req.url, "https://i.weread.qq.com/shelf/sync?synckey=0") + Assert.eq(req.headers.vid, "42") + Assert.eq(req.headers.accessToken, "at-1") + Assert.eq(req.headers.appver, "10.2.2.10167650") + Assert.is_nil(err) + Assert.not_nil(data.books) + Assert.eq(meta.status, 200) +end + +-- GET 遇 -2012:续期(refreshToken + kickType)后用新令牌重放一次,新凭据落盘。 +do + logged_in() + state.cfg.eink.install_id = "inst" + local calls = 0 + state.responder = function(opts) + if opts.url:find("/login", 1, true) then + return reply(200, { vid = 42, accessToken = "at-2", refreshToken = "rt-2" }) + end + calls = calls + 1 + if calls == 1 then return reply(200, { errCode = -2012, errMsg = "expired" }) end + return reply(200, { ok = 1 }) + end + local data + Eink.callAsync("GET", "/book/getProgress", { query = { bookId = "b" } }, function(d) data = d end) + Assert.eq(#state.requests, 3, "原请求 + 续期 + 重放") + local mint = JsonStub.decode(state.requests[2].body) + Assert.eq(mint.refreshToken, "rt-1") + Assert.eq(mint.kickType, 1) + local App = require("moonsource_weread.app") + Assert.eq(mint.signature, App.sign({ "gt", "dev-1", string.format("%.0f", mint.timestamp), tostring(mint.random), "rt-1" })) + Assert.is_nil(mint.deviceType, "App 续期体没有 deviceType") + Assert.eq(mint.wxToken, 0) + Assert.eq(mint.refCgi, "") + Assert.eq(state.requests[3].headers.accessToken, "at-2") + Assert.eq(data.ok, 1) + Assert.eq(state.cfg.wr_skey, "at-2") + Assert.eq(state.cfg.eink.refresh_token, "rt-2") + Assert.eq(state.cfg.eink.device_id, "dev-1") + Assert.eq(state.cfg.eink.install_id, "inst", "续期不丢安装 ID") +end + +-- 公众号授权:同一次 /login,wxToken=1,refCgi 是失败的那次请求。 +do + logged_in() + state.responder = function() return reply(200, { vid = 42, accessToken = "at-wx", refreshToken = "rt-wx" }) end + local ok + Eink.refreshAsync(function(o) ok = o end, { wxToken = 1, refCgi = "https://weread.qq.com/web/mp/articles?bookId=MP_WXS_1" }) + local mint = JsonStub.decode(state.requests[1].body) + Assert.is_true(ok) + Assert.eq(mint.wxToken, 1) + Assert.eq(mint.refCgi, "https://weread.qq.com/web/mp/articles?bookId=MP_WXS_1") + Assert.eq(mint.kickType, 1) + Assert.eq(state.cfg.eink.refresh_token, "rt-wx") +end + +-- 续期回包不带 refreshToken(线上常态):沿用旧 refreshToken,仍算成功。 +do + logged_in() + state.responder = function() return reply(200, { vid = 42, accessToken = "at-3" }) end + local ok, err + Eink.refreshAsync(function(o, e) ok, err = o, e end) + Assert.is_true(ok) + Assert.is_nil(err) + Assert.eq(state.cfg.wr_skey, "at-3") + Assert.eq(state.cfg.eink.refresh_token, "rt-1") +end + +-- 扫码登录回包缺 refreshToken 仍按失败。 +do + reset({ eink = { device_id = "99" } }) + state.responder = function() return reply(200, { vid = 1, accessToken = "at" }) end + local user + Eink.completeQrLoginAsync({ wx_code = "c" }, function(u) user = u end) + Assert.is_nil(user) + Assert.is_nil(state.cfg.wr_skey) +end + +-- POST 遇 401:只续期不重放(写可能已落地),回调失败。 +do + logged_in() + state.responder = function(opts) + if opts.url:find("/login", 1, true) then + return reply(200, { vid = 42, accessToken = "at-2", refreshToken = "rt-2" }) + end + return { code = 401, body = "" } + end + local data, err + Eink.callAsync("POST", "/book/read", { body = { a = 1 } }, function(d, e) data, err = d, e end) + Assert.eq(#state.requests, 2, "原请求 + 续期,不重放") + Assert.is_nil(data) + Assert.not_nil(err) + Assert.eq(state.cfg.wr_skey, "at-2", "续期仍然落盘,下个请求可用") + Assert.eq(state.requests[1].headers["Content-Type"], "application/json; charset=UTF-8") +end + +-- -2041 人机验证:不续期、不重试。 +do + logged_in() + state.responder = function() return reply(200, { errCode = -2041 }) end + local err, meta + Eink.callAsync("GET", "/shelf/sync", nil, function(_, e, m) err, meta = e, m end) + Assert.eq(#state.requests, 1) + Assert.matches(err, "%-2041") + Assert.eq(meta.errcode, -2041) +end + +-- 官方 10.2.2:errMsg 等于错误码时不原样展示。-2025 进阅读错误页「加载失败」;有中文说明则保留。 +do + logged_in() + state.responder = function() return { code = 499, body = '{"errCode":-2025,"errMsg":"-2025"}' } end + local err, meta + Eink.callAsync("GET", "/book/chapterdownload", nil, function(_, e, m) err, meta = e, m end) + Assert.eq(err, "加载失败") + Assert.eq(meta.errcode, -2025) + Assert.eq(Eink.userMessage(-2030, "-2030"), "本书已下架") + Assert.eq(Eink.userMessage(-2112, ""), "余额不足") + Assert.eq(Eink.userMessage(-2223, "-2223", 402), "试读结束") + Assert.eq(Eink.userMessage(-2281, "-2281"), "章节价格已更新,请重新购买") + Assert.eq(Eink.userMessage(-2202, nil), "章节已经购买过,请勿重复购买") + Assert.eq(Eink.userMessage(-1, "服务器忙"), "服务器忙") + Assert.eq(Eink.userMessage(nil, "", 500), "HTTP 500") +end + +-- 未登录直接失败,不发请求;退出登录保留设备 ID。 +-- 只有网页会话、没有 refresh_token 也不算 Eink 会话(网页扫码的老用户)。 +do + reset({ wr_vid = "42", wr_skey = "web" }) + Assert.is_false(Eink.hasSession()) +end + +do + logged_in() + Eink.clearSession() + Assert.is_false(Eink.hasSession()) + Assert.eq(state.cfg.eink.device_id, "dev-1") + Assert.is_nil(state.cfg.eink.refresh_token) + local err + Eink.callAsync("GET", "/shelf/sync", nil, function(_, e) err = e end) + Assert.not_nil(err) + Assert.eq(#state.requests, 0) +end diff --git a/tests/weread/mapper_spec.lua b/tests/weread/mapper_spec.lua new file mode 100644 index 0000000..eb88426 --- /dev/null +++ b/tests/weread/mapper_spec.lua @@ -0,0 +1,511 @@ +--[[-- +moonsource_weread.mapper 离线用例 + +@module tests.moonsource_weread.mapper_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") + +package.preload["moonsource_weread.mapper"] = nil +package.loaded["moonsource_weread.mapper"] = nil +package.preload["source.contract"] = nil +-- contract 可能仍在 loaded,保留即可 + +local Mapper = require("moonsource_weread.mapper") + +do + local _b, cover = Mapper.book({ bookId = "wx-2", cover = "https://cdn.weread.qq.com/weread/cover/80/y_1/s_y_1.jpg" }) + Assert.eq(cover, "https://cdn.weread.qq.com/weread/cover/80/y_1/t7_y_1.jpg") +end + +do + local b, cover = Mapper.book({ + bookId = "wx-1", + bookName = "三体", + author = "刘慈欣", + cover = "http://x/c.jpg", + progressPercent = 42, + }) + Assert.eq(b.source_id, "ext.weread") + Assert.eq(b.stable_id, "wx-1") + Assert.eq(b.title, "三体") + Assert.eq(b.percent, 42) + Assert.eq(cover, "http://x/c.jpg") + Assert.is_nil(b.id) +end + +-- 空封面必须视为缺失,不能参与远端 upsert 覆盖本地已有封面。 +do + local b, cover = Mapper.book({ bookId = "wx-empty", title = "保留封面", cover = "" }) + Assert.is_nil(b.cover) + Assert.is_nil(cover) +end + +-- bookInfo 扩展元数据原样交给 meta(规范化在 BookDB 入库时做),newRating 千分制折成十分制 +do + local b = Mapper.book({ + bookId = "wx-meta", publisher = "湖南文艺出版社", publishTime = "2022-01-01 00:00:00", + isbn = "9787572606878", language = "zh", totalWords = 68000, newRating = 955, + }) + Assert.eq(b.meta.publisher, "湖南文艺出版社") + Assert.eq(b.meta.published, "2022-01-01 00:00:00") + Assert.eq(b.meta.isbn, "9787572606878") + Assert.eq(b.meta.language, "zh") + Assert.eq(b.meta.words, 68000) + Assert.eq(b.meta.rating.score, 9.55) + Assert.eq(b.meta.rating.by, "weread") +end + +-- 微信作品完结 finished=1 不当作用户读完。连载判断要的 payType / type / 完结留下。 +do + local b = Mapper.book({ bookId = "1", finished = 1, progress = 20, payType = 2, type = 0 }) + Assert.eq(b.percent, 20) + Assert.eq(b.meta.source["ext.weread"].pay_type, 2) + Assert.eq(b.meta.source["ext.weread"].book_type, 0) + Assert.eq(b.meta.source["ext.weread"].ended, true) +end + +do + local shelf = { + books = { { bookId = "1", title = "A" } }, + recentBooks = { { bookId = "2", title = "B" } }, + finishReadBooks = { { bookId = "1", title = "A dup" }, { bookId = "3", title = "C" } }, + bookProgress = { { bookId = "1", progress = 33 } }, + albums = {}, + } + local list = Mapper.shelfList(shelf) + Assert.eq(#list.data, 3) + local ids = {} + for _, b in ipairs(list.data) do ids[b.stable_id] = b.title end + Assert.eq(ids["1"], "A") + Assert.eq(ids["2"], "B") + Assert.eq(ids["3"], "C") + Assert.eq(list.data[1].percent, 33) +end + +do + local shelf = { + books = { { bookId = "1", title = "A" } }, + bookProgress = { { bookId = "1", progress = 33 } }, + albums = {}, + } + local list = Mapper.shelfList(shelf) + Assert.eq(#list.data, 1) + Assert.eq(list.data[1].percent, 33) +end + +do + local Settings = require("utils.settings") + local cfg = Settings.getSource("ext.weread") + cfg.category_as_group = true + Settings.saveSource("ext.weread", cfg) + local list = Mapper.shelfList({ + books = { + { bookId = "1", title = "A", category = "官方" }, + { bookId = "2", title = "B", category = "官方" }, + }, + archive = { + { name = "我的", bookIds = { 1 } }, + { name = "其它", bookIds = { 1 } }, + }, + }) + Assert.eq(list.data[1].category, "我的", "开:进组用分组名") + Assert.is_nil(list.data[2].category, "开:没进组不写题材,避免混合") + Assert.is_true(list.data[1].category_authoritative) + Assert.is_true(list.data[2].category_authoritative, "没进组也是这次快照的分类口径") + cfg.category_as_group = false + Settings.saveSource("ext.weread", cfg) + local genre = Mapper.shelfList({ + books = { + { bookId = "1", title = "A", category = "官方" }, + { bookId = "2", title = "B", category = "官方" }, + }, + archive = { { name = "我的", bookIds = { 1 } } }, + }) + Assert.eq(genre.data[1].category, "官方", "关:只用题材") + Assert.eq(genre.data[2].category, "官方", "关:忽略分组") +end + +do + local chapters = Mapper.chapters({ + data = { + { + bookId = "1", + updated = { + { chapterIdx = 2, chapterUid = "u2", title = "二", wordCount = 10, level = 2 }, + { + chapterIdx = 1, chapterUid = "u1", title = "一", wordCount = 10, level = 1, + anchors = { { title = "第一章", level = 2 } }, + }, + { chapterIdx = 3, chapterUid = "u3", title = "封面", wordCount = 10 }, + }, + }, + }, + }, "1") + Assert.eq(#chapters, 2) + Assert.eq(chapters[1].idx, 1) + Assert.eq(chapters[1].uid, "u1") + Assert.eq(chapters[1].depth, 1) + Assert.eq(chapters[1].anchors[1].title, "第一章") + Assert.eq(chapters[1].anchors[1].depth, 2) + Assert.eq(chapters[1].toc_version, 5) + Assert.not_nil(chapters[1].words, "带字数:关联书按篇幅对齐") + Assert.eq(chapters[2].title, "二", "出版书(epub)章名原样") + Assert.eq(chapters[2].depth, 2) +end + + +do + -- 微信给每章挂的同名同层自锚点(就是章首)不是章内小节,丢掉;同名更深与异名小节保留。 + local chapters = Mapper.chapters({ + data = { + { + bookId = "1", + updated = { + { chapterIdx = 1, chapterUid = "u1", title = "龙卷风", wordCount = 10, level = 2, + anchors = { { title = "龙卷风", level = 2 } } }, + { chapterIdx = 2, chapterUid = "u2", title = "序", wordCount = 10, level = 1, + anchors = { { title = "序", level = 2 }, { title = "小节", level = 2 } } }, + }, + }, + }, + }, "1") + Assert.is_nil(chapters[1].anchors, "同名同层自锚点丢弃,目录不再一章两行") + Assert.eq(#chapters[2].anchors, 2, "同名更深与异名小节保留") +end +do + -- 网文(book.format=txt,chapterInfos 实测字段):按 chapterIdx 补「第 N 章」,已带序号的不重复补,空章名只留序号。 + local chapters = Mapper.chapters({ + data = { + { + bookId = "820954", + book = { bookId = "820954", format = "txt" }, + updated = { + { chapterIdx = 1, chapterUid = 1, title = "万年之后", wordCount = 1290 }, + { chapterIdx = 2, chapterUid = 2, title = "第二章 想整我?", wordCount = 1430 }, + { chapterIdx = 3, chapterUid = 3, title = "第一次见面", wordCount = 10 }, + { chapterIdx = 4, chapterUid = 4, title = "", wordCount = 10 }, + { chapterIdx = 5, chapterUid = 5, title = "第12章", wordCount = 10 }, + }, + }, + }, + }, "820954") + local titles = {} + for i, ch in ipairs(chapters) do titles[i] = ch.title end + Assert.eq(table.concat(titles, "|"), "第1章 万年之后|第二章 想整我?|第3章 第一次见面|第4章|第12章") + Assert.eq(chapters[1].format, "txt") +end + +do + local chapters = Mapper.chapters({ + data = { + { + bookId = "1", + updated = { + { chapterIdx = 1, chapterUid = "u1", title = "图章", wordCount = 10, tar = "/web/tar/1" }, + }, + }, + }, + }, "1") + Assert.eq(chapters[1].tar, "/web/tar/1") +end + +do + local pos = Mapper.progress({ progress = 50, chapterUid = "u1" }) + Assert.eq(pos.fraction, 0.5) +end + +do + local pos, uid = Mapper.progress({ + bookId = "42", + book = { chapterUid = "u7", progress = 77, chapterOffset = 5000 }, + }) + Assert.eq(uid, "u7") + Assert.eq(pos.fraction, 0.77) + Assert.is_nil(pos.chapter_fraction, "原文偏移不是章内万分比") + Assert.eq(pos.extra.chapter_offset, 5000) +end + +do + local pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1, chapterOffset = 1 } }) + Assert.is_nil(pos.chapter_fraction) + Assert.eq(pos.extra.chapter_offset, 1) + pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1, chapterOffset = 0 } }) + Assert.is_nil(pos.chapter_fraction) + Assert.eq(pos.extra.chapter_offset, 0) + pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1 } }) + Assert.is_nil(pos.chapter_fraction) +end + +-- 云端最近阅读时间:书行 readUpdateTime 与 bookProgress.updateTime 取较新的 +do + local b = Mapper.book({ bookId = "wx-r", title = "R", readUpdateTime = 1700000000 }) + Assert.eq(b.read_at, 1700000000) + Mapper.applyProgress(b, { bookId = "wx-r", progress = 10, updateTime = 1700000500 }) + Assert.eq(b.read_at, 1700000500) + Mapper.applyProgress(b, { bookId = "wx-r", progress = 10, updateTime = 1600000000 }) + Assert.eq(b.read_at, 1700000500, "旧的不覆盖新的") + local list = Mapper.shelfList({ + books = { { bookId = "a", title = "A" } }, + bookProgress = { { bookId = "a", progress = 5, updateTime = 1234 } }, + }) + Assert.eq(list.data[1].read_at, 1234) + + -- 公众号只走订阅导入,书架同步不收进书库 + local mixed = Mapper.shelfList({ books = { { bookId = "a", title = "A" }, { bookId = "MP_WXS_1", title = "号" } } }) + Assert.len(mixed.data, 1) + Assert.eq(mixed.data[1].stable_id, "a") +end +do -- 书城目录:榜单与带子分类的分类,其余丢弃 + local tree = Mapper.storeTree({ data = { + { categories = { + { CategoryId = "rising", title = "飙升榜", ranklist = 1, sublist = {} }, + { CategoryId = "6200", title = "有声小说榜", sublist = {} }, + } }, + { categories = { + { CategoryId = 700000, title = "计算机", sublist = { { CategoryId = 700001, title = "软件学习" } } }, + } }, + } }) + Assert.len(tree.rankings, 1) + Assert.eq(tree.rankings[1].id, "rising") + Assert.len(tree.categories, 1) + Assert.eq(tree.categories[1].id, "700000") + Assert.eq(tree.categories[1].subs[1].id, "700001") +end + +--[[-- +moonsource_weread.mapper 离线用例 + +@module tests.moonsource_weread.mapper_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") + +package.preload["moonsource_weread.mapper"] = nil +package.loaded["moonsource_weread.mapper"] = nil +package.preload["source.contract"] = nil +-- contract 可能仍在 loaded,保留即可 + +local Mapper = require("moonsource_weread.mapper") + +do + local b, cover = Mapper.book({ + bookId = "wx-1", + bookName = "三体", + author = "刘慈欣", + cover = "http://x/c.jpg", + progressPercent = 42, + }) + Assert.eq(b.source_id, "ext.weread") + Assert.eq(b.stable_id, "wx-1") + Assert.eq(b.title, "三体") + Assert.eq(b.percent, 42) + Assert.eq(cover, "http://x/c.jpg") + Assert.is_nil(b.id) +end + +-- 空封面必须视为缺失,不能参与远端 upsert 覆盖本地已有封面。 +do + local b, cover = Mapper.book({ bookId = "wx-empty", title = "保留封面", cover = "" }) + Assert.is_nil(b.cover) + Assert.is_nil(cover) +end + +-- bookInfo 扩展元数据原样交给 meta(规范化在 BookDB 入库时做),newRating 千分制折成十分制 +do + local b = Mapper.book({ + bookId = "wx-meta", publisher = "湖南文艺出版社", publishTime = "2022-01-01 00:00:00", + isbn = "9787572606878", language = "zh", totalWords = 68000, newRating = 955, + }) + Assert.eq(b.meta.publisher, "湖南文艺出版社") + Assert.eq(b.meta.published, "2022-01-01 00:00:00") + Assert.eq(b.meta.isbn, "9787572606878") + Assert.eq(b.meta.language, "zh") + Assert.eq(b.meta.words, 68000) + Assert.eq(b.meta.rating.score, 9.55) + Assert.eq(b.meta.rating.by, "weread") +end + +-- 微信作品完结 finished=1 不当作用户读完。连载判断要的 payType / type / 完结留下。 +do + local b = Mapper.book({ bookId = "1", finished = 1, progress = 20, payType = 2, type = 0 }) + Assert.eq(b.percent, 20) + Assert.eq(b.meta.source["ext.weread"].pay_type, 2) + Assert.eq(b.meta.source["ext.weread"].book_type, 0) + Assert.eq(b.meta.source["ext.weread"].ended, true) +end + +do + local shelf = { + books = { { bookId = "1", title = "A" } }, + recentBooks = { { bookId = "2", title = "B" } }, + finishReadBooks = { { bookId = "1", title = "A dup" }, { bookId = "3", title = "C" } }, + bookProgress = { { bookId = "1", progress = 33 } }, + albums = {}, + } + local list = Mapper.shelfList(shelf) + Assert.eq(#list.data, 3) + local ids = {} + for _, b in ipairs(list.data) do ids[b.stable_id] = b.title end + Assert.eq(ids["1"], "A") + Assert.eq(ids["2"], "B") + Assert.eq(ids["3"], "C") + Assert.eq(list.data[1].percent, 33) +end + +do + local shelf = { + books = { { bookId = "1", title = "A" } }, + bookProgress = { { bookId = "1", progress = 33 } }, + albums = {}, + } + local list = Mapper.shelfList(shelf) + Assert.eq(#list.data, 1) + Assert.eq(list.data[1].percent, 33) +end + +do + local Settings = require("utils.settings") + local cfg = Settings.getSource("ext.weread") + cfg.category_as_group = true + Settings.saveSource("ext.weread", cfg) + local list = Mapper.shelfList({ + books = { + { bookId = "1", title = "A", category = "官方" }, + { bookId = "2", title = "B", category = "官方" }, + }, + archive = { + { name = "我的", bookIds = { 1 } }, + { name = "其它", bookIds = { 1 } }, + }, + }) + Assert.eq(list.data[1].category, "我的", "开:进组用分组名") + Assert.is_nil(list.data[2].category, "开:没进组不写题材,避免混合") + Assert.is_true(list.data[1].category_authoritative) + Assert.is_true(list.data[2].category_authoritative, "没进组也是这次快照的分类口径") + cfg.category_as_group = false + Settings.saveSource("ext.weread", cfg) + local genre = Mapper.shelfList({ + books = { + { bookId = "1", title = "A", category = "官方" }, + { bookId = "2", title = "B", category = "官方" }, + }, + archive = { { name = "我的", bookIds = { 1 } } }, + }) + Assert.eq(genre.data[1].category, "官方", "关:只用题材") + Assert.eq(genre.data[2].category, "官方", "关:忽略分组") +end + +do + local chapters = Mapper.chapters({ + data = { + { + bookId = "1", + updated = { + { chapterIdx = 2, chapterUid = "u2", title = "二", wordCount = 10, level = 2 }, + { + chapterIdx = 1, chapterUid = "u1", title = "一", wordCount = 10, level = 1, + anchors = { { title = "第一章", level = 2 } }, + }, + { chapterIdx = 3, chapterUid = "u3", title = "封面", wordCount = 10 }, + }, + }, + }, + }, "1") + Assert.eq(#chapters, 2) + Assert.eq(chapters[1].idx, 1) + Assert.eq(chapters[1].uid, "u1") + Assert.eq(chapters[1].depth, 1) + Assert.eq(chapters[1].anchors[1].title, "第一章") + Assert.eq(chapters[1].anchors[1].depth, 2) + Assert.eq(chapters[1].toc_version, 5) + Assert.not_nil(chapters[1].words, "带字数:关联书按篇幅对齐") + Assert.eq(chapters[2].title, "二", "出版书(epub)章名原样") + Assert.eq(chapters[2].depth, 2) +end + +do + -- 网文(book.format=txt,chapterInfos 实测字段):按 chapterIdx 补「第 N 章」,已带序号的不重复补,空章名只留序号。 + local chapters = Mapper.chapters({ + data = { + { + bookId = "820954", + book = { bookId = "820954", format = "txt" }, + updated = { + { chapterIdx = 1, chapterUid = 1, title = "万年之后", wordCount = 1290 }, + { chapterIdx = 2, chapterUid = 2, title = "第二章 想整我?", wordCount = 1430 }, + { chapterIdx = 3, chapterUid = 3, title = "第一次见面", wordCount = 10 }, + { chapterIdx = 4, chapterUid = 4, title = "", wordCount = 10 }, + { chapterIdx = 5, chapterUid = 5, title = "第12章", wordCount = 10 }, + }, + }, + }, + }, "820954") + local titles = {} + for i, ch in ipairs(chapters) do titles[i] = ch.title end + Assert.eq(table.concat(titles, "|"), "第1章 万年之后|第二章 想整我?|第3章 第一次见面|第4章|第12章") + Assert.eq(chapters[1].format, "txt") +end + +do + local chapters = Mapper.chapters({ + data = { + { + bookId = "1", + updated = { + { chapterIdx = 1, chapterUid = "u1", title = "图章", wordCount = 10, tar = "/web/tar/1" }, + }, + }, + }, + }, "1") + Assert.eq(chapters[1].tar, "/web/tar/1") +end + +do + local pos = Mapper.progress({ progress = 50, chapterUid = "u1" }) + Assert.eq(pos.fraction, 0.5) +end + +do + local pos, uid = Mapper.progress({ + bookId = "42", + book = { chapterUid = "u7", progress = 77, chapterOffset = 5000 }, + }) + Assert.eq(uid, "u7") + Assert.eq(pos.fraction, 0.77) + Assert.is_nil(pos.chapter_fraction) + Assert.eq(pos.extra.chapter_offset, 5000) +end + +do + local pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1, chapterOffset = 1 } }) + Assert.is_nil(pos.chapter_fraction) + Assert.eq(pos.extra.chapter_offset, 1) + pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1, chapterOffset = 0 } }) + Assert.is_nil(pos.chapter_fraction) + Assert.eq(pos.extra.chapter_offset, 0) + pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1 } }) + Assert.is_nil(pos.chapter_fraction) +end + +-- 云端最近阅读时间:书行 readUpdateTime 与 bookProgress.updateTime 取较新的 +do + local b = Mapper.book({ bookId = "wx-r", title = "R", readUpdateTime = 1700000000 }) + Assert.eq(b.read_at, 1700000000) + Mapper.applyProgress(b, { bookId = "wx-r", progress = 10, updateTime = 1700000500 }) + Assert.eq(b.read_at, 1700000500) + Mapper.applyProgress(b, { bookId = "wx-r", progress = 10, updateTime = 1600000000 }) + Assert.eq(b.read_at, 1700000500, "旧的不覆盖新的") + local list = Mapper.shelfList({ + books = { { bookId = "a", title = "A" } }, + bookProgress = { { bookId = "a", progress = 5, updateTime = 1234 } }, + }) + Assert.eq(list.data[1].read_at, 1234) + + -- 公众号只走订阅导入,书架同步不收进书库 + local mixed = Mapper.shelfList({ books = { { bookId = "a", title = "A" }, { bookId = "MP_WXS_1", title = "号" } } }) + Assert.len(mixed.data, 1) + Assert.eq(mixed.data[1].stable_id, "a") +end diff --git a/tests/weread/mp_spec.lua b/tests/weread/mp_spec.lua new file mode 100644 index 0000000..c3df129 --- /dev/null +++ b/tests/weread/mp_spec.lua @@ -0,0 +1,324 @@ +--[[-- moonsource_weread.mp:公众号文章列表(新到旧)、书架里的公众号与分组、文章页 → 正文、图片改写。 --]] + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +Stubs.install() +package.loaded["json"] = { decode = require("support.json_stub").decode } + +local pages, urls = {}, {} +local localized = {} +local renewals = 0 +local wx_refreshes = {} +package.loaded["moonsource_weread.auth"] = { + sessionHeaders = function(extra) + local h = { Cookie = "wr_vid=1; wr_skey=2" } + if extra then for k, v in pairs(extra) do h[k] = v end end + return h + end, + webPostAsync = function(url, _body, _opts, cb) + renewals = renewals + 1 + Assert.matches(url, "/web/login/renewal") + cb("{}", nil, { headers = { ["X-WR-Ticket"] = "T1", ["x-wrpa-0"] = "W1" } }) + return { cancel = function() end } + end, + webGetAsync = function(url, _opts, cb) + urls[#urls + 1] = url + cb(pages[url:match("reviewId=(.*)$") or "list"]) + return { cancel = function() end } + end, +} +-- 正文改走 Request.stream:按 reviewId 吐 pages,超大页边吐边让调用方断开。 +local stream_override = nil +package.loaded["http.request"] = { + stream = function(opts, h) + if stream_override then return stream_override(opts, h) end + local job = { stopped = false } + function job:cancel() self.stopped = true end + urls[#urls + 1] = opts.url + local key = opts.url:match("reviewId=(.*)$") or "list" + local body = pages[key] + if body == nil then + if h.on_headers then h.on_headers(404, {}) end + h.on_done("HTTP 404") + return job + end + if h.on_headers then h.on_headers(200, {}) end + local CHUNK = 256 * 1024 + for i = 1, #body, CHUNK do + if job.stopped then break end + h.on_data(body:sub(i, i + CHUNK - 1)) + end + h.on_done(job.stopped and "cancelled" or nil) + return job + end, + header = function(res, name) + local headers = res and res.headers + if not headers then return nil end + if type(headers.get) == "function" then return headers:get(name, true) end + local lower = name:lower() + for k, v in pairs(headers) do + if type(k) == "string" and k:lower() == lower then return v end + end + end, +} +package.loaded["http.timeout"] = { net = function() return 1 end } +package.loaded["http.request.header"] = { forRequest = function(e) return e or {} end, merge = function(a, b) + local o = {} + for k, v in pairs(b or {}) do o[k] = v end + for k, v in pairs(a or {}) do o[k] = v end + return o +end } +package.loaded["moonsource_weread.assets"] = { + localizeArticleAsync = function(dir, html, cb) + localized[#localized + 1] = dir + cb(html) + return { cancel = function() end } + end, +} +package.loaded["moonsource_weread.eink"] = { + refreshAsync = function(cb, opts) + wx_refreshes[#wx_refreshes + 1] = opts + cb(true) + return { cancel = function() end } + end, + callAsync = function(_method, path, opts, cb) + local q = opts and opts.query or {} + urls[#urls + 1] = path .. "?" .. require("utils.text").formEncode(q) + local raw = pages.list + if type(raw) ~= "string" then + cb(nil, "微信读书拒绝了请求,请稍后再试", { errcode = -2041 }) + return { cancel = function() end } + end + local data = package.loaded["json"].decode(raw) + if type(data) == "table" and (data.errcode or data.errCode) then + cb(nil, data.errmsg or data.errMsg, { errcode = tonumber(data.errcode or data.errCode) }) + else + cb(data) + end + return { cancel = function() end } + end, +} +package.loaded["moonsource_weread.mp"] = nil +local Mp = require("moonsource_weread.mp") + +local function wire(items) + local subs = {} + for i, item in ipairs(items) do + subs[i] = { reviewId = item[1], review = { reviewId = item[1], createTime = item[2], mpInfo = { title = item[3] } } } + end + return { reviews = { { createTime = 0, subReviews = subs } } } +end + +-- 文章列表:新到旧、去重、无标题用日期。 +local list = Mp.articles(wire({ { "r1", 100, "一" }, { "r2", 200, "" }, { "r1", 100, "一" } })) +Assert.len(list, 2) +Assert.eq(list[1].guid, "r2") +Assert.eq(list[1].title, os.date("%Y-%m-%d", 200)) +Assert.eq(list[2].title, "一") +Assert.len(Mp.articles({}), 0) +local flat = Mp.articles({ data = { + { reviewId = "a", createTime = 10, mpInfo = { title = "甲" } }, + { reviewId = "b", createTime = 30, mpInfo = { title = "" } }, + { reviewId = "a", createTime = 10, mpInfo = { title = "甲" } }, +} }) +Assert.len(flat, 2) +Assert.eq(flat[1].guid, "b") +Assert.eq(flat[1].title, os.date("%Y-%m-%d", 30)) +Assert.eq(flat[2].title, "甲") + +-- 分页:App /mp/chapters,offset 与第三个回调都是篇数。 +pages.list = '{"data":[{"reviewId":"r9","createTime":9,"mpInfo":{"title":"九"}}]}' +local got, groups +Mp.fetchArticlesAsync("MP_WXS_1", 40, function(items, _e, n) got, groups = items, n end) +Assert.eq(got[1].guid, "r9") +Assert.eq(groups, 1) +Assert.matches(urls[#urls], "/mp/chapters?") +Assert.matches(urls[#urls], "offset=40") +Assert.matches(urls[#urls], "count=20") +pages.list = '{"errcode":-2010,"errmsg":"登录超时"}' +local err +Mp.fetchArticlesAsync("MP_WXS_1", 0, function(items, e) got, err = items, e end) +Assert.eq(got, nil) +Assert.eq(err, "登录超时") +-- -2041:wxToken=1 后续一次仍被拒,换成公众号授权失效。 +pages.list = nil +renewals = 0 +wx_refreshes = {} +Mp.fetchArticlesAsync("MP_WXS_1", 0, function(items, e) got, err = items, e end) +Assert.eq(got, nil) +Assert.eq(err, Mp.AUTH_EXPIRED) +Assert.eq(renewals, 1, "wxToken=1 成功后补一次网页头") +Assert.eq(#wx_refreshes, 1) +Assert.eq(wx_refreshes[1].wxToken, 1) +Assert.matches(wx_refreshes[1].refCgi, "/mp/chapters") + +-- 书架里的公众号:books 行、mp.book 单对象、data.officialAccounts 都收,去重;分组取 archive 名。 +local accounts = Mp.accounts({ + books = { { bookId = "1", title = "书" }, { bookId = "MP_WXS_3", title = "号三" } }, + mp = { book = { bookId = "MP_WXS_1", title = "号一" }, show = 1 }, + data = { officialAccounts = { { bookId = "MP_WXS_2", title = "号二" }, { bookId = "MP_WXS_1", title = "重复" } } }, + archive = { { name = "科技", bookIds = { "MP_WXS_1", "1" } } }, +}) +local by = {} +for _idx, a in ipairs(accounts) do by[a.id] = a end +Assert.len(accounts, 3) +Assert.eq(by["MP_WXS_1"].title, "号一") +Assert.eq(by["MP_WXS_1"].group, "科技") +Assert.eq(by["MP_WXS_2"].group, "") +Assert.eq(by["1"], nil, "普通书不收") +Assert.eq(Mp.isMp("MP_WXS_9"), true) +Assert.eq(Mp.isMp("3300"), false) + +-- 正文:只取 js_content,去脚本 / svg,剥内联字号(两种引号),懒加载图换 src 并降档。 +local html = '

' +local body = Mp.extractBody(html) +Assert.not_nil(body:find("

正文

", 1, true), "字号剥掉、其余样式保留") +Assert.not_nil(body:find("二", 1, true), "单引号样式也剥") +Assert.is_nil(body:find("svg", 1, true)) +Assert.is_nil(body:find("script", 1, true)) +Assert.not_nil(body:find('', 1, true), body) +Assert.eq(Mp.extractBody("没有正文"), nil) +local many = '
' .. string.rep('', 40) .. "
\n" + .. '\n" +Assert.matches(Mp.extractBody(real), "图文正文") +Assert.is_nil(Mp.extractBody(real):find("不该用这份", 1, true)) + +-- 图片 / 纯文字消息没有 js_content:正文取脚本里的 content_noencode(解 \x / \u / \n 转义),图片取 picture_page_info_list。 +local picture = "
" +local pic = Mp.extractBody(picture) +Assert.matches(pic, "第一行") +Assert.matches(pic, "第二行 & '引号'") +Assert.not_nil(pic:find('', 1, true), pic) +Assert.not_nil(pic:find("sz_mmbiz_png/b/640", 1, true)) +Assert.is_nil(pic:find("evil", 1, true), "只取 picture_page_info_list 里的图") +Assert.matches(Mp.extractBody(""), "

HTML 正文

") +Assert.is_nil(Mp.extractBody("")) +local sto = Mp.extractBody("") +Assert.not_nil(sto:find('src="http://320.wxapp.tc.qq.com/s?m=1&k=2"', 1, true), sto) + +-- emoji:KOReader 字体画不出,一律去掉(不留方块)。脚本正文里的代理对先合成码点再去掉,不能留下两段非法 UTF-8 +local GRIN = "\240\159\152\128" +Assert.eq(Mp.extractBody(""), "

AB中

") +Assert.is_nil(Mp.extractBody(""):find("\237", 1, true)) +-- 正文里的码点(含 ZWJ 序列、肤色、VS16)去掉、★ 保留;雪碧图空 span 删;QQ 表情透明占位图去掉、留 alt +local family = "\240\159\145\168\226\128\141\240\159\145\169" -- 👨‍👩 +local thumb = "\240\159\145\141\240\159\143\189" -- 👍🏽 +local emo = Mp.extractBody('

好' .. GRIN .. family .. thumb .. "\226\157\164\239\184\143" .. "\226\152\133" + .. '' + .. '[微笑]' + .. '

') +Assert.eq(emo, "

好\226\157\164\226\152\133[微笑]

") + +-- 拉正文:图片交给 assets 落到给定目录;不给目录不落地。 +pages["r1"] = html +Mp.fetchContentAsync("r1", "/tmp/x/images", function(h) got = h end) +Assert.matches(got, "正文") +Assert.eq(localized[1], "/tmp/x/images") +Mp.fetchContentAsync("r1", nil, function(h) got = h end) +Assert.len(localized, 1, "不给目录不下图") +pages["big"] = html .. string.rep("x", 9 * 1024 * 1024) +Mp.fetchContentAsync("big", nil, function(p, e) got, err = p, e end) +Assert.matches(got, "正文", "页面大小不设上限") +Mp.fetchContentAsync("none", nil, function(p, e) got, err = p, e end) +Assert.eq(got, nil) + +-- 「验证」反爬页:重拉,最多 VERIFY_TRIES 次;一直是验证页给专门的提示。 +local verify_page = "验证x" +local seq = { verify_page, html } +local calls = 0 +stream_override = function(_opts, h) + calls = calls + 1 + local body = seq[calls] or verify_page + local job = { cancel = function() end } + if h.on_headers then h.on_headers(200, {}) end + h.on_data(body) + h.on_done(nil) + return job +end +local delays = {} +Mp.later = function(sec, fn) delays[#delays + 1] = sec; fn() end +got = nil +Mp.fetchContentAsync("v", nil, function(h) got = h end) +Assert.eq(calls, 2); Assert.matches(got, "正文"); Assert.eq(delays[1], 2, "退避再拉") +calls, seq = 0, {} +Mp.fetchContentAsync("v", nil, function(p, e) got, err = p, e end) +Assert.eq(calls, Mp.VERIFY_TRIES); Assert.eq(got, nil); Assert.matches(err, "验证") +stream_override = nil + +-- 正文 -2041:先续网页头再重试,续上了不再打 wxToken=1。 +do + local sent = {} + stream_override = function(opts, h) + sent[#sent + 1] = opts.headers or {} + if h.on_headers then h.on_headers(200, {}) end + h.on_data(#sent == 1 and '{"errcode":-2041}' or '
六
') + h.on_done(nil) + return { cancel = function() end } + end + local html + renewals = 0 + wx_refreshes = {} + Mp.fetchContentAsync("r6", nil, function(h) html = h end) + Assert.eq(renewals, 1) + Assert.eq(#wx_refreshes, 0, "网页头续上了就不再打 wxToken=1") + Assert.matches(html, "六") + Assert.eq(sent[2]["x-wr-ticket"], "T1") + Assert.eq(sent[2]["x-wrpa-0"], "W1") + stream_override = nil +end + +-- 网页头续完仍是 -2041:wxToken=1 之后第三次拉到正文。 +do + local sent = 0 + stream_override = function(_opts, h) + sent = sent + 1 + if h.on_headers then h.on_headers(200, {}) end + h.on_data(sent < 3 and '{"errcode":-2041,"errMsg":"-2041"}' or '
八
') + h.on_done(nil) + return { cancel = function() end } + end + local html + renewals = 0 + wx_refreshes = {} + Mp.fetchContentAsync("r8", nil, function(h) html = h end) + Assert.eq(sent, 3) + Assert.eq(renewals, 2) + Assert.eq(#wx_refreshes, 1) + Assert.eq(wx_refreshes[1].wxToken, 1) + Assert.matches(wx_refreshes[1].refCgi, "/web/mp/content") + Assert.matches(html, "八") + stream_override = nil +end + +-- 正文先按 id 切片:js_content 之前的大段脚本不参与匹配;属性顺序不同也认。 +do + local page = "" + .. '' + Assert.eq(Mp.extractBody(page), "

切片正文

") +end + +-- 旧版本同步进书库的公众号行:只撕 MP_WXS_ 的,普通书不动。 +do + local removed = {} + local n = Mp.dropLegacyBooks({ + stableIdsBySource = function(source) Assert.eq(source, "ext.weread"); return { "100", "MP_WXS_1", "MP_WXS_2" } end, + remove = function(source, id) removed[#removed + 1] = source .. ":" .. id end, + }) + Assert.eq(n, 2) + Assert.eq(table.concat(removed, ","), "ext.weread:MP_WXS_1,ext.weread:MP_WXS_2") +end diff --git a/tests/weread/notes_push_spec.lua b/tests/weread/notes_push_spec.lua new file mode 100644 index 0000000..4468ac4 --- /dev/null +++ b/tests/weread/notes_push_spec.lua @@ -0,0 +1,168 @@ +--[[-- +moonsource_weread.notes_push:删除先行、预检失败整轮失败、远端已没有的 bookmarkId 被清掉、取消后不回调。 +@module tests.moonsource_weread.notes_push_spec +--]] + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +Stubs.install() + +local NotesPush = require("moonsource_weread.notes_push") + +--- 只记调用、按表回包的假客户端(回包走 nextTick,模拟真异步)。 +local function fakeClient(replies) + local calls = {} + ---@type { calls: string[], [string]: any } + local client = { calls = calls } + local function method(name) + return function(_self, ...) + local args = { ... } + local cb = args[#args] + calls[#calls + 1] = name + local reply = replies[name] + require("ui/uimanager"):nextTick(function() + if type(reply) == "function" then reply = reply() end + if reply == false then cb(nil, name .. " failed") else cb(reply or {}) end + end) + return { cancel = function() calls[#calls + 1] = "cancel:" .. name end } + end + end + for _idx, name in ipairs({ "removeBookmarkAsync", "deleteReviewAsync", "bookmarkListAsync", + "myReviewsAsync", "addBookmarkAsync", "updateBookmarkAsync", "editReviewAsync", + "addReviewAsync", "bookInfoAsync" }) do + client[name] = method(name) + end + return client +end + +local identity = { source_id = "ext.weread", stable_id = "b1", chapter_idx = 1 } + +do -- 删除墓碑:先删想法再删划线,删完从注解里移除,后续无事可做即成功 + local client = fakeClient({ bookmarkListAsync = { updated = {} }, myReviewsAsync = { reviews = {} } }) + local annotations = { { wr_deleted = true, wr_bookmark_id = "bm1", wr_review_id = "rv1" } } + local ok, err + NotesPush.run(client, identity, "c1", "

x

", annotations, function(o, e) ok, err = o, e end) + Stubs.flush() + Assert.is_true(ok) + Assert.is_nil(err) + Assert.eq(client.calls[1], "deleteReviewAsync") + Assert.eq(client.calls[2], "removeBookmarkAsync") + Assert.len(annotations, 0) +end + +do -- 只有想法的墓碑(没记过划线 id):按 range 在远端找到划线一并删掉 + local client = fakeClient({ + bookmarkListAsync = { updated = { { chapterUid = "c1", range = "10-20", bookmarkId = "bm9" } } }, + myReviewsAsync = { reviews = {} }, + }) + local annotations = { { wr_deleted = true, wr_review_id = "rv1", wr_range = "10-20" } } + local ok + NotesPush.run(client, identity, "c1", "

x

", annotations, function(o) ok = o end) + Stubs.flush() + Assert.is_true(ok) + Assert.eq(client.calls[1], "deleteReviewAsync") + Assert.eq(client.calls[2], "bookmarkListAsync") + Assert.eq(client.calls[3], "removeBookmarkAsync") + Assert.len(annotations, 0) +end + +do -- 预检失败:整轮失败,带上错误 + local client = fakeClient({ bookmarkListAsync = false }) + local ok, err + NotesPush.run(client, identity, "c1", "

x

", {}, function(o, e) ok, err = o, e end) + Stubs.flush() + Assert.is_nil(ok) + Assert.eq(err, "bookmarkListAsync failed") +end + +do -- 远端已没有的 bookmarkId 被清掉(下轮当新划线重传),删除请求失败则停在删除 + local client = fakeClient({ bookmarkListAsync = { updated = {} }, myReviewsAsync = { reviews = {} } }) + local item = { drawer = "lighten", text = "t", wr_bookmark_id = "gone" } + NotesPush.run(client, identity, "c1", nil, { item }, function() end) + Stubs.flush() + Assert.is_nil(item.wr_bookmark_id) + + client = fakeClient({ removeBookmarkAsync = false }) + local ok + local annotations = { { wr_deleted = true, wr_bookmark_id = "bm1" } } + NotesPush.run(client, identity, "c1", nil, annotations, function(o) ok = o end) + Stubs.flush() + Assert.is_nil(ok) + Assert.len(annotations, 1, "删除失败保留墓碑下轮重试") +end + +do -- 取消:在途请求被取消,迟到回包不回调 + local client = fakeClient({}) + local called = false + local job = NotesPush.run(client, identity, "c1", nil, {}, function() called = true end) + job.cancel() + Stubs.flush() + Assert.is_false(called) + Assert.eq(client.calls[2], "cancel:bookmarkListAsync") +end + +do -- 想法列表预检失败只跳过想法对账,不阻断划线:已有 review id 保留 + local client = fakeClient({ bookmarkListAsync = { updated = {} }, myReviewsAsync = false }) + local item = { drawer = "lighten", text = "t", wr_bookmark_id = "gone", wr_review_id = "rv1" } + local ok, err + NotesPush.run(client, identity, "c1", nil, { item }, function(o, e) ok, err = o, e end) + Stubs.flush() + Assert.is_nil(err) + Assert.eq(item.wr_review_id, "rv1") + Assert.is_nil(item.wr_bookmark_id) +end + +do -- 新划线定位:range 原文走 Position 缓存(开书记住的那份),同步命中不重拉整章 + local Toc = require("moonsource_weread.toc") + local Position = require("moonsource_weread.progress") + local old_read, old_load = Toc.read, Position.loadAsync + Toc.read = function() return { { uid = "c1" } } end + local load_calls = 0 + Position.loadAsync = function(_identity, _chapter, cb) + load_calls = load_calls + 1 + -- 缓存命中:同步回调、返回 nil(与 Position.loadAsync 真实行为一致) + cb('tttttttttt

hello world

', "html") + return nil + end + local submitted = false + local item = { + drawer = "lighten", text = "hello", + pos0 = "/html/body/p/text().0", pos1 = "/html/body/p/text().5", + } + local client = fakeClient({ + bookmarkListAsync = function() + if not submitted then return { updated = {} } end + return { updated = { { + chapterUid = "c1", range = item.wr_range, bookmarkId = "bm-new", + markText = "hello", type = 1, + } } } + end, + myReviewsAsync = { reviews = {} }, + addBookmarkAsync = function() submitted = true; return { bookmarkId = "bm-new" } end, + bookInfoAsync = { book = { version = 7 } }, + }) + local ok, err + NotesPush.run(client, identity, "c1", + "

hello world

", { item }, + function(o, e) ok, err = o, e end) + Stubs.flush() + Toc.read, Position.loadAsync = old_read, old_load + Assert.is_true(ok) + Assert.is_nil(err) + Assert.eq(load_calls, 1) + -- 53 = wire 原文里

之前的全部 rune(head/title 计入),与本地壳无关 + Assert.eq(item.wr_range, "53-58") + Assert.eq(item.wr_bookmark_id, "bm-new") +end + +do -- 想法清单拿不到:新想法不推(认不回上轮已成功的会重复),报失败留脏;划线与已有想法照常 + local client = fakeClient({ bookmarkListAsync = { updated = {} }, myReviewsAsync = false }) + local item = { drawer = "lighten", text = "t", note = "想法", wr_review_only = true, wr_range = "1-2" } + local ok, err + NotesPush.run(client, identity, "c1", nil, { item }, function(o, e) ok, err = o, e end) + Stubs.flush() + Assert.is_nil(ok) + Assert.not_nil(err) + Assert.is_nil(item.wr_review_id) + for _, name in ipairs(client.calls) do Assert.is_true(name ~= "addReviewAsync", "不得重复新增想法") end +end diff --git a/tests/weread/package_spec.lua b/tests/weread/package_spec.lua new file mode 100644 index 0000000..530e1c5 --- /dev/null +++ b/tests/weread/package_spec.lua @@ -0,0 +1,142 @@ +--[[-- +moonsource_weread.package:App 章节包口令派生与 ZipCrypto 解包。 --]] + +local Assert = require("support.assert") +local Package = require("moonsource_weread.package") + +-- 抓包样本:vid 与响应头 encryptKey → 口令。 +Assert.eq(Package.password("393727764", "LEyM8AVZMBvMt93WBCFCPw=="), "I1RVbke@p") +Assert.is_nil(Package.password("abc", "LEyM8AVZMBvMt93WBCFCPw==")) + +-- zip -P 生成:a.txt 为 deflate、b.txt 为 stored,均带数据描述符。 +local hex = "504b0304140009000800e5a2565df9129239220000000902000005001c00612e74787455540900032e00da6a2e00da6a75780b000104f50100000400000000905dd2c021a840192b344394132d37f6762d7d7cf1a02473b117f93084642c384d7f504b0708f91292392200000009020000504b03040a0009000000e5a2565d69111fb6120000000600000005001c00622e74787455540900032e00da6a2e00da6a75780b000104f50100000400000000dfd0647c7666697985230063aeed35d06c94504b070869111fb61200000006000000504b01021e03140009000800e5a2565df91292392200000009020000050018000000000001000000a48100000000612e74787455540500032e00da6a75780b000104f50100000400000000504b01021e030a0009000000e5a2565d69111fb61200000006000000050018000000000001000000a48171000000622e74787455540500032e00da6a75780b000104f50100000400000000504b0506000000000200020096000000d20000000000" +local zip = hex:gsub("%x%x", function(h) return string.char(tonumber(h, 16)) end) +local files = Package.unzip(zip, "I1RVbke@p") +Assert.eq(files["a.txt"], ("hello 月读 "):rep(40) .. "\n") +Assert.eq(files["b.txt"], "second") + +local need = Package.unzipNeed(zip) +local unpacked = #files["a.txt"] + #files["b.txt"] +Assert.eq(need, 2 * unpacked + 3 * 34 + 65536, + "预检覆盖正文拼接、最大加密条目的三份临时缓冲与 inflate 输出块") +Assert.eq(Package.unzipNeed("not a zip"), 3 * #"not a zip") + +local bad, err = Package.unzip(zip, "wrong") +Assert.is_nil(bad) +Assert.matches(err, "^zip:") +local none, err2 = Package.unzip(zip, nil) +Assert.is_nil(none) +Assert.matches(err2, "password required") + +local info = "info" +package.loaded["json"] = { + decode = function(raw) + Assert.eq(raw, info) + return { chapters = { { chapterUid = 27, files = { "Text/S.xhtml", "Text/S_1.xhtml", "Text/S_2.xhtml" } } } } + end, +} +package.loaded["moonsource_weread.package"] = nil +local Composed = require("moonsource_weread.package") +local book = { + ["info.txt"] = info, + ["Text/S.xhtml"] = "

T

", + ["Text/S_1.xhtml"] = "

a

", + ["Text/S_2.xhtml"] = "

b

", +} +Assert.eq(Composed.chapterHtml(book, 27), "

T

a

b

") +local miss, merr = Composed.chapterHtml(book, 99) +Assert.is_nil(miss) +Assert.matches(merr, "not in package") + +-- TXT 走 ZIP 时 info.txt 只有 chapterUid、没有 files:不能再索引 files[1] 崩掉。 +package.loaded["json"] = { + decode = function() + return { chapters = { { chapterUid = 1595 } } } + end, +} +package.loaded["moonsource_weread.package"] = nil +local NoFiles = require("moonsource_weread.package") +local bare, bare_err = NoFiles.chapterHtml({ ["info.txt"] = "bare" }, 1595) +Assert.is_nil(bare) +Assert.matches(bare_err, "no HTML files") + +-- ZIP 解开后的 map:正文条目 bookId_uid / bookId_uid_o(实机样本)及续篇。 +local zip_map = { + ["info.txt"] = '{"chapters":[{"chapterUid":1595}]}', + ["820954_1595_o"] = "\239\187\191甲", + ["820954_1595_0001"] = "乙", + ["820954_1596_o"] = "别章", +} +Assert.eq(Package.chapterZipText(zip_map, "820954", 1595), "甲乙", "_o 主文件须排在 _0001 续篇前") +Assert.is_nil(Package.chapterZipText(zip_map, "820954", 9)) +Assert.is_nil(Package.chapterZipText({ ["info.txt"] = "{}" }, "820954", 1)) + +local function tarHeader(name, size) + local h = string.rep("\0", 512) + local function poke(off, s) + h = h:sub(1, off - 1) .. s .. h:sub(off + #s) + end + poke(1, name) + poke(125, string.format("%011o", size)) + poke(157, "0") + poke(258, "ustar\0") + return h +end + +local function tarEntry(name, data) + local padded = data .. string.rep("\0", (512 - (#data % 512)) % 512) + return tarHeader(name, #data) .. padded +end + +local tar = tarEntry("info.txt", "{}") + .. tarEntry("820954_1", "\239\187\191甲") + .. tarEntry("820954_1_0001", "乙") + .. tarEntry("820954_12", "别章") + .. string.rep("\0", 1024) +local text = Package.chapterText(tar, "820954", 1) +Assert.eq(text, "甲乙") +local absent = Package.chapterText(tar, "820954", 9) +Assert.is_nil(absent) + +Assert.eq(Package.pickStyle({ ["Styles/stylesheets.css"] = "a" }), "a") +Assert.eq(Package.pickStyle({ ["Styles/stylesheet.css"] = "b" }), "b") +Assert.eq(Package.pickStyle({ + ["Styles/extra.css"] = "x", + ["Styles/stylesheet.css"] = "b", +}), "b") +Assert.eq(Package.pickStyle({ ["Styles/a.css"] = "1", ["Styles/z.css"] = "2" }), "1") +Assert.is_nil(Package.pickStyle({ ["Text/a.xhtml"] = "

" })) + +-- 官方 chapters 批次串:连续合并,首批 0-n,其后 0,a-b。 +Assert.eq(Package.formatChaptersParam({ 1, 2, 3, 4, 5 }), "0-5") +Assert.eq(Package.formatChaptersParam({ 6, 7, 8, 9, 10 }), "0,6-10") +Assert.eq(Package.formatChaptersParam({ 96, 97, 98, 99, 100 }), "0,96-100") +Assert.eq(Package.formatChaptersParam({ 12 }), "0,12") +Assert.eq(Package.formatChaptersParam({}), "0") +Assert.eq(Package.formatChaptersParam({ "a", "b" }), "0,a,b") + +-- 批量解包:一次 zip 多章 + 样式。 +package.loaded["json"] = { + decode = function() + return { chapters = { + { chapterUid = 1, files = { "Text/c1.xhtml" } }, + { chapterUid = 2, files = { "Text/c2.xhtml" } }, + } } + end, +} +package.loaded["moonsource_weread.package"] = nil +local Batch = require("moonsource_weread.package") +local batch_files = { + ["info.txt"] = "info", + ["Text/c1.xhtml"] = "

一

", + ["Text/c2.xhtml"] = "

二

", + ["Styles/stylesheets.css"] = ".x{}", +} +local extracted, style = Batch.extractChapters(batch_files, "bid", { 1, 2 }, "epub") +Assert.eq(style, ".x{}") +Assert.eq(extracted["1"].text, "

一

") +Assert.eq(extracted["2"].text, "

二

") +Assert.is_nil(extracted["1"].err) +local miss = Batch.extractChapters(batch_files, "bid", { 9 }, "epub") +Assert.not_nil(miss["9"].err) + diff --git a/tests/weread/progress_spec.lua b/tests/weread/progress_spec.lua new file mode 100644 index 0000000..4940ef4 --- /dev/null +++ b/tests/weread/progress_spec.lua @@ -0,0 +1,146 @@ +--[[-- +微信进度原文缓存与章节壳层的坐标回归。 + +@module tests.moonsource_weread.progress_spec +--]] + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +package.preload["json"] = function() return JSON end + +local fetched = 0 +local source = "

原始正文与章节末尾

" +package.preload["moonsource_weread.chapter"] = function() + return { + fetchHtmlAsync = function(_id, _chapter, cb) + fetched = fetched + 1 + cb(source, nil, source, "html") + end, + } +end +local Position = require("moonsource_weread.progress") +local Paths = require("utils.paths") +local identity = { source_id = "ext.weread", stable_id = "progress-coordinate-spec" } +local chapter = { idx = 1, uid = "old", title = "章名" } +local path = Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/1.position.json" +local local_path = Paths.chapterPath(identity.stable_id, 1, identity.source_id) +os.remove(path) +os.remove(local_path) + +local ok, err = Position.remember(identity.stable_id, chapter, source, "html") +Assert.is_true(ok) +Assert.is_nil(err) +local raw, format +Position.loadAsync(identity, chapter, function(s, f) raw, format = s, f end) +Assert.eq(raw, source) +Assert.eq(format, "html") +Assert.eq(fetched, 0, "相同章节原文命中缓存,不联网") + +chapter.uid = "new" +Position.loadAsync(identity, chapter, function(s, f) raw, format = s, f end) +Assert.eq(fetched, 1, "章节 uid 变化不能复用旧原文") +Assert.eq(raw, source) +Position.loadAsync(identity, chapter, function(s) raw = s end) +Assert.eq(fetched, 1) + +local pos = { fraction = 0.5, extra = { chapter_offset = 16 } } +Assert.is_true(Position.localize(identity, chapter, pos, source, "html")) +Assert.eq(pos.locator, "/html/body/p/text().1") +Assert.is_nil(pos.chapter_fraction, "字符比不能进章内页比例字段") +Assert.not_nil(pos.extra.chapter_char_fraction) +Assert.eq(Position.encode(identity, chapter, pos, source, "html"), 16) + +pos = { fraction = 0.5, extra = { chapter_offset = 1 } } +Assert.is_true(Position.localize(identity, chapter, pos, "一行正文\n第二行", "txt")) +Assert.eq(pos.locator, "/html/body/p[1]/text().1", "TXT 的标题与章节壳层不能改变原文字符坐标") +Assert.eq(Position.encode(identity, chapter, pos, "一行正文\n第二行", "txt"), 1) +Assert.eq(Position.encode(identity, chapter, { fraction = 0, chapter_fraction = 0 }, source, "html"), 0) +Assert.not_nil(Position.encode(identity, chapter, { fraction = 1, chapter_fraction = 1 }, source, "html")) +local mid_offset = Position.encode(identity, chapter, { fraction = 0.5, chapter_fraction = 0.25 }, source, "html") +local Annotations = require("book.annotations") +local wire_end = Annotations.rangeMapping(source, "html").ends +wire_end = wire_end[#wire_end] or 0 +Assert.eq(mid_offset, math.floor(0.25 * wire_end + 0.5), "没有 locator 时按章内比例换算原文偏移") +local offset, summary, fraction, reason = Position.encode(identity, chapter, { fraction = 0.5 }, source, "html") +Assert.eq(offset, 0, "没有定位和章内比例时按章首上报") +Assert.eq(summary, "") +Assert.eq(fraction, 0) +Assert.is_nil(reason) +Assert.eq(Position.encode(identity, chapter, { + fraction = 0.5, locator = "/html/body/div/text().0", extra = { chapter_idx = 1, chapter_offset = 16 }, +}, source, "html"), 16, "对不上时回退同章旧偏移") +Assert.eq(Position.encode(identity, chapter, { + fraction = 0.5, locator = "/html/body/div/text().0", extra = { chapter_idx = 9, chapter_offset = 16 }, +}, source, "html"), 0, "旧偏移属于别的章时不能复用") +Assert.eq(Position.encode(identity, chapter, { + fraction = 0.5, chapter_fraction = 0.25, locator = "/html/body/div/text().0", + extra = { chapter_idx = 1, chapter_offset = 16 }, +}, source, "html"), mid_offset, "对不上时优先章内比例,不用陈旧 extra 偏移") + +local open = io.open +io.open = function(filename, mode) + if filename == path .. ".part" then return nil, "read-only cache" end + return open(filename, mode) +end +ok, err = Position.remember(identity.stable_id, chapter, source, "html") +io.open = open +Assert.is_nil(ok) +Assert.eq(err, "read-only cache") +os.remove(path) + +do + local comic = '' + .. '
' + .. '
' + .. '' + local comic_id = { source_id = "ext.weread", stable_id = "progress-comic-spec" } + local comic_chapter = { idx = 4, uid = "29", title = "向日葵花园" } + local comic_local = Paths.chapterPath(comic_id.stable_id, 4, comic_id.source_id) + Paths.ensureDir(comic_local:match("(.+)/[^/]+$")) + local out = assert(io.open(comic_local, "wb")) + out:write(comic) + out:close() + local pos = { + locator = "/html/body/div[2]/img.0", + chapter_fraction = 0.5, + extra = {}, + } + local offset, summary, fraction, err = Position.encode(comic_id, comic_chapter, pos, comic, "html") + Assert.is_nil(err) + Assert.not_nil(offset) + Assert.is_true(offset > 0, "第二张图不应落在文档开头") + Assert.eq(summary, "") + Assert.eq(fraction, 0.5, "纯图章沿用阅读器章内页比例") + local frag_offset, frag_summary, frag_fraction, frag_err = Position.encode(comic_id, comic_chapter, { + locator = "/body/DocFragment[1]/body/div[2]/img.0", + chapter_fraction = 0.5, + extra = {}, + }, comic, "html") + Assert.is_nil(frag_err) + Assert.eq(frag_offset, offset, "纯图章 DocFragment 路径应映到同一偏移") + Assert.eq(frag_summary, "") + Assert.eq(frag_fraction, 0.5) + local raw_len = 0 + do + local i, len = 1, #comic + while i <= len do + local byte = comic:byte(i) + i = i + (byte < 0x80 and 1 or byte < 0xe0 and 2 or byte < 0xf0 and 3 or 4) + raw_len = raw_len + 1 + end + end + local fb_offset, fb_summary, fb_fraction, fb_err = Position.encode(comic_id, comic_chapter, { + locator = "/html/body/div[9]/img.0", + chapter_fraction = 0.25, + extra = {}, + }, comic, "html") + Assert.is_nil(fb_err) + Assert.eq(fb_offset, math.floor(0.25 * raw_len + 0.5), "纯图章对不上时按原文 HTML 长度比例回退") + Assert.eq(fb_summary, "") + Assert.eq(fb_fraction, 0.25) + -- 正文回归:原有文本章 encode 不被破坏 + Assert.eq(Position.encode(identity, chapter, { + locator = "/html/body/p/text().1", fraction = 0.5, extra = { chapter_offset = 16 }, + }, source, "html"), 16) + os.remove(comic_local) +end diff --git a/tests/weread/protocol_spec.lua b/tests/weread/protocol_spec.lua new file mode 100644 index 0000000..ca25cd0 --- /dev/null +++ b/tests/weread/protocol_spec.lua @@ -0,0 +1,199 @@ +--[[-- +moonsource_weread.protocol 离线用例(依赖本机 koreader/base 的 ffi/sha2) + +@module tests.wechat_protocol_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") +local md5 = require("ffi/sha2").md5 +local Protocol = require("moonsource_weread.protocol") + +-- encode:数字 vs 非数字路径不同;结果确定性 +do + Assert.eq(Protocol.encode("123"), "2023270027b202cb962a56f") + Assert.eq(Protocol.encode("abc"), "900427206616263900156d7") + -- 同一输入多次一致 + Assert.eq(Protocol.encode("3300022941"), Protocol.encode("3300022941")) +end + +-- sortedQuery:按 key 排序,跳过 s,做 urlencode +do + Assert.eq(Protocol.sortedQuery({ b = 2, a = 1, s = "drop" }), "a=1&b=2") + Assert.eq(Protocol.sortedQuery({ q = "a b" }), "q=a%20b") + Assert.eq(Protocol.sortedQuery({ t = true, f = false }), "f=false&t=true") +end + +-- sign:对 query 串确定性哈希 +do + Assert.eq(Protocol.sign("a=1&b=2"), "2a0a2922") + Assert.eq(Protocol.sign(""), Protocol.sign("")) +end + +-- readerUrl +do + local url = Protocol.readerUrl("3300022941") + Assert.is_true(url:find("^https://weread%.qq%.com/web/reader/", 1) ~= nil) + Assert.is_true(url:find("k", 1, true) == nil) + + local with_ch = Protocol.readerUrl("3300022941", "100") + Assert.is_true(with_ch:find("k" .. Protocol.encode("100"), 1, true) ~= nil) + Assert.is_true(with_ch:find(Protocol.encode("3300022941"), 1, true) ~= nil) +end + +-- contentParams:结构完整,s 与 sortedQuery 自洽;固定时间/随机 +do + local real_time, real_random = os.time, math.random + os.time = function() + return 1700000000 + end + math.random = function() + return 3 + end + local psvts = "not-matching" + local params = Protocol.contentParams("bid", "cuid", psvts, { style = true, sc = 2 }) + os.time = real_time + math.random = real_random + + Assert.eq(params.b, Protocol.encode("bid")) + Assert.eq(params.c, Protocol.encode("cuid")) + Assert.eq(params.ps, psvts) + Assert.eq(params.sc, 2) + Assert.eq(params.st, 1) + Assert.eq(params.prevChapter, false) + Assert.not_nil(params.s) + local expect_s = Protocol.sign(Protocol.sortedQuery(params)) + Assert.eq(params.s, expect_s) +end + +-- contentParams:encode(ct)==psvts 时 ct 递增 +do + local ct0 = 1700000001 + local real_time, real_random = os.time, math.random + os.time = function() + return ct0 + end + math.random = function() + return 1 + end + local psvts = Protocol.encode(ct0) + local params = Protocol.contentParams("b", "c", psvts) + os.time = real_time + math.random = real_random + Assert.eq(params.ct, tostring(ct0 + 1)) + Assert.eq(params.pc, Protocol.encode(ct0 + 1)) +end + +-- decodeShards:错误路径 +do + local t, err = Protocol.decodeShards() + Assert.is_nil(t) + Assert.eq(err, "empty shards") + + t, err = Protocol.decodeShards("too-short") + Assert.is_nil(t) + Assert.eq(err, "shard too short") + + t, err = Protocol.decodeShards(string.rep("0", 32) .. "body-with-bad-md5!!!!") + Assert.is_nil(t) + Assert.eq(err, "shard md5 mismatch") +end + +-- decodeShards:长正文(swapPositions 多位置分支) +-- +-- 反向构造:从明文 base64 出发,按 reverseSwaps 的交换序列倒序施加得到混淆串, +-- 解码后必须还原。交换下标恒小于 len-n-1,不会碰到 swapPositions 读取的尾部字节, +-- 所以位置表可以直接从明文 base64 上算。 +do + local function upvalue(fn, name) + local i = 1 + while true do + local n, v = debug.getupvalue(fn, i) + if n == nil then + return nil + end + if n == name then + return v + end + i = i + 1 + end + end + local decodeEncodedBody = upvalue(Protocol.decodeShards, "decodeEncodedBody") + Assert.not_nil(decodeEncodedBody) + local swapPositions = upvalue(decodeEncodedBody, "swapPositions") + Assert.not_nil(swapPositions) + + local plain = string.rep("微信读书章节正文 weread chapter body. ", 20) + local b64 = require("utils.text").base64Encode(plain) + Assert.is_true(#b64 > 200) + + local positions = swapPositions(b64) + Assert.is_true(#positions > 2, "长输入应走多位置分支") + Assert.eq(#positions % 2, 0) + + -- reverseSwaps 实际执行的交换序列 + local ops = {} + for i = #positions, 1, -2 do + for k = 1, 0, -1 do + ops[#ops + 1] = { positions[i] + k + 1, positions[i - 1] + k + 1 } + end + end + local chars = {} + for i = 1, #b64 do + chars[i] = b64:sub(i, i) + end + for i = #ops, 1, -1 do + local a, b = ops[i][1], ops[i][2] + chars[a], chars[b] = chars[b], chars[a] + end + local body = "x" .. table.concat(chars) + local text, err = Protocol.decodeShards(md5(body):upper() .. body) + Assert.is_nil(err) + Assert.eq(text, plain) +end + +-- decodeShards:合法分片 → hello +do + -- 构造:对 base64("hello") 做与 reverseSwaps 相反的交换(len<11 → positions {0,2}) + local b64 = "aGVsbG8=" + local chars = {} + for i = 1, #b64 do + chars[i] = b64:sub(i, i) + end + local function swap(i, j) + chars[i], chars[j] = chars[j], chars[i] + end + swap(3, 1) + swap(4, 2) + local body = "x" .. table.concat(chars) + local shard = md5(body):upper() .. body + local text, err = Protocol.decodeShards(shard) + Assert.is_nil(err) + Assert.eq(text, "hello") +end + +-- makeReadPayload:rt/ts/rn/sg 字段齐全 +do + local real_time, real_random = os.time, math.random + os.time = function() return 1700000000 end + math.random = function() return 42 end + local payload = Protocol.makeReadPayload({ + book_id = "123", + chapter_uid = "9", + chapter_idx = 1, + progress = 50, + summary = "章节", + psvts = "abc", + elapsed_seconds = 30, + }) + os.time = real_time + math.random = real_random + Assert.eq(payload.pr, 50) + Assert.eq(payload.rt, 30) + Assert.eq(payload.sm, "章节") + -- 摘要按码点截 20 个,不切断多字节字符;非法字节处停住 + Assert.eq(Protocol.makeReadPayload({ summary = string.rep("书", 25) }).sm, string.rep("书", 20)) + Assert.eq(Protocol.makeReadPayload({ summary = "ab\255cd" }).sm, "ab") + Assert.not_nil(payload.sg) + Assert.not_nil(payload.s) +end diff --git a/tests/weread/reviews_spec.lua b/tests/weread/reviews_spec.lua new file mode 100644 index 0000000..667ebda --- /dev/null +++ b/tests/weread/reviews_spec.lua @@ -0,0 +1,265 @@ +--[[-- +moonsource_weread.reviews 离线用例:热点定位、批量请求与分页映射。 + +@module tests.moonsource_weread.reviews_spec +--]] + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +Stubs.install() +package.preload["json"] = function() return require("support.json_stub") end +package.loaded["json"] = nil +local Reviews = require("moonsource_weread.reviews") + +local html = table.concat({ + "

一

", + "

我在森崎书店的日子,是从夏初到翌年的初春。

", + "

重复句。

重复句。

", + "

第一段结尾

第二段开头

", + "", +}) + +---@param range string +---@param abstract string +---@param total integer +local function entry(range, abstract, total) + return { + range = range, + totalCount = total, + maxIdx = 1, + hasMore = 1, + pageReviews = { { + reviewId = "r-" .. range, + likesCount = 21, + review = { abstract = abstract, content = "点评", createTime = 1788166709, author = { name = "橘枳" } }, + } }, + } +end + +do + local hotspots = Reviews.hotspots({ reviews = { + entry("386-407", "我在森崎书店的日子,是从夏初到翌年的初春。", 83), + -- 重复原句无法消歧:不画错位置,直接丢。 + entry("500-504", "重复句。", 5), + -- 跨段原句带换行:按段落边界规范化后仍能定位。 + entry("600-611", "第一段结尾\n第二段开头", 7), + entry("700-710", "正文里没有的句子", 3), + -- 没有段评的热点不标。 + entry("800-810", "我在森崎书店的日子", 0), + } }) + Assert.len(hotspots, 4) + Assert.is_nil(rawget(hotspots[1], "pos0"), "拉取不定位") + local spots = Reviews.locate(hotspots, html) + Assert.len(spots, 2) + Assert.eq(spots[1].range, "386-407") + Assert.eq(spots[1].total, 83) + Assert.eq(spots[1].pos0, "/html/body/p[1]/text().0") + Assert.eq(spots[1].pos1, "/html/body/p[1]/text().21") + Assert.eq(spots[2].range, "600-611") + Assert.eq(spots[2].pos0, "/html/body/p[4]/text().0") + Assert.eq(spots[2].pos1, "/html/body/p[5]/text().5") + Assert.len(Reviews.hotspots({}), 0) + Assert.len(Reviews.locate({}, html), 0) + -- 同一批热点可在另一份 HTML 上重新定位(整本 EPUB 的各分片)。 + local other = Reviews.locate(hotspots, "

前文。我在森崎书店的日子,是从夏初到翌年的初春。

") + Assert.len(other, 1) + Assert.eq(other[1].pos0, "/docfragment/body/p/text().3") +end + +do + local item = Reviews.item(entry("1-2", "x", 1).pageReviews[1]) + Assert.eq(item.id, "r-1-2") + Assert.eq(item.author, "橘枳") + Assert.eq(item.content, "点评") + Assert.eq(item.likes, 21) + Assert.eq(item.replies, 0) + Assert.eq(item.time, 1788166709) + local with_replies = Reviews.item({ + reviewId = "r", likesCount = 1, commentsCount = 4, + review = { content = "点评", createTime = 1, author = { name = "甲" } }, + }) + Assert.eq(with_replies.replies, 4) +end + +do -- 想法下的评论页:楼中楼只记被回复者;空列表但声称有条数是失败;游标不前进就停 + local page = Reviews.comments({ + commentsCount = 3, + commentsHasMore = 1, + commentsMaxIdx = 2, + comments = { + { commentId = "c1", content = "说得对", createTime = 10, likesCount = 2, author = { name = "乙" } }, + { commentId = "c2", content = "同意", createTime = 11, author = { name = "丙" }, + replyUser = { name = "乙" } }, + }, + }, 0) + Assert.len(page.items, 2) + Assert.eq(page.items[1].id, "c1") + Assert.eq(page.items[1].author, "乙") + Assert.eq(page.items[1].likes, 2) + Assert.eq(page.items[1].replies, 0) + Assert.is_nil(page.items[1].reply_to) + Assert.eq(page.items[2].reply_to, "乙") + Assert.eq(page.total, 3) + Assert.eq(page.max_idx, 2) + Assert.is_true(page.more) + + local again = Reviews.comments({ commentsCount = 3, commentsHasMore = 1, commentsMaxIdx = 2, comments = { + { commentId = "c3", content = "还有", createTime = 12, author = { name = "丁" } }, + } }, 2) + Assert.is_false(again.more, "游标停在原地就不再翻") + + local _empty, err = Reviews.comments({ commentsCount = 4, comments = {} }, 0) + Assert.is_nil(_empty) + Assert.eq(err, "无法获取回复") + _empty, err = Reviews.comments({ commentsCount = 1 }, 0) + Assert.is_nil(_empty) + Assert.eq(err, "无法获取回复") + + local none = Reviews.comments({ commentsCount = 0, commentsHasMore = 0 }, 0) + Assert.len(none.items, 0) + Assert.is_false(none.more) +end + +--- 回调由测试手动触发的假 client:每个请求的回调按发出顺序留在 calls 里。 +local function fakeClient() + local client = { calls = {}, cancelled = {} } + function client:underlinesAsync(book_id, chapter_uid, cb) + self.calls[#self.calls + 1] = { "underlines", book_id, chapter_uid, cb = cb } + self.underlines_cb = cb + return { cancel = function() self.cancelled[#self.cancelled + 1] = "underlines" end } + end + function client:readReviewsAsync(book_id, chapter_uid, reviews, cb) + local n = #self.calls + 1 + self.calls[n] = { "readReviews", book_id, chapter_uid, reviews, cb = cb } + self.reviews_cb = cb + return { cancel = function() self.cancelled[#self.cancelled + 1] = n end } + end + return client +end + +local hit_entry = entry("386-407", "我在森崎书店的日子,是从夏初到翌年的初春。", 83) + +do + -- underlines → 批量 readReviews(每句 1 条)。 + local client = fakeClient() + local got + Reviews.hotspotsAsync(client, "b", "c1", function(spots) got = spots end) + client.underlines_cb({ underlines = { + { range = "386-407", count = 935, type = 2 }, + { range = "740-758", count = 0, type = 0 }, + } }) + local reviews = client.calls[2][4] + Assert.eq(client.calls[2][1], "readReviews") + Assert.len(reviews, 2) + Assert.eq(reviews[2].range, "740-758") + Assert.eq(reviews[1].count, 1) + Assert.eq(reviews[1].maxIdx, 0) + client.reviews_cb({ reviews = { hit_entry } }) + Assert.len(got, 1) + + -- 热点多时分批(整批过大服务端 3 秒超时):40/40/40/5,同时最多 3 批在飞,结果按批次顺序合并。 + client = fakeClient() + got = nil + Reviews.hotspotsAsync(client, "b", "c2", function(spots) got = spots end) + local many = {} + for i = 1, 125 do many[i] = { range = i .. "-" .. (i + 1) } end + client.underlines_cb({ underlines = many }) + Assert.len(client.calls, 4, "3 批并发") + Assert.eq(client.calls[2][4][1].range, "1-2") + Assert.eq(client.calls[3][4][1].range, "41-42") + Assert.len(client.calls[4][4], 40) + client.calls[3].cb({ reviews = { entry("41-42", "第二批", 1) } }) + Assert.len(client.calls, 5, "回来一批补一批") + Assert.len(client.calls[5][4], 5) + client.calls[5].cb({ reviews = { entry("121-122", "第四批", 1) } }) + client.calls[4].cb({ reviews = {} }) + Assert.is_nil(got) + client.calls[2].cb({ reviews = { entry("1-2", "第一批", 1) } }) + Assert.len(got, 3) + Assert.eq(got[1].range, "1-2") + Assert.eq(got[2].range, "41-42") + Assert.eq(got[3].range, "121-122") + + -- 一批失败:取消其余在飞批次,整章报错、不落盘,迟到的回包不再回调。 + client = fakeClient() + local batch_err, calls = nil, 0 + got = nil + Reviews.hotspotsAsync(client, "b", "c3", function(spots, e) + calls, got, batch_err = calls + 1, spots, e + end) + client.underlines_cb({ underlines = many }) + client.calls[3].cb(nil, "timeout of 3000ms exceeded") + Assert.len(client.calls, 4, "失败后不再发新批") + Assert.len(client.cancelled, 2) + Assert.is_nil(got) + Assert.eq(batch_err, "timeout of 3000ms exceeded") + client.calls[2].cb({ reviews = {} }) + Assert.eq(calls, 1) + client = fakeClient() + Reviews.hotspotsAsync(client, "b", "c3", function() end) + Assert.len(client.calls, 1, "失败不落盘") + + -- 本章没有热点:不发 readReviews。 + client = fakeClient() + got = nil + Reviews.hotspotsAsync(client, "b", "c4", function(spots) got = spots end) + client.underlines_cb({ underlines = {} }) + Assert.len(client.calls, 1) + Assert.len(got, 0) + + -- 失败原样回传错误。 + client = fakeClient() + local err + Reviews.hotspotsAsync(client, "b", "c5", function(spots, e) got, err = spots, e end) + client.underlines_cb(nil, "boom") + Assert.is_nil(got) + Assert.eq(err, "boom") + + -- 取消:取消在飞的批次,迟到的回包不再回调。 + client = fakeClient() + local called = false + local job = Reviews.hotspotsAsync(client, "b", "c6", function() called = true end) + client.underlines_cb({ underlines = { { range = "386-407" } } }) + job.cancel() + Assert.eq(client.cancelled[1], 2) + client.reviews_cb({ reviews = {} }) + Assert.is_false(called) +end + +do + local client = fakeClient() + local page, err + Reviews.pageAsync(client, "b", "4", "386-407", 2, function(p, e) page, err = p, e end) + local req = client.calls[1][4][1] + Assert.eq(req.range, "386-407") + Assert.eq(req.maxIdx, 2) + Assert.eq(req.count, 30) + client.reviews_cb({ reviews = { entry("386-407", "x", 83) } }) + Assert.is_nil(err) + Assert.len(page.items, 1) + Assert.eq(page.total, 83) + Assert.eq(page.max_idx, 1) + Assert.is_true(page.more) + + Reviews.pageAsync(client, "b", "4", "386-407", 0, function(p, e) page, err = p, e end) + client.reviews_cb(nil, "offline") + Assert.is_nil(page) + Assert.eq(err, "offline") +end + +do -- 已删除段评(无 review 体)和匿名作者不让整页崩溃 + local client = fakeClient() + local page, err + Reviews.pageAsync(client, "b", "4", "1-2", 0, function(p, e) page, err = p, e end) + client.reviews_cb({ reviews = { { + totalCount = 2, maxIdx = 2, hasMore = 0, + pageReviews = { + { reviewId = "gone" }, + { reviewId = "anon", review = { content = "hi", createTime = 1 } }, + }, + } } }) + Assert.is_nil(err) + Assert.len(page.items, 1) + Assert.eq(page.items[1].id, "anon") + Assert.eq(page.items[1].author, "") +end diff --git a/tests/weread/setting_spec.lua b/tests/weread/setting_spec.lua new file mode 100644 index 0000000..3da2114 --- /dev/null +++ b/tests/weread/setting_spec.lua @@ -0,0 +1,127 @@ +--[[-- +微信读书设置页行:账号直接是设置行,登录后才追加续期与退出。 + +@module tests.moonsource_weread.setting_spec +--]] + +local Assert = require("support.assert") + +local cfg = {} +local saved = 0 +package.preload["utils.settings"] = function() + return { + getSource = function() return cfg end, + saveSource = function(_, value) cfg = value; saved = saved + 1 end, + } +end +local logged_in = false +local cleared = false +package.preload["moonsource_weread.auth"] = function() + return { + hasSession = function() return logged_in end, + userLabel = function() return "tester" end, + clearSession = function() cleared = true; logged_in = false end, + } +end +local Themed = require("support.theme_stubs") +Themed.install() +package.preload["ui/network/manager"] = function() + return { runWhenConnected = function(_, fn) fn() end } +end +local begin_cb, wait_cb +local begin_cancels, wait_cancels = 0, 0 +package.preload["moonsource_weread.eink"] = function() + return { + beginQrLoginAsync = function(cb) + begin_cb = cb + return { cancel = function() begin_cancels = begin_cancels + 1 end } + end, + waitQrLoginAsync = function(_, cb) + wait_cb = cb + return { cancel = function() wait_cancels = wait_cancels + 1 end } + end, + } +end +package.preload["ui.themes.widgets.row"] = function() + return { widget = function(opts) return opts end } +end +local auth_changed = 0 +package.preload["source.registry"] = function() + return { + reload = function() auth_changed = auth_changed + 1 end, + invalidate = function() end, + } +end + +package.loaded["moonsource_weread.setting"] = nil +local Setting = require("moonsource_weread.setting") +local updates = 0 +local plugin = { desktop = { updateView = function() updates = updates + 1 end } } + +-- 未登录:账号、合并本地阅读时长、显示段评、自定义分组代替分类四行。 +local rows = Setting.rows(plugin) +Assert.len(rows, 4) +Assert.eq(rows[1]().status, "未登录 · 点此扫码") + +-- 合并本地阅读时长默认关(云端优先);点按落盘开启并刷新设置页。 +local merge = rows[2]() +Assert.eq(merge.kind, "toggle") +Assert.eq(merge.title, "合并本地阅读时长") +Assert.is_false(merge.status_on) +merge.callback() +Assert.is_true(cfg.merge_local_stats) +Assert.eq(saved, 1) +Assert.eq(updates, 1) +Assert.is_true(rows[2]().status_on) + +-- 段评默认关;点按落盘开启。 +local reviews = rows[3]() +Assert.eq(reviews.title, "显示段评") +Assert.is_false(reviews.status_on) +reviews.callback() +Assert.is_true(cfg.show_paragraph_reviews) +Assert.is_true(rows[3]().status_on) + +-- 自定义分组代替分类默认开;点按关闭并清增量游标。 +local groups = rows[4]() +Assert.eq(groups.title, "使用自定义分组代替分类") +Assert.is_true(groups.status_on) +cfg.shelf_cursor = { vid = "1", synckey = 9 } +groups.callback() +Assert.is_false(cfg.category_as_group) +Assert.is_nil(cfg.shelf_cursor) +Assert.is_false(rows[4]().status_on) + +-- 已登录:追加续期与退出;退出先确认,确认后才清会话。 +logged_in = true +rows = Setting.rows(plugin) +Assert.len(rows, 6) +Assert.eq(rows[1]().status, "tester") +Assert.eq(rows[5]().title, "续期会话") +local logout = rows[6]() +Assert.eq(logout.title, "退出登录") +logout.callback() +Assert.is_false(cleared, "未确认不退出") +local confirm = Themed.last("confirm") +Assert.is_true(confirm.shown) +confirm.ok_callback() +Assert.is_true(cleared) +Assert.eq(auth_changed, 1) + +-- 扫码:先出不可取消的进度窗,拿到二维码换成 QR 窗;代码换窗不算取消,用户关窗才取消轮询。 +logged_in = false +Setting.rows(plugin)[1]().callback() +local waiting = Themed.last("progress_dialog") +Assert.eq(waiting.text, "正在获取二维码…") +Assert.eq(waiting.dismissable, false) +begin_cb({ uid = "u1", qr_payload = "weread://login?u1" }) +Assert.is_true(waiting.closed) +Assert.eq(begin_cancels, 0) +local qr = Themed.last("qr") +Assert.eq(qr.text, "weread://login?u1") +qr:close() +Assert.eq(wait_cancels, 1) +local made = #Themed.made +wait_cb(nil, "迟到", "error") +Assert.eq(#Themed.made, made, "已取消的轮询不再弹提示") + diff --git a/tests/weread/shelf_import_spec.lua b/tests/weread/shelf_import_spec.lua new file mode 100644 index 0000000..9a1c0aa --- /dev/null +++ b/tests/weread/shelf_import_spec.lua @@ -0,0 +1,113 @@ +--[[-- +moonsource_weread.shelf_import:大快照落盘、分批入库、收尾对账(书库与游标桩掉)。 + +@module tests.moonsource_weread.shelf_import_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Stubs = require("support.stubs") + +local dir = Config.dir() .. "/shelf_import_spec" +os.execute("mkdir -p '" .. dir .. "'") + +local upserted, hidden_keep, saved = {}, nil, nil +package.loaded["utils.paths"] = { + sourceCacheDir = function() return dir end, + ensureDir = function() return true end, +} +package.loaded["book.books_db"] = { + upsertRemoteMany = function(rows) + for _idx, row in ipairs(rows) do upserted[#upserted + 1] = row end + return true + end, + hideMissing = function(_source_id, keep) + hidden_keep = keep + return 2 + end, +} +local oversize_next = false +package.loaded["moonsource_weread.eink"] = { + save = function(patch) saved = patch end, + callAsync = function(_method, _path, _opts, cb) + if oversize_next then + oversize_next = false + cb({ body = "{}" }, nil, { oversize = true }) + else + cb({}) + end + return { cancel = function() end } + end, +} +package.loaded["utils.awake"] = { hold = function() end } +package.loaded["utils.settings"] = { getSource = function() return { wr_vid = "v1" } end } +package.loaded["moonsource_weread.shelf_import"] = nil +package.loaded["moonsource_weread.mapper"] = nil + +local ShelfImport = require("moonsource_weread.shelf_import") + +Assert.is_nil(ShelfImport.size()) +Assert.is_true(ShelfImport.stash("{}")) +Assert.eq(ShelfImport.size(), 2) + +local ids = ShelfImport.ingest({ + books = { { bookId = "b1", title = "书一" }, { bookId = "b2", title = "书二" } }, + bookProgress = { { bookId = "b1", progress = 50 } }, + archive = { { name = "分组", bookIds = { "b1" } } }, +}) +Assert.len(ids, 2) +Assert.eq(upserted[1].source_id, "ext.weread") +Assert.eq(upserted[1].deleted, 0) +Assert.eq(upserted[1].percent, 50) + +Assert.eq(ShelfImport.commit(ids, 77), 2) +Assert.eq(hidden_keep, ids) +Assert.eq(saved.shelf_cursor.synckey, 77) +Assert.eq(saved.shelf_cursor.vid, "v1") +Assert.is_nil(ShelfImport.size()) + +-- 后台同步发现/重试待导入快照时不弹窗;用户手动刷新才打开导入页。 +do + local Client = require("moonsource_weread.client") + Assert.is_true(ShelfImport.stash("{}")) + local opened = 0 + require("utils.extension").add("web.open_page", function() opened = opened + 1 end) + local got + local handle = Client.shelfSyncAsync({}, function(data, err) got = { data, err } end, true, false) + Assert.is_true(handle ~= nil) + Stubs.flush() + Assert.eq(opened, 0, "后台重试不重复弹出待导入页") + Assert.is_nil(got[1]) + Assert.eq(got[2], ShelfImport.TOO_LARGE) + + got = nil + handle = Client.shelfSyncAsync({}, function(data, err) got = { data, err } end, true, true) + Assert.is_true(handle ~= nil) + Stubs.flush() + Assert.eq(opened, 1, "手动强制刷新可重新打开待导入页") + Assert.is_nil(got[1]) + Assert.eq(got[2], ShelfImport.TOO_LARGE) + ShelfImport.discard() + + -- 首次后台全量超限只保存快照,不能在用户已进入阅读器后突然弹页。 + oversize_next = true + got = nil + handle = Client.shelfSyncAsync({}, function(data, err) got = { data, err } end, true, false) + Assert.is_true(handle ~= nil) + Assert.eq(opened, 1, "后台首次遇到超大书架只保存快照") + Assert.is_nil(got[1]) + Assert.eq(got[2], ShelfImport.TOO_LARGE) + Assert.is_true(ShelfImport.size() ~= nil) + ShelfImport.discard() + + -- 显式刷新触发的全量超限仍应直接打开导入页。 + oversize_next = true + got = nil + handle = Client.shelfSyncAsync({}, function(data, err) got = { data, err } end, true, true) + Assert.is_true(handle ~= nil) + Assert.eq(opened, 2, "手动刷新遇到超大书架打开导入页") + Assert.is_nil(got[1]) + Assert.eq(got[2], ShelfImport.TOO_LARGE) + ShelfImport.discard() +end diff --git a/tests/weread/stats_spec.lua b/tests/weread/stats_spec.lua new file mode 100644 index 0000000..578a34d --- /dev/null +++ b/tests/weread/stats_spec.lua @@ -0,0 +1,89 @@ +--[[-- moonsource_weread.stats:readdata/detail → reading_stats 行映射。 --]] + +local Assert = require("support.assert") +local Stats = require("moonsource_weread.stats") + +do + local result = Stats.fromWires("ext.weread", { + totalReadTime = 7200, + }, { { + baseTime = 1704067200, + readTimes = { + ["1704067200"] = 9999, + ["1704240000"] = 8888, + }, + dailyReadTimes = { + ["1704067200"] = 900, + ["1704153600"] = 600, + }, + readLongest = { + { book = { bookId = "42" }, readTime = 1500 }, + }, + } }, nil, nil, 1800000000) + Assert.eq(result.replace.mode, "ranges") + Assert.len(result.replace.ranges, 3) + local legacy_week + for _, range in ipairs(result.replace.ranges) do + if range.stable_prefix == "__wr:week:" then legacy_week = range end + end + Assert.eq(legacy_week.from_ts, 0, "旧周排行行必须整段清掉") + Assert.eq(legacy_week.to_ts, 1800000000) + local by_id = {} + for _, row in ipairs(result.rows) do by_id[row.stable_id] = row end + Assert.eq(by_id[Stats.TOTAL_ID].duration, 7200) + Assert.eq(by_id["__wr:day:1704067200"].duration, 900, + "年度日明细必须优先于月度分桶") + Assert.eq(by_id["__wr:day:1704153600"].duration, 600) + Assert.is_nil(by_id["__wr:day:1704240000"], + "年度月桶不能伪装成某一天的时长") + for _, row in ipairs(result.rows) do + Assert.is_true(row.record_type ~= "book", "周期排行不再落库") + end +end + +do + local january = 1704067200 + local february = 1706745600 + local annual = { + readTimes = { + [tostring(january)] = 1200, + [tostring(february)] = 0, + }, + } + local bases = Stats.monthlyBaseTimes(annual) + Assert.len(bases, 1) + Assert.eq(bases[1], january) + + local result = Stats.fromWires("ext.weread", { + totalReadTime = 1200, + }, { annual }, { { + readTimes = { + [tostring(january + 86400)] = 1200, + }, + } }) + local by_id = {} + for _, row in ipairs(result.rows) do by_id[row.stable_id] = row end + Assert.eq(by_id["__wr:day:" .. tostring(january + 86400)].duration, 1200) +end + +-- changedBooks:只挑云端累计与本地快照不同的书,按更新时间倒序截断到 limit +do + local changed = Stats.changedBooks({ + { bookId = "a", readingTime = 100, updateTime = 1 }, + { bookId = "b", readingTime = 200, updateTime = 3 }, + { bookId = "c", readingTime = 300, updateTime = 2 }, + { bookId = "same", readingTime = 50, updateTime = 9 }, + { bookId = "never", updateTime = 8 }, + }, { same = 50 }, 2) + Assert.len(changed, 2) + Assert.eq(changed[1].id, "b") + Assert.eq(changed[2].id, "c") + Assert.len(Stats.changedBooks(nil, {}, 20), 0) + -- 云端清零(缺 readingTime)而本地有快照:也算变化,要去清掉旧明细 + local cleared = Stats.changedBooks({ { bookId = "gone" } }, { gone = 10 }, 20) + Assert.eq(cleared[1].reading_time, 0) + local rows = Stats.fromWires("ext.weread", {}, {}, nil, { + { id = "gone", reading_time = 0, wire = {} }, + }, 1000).rows + Assert.len(rows, 0, "累计为 0 不写快照,靠 replace.books 清旧行") +end diff --git a/tests/weread/sync_spec.lua b/tests/weread/sync_spec.lua new file mode 100644 index 0000000..a9180a3 --- /dev/null +++ b/tests/weread/sync_spec.lua @@ -0,0 +1,506 @@ +--[[-- +source.wechat notes/annotations/mapper 离线用例 + +@module tests.moonsource_weread.sync_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") + +package.loaded["moonsource_weread.mapper"] = nil +package.loaded["moonsource_weread.notes"] = nil +package.loaded["book.annotations"] = nil +-- 本地目录:书 820954 的微信 uid 4 对应本地第 4 章;其余书未缓存。 +package.loaded["source.toc"] = { + index = function(_source_id, stable_id, uid) + return stable_id == "820954" and uid == "4" and 4 or nil + end, +} + +local Mapper = require("moonsource_weread.mapper") +local Notes = require("moonsource_weread.notes") +local Annotations = require("book.annotations") + +do + local anns = Notes.toAnnotations({ + updated = { + { + chapterUid = "9", + markText = "hello", + range = "0-5", + createTime = 100, + }, + }, + }, "9", { + reviews = { + { review = { range = "0-5", content = "想法", reviewId = "rv1" } }, + { review = { content = "整本书评,无 range" } }, + }, + }) + Assert.eq(#anns, 1) + Assert.eq(anns[1].text, "hello") + Assert.eq(anns[1].note, "想法") + Assert.eq(anns[1].wr_review_id, "rv1") +end + +do + -- 真实行为:直接发表选中文本想法时,bookmarklist 没有同 range 划线。 + local anns = Notes.toAnnotations({ + updated = { + { + chapterUid = "41", chapterIdx = 6, bookmarkId = "bm1", + type = 1, range = "387-390", markText = "许三观", createTime = 1, + }, + }, + }, "41", { + reviews = { + { + review = { + reviewId = "rv1", chapterUid = 41, chapterIdx = 6, + range = "425-431", abstract = "拍打着屁股,", content = "冲冲冲", + }, + }, + }, + }) + Assert.eq(#anns, 2) + Assert.is_true(anns[2].wr_review_only) + Assert.eq(anns[2].note, "冲冲冲") + + -- 单条「许三观」重复无法定位;与后面的唯一想法一起按 range 顺序即可锁定章首。 + local shell = "

第二章

许三观坐着,拍打着屁股,尘土就在许三观身上。

" + .. "

许三观又站起来。

" + local path = os.tmpname() + local file = assert(io.open(path, "wb")); file:write(shell); file:close() + local localized = Notes.localizeAnnotations(nil, anns, path, { + { + wr_bookmark_id = "bm1", drawer = "lighten", text = "许三观", + page = "/html/body/p[2]/text().0", + pos0 = "/html/body/p[2]/text().0", pos1 = "/html/body/p[2]/text().3", + }, + }) + os.remove(path) + Assert.eq(localized[1].pos0, "/html/body/p[1]/text().0") + Assert.eq(localized[2].note, "冲冲冲") + Assert.is_true(type(localized[2].pos0) == "string") +end + +do + -- 真实 /book/bookmarklist 回包:markText 明文、chapterIdx 只在 chapters 里 + local anns = Notes.toAnnotations({ + synckey = 1787872819, + updated = { + { + bookId = "820954", + chapterUid = 4, + bookmarkId = "820954_4_303-332", + type = 1, + colorStyle = 2, + createTime = 1601272592, + range = "303-332", + markText = "“当然不是!”几乎是下意识的,牧云开口回应道。", + }, + }, + chapters = { { title = "课堂解答", chapterUid = 4, chapterIdx = 4 } }, + }, nil, nil, "ext.weread", "820954") + Assert.eq(#anns, 1) + Assert.eq(anns[1].chapter_idx, 4) + Assert.eq(anns[1].wr_range, "303-332") + Assert.eq(anns[1].wr_bookmark_id, "820954_4_303-332") + Assert.eq(anns[1].text, "“当然不是!”几乎是下意识的,牧云开口回应道。") + Assert.is_nil(anns[1].note) + Assert.eq(anns[1].color, "green") +end + +do + local wire = { + updated = { + { chapterUid = "9", markText = "hello", range = "0-5", createTime = 100, type = 1 }, + { chapterUid = "9", markText = "skip", range = "1-2", createTime = 101, type = 0 }, + }, + items = { + { chapterUid = "9", markText = "popular", range = "2-5", userVid = "999" }, + }, + } + Assert.eq(#Notes.toAnnotations(wire, "9"), 1) + Assert.eq(#Notes.toAnnotations({ items = wire.items }, "9"), 0) + -- 本地目录映射不到:原始 chapterIdx / wire.chapters 都不是本地章号,留空。 + Assert.is_nil(Notes.toAnnotations({ + updated = { + { chapterUid = "8", chapterIdx = 8, markText = "x", range = "0-1", type = 1, createTime = 1 }, + }, + }, nil, nil, "ext.weread", "1")[1].chapter_idx) + Assert.is_nil(Notes.toAnnotations({ + chapters = { { chapterUid = "9", chapterIdx = 9 } }, + updated = { + { chapterUid = "9", markText = "x", range = "0-1", type = 1, createTime = 1 }, + }, + }, nil, nil, "ext.weread", "1")[1].chapter_idx) +end + +--- 单条划线走 locateBatch,返回 pos0, pos1;定位不到返回 nil。 +local function locate(html, text, range) + local item = { text = text, wr_range = range } + local hit = Annotations.locateBatch(html, { item })[item] + if hit then return hit.pos0, hit.pos1 end +end + +do + -- 章节壳:

不占 p 编号;段首缩进折叠为 1 空格,故 p[2] 从 offset 1 起。 + -- 期望值取自 KOReader 自己写出的 xpointer(pos1 是半开上界)。 + local shell = table.concat({ + "指婚

指婚

", + "

莫问毕竟是六星炼丹师。

\n", + "

要是牧钱反应过来。

\n", + "

重复段落文本。

\n", + "

重复段落文本。

", + "", + }) + + local pos0, pos1 = locate(shell, "莫问毕竟是六星炼丹师。") + Assert.eq(pos0, "/html/body/p[1]/text().0") + Assert.eq(pos1, "/html/body/p[1]/text().11") + + pos0, pos1 = locate(shell, "要是牧钱反应过来。") + Assert.eq(pos0, "/html/body/p[2]/text().1") + Assert.eq(pos1, "/html/body/p[2]/text().10") + + -- markText 带换行/多空格时按 crengine 规则折叠后再比 + Assert.eq(locate(shell, " 莫问毕竟是六星炼丹师。\n"), "/html/body/p[1]/text().0") + + -- wire range 与本地壳不是同一坐标系;重复文本不能靠 range 猜,宁可不画错位置。 + Assert.is_nil(locate(shell, "重复段落文本。")) + Assert.is_nil(locate(shell, "重复段落文本。", "34-41")) + + Assert.is_nil(locate(shell, "正文里不存在的句子")) + Assert.is_nil(locate(shell, "")) + + -- 已同步条目即使文本重复,也按 bookmarkId 复用原生坐标并接受远端笔记更新。 + local path = os.tmpname() + local file = assert(io.open(path, "wb")); file:write(shell); file:close() + local localized = Notes.localizeAnnotations(nil, { + { drawer = "lighten", text = "重复段落文本。", note = "远端新想法", wr_bookmark_id = "bm-2" }, + }, path, { + { + drawer = "lighten", text = "重复段落文本。", note = "旧想法", wr_bookmark_id = "bm-2", + page = "/html/body/p[4]/text().0", + pos0 = "/html/body/p[4]/text().0", pos1 = "/html/body/p[4]/text().7", + }, + }) + os.remove(path) + Assert.eq(localized[1].pos0, "/html/body/p[4]/text().0") + Assert.eq(localized[1].note, "远端新想法") +end + +do + -- 本地图片 URL、章节壳与 wire HTML 不同,range 仍必须落在 wire rune 坐标。 + local wire = "\239\187\191

A&B

" + .. '

重复

重复

' + local shell = "

标题

A&B

" + .. '

重复

重复

' + local mapping, flow = Annotations.rangeMapping(wire), Annotations.flow(shell) + local range, err = Annotations.toWireRange( + mapping, flow, "重复", "/html/body/p[3]/text().0", "/html/body/p[3]/text().2" + ) + Assert.is_nil(err) + Assert.eq(range, "59-61") + local first = Annotations.toWireRange( + mapping, flow, "A&B", "/html/body/p[1]/text().0", "/html/body/p[1]/text().3" + ) + Assert.eq(first, "3-10") + local ambiguous, ambiguous_err = Annotations.toWireRange(mapping, flow, "重复") + Assert.is_nil(ambiguous) + Assert.eq(ambiguous_err, "ambiguous local highlight") + Assert.eq(Annotations.wireMapping("

x

y

").text, "xy") +end + +do + -- range 基准是完整解码 xhtml:head 与 xml 声明计入偏移,但其中文字不参与匹配。 + local wire = '正文

正文

' + local shell = "

正文

" + local prefix = wire:sub(1, wire:find("

正文", 1, true) + 2) + local start = select(2, prefix:gsub("[^\128-\191]", "")) + local range = Annotations.toWireRange(Annotations.rangeMapping(wire, "html"), + Annotations.flow(shell), "正文", "/html/body/p/text().0", "/html/body/p/text().2") + Assert.eq(range, string.format("%d-%d", start, start + 2)) +end + +do + -- TXT:range 对纯文本逐 rune 计(BOM 不计,"<" 不是标签),与 weread 的 Source.plain 一致。 + local plain = "\239\187\191甲<&乙\n 丙丁" + local shell = "" .. require("utils.text").textToBody(plain:sub(4)) .. "" + local flow = Annotations.flow(shell) + Assert.eq(Annotations.toWireRange(Annotations.rangeMapping(plain, "txt"), flow, + "<&", "/html/body/p[1]/text().1", "/html/body/p[1]/text().3"), "1-3") + Assert.eq(Annotations.toWireRange(Annotations.rangeMapping(plain, "txt"), flow, + "丙丁", "/html/body/p[2]/text().0", "/html/body/p[2]/text().2"), "7-9") +end + +do + -- KOReader 跨段选区在段间带换行与缩进;微信正文段间也有缩进空白。都必须能定位。 + local wire = "

第一段结尾

\n

第二段开头

" + local shell = "

第一段结尾

第二段开头

" + local range, err = Annotations.toWireRange(Annotations.rangeMapping(wire), Annotations.flow(shell), + "结尾\n 第二", "/html/body/p[1]/text().5", "/html/body/p[2]/text().4") + Assert.is_nil(err) + local head = wire:find("结尾", 1, true) + local runes_before = select(2, wire:sub(1, head - 1):gsub("[^\128-\191]", "")) + Assert.eq(range:match("^(%d+)"), tostring(runes_before)) + + -- 起点 xpointer 对不上(旧版按扁平 p[N] 写出的坐标)时靠唯一文本定位,不拿终点去比。 + Assert.eq(Annotations.toWireRange(Annotations.rangeMapping(wire), Annotations.flow(shell), + "第二段", "/html/body/div/p[9]/span/text().0", "/html/body/div/p[9]/text().3") ~= nil, true) +end + +do + -- xpointer 与 crengine 写法逐字一致(期望值由 crengine getTextFromXPointers 反查确认): + -- 同名兄弟唯一时不带 [k],拼接的多份文档是 html[k],内联元素把文本拆成 text()[k],脚注正文不参与匹配。 + local shell = table.concat({ + '', + 'a', + '

第一段注后文字

\n

第二段

', + '', + '', + 'b', + '

次文档首段

次文档 粗体 尾巴

', + '', + }) + local cases = { + { "注后文字", "/html[1]/body/div/p[1]/text()[2].0", "/html[1]/body/div/p[1]/text()[2].4" }, + { "第二段", "/html[1]/body/div/p[2]/text().0", "/html[1]/body/div/p[2]/text().3" }, + { "次文档首段", "/html[2]/body/p[1]/text().0", "/html[2]/body/p[1]/text().5" }, + { "尾巴", "/html[2]/body/p[2]/text()[2].1", "/html[2]/body/p[2]/text()[2].3" }, + { "粗体", "/html[2]/body/p[2]/b/text().0", "/html[2]/body/p[2]/b/text().2" }, + } + for _idx, case in ipairs(cases) do + local pos0, pos1 = locate(shell, case[1]) + Assert.eq(pos0, case[2]) + Assert.eq(pos1, case[3]) + end + Assert.is_nil(locate(shell, "脚注正文")) + Assert.eq(locate("

正文

", "正文"), "/html/body/p/text().0") +end + +do + -- 跨段划线:微信 markText 直接跨

边界,段首缩进与段间换行都不在其中 + local shell = table.concat({ + "

课堂解答

", + '

“当然不是!”

\n', + "

几乎是下意识的,牧云开口回应道。

", + "", + }) + local pos0, pos1 = locate(shell, "“当然不是!”几乎是下意识的,牧云开口回应道。") + Assert.eq(pos0, "/html/body/p[1]/text().1") + Assert.eq(pos1, "/html/body/p[2]/text().17") + + -- 单段仍按原样定位,不受跨段流影响 + Assert.eq(locate(shell, "牧云开口回应道。"), "/html/body/p[2]/text().9") +end + +do + -- 定位失败的远端划线不能进 doc_settings:drawSavedHighlight 会解 pos0 并抛错 + local localized = Notes.localizeAnnotations(nil, { + { drawer = "lighten", text = "找不到的原文", wr_range = "0-6" }, + }, nil) + Assert.eq(#localized, 1) + Assert.is_nil(localized[1].pos0) +end + +do + -- range 是原始 HTML 索引(含标签),不能按可见文本切片。旧实现先用 textAtRange + -- 把 "0-4" 当成可见文本偏移切成 "AAAA",导致划线定位被错误覆盖。 + local html = 't

t

' + .. '

AAAA作者:罗贯BBBB

' + .. '' + local path = os.tmpname() + local f = assert(io.open(path, "wb")); f:write(html); f:close() + local localized = Notes.localizeAnnotations(nil, { + { drawer = "lighten", text = "作者:罗贯", wr_range = "0-4" }, + }, path) + os.remove(path) + Assert.eq(#localized, 1) + Assert.eq(localized[1].pos0, "/html/body/p/text().0") + Assert.eq(localized[1].pos1, "/html/body/p/text().5") +end + +do + Assert.eq(Notes.decodeMarkText("5L2c6ICF77ya572X6LSv"), "作者:罗贯") + Assert.eq(require("utils.text").base64Encode("作者:罗贯"), "5L2c6ICF77ya572X6LSv") + local body = Notes.toBookmarkBody("1", 9, 2, 395275575, { + text = "hello", + drawer = "lighten", + wr_range = "0-5", + }) + Assert.eq(body.bookId, "1") + Assert.eq(body.chapterUid, 9) + Assert.eq(body.bookVersion, 395275575) + Assert.eq(body.range, "0-5") + Assert.eq(body.markText, "hello") + Assert.eq(#Notes.pushCandidates({ + { drawer = "lighten", text = "a" }, + { drawer = "lighten", text = "note", note = "想法" }, + { drawer = "lighten", text = "b", wr_bookmark_id = 1 }, + }), 1) + Assert.eq(#Notes.notePushCandidates({ + { note = "想法", wr_range = "0-1", wr_bookmark_id = "bm1" }, + { note = "独立想法", wr_range = "2-3", wr_review_only = true }, + { note = "未修改", wr_range = "3-4", wr_review_id = "rv1" }, + { note = "已修改", wr_range = "4-5", wr_review_id = "rv2", wr_update_review = true }, + { note = "无划线", wr_range = "0-1" }, + }), 3) + local review_body = Notes.toReviewBody("1", 9, { + note = "想法", + text = "原文", + wr_range = "0-5", + }) + Assert.eq(review_body.bookId, "1") + Assert.eq(review_body.content, "想法") + Assert.eq(review_body.abstract, "原文") + Assert.eq(review_body.range, "0-5") + Assert.eq(review_body.chapterUid, 9) + local pending = { + text = "原文", note = "想法", wr_range = "0-5", wr_review_only = true, + } + local confirmed = Notes.reconcileReviews({ pending }, { + reviews = { { review = { + reviewId = "rv-recovered", range = "9-14", abstract = "原文", content = "想法", + } } }, + }) + Assert.eq(pending.wr_review_id, "rv-recovered") + Assert.is_true(confirmed[pending]) + local current = Notes.prepareLocalAnnotations({ + { + datetime = "old", page = "/body/a", drawer = "lighten", + note = "旧笔记", wr_bookmark_id = "bm1", wr_review_id = "rv1", + }, + { + datetime = "old", page = "/body/b", drawer = "lighten", + wr_bookmark_id = "bm2", + }, + }, { + { + datetime = "new", page = "/body/a", drawer = "lighten", + wr_bookmark_id = "bm1", + }, + }) + Assert.is_true(current[1].wr_delete_review) + Assert.is_true(current[2].wr_deleted) + Assert.eq(current[2].wr_bookmark_id, "bm2") + + local remote_note = { { + page = "/body/n", datetime = "r", text = "原文", note = "想法", + wr_range = "100-102", wr_review_id = "rv1", + } } + local local_note = { { + page = "/body/n", datetime = "l", text = "原文", note = "想法", + wr_range = "300-302", + } } + Assert.len(Notes.mergeAnnotations(remote_note, local_note, false, true), 1) + + local twins = { + { page = "/body/a", text = "同一处", wr_range = "10-20", wr_bookmark_id = "b1" }, + { page = "/body/a", text = "同一处", wr_range = "10-20", wr_bookmark_id = "b2" }, + } + Assert.len(Notes.mergeAnnotations(twins, { { page = "/body/a", text = "同一处", wr_range = "10-20", wr_bookmark_id = "b2" } }, false, true), 1) + -- 上传后确认没回来的本地划线(无 id / range)与远端同坐标:只留一条 + local unconfirmed = { { page = "/body/a", pos0 = "/p.0", pos1 = "/p.9", text = "同一处", drawer = "lighten" } } + local pulled = { { page = "/body/a", pos0 = "/p.0", pos1 = "/p.9", text = "同一处", wr_range = "10-20", wr_bookmark_id = "b1" } } + local merged = Notes.mergeAnnotations(pulled, unconfirmed, false, true) + Assert.len(merged, 1) + Assert.eq(merged[1].wr_bookmark_id, "b1") + local version = Mapper.bookVersion({ book = { version = 123 } }) + Assert.eq(version, 123) +end + +do -- 同文、同备注或同范围不能覆盖不同位置的真实划线。 + local first = { + page = "/p[1]", pos0 = "/p[1].0", pos1 = "/p[1].4", + text = "重复原文", note = "想法一", drawer = "lighten", + } + local second = { + page = "/p[8]", pos0 = "/p[8].0", pos1 = "/p[8].4", + text = first.text, note = "想法二", drawer = "lighten", + } + local merged, dropped, deduped = Notes.mergeAnnotations({}, { first, second }, false, false) + Assert.len(merged, 2) + Assert.eq(dropped, 0) + Assert.eq(deduped, 0) + Assert.eq(merged[2].note, "想法二") + second.note = first.note + Assert.len(Notes.mergeAnnotations({ first }, { second }, false, false), 2) + first.wr_range, second.wr_range = "0-4", "0-4" + Assert.len(Notes.mergeAnnotations({ first, second }, {}, false, false), 2) + Assert.len(Notes.mergeAnnotations({ first, second }, { first, second }, false, false), 2) +end + +do -- 想法列表没拿到:本地已有的想法接回拉下来的划线,review-only 条目保留 + local anns = { + { text = "a", wr_bookmark_id = "b1" }, + { text = "c", wr_bookmark_id = "b2" }, + } + local out = Notes.keepLocalReviews(anns, { + { text = "a", note = "想法A", wr_bookmark_id = "b1", wr_review_id = "r1" }, + { text = "x", note = "只有想法", wr_review_id = "r2", wr_review_only = true }, + { text = "gone", note = "无关", wr_review_id = "r3" }, + }) + Assert.eq(out[1].note, "想法A") + Assert.eq(out[1].wr_review_id, "r1") + Assert.is_nil(out[2].note) + Assert.eq(#out, 3) + Assert.eq(out[3].wr_review_id, "r2") +end + +do -- 无 text/range 的位置记录:合并时按内容键去重,不能在开书时再翻倍 + local marker = { + datetime = "2026-11-03 14:54:54", + page = "/html/body/div[2]/p[431]/text()[1].37", + pageno = 45, + total_pages = 448, + } + local highlight = { + datetime = "2026-11-04 10:00:00", + page = "/html/body/div[2]/p[2]/text()[1].0", + pos0 = "/html/body/div[2]/p[2]/text()[1].0", + pos1 = "/html/body/div[2]/p[2]/text()[1].6", + drawer = "lighten", + text = "合法高亮", + wr_range = "10-20", + wr_bookmark_id = "bm-keep", + } + local review = { + datetime = "2026-11-04 10:01:00", + page = "/html/body/div[2]/p[3]/text()[1].0", + pos0 = "/html/body/div[2]/p[3]/text()[1].0", + pos1 = "/html/body/div[2]/p[3]/text()[1].4", + drawer = "lighten", + text = "带想法的原文", + note = "一条想法", + wr_range = "30-40", + wr_review_id = "rv-keep", + wr_review_only = true, + } + local bloated = {} + for _i = 1, 4096 do bloated[#bloated + 1] = marker end + bloated[#bloated + 1] = highlight + bloated[#bloated + 1] = review + + local cleaned = Notes.cleanAnnotations(bloated, 448) + Assert.len(cleaned, 3, "清洗后应只剩 1 条位置记录 + 高亮 + 想法") + local texts = {} + for _idx, item in ipairs(cleaned) do texts[item.text or ""] = true end + Assert.is_true(texts["合法高亮"]) + Assert.is_true(texts["带想法的原文"]) + + local merged, dropped, deduped = Notes.mergeAnnotations(bloated, bloated, false, false) + Assert.eq(dropped, 0) + Assert.len(merged, 3, "远端和本地各有 4096 份拷贝时合并不得膨胀") + Assert.is_true(deduped >= 4096) + local again = Notes.mergeAnnotations(merged, merged, false, false) + Assert.len(again, 3, "再合并一次仍是 3 条") + local kept = {} + for _idx, item in ipairs(merged) do + if item.wr_bookmark_id then kept.highlight = item end + if item.wr_review_id then kept.review = item end + end + Assert.eq(kept.highlight.wr_bookmark_id, "bm-keep") + Assert.eq(kept.review.wr_review_id, "rv-keep") +end diff --git a/tests/weread/toc_spec.lua b/tests/weread/toc_spec.lua new file mode 100644 index 0000000..8bdeb31 --- /dev/null +++ b/tests/weread/toc_spec.lua @@ -0,0 +1,130 @@ +--[[-- +moonsource_weread.toc:目录缓存读取与按 idx/uid 定位。 --]] + +local Assert = require("support.assert") +local Config = require("support.config") +local db_path = Config.dir() .. "/wechat_toc_spec.sqlite3" +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +package.preload["utils.paths"] = function() return { dbPath = function() return db_path end } end + +local store = {} +local upserted = {} +local reads = 0 +local now = 1000 +local original_time = os.time +os.time = function() return now end +local writes = true +package.preload["book.books_db"] = function() + return { + getToc = function(_source_id, stable_id, max_age) + reads = reads + 1 + local row = store[stable_id] + if not row or (max_age and now - row.at >= max_age) then return nil end + return row.payload, row.at + end, + setToc = function(_source_id, stable_id, payload) + if not writes then return false end + upserted[stable_id] = payload + store[stable_id] = { payload = payload, at = now } + return true + end, + } +end +package.preload["json"] = function() + return { + decode = require("support.json_stub").decode, + encode = function(value) return "encoded:" .. tostring(#value) end, + } +end + +package.loaded["moonsource_weread.toc"] = nil +local Toc = require("moonsource_weread.toc") +local readToc = require("book.toc_db").read +require("book.toc_db").read = function(...) + reads = reads + 1 + return readToc(...) +end + +do + Assert.is_nil(Toc.read("ext.weread", "missing")) + Assert.is_nil(Toc.read("ext.weread", "broken")) +end + +do + -- payload 是目录数组(与 Mapper.chapters 输出一致),按数组索引定位。 + store["b2"] = { payload = [[ + [{"idx":1,"source_idx":2,"uid":"u1","toc_version":3},{"idx":2,"source_idx":4,"uid":"u2"}] + ]], at = now } + Assert.eq(Toc.uid("ext.weread", "b2", 1), "u1") + Assert.eq(Toc.uid("ext.weread", "b2", 2), "u2") + Assert.is_nil(Toc.uid("ext.weread", "b2", 99)) + Assert.eq(Toc.index("ext.weread", "b2", "u2"), 2) + Assert.is_nil(Toc.index("ext.weread", "b2", "u9")) + Assert.eq(Toc.sourceIndex("ext.weread", "b2", 1), 2) + Assert.eq(Toc.sourceIndex("ext.weread", "b2", 2), 4) + Assert.is_nil(Toc.sourceIndex("ext.weread", "b2", 99)) +end + +do + store["old"] = { payload = [[{"idx":1,"source_idx":2,"uid":"old"}]], at = now } + local old = Toc.read("ext.weread", "old") + Assert.not_nil(old, "旧目录仍须支持离线读取") + Assert.is_false(Toc.isCurrent(old)) +end + +do + -- 解码结果进内存:库里的行没了也照样命中,翻页/按章补报不再反复 decode 整份目录。 + local before = reads + store["b2"] = nil + require("utils.db").removeIdentity("toc_entries", "ext.weread", "b2") + require("utils.db").removeIdentity("toc_snapshots", "ext.weread", "b2") + Assert.eq(Toc.uid("ext.weread", "b2", 1), "u1") + Assert.eq(Toc.index("ext.weread", "b2", "u2"), 2) + Assert.eq(reads, before, "命中内存缓存时不得再查库") + + -- clear 后回落到库(此时库里已无数据) + Toc.clear() + Assert.is_nil(Toc.read("ext.weread", "b2")) + Assert.is_true(reads > before) +end + +do + -- put 落库并直接接管缓存,无需再 decode 一遍 + local list = { { idx = 1, uid = "p1" }, { idx = 2, uid = "p2" }, { idx = 3, uid = "p3" } } + Toc.put("ext.weread", "b3", list) + Assert.is_nil(upserted["b3"], "不再写旧 JSON 列") + local before = reads + Assert.eq(Toc.uid("ext.weread", "b3", 3), "p3") + Assert.eq(Toc.index("ext.weread", "b3", "p2"), 2) + Assert.eq(reads, before) + + -- 章内进度 + 章节序号 → 全书 fraction + Assert.eq(Toc.wholeFraction("ext.weread", "b3", 1, 0), 0) + Assert.eq(Toc.wholeFraction("ext.weread", "b3", 2, 0.5), 0.5) + Assert.eq(Toc.wholeFraction("ext.weread", "b3", 3, 1), 1) + Assert.is_nil(Toc.wholeFraction("ext.weread", "unknown", 1, 0)) + + local cached_reads = reads + Assert.eq(Toc.uid("ext.weread", "b3", 1), "p1") + Assert.eq(reads, cached_reads) + Toc.clear() + Toc.read("ext.weread", "b3") + Assert.is_true(reads > cached_reads, "clear 后必须回库") +end + +do + local list = { { idx = 1, uid = "failed" } } + writes = false + Assert.is_false(Toc.put("ext.weread", "failed", list)) + Assert.is_nil(Toc.read("ext.weread", "failed")) + writes = true + -- 清内存后直接从逐章表恢复。 + Toc.clear() + Assert.eq(Toc.read("ext.weread", "b3")[1].uid, "p1") + now = now + 6 * 60 * 60 + Assert.eq(Toc.read("ext.weread", "b3")[1].uid, "p1", "目录不做时间保鲜,旧缓存仍可用") +end + +os.time = original_time +require("utils.db").close() +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end diff --git a/tests/weread/wechat_spec.lua b/tests/weread/wechat_spec.lua new file mode 100644 index 0000000..5aba5ec --- /dev/null +++ b/tests/weread/wechat_spec.lua @@ -0,0 +1,1825 @@ +--[[-- +source.wechat 门面离线用例:进度 fraction↔percent 换算、chapter_uid 目录匹配、封面缓存。 + +client/auth/chapter/settings 用 package.preload 打桩;mapper 用真实实现。 + +@module tests.wechat_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") +local db_path = require("support.config").dir() .. "/wechat_source_spec.sqlite3" +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +require("utils.paths").dbPath = function() return db_path end + +-- 顶掉网络/会话依赖;结束后统一还原 +local saved_preload = {} +local function stub(name, factory) + saved_preload[name] = package.preload[name] + package.preload[name] = factory + package.loaded[name] = nil +end + +-- 可控假 client:每个用例按需覆写方法 +local fake_client = { + markFinishedAsync = function(_, _book_id, cb) + cb({ status = 4 }) + return { cancel = function() end } + end, +} +local chapter_open = {} +local chapter_range_html = "

" .. string.rep("正文", 8000) .. "

" +local chapter_fetches = 0 +local progress_ui = { shown = 0, closed = 0, progress = {} } +local remembered_stats_books = {} +local existing_book + +-- 目录缓存 payload 要真解码才能取出 chapter_uid +stub("json", function() + return { + decode = require("support.json_stub").decode, + encode = require("support.json_stub").encode, + } +end) + +-- 目录缓存:按 stable_id 供给 payload,未登记的书一律未命中 +local toc_payload = {} +stub("book.books_db", function() + return { + reconcile = function(_, books) remembered_stats_books.last_snapshot = books; return true, 0 end, + stableIdsBySource = function() return {} end, + get = function() return existing_book end, + getMany = function(_, ids) + local out = {} + for _idx, id in ipairs(ids) do + local row = (remembered_stats_books.local_rows or {})[id] + if row then out[id] = row end + end + return out + end, + getToc = function(_, stable_id) return toc_payload[stable_id] end, + setToc = function(_, stable_id, payload) + toc_payload[stable_id] = payload + return true + end, + libraryStableIdsBySource = function() + return remembered_stats_books.local_library or {} + end, + pendingDeleteIds = function() + local m = remembered_stats_books.marked_deleted + return m and not remembered_stats_books.removed and { m.stable_id } or {} + end, + pendingShelfAddIds = function() + return remembered_stats_books.pending_adds or {} + end, + unsynced = function() + local m = remembered_stats_books.marked_deleted + return m and not remembered_stats_books.removed and { m } or {} + end, + markSynced = function() return true end, + setRead = function(source_id, stable_id, is_read) + remembered_stats_books.set_read = { + source_id = source_id, stable_id = stable_id, is_read = is_read, + } + return true + end, + remove = function(source_id, stable_id) + remembered_stats_books.removed = { source_id = source_id, stable_id = stable_id } + return true + end, + } +end) +local existing_progress +stub("book.progress_db", function() + return { + get = function() return existing_progress end, + upsertRemote = function() return true end, + unsynced = function() return {} end, + } +end) +stub("book.chapters_db", function() + return { + deleteUnder = function(dir) + remembered_stats_books.chapter_deleted_under = dir + return true + end, + } +end) +stub("utils.settings", function() + return { + getSource = function() return {} end, + saveSource = function() end, + } +end) +stub("moonsource_weread.auth", function() + return { + hasSession = function() return true end, + userLabel = function() return "tester" end, + sessionHeaders = function() return { Cookie = "wr_skey=stub" } end, + } +end) +fake_client.addToShelfAsync = function(_, _, cb) + if cb then cb({ ok = true }) end + return { cancel = function() end } +end +stub("moonsource_weread.client", function() + return fake_client +end) +stub("moonsource_weread.chapter", function() + return { + fetchHtmlAsync = function(_, _, cb) + chapter_fetches = chapter_fetches + 1 + cb(chapter_range_html, nil, chapter_range_html, "html") + return { cancel = function() end } + end, + fetchContentAsync = function(_, _, cb) + cb(nil, "试读") + return { cancel = function() end } + end, + } +end) +stub("book.review_cache", function() + return { + hotspotsAsync = function(_, fetch, cb) return fetch(cb) end, + pageAsync = function(_, _, _, fetch, cb) return fetch(cb) end, + } +end) +stub("ui/network/manager", function() + return { runWhenConnected = function(_, fn) fn() end, isConnected = function() return true end } +end) +stub("ui/widget/progressbardialog", function() + return { + new = function(_, opts) + return { + show = function() progress_ui.shown = progress_ui.shown + 1 end, + close = function() progress_ui.closed = progress_ui.closed + 1 end, + reportProgress = function(_, step) + progress_ui.progress[#progress_ui.progress + 1] = step + end, + } + end, + } +end) +stub("source.chapter", function() + return { + openWithUi = function(_, _, _, _, ops, cb) + local dialog = require("ui/widget/progressbardialog"):new{} + dialog:show() + ops.progress = function(step) dialog:reportProgress(step) end + ops.progress(1) + ops.progress(4) + dialog:close() + chapter_open.ops = ops + cb(chapter_open.path, chapter_open.err) + return { cancel = function() chapter_open.cancelled = true end } + end, + } +end) +stub("book.store", function() + return { + rememberMany = function(books) remembered_stats_books = books end, + markDeleted = function(source_id, stable_id) + remembered_stats_books.marked_deleted = { source_id = source_id, stable_id = stable_id } + return true + end, + } +end) + +package.loaded["moonsource_weread.source"] = nil +local WeChat = require("moonsource_weread.source") + +local REF = { source_id = "ext.weread", stable_id = "b1", book = { title = "微信书" } } + +do + local caps = WeChat.new():capabilities() + Assert.is_false(caps.scrape) + Assert.is_true(caps.edit) + Assert.is_true(caps.stats_pull) +end + +-- 年度不带日明细时,必须继续拉对应月份。 +do + local requests = {} + fake_client.readStatsAsync = function(_, mode, base_time, cb) + requests[#requests + 1] = { mode, base_time } + if mode == "overall" then + cb({ + totalReadTime = 7200, + readTimes = { + ["1735689600"] = 3600, + ["1767225600"] = 3600, + }, + }) + elseif mode == "annually" and base_time == 1735689600 then + cb({ + baseTime = base_time, + readTimes = { [tostring(base_time)] = 900 }, + }) + elseif mode == "annually" then + cb({ + baseTime = base_time, + dailyReadTimes = { [tostring(base_time)] = 900 }, + }) + else + cb({ + baseTime = base_time, + readTimes = { [tostring(base_time + 86400)] = 900 }, + }) + end + return { cancel = function() end } + end + -- 书架:same 云端累计与本地快照一致 → 不拉;新近更新的 fresh 先拉;broken 拉失败只跳过 + fake_client.shelfSyncAsync = function(_, cb) + cb({ bookProgress = { + { bookId = "same", readingTime = 500, updateTime = 30 }, + { bookId = "broken", readingTime = 100, updateTime = 10 }, + { bookId = 42, readingTime = 2578, updateTime = 20 }, + } }) + return { cancel = function() end } + end + local readinfo = {} + fake_client.readInfoAsync = function(_, book_id, cb) + readinfo[#readinfo + 1] = book_id + if book_id == "broken" then + cb(nil, "网络错误") + else + cb({ readDetail = { totalReadingTime = 2578, data = { + { readDate = 1790352000, readTime = 440 }, + { readDate = 1790438400, readTime = 134 }, + { readDate = 1790524800, readTime = 0 }, + } } }) + end + return { cancel = function() end } + end + local StatsDB = require("book.stats_db") + local real_book_totals = StatsDB.bookTotals + StatsDB.bookTotals = function(source_id) + Assert.eq(source_id, "ext.weread") + return { same = 500, broken = 90 } + end + local result + WeChat.new():pullStatsAsync(function(value) result = value end) + StatsDB.bookTotals = real_book_totals + fake_client.shelfSyncAsync, fake_client.readInfoAsync = nil, nil + Assert.eq(readinfo[1], "42", "最近更新的书先拉,数字 bookId 统一为字符串") + Assert.eq(readinfo[2], "broken") + Assert.len(readinfo, 2, "云端累计没变的书不发 readinfo") + Assert.len(result.replace.books, 1, "拉失败的书不替换,快照不变留待下次重试") + Assert.eq(result.replace.books[1], "42") + local book_days, book_total = {}, nil + for _, row in ipairs(result.rows) do + if row.stable_id == "42" and row.record_type == "book_day" then + book_days[#book_days + 1] = row + Assert.is_true(row.last_time > 0, "book_day 记拉取时间") + end + if row.stable_id == "42" and row.record_type == "book_total" then book_total = row.duration end + if row.record_type == "day" then Assert.is_true(row.last_time > 0, "日桶记拉取时间") end + end + Assert.len(book_days, 2, "0 秒的日子不落行") + Assert.eq(book_total, 2578, "快照取书架 readingTime,与触发拉取的值一致才能收敛") + Assert.eq(requests[1][1], "overall") + Assert.eq(requests[2][1], "annually") + Assert.eq(requests[3][1], "annually") + Assert.eq(requests[4][1], "monthly") + Assert.eq(requests[4][2], 1735689600) + Assert.len(requests, 4, "不再按周拉排行") + Assert.not_nil(requests[2][2]) + Assert.not_nil(requests[3][2]) + Assert.eq(result.replace.mode, "ranges") + Assert.len(result.replace.ranges, 4) + local total, monthly_day + for _, row in ipairs(result.rows) do + if row.record_type == "total" then total = row.duration end + if row.stable_id == "__wr:day:1735776000" then monthly_day = row.duration end + end + Assert.eq(total, 7200) + Assert.eq(monthly_day, 900) + fake_client.readStatsAsync = nil +end + +toc_payload["bp"] = require("support.json_stub").encode({ + { idx = 1, source_idx = 3, uid = "u1", title = "一" }, + { idx = 2, source_idx = 5, uid = "u2", title = "二" }, +}) + +-- pushStatsAsync 按 App 离线上报:全部书一次 batchUploadProgress;成功才确认,失败一本都不确认。 +do + local Eink = require("moonsource_weread.eink") + local real_creds, real_install = Eink.credentials, Eink.installId + Eink.credentials = function() return { vid = "9", device_id = "dev1" } end + Eink.installId = function() return "inst1" end + local src = WeChat.new() + local posted = {} + local fail_batch + fake_client.guestTokenAsync = function(_, cb) cb("tok") end + fake_client.getProgressAsync = function(_, _book_id, cb) + cb({ book = { chapterUid = 12, chapterIdx = 9, chapterOffset = 23456, + progress = 77, summary = "云端最新位置" } }) + end + fake_client.reportBatchAsync = function(_, books, cb) + posted = books + if fail_batch then cb(nil, "boom") else cb({ succ = 1 }) end + end + local rows = { + { id = 1, stable_id = "bp", chapter_idx = 1, chapter_fraction = 0.5, start_time = 3590, duration = 20 }, + { id = 2, stable_id = "bp", chapter_idx = 2, chapter_fraction = 0.25, start_time = 7300, duration = 10 }, + { id = 3, stable_id = "nobook", chapter_idx = 1, start_time = 100, duration = 5 }, + } + local data, err + src:pushStatsAsync(rows, function(value, e) data, err = value, e end) + Assert.is_nil(err) + Assert.len(posted, 2, "两本书一次离线上报,不按本拆请求") + Assert.eq(posted[1].isResendReadingInfo, 1) + Assert.eq(posted[2].isResendReadingInfo, 1) + local body = posted[1] + Assert.eq(body.bookId, "bp") + Assert.eq(body.chapterUid, 12) + Assert.eq(body.chapterIdx, 9, "保留云端最新章节,不用旧统计行的位置") + Assert.eq(body.chapterOffset, 23456, "原文偏移可超过 10000") + Assert.eq(body.currentProgress, 77) + Assert.eq(body.progress, 77) + Assert.eq(body.readUpdateTime, 7310, "批量体带这段阅读结束的时间,不是发送时刻") + Assert.eq(posted[2].readUpdateTime, 105) + Assert.eq(body.summary, "云端最新位置") + Assert.eq(body.deviceId, "dev1") + Assert.eq(body.installId, "inst1") + Assert.eq(body.readingTime, 30) + Assert.len(body.hours, 3, "跨整点拆桶") + Assert.eq(body.hours[1].startOfHour, 0) + Assert.eq(body.hours[1].readingTime, 10) + Assert.eq(#body.signature, 64) + Assert.len(data.synced_ids, 3, "上报成功与无目录跳过的行都确认") + + local ProgressDB = require("book.progress_db") + local orig_get = ProgressDB.get + local progress_hits = 0 + local cloud_progress = fake_client.getProgressAsync + fake_client.getProgressAsync = function(_, book_id, cb) + progress_hits = progress_hits + 1 + cloud_progress(_, book_id, cb) + end + ProgressDB.get = function(_, stable_id) + if stable_id ~= "bp" then return nil end + return { + sync_status = 1, fraction = 0.4, chapter_idx = 1, chapter_fraction = 0.5, + extra = { + chapter_uid = 8, chapter_idx = 1, chapter_offset = 999, + summary = "本地位置", book_version = 3, + }, + } + end + posted = {} + src:pushStatsAsync(rows, function(value, e) data, err = value, e end) + Assert.is_nil(err) + Assert.eq(posted[1].chapterUid, 8) + Assert.eq(posted[1].chapterIdx, 3, "本地章序号要换成微信原始 chapterIdx") + Assert.eq(posted[1].chapterOffset, 999, "时长上报带上次确认的本地坐标,不抄云端") + Assert.eq(posted[1].currentProgress, 40) + Assert.eq(posted[1].progress, 40) + Assert.eq(posted[1].summary, "本地位置") + Assert.eq(posted[1].bookVersion, 3) + Assert.eq(posted[1].chapterProgress, 50) + Assert.eq(progress_hits, 1, "有本地坐标的书不再拉云端进度") + Assert.eq(posted[2].chapterOffset, 23456) + + ProgressDB.get = function(_, stable_id) + if stable_id == "bp" then return { sync_status = 0 } end + end + posted = {} + src:pushStatsAsync(rows, function(value, e) data, err = value, e end) + Assert.is_nil(err) + Assert.len(posted, 1, "进度还是脏的,这本书的时长留给进度请求") + Assert.eq(posted[1].bookId, "nobook") + Assert.len(data.synced_ids, 1) + Assert.eq(data.synced_ids[1], 3) + + local Session = require("reader.session") + local orig_current = Session.current + Session.current = function() + return { identity = { source_id = "ext.weread", stable_id = "bp" } } + end + ProgressDB.get = orig_get + posted = {} + src:pushStatsAsync(rows, function(value, e) data, err = value, e end) + Assert.is_nil(err) + Assert.len(posted, 1, "书正开着,时长先别报") + Assert.eq(posted[1].bookId, "nobook") + Session.current = orig_current + fake_client.getProgressAsync = cloud_progress + + posted, fail_batch = {}, true + src:pushStatsAsync(rows, function(value, e) data, err = value, e end) + Assert.is_nil(data) + Assert.eq(err, "boom", "整批失败就报错,行留作脏行") + + fake_client.guestTokenAsync, fake_client.reportBatchAsync, fake_client.getProgressAsync = nil, nil, nil + Eink.credentials, Eink.installId = real_creds, real_install +end + +-- 开章与拉取结束都不抢写云端进度,必须等阅读会话解决冲突。 +do + local src = WeChat.new() + require("moonsource_weread.context").clear() + local entered = {} + fake_client.putProgressAsync = function(_, book_id, opts, cb) + entered[#entered + 1] = opts + require("moonsource_weread.context").reader(book_id, opts.chapter_uid).entered = true + cb({ ok = true }) + end + local stats_pushes = {} + stub("book.stats", function() + return { push = function(source) stats_pushes[#stats_pushes + 1] = source end } + end) + local identity = { source_id = "ext.weread", stable_id = "bp", chapter_idx = 1 } + src:onEvent("chapter_changed", { + identity = identity, + position = { fraction = 0.1, chapter_idx = 1, chapter_fraction = 0.2 }, + }) + require("support.stubs").flush() + Assert.len(entered, 0, "开读章节不能在冲突决议前覆盖云端") + Assert.len(stats_pushes, 1, "开章时顺手补报上一章已落库的时长") + + -- 开书拉云端进度期间挂起 enter,拉取回调之后再发,避免 enter 写的位置吞掉进度冲突。 + local pull_cb + fake_client.getProgressAsync = function(_, _, cb) + pull_cb = cb + return { cancel = function() end } + end + require("moonsource_weread.context").clear() + entered = {} + local pulled + src:getProgressAsync(identity, function(_, err) pulled = err end) + src:onEvent("chapter_changed", { identity = identity, position = { chapter_idx = 1 } }) + require("support.stubs").flush() + Assert.len(entered, 0, "拉取未返回前不 enter") + pull_cb(nil, "offline") + require("support.stubs").flush() + Assert.eq(pulled, "offline") + Assert.len(entered, 0, "拉取失败也不能抢写") + + -- 取消拉取(关书 / 换书)不能吞掉挂起的 enter;回调后再取消也不重复发。 + entered = {} + local job = src:getProgressAsync(identity, function() error("取消后不回调") end) + src:onEvent("chapter_changed", { identity = identity, position = { chapter_idx = 1 } }) + require("support.stubs").flush() + Assert.len(entered, 0) + job.cancel() + require("support.stubs").flush() + Assert.len(entered, 0, "取消不上传位置") + job.cancel() + pull_cb(nil, "late") + require("support.stubs").flush() + Assert.len(entered, 0, "取消后迟到的回包不上传") + src:onEvent("chapter_changed", { identity = identity, position = { chapter_idx = 1 } }) + require("support.stubs").flush() + Assert.len(entered, 0, "之后切章仍不抢写") + fake_client.putProgressAsync = nil + fake_client.getProgressAsync = nil +end + +-- 拉进度:精确定位拿不到正文(离线)或对不上时退回章级位置,不把整条进度丢掉。 +do + local src = WeChat.new() + local Toc = require("moonsource_weread.toc") + local Position = require("moonsource_weread.progress") + local old_index, old_read, old_load, old_localize = Toc.index, Toc.read, Position.loadAsync, Position.localize + Toc.index = function() return 3 end + Toc.read = function() return { [3] = { title = "第三章" } } end + fake_client.getProgressAsync = function(_, _, cb) + cb({ book = { chapterUid = 33, chapterIdx = 9, chapterOffset = 120, progress = 40 } }) + return { cancel = function() end } + end + local identity = { source_id = "ext.weread", stable_id = "bp", chapter_idx = 1 } + + Position.loadAsync = function(_identity, _chapter, cb) cb(nil, "offline") end + local pos, err + src:getProgressAsync(identity, function(p, e) pos, err = p, e end) + Assert.is_nil(err) + Assert.eq(pos.chapter_idx, 3, "正文拿不到:退回章级位置") + Assert.eq(pos.extra.chapter_uid, 33) + Assert.eq(pos.extra.chapter_offset, 120, "原文偏移保留给 push 复用") + + Position.loadAsync = function(_identity, _chapter, cb) cb("

x

", "html") end + Position.localize = function() return nil, "无法定位阅读进度" end + pos, err = nil, nil + src:getProgressAsync(identity, function(p, e) pos, err = p, e end) + Assert.is_nil(err) + Assert.eq(pos.chapter_idx, 3, "定位失败:退回章级位置") + + Toc.index, Toc.read, Position.loadAsync, Position.localize = old_index, old_read, old_load, old_localize + fake_client.getProgressAsync = nil +end + +-- getDetailAsync:wire 经 mapper 转 Book,并把封面 URL 记进缓存供 coverRequest 用 +do + local src = WeChat.new() + existing_book = { deleted = 0 } + existing_progress = { fraction = 0.37 } + fake_client.bookInfoAsync = function(_, book_id, cb) + Assert.eq(book_id, "b1") + cb({ book = { bookId = "b1", title = "详情书", author = "某人", + intro = "完整简介", cover = "https://img.weread.qq.com/c.jpg" } }) + return { cancel = function() end } + end + local book, err + src:getDetailAsync(REF, function(b, e) book, err = b, e end) + Assert.is_nil(err) + Assert.eq(book.stable_id, "b1") + Assert.eq(book.title, "详情书") + Assert.eq(book.intro, "完整简介") + Assert.eq(book.percent, 37, "详情接口缺进度时必须保留数据库进度") + Assert.len(remembered_stats_books, 1) + Assert.eq(remembered_stats_books[1].intro, "完整简介", + "完整详情必须持久化,不能只活在当前详情页") + Assert.eq(src:coverRequest(REF).url, "https://img.weread.qq.com/c.jpg") + + -- 空 wire → 明确报错而非返回半个 Book + fake_client.bookInfoAsync = function(_, _, cb) + cb({}) + return { cancel = function() end } + end + book, err = nil, nil + src:getDetailAsync(REF, function(b, e) book, err = b, e end) + Assert.is_nil(book) + Assert.eq(err, "书籍详情为空") + + fake_client.bookInfoAsync = function(_, _, cb) + cb(nil, "详情拉取失败") + return { cancel = function() end } + end + book, err = nil, nil + src:getDetailAsync(REF, function(b, e) book, err = b, e end) + Assert.is_nil(book) + Assert.eq(err, "详情拉取失败") + fake_client.bookInfoAsync = nil + existing_book = nil + existing_progress = nil +end + +-- openBookAsync:源自己管理联网/进度 UI,成功首参只返回已入库物理路径。 +do + chapter_open.path = "/cache/wechat/b1/2.html" + chapter_open.err = nil + local src = WeChat.new() + local path, err, extra + src:openBookAsync(REF, { chapter_idx = 2 }, function(...) + path, err, extra = ... + end) + Assert.eq(path, "/cache/wechat/b1/2.html") + Assert.is_nil(err) + Assert.is_nil(extra, "源打开回调不得泄露章节上下文") + Assert.eq(progress_ui.shown, 1) + Assert.eq(progress_ui.closed, 1) + Assert.eq(progress_ui.progress[#progress_ui.progress], 4) + + chapter_open.path = nil + chapter_open.err = "下载失败" + src:openBookAsync(REF, nil, function(p, e) + path, err = p, e + end) + Assert.is_nil(path) + Assert.eq(err, "下载失败") + Assert.eq(progress_ui.shown, 2) + Assert.eq(progress_ui.closed, 2) + + -- 用户点开的章取不到正文:给临时提示页,不是失败;预取 / 整本缓存不经这里。 + local payload, fetch_err + chapter_open.ops.fetchContent(REF, { title = "第二章" }, function(p, e) payload, fetch_err = p, e end) + Assert.is_nil(fetch_err) + Assert.is_true(payload.temporary) + Assert.matches(payload.html, "试读") +end + +-- putProgressAsync:fraction → percent(0/1 边界、四舍五入、缺进度兜底) +do + toc_payload["b1"] = [[ + [{"idx":1,"source_idx":2,"uid":"40"},{"idx":2,"source_idx":4,"uid":"41"}, + {"idx":3,"source_idx":7,"uid":"42"}] + ]] + local captured + local StatsDB = require("book.stats_db") + local orig_unsynced, orig_mark = StatsDB.unsyncedBySource, StatsDB.markSynced + local marked_hours + StatsDB.unsyncedBySource = function() + return { { id = 7, stable_id = "b1", start_time = 3600, duration = 15 } } + end + StatsDB.markSynced = function(ids) + marked_hours = ids + return true + end + fake_client.putProgressAsync = function(_, stable_id, opts, cb) + captured = { + stable_id = stable_id, + progress = opts.progress, + current_progress = opts.current_progress, + chapter_uid = opts.chapter_uid, + chapter_idx = opts.chapter_idx, + chapter_offset = opts.chapter_offset, + summary = opts.summary, + hours = opts.hours, + } + cb({ ok = true }) + return { cancel = function() end } + end + local src = WeChat.new() + + local function put(pos) + if pos and not pos.locator and pos.extra and pos.extra.chapter_idx == 0 then + pos.chapter_fraction = 0 + end + local ok, err + src:putProgressAsync(REF, pos, function(v, e) ok, err = v, e end) + return ok, err + end + + -- 源私有的 chapter_uid 走 extra;REF 无 chapter_idx,归一后为 0 + local UID = { chapter_uid = 42, chapter_idx = 0, chapter_offset = 12345 } + Assert.is_true(put({ fraction = 0, extra = UID })) + Assert.eq(captured.progress, 0) + Assert.eq(captured.hours[1].readingTime, 15, "进度请求带上还没报的时长") + Assert.eq(marked_hours[1], 7, "报成功才确认这些统计行") + Assert.eq(UID.chapter_offset, 0, "编码出的坐标写回 extra,下一轮时长才带得走") + Assert.is_true(put({ fraction = 1, extra = UID })) + Assert.eq(captured.progress, 100) + Assert.eq(captured.current_progress, 100) + Assert.is_true(put({ fraction = 0.5, extra = UID })) + Assert.eq(captured.progress, 50) + -- 四舍五入:0.666 → 67 + Assert.is_true(put({ fraction = 0.666, extra = UID })) + Assert.eq(captured.progress, 67) + -- clampFraction 兼容 1..100 百分数入参 + Assert.is_true(put({ fraction = 25, extra = UID })) + Assert.eq(captured.progress, 25) + -- 缺 chapter_uid 无法上传 + Assert.is_nil(put({})) + Assert.is_nil(put(nil)) + -- 没有章节的行:未读完 → 永久失败;读完(手动标已读)→ 按末章读完上报 + local perm + src:putProgressAsync(REF, { fraction = 0.5 }, function(_, _, meta) perm = meta end) + require("support.stubs").flush() + Assert.is_true(perm and perm.permanent) + local done + src:putProgressAsync(REF, { fraction = 1 }, function(v) done = v end) + require("support.stubs").flush() + Assert.is_true(done) + Assert.eq(captured.chapter_uid, "42") + Assert.eq(captured.chapter_offset, 16015, "章末取真实原文坐标,不是固定 10000") + Assert.eq(captured.progress, 100) + local BookDB = require("book.books_db") + local orig_book = BookDB.get + BookDB.get = function() + return { meta = { + weread_ended = true, + source = { ["ext.weread"] = { pay_type = 2, ended = false } }, + } } + end + Assert.is_true(put({ fraction = 1, extra = UID })) + Assert.eq(captured.progress, 99, "未完结连载的书架进度封顶 99") + Assert.eq(captured.current_progress, 100) + local serial_done + src:putProgressAsync(REF, { fraction = 1 }, function(v) serial_done = v end) + require("support.stubs").flush() + Assert.is_true(serial_done) + Assert.eq(captured.progress, 99, "手动读完连载仍封顶,读完标记走 markstatus") + BookDB.get = function() return { meta = { weread_pay = 2, weread_ended = false } } end + Assert.is_true(put({ fraction = 1, extra = UID })) + Assert.eq(captured.progress, 99, "兼容已保存的旧版微信元数据") + BookDB.get = orig_book + require("source.toc").clear() + -- stable_id 透传 + Assert.eq(captured.stable_id, "b1") + -- 仅有 chapter_idx、无 uid 且目录拉取失败时不上传 + fake_client.chapterInfosAsync = function(_, _, cb) + cb(nil, "目录拉取失败") + return { cancel = function() end } + end + Assert.is_nil(put({ fraction = 0.5, locator = "epubcfi(/6/4)", chapter_idx = 3 })) + Assert.is_true(put({ fraction = 0.5, extra = UID })) + Assert.eq(captured.chapter_uid, 42) + Assert.is_true(put({ + fraction = 0.5, chapter_idx = 3, chapter_fraction = 0.25, chapter_title = "序章", + locator = "/html/body/p/text().12345", + extra = { chapter_uid = 42, chapter_idx = 3, chapter_offset = 1 }, + })) + Assert.eq(captured.chapter_idx, 7, "上传必须使用微信原始 chapterIdx") + Assert.eq(captured.chapter_offset, 12360, "必须按 XPointer 计算,不能复用旧 extra 偏移") + Assert.eq(captured.summary, string.rep("文正", 15), "摘要必须是当前位置正文,不是章名") + -- extra 记的是别的章:不复用旧 uid,回落到目录解析(此处目录拉取失败 → 不上传) + Assert.is_nil(put({ fraction = 0.5, chapter_idx = 7, extra = { chapter_uid = 42, chapter_idx = 3 } })) + -- 目标章不在目录里:不能回退成当前打开章的 uid,否则进度报到错误章节 + require("support.stubs").flush() + captured = nil + local in_chapter = setmetatable({ chapter_idx = 1 }, { __index = REF }) + local ok, err + src:putProgressAsync(in_chapter, { fraction = 0.5, chapter_idx = 9 }, function(v, e) ok, err = v, e end) + require("support.stubs").flush() + Assert.is_nil(ok) + Assert.eq(err, "缺少章节信息") + Assert.is_nil(captured, "不得用当前章 uid 40 上报") + -- locator 对不上章节正文:按章级坐标回退上报,不再失败重试 + local map_ok, map_err, map_meta + captured = nil + src:putProgressAsync(REF, { + fraction = 0.5, + chapter_fraction = 0.25, + locator = "/html/body/div/text().0", + extra = { chapter_uid = 42, chapter_idx = 0, chapter_offset = 99999 }, + }, function(v, e, meta) map_ok, map_err, map_meta = v, e, meta end) + Assert.is_true(map_ok) + Assert.is_nil(map_err) + Assert.not_nil(captured) + Assert.is_nil(map_meta and map_meta.permanent) + Assert.eq(captured.chapter_offset, math.floor(0.25 * 16015 + 0.5), + "对不上时按章内比例换算,不复用陈旧 extra 偏移") + captured = nil + src:putProgressAsync(REF, { + fraction = 0.5, + locator = "/html/body/div/text().0", + extra = { chapter_uid = 42, chapter_idx = 0, chapter_offset = 321 }, + }, function(v, e, meta) map_ok, map_err, map_meta = v, e, meta end) + Assert.is_true(map_ok) + Assert.is_nil(map_err) + Assert.eq(captured.chapter_offset, 321, "没有章内比例时回退同章旧偏移") + captured = nil + src:putProgressAsync(REF, { + fraction = 0.5, + locator = "/html/body/div/text().0", + extra = { chapter_uid = 42, chapter_idx = 0 }, + }, function(v, e, meta) map_ok, map_err, map_meta = v, e, meta end) + Assert.is_true(map_ok) + Assert.is_nil(map_err) + Assert.eq(captured.chapter_offset, 0, "对不上且没有可用比例/偏移时按章首上报") + toc_payload["b1"] = nil + require("book.toc_db").removeIdentity("ext.weread", "b1") + require("moonsource_weread.toc").clear() + StatsDB.unsyncedBySource, StatsDB.markSynced = orig_unsynced, orig_mark +end + +-- putProgressAsync:失败时错误原样透传;client 的 permanent 元信息也要透传 +do + fake_client.putProgressAsync = function(_, _, _, cb) + cb(nil, "写入失败") + return { cancel = function() end } + end + local src = WeChat.new() + local ok, err + src:putProgressAsync(REF, { + fraction = 0.5, chapter_fraction = 0, extra = { chapter_uid = 42, chapter_idx = 0 }, + }, function(v, e) ok, err = v, e end) + Assert.is_nil(ok) + Assert.eq(err, "写入失败") + + fake_client.putProgressAsync = function(_, _, _, cb) + cb(nil, "上报响应异常", { permanent = true }) + return { cancel = function() end } + end + local soft_ok, soft_err, soft_meta + src:putProgressAsync(REF, { + fraction = 0.5, chapter_fraction = 0, extra = { chapter_uid = 42, chapter_idx = 0 }, + }, function(v, e, m) soft_ok, soft_err, soft_meta = v, e, m end) + Assert.is_nil(soft_ok) + Assert.eq(soft_err, "上报响应异常") + Assert.is_true(soft_meta and soft_meta.permanent) +end + +-- getProgressAsync:percent → fraction(边界 0/100、缺进度兜底、已读完抬满) +do + local wire + fake_client.getProgressAsync = function(_, _, cb) + cb(wire) + return { cancel = function() end } + end + local src = WeChat.new() + + local function get() + local pos, err + src:getProgressAsync(REF, function(p, e) pos, err = p, e end) + return pos, err + end + + wire = { percent = 50 } + local pos = get() + Assert.eq(pos.fraction, 0.5) + Assert.is_nil(pos.chapter_idx) + + wire = { percent = 0 } + Assert.eq(get().fraction, 0) + + wire = { percent = 100 } + Assert.eq(get().fraction, 1) + + -- 缺进度兜底:wire 无进度字段按 0 + wire = {} + Assert.eq(get().fraction, 0) + + -- 已读完标记把进度抬到 100% + wire = { percent = 30, finishReading = 1 } + Assert.eq(get().fraction, 1) + + -- getProgress 真实 wire:{ bookId, book: { chapterUid, progress, ... } } + wire = { bookId = "42", book = { chapterUid = "99", chapterIdx = 7, progress = 77, chapterOffset = 5000 } } + pos = get() + Assert.eq(pos.fraction, 0.77) + Assert.eq(pos.chapter_idx, 7) + Assert.eq(pos.extra.chapter_offset, 5000) + Assert.eq(pos.locator, "/html/body/p/text().4985") + + -- 自带 chapter_idx 时直接回调,不再拉目录 + wire = { percent = 10, chapterIdx = 7, chapterUid = "99" } + pos = get() + Assert.eq(pos.chapter_idx, 7) + Assert.eq(pos.fraction, 0.1) +end + +-- getProgressAsync:网络失败错误透传;取消后迟到的回调被丢弃 +do + fake_client.getProgressAsync = function(_, _, cb) + cb(nil, "拉取失败") + return { cancel = function() end } + end + local src = WeChat.new() + local pos, err + src:getProgressAsync(REF, function(p, e) pos, err = p, e end) + Assert.is_nil(pos) + Assert.eq(err, "拉取失败") + + local pending + fake_client.getProgressAsync = function(_, _, cb) + pending = cb + return { cancel = function() end } + end + local fired = false + local handle = src:getProgressAsync(REF, function() fired = true end) + handle.cancel() + pending({ percent = 50 }) + Assert.is_false(fired) +end + +-- 封面缓存:syncBooksAsync 记住 http(s) 封面,非法 URL / 无封面不缓存 +do + fake_client.shelfSyncAsync = function(_, cb) + cb({ + books = { + { book = { bookId = "b1", title = "书一", cover = "https://cdn.example.com/a.jpg" } }, + { book = { bookId = "b2", title = "书二", cover = "//cdn.example.com/b.jpg" } }, + { book = { bookId = "b3", title = "书三" } }, + }, + }) + return { cancel = function() end } + end + local src = WeChat.new() + local result + src:syncBooksAsync(nil, function(r) result = r end) + require("support.stubs").flush() + Assert.not_nil(result) + + -- 合法 http(s) 封面入缓存,coverRequest 带回会话头 + local req = src:coverRequest({ source_id = "ext.weread", stable_id = "b1" }) + Assert.not_nil(req) + Assert.eq(req.url, "https://cdn.example.com/a.jpg") + Assert.eq(req.headers.Cookie, "wr_skey=stub") + + -- 新源实例没有内存缓存,必须从 Book/数据库恢复封面。 + local fresh = WeChat.new() + local direct = fresh:coverRequest({ + source_id = "ext.weread", stable_id = "b1", cover = "https://cdn.example.com/a.jpg", + }) + Assert.eq(direct.url, "https://cdn.example.com/a.jpg") + Assert.eq(direct.headers.Cookie, "wr_skey=stub") + + -- 非 http(s) 前缀的封面不入缓存 + local req2, err2 = src:coverRequest({ source_id = "ext.weread", stable_id = "b2" }) + Assert.is_nil(req2) + Assert.eq(err2, "无封面") + + -- 无封面字段的书籍 + local req3 = src:coverRequest({ source_id = "ext.weread", stable_id = "b3" }) + Assert.is_nil(req3) + + -- 重复列表刷新封面缓存(后写覆盖先写) + fake_client.shelfSyncAsync = function(_, cb) + cb({ + books = { + { book = { bookId = "b1", title = "书一", cover = "https://cdn.example.com/a2.jpg" } }, + }, + }) + return { cancel = function() end } + end + src:syncBooksAsync(nil, function() end) + require("support.stubs").flush() + Assert.eq(src:coverRequest({ source_id = "ext.weread", stable_id = "b1" }).url, + "https://cdn.example.com/a2.jpg") + + -- close 清空实例的封面缓存 + src:close() + local req4 = src:coverRequest({ source_id = "ext.weread", stable_id = "b1" }) + Assert.is_nil(req4) +end + +-- syncBooksAsync:本地新加架经 addToShelf 上行,SyncResult.pushed 填实; +-- 已同步但云端已移除的书不加回。 +do + local added = {} + local shelf_calls = 0 + fake_client.shelfSyncAsync = function(_, cb) + shelf_calls = shelf_calls + 1 + cb({ + books = { + { book = { bookId = "remote1", title = "远端书" } }, + }, + }) + return { cancel = function() end } + end + fake_client.addToShelfAsync = function(_, bookId, cb) + added[#added + 1] = bookId + cb({ ok = true }) + return { cancel = function() end } + end + remembered_stats_books.local_library = { "remote1", "local_only", "removed_on_phone" } + remembered_stats_books.pending_adds = { "local_only" } + local src = WeChat.new() + local result + src:syncBooksAsync(nil, function(r) result = r end) + require("support.stubs").flush() + Assert.not_nil(result) + Assert.eq(result.pushed, 1) + Assert.eq(#added, 1) + Assert.eq(added[1], "local_only") + Assert.eq(shelf_calls, 2, "有上行后应再拉一次书架再 reconcile") + remembered_stats_books.local_library = nil + remembered_stats_books.pending_adds = nil +end + +-- pullNotesAsync:微信原始 chapterIdx 必须按 uid 映射成本地过滤后的章节序号。 +do + toc_payload["bpull"] = '[{"idx":5,"source_idx":6,"uid":"41"}]' + fake_client.bookmarkListAsync = function(_, _, cb) + cb({ + updated = { + { + chapterUid = "41", chapterIdx = 6, bookmarkId = "bm1", + type = 1, range = "1-3", markText = "划线", createTime = 1, + }, + }, + chapters = { { chapterUid = "41", chapterIdx = 6 } }, + }) + return { cancel = function() end } + end + fake_client.myReviewsAsync = function(_, _, cb) + cb({ reviews = {} }) + return { cancel = function() end } + end + local annotations + WeChat.new():pullNotesAsync({ + source_id = "ext.weread", stable_id = "bpull", chapter_idx = 5, + }, function(value) annotations = value end) + require("support.stubs").flush() + Assert.eq(annotations[1].chapter_idx, 5) + + -- 目录缓存没有、也拉不到:章节号留空,绝不回退成原始序号 6(本地第 6 章是别的章)。 + toc_payload["bpull"] = nil + require("book.toc_db").removeIdentity("ext.weread", "bpull") + require("source.toc").clear() + fake_client.chapterInfosAsync = function(_, _, cb) + cb(nil, "目录拉取失败") + return { cancel = function() end } + end + annotations = nil + WeChat.new():pullNotesAsync({ + source_id = "ext.weread", stable_id = "bpull", chapter_idx = 5, + }, function(value) annotations = value end) + require("support.stubs").flush() + Assert.len(annotations, 1) + Assert.is_nil(annotations[1].chapter_idx) +end + +-- pushNotesAsync:划线与想法两段队列必须串起来 +do + chapter_fetches = 0 + local NOTE_REF = { + source_id = "ext.weread", + stable_id = "bpush", + chapter_idx = 2, + book = { title = "微信书" }, + } + require("moonsource_weread.context").rememberBookVersion("bpush", 7) + -- chapter_uid 只从目录缓存解析,预置一条免去拉取 + toc_payload["bpush"] = '[{"idx":1,"source_idx":3,"uid":"8"},{"idx":2,"source_idx":6,"uid":"9"}]' + local calls + local remote_bookmarks = { + { + chapterUid = "9", chapterIdx = 6, bookmarkId = "bm1", + type = 1, range = "3-6", markText = "旧划线", + }, + } + chapter_range_html = "

旧划线

新划线

补偿划线

" + .. "

部分一

部分二

" + local Paths = require("utils.paths") + local chapter_path = Paths.chapterPath("bpush", 2, "ext.weread") + assert(Paths.ensureDir(Paths.bookWorkDir("bpush", "ext.weread"))) + -- 沙箱跨运行保留:清掉上次留下的 range 原文缓存,首个定位必走一次拉取并回填缓存 + os.remove(Paths.bookWorkDir("bpush", "ext.weread") .. "/2.position.json") + local chapter_file = assert(io.open(chapter_path, "wb")) + chapter_file:write("

微信书

旧划线

新划线

" + .. "

补偿划线

部分一

部分二

") + chapter_file:close() + local omit_next_id = false + local fail_text + local bookmark_ids = { + ["新划线"] = "bm-new", + ["补偿划线"] = "bm-postflight", + ["部分一"] = "bm-part1", + ["部分二"] = "bm-part2", + } + fake_client.bookmarkListAsync = function(_, _, cb) + cb({ updated = remote_bookmarks }) + return { cancel = function() end } + end + fake_client.myReviewsAsync = function(_, _, cb) + cb({ reviews = { { review = { reviewId = "rv1" } } } }) + return { cancel = function() end } + end + fake_client.addBookmarkAsync = function(_, _, _, body, cb) + local text = body.markText + local remote_id = bookmark_ids[text] + calls[#calls + 1] = { + api = "addBookmark", range = body.range, chapter_idx = body.chapterIdx, + } + if text == fail_text then + fail_text = nil + cb(nil, "timeout") + return { cancel = function() end } + end + remote_bookmarks[#remote_bookmarks + 1] = { + chapterUid = "9", chapterIdx = 6, bookmarkId = remote_id, + type = 1, range = body.range, markText = text, + } + if omit_next_id then + omit_next_id = false + cb({ succ = 1 }) + else + cb({ bookmarkId = remote_id }) + end + return { cancel = function() end } + end + fake_client.addReviewAsync = function(_, body, cb) + calls[#calls + 1] = { api = "addReview", content = body.content, range = body.range } + cb({ reviewId = "rv-new" }) + return { cancel = function() end } + end + fake_client.editReviewAsync = function(_, body, cb) + calls[#calls + 1] = { + api = "editReview", content = body.content, review_id = body.reviewId, + book_id = body.bookId, chapter_uid = body.chapterUid, + range = body.range, abstract = body.abstract, + } + cb({ succ = 1 }) + return { cancel = function() end } + end + fake_client.deleteReviewAsync = function(_, review_id, cb) + calls[#calls + 1] = { api = "deleteReview", review_id = review_id } + cb({ succ = 1 }) + return { cancel = function() end } + end + fake_client.removeBookmarkAsync = function(_, bookmark_id, cb) + calls[#calls + 1] = { api = "removeBookmark", bookmark_id = bookmark_id } + cb({ succ = 1 }) + return { cancel = function() end } + end + fake_client.updateBookmarkAsync = function(_, body, cb) + calls[#calls + 1] = { + api = "updateBookmark", bookmark_id = body.bookmarkId, color_style = body.colorStyle, + } + cb({ succ = 1 }) + return { cancel = function() end } + end + + local src = WeChat.new() + local function push(annotations) + calls = {} + local ok, err + src:pushNotesAsync(NOTE_REF, annotations, function(v, e) ok, err = v, e end) + require("support.stubs").flush() + return ok, err + end + + -- 在已有划线上写想法:无新划线可传,直接走 useredit + local ok, err = push({ + { + drawer = "lighten", text = "旧划线", wr_range = "0-3", + wr_bookmark_id = "bm1", wr_review_id = "rv1", note = "改过的想法", + wr_update_review = true, + }, + }) + Assert.is_true(ok, "editReview 未完成: " .. tostring(err)) + Assert.is_nil(err) + Assert.eq(#calls, 1) + Assert.eq(calls[1].api, "editReview") + Assert.eq(calls[1].review_id, "rv1") + Assert.eq(calls[1].content, "改过的想法") + Assert.eq(calls[1].book_id, "bpush") + Assert.eq(calls[1].chapter_uid, 9) + Assert.eq(calls[1].abstract, "旧划线") + Assert.eq(chapter_fetches, 0) + + -- 想法列表只拿到一页(hasMore):不在这页的 review id 不能当云端已删清掉, + -- 否则会走 addReview 在云端重建一条重复想法。 + local real_my_reviews = fake_client.myReviewsAsync + fake_client.myReviewsAsync = function(_, _, cb) + cb({ reviews = { { review = { reviewId = "rv1" } } }, hasMore = 1, totalCount = 101 }) + return { cancel = function() end } + end + local far = { + drawer = "lighten", text = "旧划线", wr_range = "0-3", + wr_bookmark_id = "bm1", wr_review_id = "rv-far", note = "第101条想法", + wr_update_review = true, + } + ok, err = push({ far }) + Assert.is_true(ok, tostring(err)) + Assert.eq(#calls, 1) + Assert.eq(calls[1].api, "editReview") + Assert.eq(calls[1].review_id, "rv-far") + + -- 全量列表里确实没有:视为云端已删,按新想法重建(原有语义)。 + fake_client.myReviewsAsync = function(_, _, cb) + cb({ reviews = { { review = { reviewId = "rv1" } } }, hasMore = 0, totalCount = 1 }) + return { cancel = function() end } + end + far.wr_review_id, far.wr_update_review = "rv-far", true + ok = push({ far }) + Assert.is_true(ok) + Assert.eq(calls[1].api, "addReview") + fake_client.myReviewsAsync = real_my_reviews + + -- 已有划线但还没有 review:走 add + ok = push({ + { drawer = "lighten", text = "旧划线", wr_range = "0-3", wr_bookmark_id = "bm1", note = "新想法" }, + }) + Assert.is_true(ok) + Assert.eq(#calls, 1) + Assert.eq(calls[1].api, "addReview") + Assert.eq(calls[1].content, "新想法") + + -- 删除整条原生笔记:远端 review 与 bookmark 都要删除,墓碑随后移除。 + local deleted = { + wr_deleted = true, wr_bookmark_id = "bm1", wr_review_id = "rv1", + } + ok, err = push({ deleted }) + Assert.is_true(ok, tostring(err)) + Assert.eq(#calls, 2) + Assert.eq(calls[1].api, "deleteReview") + Assert.eq(calls[2].api, "removeBookmark") + + -- 只清空 note:删除 review,但保留底层划线。 + local cleared = { + datetime = "2026-01-01", drawer = "lighten", text = "旧划线", + wr_range = "0-3", wr_bookmark_id = "bm1", wr_review_id = "rv1", + wr_delete_review = true, + } + ok, err = push({ cleared }) + Assert.is_true(ok, tostring(err)) + Assert.eq(#calls, 1) + Assert.eq(calls[1].api, "deleteReview") + Assert.eq(cleared.wr_bookmark_id, "bm1") + Assert.is_nil(cleared.wr_review_id) + + -- 本地修改划线颜色走 updateBookmark,不得伪造新划线。 + local recolored = { + datetime = "2026-01-01", drawer = "lighten", color = "green", text = "旧划线", + wr_range = "0-3", wr_bookmark_id = "bm1", wr_update_bookmark = true, + } + ok, err = push({ recolored }) + Assert.is_true(ok, tostring(err)) + Assert.eq(#calls, 1) + Assert.eq(calls[1].api, "updateBookmark") + Assert.eq(calls[1].color_style, 2) + Assert.is_nil(recolored.wr_update_bookmark) + + -- KOReader 原生 note 直接映射微信想法,不能先制造一条远端高亮。 + local fresh = { drawer = "lighten", text = "新划线", wr_range = "4-9", note = "随手记" } + ok, err = push({ fresh }) + Assert.is_true(ok) + Assert.is_nil(err) + Assert.eq(#calls, 1) + Assert.eq(calls[1].api, "addReview") + Assert.eq(calls[1].content, "随手记") + Assert.is_nil(fresh.wr_bookmark_id) + Assert.eq(fresh.wr_review_id, "rv-new") + Assert.eq(chapter_fetches, 1) + + -- 前面已有远端笔记时,仍必须扫描并上传后面的本地新笔记。 + local later = { drawer = "lighten", text = "部分一", note = "后面的新笔记" } + ok, err = push({ + { + drawer = "lighten", text = "旧划线", note = "没修改", + wr_range = "0-3", wr_bookmark_id = "bm1", wr_review_id = "rv1", + }, + later, + }) + Assert.is_true(ok, tostring(err)) + Assert.eq(#calls, 1) + Assert.eq(calls[1].api, "addReview") + Assert.eq(calls[1].content, "后面的新笔记") + Assert.eq(later.wr_review_id, "rv-new") + + -- addBookmark 回包缺 id 时由一次 postflight 找回,不能把未确认提交误判成功。 + omit_next_id = true + local recovered = { drawer = "lighten", text = "补偿划线" } + ok, err = push({ recovered }) + Assert.is_true(ok, tostring(err)) + Assert.eq(recovered.wr_bookmark_id, "bm-postflight") + -- 后续定位全部命中首轮回填的 range 原文缓存,不再重拉整章 + Assert.eq(chapter_fetches, 1) + + -- 批次后半超时:下轮 preflight 必须认回前半成功项,只补传失败项。 + fail_text = "部分一" + ok = push({ + { drawer = "lighten", text = "部分一" }, + { drawer = "lighten", text = "部分二" }, + }) + Assert.is_nil(ok) + local retry_first = { drawer = "lighten", text = "部分一" } + local retry_second = { drawer = "lighten", text = "部分二" } + ok, err = push({ retry_first, retry_second }) + Assert.is_true(ok, tostring(err)) + Assert.eq(#calls, 1) + Assert.eq(retry_first.wr_bookmark_id, "bm-part1") + Assert.eq(retry_second.wr_bookmark_id, "bm-part2") + + -- 章内定位不到的划线只跳过自己:不能让一条坏数据卡住整章,每次重试都停在它身上。 + local ghost = { drawer = "lighten", text = "正文里没有这句" } + local located = { drawer = "lighten", text = "新划线" } + ok, err = push({ ghost, located }) + Assert.is_true(ok, tostring(err)) + Assert.eq(#calls, 1) + Assert.eq(calls[1].api, "addBookmark") + Assert.eq(located.wr_bookmark_id, "bm-new") + Assert.is_nil(ghost.wr_bookmark_id) + + -- 带想法的划线在远端已被删:预检清掉 bookmark id 后仍要把想法推上去,不能静默成功。 + local orphan = { + drawer = "lighten", text = "新划线", wr_range = "0-3", + wr_bookmark_id = "bm-gone", note = "孤儿想法", + } + ok, err = push({ orphan }) + Assert.is_true(ok, tostring(err)) + Assert.eq(#calls, 1) + Assert.eq(calls[1].api, "addReview") + Assert.eq(calls[1].content, "孤儿想法") + Assert.eq(orphan.wr_review_id, "rv-new") + + -- 无划线也无想法:不发请求 + ok = push({ { drawer = "lighten", text = "旧划线", wr_bookmark_id = "bm1", wr_range = "0-3" } }) + Assert.is_true(ok) + Assert.eq(#calls, 0) + os.remove(chapter_path) +end + +-- 长按删除:本地先标删,已连网时顺手入队推脏;推脏的书架域推云端真删并撕墓碑 +do + remembered_stats_books.marked_deleted, remembered_stats_books.removed = nil, nil + local removed, full_syncs = nil, 0 + fake_client.removeFromShelfAsync = function(_, bookId, cb) + removed = bookId + cb({ ok = true }) + return { cancel = function() end } + end + fake_client.shelfSyncAsync = function(_, cb) + full_syncs = full_syncs + 1 + cb({ books = {} }) + return { cancel = function() end } + end + local enqueued = {} + package.loaded["workers.tasks"] = { enqueue = function(spec) enqueued[#enqueued + 1] = spec.key; return spec end } + local src = WeChat.new() + local ok + src:deleteBookAsync({ source_id = "ext.weread", stable_id = "del1" }, function(success) + ok = success + end) + require("support.stubs").flush() + Assert.is_true(ok) + Assert.eq(remembered_stats_books.marked_deleted.stable_id, "del1") + Assert.eq(enqueued[1], "dirty\0ext.weread") + src:syncBooksAsync({ dirty_only = true }, function() end) + require("support.stubs").flush() + Assert.eq(removed, "del1") + Assert.eq(remembered_stats_books.removed.stable_id, "del1") + Assert.eq(full_syncs, 0, "推脏不拉全量书架") + package.loaded["workers.tasks"] = nil + fake_client.removeFromShelfAsync, fake_client.shelfSyncAsync = nil, nil +end + +-- 段评:开关读源配置;按目录解析本章 chapter_uid,章节 HTML 读本地文件定位。 +do + toc_payload["b1"] = [[ [{"idx":1,"source_idx":2,"uid":"40"}] ]] + require("book.toc_db").removeIdentity("ext.weread", "b1") + local Settings = require("utils.settings") + local src = WeChat.new() + Assert.is_false(src:paragraphReviewsEnabled()) + local getSource = Settings.getSource + Settings.getSource = function() return { show_paragraph_reviews = true } end + Assert.is_true(src:paragraphReviewsEnabled()) + Settings.getSource = getSource + + local calls = {} + fake_client.underlinesAsync = function(_self, book_id, uid, cb) + calls[#calls + 1] = { book_id, uid } + cb({ underlines = { { range = "1-5" } } }) + return { cancel = function() end } + end + fake_client.readReviewsAsync = function(_self, book_id, uid, reviews, cb) + calls[#calls + 1] = { book_id, uid, reviews } + cb({ reviews = { { + range = "1-5", totalCount = 3, maxIdx = 1, hasMore = 0, + pageReviews = { { review = { abstract = "甲乙丙丁。", author = { name = "a" }, content = "c" } } }, + } } }) + return { cancel = function() end } + end + local identity = setmetatable({ chapter_idx = 1 }, { __index = REF }) + local hotspots + src:paragraphHotspotsAsync(identity, function(value) hotspots = value end) + require("support.stubs").flush() + Assert.eq(calls[1][1], "b1") + Assert.eq(calls[1][2], "40") + Assert.len(hotspots, 1) + local spots = src:locateHotspots(hotspots, "

甲乙丙丁。

") + Assert.len(spots, 1) + Assert.eq(spots[1].pos0, "/html/body/p/text().0") + + local page + src:paragraphReviewPageAsync(identity, "1-5", 0, function(value) page = value end) + require("support.stubs").flush() + Assert.eq(calls[3][3][1].count, 30) + Assert.eq(page.total, 3) + Assert.is_false(page.more) + + -- 本章不在目录且目录拉不到:报错,不发段评请求。 + fake_client.chapterInfosAsync = function(_self, _book_id, cb) + cb(nil, "目录拉取失败") + return { cancel = function() end } + end + local err + src:paragraphReviewPageAsync(setmetatable({ chapter_idx = 9 }, { __index = REF }), "1-5", 0, + function(_page, e) err = e end) + require("support.stubs").flush() + Assert.not_nil(err) + Assert.len(calls, 3) + toc_payload["b1"] = nil + require("book.toc_db").removeIdentity("ext.weread", "b1") + require("moonsource_weread.toc").clear() + + -- 书名搜索:只留带 bookId 的书目。 + local keyword + fake_client.searchAsync = function(_self, word, cb) + keyword = word + cb({ books = { + { type = 0, bookInfo = { bookId = 834464, title = "活着", author = "余华", publisher = "作家" } }, + { type = 3, mpInfo = { title = "公众号" } }, + } }) + return { cancel = function() end } + end + local found + src:searchBooksAsync("活着", function(books) found = books end) + Assert.eq(keyword, "活着") + Assert.len(found, 1) + Assert.eq(found[1].book_id, "834464") + Assert.eq(found[1].author, "余华") +end + +-- pushNotesAsync 中途取消:在途请求被取消,迟到回包不回调、不再发后续请求。 +do + toc_payload["bcancel"] = '[{"idx":1,"source_idx":1,"uid":"7"}]' + local pending, cancelled, requests = nil, 0, 0 + fake_client.bookmarkListAsync = function(_, _, cb) + requests = requests + 1 + pending = cb + return { cancel = function() cancelled = cancelled + 1 end } + end + fake_client.myReviewsAsync = function() + requests = requests + 1 + error("取消后不应继续请求") + end + local src = WeChat.new() + local called = false + local job = src:pushNotesAsync( + { source_id = "ext.weread", stable_id = "bcancel", chapter_idx = 1 }, + { { drawer = "lighten", text = "甲" } }, + function() called = true end + ) + require("support.stubs").flush() + Assert.eq(requests, 1, "先发预检") + job.cancel() + Assert.eq(cancelled, 1, "取消在途的预检请求") + pending({ updated = {} }) + require("support.stubs").flush() + Assert.is_false(called, "取消后不回调") + Assert.eq(requests, 1) + + -- 无事可做直接成功,不发请求。 + local ok + Assert.is_nil(src:pushNotesAsync({ source_id = "ext.weread", stable_id = "bcancel", chapter_idx = 1 }, + { { drawer = "lighten", text = "甲", wr_bookmark_id = "b", wr_range = "0-1" } }, + function(v) ok = v end)) + Assert.is_true(ok) + Assert.eq(requests, 1) + toc_payload["bcancel"] = nil + require("book.toc_db").removeIdentity("ext.weread", "bcancel") + fake_client.bookmarkListAsync = nil + fake_client.myReviewsAsync = nil +end + +-- 增量拉书架:有游标时只拉 id 增量,变更补详情、其余用本地行拼快照,不走全量 +do + remembered_stats_books.local_library = { "a", "b", "gone" } + remembered_stats_books.pending_adds = {} + remembered_stats_books.local_rows = { + a = { source_id = "ext.weread", stable_id = "a", title = "甲", deleted = 0 }, + b = { source_id = "ext.weread", stable_id = "b", title = "乙旧", category = "我的分组", deleted = 0 }, + gone = { source_id = "ext.weread", stable_id = "gone", title = "删", deleted = 0 }, + } + local ids_req, books_req, full_called = nil, nil, false + fake_client.shelfSyncIdsAsync = function(_, synckey, count, cb) + ids_req = { synckey = synckey, count = count } + cb({ synckey = 101, bookCount = 3, removed = { "gone" }, + bookIds = { { bookId = "a", type = 0 }, { bookId = "b", type = 0 }, { bookId = "c", type = 0 } }, + archive = {}, albumRemoved = {}, removedArchive = {} }) + return { cancel = function() end } + end + fake_client.shelfSyncBooksAsync = function(_, ids, cb) + books_req = ids + cb({ books = { + { bookId = "a", title = "甲", category = "都市" }, + { bookId = "b", title = "乙新", category = "玄幻" }, + { bookId = "c", title = "丙", category = "玄幻" }, + }, bookProgress = { { bookId = "c", progress = 50 } }, albums = {}, emptyInfoIds = {} }) + return { cancel = function() end } + end + fake_client.shelfSyncAsync = function(_, cb) + full_called = true + cb({ books = {} }) + return { cancel = function() end } + end + local src = WeChat.new() + src.cfg.wr_vid = "v1" + src.cfg.category_as_group = true + src.cfg.shelf_cursor = { vid = "v1", synckey = 100 } + local Settings = require("utils.settings") + local getSource = Settings.getSource + Settings.getSource = function() return { category_as_group = true } end + local result + src:syncBooksAsync(nil, function(r) result = r end) + require("support.stubs").flush() + Assert.not_nil(result) + Assert.is_false(full_called, "后台刷新应优先走增量,对不齐再回退全量") + Assert.eq(ids_req.synckey, 100) + Assert.eq(ids_req.count, 3) + Assert.len(books_req, 3) + local snap = {} + for _idx, b in ipairs(remembered_stats_books.last_snapshot) do snap[b.stable_id] = b end + Assert.eq(snap.a.title, "甲") + Assert.is_nil(snap.a.category, "没进组的旧书不被详情题材盖掉") + Assert.eq(snap.b.title, "乙新") + Assert.eq(snap.b.category, "我的分组", "分组无变更时保留本地分组名") + Assert.is_nil(snap.gone, "removed 的书不进快照") + Assert.not_nil(snap.c, "新增的书经 syncbook 补进快照") + Assert.is_nil(snap.c.category, "新书没进组,不写详情题材") + Assert.eq(src.cfg.shelf_cursor.synckey, 101, "reconcile 成功后推进游标") + Settings.getSource = getSource + fake_client.shelfSyncIdsAsync, fake_client.shelfSyncBooksAsync = nil, nil + remembered_stats_books.local_library, remembered_stats_books.local_rows = nil, nil + remembered_stats_books.last_snapshot = nil +end + +-- 手动刷新使用全量快照,即使已有增量游标也不走 id 增量接口。 +do + local full_called, ids_called = false, false + fake_client.shelfSyncIdsAsync = function() + ids_called = true + return { cancel = function() end } + end + fake_client.shelfSyncAsync = function(_, cb, _spill, open_import) + full_called = true + Assert.is_true(open_import, "手动全量可打开大书架导入页") + cb({ synckey = 8, books = { { bookId = "a", title = "甲" } } }) + return { cancel = function() end } + end + local src = WeChat.new() + src.cfg.wr_vid = "v1" + src.cfg.category_as_group = true + src.cfg.shelf_cursor = { vid = "v1", synckey = 7 } + local result + src:syncBooksAsync({ force = true }, function(r) result = r end) + require("support.stubs").flush() + Assert.not_nil(result) + Assert.is_true(full_called) + Assert.is_false(ids_called) + fake_client.shelfSyncIdsAsync, fake_client.shelfSyncAsync = nil, nil +end + +-- 未完成的全量导入优先于增量:后台同步不弹页,手动强制刷新才能重新打开。 +do + local saved_import = package.loaded["moonsource_weread.shelf_import"] + package.loaded["moonsource_weread.shelf_import"] = { + size = function() return 100 end, + TOO_LARGE = "pending import", + } + local src = WeChat.new() + src.cfg.wr_vid = "v1" + src.cfg.category_as_group = true + src.cfg.shelf_cursor = { vid = "v1", synckey = 100 } + + local ids_called, reopen_pending = false, nil + fake_client.shelfSyncIdsAsync = function() + ids_called = true + return { cancel = function() end } + end + fake_client.shelfSyncAsync = function(_, cb, spill, reopen) + Assert.is_true(spill) + reopen_pending = reopen + cb(nil, "pending import") + return { cancel = function() end } + end + + local result, err + src:syncBooksAsync(nil, function(r, e) result, err = r, e end) + require("support.stubs").flush() + Assert.is_false(ids_called, "待导入快照期间不继续增量") + Assert.is_true(result.skipped, "后台发现待导入快照时安静跳过") + Assert.eq(result.reason, "pending_import") + Assert.is_nil(err) + Assert.is_nil(reopen_pending, "后台重试不重新打开导入页") + + src:syncBooksAsync({ force = true }, function(r, e) result, err = r, e end) + require("support.stubs").flush() + Assert.is_false(ids_called) + Assert.is_true(reopen_pending, "手动强制刷新重新打开已有导入页") + Assert.eq(err, "pending import") + + fake_client.shelfSyncIdsAsync, fake_client.shelfSyncAsync = nil, nil + package.loaded["moonsource_weread.shelf_import"] = saved_import +end + +-- 增量对不齐(数量对不上)回退全量,全量成功后游标取全量回包的 synckey +do + remembered_stats_books.local_library = { "a" } + remembered_stats_books.pending_adds = {} + remembered_stats_books.local_rows = { + a = { source_id = "ext.weread", stable_id = "a", title = "甲", deleted = 0 }, + } + local full_called = false + fake_client.shelfSyncIdsAsync = function(_, _synckey, _count, cb) + cb({ synckey = 102, bookCount = 99, removed = {}, bookIds = {}, + archive = {}, albumRemoved = {}, removedArchive = {} }) + return { cancel = function() end } + end + fake_client.shelfSyncAsync = function(_, cb) + full_called = true + cb({ synckey = 555, books = { { bookId = "a", title = "甲" } } }) + return { cancel = function() end } + end + local src = WeChat.new() + src.cfg.wr_vid = "v1" + src.cfg.category_as_group = true + src.cfg.shelf_cursor = { vid = "v1", synckey = 100 } + local result + src:syncBooksAsync(nil, function(r) result = r end) + require("support.stubs").flush() + Assert.not_nil(result) + Assert.is_true(full_called, "数量对不齐应回退全量") + Assert.eq(src.cfg.shelf_cursor.synckey, 555) + fake_client.shelfSyncIdsAsync = nil + remembered_stats_books.local_library, remembered_stats_books.local_rows = nil, nil + remembered_stats_books.last_snapshot = nil +end + +-- 键没写过:缺省改开,清掉旧游标走全量,并落成 true。 +do + local full_called, ids_called = false, false + fake_client.shelfSyncIdsAsync = function() + ids_called = true + return { cancel = function() end } + end + fake_client.shelfSyncAsync = function(_, cb) + full_called = true + cb({ synckey = 7, books = { { bookId = "a", title = "甲" } } }) + return { cancel = function() end } + end + local src = WeChat.new() + src.cfg.wr_vid = "v1" + src.cfg.category_as_group = nil + src.cfg.shelf_cursor = { vid = "v1", synckey = 100 } + local result + src:syncBooksAsync(nil, function(r) result = r end) + require("support.stubs").flush() + Assert.not_nil(result) + Assert.is_true(full_called, "缺省开应走全量") + Assert.is_false(ids_called, "游标已清,不拉增量") + Assert.is_true(src.cfg.category_as_group) + Assert.eq(src.cfg.shelf_cursor.synckey, 7) + fake_client.shelfSyncIdsAsync = nil +end + +-- 书城浏览:目录树与榜单书每次都调 client,源不留实例缓存(新鲜度归 client 的 http 缓存) +do + local cat_calls, book_calls = 0, 0 + fake_client.storeCategoriesAsync = function(_, cb) + cat_calls = cat_calls + 1 + cb({ data = { { categories = { + { CategoryId = "rising", title = "飙升榜", ranklist = 1, sublist = {} }, + } } } }) + return { cancel = function() end } + end + fake_client.storeBooksAsync = function(_, _node, _offset, _is_rank, cb) + book_calls = book_calls + 1 + cb({ books = {}, hasMore = 0 }) + return { cancel = function() end } + end + local src = WeChat.new() + local res + src:browseAsync({}, function(r) res = r end) + Assert.eq(cat_calls, 1) + Assert.eq(res.groups[1].chips[1].id, "rising") + src:browseAsync({}, function(r) res = r end) + Assert.eq(cat_calls, 2, "源不缓存目录树,每次浏览都调 client") + Assert.eq(book_calls, 2, "榜单书每次调 client") + + -- 目录同步回完、榜单请求在途:取消必须打到在途请求,外层赋值不能覆盖它。 + local cancelled = 0 + fake_client.storeBooksAsync = function() + return { cancel = function() cancelled = cancelled + 1 end } + end + local browse_handle = src:browseAsync({}, function() error("请求尚未完成") end) + browse_handle.cancel() + Assert.eq(cancelled, 1) + fake_client.storeCategoriesAsync, fake_client.storeBooksAsync = nil, nil +end + +-- 翻页先保存本地进度,解决开书冲突后最多 5 秒上推一次;在途更新会再推最新修订。 +do + local Session = require("reader.session") + local old_current = Session.current + local old_progress = package.loaded["reader.session.progress"] + local old_uimanager = package.loaded["ui/uimanager"] + local Network = require("ui/network/manager") + local old_is_connected = Network.isConnected + local connected = true + local active = { + identity = { source_id = "ext.weread", stable_id = "page-sync" }, + } + local saves, scheduled, ticks, sync_callbacks = 0, {}, {}, {} + local cancelled = 0 + local manager = { + scheduleIn = function(_, delay, fn) + scheduled[#scheduled + 1] = { delay = delay, fn = fn } + end, + unschedule = function(_, fn) + for _idx, item in ipairs(scheduled) do + if item.fn == fn then item.cancelled = true end + end + end, + nextTick = function(_, fn) ticks[#ticks + 1] = fn end, + } + Session.current = function() return active end + local decision = require("book.progress").decision(active.identity) + decision.phase = "pulling" + Network.isConnected = function() return connected end + package.loaded["reader.session.progress"] = { + save = function(_snapshot, cb) + saves = saves + 1 + cb(true) + end, + } + package.loaded["ui/uimanager"] = manager + existing_progress = { sync_status = 0 } + + local src = WeChat.new() + local sync_calls = 0 + src.syncProgressAsync = function(_, opts, cb) + sync_calls = sync_calls + 1 + Assert.eq(opts.identity.stable_id, "page-sync") + Assert.is_true(opts.dirty_only) + sync_callbacks[#sync_callbacks + 1] = cb + return { cancel = function() cancelled = cancelled + 1 end } + end + local event = { identity = active.identity, position = { fraction = 0.2 } } + src:onEvent("page_changed", event) + Assert.eq(saves, 1) + Assert.eq(#scheduled, 0, "开书进度尚未决议时不能推送") + + decision.phase = "ready" + src:onEvent("page_changed", event) + src:onEvent("page_changed", event) + Assert.eq(saves, 3) + Assert.eq(#scheduled, 1, "快速翻页合并为一个定时请求") + Assert.eq(scheduled[1].delay, 5) + + scheduled[1].fn() + Assert.eq(sync_calls, 1) + src:onEvent("page_changed", event) + sync_callbacks[1]({ pushed = 1 }) + ticks[1]() + Assert.eq(#scheduled, 2, "在途请求期间位置变化后,旧修订确认后继续推最新位置") + + scheduled[2].fn() + Assert.eq(sync_calls, 2) + src:onEvent("reading_stopped", { identity = active.identity }) + Assert.eq(cancelled, 0, "不能取消可能已被服务端接收的阅读上报") + sync_callbacks[2]({ pushed = 1 }) + ticks[2]() + Assert.eq(#scheduled, 3, "关书前写入的新修订在旧请求完成后继续上推") + + src:onEvent("reading_stopped", { identity = active.identity }) + Assert.is_true(scheduled[3].cancelled, "关书或休眠取消未触发的定时请求") + + connected = false + src:onEvent("page_changed", event) + Assert.eq(saves, 5) + Assert.eq(#scheduled, 3, "离线仍保存进度,但不启动网络同步") + + Session.current = old_current + Network.isConnected = old_is_connected + package.loaded["reader.session.progress"] = old_progress + package.loaded["ui/uimanager"] = old_uimanager + existing_progress = nil + require("book.progress").closeDecision(active.identity) +end + +-- 阅读会话启动 Web 在读心跳,零时长且停读后不再续发。 +do + local Session = require("reader.session") + local Network = require("ui/network/manager") + local Toc = require("moonsource_weread.toc") + local old_current, old_connected = Session.current, Network.isConnected + local old_manager = package.loaded["ui/uimanager"] + local old_context = package.loaded["moonsource_weread.context"] + local old_progress_db = package.loaded["book.progress_db"] + local old_uid, old_source_index = Toc.uid, Toc.sourceIndex + local old_report = fake_client.reportReadAsync + local active = { + identity = { source_id = "ext.weread", stable_id = "presence" }, + } + local scheduled, sent = {}, {} + Session.current = function() return active end + Network.isConnected = function() return true end + package.loaded["ui/uimanager"] = { + scheduleIn = function(_, delay, fn) + scheduled[#scheduled + 1] = { delay = delay, fn = fn } + end, + unschedule = function(_, fn) + for _idx, timer in ipairs(scheduled) do + if timer.fn == fn then timer.cancelled = true end + end + end, + } + local web_session = { psvts = "ps", pclts = "pc", token = "tk" } + package.loaded["moonsource_weread.context"] = { + sessionAsync = function(_, book_id, _force, cb) + Assert.eq(book_id, "presence") + cb(web_session) + end, + } + package.loaded["book.progress_db"] = { + get = function() return { extra = { chapter_idx = 1, chapter_offset = 345 } } end, + } + Toc.uid = function() return "chapter-uid" end + Toc.sourceIndex = function() return 11 end + fake_client.reportReadAsync = function(_, body, _referer, cb) + sent[#sent + 1] = body + cb({ succ = 1 }) + end + + local src = WeChat.new() + src:onEvent("reading_started", { + identity = active.identity, + position = { + chapter_idx = 1, chapter_title = "测试章节", chapter_fraction = 0.6, fraction = 0.42, + }, + }) + Assert.eq(#sent, 2, "首次心跳先 enter,再发送在读状态") + Assert.eq(sent[1].ci, 11) + Assert.eq(sent[1].co, 345, "心跳重用最近确认的精确 App 坐标") + Assert.eq(sent[1].pr, 42) + Assert.eq(sent[2].rt, 0, "Web 心跳不重复计时") + Assert.eq(#scheduled, 1) + Assert.eq(scheduled[1].delay, 30) + + scheduled[1].fn() + Assert.eq(#sent, 3) + Assert.eq(sent[3].rt, 0) + src:onEvent("reading_stopped", { identity = active.identity }) + Assert.is_true(scheduled[2].cancelled, "关书后停止心跳") + + Session.current, Network.isConnected = old_current, old_connected + package.loaded["ui/uimanager"] = old_manager + package.loaded["moonsource_weread.context"] = old_context + package.loaded["book.progress_db"] = old_progress_db + Toc.uid, Toc.sourceIndex = old_uid, old_source_index + fake_client.reportReadAsync = old_report +end + +-- 还原打桩,避免影响本文件之后的其它用例 +for name, factory in pairs(saved_preload) do + package.preload[name] = factory + package.loaded[name] = nil +end +package.loaded["moonsource_weread.source"] = nil