✨ 初始提交:月读第三方书源插件集合
每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <[email protected]>
This commit is contained in:
commit
ed44254f1c
54 files changed
+15615
No files matched your search
@@ -0,0 +1,18 @@
|
||||
# 微信读书
|
||||
|
||||
| 能力 | 是否支持 | 备注 |
|
||||
| --- | --- | --- |
|
||||
| 微信扫码登录与续期 | 支持 | 使用官方扫码及登录令牌流程 |
|
||||
| 书架拉取 | 支持 | 全量/增量同步、分组、变更详情补齐;大快照支持浏览器分批导入 |
|
||||
| 书架新增与移出 | 支持 | 本地先生效,联网后推送;真实账号端到端回读未完成本次验证 |
|
||||
| 详情与目录 | 支持 | App 接口读取书籍和章节元数据 |
|
||||
| 正文下载与阅读 | 支持 | EPUB/TXT 包本机解包,受账号阅读权限限制 |
|
||||
| 搜索与分类书城 | 支持 | App 搜索、公开 Web 分类和分类书单;不是完整 App 书城复刻 |
|
||||
| 阅读进度同步 | 支持 | 开书比较云端位置;本地先落盘,阅读中合并推送,离线保留待同步数据 |
|
||||
| 阅读时长同步 | 支持 | 上传本地采集时长及补报数据 |
|
||||
| 维持官网「在读」状态 | 已实现,未实测 | 零时长 Web 心跳,不重复增加阅读时长 |
|
||||
| 划线与想法同步 | 支持 | 走属主书籍的注解接口 |
|
||||
| 整书书评与独立章评 | 不支持 | 未接入可验证接口,不能把其他书籍的想法当作属主书评 |
|
||||
| 段评与回复 | 支持 | 按章节及文本范围定位,使用公共评论标记和列表 |
|
||||
| 离线阅读 | 支持 | 已下载内容和本地记录可用;联网后再同步 |
|
||||
| 账号切换 | 部分支持 | 游标按账号作废;旧本地书架不自动清理,不是完整账号分区 |
|
||||
@@ -0,0 +1,5 @@
|
||||
local _ = require("gettext")
|
||||
return {
|
||||
fullname = _("月读书源:微信读书"),
|
||||
description = _("给月读增加「微信读书」书源。需要同时安装月读,与平台官方无关。"),
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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"),
|
||||
}
|
||||
@@ -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 = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("笔记同步"), _("统计同步"), _("他人段评") },
|
||||
}
|
||||
@@ -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
|
||||
@@ -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 = "<style type=\"text/css\">"
|
||||
.. ".content,.content1{text-indent:2em;text-align:justify}"
|
||||
.. ".bold,.firstTitle,.secondTitle,.thirdTitle,.contentCR,.contentCR1,.contentCR2{text-indent:0}"
|
||||
.. "</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("(<link%s[^>]-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 = "<style>h1 + h1, .moon-title h1 { page-break-before: avoid; }"
|
||||
.. " body.bgimg-1 { background-image: none; }"
|
||||
.. " .moon-title { background-image: url(images/bq.jpg); background-size: cover;"
|
||||
.. " background-position: center bottom; height: 90vh; padding-top: 30vh;"
|
||||
.. " page-break-before: always; page-break-after: always; }</style>"
|
||||
|
||||
--- body.bgimg-1 的章:丢掉开头垫底的透明出血图,把紧跟着的连续 h1 包进整页容器。
|
||||
---@param html string
|
||||
---@return string
|
||||
local function wrapTitlePage(html)
|
||||
local head, rest = html:match('^(.-<body class="bgimg%-1">%s*)(.*)$')
|
||||
if not head then return html end
|
||||
rest = rest:gsub('^<p class="bleed%-pic">.-</p>%s*', "", 1)
|
||||
local pos = 1
|
||||
while true do
|
||||
local _s, e = rest:find("^<h1[^>]*>.-</h1>%s*", pos)
|
||||
if not e then break end
|
||||
pos = e + 1
|
||||
end
|
||||
if pos == 1 then return head .. rest end
|
||||
return head .. '<div class="moon-title">' .. rest:sub(1, pos - 1) .. "</div>" .. rest:sub(pos)
|
||||
end
|
||||
|
||||
--- 相对 css link 解不到文件时 CRE 不会应用 .content 缩进;去掉坏相对 link,换上兜底样式。
|
||||
---@param html string
|
||||
---@return string
|
||||
local function withFallbackStyle(html)
|
||||
html = html:gsub("(<link%s[^>]-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("</head>", 1, true) then
|
||||
return (html:gsub("</head>", FALLBACK_STYLE .. "</head>", 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("</head>", function() return TITLE_CSS .. "</head>" 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<string, string> 原始 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
|
||||
@@ -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
|
||||
@@ -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<string, string>): 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<string, { text: string, format: '"html"'|'"txt"', style: string|nil }>
|
||||
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(".*()</body>")
|
||||
if not last then return html .. block end
|
||||
return html:sub(1, last - 1) .. block .. html:sub(last)
|
||||
end
|
||||
|
||||
--- 原书脚注是 ``<img class="qqreader-footnote" alt="注文">``,注文只在 alt 里,点了没东西可弹。
|
||||
--- 图标原样包进 noteref 链接,注文放进 body 末尾的 footnote aside,交给 KOReader(页底或弹窗由设置决定)。
|
||||
--- 不加 ``<p>``、不动正文文字:段落序号与字偏移不变,划线 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("<img%s[^>]*>", 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('<a href="#wr-fn%d" id="wr-fnref%d" epub:type="noteref">%s</a>', 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(
|
||||
'<aside id="wr-fn%d" epub:type="footnote">[%d] %s <a href="#wr-fnref%d">↩</a></aside>',
|
||||
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 → 注文」:``<p class="noteContent"><a id="zhu116">[116]</a>注文</p>``。
|
||||
--- 注文保留原样转义(不解实体),直接当元素内容合法。
|
||||
---@param html string
|
||||
---@return table<string, string>
|
||||
local function noteTexts(html)
|
||||
local map = {}
|
||||
for para in html:gmatch("<p[%s>].-</p>") do
|
||||
local id = para:match('<a[^>]-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<string, table<string, string>>
|
||||
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<string, string>
|
||||
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('<a%s[^>]-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('<a(%s[^>]-)href="([^"#:]+)#([^"]+)"([^>]*)>(.-)</a>', function(pre, file, frag, post, inner)
|
||||
local text = (note_files[bookId .. "\0" .. Text.basename(file)] or {})[frag]
|
||||
inner = inner:gsub("<img%s[^>]*>", iconSized)
|
||||
if not text then return inner end
|
||||
notes[#notes + 1] = { text = text, label = Text.trim((inner:gsub("<[^>]+>", ""))) }
|
||||
return string.format('<a%sid="wr-ntref%d" href="#wr-nt%d" epub:type="noteref"%s>%s</a>', pre, #notes, #notes, post, inner)
|
||||
end)
|
||||
local asides = {}
|
||||
for i, note in ipairs(notes) do
|
||||
asides[i] = string.format(
|
||||
'<aside id="wr-nt%d" epub:type="footnote">%s %s <a href="#wr-ntref%d">↩</a></aside>',
|
||||
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 = "<h1>" .. Text.xmlEscape(title) .. "</h1>" .. 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
|
||||
@@ -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
|
||||
@@ -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<string, WechatReaderState>
|
||||
local readers = {}
|
||||
---@type table<string, WechatReportSession>
|
||||
local sessions = {}
|
||||
---@type table<string, number>
|
||||
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
|
||||
@@ -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
|
||||
@@ -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 {}
|
||||
@@ -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",
|
||||
}
|
||||
@@ -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",
|
||||
}
|
||||
@@ -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",
|
||||
["已丢弃"] = "已丟棄",
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
return {
|
||||
["完结"] = "完結",
|
||||
["连载"] = "連載",
|
||||
["已完结"] = "已完結",
|
||||
["上报响应异常"] = "上報回應異常",
|
||||
["书籍详情为空"] = "書籍詳情為空",
|
||||
["二维码已失效,请重新登录"] = "二維碼已失效,請重新登入",
|
||||
["点这个提示上的「重新登录」。二维码出来以后,打开手机微信,点右上角「+」,再点「扫一扫」,对准屏幕上的二维码,在手机上点确认。"] = "點這個提示上的「重新登入」。二維碼出來以後,打開手機微信,點右上角「+」,再點「掃一掃」,對準螢幕上的二維碼,在手機上點確認。",
|
||||
["想法列表暂不可用,稍后重试"] = "想法列表暫不可用,稍後重試",
|
||||
["划线上传后未在远端确认"] = "劃線上傳後未在遠端確認",
|
||||
["划线上传失败"] = "劃線上傳失敗",
|
||||
["合并本地阅读时长"] = "合併本機閱讀時長",
|
||||
["关闭时以云端为准;打开后每天取云端与本地中较大的,补上离线阅读。只影响月读里的统计"] = "關閉時以雲端為準;開啟後每天取雲端與本機中較大的,補上離線閱讀。只影響月讀裡的統計",
|
||||
["确定退出微信读书账号?"] = "確定登出微信讀書帳號?",
|
||||
["已登录:%1"] = "已登入:%1",
|
||||
["已续期"] = "已續期",
|
||||
["微信扫码登录"] = "微信掃碼登入",
|
||||
["微信读书账号"] = "微信讀書帳號",
|
||||
["本书已下架"] = "本書已下架",
|
||||
["余额不足"] = "餘額不足",
|
||||
["章节已经购买过,请勿重复购买"] = "章節已經購買過,請勿重複購買",
|
||||
["本书已下架,部分内容不再支持购买"] = "本書已下架,部分內容不再支援購買",
|
||||
["章节价格已更新,请重新购买"] = "章節價格已更新,請重新購買",
|
||||
["试读结束"] = "試讀結束",
|
||||
["想法上传失败"] = "想法上傳失敗",
|
||||
["想法上传成功但缺少 reviewId"] = "想法上傳成功但缺少 reviewId",
|
||||
["按章书籍请打开章节后同步划线"] = "分章書籍請開啟章節後再同步劃線",
|
||||
["无法定位划线范围"] = "無法定位劃線範圍",
|
||||
["无法开始登录"] = "無法開始登入",
|
||||
["无法确认划线上传结果"] = "無法確認劃線上傳結果",
|
||||
["无法获取章节坐标"] = "無法取得章節座標",
|
||||
["无法预检远端划线"] = "無法預檢遠端劃線",
|
||||
["未登录 · 点此扫码"] = "未登入 · 點此掃碼",
|
||||
["正在获取二维码…"] = "正在取得二維碼…",
|
||||
["章节目录保存失败"] = "章節目錄儲存失敗",
|
||||
["章节缺少 uid"] = "章節缺少 uid",
|
||||
["第 %d 章"] = "第 %d 章",
|
||||
["续期会话"] = "續期工作階段",
|
||||
["续期失败"] = "續期失敗",
|
||||
["缺少书籍版本"] = "缺少書籍版本",
|
||||
["缺少本地章节正文,无法定位划线"] = "缺少本機章節正文,無法定位劃線",
|
||||
["缺少章节信息"] = "缺少章節資訊",
|
||||
["返回非 JSON"] = "回傳非 JSON",
|
||||
["无法定位阅读进度"] = "無法定位閱讀進度",
|
||||
["远端划线未确认,不能上传想法"] = "遠端劃線未確認,不能上傳想法",
|
||||
["已在微信中拒绝登录"] = "已在微信中拒絕登入",
|
||||
["获取二维码票据失败"] = "取得 QR 碼票據失敗",
|
||||
["请先扫码登录微信读书墨水屏"] = "請先掃碼登入微信讀書墨水屏",
|
||||
["鉴权失败,请求结果未知"] = "驗證失敗,請求結果未知",
|
||||
["打开手机上的微信读书 App,按它的提示完成人机验证。验证完回到月读,把这一章再打开一次。"] = "打開手機上的微信讀書 App,按它的提示完成人機驗證。驗證完回到月讀,把這一章再打開一次。",
|
||||
["阅读时给有他人段评的句子画线,点按查看;需联网"] = "閱讀時為有他人段評的句子畫線,點按查看;需連網",
|
||||
["无法获取段评"] = "無法取得段評",
|
||||
["公众号授权已失效,请在微信读书 App 中打开任意公众号重新授权后再试"] = "公眾號授權已失效,請在微信讀書 App 中打開任意公眾號重新授權後再試",
|
||||
["微信读书拒绝了请求,请稍后再试"] = "微信讀書拒絕了請求,請稍後再試",
|
||||
["微信读书要求验证,请稍后再试"] = "微信讀書要求驗證,請稍後再試",
|
||||
["这一章暂时无法加载:%s\n请稍后重试。"] = "這一章暫時無法載入:%s\n請稍後重試。",
|
||||
["没有可浏览的榜单"] = "沒有可瀏覽的榜單",
|
||||
["书架同步"] = "書架同步",
|
||||
["微信读书书架与在线阅读"] = "微信讀書書架與線上閱讀",
|
||||
["搜索与发现"] = "搜尋與發現",
|
||||
["笔记同步"] = "筆記同步",
|
||||
["统计同步"] = "統計同步",
|
||||
["进度同步"] = "進度同步",
|
||||
["书架数据太大,设备无法直接处理。已开启远程管理,请扫码在浏览器点「开始导入」完成同步。"] = "書架資料太大,裝置無法直接處理。已開啟遠端管理,請掃碼在瀏覽器點「開始匯入」完成同步。",
|
||||
["微信读书错误 "] = "微信讀書錯誤 ",
|
||||
["微信读书公众号"] = "微信讀書公眾號",
|
||||
["正在读取微信读书书架…"] = "正在讀取微信讀書書架…",
|
||||
["请先登录微信读书"] = "請先登入微信讀書",
|
||||
["微信读书书架里没有公众号"] = "微信讀書書架裡沒有公眾號",
|
||||
["微信读书"] = "微信讀書",
|
||||
["请先扫码登录微信读书"] = "請先掃碼登入微信讀書",
|
||||
}
|
||||
@@ -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
|
||||
@@ -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<string, 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<string, string>
|
||||
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<string, boolean>
|
||||
---@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
|
||||
@@ -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("<img%s[^>]*>", 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 '<img src="' .. Text.xmlEscape(src) .. '"/>'
|
||||
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] = '<p><img src="' .. url .. '"/></p>'
|
||||
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(".*()<div")
|
||||
local body
|
||||
if start then
|
||||
local from = math.max(1, at - 512) + start - 1
|
||||
local tail = html:sub(from)
|
||||
body = tail:match('^<div[^>]*>(.-)</div>%s*<script') or tail:match('^<div[^>]*>(.*)')
|
||||
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("<script.-</script>", ""):gsub("<style.-</style>", "")
|
||||
:gsub("<svg.-</svg>", ""):gsub("<svg[^>]*/>", "")
|
||||
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('<span[^>]-class="emoji emoji%x+"[^>]*>%s*</span>', "")
|
||||
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("<title>%s*验证%s*</title>") ~= 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
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.4 KiB |
@@ -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<string, WechatAnnotation>
|
||||
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<string, 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<string, 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<string, 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<string, boolean>
|
||||
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<table, boolean>
|
||||
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<string, boolean>
|
||||
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<table, boolean> 本轮已在远端确认的条目
|
||||
---@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<table, boolean> 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
|
||||
@@ -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<table, boolean> 已在远端确认的条目
|
||||
---@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<table, boolean>
|
||||
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
|
||||
@@ -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<string, string>|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<string, string> 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<string, string>
|
||||
---@param book_id string
|
||||
---@param uids (string|number)[]
|
||||
---@param book_type '"epub"'|'"txt"'
|
||||
---@return table<string, { text: string|nil, err: string|nil, format: string }>
|
||||
---@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<string, string> 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("<body[^>]*>(.*)</body>")
|
||||
if not inner then return nil, "package: bad part " .. tostring(chapter.files[i]) end
|
||||
local last = html:match(".*()</body>")
|
||||
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
|
||||
@@ -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 = "<h1>" .. Text.xmlEscape(chapter.title or "") .. "</h1>" .. 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
|
||||
@@ -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
|
||||
@@ -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<string, { url: string, headers?: table<string, string> }>|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<string, string> }[]|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
|
||||
@@ -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
|
||||
@@ -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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,194 @@
|
||||
--[[--
|
||||
微信读书阅读统计:累计总量、账户日桶与单书明细 wire → reading_stats 领域行。
|
||||
|
||||
账户级日桶 ``__wr:day:<ts>``;权威累计时长 ``__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<string, number> 本地 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
|
||||
@@ -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
|
||||
@@ -0,0 +1,36 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- 微信书架分批导入页(features/wechat_import 经 web.routes 开放;逻辑在 /wechat_import.js,接口 /api/wechat_import/*) -->
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>微信书架导入 - 远程管理</title>
|
||||
<link rel="icon" href="/favicon.ico?v=2" sizes="16x16 32x32 48x48">
|
||||
<meta name="theme-color" content="#263a52">
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
<script>try{var t=localStorage.getItem('moon-theme');if(t==='light'||t==='dark')document.documentElement.setAttribute('data-theme',t);var l=localStorage.getItem('moon-lang');if(l&&!/^zh_CN/.test(l))document.documentElement.classList.add('i18n-wait')}catch(e){}</script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="appbar"><div class="appbar-inner">
|
||||
<a class="appbar-brand" href="/"><img src="/logo.jpg" alt="" width="28" height="28"><span>月读远程管理</span></a>
|
||||
<nav class="appbar-nav" aria-label="页面导航">
|
||||
<a href="/"><span>首页</span></a><a href="/file.html"><span>文件</span></a><a href="/input.html"><span>输入</span></a><a href="/clipboard.html"><span>剪贴板</span></a><a href="/settings.html"><span>配置</span></a><a href="/update.html"><span>更新</span></a>
|
||||
</nav>
|
||||
<button type="button" id="theme-toggle" class="icon-btn" aria-label="切换主题" title="主题:跟随系统"><svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor" aria-hidden="true"><path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm0 18V4a8 8 0 0 1 0 16z"/></svg></button>
|
||||
</div></header>
|
||||
<main class="page single-page">
|
||||
<section class="panel">
|
||||
<div class="panel-head"><h1>微信书架分批导入</h1></div>
|
||||
<p id="info" class="state" role="status" aria-live="polite"></p>
|
||||
<p>
|
||||
<button type="button" id="start" class="btn" disabled>开始导入</button>
|
||||
<button type="button" id="discard" class="btn" disabled>丢弃数据</button>
|
||||
</p>
|
||||
<div class="pg-track" role="progressbar" aria-label="导入进度"><div id="bar" class="pg-fill"></div></div>
|
||||
<pre id="log"></pre>
|
||||
</section>
|
||||
</main>
|
||||
<script src="/js.js"></script>
|
||||
<script src="/wechat_import.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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();
|
||||
})();
|
||||
Reference in new issue
Block a user