From 77c37bc89a4497075dfdf6bd7aa78cc07f80e693 Mon Sep 17 00:00:00 2001 From: Garfield Date: Mon, 16 Nov 2026 12:07:59 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=E5=88=9D=E5=A7=8B=E6=8F=90?= =?UTF-8?q?=E4=BA=A4=EF=BC=9A=E6=9C=88=E8=AF=BB=E7=AC=AC=E4=B8=89=E6=96=B9?= =?UTF-8?q?=E4=B9=A6=E6=BA=90=E6=8F=92=E4=BB=B6=E9=9B=86=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- moonsource-douban.koplugin/README.md | 22 + moonsource-douban.koplugin/_meta.lua | 5 + moonsource-douban.koplugin/main.lua | 9 + moonsource-douban.koplugin/moon_source.lua | 15 + .../moonsource_douban/_meta.lua | 17 + .../moonsource_douban/client.lua | 827 ++++++++++++++++++ .../moonsource_douban/l10n/en.lua | 62 ++ .../moonsource_douban/l10n/zh_TW.lua | 62 ++ .../moonsource_douban/loadmeta.lua | 5 + .../moonsource_douban/mapper.lua | 813 +++++++++++++++++ .../moonsource_douban/phone_login.lua | 131 +++ .../moonsource_douban/qrlogin.lua | 137 +++ .../moonsource_douban/reviews.lua | 62 ++ .../moonsource_douban/setting.lua | 122 +++ .../moonsource_douban/source.lua | 456 ++++++++++ tests/douban/browse_spec.lua | 93 ++ tests/douban/client_spec.lua | 511 +++++++++++ tests/douban/community_spec.lua | 160 ++++ tests/douban/login_spec.lua | 128 +++ tests/douban/phone_login_spec.lua | 176 ++++ tests/douban/progress_spec.lua | 65 ++ tests/douban/qrlogin_spec.lua | 58 ++ tests/douban/reviews_spec.lua | 57 ++ tests/douban/setting_spec.lua | 42 + tests/douban/shelf_spec.lua | 135 +++ tests/douban/stats_spec.lua | 82 ++ tests/douban/toc_cache_spec.lua | 53 ++ 27 files changed, 4305 insertions(+) create mode 100644 moonsource-douban.koplugin/README.md create mode 100644 moonsource-douban.koplugin/_meta.lua create mode 100644 moonsource-douban.koplugin/main.lua create mode 100644 moonsource-douban.koplugin/moon_source.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/_meta.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/client.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/l10n/en.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/l10n/zh_TW.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/loadmeta.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/mapper.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/phone_login.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/qrlogin.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/reviews.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/setting.lua create mode 100644 moonsource-douban.koplugin/moonsource_douban/source.lua create mode 100644 tests/douban/browse_spec.lua create mode 100644 tests/douban/client_spec.lua create mode 100644 tests/douban/community_spec.lua create mode 100644 tests/douban/login_spec.lua create mode 100644 tests/douban/phone_login_spec.lua create mode 100644 tests/douban/progress_spec.lua create mode 100644 tests/douban/qrlogin_spec.lua create mode 100644 tests/douban/reviews_spec.lua create mode 100644 tests/douban/setting_spec.lua create mode 100644 tests/douban/shelf_spec.lua create mode 100644 tests/douban/stats_spec.lua create mode 100644 tests/douban/toc_cache_spec.lua diff --git a/moonsource-douban.koplugin/README.md b/moonsource-douban.koplugin/README.md new file mode 100644 index 0000000..5a4ef66 --- /dev/null +++ b/moonsource-douban.koplugin/README.md @@ -0,0 +1,22 @@ +# 豆瓣阅读 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| App 扫码与短信登录 | 支持 | 豆瓣阅读 App 扫码;短信支持国际区号,历史授权迁移交由官网确认 | +| 浏览器登录与 Cookie 导入 | 支持 | 手动粘贴或浏览器扩展回传 | +| 设备密码登录 | 不支持 | 未接入 | +| 搜索与分类书城 | 支持 | 原创、出版动态分类、子分类及排序、资费和状态筛选 | +| 书架拉取与分组 | 支持 | 官网分组可作为书库分类 | +| 加入远端书架 | 支持 | 本地先生效,上传后回读确认 | +| 移出远端书架 | 已实现,未实测 | 清缓存、留墓碑;远端确认后清记录 | +| 目录与正文 | 支持 | 专栏按章;出版电子书按正文目录切章,免费内容可匿名读取 | +| 已购正文 | 已实现,未实测 | 以官方阅读权限为准,不绕过购买 | +| 章节与全本缓存 | 支持 | 兼容旧缓存,已缓存章节可离线续读和重开 | +| 阅读进度同步 | 部分支持 | 专栏下行不能恢复最近章,上行持久化未确认;出版仅近似章首比例 | +| 阅读时长同步 | 部分支持 | 上传本地会话,拉取累计及近 30 日时长;不把访问记录伪造为阅读会话 | +| 个人笔记同步 | 不支持 | 未接个人划线、书签和笔记双向同步 | +| 整书书评 | 部分支持 | 长短评首批预览;首页匿名,后续页需登录 | +| 章评 | 部分支持 | 仅专栏章节;章末入口、分页和缓存,后续页需登录且未完成真实登录实测 | +| 段评 | 支持 | 保留按段落 ID 定位的他人批注,与章评共存 | +| 评论回复与写操作 | 不支持 | 未接回复分页、发评、点赞或删评 | +| 账号切换 | 部分支持 | 同账号可续期;换号须先退出清理旧数据,未同步记录会丢失 | diff --git a/moonsource-douban.koplugin/_meta.lua b/moonsource-douban.koplugin/_meta.lua new file mode 100644 index 0000000..008deae --- /dev/null +++ b/moonsource-douban.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:豆瓣读书"), + description = _("给月读增加「豆瓣读书」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-douban.koplugin/main.lua b/moonsource-douban.koplugin/main.lua new file mode 100644 index 0000000..b4cccb5 --- /dev/null +++ b/moonsource-douban.koplugin/main.lua @@ -0,0 +1,9 @@ +--[[-- +KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。 +--]] +local WidgetContainer = require("ui/widget/container/widgetcontainer") + +return WidgetContainer:extend{ + name = "moonsource_douban", + is_doc_only = false, +} diff --git a/moonsource-douban.koplugin/moon_source.lua b/moonsource-douban.koplugin/moon_source.lua new file mode 100644 index 0000000..64e845b --- /dev/null +++ b/moonsource-douban.koplugin/moon_source.lua @@ -0,0 +1,15 @@ +--[[-- +月读第三方书源描述:豆瓣读书。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。 +--]] + +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_douban.source").meta() end, + new = function() return require("moonsource_douban.source").new() end, + setting = lazy("moonsource_douban.setting"), +} diff --git a/moonsource-douban.koplugin/moonsource_douban/_meta.lua b/moonsource-douban.koplugin/moonsource_douban/_meta.lua new file mode 100644 index 0000000..93a6d06 --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/_meta.lua @@ -0,0 +1,17 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +豆瓣阅读网页搜索和免费章节不需要登录。书架和已购正文要豆瓣阅读 App 扫码。 + +@module moonsource_douban._meta +--]] + +local _ = require("l10n").get("moonsource_douban") + +return { + id = "ext.douban", + name = _("豆瓣阅读"), + type = "chapter", + description = _("豆瓣阅读书架与在线阅读"), + abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("统计同步"), _("VIP 章节"), _("段评"), _("书评"), _("章节评论") }, +} diff --git a/moonsource-douban.koplugin/moonsource_douban/client.lua b/moonsource-douban.koplugin/moonsource_douban/client.lua new file mode 100644 index 0000000..d585fdb --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/client.lua @@ -0,0 +1,827 @@ +--[[-- +豆瓣阅读网页接口。 + +搜索、专栏目录和免费章节不登录也能读。正文密钥在匿名时是 SHA-256("anonymous")。 +登录是豆瓣阅读 App 扫码:先跟到 accounts.arkread.com 的授权页,再轮询二维码。 +扫码成功后授权页跳回 read.douban.com,会话是 Set-Cookie,解密密钥换成用户编号。 + +@module moonsource_douban.client +--]] + +local JSON = require("json") +local Mapper = require("moonsource_douban.mapper") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_douban") + +local Client = {} + +local SOURCE_ID = "ext.douban" +local READ_HOST = "read.douban.com" +local ACCOUNT_HOST = "accounts.arkread.com" +local READ = "https://" .. READ_HOST +local ACCOUNT = "https://" .. ACCOUNT_HOST +local LOGIN_URL = READ .. "/oidc/login?redir=https%3A%2F%2Fread.douban.com%2F" +local LOGIN_EXPIRED = "豆瓣阅读登录已失效,请点「重新登录」,用豆瓣阅读 App 扫码。" + +local active = { jars = {} } +local anonymous = { jars = {}, public = true } +local login_epoch = 0 +local article_cache = {} +local loaded = false + +local function remember(host, header, session) + if type(host) ~= "string" or type(header) ~= "string" or header == "" then return end + session = session or active + local jar = session.jars[host] or {} + session.jars[host] = jar + local name, value = header:match("^%s*([^=;%s]+)=([^;]*)") + if name then jar[name] = value ~= "" and value or nil end +end + +function Client.reset() + active = { jars = {} } + login_epoch = login_epoch + 1 + article_cache = {} + loaded = false +end + +function Client.load() + active = { jars = {} } + local cookie = require("utils.settings").getSource(SOURCE_ID).cookie + for pair in (cookie or ""):gmatch("[^;]+") do remember(READ_HOST, pair) end + loaded = true +end + +---@param host string +---@return string|nil +function Client.cookieFor(host, session) + local jar = (session or active).jars[host] + if not jar then return nil end + local names = {} + for name in pairs(jar) do names[#names + 1] = name end + table.sort(names) + if #names == 0 then return nil end + local parts = {} + for _idx, name in ipairs(names) do parts[#parts + 1] = name .. "=" .. jar[name] end + return table.concat(parts, "; ") +end + +---@return boolean +function Client.loggedIn() + local cfg = require("utils.settings").getSource(SOURCE_ID) + return cfg.logged_in == true and type(cfg.user_id) == "string" and cfg.user_id ~= "" + and type(cfg.cookie) == "string" and cfg.cookie ~= "" +end + +---@return string|nil +function Client.userId() + local cfg = require("utils.settings").getSource(SOURCE_ID) + if cfg.logged_in == true and type(cfg.user_id) == "string" and cfg.user_id ~= "" then return cfg.user_id end + return nil +end + +---@param user { id: string, name: string } +local function persist(user, session) + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + cfg.cookie = Client.cookieFor(READ_HOST, session) + cfg.user_id = user.id + cfg.name = user.name + cfg.logged_in = true + settings.saveSource(SOURCE_ID) + login_epoch = login_epoch + 1 + Client.load() + active.read_csrf = session.read_csrf + article_cache = {} +end + +---@param url string +---@return string +local function hostOf(url) + return url:match("^https://([^/?#]+)") +end + +---@param code any +---@return boolean +local function httpOk(code) + code = tonumber(code) + return code ~= nil and code >= 200 and code < 300 +end + +---@param host string +---@param res table|nil +---@return string|nil +local function expired(host, res, cookie) + if host == READ_HOST and tonumber(res and res.code) == 401 + and cookie == require("utils.settings").getSource(SOURCE_ID).cookie + and Client.loggedIn() then + return require("source.auth").expire(SOURCE_ID, _(LOGIN_EXPIRED)) + end + return nil +end + +---@param res table|nil +local function absorb(host, res, session) + if not res then return end + for _idx, line in ipairs(Request.headerAll(res, "Set-Cookie")) do remember(host, line, session) end +end + +---@param method string +---@param url string +---@param body string|nil +---@param content_type string|nil +---@param cb fun(res: table|nil, err: string|nil) +---@return HttpJob +local function raw(method, url, body, content_type, cb, session) + if not loaded then Client.load() end + session = session or active + local host = hostOf(url) + if host ~= READ_HOST and host ~= ACCOUNT_HOST then + return require("source.base").defer(cb, nil, _("登录跳转地址无效")) + end + local headers = { Accept = "application/json, text/html;q=0.8" } + local cookie = not session.public and Client.cookieFor(host, session) or nil + if cookie then headers.Cookie = cookie end + if content_type then headers["Content-Type"] = content_type end + if host == ACCOUNT_HOST and session.csrf then + headers["X-CSRF-Token"] = session.csrf + headers.Referer = ACCOUNT .. "/" + end + if host == READ_HOST and method ~= "GET" and session.read_csrf then headers["X-CSRF-Token"] = session.read_csrf end + return Request.request({ + url = url, + method = method, + body = body, + headers = headers, + cache_ttl = 0, + timeout = require("http.timeout").net(0.5), + }, function(res, err) + if session.cancelled then return end + if not session.public then absorb(host, res, session) end + if res and host == READ_HOST then + local token = Mapper.readCsrf(res.body) + if token then session.read_csrf = token end + end + if err or not res then cb(nil, err and tostring(err) or _("请求失败")); return end + cb(res) + end) +end + +--- 登录后 read.douban.com 的写请求要带首页里的 CSRF。没有就先拉一次首页。 +---@param method string +---@param url string +---@param body string|nil +---@param content_type string|nil +---@param cb fun(res: table|nil, err: string|nil) +---@return HttpJob +local function send(method, url, body, content_type, cb) + if not loaded then Client.load() end + local session = active + if method == "GET" or hostOf(url) ~= READ_HOST or session.read_csrf or not Client.loggedIn() then + return raw(method, url, body, content_type, cb) + end + local cancelled, job = false, nil + local handle = { cancel = function() + cancelled = true + if job and job.cancel then job.cancel() end + end } + local advanced = false + local first = raw("GET", READ .. "/", nil, nil, function(res, err) + advanced = true + if cancelled then return end + if session ~= active then cb(nil, _("登录状态已变化,请重试")); return end + if not res or not httpOk(res.code) then cb(nil, err or _("请求失败")); return end + if not session.read_csrf then cb(nil, _("请求失败")); return end + job = raw(method, url, body, content_type, function(res2, err2) + if not cancelled then cb(res2, err2) end + end) + end) + if not advanced then job = first end + return handle +end + +---@param method string +---@param url string +---@param payload table|nil +---@param cb fun(wire: table|nil, err: string|nil, res: table|nil) +---@return HttpJob +local function jsonCall(method, url, payload, cb, public) + local body, content_type + if method ~= "GET" then + body = payload and JSON.encode(payload) or "{}" + content_type = "application/json" + end + local cookie = require("utils.settings").getSource(SOURCE_ID).cookie + local function done(res, err) + if not res then cb(nil, err or _("请求失败")); return end + if not public and cookie ~= require("utils.settings").getSource(SOURCE_ID).cookie then + cb(nil, _("登录状态已变化,请重试")); return + end + local reason = not public and expired(hostOf(url), res, cookie) + if reason then cb(nil, reason, res); return end + if not httpOk(res.code) then cb(nil, _("请求失败"), res); return end + local ok, wire = pcall(JSON.decode, res.body or "") + if not ok or type(wire) ~= "table" then cb(nil, _("请求失败"), res); return end + cb(wire, nil, res) + end + if public then return raw(method, url, body, content_type, done, anonymous) end + return send(method, url, body, content_type, done) +end + +---@param url string +---@param hops integer +---@param cb fun(body: string|nil, err: string|nil, final_url: string|nil) +---@return HttpJob +local function follow(url, hops, cb, session) + local cancelled, job = false, nil + local function step(current, count) + local advanced = false + local next_job = raw("GET", current, nil, nil, function(res, err) + advanced = true + if cancelled then return end + if not res then cb(nil, err or _("登录失败")); return end + local code = tonumber(res.code) + if code == 301 or code == 302 or code == 303 or code == 307 or code == 308 then + if count >= 6 then cb(nil, _("登录失败")); return end + local location = Request.header(res, "Location") + if type(location) ~= "string" or location == "" then cb(nil, _("登录失败")); return end + if location:sub(1, 2) == "//" then location = "https:" .. location + elseif location:sub(1, 1) == "/" then location = current:match("^(https://[^/]+)") .. location end + step(location, count + 1) + return + end + if not httpOk(code) then cb(nil, _("登录失败")); return end + cb(res.body or "", nil, current) + end, session) + if not advanced then job = next_job end + end + step(url, hops) + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +---@param keyword string +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return HttpJob +function Client.searchAsync(keyword, cb) + return jsonCall("POST", READ .. "/j/search_v2", Mapper.searchBody(keyword), function(wire, err) + if not wire then cb(nil, err); return end + cb(Mapper.searchBooks(wire)) + end, true) +end + +function Client.categoriesAsync(cb) + return raw("GET", READ .. "/category/", nil, nil, function(res, err) + if not res or not httpOk(res.code) then cb(nil, err or _("请求失败")); return end + cb(Mapper.categories(res.body)) + end, anonymous) +end + +function Client.catalogAsync(opts, page, cb) + return jsonCall("POST", READ .. "/j/kind/", Mapper.catalogBody(opts, page), function(wire, err) + if not wire then cb(nil, err); return end + local books, reason = Mapper.searchBooks(wire) + local total = tonumber(wire.total) + if not books or not total or total < 0 then cb(nil, reason or _("响应无效")); return end + cb(books, nil, #wire.list == 20 and page * 20 < total) + end, true) +end + +---@param works_id string +---@param cb fun(target: table|nil, err: string|nil) +---@return HttpJob +local function accessAsync(works_id, cb, public) + return jsonCall("POST", READ .. "/j/graphql", Mapper.worksBody(works_id, Mapper.ACCESS_HASH), function(wire, err) + if not wire then cb(nil, err); return end + local target = Mapper.reader(Mapper.readerUrl(wire)) + if not target then cb(nil, _("请求失败")); return end + cb(target) + end, public) +end + +---@param works_id string +---@param cb fun(book: Book|nil, err: string|nil) +---@return HttpJob +function Client.detailAsync(works_id, cb) + local cancelled, job = false, nil + local advanced = false + local first = accessAsync(works_id, function(target, err) + advanced = true + if cancelled then return end + if not target then cb(nil, err); return end + if target.kind == "column" then + job = jsonCall("GET", READ .. "/j/column/" .. target.column_id .. "/", nil, function(wire, col_err) + if cancelled then return end + local row = wire and Mapper.columnBook(works_id, wire) + if row then cb(row); return end + cb(nil, col_err or _("请求失败")) + end) + return + end + job = jsonCall("POST", READ .. "/j/graphql", Mapper.worksBody(works_id, Mapper.INFO_HASH), function(wire, info_err) + if cancelled then return end + local row = wire and Mapper.infoBook(works_id, wire) + if row then cb(row); return end + cb(nil, info_err or _("请求失败")) + end) + end) + if not advanced then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +---@param aid string +---@param cb fun(article: table|nil, err: string|nil) +---@return HttpJob +function Client.articleAsync(aid, cb) + local cached = article_cache[aid] + if cached then return require("source.base").defer(cb, cached) end + local user_id = Client.userId() + local cookie = require("utils.settings").getSource(SOURCE_ID).cookie + return send("POST", READ .. "/j/article_v2/get_reader_data", "aid=" .. Text.urlEncode(tostring(aid)), + "application/x-www-form-urlencoded", function(res, err) + if not res then cb(nil, err or _("请求失败")); return end + if cookie ~= require("utils.settings").getSource(SOURCE_ID).cookie then + cb(nil, _("登录状态已变化,请重试")); return + end + local reason = expired(READ_HOST, res, cookie) + if reason then cb(nil, reason); return end + if not httpOk(res.code) then cb(nil, _("请求失败")); return end + local ok, wire = pcall(JSON.decode, res.body or "") + if not ok or type(wire) ~= "table" then cb(nil, _("请求失败")); return end + if wire.r and tonumber(wire.r) ~= 0 then + cb(nil, type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("请求失败")) + return + end + if type(wire.data) ~= "string" or wire.data == "" then cb(nil, _("正文为空")); return end + local article, decrypt_err = Mapper.decrypt(wire.data, user_id) + if not article then cb(nil, decrypt_err); return end + article_cache[tostring(aid)] = article + cb(article) + end) +end + +---@param works_id string +---@param cb fun(chapters: BookChapter[]|nil, err: string|nil) +---@return HttpJob +function Client.tocAsync(works_id, cb) + local cancelled, job = false, nil + local advanced = false + local first = accessAsync(works_id, function(target, err) + advanced = true + if cancelled then return end + if not target then cb(nil, err); return end + if target.kind == "column" then + job = jsonCall("GET", READ .. "/j/column/" .. target.column_id .. "/", nil, function(wire, col_err) + if cancelled then return end + if not wire then cb(nil, col_err); return end + cb(Mapper.columnChapters(wire)) + end) + return + end + job = Client.articleAsync(target.aid, function(article, article_err) + if cancelled then return end + if not article then cb(nil, article_err); return end + cb(Mapper.ebookChapters(article, target.aid)) + end) + end) + if not advanced then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 本章这些段落上的他人批注。正文段落编号用逗号拼进表单。 +---@param aid string +---@param paragraph_ids string[] +---@param cb fun(rows: table|nil, err: string|nil) +---@return HttpJob|{ cancel: fun() } +function Client.annotationsAsync(aid, paragraph_ids, cb) + if type(paragraph_ids) ~= "table" or paragraph_ids[1] == nil then + return require("source.base").defer(cb, {}) + end + local cookie = require("utils.settings").getSource(SOURCE_ID).cookie + local body = "paragraph_ids=" .. Text.urlEncode(table.concat(paragraph_ids, ",")) + local url = READ .. "/j/article_v2/" .. Text.urlEncode(tostring(aid)) .. "/annotations_by_paragraphs" + return send("POST", url, body, "application/x-www-form-urlencoded", function(res, err) + if not res then cb(nil, err or _("请求失败")); return end + local reason = expired(READ_HOST, res, cookie) + if reason then cb(nil, reason); return end + if not httpOk(res.code) then cb(nil, _("请求失败")); return end + local ok, wire = pcall(JSON.decode, res.body or "") + if not ok or type(wire) ~= "table" or (next(wire) ~= nil and wire[1] == nil) then + cb(nil, _("响应无效")); return + end + cb(wire) + end) +end + +---@param aid string +---@param start_pid number|nil +---@param end_pid number|nil +---@param cb fun(text: string|nil, err: string|nil) +---@return HttpJob +function Client.textAsync(aid, start_pid, end_pid, cb) + return Client.articleAsync(aid, function(article, err) + if not article then cb(nil, err); return end + local text = Mapper.blocksText(article, start_pid, end_pid) + if text == "" then cb(nil, _("正文为空")); return end + cb(text) + end) +end + +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return HttpJob +function Client.shelfAsync(cb) + if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录豆瓣阅读")) end + local cancelled, job = false, nil + local function loadWorks(ids, groups) + job = jsonCall("POST", READ .. "/j/graphql", Mapper.shelfWorksBody(ids), function(detail, err) + if cancelled then return end + if not detail then cb(nil, err); return end + cb(Mapper.shelfWorks(detail, groups, ids)) + end) + end + local function loadGroupDetails(ids, folder_ids) + local advanced = false + local pending = jsonCall("POST", READ .. "/j/graphql", { + variables = { folderIds = folder_ids, userId = Client.userId() }, + extensions = { persistedQuery = { version = 1, sha256Hash = Mapper.SHELF_FOLDERS_HASH } }, + }, function(wire, err) + advanced = true + if cancelled then return end + if not wire then cb(nil, err); return end + local groups, group_err = Mapper.shelfGroups(wire, folder_ids) + if not groups then cb(nil, group_err); return end + loadWorks(ids, groups) + end) + if not advanced then job = pending end + end + local function loadGroups(ids) + local advanced = false + local pending = jsonCall("GET", READ .. "/j/bookshelf/folder/", nil, function(wire, err) + advanced = true + if cancelled then return end + if not wire then cb(nil, err); return end + local folder_ids, folder_err = Mapper.folderIds(wire) + if not folder_ids then cb(nil, folder_err); return end + if #folder_ids == 0 then loadWorks(ids, {}); return end + loadGroupDetails(ids, folder_ids) + end) + if not advanced then job = pending end + end + local advanced = false + local first = jsonCall("GET", READ .. "/j/bookshelf/", nil, function(wire, err) + advanced = true + if cancelled then return end + if not wire then cb(nil, err); return end + local ids, id_err = Mapper.shelfIds(wire) + if not ids then cb(nil, id_err); return end + if #ids == 0 then cb({}); return end + if require("source.category_setting").enabled(SOURCE_ID) then loadGroups(ids) + else loadWorks(ids) end + end) + if not advanced then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +---@param works_id string +---@param method string +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return HttpJob +local function shelfWrite(works_id, method, cb) + if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录豆瓣阅读")) end + return jsonCall(method, READ .. "/j/bookshelf/", { worksIds = { tostring(works_id) } }, function(wire, err) + if not wire then cb(nil, err or (method == "DELETE" and _("移出豆瓣阅读书架失败") or _("加入豆瓣阅读书架失败"))); return end + cb(true) + end) +end + +function Client.addAsync(works_id, cb) + return shelfWrite(works_id, "POST", cb) +end + +function Client.removeAsync(works_id, cb) + return shelfWrite(works_id, "DELETE", cb) +end + +--- 进度和阅读时长的回包没有字段可用,2xx 就算写上了。 +---@param url string +---@param body string +---@param content_type string +---@param fail string +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return HttpJob +local function write(url, body, content_type, fail, cb) + if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录豆瓣阅读")) end + local cookie = require("utils.settings").getSource(SOURCE_ID).cookie + return send("POST", url, body, content_type, function(res, err) + if not res then cb(nil, err or fail); return end + local reason = expired(READ_HOST, res, cookie) + if reason then cb(nil, reason); return end + if not httpOk(res.code) then cb(nil, fail); return end + if res.body and res.body ~= "" then + local ok, wire = pcall(JSON.decode, res.body) + if not ok or type(wire) ~= "table" + or (wire.r ~= nil and wire.r ~= 0 and wire.r ~= false) then + cb(nil, fail) + return + end + end + cb(true) + end) +end + +---@param works_id string +---@param cb fun(mark: { paragraph_id: string }|nil, err: string|nil) +---@return HttpJob +function Client.progressAsync(works_id, cb) + if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录豆瓣阅读")) end + return jsonCall("GET", READ .. "/j/progress/?works_id=" .. tostring(works_id), nil, function(wire, err) + if not wire then cb(nil, err); return end + local mark, empty = Mapper.progress(wire) + if empty then cb(nil); return end + if not mark then cb(nil, _("请求失败")); return end + cb(mark) + end) +end + +--- 上传正文段落及分段索引;百分比只在整本(非专栏)时带上,和网页一致。 +---@param works_id string +---@param paragraph_id string +---@param idx integer +---@param total integer +---@param with_percent boolean +---@param cb fun(ok: boolean|nil, err: string|nil) +---@param position table|nil 官网正文分段索引 +---@return HttpJob +function Client.putProgressAsync(works_id, paragraph_id, idx, total, with_percent, cb, position) + local count = total > 0 and total or 1 + local payload = { + works_id = tonumber(works_id) or works_id, + paragraph_id = tonumber(paragraph_id) or paragraph_id, + paragraph_offset = 0, + part_sequence = position and position.part_sequence or idx - 1, + part_paragraph_sequence = position and position.part_paragraph_sequence or 0, + } + if with_percent then payload.percentage = math.floor((idx - 1) / count * 100) end + return write(READ .. "/j/progress/", Text.formEncode(payload), + "application/x-www-form-urlencoded", _("豆瓣阅读进度保存失败"), cb) +end + +--- 阅读时长。网页把会话数组原样 POST 到 /j/reading_time,时间是 ISO。 +---@param sessions table[] +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return HttpJob +function Client.pushReadingAsync(sessions, cb) + return write(READ .. "/j/reading_time", JSON.encode(sessions), + "application/json", _("豆瓣阅读阅读记录保存失败"), cb) +end + +function Client.readingStatsAsync(begin_date, cb) + if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录豆瓣阅读")) end + return jsonCall("POST", READ .. "/j/graphql", { + variables = { userId = Client.userId(), beginDate = begin_date }, + extensions = { persistedQuery = { version = 1, sha256Hash = Mapper.READING_TIME_HASH } }, + }, cb) +end + +---@class DoubanLogin +---@field jars table +---@field epoch integer +---@field cancelled boolean|nil +---@field csrf string|nil +---@field read_csrf string|nil +local Login = {} +Login.__index = Login + +---@param cookie string|nil +---@return DoubanLogin +function Client.newLogin(cookie) + local session = setmetatable({ jars = {}, epoch = login_epoch }, Login) + for pair in (cookie or ""):gmatch("[^;]+") do remember(READ_HOST, pair, session) end + return session +end + +function Login:cancel() + self.cancelled = true +end + +function Login:commit(user) + if self.cancelled or self.epoch ~= login_epoch then return nil, _("登录状态已变化,请重试") end + if not Client.cookieFor(READ_HOST, self) then return nil, _("登录失败") end + local cfg = require("utils.settings").getSource(SOURCE_ID) + if (cfg.logged_in or cfg.cookie or cfg.user_id) and cfg.user_id ~= user.id then + local cleared = require("source.logout").clear(SOURCE_ID, function() + cfg.cookie, cfg.user_id, cfg.name, cfg.logged_in = nil, nil, nil, nil + require("utils.settings").saveSource(SOURCE_ID) + Client.reset() + end) + if not cleared then return nil, _("准备本地同步失败") end + end + persist(user, self) + return true +end + +function Login:checkCookieAsync(cb) + return follow(READ .. "/", 0, function(html, err, final_url) + if self.cancelled or self.epoch ~= login_epoch then cb(false, _("登录状态已变化,请重试")); return end + local user = html and hostOf(final_url) == READ_HOST and Mapper.user(html) + if not user then cb(false, err or _("登录失败")); return end + cb(true, nil, user) + end, self) +end + +---@param cb fun(authorize: string|nil, err: string|nil) +---@return HttpJob +function Login:beginAsync(cb) + return follow(LOGIN_URL, 0, function(html, err, authorize) + if not html then cb(nil, err or _("登录失败")); return end + self.csrf = Mapper.csrf(html) + if not self.csrf or hostOf(authorize) ~= ACCOUNT_HOST then cb(nil, _("登录失败")); return end + self.authorize = authorize + cb(authorize) + end, self) +end + +local function accountResponse(res, err) + if not res then return nil, err or _("请求失败") end + local ok, wire = pcall(JSON.decode, res.body or "") + if not httpOk(res.code) then + if ok and type(wire) == "table" and type(wire.message) == "string" and wire.message ~= "" then + return nil, wire.message + end + return nil, _("请求失败") + end + if not ok or type(wire) ~= "table" then return nil, _("响应无效") end + return wire +end + +---@param phone string 国际区号与手机号,例如 +86… +---@param cb fun(retry_after: number|nil, err: string|nil) +---@return HttpJob +function Login:sendPhoneCodeAsync(phone, cb) + return raw("POST", ACCOUNT .. "/oidc/phone/verify_code", JSON.encode({ phone_number = phone }), + "application/json", function(res, err) + local wire, reason = accountResponse(res, err) + if not wire then cb(nil, reason); return end + if not (type(wire.retry_after) == "number" and wire.retry_after >= 0 and wire.retry_after < math.huge) then + cb(nil, _("响应无效")); return + end + cb(wire.retry_after) + end, self) +end + +---@param phone string +---@param code string +---@param cb fun(user: table|nil, err: string|nil) +---@return HttpJob +function Login:verifyPhoneAsync(phone, code, cb) + local cancelled, job, advanced = false, nil, false + local first = raw("POST", ACCOUNT .. "/oidc/phone/verify", JSON.encode({ phone_number = phone, code = code }), + "application/json", function(res, err) + advanced = true + if cancelled then return end + local wire, reason = accountResponse(res, err) + if not wire then cb(nil, reason); return end + if type(wire.transfer_info) == "table" then + cb(nil, _("此账号需要在豆瓣阅读官网确认历史数据授权,完成后再登录")); return + end + job = self:finishQrAsync(self.authorize, function(user, finish_err) + if not cancelled then cb(user, finish_err) end + end) + end, self) + if not advanced then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +---@param cb fun(ticket: { qr: string, code: string, authorize: string, expires_in: number }|nil, err: string|nil) +---@return HttpJob +function Login:beginQrAsync(cb) + local cancelled, job = false, nil + local advanced = false + local first = self:beginAsync(function(authorize, err) + advanced = true + if cancelled then return end + if not authorize then cb(nil, err or _("获取二维码失败")); return end + job = raw("POST", ACCOUNT .. "/oidc/qrcode/generate", nil, "application/json", function(res, gen_err) + if cancelled then return end + if not res or not httpOk(res.code) then cb(nil, gen_err or _("获取二维码失败")); return end + local decoded, wire = pcall(JSON.decode, res.body or "") + if not decoded then cb(nil, _("获取二维码失败")); return end + local ticket = wire and Mapper.qr(wire, ACCOUNT) + if not ticket or type(authorize) ~= "string" then cb(nil, gen_err or _("获取二维码失败")); return end + cb({ qr = ticket.qr, code = ticket.code, authorize = authorize, expires_in = ticket.expires_in }) + end, self) + end) + if not advanced then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +---@param code string +---@param cb fun(kind: string|nil, err: string|nil) +---@return HttpJob +function Login:qrStatusAsync(code, cb) + return raw("POST", ACCOUNT .. "/oidc/qrcode/status", JSON.encode({ code = code }), "application/json", function(res, err) + if not res or not httpOk(res.code) then cb(nil, err or _("登录失败")); return end + local decoded, wire = pcall(JSON.decode, res.body or "") + local kind = decoded and Mapper.qrStatus(wire) + if not kind then cb(nil, _("登录失败")); return end + cb(kind) + end, self) +end + +---@param authorize string +---@param cb fun(user: { id: string, name: string }|nil, err: string|nil) +---@return HttpJob +function Login:finishQrAsync(authorize, cb) + local cancelled, job = false, nil + local advanced = false + local first = follow(authorize, 0, function(html, err, final_url) + advanced = true + if cancelled then return end + if not html then cb(nil, err or _("登录失败")); return end + local user = Mapper.user(html) + if user and hostOf(final_url) == READ_HOST then + local ok, reason = self:commit(user) + cb(ok and user or nil, reason) + return + end + if hostOf(final_url) == READ_HOST then cb(nil, _("登录失败")); return end + job = follow(READ .. "/", 0, function(home, home_err) + if cancelled then return end + user = home and Mapper.user(home) + if not user then cb(nil, home_err or _("登录失败")); return end + local ok, reason = self:commit(user) + cb(ok and user or nil, reason) + end, self) + end, self) + if not advanced then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +---@param works_id string +---@param chapter_id string|nil +---@param offset integer +---@param cb fun(page: table|nil, err: string|nil) +---@return HttpJob +function Client.communityAsync(works_id, chapter_id, offset, cb) + if offset > 0 and not Client.loggedIn() then + return require("source.base").defer(cb, nil, _("请先登录豆瓣阅读")) + end + local cancelled, job, pending = false, nil, true + local function fetch(column_id) + local body = Mapper.worksBody(works_id, + "sha256:ec47b1cca2876392e72ca83dd4d59b12e2e27b72366d2c1b7a8e9ff672f4bb7c") + if chapter_id then + body.extensions.persistedQuery.sha256Hash = + "sha256:161b3ceea6f04246919461367c6c071d62020836125a9ba6c42022295717a30a" + body.variables.worksId = nil + body.variables.columnId = column_id + body.variables.chapterId = chapter_id + end + body.variables.start, body.variables.limit = offset, 20 + body.variables.sort, body.variables.isAdmin = "TIME_DESC", false + return jsonCall("POST", READ .. "/j/graphql", body, function(wire, err) + if cancelled then return end + if not wire then cb(nil, err); return end + cb(Mapper.communityPage(wire, offset, chapter_id)) + end, offset == 0) + end + if not chapter_id then return fetch() end + local first = accessAsync(works_id, function(target, err) + pending = false + if cancelled then return end + if not target then cb(nil, err); return end + if target.kind ~= "column" then + cb({ items = {}, total = 0, more = false, max_idx = offset, unsupported = true }) + return + end + job = fetch(target.column_id) + end, true) + if pending then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +return Client diff --git a/moonsource-douban.koplugin/moonsource_douban/l10n/en.lua b/moonsource-douban.koplugin/moonsource_douban/l10n/en.lua new file mode 100644 index 0000000..90db07c --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/l10n/en.lua @@ -0,0 +1,62 @@ +return { + ["书评预览"] = "Book comment previews", + ["豆瓣阅读手机号登录"] = "Douban Read SMS sign-in", + ["国际区号"] = "Country calling code", + ["请输入有效的手机号和国际区号"] = "Enter a valid phone number and country calling code.", + ["请稍后再获取验证码"] = "Please wait before requesting another code.", + ["验证码已发送"] = "Verification code sent", + ["正在获取验证码…"] = "Requesting a verification code…", + ["正在处理,请稍候"] = "Processing, please wait.", + ["请先获取该手机号的验证码,再填写验证码登录"] = "Request a code for this phone number, then enter it to sign in.", + ["登录前请阅读并同意豆瓣阅读使用协议、隐私政策和社区指导原则"] = "Before signing in, read and agree to the Douban Read terms, privacy policy and community guidelines.", + ["同意并登录"] = "Agree and sign in", + ["此账号需要在豆瓣阅读官网确认历史数据授权,完成后再登录"] = "This account requires authorization for historical data on the official Douban Read website. Complete that step before signing in here.", + ["豆瓣阅读登录 Cookie"] = "Douban Read login Cookie", + ["切换豆瓣阅读账号前,请先退出旧账号;退出会清理该源的本地书架和阅读记录"] = "Sign out of the old Douban Read account before switching accounts. Signing out clears this source's local shelf and reading records.", + ["登录状态已变化,请重试"] = "The login session changed. Please retry.", + ["登录跳转地址无效"] = "Invalid login redirect", + ["原创"] = "Original", + ["销量"] = "Sales", + ["好评"] = "Top rated", + ["价格最低"] = "Lowest price", + ["豆瓣高分"] = "Douban rating", + ["章节评论"] = "Chapter comments", + ["请先登录豆瓣阅读"] = "Please sign in to Douban Read first", + ["获取验证码"] = "Get code", + ["豆瓣阅读"] = "Douban Read", + ["豆瓣阅读书架与在线阅读"] = "Douban Read shelf and online reading", + ["豆瓣阅读扫码登录"] = "Douban Read QR sign-in", + ["用豆瓣阅读 App 扫一扫"] = "Scan with the Douban Read app", + ["打开豆瓣阅读 App,扫屏幕上的二维码"] = "Open the Douban Read app and scan the QR code", + ["豆瓣阅读账号"] = "Douban Read account", + ["未登录豆瓣阅读"] = "Not signed in to Douban Read", + ["豆瓣阅读目录为空"] = "Douban Read chapter list is empty", + ["豆瓣阅读登录已失效,请点「重新登录」,用豆瓣阅读 App 扫码。"] = "Douban Read sign-in has expired. Tap Sign in again and scan with the Douban Read app.", + ["确定退出豆瓣阅读账号?"] = "Sign out of Douban Read?", + ["豆瓣阅读书架数据无法识别"] = "Douban Read shelf data was not recognized", + ["移出豆瓣阅读书架失败"] = "Could not remove the book from the Douban Read shelf", + ["加入豆瓣阅读书架失败"] = "Could not add the book to the Douban Read shelf", + ["豆瓣阅读进度保存失败"] = "Could not save the Douban Read position", + ["豆瓣阅读阅读记录保存失败"] = "Could not save the Douban Read reading time", + ["缺少豆瓣阅读章节位置"] = "Missing the Douban Read chapter position", + ["正文为空"] = "Chapter text is empty", + ["正文解密失败"] = "Could not decrypt the chapter", + ["手机号验证码登录"] = "Sign in with an SMS code", + ["本章未购买"] = "This chapter has not been purchased", + ["出版"] = "Published", + ["价格"] = "Price", + ["免费"] = "Free", + ["付费"] = "Paid", + ["连载中"] = "Ongoing", + ["已完结"] = "Completed", + ["未登录 · 点此扫码"] = "Not signed in · tap to scan", + ["正在登录…"] = "Signing in…", + ["章节目录保存失败"] = "Failed to save chapter list", + ["手机号"] = "Phone number", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header", + ["VIP 章节"] = "VIP chapters", + ["书架同步"] = "Shelf sync", + ["搜索与发现"] = "Search and discover", + ["统计同步"] = "Statistics sync", + ["进度同步"] = "Progress sync", +} diff --git a/moonsource-douban.koplugin/moonsource_douban/l10n/zh_TW.lua b/moonsource-douban.koplugin/moonsource_douban/l10n/zh_TW.lua new file mode 100644 index 0000000..80d631b --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/l10n/zh_TW.lua @@ -0,0 +1,62 @@ +return { + ["书评预览"] = "書評預覽", + ["豆瓣阅读手机号登录"] = "豆瓣閱讀手機號碼登入", + ["国际区号"] = "國際區碼", + ["请输入有效的手机号和国际区号"] = "請輸入有效的手機號碼和國際區碼", + ["请稍后再获取验证码"] = "請稍後再取得驗證碼", + ["验证码已发送"] = "驗證碼已發送", + ["正在获取验证码…"] = "正在取得驗證碼…", + ["正在处理,请稍候"] = "正在處理,請稍候", + ["请先获取该手机号的验证码,再填写验证码登录"] = "請先取得該手機號碼的驗證碼,再填寫驗證碼登入", + ["登录前请阅读并同意豆瓣阅读使用协议、隐私政策和社区指导原则"] = "登入前請閱讀並同意豆瓣閱讀使用協議、隱私政策和社群指導原則", + ["同意并登录"] = "同意並登入", + ["此账号需要在豆瓣阅读官网确认历史数据授权,完成后再登录"] = "此帳號需要在豆瓣閱讀官網確認歷史資料授權,完成後再登入", + ["豆瓣阅读登录 Cookie"] = "豆瓣閱讀登入 Cookie", + ["切换豆瓣阅读账号前,请先退出旧账号;退出会清理该源的本地书架和阅读记录"] = "切換豆瓣閱讀帳號前,請先登出舊帳號;登出會清理此書源的本機書架和閱讀記錄", + ["登录状态已变化,请重试"] = "登入狀態已改變,請重試", + ["登录跳转地址无效"] = "登入重新導向網址無效", + ["原创"] = "原創", + ["销量"] = "銷量", + ["好评"] = "好評", + ["价格最低"] = "價格最低", + ["豆瓣高分"] = "豆瓣高分", + ["章节评论"] = "章節評論", + ["请先登录豆瓣阅读"] = "請先登入豆瓣閱讀", + ["获取验证码"] = "取得驗證碼", + ["豆瓣阅读"] = "豆瓣閱讀", + ["豆瓣阅读书架与在线阅读"] = "豆瓣閱讀書架與線上閱讀", + ["豆瓣阅读扫码登录"] = "豆瓣閱讀掃碼登入", + ["用豆瓣阅读 App 扫一扫"] = "用豆瓣閱讀 App 掃一掃", + ["打开豆瓣阅读 App,扫屏幕上的二维码"] = "打開豆瓣閱讀 App,掃螢幕上的二維碼", + ["豆瓣阅读账号"] = "豆瓣閱讀帳號", + ["未登录豆瓣阅读"] = "未登入豆瓣閱讀", + ["豆瓣阅读目录为空"] = "豆瓣閱讀目錄為空", + ["豆瓣阅读登录已失效,请点「重新登录」,用豆瓣阅读 App 扫码。"] = "豆瓣閱讀登入已失效,請點「重新登入」,用豆瓣閱讀 App 掃碼。", + ["确定退出豆瓣阅读账号?"] = "確定退出豆瓣閱讀帳號?", + ["豆瓣阅读书架数据无法识别"] = "豆瓣閱讀書架資料無法識別", + ["移出豆瓣阅读书架失败"] = "移出豆瓣閱讀書架失敗", + ["加入豆瓣阅读书架失败"] = "加入豆瓣閱讀書架失敗", + ["豆瓣阅读进度保存失败"] = "豆瓣閱讀進度保存失敗", + ["豆瓣阅读阅读记录保存失败"] = "豆瓣閱讀閱讀記錄保存失敗", + ["缺少豆瓣阅读章节位置"] = "缺少豆瓣閱讀章節位置", + ["正文为空"] = "正文為空", + ["正文解密失败"] = "正文解密失敗", + ["手机号验证码登录"] = "手機號碼驗證碼登入", + ["本章未购买"] = "本章未購買", + ["出版"] = "出版", + ["价格"] = "價格", + ["免费"] = "免費", + ["付费"] = "付費", + ["连载中"] = "連載中", + ["已完结"] = "已完結", + ["未登录 · 点此扫码"] = "未登入 · 點此掃碼", + ["正在登录…"] = "正在登入…", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["手机号"] = "手機號碼", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie", + ["VIP 章节"] = "VIP 章節", + ["书架同步"] = "書架同步", + ["搜索与发现"] = "搜尋與發現", + ["统计同步"] = "統計同步", + ["进度同步"] = "進度同步", +} diff --git a/moonsource-douban.koplugin/moonsource_douban/loadmeta.lua b/moonsource-douban.koplugin/moonsource_douban/loadmeta.lua new file mode 100644 index 0000000..62dbabe --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_douban._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-douban.koplugin/moonsource_douban/mapper.lua b/moonsource-douban.koplugin/moonsource_douban/mapper.lua new file mode 100644 index 0000000..2576d7e --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/mapper.lua @@ -0,0 +1,813 @@ +--[[-- +豆瓣阅读网页响应 → 领域对象。纯函数,不发请求。 + +搜索和作品查询是持久化 GraphQL:请求里只有 sha256,没有查询文本。 +正文是 Base64 后的 AES-256-CBC。末尾 16 字节是 IV,再往前的密文才解密,最后 13 字节丢掉。 +密钥是 SHA-256("anonymous"),登录后换成 SHA-256(用户编号)。 + +@module moonsource_douban.mapper +--]] + +local Aes = require("crypto.aes") +local CategorySetting = require("source.category_setting") +local JSON = require("json") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_douban") + +local Mapper = {} + +local SOURCE_ID = "ext.douban" + +Mapper.TOC_VERSION = 2 +Mapper.SEARCH_HASH = "sha256:92911ffc68782f44a56764094edc0068f283c29fb447277f8ed2911af6bbd0a0" +Mapper.ACCESS_HASH = "sha256:bf9257d4f673ee55c4ef0fbf7f495a4cf1fd972048ef4a823d92f40636c36f25" +Mapper.INFO_HASH = "sha256:2ba0b5cafe47036cf931fcf749803c0fed974b448cd479e48fc35edd75e540a7" +--- 书架页先拿编号,再用这条查询补 title / author / cover。 +Mapper.SHELF_WORKS_HASH = "sha256:d9cff923ff4ed25849b6dc0d493b027533c4f252647107f2226de11b78f7b831" +Mapper.SHELF_FOLDERS_HASH = "sha256:226417726ce78055a35e7281426637272fdaaef4a001e15a975a41e37a2331cc" +Mapper.READING_TIME_HASH = "sha256:03a310ea89efc4801c0071c4d3c5bcae7ae9227cada95c731e7222a0811e491f" + +local SEARCH_VARIABLES = { + includeRating = false, + includeBookRating = false, + includeUpdateTime = false, + includeSaleInfo = false, + includePurchase = false, + includeLibraryCount = false, + includeFandom = false, + includeFanfictionTags = false, +} + +---@param value any +---@return string +local function clean(value) + if type(value) ~= "string" then return "" end + return Text.trim(Text.xmlDecode(value)) +end + +---@param title any +---@param idx integer +---@return string +local function chapterTitle(title, idx) + local cleaned = clean(title) + if cleaned ~= "" then return cleaned end + return require("ffi/util").template(_("第 %1 章"), idx) +end + +---@param cover any +---@return string|nil +local function picture(cover) + if type(cover) ~= "string" or cover == "" then return nil end + cover = Text.xmlDecode(cover) + if cover:sub(1, 2) == "//" then return "https:" .. cover end + return cover +end + +---@param author any +---@return string +local function authors(author) + if type(author) == "string" then return clean(author) end + if type(author) ~= "table" then return "" end + if type(author.name) == "string" then return clean(author.name) end + local names = {} + for _idx, person in ipairs(author) do + local name = type(person) == "table" and person.name or person + if type(name) == "string" and name ~= "" then names[#names + 1] = clean(name) end + end + return table.concat(names, " ") +end + +---@param id any +---@param title any +---@param author any +---@param intro any +---@param cover any +---@param category any +---@return Book +local function book(id, title, author, intro, cover, category) + return { + source_id = SOURCE_ID, + stable_id = tostring(id), + title = clean(title), + authors = authors(author), + intro = clean(intro), + cover = picture(cover), + category = clean(category) ~= "" and clean(category) or nil, + } +end + +---@param works_id any +---@param hash string +---@return table +function Mapper.worksBody(works_id, hash) + return { + variables = { worksId = tostring(works_id) }, + extensions = { persistedQuery = { version = 1, sha256Hash = hash } }, + } +end + +---@param keyword string +---@return table +function Mapper.searchBody(keyword) + return { + sort = "default", + page = 1, + q = keyword, + extensions = { persistedQuery = { version = 1, sha256Hash = Mapper.SEARCH_HASH } }, + variables = SEARCH_VARIABLES, + } +end + +---@param opts table +---@param page integer +---@return table +function Mapper.catalogBody(opts, page) + local body = { + kind = tonumber(opts.category), + sort = opts.sort, + page = page, + extensions = { persistedQuery = { version = 1, sha256Hash = Mapper.SEARCH_HASH } }, + variables = SEARCH_VARIABLES, + } + if opts.pay == "free" then body.minPrice, body.maxPrice = 0, 0 + elseif opts.pay == "paid" then body.minPrice = 1 end + if opts.state == "complete" then body.isFinished = true + elseif opts.state == "serial" then body.isFinished = false end + return body +end + +---@param html string +---@return table|nil +---@return string|nil +function Mapper.categories(html) + local raw = type(html) == "string" and html:match("Ark%.kindTree%s*=%s*(%b[])") + local ok, tree = pcall(JSON.decode, raw or "") + if not ok or type(tree) ~= "table" then return nil, _("响应无效") end + local categories = { original = {}, publish = {} } + local function append(rows, out) + for _idx, row in ipairs(rows) do + if type(row) ~= "table" or type(row.id) ~= "number" or type(row.name) ~= "string" + or type(row.children) ~= "table" then return false end + out[#out + 1] = { id = tostring(row.id), title = clean(row.name) } + if not append(row.children, out) then return false end + end + return true + end + for _idx, root in ipairs(tree) do + if type(root) ~= "table" then return nil, _("响应无效") end + local channel = root.id == 0 and "original" or root.id == 1 and "publish" or nil + if channel and (type(root.children) ~= "table" or not append(root.children, categories[channel])) then + return nil, _("响应无效") + end + end + if #categories.original == 0 or #categories.publish == 0 then return nil, _("响应无效") end + return categories +end + +---@param item table +---@return Book|nil +local function worksBook(item) + if type(item) ~= "table" or item.isAudio == true or item.isBundle == true then return nil end + local id = item.id or item.worksId or item.works_id + local title = item.title or item.name + if id == nil or title == nil or title == "" then return nil end + local category = item.category + if type(item.kinds) == "table" and type(item.kinds[1]) == "table" then + category = item.kinds[1].shortName or item.kinds[1].name + end + return book(id, title, item.author or item.agent, item.abstract or item.intro, item.cover or item.cover_url, category) +end + +---@param wire table|nil +---@return Book[]|nil +---@return string|nil +function Mapper.searchBooks(wire) + if type(wire) ~= "table" or type(wire.list) ~= "table" then + return nil, type(wire) == "table" and type(wire.error) == "string" and wire.error or _("请求失败") + end + local books = {} + for _idx, item in ipairs(wire.list) do + local row = worksBook(item) + if row then books[#books + 1] = row end + end + return books +end + +---@param url string|nil +---@return { kind: string, column_id: string|nil, aid: string|nil }|nil +function Mapper.reader(url) + if type(url) ~= "string" then return nil end + local column_id = url:match("/reader/column/(%d+)/") + if column_id then return { kind = "column", column_id = column_id } end + local aid = url:match("/reader/ebook/(%d+)") + if aid then return { kind = "ebook", aid = aid } end + return nil +end + +---@param wire table|nil +---@return string|nil +function Mapper.readerUrl(wire) + local data = type(wire) == "table" and wire.data or nil + local works = type(data) == "table" and data.works or nil + local url = type(works) == "table" and works.readerUrl or nil + if type(url) ~= "string" or url == "" then return nil end + return url +end + +---@param works_id string +---@param wire table|nil +---@return Book|nil +function Mapper.columnBook(works_id, wire) + if type(wire) ~= "table" or wire.type ~= "column" or type(wire.title) ~= "string" then return nil end + return book(works_id, wire.title, wire.agent, wire.abstract, wire.cover or wire.retina_cover, wire.category) +end + +---@param works_id string +---@param wire table|nil +---@return Book|nil +function Mapper.infoBook(works_id, wire) + local data = type(wire) == "table" and wire.data or nil + local works = type(data) == "table" and (data.universalWorks or data.works) or nil + if type(works) ~= "table" or type(works.title) ~= "string" then return nil end + return book(works_id, works.title, nil, nil, nil, nil) +end + +---@param wire table|nil +---@return BookChapter[]|nil +---@return string|nil +function Mapper.columnChapters(wire) + if type(wire) ~= "table" or type(wire.chapters) ~= "table" then return nil, _("豆瓣阅读目录为空") end + local chapters = {} + for idx, item in ipairs(wire.chapters) do + if type(item) == "table" and item.id ~= nil then + local free = item.is_free == true or item.is_paid == true or item.is_allowed_to_read == true + chapters[#chapters + 1] = { + idx = idx, + uid = tostring(item.id), + title = chapterTitle(item.title, idx), + content_url = tostring(item.id), + vip = not free, + } + end + end + if not chapters[1] then return nil, _("豆瓣阅读目录为空") end + chapters[1].toc_version = Mapper.TOC_VERSION + return chapters +end + +---@param b64 string +---@param user_id string|nil +---@return table|nil +---@return string|nil +function Mapper.decrypt(b64, user_id) + local raw = Text.base64Decode(b64) + local cipher_len = #raw - 16 - 13 + if cipher_len < 16 or cipher_len % 16 ~= 0 then return nil, _("正文解密失败") end + local material = type(user_id) == "string" and user_id ~= "" and user_id or "anonymous" + local sha2 = require("ffi/sha2") + local key = sha2.hex_to_bin(sha2.sha256(material)) + local ok, plain = pcall(Aes.cbc_decrypt, raw:sub(1, cipher_len), key, raw:sub(cipher_len + 1, cipher_len + 16)) + if not ok or type(plain) ~= "string" then return nil, _("正文解密失败") end + local decoded, article = pcall(JSON.decode, plain) + if not decoded or type(article) ~= "table" then return nil, _("正文解密失败") end + return article +end + +---@param data table|nil +---@return string +local function paragraphText(data) + local text = data and data.text + if type(text) == "table" then + local parts = {} + for _idx, run in ipairs(text) do + if run.kind == "plaintext" then parts[#parts + 1] = run.content end + end + text = table.concat(parts) + end + return type(text) == "string" and Text.trim(text) or "" +end + +---@param article table +---@param start_pid number|nil +---@param end_pid number|nil +---@return string +function Mapper.blocksText(article, start_pid, end_pid) + local lines = {} + local posts = type(article.posts) == "table" and article.posts or {} + for _pidx, post in ipairs(posts) do + local contents = type(post) == "table" and post.contents or nil + if type(contents) == "table" then + for _bidx, block in ipairs(contents) do + local id = type(block) == "table" and tonumber(block.id) or nil + local in_range = not start_pid or (id and id >= start_pid and (not end_pid or id < end_pid)) + local kind = type(block) == "table" and block.type or nil + if in_range and (kind == "paragraph" or kind == "headline") then + local text = paragraphText(block.data) + if text ~= "" then lines[#lines + 1] = text end + end + end + end + end + return table.concat(lines, "\n") +end + +--- 本章非空段的段落编号,顺序和章节 HTML 里的

一致。 +---@param article table|nil +---@param start_pid number|nil +---@param end_pid number|nil +---@return string[] +function Mapper.paragraphIds(article, start_pid, end_pid) + local ids = {} + local posts = type(article) == "table" and article.posts or {} + for _pidx, post in ipairs(type(posts) == "table" and posts or {}) do + local contents = type(post) == "table" and post.contents or nil + if type(contents) == "table" then + for _bidx, block in ipairs(contents) do + local id = type(block) == "table" and tonumber(block.id) or nil + local in_range = not start_pid or (id and id >= start_pid and (not end_pid or id < end_pid)) + local kind = type(block) == "table" and block.type or nil + if id and in_range and (kind == "paragraph" or kind == "headline") and paragraphText(block.data) ~= "" then + ids[#ids + 1] = tostring(block.id) + end + end + end + end + return ids +end + +--- 批注时间。秒级数字;13 位毫秒收成秒。没有数字就给 0。 +---@param value any +---@return integer +local function created(value) + local n = tonumber(value) + if n then + if n > 1e12 then n = math.floor(n / 1000) end + return math.floor(n) + end + if type(value) ~= "string" then return 0 end + local year, month, day, hour, min, sec = value:match("^(%d%d%d%d)%-(%d%d)%-(%d%d)T(%d%d):(%d%d):(%d%d)") + if not year then return 0 end + local stamp = os.time({ + year = tonumber(year), month = tonumber(month), day = tonumber(day), + hour = tonumber(hour), min = tonumber(min), sec = tonumber(sec), + }) + if not stamp then return 0 end + local now = os.time() + return stamp + os.difftime(now, os.time(os.date("!*t", now))) +end + +--- 一段上的批注条数。没有 note 的划线不是段评。range 是本章第几个非空段。 +---@param rows table|nil +---@param pids string[] +---@return { range: string, text: string, total: integer }[]|nil +function Mapper.reviewHotspots(rows, pids) + if type(rows) ~= "table" then return nil end + local index = {} + for idx, pid in ipairs(pids) do index[tostring(pid)] = tostring(idx) end + local counts = {} + for _idx, row in ipairs(rows) do + local note = type(row) == "table" and type(row.note) == "string" and Text.trim(row.note) or "" + local pid = type(row) == "table" and row.startContainerId ~= nil and tostring(row.startContainerId) or nil + local range = pid and index[pid] + if range and note ~= "" then counts[range] = (counts[range] or 0) + 1 end + end + local out = {} + for range, total in pairs(counts) do + out[#out + 1] = { range = range, text = "", total = total } + end + table.sort(out, function(a, b) return tonumber(a.range) < tonumber(b.range) end) + return out +end + +--- 某一段的批注。作者是 owner.name,赞是 n_favorites。 +---@param rows table|nil +---@param pids string[] +---@param range string|number +---@return { items: table[], total: integer, max_idx: integer, more: boolean }|nil +function Mapper.reviewPage(rows, pids, range) + if type(rows) ~= "table" then return nil end + local pid = pids[tonumber(range)] + local items = {} + for _idx, row in ipairs(rows) do + if type(row) == "table" and pid and tostring(row.startContainerId) == tostring(pid) then + local note = type(row.note) == "string" and Text.trim(row.note) or "" + local owner = type(row.owner) == "table" and row.owner or nil + local name = owner and type(owner.name) == "string" and owner.name or "" + if note ~= "" then + items[#items + 1] = { + id = tostring(row.id or ""), + author = name, + content = note, + likes = tonumber(row.n_favorites) or 0, + images = {}, + time = created(row.create_time), + } + end + end + end + return { items = items, total = #items, max_idx = 1, more = false } +end + +---@param article table +---@param aid string +---@return BookChapter[]|nil +---@return string|nil +function Mapper.ebookChapters(article, aid) + local toc = type(article.toc) == "table" and article.toc or {} + local chapters = {} + for idx, item in ipairs(toc) do + if type(item) == "table" and item.paragraph_id ~= nil then + local pid = tonumber(item.paragraph_id) + local next_item = toc[idx + 1] + local next_pid = type(next_item) == "table" and tonumber(next_item.paragraph_id) or nil + chapters[#chapters + 1] = { + idx = idx, + uid = tostring(item.paragraph_id), + title = chapterTitle(item.title, idx), + content_url = tostring(aid), + end_pid = next_pid and tostring(next_pid) or nil, + slice = true, + vip = Mapper.blocksText(article, pid, next_pid) == "", + depth = (tonumber(item.level) or 0) + 1, + } + end + end + if not chapters[1] then + local text = Mapper.blocksText(article, nil, nil) + local title = type(article.posts) == "table" and type(article.posts[1]) == "table" and article.posts[1].title or nil + if text == "" then return nil, _("豆瓣阅读目录为空") end + chapters[1] = { + idx = 1, + uid = tostring(aid), + title = chapterTitle(title, 1), + content_url = tostring(aid), + vip = false, + } + end + chapters[1].toc_version = Mapper.TOC_VERSION + return chapters +end + +--- 首页脚本里的写请求令牌。没有它,登录后的 POST 会被拒。 +---@param html string|nil +---@return string|nil +function Mapper.readCsrf(html) + if type(html) ~= "string" then return nil end + return html:match("CSRF_TOKEN%s*=%s*'([^']+)'") + or html:match('CSRF_TOKEN%s*=%s*"([^"]+)"') +end + +--- `/j/bookshelf/` 只有编号。书架页 GraphQL 的 `libraryList.list[].worksId` 同形。 +---@param wire table|nil +---@return string[]|nil +---@return string|nil +function Mapper.shelfIds(wire) + if type(wire) ~= "table" or wire.errors then return nil, _("豆瓣阅读书架数据无法识别") end + local rows = wire.worksIds + if type(rows) ~= "table" then + local user = type(wire.data) == "table" and wire.data.user or nil + local shelf = type(user) == "table" and type(user.bookshelf) == "table" and user.bookshelf or nil + local library = type(shelf) == "table" and shelf.libraryList or nil + rows = type(library) == "table" and library.list or nil + end + if type(rows) ~= "table" or (next(rows) ~= nil and rows[1] == nil) then + return nil, _("豆瓣阅读书架数据无法识别") + end + local ids = {} + for _idx, item in ipairs(rows) do + local id = item + if type(item) == "table" then id = item.worksId or item.id or item.works_id end + if type(id) == "number" then id = tostring(id) end + if type(id) ~= "string" or id == "" then return nil, _("豆瓣阅读书架数据无法识别") end + ids[#ids + 1] = id + end + + return ids +end + +---@param wire table|nil +---@return (string|number)[]|nil +---@return string|nil +function Mapper.folderIds(wire) + local ids = type(wire) == "table" and wire.folderIds + if type(ids) ~= "table" or (next(ids) ~= nil and ids[1] == nil) then return nil, _("响应无效") end + for _idx, id in ipairs(ids) do + if (type(id) ~= "string" and type(id) ~= "number") or id == "" then return nil, _("响应无效") end + end + return ids +end + +--- 与微信相同:多组成员按官网分组顺序取第一个,响应顺序不决定分类。 +---@param wire table|nil +---@param ids (string|number)[] +---@return table|nil +---@return string|nil +function Mapper.shelfGroups(wire, ids) + if type(wire) ~= "table" or wire.errors then return nil, _("响应无效") end + local user = type(wire.data) == "table" and wire.data.user + local shelf = type(user) == "table" and user.bookshelf + local folders = type(shelf) == "table" and shelf.folders + local list = type(folders) == "table" and folders.list + if type(list) ~= "table" or (next(list) ~= nil and list[1] == nil) then return nil, _("响应无效") end + local by_id = {} + for _idx, folder in ipairs(list) do + if type(folder) ~= "table" or (type(folder.id) ~= "string" and type(folder.id) ~= "number") + or folder.id == "" or type(folder.name) ~= "string" or folder.name == "" + or type(folder.libraryList) ~= "table" or by_id[tostring(folder.id)] then + return nil, _("响应无效") + end + local members, err = Mapper.shelfIds({ worksIds = folder.libraryList.list }) + if not members then return nil, err end + by_id[tostring(folder.id)] = { name = folder.name, members = members } + end + local groups = {} + for _idx, id in ipairs(ids) do + local folder = by_id[tostring(id)] + if not folder then return nil, _("响应无效") end + for _member_idx, works_id in ipairs(folder.members) do + groups[works_id] = groups[works_id] or folder.name + end + end + return groups +end + +---@param ids string[] +---@return table +function Mapper.shelfWorksBody(ids) + return { + variables = { worksIds = ids }, + extensions = { persistedQuery = { version = 1, sha256Hash = Mapper.SHELF_WORKS_HASH } }, + } +end + +--- 编号查回来的作品。有声书不进书架。 +---@param wire table|nil +---@param groups table|nil +---@param ids string[]|nil +---@return Book[]|nil +---@return string|nil +function Mapper.shelfWorks(wire, groups, ids) + if type(wire) ~= "table" or wire.errors then return nil, _("豆瓣阅读书架数据无法识别") end + local data = type(wire) == "table" and wire.data or nil + local list = type(data) == "table" and data.worksList or nil + if type(list) ~= "table" or (next(list) ~= nil and list[1] == nil) then + return nil, _("豆瓣阅读书架数据无法识别") + end + local books, seen = {}, {} + for _idx, item in ipairs(list) do + if type(item) ~= "table" or item.id == nil then return nil, _("豆瓣阅读书架数据无法识别") end + seen[tostring(item.id)] = true + local row = worksBook(item) + if row then + local genre = row.category + if not genre and type(item.isOrigin) == "boolean" then + genre = item.isOrigin and _("原创") or _("出版") + end + row.category = CategorySetting.apply(SOURCE_ID, genre, groups and groups[row.stable_id]) + row.category_authoritative = true + books[#books + 1] = row + elseif item.isAudio ~= true and item.isBundle ~= true then + return nil, _("豆瓣阅读书架数据无法识别") + end + end + for _idx, id in ipairs(ids or {}) do + if not seen[id] then return nil, _("豆瓣阅读书架数据无法识别") end + end + if #books == 0 and #list > 0 then return nil, _("豆瓣阅读书架数据无法识别") end + return books +end + +---@param wire table|nil +---@return Book[]|nil +---@return string|nil +function Mapper.shelf(wire) + local rows = wire + if type(wire) == "table" and wire[1] == nil then + rows = wire.worksIds or wire.list or wire.works or wire.items + if rows == nil then + if wire.error or wire.message or next(wire) ~= nil then + return nil, _("豆瓣阅读书架数据无法识别") + end + rows = {} + end + end + if type(rows) ~= "table" then return nil, _("豆瓣阅读书架数据无法识别") end + local books = {} + for _idx, item in ipairs(rows) do + local row = worksBook(item) + if row then books[#books + 1] = row end + end + if #books == 0 and #rows > 0 then return nil, _("豆瓣阅读书架数据无法识别") end + return books +end + +---@param html string +---@return string|nil +function Mapper.csrf(html) + if type(html) ~= "string" then return nil end + return html:match('name="csrf%-token"%s+content="([^"]+)"') + or html:match('content="([^"]+)"%s+name="csrf%-token"') +end + +---@param html string +---@return { id: string, name: string }|nil +function Mapper.user(html) + if type(html) ~= "string" then return nil end + local raw = html:match("Ark%.user%s*=%s*(%b{})") + if not raw then return nil end + local ok, user = pcall(JSON.decode, raw) + if not ok or type(user) ~= "table" or user.isAnonymous == true + or (type(user.id) ~= "string" and type(user.id) ~= "number") or tostring(user.id) == "" then return nil end + local name = user.name or user.nickname or user.screenName or "" + return { id = tostring(user.id), name = type(name) == "string" and name or "" } +end + +---@param wire table|nil +---@param origin string +---@return { qr: string, code: string, expires_in: number }|nil +function Mapper.qr(wire, origin) + if type(wire) ~= "table" or type(wire.url) ~= "string" or wire.url == "" then return nil end + local code = wire.url:match("[?&]code=([^&]+)") + if not code or code == "" then return nil end + if wire.url:sub(1, 1) ~= "/" or wire.url:sub(1, 2) == "//" then return nil end + return { qr = origin .. wire.url, code = code, expires_in = tonumber(wire.expires_in) or 300 } +end + +---@param wire table|nil +---@return string|nil +function Mapper.qrStatus(wire) + if type(wire) ~= "table" or type(wire.confirmed) ~= "boolean" then return nil end + if wire.confirmed then return "ok" end + return "wait" +end + +--- 进度回包。`r` 为真或没有 progress 是云端无位置,不是请求失败。 +---@param wire table|nil +---@return { paragraph_id: string }|nil +---@return boolean empty +function Mapper.progress(wire) + if type(wire) ~= "table" then return nil, false end + local item = wire.progress + -- 网页把 r 当布尔用:0 是成功。Lua 里 0 为真,不能直接 if wire.r。 + local failed = wire.r ~= nil and wire.r ~= false and wire.r ~= 0 + if failed then return nil, false end + if item == nil or item == JSON.null then return nil, true end + if type(item) ~= "table" or item.paragraph_id == nil or tostring(item.paragraph_id) == "" then + return nil, false + end + return { paragraph_id = tostring(item.paragraph_id) }, false +end + +--- 章节正文里第一个能定位的段落。专栏进度记在这一章的 article 上。 +---@param article table|nil +---@return string|nil +function Mapper.firstParagraphId(article) + local posts = type(article) == "table" and article.posts or nil + if type(posts) ~= "table" then return nil end + for _pidx, post in ipairs(posts) do + local contents = type(post) == "table" and post.contents or nil + if type(contents) == "table" then + for _bidx, block in ipairs(contents) do + local kind = type(block) == "table" and block.type or nil + if block.id ~= nil and kind == "paragraph" and paragraphText(block.data) ~= "" then + return tostring(block.id) + end + + end + end + end + return nil +end + +--- 官网分段索引来自 posts[].contents[],不是月读章节号。 +---@param article table +---@param pid string +---@param end_pid string|nil +---@return table|nil +function Mapper.progressPosition(article, pid, end_pid) + local reached = false + for part_idx, post in ipairs(article.posts or {}) do + for paragraph_idx, block in ipairs(post.contents or {}) do + local id = block.id ~= nil and tostring(block.id) or nil + if id == pid then reached = true end + if reached and end_pid and id == end_pid then return nil end + if reached and id and block.type == "paragraph" and paragraphText(block.data) ~= "" then + return { + paragraph_id = id, + part_sequence = part_idx - 1, + part_paragraph_sequence = paragraph_idx - 1, + } + end + end + end + return nil +end + +---@param wire table +---@param begin_date string +---@param fetched_at number +---@return BookStatsPullResult|nil +---@return string|nil +function Mapper.readingStats(wire, begin_date, fetched_at) + if type(wire) ~= "table" or wire.errors then return nil, _("响应无效") end + local user = type(wire) == "table" and type(wire.data) == "table" and wire.data.user + local total = type(user) == "table" and user.readingTimeTotal + local history = type(user) == "table" and user.readingTimeHistory + local function seconds(value) + return type(value) == "number" and value >= 0 and value < math.huge and value or nil + end + if type(total) ~= "table" or not seconds(total.duration) or type(history) ~= "table" + or (next(history) ~= nil and history[1] == nil) then return nil, _("响应无效") end + local function midnight(date) + if type(date) ~= "string" then return nil end + local year, month, day = date:match("^(%d%d%d%d)%-(%d%d)%-(%d%d)$") + if not year then return nil end + local time = os.time({ year = tonumber(year), month = tonumber(month), day = tonumber(day), hour = 0 }) + return time and os.date("%Y-%m-%d", time) == date and time or nil + end + local from = midnight(begin_date) + if not from then return nil, _("响应无效") end + local rows, seen = {}, {} + local function row(id, kind, start_time, duration) + if duration > 0 then + rows[#rows + 1] = { + source_id = SOURCE_ID, stable_id = id, record_type = kind, + start_time = start_time, duration = duration, last_time = fetched_at, + page = 0, total_pages = 0, event_count = 0, + } + end + end + row("__douban:total", "total", fetched_at, total.duration) + for _idx, item in ipairs(history) do + local date = type(item) == "table" and item.date + local time = midnight(date) + local reading = type(item) == "table" and item.readingTime + local duration = type(reading) == "table" and seconds(reading.duration) + if not time or not duration or time < from or time > fetched_at or seen[date] then + return nil, _("响应无效") + end + seen[date] = true + row("__douban:day:" .. date, "day", time, duration) + end + return { + rows = rows, + replace = { mode = "ranges", ranges = { + { stable_prefix = "__douban:day:", from_ts = from, to_ts = fetched_at }, + { stable_prefix = "__douban:total", from_ts = 0, to_ts = fetched_at }, + } }, + } +end + +---@param wire table +---@param offset integer +---@param chapter_id string|nil +---@return table|nil, string|nil +function Mapper.communityPage(wire, offset, chapter_id) + if type(wire) == "table" and type(wire.errors) == "table" then + for _idx, err in ipairs(wire.errors) do + if type(err) == "table" and err.message == "AnonymousError" then + return nil, _("请先登录豆瓣阅读") + end + end + end + local works = type(wire) == "table" and type(wire.data) == "table" and wire.data.works + local comments = type(works) == "table" and works.comments + local rows = type(comments) == "table" and comments.list + local total = type(comments) == "table" and tonumber(comments.total) + if type(wire) ~= "table" or wire.errors ~= nil and (type(wire.errors) ~= "table" or #wire.errors > 0) + or type(rows) ~= "table" + or not total or total < 0 or #rows == 0 and offset < total then + return nil, _("响应无效") + end + local items = {} + for _idx, row in ipairs(rows) do + local scope = type(row) == "table" and row.works + local stamp = type(row) == "table" and type(row.createTime) == "string" + and row.createTime:match("^%d%d%d%d%-%d%d%-%d%d") + if type(row) ~= "table" or (type(row.id) ~= "string" and type(row.id) ~= "number") + or row.id == "" or type(row.content) ~= "string" + or not stamp or type(scope) ~= "table" + or row.commentType ~= (chapter_id and "Discussion" or "Review") + or chapter_id and (scope.isChapter ~= true or tostring(scope.id) ~= chapter_id) + or not chapter_id and scope.isChapter ~= false then + return nil, _("响应无效") + end + local content = Text.stripHtml(row.content) + if type(row.title) == "string" and row.title ~= "" then + content = row.title .. "\n" .. content + end + local user = type(row.user) == "table" and row.user or {} + items[#items + 1] = { + id = tostring(row.id), author = type(user.name) == "string" and user.name or "", + text = content, content = content, time = stamp, + likes = tonumber(row.upvoteCount), grade = tonumber(row.rating), + replies = 0, + } + end + local next_idx = offset + #rows + return { items = items, total = total, max_idx = next_idx, more = next_idx < total, + pages = math.max(1, math.ceil(total / 20)), + title = not chapter_id and (#items < total and _("书评预览") or _("书评")) or nil } +end + +return Mapper diff --git a/moonsource-douban.koplugin/moonsource_douban/phone_login.lua b/moonsource-douban.koplugin/moonsource_douban/phone_login.lua new file mode 100644 index 0000000..47a00bc --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/phone_login.lua @@ -0,0 +1,131 @@ +--[[-- +豆瓣阅读短信登录。手机号、验证码和候选会话只属于当前输入窗口。 + +@module moonsource_douban.phone_login +--]] + +local Client = require("moonsource_douban.client") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_douban") + +local PhoneLogin = {} +PhoneLogin.__index = PhoneLogin + +function PhoneLogin:new(on_user) + return setmetatable({ on_user = on_user, session = Client.newLogin(), generation = 0 }, PhoneLogin) +end + +function PhoneLogin:cancel() + self.generation = self.generation + 1 + if self.job then self.job.cancel() end + self.job, self.busy = nil, false + self.session:cancel() +end + +function PhoneLogin:_request(method, callback, ...) + local args = { ... } + local count, pending, gen = select("#", ...) + 1, true, self.generation + self.busy = true + args[count] = function(...) + pending = false + if gen ~= self.generation then return end + self.job, self.busy = nil, false + callback(...) + end + local job = self.session[method](self.session, unpack(args, 1, count)) + if pending then self.job = job end +end + +function PhoneLogin:send(country, number) + if not require("ui/network/manager"):isConnected() then + require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show() + return + end + if self.busy then + require("ui.themes.widgets.toast"):new{ text = _("正在处理,请稍候"), timeout = 2 }:show() + return + end + country, number = Text.trim(country), Text.trim(number) + if not country:match("^%+%d+$") or not number:match("^%d+$") then + require("ui.themes.widgets.toast"):new{ text = _("请输入有效的手机号和国际区号"), timeout = 3 }:show() + return + end + local phone = country .. number + if self.retry_at and os.time() < self.retry_at then + require("ui.themes.widgets.toast"):new{ text = _("请稍后再获取验证码"), timeout = 3 }:show() + return + end + if not self.session.authorize then + require("ui.themes.widgets.toast"):new{ text = _("正在获取验证码…"), timeout = 2 }:show() + self:_request("beginAsync", function(authorize, err) + if not authorize then + require("ui.themes.widgets.toast"):new{ text = err or _("登录失败"), timeout = 3 }:show() + return + end + self:send(country, number) + end) + return + end + self:_request("sendPhoneCodeAsync", function(wait, err) + if wait == nil then + require("ui.themes.widgets.toast"):new{ text = err or _("请求失败"), timeout = 3 }:show() + return + end + self.phone, self.retry_at = phone, os.time() + wait + require("ui.themes.widgets.toast"):new{ text = _("验证码已发送"), timeout = 3 }:show() + end, phone) +end + +function PhoneLogin:verify(country, number, code) + if self.busy then + require("ui.themes.widgets.toast"):new{ text = _("正在处理,请稍候"), timeout = 2 }:show() + return + end + if not require("ui/network/manager"):isConnected() then + require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show() + return + end + local phone = Text.trim(country) .. Text.trim(number) + code = Text.trim(code) + if phone ~= self.phone or not code:match("^%d+$") then + require("ui.themes.widgets.toast"):new{ text = _("请先获取该手机号的验证码,再填写验证码登录"), timeout = 3 }:show() + return + end + require("ui.themes.widgets.toast"):new{ text = _("正在登录…"), timeout = 2 }:show() + self:_request("verifyPhoneAsync", function(user, err) + if not user then + require("ui.themes.widgets.toast"):new{ text = err or _("登录失败"), timeout = 4 }:show() + return + end + self:cancel() + self.dialog:close() + self.on_user(user) + end, phone, code) +end + +function PhoneLogin:start() + self.dialog = require("ui.themes.widgets.input"):new{ + title = _("豆瓣阅读手机号登录"), + fields = { + { label = _("国际区号"), text = "+86", hint = "+86" }, + { label = _("手机号"), input_type = "number" }, + { label = _("验证码"), input_type = "number" }, + }, + keep_open = true, + ok_text = _("登录"), + actions = { { text = _("获取验证码"), callback = function(country, number) self:send(country, number) end } }, + callback = function(country, number, code) + require("ui.themes.widgets.confirm"):new{ + text = _("登录前请阅读并同意豆瓣阅读使用协议、隐私政策和社区指导原则") + .. "\nhttps://read.douban.com/about/agreement\nhttps://read.douban.com/privacy" + .. "\nhttps://read.douban.com/faq?type=guideline", + ok_text = _("同意并登录"), + ok_callback = function() self:verify(country, number, code) end, + }:show() + end, + cancel_callback = function() self:cancel() end, + } + self.dialog:show() +end + +return PhoneLogin diff --git a/moonsource-douban.koplugin/moonsource_douban/qrlogin.lua b/moonsource-douban.koplugin/moonsource_douban/qrlogin.lua new file mode 100644 index 0000000..c8f95d5 --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/qrlogin.lua @@ -0,0 +1,137 @@ +--[[-- +豆瓣阅读 App 扫码登录。 + +二维码内容是 https://accounts.arkread.com/oidc/qrcode/confirm?code= 。 +每 1.5 秒轮询状态,确认后重新打开授权页,跟跳转直到读到登录用户。 + +@module moonsource_douban.qrlogin +--]] + +local Client = require("moonsource_douban.client") +local _ = require("l10n").get("moonsource_douban") + +local QRLogin = {} +QRLogin.__index = QRLogin + +local POLL_INTERVAL = 1.5 +local POLL_LIMIT = 200 + +---@param on_user fun(user: { id: string, name: string }) +---@return table +function QRLogin:new(on_user) + return setmetatable({ on_user = on_user, generation = 0 }, QRLogin) +end + +function QRLogin:cancel() + self.generation = self.generation + 1 + if self.job and self.job.cancel then self.job.cancel() end + self.job = nil + if self.session then self.session:cancel() end +end + +function QRLogin:_request(method, callback, ...) + local args = { ... } + local count, pending, gen = select("#", ...) + 1, true, self.generation + args[count] = function(...) + pending = false + if gen ~= self.generation then return end + self.job = nil + callback(...) + end + local job = self.session[method](self.session, unpack(args, 1, count)) + if pending then self.job = job end +end + +---@param text string +function QRLogin:toast(text) + require("ui.themes.widgets.toast"):new{ text = text, timeout = 3 }:show() +end + +---@param text string +function QRLogin:_retry(text) + self:cancel() + if self.dialog then + local dialog = self.dialog + self.dialog = nil + dialog:close() + end + require("ui.themes.widgets.confirm"):new{ + text = text, + ok_text = _("重新获取"), + ok_callback = function() self:start() end, + }:show() +end + +---@param gen integer +---@param code string +---@param authorize string +---@param polls integer +function QRLogin:_poll(gen, code, authorize, polls) + if gen ~= self.generation then return end + if polls > POLL_LIMIT or os.time() >= self.deadline then + self:_retry(_("二维码已过期")) + return + end + self:_request("qrStatusAsync", function(kind, err) + if gen ~= self.generation then return end + self.job = nil + if kind == "ok" then + self:_request("finishQrAsync", function(user, reason) + if gen ~= self.generation then return end + self.job = nil + if not user then + self:_retry(reason or _("登录失败")) + return + end + self:cancel() + if self.dialog then + local dialog = self.dialog + self.dialog = nil + dialog:close() + end + self.on_user(user) + end, authorize) + return + end + if kind ~= "wait" then + self:_retry(err or _("登录失败")) + return + end + require("ui/uimanager"):scheduleIn(POLL_INTERVAL, function() + if gen == self.generation then self:_poll(gen, code, authorize, polls + 1) end + end) + end, code) +end + +function QRLogin:start() + self:cancel() + self.session = Client.newLogin() + local gen = self.generation + self:_request("beginQrAsync", function(ticket, err) + if gen ~= self.generation then return end + self.job = nil + if not ticket then + self:toast(err or _("获取二维码失败")) + return + end + local dialog + dialog = require("ui.themes.widgets.qr"):new{ + title = _("豆瓣阅读扫码登录"), + text = ticket.qr, + caption = _("用豆瓣阅读 App 扫一扫"), + close_callback = function() + if self.dialog == dialog then + self.dialog = nil + self:cancel() + self:toast(_("已取消登录")) + end + end, + } + self.dialog = dialog + self.deadline = os.time() + ticket.expires_in + dialog:show() + self:_poll(gen, ticket.code, ticket.authorize, 1) + end) +end + +return QRLogin diff --git a/moonsource-douban.koplugin/moonsource_douban/reviews.lua b/moonsource-douban.koplugin/moonsource_douban/reviews.lua new file mode 100644 index 0000000..7c0945b --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/reviews.lua @@ -0,0 +1,62 @@ +--[[-- +豆瓣阅读段评。 + +他人批注走 POST `/j/article_v2/

/annotations_by_paragraphs`。 +有 `note` 的才是段评,纯划线丢掉。段落序号按本章非空段,和章节 HTML 的 `

` 一致。 + +@module moonsource_douban.reviews +--]] + +local Client = require("moonsource_douban.client") +local Mapper = require("moonsource_douban.mapper") + +local Reviews = {} + +---@param chapter BookChapter +---@param cb fun(rows: table|nil, pids: string[]|nil, err: string|nil) +---@return { cancel: fun() } +local function load(chapter, cb) + local handle = {} + local start_pid = chapter.slice and tonumber(chapter.uid) or nil + local end_pid = chapter.slice and tonumber(chapter.end_pid) or nil + local pending = true + local first = Client.articleAsync(chapter.content_url, function(article, err) + pending = false + if handle.cancelled then return end + if not article then cb(nil, nil, err); return end + local pids = Mapper.paragraphIds(article, start_pid, end_pid) + handle.job = Client.annotationsAsync(chapter.content_url, pids, function(rows, reason) + if handle.cancelled then return end + if not rows then cb(nil, nil, reason); return end + cb(rows, pids) + end) + end) + if pending then handle.job = first end + return { cancel = function() + handle.cancelled = true + if handle.job and handle.job.cancel then handle.job.cancel() end + end } +end + +---@param chapter BookChapter +---@param cb fun(hotspots: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Reviews.hotspotsAsync(chapter, cb) + return load(chapter, function(rows, pids, err) + if not rows then cb(nil, err); return end + cb(Mapper.reviewHotspots(rows, pids)) + end) +end + +---@param chapter BookChapter +---@param range string|number +---@param cb fun(page: table|nil, err: string|nil) +---@return { cancel: fun() } +function Reviews.pageAsync(chapter, range, cb) + return load(chapter, function(rows, pids, err) + if not rows then cb(nil, err); return end + cb(Mapper.reviewPage(rows, pids, range)) + end) +end + +return Reviews diff --git a/moonsource-douban.koplugin/moonsource_douban/setting.lua b/moonsource-douban.koplugin/moonsource_douban/setting.lua new file mode 100644 index 0000000..f7eef8d --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/setting.lua @@ -0,0 +1,122 @@ +--[[-- +豆瓣阅读账号:App 扫码或电脑浏览器 Cookie。登录态是 read.douban.com 的 Cookie 和用户编号。 + +@module moonsource_douban.setting +--]] + +local _ = require("l10n").get("moonsource_douban") +local CookieLogin = require("source.cookie_login") + +local SOURCE_ID = "ext.douban" +local Setting = {} +local LOGIN_URL = "https://read.douban.com/oidc/login" + +---@return boolean +local function loggedIn() + return require("moonsource_douban.client").loggedIn() +end + +---@param user { id: string, name: string } +local function save(user) + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() + local name = user.name ~= "" and user.name or _("已登录") + require("ui.themes.widgets.toast"):new{ text = name, timeout = 2 }:show() +end + +local SPEC = { + id = SOURCE_ID, + title = _("豆瓣阅读账号"), + cookie_title = _("豆瓣阅读登录 Cookie"), + cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"), + logout_text = _("确定退出豆瓣阅读账号?"), + loggedIn = loggedIn, + checkAsync = function(cookie, cb) + local login = require("moonsource_douban.client").newLogin(cookie) + return login:checkCookieAsync(function(ok, err, user) + cb(ok, err, user and { user = user, login = login }) + end) + end, + commit = function(_cookie, candidate, cb) + local ok, err = candidate.login:commit(candidate.user) + if ok then + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() + end + cb(ok == true, err) + end, +} + +Setting.browser = { + domain = "read.douban.com", + scope = "cookie", + login = LOGIN_URL, + check = "https://read.douban.com/", + icon = "https://static.arkread.com/ark/pics/favicon/v6/favicon.10c09c23.ico", + isAuthorized = function() return CookieLogin.authorized(SPEC) end, + apply = function(payload, cb) + local cookies = {} + for _idx, cookie in ipairs(type(payload.cookies) == "table" and payload.cookies or {}) do + local domain = type(cookie.domain) == "string" and cookie.domain:gsub("^%.", ""):lower() + if domain == "douban.com" or domain == "read.douban.com" then cookies[#cookies + 1] = cookie end + end + return CookieLogin.save(SPEC, CookieLogin.fromPayload({ cookies = cookies }, "douban.com"), cb) + end, +} + +---@return string, boolean +function Setting.rowStatus() + local on = loggedIn() + return on and _("已登录") or _("未登录 · 点此扫码"), on +end + +function Setting.open() + if not require("ui/network/manager"):isConnected() then + require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show() + return + end + require("moonsource_douban.qrlogin"):new(save):start() +end + +---@param plugin table|nil +---@return table[] +function Setting.rows(plugin) + local Row = require("ui.themes.widgets.row") + local rows = { + function(iw) + local status, status_on = Setting.rowStatus() + return Row.widget({ + width = iw, chevron = true, kind = "nav", icon = "account_circle", + title = SPEC.title, + subtitle = _("打开豆瓣阅读 App,扫屏幕上的二维码"), + status = status, status_on = status_on, + callback = function() Setting.open() end, + }) + end, + } + rows[#rows + 1] = function(iw) + return Row.widget({ + width = iw, chevron = true, kind = "nav", icon = "sms", + title = _("手机号验证码登录"), + callback = function() require("moonsource_douban.phone_login"):new(save):start() end, + }) + end + rows[#rows + 1] = CookieLogin.browserRow() + rows[#rows + 1] = CookieLogin.pasteRow(SPEC) + rows[#rows + 1] = require("source.category_setting").row(SOURCE_ID, plugin) + rows[#rows + 1] = require("source.review_setting").row(SOURCE_ID, plugin) + if loggedIn() then + rows[#rows + 1] = require("source.logout").row(SOURCE_ID, _("确定退出豆瓣阅读账号?"), function() + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + cfg.cookie, cfg.user_id, cfg.name, cfg.logged_in = nil, nil, nil, nil + settings.saveSource(SOURCE_ID) + require("moonsource_douban.client").reset() + end) + end + return rows +end + +Setting.login = Setting.open + +return Setting diff --git a/moonsource-douban.koplugin/moonsource_douban/source.lua b/moonsource-douban.koplugin/moonsource_douban/source.lua new file mode 100644 index 0000000..625a3fa --- /dev/null +++ b/moonsource-douban.koplugin/moonsource_douban/source.lua @@ -0,0 +1,456 @@ +--[[-- +豆瓣阅读数据源。 + +搜索和免费章节不需要登录。书架在 App 扫码后同步。 +进度按作品拉取;专栏再按章节 article 记一条,网站打开该章才能续上。 +阅读时长走 /j/reading_time。未购买的章节给一页提示,不当成缓存。 + +@module moonsource_douban +--]] + +local Client = require("moonsource_douban.client") +local Browse = require("source.browse") +local Mapper = require("moonsource_douban.mapper") +local Shelf = require("source.shelf") +local SourceBase = require("source.base") +local Text = require("utils.text") +local Toc = require("source.toc") +local _ = require("l10n").get("moonsource_douban") + +local Douban = {} + +---@return BookSourceMeta +function Douban.meta() + return require("moonsource_douban.loadmeta")() +end + +---@class DoubanSource : SourceBase +local Source = setmetatable({ shelf_add = true }, { __index = SourceBase }) +Source.__index = Source + +---@return DoubanSource +function Douban.new() + local meta = Douban.meta() + return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source) +end + +---@return boolean +function Source:configured() + return Client.loggedIn() +end + +function Source:capabilities() + local caps = SourceBase.capabilities(self) + caps.stats_pull = true + return caps +end + +local Remote = {} + +function Remote:shelfSyncAsync(cb) return Client.shelfAsync(cb) end + +---@param stable_id string +---@param cb fun(ok: boolean|nil, err: string|nil) +function Remote:addToShelfAsync(stable_id, cb) + return Client.addAsync(stable_id, cb) +end + +---@param stable_id string +---@param cb fun(ok: boolean|nil, err: string|nil) +function Remote:removeFromShelfAsync(stable_id, cb) + return Client.removeAsync(stable_id, cb) +end + +function Source:syncBooksAsync(opts, cb) + if not self:configured() then return SourceBase.skipped(cb, "douban not logged in") end + return Shelf.syncAsync(self.id, Remote, function(books) return books end, opts, cb) +end + +---@param keyword string +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +function Source:searchAsync(keyword, cb) + return Client.searchAsync(keyword, function(books, err) + if not books then cb(nil, err or _("请求失败")); return end + cb({ data = books }) + end) +end + +---@param opts { node?: string, limit?: integer }|nil +---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil) +function Source:browseAsync(opts, cb) + local limit = opts and opts.limit or 60 + local channel, category, sort, pay, state = (opts and opts.node or ""):match( + "^(%a+):(%d+):([%a_]+):(%a+):(%a+)$") + if channel ~= "publish" then channel = "original" end + local root = channel == "original" and "0" or "1" + category, sort, pay, state = category or root, sort or "hot", pay or "all", state or "all" + local sorts = { + { id = "hot", title = _("热门") }, { id = "new", title = _("最新") }, + { id = "sales", title = _("销量") }, { id = "rating", title = _("好评") }, + } + if channel == "publish" then + state = "all" + sorts[#sorts + 1] = { id = "price_asc", title = _("价格最低") } + sorts[#sorts + 1] = { id = "book_rating", title = _("豆瓣高分") } + end + local valid_sort = false + for _idx, row in ipairs(sorts) do if row.id == sort then valid_sort = true end end + if not valid_sort then sort = "hot" end + if pay ~= "free" and (pay ~= "paid" or channel ~= "publish") then pay = "all" end + if state ~= "serial" and state ~= "complete" then state = "all" end + local handle, pending = {}, true + local initial = Client.categoriesAsync(function(categories, err) + pending = false + if handle.cancelled then return end + if not categories then cb(nil, err); return end + local valid_category = category == root + for _idx, row in ipairs(categories[channel]) do if row.id == category then valid_category = true end end + if not valid_category then category = root end + local values = { channel, category, sort, pay, state } + local function chips(title, rows, position) + local list = {} + for _idx, row in ipairs(rows) do + local node = { unpack(values) } + node[position] = row.id + if position == 1 then node[2], node[3], node[4], node[5] = row.id == "publish" and "1" or "0", "hot", "all", "all" end + list[#list + 1] = { id = table.concat(node, ":"), title = row.title } + end + local current = { unpack(values) } + if position == 1 then current[2], current[3], current[4], current[5] = root, "hot", "all", "all" end + local group = Browse.group(list, table.concat(current, ":")) + group.title = title + return group + end + local cats = { { id = root, title = _("全部") } } + for _idx, row in ipairs(categories[channel]) do cats[#cats + 1] = row end + local prices = { { id = "all", title = _("全部") }, { id = "free", title = _("免费") } } + if channel == "publish" then prices[#prices + 1] = { id = "paid", title = _("付费") } end + local groups = { + chips(nil, { { id = "original", title = _("原创") }, { id = "publish", title = _("出版") } }, 1), + chips(_("分类"), cats, 2), + chips(_("排序"), sorts, 3), + chips(_("价格"), prices, 4), + } + if channel == "original" then + groups[#groups + 1] = chips(_("状态"), { + { id = "all", title = _("全部") }, { id = "serial", title = _("连载中") }, + { id = "complete", title = _("已完结") }, + }, 5) + end + handle.job = Browse.pages(function(page, done) + return Client.catalogAsync({ category = category, sort = sort, pay = pay, state = state }, page, done) + end, limit, groups, function(result, reason) + if result then + for idx = #result.data, limit + 1, -1 do result.data[idx] = nil end + end + if not handle.cancelled then cb(result, reason) end + end) + end) + if pending then handle.job = initial end + function handle.cancel() + handle.cancelled = true + if handle.job then handle.job.cancel() end + end + return handle +end + +function Source:getDetailAsync(identity, cb) + return Client.detailAsync(identity.stable_id, function(book, err) + if book then cb(require("book.store").rememberDetail(book)); return end + local row = identity.book or require("book.books_db").get(self.id, identity.stable_id) + if row then cb(row); return end + cb(nil, err or _("请求失败")) + end) +end + +---@param self DoubanSource +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +local function fetchTocAsync(self, identity, cb) + return Client.tocAsync(identity.stable_id, function(toc, err) + if not toc then cb(nil, err); return end + if #toc == 0 then cb(nil, _("豆瓣阅读目录为空")); return end + if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end + cb(toc) + end) +end + +function Source:loadTocAsync(identity, cb, force) + if not force then + local cached = Toc.read(self.id, identity.stable_id) + if cached and #cached > 0 and (cached[1].toc_version == Mapper.TOC_VERSION + or not require("ui/network/manager"):isConnected()) then + return SourceBase.defer(cb, cached) + end + end + return fetchTocAsync(self, identity, cb) +end + +Source.refreshTocAsync = fetchTocAsync + +---@param self DoubanSource +---@param open boolean +---@return ChapterFetchContent +local function fetcher(self, open) + return function(_identity, chapter, done) + if chapter.vip then + if not open then done(nil, _("本章未购买")); return end + local notice = string.format(_("这是 VIP 章节,你还没有购买。\n请先在%s购买本章,再回来阅读。"), self.name) + done({ title = chapter.title, html = Text.chapterHtml(chapter.title, notice), temporary = true }) + return + end + local start_pid = chapter.slice and tonumber(chapter.uid) or nil + local end_pid = chapter.slice and tonumber(chapter.end_pid) or nil + return Client.textAsync(chapter.content_url, start_pid, end_pid, function(text, err) + if text then + local html = Text.chapterHtml(chapter.title, text) + if not chapter.slice and self:paragraphReviewsEnabled() then + html = require("book.review_locate").prepareChapterEnd(html) + end + done({ title = chapter.title, html = html }) + return + end + done(nil, err) + end) + end +end + +local function reuseChapterEnd(self, identity) + if not self:paragraphReviewsEnabled() then return nil end + return function(path) + local toc = Toc.read(self.id, identity.stable_id) + if toc and toc[1] and not toc[1].slice then + return require("book.review_locate").reuseChapterEnd(path) + end + return true + end +end + +function Source:openBookAsync(identity, opts, cb) + local Chapter = require("source.chapter") + local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi + return open(self, identity, identity.book, opts, { + loadToc = function(ref, done) return self:loadTocAsync(ref, done) end, + fetchContent = fetcher(self, true), + reuse = reuseChapterEnd(self, identity), + }, cb) +end + +function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb) + local Chapter = require("source.chapter") + return Chapter.prefetchAsync(identity, identity.book, toc, from_idx, count, { + fetchContent = fetcher(self, false), + reuse = reuseChapterEnd(self, identity), + }, cb) +end + +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + local Chapter = require("source.chapter") + return Chapter.cacheAllAsync(self, identity, fetcher(self, false), on_progress, cb, nil, range, + reuseChapterEnd(self, identity)) +end + +---@param toc BookChapter[] +---@param paragraph_id string +---@return integer|nil +local function chapterAt(toc, paragraph_id) + local pid = tonumber(paragraph_id) + for idx, chapter in ipairs(toc) do + if chapter.uid == paragraph_id then return idx end + if chapter.slice and pid then + local start_pid = tonumber(chapter.uid) + local end_pid = tonumber(chapter.end_pid) + if start_pid and pid >= start_pid and (not end_pid or pid < end_pid) then return idx end + end + end + return nil +end + +function Source:getProgressAsync(identity, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录豆瓣阅读")) end + local cancelled, progress_job, toc_job = false, nil, nil + progress_job = Client.progressAsync(identity.stable_id, function(mark, err) + if cancelled then return end + if err then cb(nil, err); return end + if not mark then cb(nil, nil, { empty = true }); return end + toc_job = self:loadTocAsync(identity, function(toc, reason) + if cancelled then return end + if not toc or #toc == 0 then cb(nil, reason or _("豆瓣阅读目录为空")); return end + local idx = chapterAt(toc, mark.paragraph_id) + if not idx then cb(nil, nil, { empty = true }); return end + cb({ + chapter_idx = idx, + chapter_title = toc[idx].title, + fraction = (idx - 1) / #toc, + extra = { chapter_uid = toc[idx].uid, chapter_idx = idx }, + }) + end) + end) + return { cancel = function() + cancelled = true + if progress_job then progress_job.cancel() end + if toc_job then toc_job.cancel() end + end } +end + +function Source:putProgressAsync(identity, pos, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录豆瓣阅读")) end + local cancelled = false + local toc_job, works_job, article_job + toc_job = self:loadTocAsync(identity, function(toc, err) + if cancelled then return end + if not toc then cb(nil, err); return end + local idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx) + local chapter = idx and toc[idx] + if not chapter then cb(nil, _("缺少豆瓣阅读章节位置")); return end + local function posted(ok, perr) + if cancelled then return end + cb(ok and true or nil, perr) + end + article_job = Client.articleAsync(chapter.content_url, function(article, article_err) + if cancelled then return end + if not article then cb(nil, article_err); return end + local pid = chapter.slice and chapter.uid or Mapper.firstParagraphId(article) + local position = pid and Mapper.progressPosition(article, pid, chapter.end_pid) + if not position then cb(nil, _("缺少豆瓣阅读章节位置")); return end + local works_id = chapter.slice and identity.stable_id or chapter.content_url + works_job = Client.putProgressAsync(works_id, position.paragraph_id, idx, #toc, chapter.slice == true, posted, position) + end) + end) + return { cancel = function() + cancelled = true + for _idx, job in pairs({ toc_job, works_job, article_job }) do + job.cancel() + end + end } +end + +---@param seconds integer +---@return string +local function iso(seconds) + return os.date("!%Y-%m-%dT%H:%M:%S", seconds) .. ".000Z" +end + +function Source:pushStatsAsync(rows, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录豆瓣阅读")) end + local sessions, ids = {}, {} + for _idx, row in ipairs(rows or {}) do + local start_time = tonumber(row.start_time) + local duration = tonumber(row.duration) + if row.id and start_time and duration and duration > 0 and type(row.stable_id) == "string" and row.stable_id ~= "" then + sessions[#sessions + 1] = { + worksId = tonumber(row.stable_id) or row.stable_id, + beginTime = iso(start_time), + endTime = iso(start_time + duration), + } + ids[#ids + 1] = row.id + elseif row.id then + ids[#ids + 1] = row.id + end + end + if #sessions == 0 then return SourceBase.defer(cb, { synced_ids = ids }) end + return Client.pushReadingAsync(sessions, function(ok, err) + if not ok then cb(nil, err); return end + cb({ synced_ids = ids }) + end) +end + +function Source:pullStatsAsync(cb) + local fetched_at = os.time() + local date = os.date("*t", fetched_at) + date.day, date.hour, date.min, date.sec = date.day - 29, 0, 0, 0 + date.isdst = nil + local begin_date = os.date("%Y-%m-%d", os.time(date)) + return Client.readingStatsAsync(begin_date, function(wire, err) + if not wire then cb(nil, err); return end + cb(Mapper.readingStats(wire, begin_date, fetched_at)) + end) +end + +function Source:paragraphReviewsEnabled() + return require("source.review_setting").enabled(self.id) +end + +---@param identity BookIdentity +---@param cb fun(chapter: BookChapter|nil, err: string|nil) +---@return { cancel: fun() } +local function chapterOf(self, identity, cb) + local cancelled, job = false, nil + job = self:loadTocAsync(identity, function(toc, err) + if cancelled then return end + local chapter = toc and toc[tonumber(identity.chapter_idx)] + if not chapter or type(chapter.content_url) ~= "string" or chapter.content_url == "" then + cb(nil, err or _("豆瓣阅读目录为空")) + return + end + cb(chapter) + end) + return { cancel = function() + cancelled = true + if job and job.cancel then job.cancel() end + end } +end + +function Source:paragraphHotspotsAsync(identity, cb) + local cancelled, chapter_job, review_job = false, nil, nil + chapter_job = chapterOf(self, identity, function(chapter, err) + if cancelled then return end + if not chapter then cb(nil, err); return end + review_job = require("moonsource_douban.reviews").hotspotsAsync(chapter, function(rows, reason) + if not cancelled then cb(rows, reason) end + end) + end) + return { cancel = function() + cancelled = true + if chapter_job then chapter_job.cancel() end + if review_job then review_job.cancel() end + end } +end + +function Source:locateHotspots(hotspots, html) + local ReviewLocate = require("book.review_locate") + return ReviewLocate.locate(ReviewLocate.paragraphs(html), hotspots, html) +end + +function Source:paragraphReviewPageAsync(identity, range, max_idx, cb) + if range == "chapter" then + return require("book.review_cache").pageAsync(identity, range, max_idx, function(done) + return require("source.with_chapter_uid").run(self, identity, _("豆瓣阅读目录为空"), + function(uid, finish) + return Client.communityAsync(identity.stable_id, uid, max_idx, finish) + end, done) + end, cb) + end + local cancelled, chapter_job, review_job = false, nil, nil + chapter_job = chapterOf(self, identity, function(chapter, err) + if cancelled then return end + if not chapter then cb(nil, err); return end + review_job = require("moonsource_douban.reviews").pageAsync(chapter, range, function(page, reason) + if not cancelled then cb(page, reason) end + end) + end) + return { cancel = function() + cancelled = true + if chapter_job then chapter_job.cancel() end + if review_job then review_job.cancel() end + end } +end + +function Source:bookReviewsAsync(identity, cb) + local ref = { source_id = self.id, stable_id = identity.stable_id } + return require("book.review_cache").pageAsync(ref, "book", 0, function(done) + return Client.communityAsync(identity.stable_id, nil, 0, done) + end, cb) +end + +function Source:chapterReviewHotspotsAsync(identity, cb) + return self:paragraphReviewPageAsync(identity, "chapter", 0, function(page, err) + if not page then cb(nil, err); return end + if page.unsupported then cb({}); return end + cb({ { range = "chapter", text = identity.book and identity.book.title or "", + total = page.total, badge = tostring(page.total), heading = _("章节评论"), + anchor = require("book.review_locate").CHAPTER_ANCHOR } }) + end) +end + +return Douban diff --git a/tests/douban/browse_spec.lua b/tests/douban/browse_spec.lua new file mode 100644 index 0000000..80f5e43 --- /dev/null +++ b/tests/douban/browse_spec.lua @@ -0,0 +1,93 @@ +--[[-- +豆瓣分类书城:动态分类、协议筛选、跨页聚合和取消。 + +@module tests.moonsource_douban.browse_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Json = require("support.json_stub") +package.preload["json"] = function() return Json end +local Mapper = require("moonsource_douban.mapper") +local tree = Json.encode({ + { id = 0, children = { { id = 505, name = "科幻小说", children = {} } } }, + { id = 1, children = { { id = 100, name = "小说", children = { + { id = 116, name = "科幻", children = {} }, + } } } }, +}) +local cats = Mapper.categories("Ark.kindTree = " .. tree .. ";") +Assert.eq(cats.original[1].id, "505") +Assert.eq(cats.publish[2].id, "116") +Assert.is_nil(Mapper.categories("登录页面")) +Assert.is_nil(Mapper.categories("Ark.kindTree = [false]")) + +local body = Mapper.catalogBody({ category = "505", sort = "new", pay = "free", state = "complete" }, 2) +Assert.eq(body.kind, 505) +Assert.eq(body.page, 2) +Assert.eq(body.minPrice, 0) +Assert.eq(body.maxPrice, 0) +Assert.eq(body.isFinished, true) +Assert.eq(body.variables.includePurchase, false) + +local requests, delayed, fail_page = {}, false, nil +package.preload["utils.settings"] = function() return { getSource = function() return { cookie = "private=1" } end } end +package.preload["http.request"] = function() + return { + headerAll = function() return {} end, + request = function(opts, cb) + local record = { opts = opts } + requests[#requests + 1] = record + local wire + if opts.method == "GET" then + wire = "Ark.kindTree = " .. tree + else + local params = Json.decode(opts.body) + record.params = params + if params.page ~= fail_page then + local list = {} + for idx = 1, 20 do list[idx] = { id = (params.page - 1) * 20 + idx, title = "测试书" } end + wire = Json.encode({ list = list, total = 100 }) + end + end + record.reply = function() + if wire then cb({ code = 200, body = wire }, nil) else cb(nil, "network failed") end + end + if not delayed or opts.method == "GET" then record.reply() end + return { cancel = function() record.cancelled = true end } + end, + } +end +local source = require("moonsource_douban.source").new() +local result +source:browseAsync({ node = "original:505:new:free:complete", limit = 60 }, function(value) result = value end) +Assert.eq(#result.data, 60) +Assert.eq(result.data[60].stable_id, "60") +Assert.eq(requests[2].params.kind, 505) +Assert.eq(requests[2].params.isFinished, true) +Assert.eq(result.groups[2].title, "分类") +Assert.eq(result.groups[2].active, "original:505:new:free:complete") +Assert.eq(result.groups[1].chips[2].id, "publish:1:hot:all:all") +for _idx, req in ipairs(requests) do Assert.is_nil(req.opts.headers.Cookie) end + +source:browseAsync({ node = "publish:505:unknown:paid:serial", limit = 20 }, function(value) result = value end) +Assert.eq(requests[#requests].params.kind, 1) +Assert.eq(requests[#requests].params.sort, "hot") +Assert.eq(requests[#requests].params.minPrice, 1) +Assert.is_nil(requests[#requests].params.isFinished) +Assert.eq(#result.groups, 4) +source:browseAsync({ limit = 25 }, function(value) result = value end) +Assert.eq(#result.data, 25) + +local err +fail_page = 2 +source:browseAsync({ limit = 60 }, function(value, reason) result, err = value, reason end) +Assert.is_nil(result) +Assert.eq(err, "network failed") +fail_page, delayed = nil, true +local calls = 0 +local job = source:browseAsync({}, function() calls = calls + 1 end) +local active = requests[#requests] +job.cancel() +Assert.is_true(active.cancelled) +active.reply() +Assert.eq(calls, 0) diff --git a/tests/douban/client_spec.lua b/tests/douban/client_spec.lua new file mode 100644 index 0000000..899a7e0 --- /dev/null +++ b/tests/douban/client_spec.lua @@ -0,0 +1,511 @@ +--[[-- +豆瓣阅读:搜索体、正文解密、专栏目录、扫码登录和书架。 + +@module tests.moonsource_douban.client_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +package.preload["json"] = function() return require("support.json_stub") end + +local Aes = require("crypto.aes") +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local Json = require("support.json_stub") +local Text = require("utils.text") +local Mapper = require("moonsource_douban.mapper") + +local cfg = {} +package.preload["utils.settings"] = function() + return { + getSource = function() return cfg end, + saveSource = function() end, + get = function() return {} end, + } +end + +local sha2 = require("ffi/sha2") +local iv = string.rep("\1", 16) +local plain = Json.encode({ + posts = { { + title = "序", + contents = { + { type = "headline", id = 10, data = { text = "标题" } }, + { type = "paragraph", id = 11, data = { text = { + { kind = "plaintext", content = "第一" }, + { kind = "plaintext", content = "段" }, + } } }, + { type = "pagebreak", id = 11.5, data = {} }, + { type = "paragraph", id = 12, data = { text = "第二段" } }, + }, + } }, + toc = { + { title = "开篇", paragraph_id = 10, level = 0 }, + { title = "", paragraph_id = 12, level = 1 }, + }, +}) + +local function seal(user_id) + local material = user_id or "anonymous" + local key = sha2.hex_to_bin(sha2.sha256(material)) + return Text.base64Encode(Aes.cbc_encrypt(plain, key, iv) .. iv .. string.rep("z", 13)) +end + +local article = Mapper.decrypt(seal(nil), nil) +Assert.eq(article.posts[1].title, "序") +Assert.eq(Mapper.blocksText(article, 10, 12), "标题\n第一段") +Assert.eq(Mapper.paragraphIds(article, 10, 12)[1], "10") +Assert.eq(Mapper.paragraphIds(article, 10, 12)[2], "11") +Assert.eq(#Mapper.paragraphIds(article, 10, 12), 2) +local spots = Mapper.reviewHotspots({ + { id = "1", note = "好看", startContainerId = "11", n_favorites = 3, owner = { name = "甲" }, create_time = 1700000000000 }, + { note = "", startContainerId = "11" }, + { note = "章外", startContainerId = "99" }, +}, { "10", "11" }) +Assert.eq(#spots, 1) +Assert.eq(spots[1].range, "2") +Assert.eq(spots[1].total, 1) +local page = Mapper.reviewPage({ + { id = "1", note = "好看", startContainerId = "11", n_favorites = 3, owner = { name = "甲" }, create_time = 1700000000000 }, +}, { "10", "11" }, "2") +Assert.eq(page.items[1].author, "甲") +Assert.eq(page.items[1].content, "好看") +Assert.eq(page.items[1].likes, 3) +Assert.eq(page.items[1].time, 1700000000) +local dated = Mapper.reviewPage({ + { id = "2", note = "日期", startContainerId = "10", owner = { name = "乙" }, create_time = "2024-01-02T00:00:00+00:00" }, +}, { "10" }, "1") +Assert.eq(os.date("!%Y-%m-%d", dated.items[1].time), "2024-01-02") +Assert.eq(page.total, 1) +Assert.eq(Mapper.blocksText(article, nil, nil), "标题\n第一段\n第二段") +Assert.eq(Mapper.decrypt(seal("42"), "42").posts[1].title, "序") +Assert.is_nil(Mapper.decrypt(seal("42"), nil)) + +local chapters = Mapper.ebookChapters(article, "594929245") +Assert.eq(#chapters, 2) +Assert.eq(chapters[1].uid, "10") +Assert.eq(chapters[1].title, "开篇") +Assert.eq(chapters[1].vip, false) +Assert.eq(chapters[1].slice, true) +Assert.eq(chapters[1].end_pid, "12") +Assert.eq(chapters[1].toc_version, Mapper.TOC_VERSION) +Assert.eq(chapters[2].title, "第 2 章") +Assert.eq(chapters[2].vip, false) +Assert.is_nil(chapters[2].end_pid) + +local rich = { posts = { { contents = { + { id = 1, type = "paragraph", data = { text = { + { kind = "plaintext", content = " 前文 " }, { kind = "plaintext", content = " 后文 " }, + } } }, + { id = 2, type = "paragraph", data = { text = {} } }, + { id = 3, type = "paragraph", data = { text = { { kind = "plaintext", content = " \n " } } } }, + { id = 4, type = "paragraph", data = { text = "尾段" } }, +} } }, toc = { { paragraph_id = 1, title = "开篇" }, { paragraph_id = 4, title = "结尾" } } } +Assert.eq(Mapper.blocksText(rich), "前文 后文\n尾段") +Assert.eq(Mapper.blocksText(rich, 1, 4), "前文 后文") +Assert.eq(Mapper.paragraphIds(rich)[1], "1") +Assert.eq(Mapper.paragraphIds(rich)[2], "4") +Assert.eq(#Mapper.paragraphIds(rich), 2) +Assert.eq(Mapper.ebookChapters(rich, "test")[1].vip, false) + +local found = Mapper.searchBooks({ + list = { + { id = "594929245", title = "三体", author = { { name = "刘慈欣" } }, cover = "//pic/a.jpg", abstract = "科幻", url = "/ebook/594929245/", kinds = { { shortName = "科幻" } } }, + { id = "1", title = "有声", isAudio = true }, + { id = "699209652", title = "如果爱", isColumn = true, url = "/column/73610846/", author = { { name = "茉莉多丁" } } }, + }, +}) +Assert.eq(#found, 2) +Assert.eq(found[1].stable_id, "594929245") +Assert.eq(found[1].authors, "刘慈欣") +Assert.eq(found[1].cover, "https://pic/a.jpg") +Assert.eq(found[1].category, "科幻") +Assert.eq(found[2].stable_id, "699209652") +Assert.is_nil(Mapper.searchBooks({ error = "PublishError" })) + +local target = Mapper.reader("/reader/column/73610846/chapter/699210556/") +Assert.eq(target.kind, "column") +Assert.eq(target.column_id, "73610846") +Assert.eq(Mapper.reader("/reader/ebook/594929245/").kind, "ebook") +Assert.eq(Mapper.readerUrl({ data = { works = { readerUrl = "/reader/ebook/594929245/" } } }), "/reader/ebook/594929245/") + +local column = Mapper.columnBook("699209652", { + type = "column", + title = "如果爱", + abstract = "简介", + cover = "https://pic/c.jpg", + category = "言情小说", + agent = { name = "茉莉多丁" }, + chapters = {}, +}) +Assert.eq(column.stable_id, "699209652") +Assert.eq(column.authors, "茉莉多丁") +Assert.eq(column.category, "言情小说") + +local toc = Mapper.columnChapters({ + chapters = { + { id = "699210556", title = "第一章", is_free = true }, + { id = "699210557", title = "第二章", is_free = false, is_paid = false, is_allowed_to_read = false }, + { id = "699210558", title = "第三章", is_paid = true }, + }, +}) +Assert.eq(#toc, 3) +Assert.eq(toc[1].content_url, "699210556") +Assert.eq(toc[1].vip, false) +Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION) +Assert.eq(toc[2].vip, true) +Assert.eq(toc[3].vip, false) + +local shelf = Mapper.shelf({ list = { { id = "9", title = "书架书", author = { { name = "甲" } } } } }) +Assert.eq(shelf[1].stable_id, "9") +Assert.eq(#Mapper.shelf({}), 0) +Assert.eq(#Mapper.shelf({ worksIds = {} }), 0) +Assert.is_nil(Mapper.shelf({ worksIds = { "9" } })) +Assert.is_nil(Mapper.shelf({ error = "Nope" })) +Assert.is_nil(Mapper.shelf({ list = { { foo = 1 } } })) +Assert.eq(#Mapper.shelfIds({ worksIds = {} }), 0) +Assert.eq(Mapper.shelfIds({ worksIds = { "9" } })[1], "9") +Assert.eq(Mapper.shelfIds({ data = { user = { bookshelf = { libraryList = { list = { { worksId = "9" } } } } } } })[1], "9") +Assert.is_nil(Mapper.shelfIds({ error = "Nope" })) +local shelf_rows = Mapper.shelfWorks({ + data = { worksList = { { id = "9", title = "书架书", author = { { name = "甲" } }, cover = "https://img/a.jpg" } } }, +}) +Assert.eq(shelf_rows[1].stable_id, "9") +Assert.eq(shelf_rows[1].title, "书架书") +Assert.eq(shelf_rows[1].authors, "甲") +Assert.eq(shelf_rows[1].cover, "https://img/a.jpg") +Assert.is_nil(Mapper.shelfWorks({ data = { worksList = { { id = "1", title = "听", isAudio = true } } } })) +Assert.eq(Mapper.readCsrf("CSRF_TOKEN = 'shelf-tok';"), "shelf-tok") + +Assert.eq(Mapper.csrf(''), "tok123") +local user = Mapper.user('Ark.user = {"id":"42","name":"读","isAnonymous":false}') +Assert.eq(user.id, "42") +Assert.eq(user.name, "读") +Assert.is_nil(Mapper.user('Ark.user = {"isAnonymous": true}')) + +local ticket = Mapper.qr({ url = "/oidc/qrcode/confirm?code=abc", expires_in = 300 }, "https://accounts.arkread.com") +Assert.eq(ticket.qr, "https://accounts.arkread.com/oidc/qrcode/confirm?code=abc") +Assert.eq(ticket.code, "abc") +Assert.eq(Mapper.qrStatus({ confirmed = false }), "wait") +Assert.eq(Mapper.qrStatus({ confirmed = true }), "ok") +local progress = Mapper.progress({ r = 0, progress = { paragraph_id = 10, paragraph_offset = 0 } }) +Assert.eq(progress.paragraph_id, "10") +Assert.eq(select(2, Mapper.progress({ r = 1 })), false) +Assert.eq(select(2, Mapper.progress({ progress = {} })), false) +Assert.eq(select(2, Mapper.progress({ r = 0 })), true) +Assert.eq(Mapper.firstParagraphId({ + posts = { { contents = { { id = 3, type = "headline" }, { id = 4, type = "paragraph", data = { text = "正文" } } } } }, +}), "4") +Assert.eq(Mapper.searchBody("三体").extensions.persistedQuery.sha256Hash, Mapper.SEARCH_HASH) + +local requests = {} +local authorize_hits = 0 +local deferred_requests, defer_column = false, false +local progress_write_body = Json.encode({ r = 0 }) +package.preload["http.request"] = function() + return { + header = function(res, name) + local headers = res and res.headers or {} + for key, value in pairs(headers) do + if key:lower() == name:lower() then return value end + end + end, + headerAll = function(res, name) + local headers = res and res.headers or {} + local found = {} + for key, value in pairs(headers) do + if key:lower() == name:lower() and type(value) == "string" then found[#found + 1] = value end + end + return found + end, + request = function(opts, callback) + local request = { method = opts.method, url = opts.url, body = opts.body, headers = opts.headers } + requests[#requests + 1] = request + local res = { code = 200, body = "{}", headers = {} } + if opts.url:find("/j/search_v2", 1, true) then + res.body = Json.encode({ list = { { id = "594929245", title = "三体", author = { { name = "刘慈欣" } } } } }) + elseif opts.url:find("/j/graphql", 1, true) and opts.body and opts.body:find(Mapper.ACCESS_HASH, 1, true) then + local works_id = opts.body:match('"worksId":"(%d+)"') + local reader = works_id == "699209652" and "/reader/column/73610846/chapter/699210556/" or "/reader/ebook/594929245/" + res.body = Json.encode({ data = { works = { readerUrl = reader } } }) + elseif opts.url:find("/j/column/73610846/", 1, true) then + res.body = Json.encode({ + type = "column", title = "如果爱", abstract = "简介", agent = { name = "茉莉多丁" }, + chapters = { { id = "699210556", title = "第一章", is_free = true } }, + }) + elseif opts.body and opts.body:find(Mapper.INFO_HASH, 1, true) then + res.body = Json.encode({ data = { universalWorks = { id = "594929245", title = "三体", isColumn = false } } }) + elseif opts.body and opts.body:find(Mapper.SHELF_WORKS_HASH, 1, true) then + res.body = Json.encode({ + data = { worksList = { { id = "9", title = "书架书", author = { { name = "甲" } }, cover = "https://img/a.jpg" } } }, + }) + elseif opts.url:find("get_reader_data", 1, true) then + res.body = Json.encode({ r = 0, data = seal(nil), readerDataVersion = "v24" }) + elseif opts.url:find("/oidc/login", 1, true) then + res.code = 302 + res.headers.Location = "https://accounts.arkread.com/oauth2/authorize?client_id=public" + elseif opts.url:find("/oauth2/authorize", 1, true) then + authorize_hits = authorize_hits + 1 + if authorize_hits == 1 then + res.body = 'Ark.user = {"isAnonymous": true}' + else + res.code = 302 + res.headers.Location = "https://read.douban.com/" + end + elseif opts.url:find("/oidc/qrcode/generate", 1, true) then + if opts.headers.Referer ~= "https://accounts.arkread.com/" then + res.code = 400 + res.body = Json.encode({ code = 1002, message = "The referrer header is missing." }) + else + res.body = Json.encode({ url = "/oidc/qrcode/confirm?code=abc", expires_in = 300 }) + end + elseif opts.url:find("/oidc/qrcode/status", 1, true) then + if opts.headers.Referer ~= "https://accounts.arkread.com/" then + res.code = 400 + res.body = Json.encode({ code = 1002, message = "The referrer header is missing." }) + else + res.body = Json.encode({ confirmed = false }) + end + elseif opts.url == "https://read.douban.com/" then + res.body = 'CSRF_TOKEN = \'shelf-tok\'; Ark.user = {"id":"42","name":"读","isAnonymous":false}' + res.headers["Set-Cookie"] = "session=s1; Path=/" + elseif opts.url:find("/j/progress/", 1, true) and opts.method == "GET" then + res.body = Json.encode({ r = 0, progress = { paragraph_id = "10", paragraph_offset = 0 } }) + elseif opts.url:find("/j/progress/", 1, true) then + res.body = progress_write_body + elseif opts.url:find("/j/reading_time", 1, true) then + res.body = "" + elseif opts.url:find("/annotations_by_paragraphs", 1, true) then + res.body = '[' + .. '{"id":"1","note":"好看","startContainerId":"11","n_favorites":2,"owner":{"name":"甲"},"create_time":1700000000},' + .. '{"note":"","startContainerId":"10"}' + .. ']' + elseif opts.url:find("/j/bookshelf/folder/", 1, true) then + res.body = Json.encode({ folderIds = {} }) + elseif opts.url:find("/j/bookshelf/", 1, true) and opts.method == "GET" then + res.body = Json.encode({ worksIds = { "9" } }) + elseif opts.url:find("/j/bookshelf/", 1, true) then + res.body = Json.encode({ ok = true }) + end + request.reply = function() callback(res, nil) end + if not deferred_requests and not (defer_column and opts.url:find("/j/column/", 1, true)) then + request.reply() + end + return { cancel = function() request.cancelled = true end } + end, + } +end + +local Client = require("moonsource_douban.client") + +local books +Client.searchAsync("三体", function(list) books = list end) +Assert.eq(books[1].title, "三体") +Assert.is_true(requests[#requests].body:find(Mapper.SEARCH_HASH, 1, true) ~= nil) +Assert.eq(requests[#requests].method, "POST") + +local detail +Client.detailAsync("699209652", function(book) detail = book end) +Assert.eq(detail.title, "如果爱") +Assert.eq(detail.authors, "茉莉多丁") +Assert.eq(detail.stable_id, "699209652") + +local ebook +Client.detailAsync("594929245", function(book) ebook = book end) +Assert.eq(ebook.title, "三体") + +local toc_rows +Client.tocAsync("594929245", function(rows) toc_rows = rows end) +Assert.eq(toc_rows[1].title, "开篇") +local reader_hits = 0 +for _idx, req in ipairs(requests) do + if req.url:find("get_reader_data", 1, true) then reader_hits = reader_hits + 1 end +end +Assert.eq(reader_hits, 1) + +local text +Client.textAsync("594929245", 10, 12, function(value) text = value end) +Stubs.flush() +Assert.eq(text, "标题\n第一段") +local reader_hits_after = 0 +for _idx, req in ipairs(requests) do + if req.url:find("get_reader_data", 1, true) then reader_hits_after = reader_hits_after + 1 end +end +Assert.eq(reader_hits_after, 1) + +local denied +Client.shelfAsync(function(_rows, err) denied = err end) +Stubs.flush() +Assert.eq(denied, "未登录豆瓣阅读") + +local ticket +local login = Client.newLogin() +login:beginQrAsync(function(value) ticket = value end) +Assert.eq(ticket.code, "abc") +Assert.eq(ticket.qr, "https://accounts.arkread.com/oidc/qrcode/confirm?code=abc") +Assert.eq(ticket.authorize, "https://accounts.arkread.com/oauth2/authorize?client_id=public") +Assert.eq(requests[#requests].headers["X-CSRF-Token"], "tok123") + +local waiting +login:qrStatusAsync("abc", function(kind) waiting = kind end) +Assert.eq(waiting, "wait") + +local logged +login:finishQrAsync(ticket.authorize, function(value) logged = value end) +Assert.eq(logged.id, "42") +Assert.eq(cfg.logged_in, true) +Assert.eq(cfg.user_id, "42") +Assert.eq(cfg.name, "读") +Assert.is_true(cfg.cookie:find("session=s1", 1, true) ~= nil) + +local shelf_books +Client.shelfAsync(function(list) shelf_books = list end) +Assert.eq(shelf_books[1].title, "书架书") +Assert.eq(shelf_books[1].authors, "甲") +Assert.eq(requests[#requests].headers["X-CSRF-Token"], "shelf-tok") +Assert.is_true(requests[#requests].body:find(Mapper.SHELF_WORKS_HASH, 1, true) ~= nil) + +local added +Client.addAsync("9", function(ok) added = ok end) +Assert.eq(added, true) +Assert.eq(requests[#requests].method, "POST") +Assert.is_true(requests[#requests].body:find("9", 1, true) ~= nil) + +local removed +Client.removeAsync("9", function(ok) removed = ok end) +Assert.eq(removed, true) +Assert.eq(requests[#requests].method, "DELETE") + +local progress_mark +Client.progressAsync("9", function(value) progress_mark = value end) +Assert.eq(progress_mark.paragraph_id, "10") +Assert.is_true(requests[#requests].url:find("works_id=9", 1, true) ~= nil) + +local progress_saved +Client.putProgressAsync("9", "10", 2, 4, true, function(ok) progress_saved = ok end) +Assert.eq(progress_saved, true) +Assert.eq(requests[#requests].method, "POST") +Assert.is_true(requests[#requests].url:find("/j/progress/", 1, true) ~= nil) +Assert.is_true(requests[#requests].body:find("percentage=25", 1, true) ~= nil) +Assert.eq(requests[#requests].headers["Content-Type"], "application/x-www-form-urlencoded") + +local progress_failure +progress_write_body = Json.encode({ r = 1 }) +Client.putProgressAsync("9", "10", 2, 4, true, function(ok, err) + progress_saved, progress_failure = ok, err +end) +Assert.is_nil(progress_saved) +Assert.eq(progress_failure, "豆瓣阅读进度保存失败") +progress_write_body = "upstream error" +Client.putProgressAsync("9", "10", 2, 4, true, function(ok, err) + progress_saved, progress_failure = ok, err +end) +Assert.is_nil(progress_saved) +Assert.eq(progress_failure, "豆瓣阅读进度保存失败") +progress_write_body = Json.encode({ r = 0 }) + +local reading_saved +Client.pushReadingAsync({ + { worksId = 9, beginTime = "2020-01-01T00:00:00.000Z", endTime = "2020-01-01T00:01:00.000Z" }, +}, function(ok) reading_saved = ok end) +Assert.eq(reading_saved, true) +Assert.is_true(requests[#requests].url:find("/j/reading_time", 1, true) ~= nil) +Assert.is_true(requests[#requests].body:find("worksId", 1, true) ~= nil) + +local noted +Client.annotationsAsync("594929245", { "10", "11" }, function(rows) noted = rows end) +Assert.eq(#noted, 2) +Assert.eq(requests[#requests].method, "POST") +Assert.is_true(requests[#requests].url:find("/j/article_v2/594929245/annotations_by_paragraphs", 1, true) ~= nil) +Assert.eq(requests[#requests].body, "paragraph_ids=10%2C11") +Assert.eq(Mapper.reviewHotspots(noted, { "10", "11" })[1].range, "2") + +cfg.cookie, cfg.logged_in, cfg.user_id = nil, nil, nil +Client.reset() +local cached_article +Client.articleAsync("cached", function(value) cached_article = value end) +Assert.is_true(cached_article ~= nil) +local cache_calls = 0 +local cache_job = Client.articleAsync("cached", function() cache_calls = cache_calls + 1 end) +Assert.eq(cache_calls, 0) +cache_job.cancel() +Stubs.flush() +Assert.eq(cache_calls, 0) +Client.articleAsync("cached", function() cache_calls = cache_calls + 1 end) +Stubs.flush() +Assert.eq(cache_calls, 1) + +deferred_requests = true +for _idx, method in ipairs({ "detailAsync", "tocAsync" }) do + for cancel_at = 0, 1 do + local calls = 0 + local job = Client[method]("699209652", function() calls = calls + 1 end) + local active = requests[#requests] + if cancel_at == 1 then + active.reply() + active = requests[#requests] + end + local count = #requests + job.cancel() + Assert.is_true(active.cancelled) + active.reply() + Stubs.flush() + Assert.eq(calls, 0) + Assert.eq(#requests, count) + end +end + +deferred_requests, defer_column = false, true +local sync_calls = 0 +local sync_job = Client.detailAsync("699209652", function() sync_calls = sync_calls + 1 end) +local second = requests[#requests] +sync_job.cancel() +Assert.is_true(second.cancelled) +second.reply() +Assert.eq(sync_calls, 0) +defer_column, deferred_requests = false, true + +cfg.cookie, cfg.logged_in, cfg.user_id = "session=s1", true, "42" +for cancel_at = 0, 2 do + Client.reset() + local calls = 0 + local job = Client.shelfAsync(function() calls = calls + 1 end) + local active = requests[#requests] + for _step = 1, cancel_at do + active.reply() + active = requests[#requests] + end + local count = #requests + job.cancel() + Assert.is_true(active.cancelled) + active.reply() + Assert.eq(calls, 0) + Assert.eq(#requests, count) +end + +for cancel_at = 0, 2 do + authorize_hits = 0 + local calls = 0 + local job = Client.newLogin():beginQrAsync(function() calls = calls + 1 end) + local active = requests[#requests] + for _step = 1, cancel_at do + active.reply() + active = requests[#requests] + end + local count = #requests + job.cancel() + Assert.is_true(active.cancelled) + active.reply() + Assert.eq(calls, 0) + Assert.eq(#requests, count) +end + +authorize_hits = 1 +local finish_calls = 0 +local finish_job = Client.newLogin():finishQrAsync("https://accounts.arkread.com/oauth2/authorize?client_id=public", + function() finish_calls = finish_calls + 1 end) +requests[#requests].reply() +local final = requests[#requests] +finish_job.cancel() +Assert.is_true(final.cancelled) +final.reply() +Assert.eq(finish_calls, 0) diff --git a/tests/douban/community_spec.lua b/tests/douban/community_spec.lua new file mode 100644 index 0000000..4e33ba8 --- /dev/null +++ b/tests/douban/community_spec.lua @@ -0,0 +1,160 @@ +--[[-- 豆瓣书评和章评:真实归属、分页、取消和独立缓存。 @module tests.moonsource_douban.community_spec --]] +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local JSON = require("support.json_stub") +package.loaded.json = JSON +local cfg = { cookie = "sid=test-private-cookie", user_id = "test-user", logged_in = true } +package.loaded["utils.settings"] = { + getSource = function() return cfg end, get = function() return {} end, + saveSource = function() end, +} +local connected, requests, mode = true, {}, "ok" +---@type {cb: fun(res: table), request: table}|nil +local pending +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +local function wire(offset, chapter) + local rows = {} + for index = offset + 1, math.min(offset + 20, 21) do + rows[#rows + 1] = { id = tostring(index), content = "

Review
text

", + createTime = "2025-01-01T12:00:00Z", commentType = chapter and "Discussion" or "Review", + works = { isChapter = chapter ~= nil, id = chapter or "101" }, + user = { name = "Reader" }, upvoteCount = 2 } + end + return { data = { works = { comments = { total = 21, list = rows } } } } +end +package.loaded["http.request"] = { + header = function() return nil end, + headerAll = function() return {} end, + request = function(opts, cb) + local request = { opts = opts } + requests[#requests + 1] = request + if opts.method == "GET" then + cb({ code = 200, headers = {}, body = "CSRF_TOKEN = 'test-csrf'" }) + return { cancel = function() request.cancelled = true end } + end + local body = JSON.decode(opts.body) + if body.extensions.persistedQuery.sha256Hash:find("bf9257", 1, true) then + cb({ code = 200, headers = {}, body = JSON.encode({ + data = { works = { readerUrl = "/reader/column/777/chapter/11/" } }, + }) }) + elseif mode == "wait" then + pending = { cb = cb, request = request } + elseif mode == "fail" then cb(nil, "network failed") + else + local result = wire(body.variables.start, body.variables.chapterId) + if mode == "wrong-chapter" then result.data.works.comments.list[1].works.id = "other" end + cb({ code = 200, headers = {}, body = JSON.encode(result) }) + end + return { cancel = function() request.cancelled = true end } + end, +} +local Client = require("moonsource_douban.client") +local Mapper = require("moonsource_douban.mapper") +local source = require("moonsource_douban.source").new() +function source:loadTocAsync(_identity, cb) + cb({ { uid = "11", idx = 1, title = "One" }, { uid = "22", idx = 2, title = "Two" } }) + return { cancel = function() end } +end +local page, err +source:bookReviewsAsync({ source_id = "ext.douban", stable_id = "101" }, function(value, reason) + page, err = value, reason +end) +Assert.is_nil(err) +Assert.len(page.items, 20) +Assert.matches(page.items[1].text, "Review") +Assert.is_false(page.items[1].text:find("

", 1, true) ~= nil) +Assert.is_nil(requests[1].opts.headers.Cookie) +Assert.eq(JSON.decode(requests[1].opts.body).variables.worksId, "101") +local identity = { source_id = "ext.douban", stable_id = "101", chapter_idx = 1 } +source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end) +Assert.is_nil(err) +Assert.len(page.items, 20) +Assert.eq(page.max_idx, 20) +Assert.is_true(page.more) +local body = JSON.decode(requests[#requests].opts.body) +Assert.eq(body.variables.columnId, "777", "专栏 ID 不等于作品 ID") +Assert.eq(body.variables.chapterId, "11") +Assert.is_nil(body.variables.worksId) +Assert.is_nil(requests[#requests].opts.headers.Cookie) +source:paragraphReviewPageAsync(identity, "chapter", 20, function(value, reason) page, err = value, reason end) +Assert.is_nil(err) +Assert.len(page.items, 1) +Assert.eq(page.max_idx, 21) +Assert.is_false(page.more) +Assert.eq(requests[#requests].opts.headers.Cookie, "sid=test-private-cookie") +Assert.eq(requests[#requests].opts.headers["X-CSRF-Token"], "test-csrf") +cfg.logged_in = false +local request_count = #requests +Client.communityAsync("101", "11", 20, function(value, reason) page, err = value, reason end) +Stubs.flush() +Assert.is_nil(page) +Assert.eq(err, "请先登录豆瓣阅读") +Assert.eq(#requests, request_count, "未登录时后续页立即说明权限,不发无效请求") +cfg.logged_in = true +Client.communityAsync("101", "11", 40, function(value, reason) page, err = value, reason end) +Assert.is_nil(err) +Assert.len(page.items, 0) +Assert.is_false(page.more) +mode = "wrong-chapter" +source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end) +Assert.is_nil(page) +Assert.eq(err, "响应无效") +connected = false +source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end) +Stubs.flush() +Assert.is_nil(err) +Assert.len(page.items, 20, "坏响应没有覆盖本章缓存") +identity.chapter_idx = 2 +source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end) +Stubs.flush() +Assert.is_nil(page, "换章不读上一章缓存") +Assert.eq(err, "未联网,无法加载段评") +connected, mode = true, "wait" +local called = false +local job = Client.communityAsync("101", "22", 0, function() called = true end) +job.cancel() +Assert.is_true(pending.request.cancelled, "同步入口回调后取消的是评论请求") +pending.cb({ code = 200, headers = {}, body = JSON.encode(wire(0, "22")) }) +Assert.is_false(called, "取消后忽略迟到评论") +mode = "fail" +Client.communityAsync("101", nil, 0, function(value, reason) page, err = value, reason end) +Assert.is_nil(page) +Assert.eq(err, "network failed") +for _idx, bad in ipairs({ {}, { errors = { { message = "bad" } } }, { errors = "bad" } }) do + local value, reason = Mapper.communityPage(bad, 0) + Assert.is_nil(value) + Assert.eq(reason, "响应无效") +end +local denied, reason = Mapper.communityPage({ errors = { { message = "AnonymousError" } } }, 20, "11") +Assert.is_nil(denied) +Assert.eq(reason, "请先登录豆瓣阅读") +for _idx, invalid_id in ipairs({ {}, "" }) do + local invalid = wire(0, "11") + invalid.data.works.comments.list[1].id = invalid_id + local value, id_err = Mapper.communityPage(invalid, 0, "11") + Assert.is_nil(value) + Assert.eq(id_err, "响应无效") +end + +do + local Chapter = require("source.chapter") + local original_open, original_text = Chapter.openAsync, Client.textAsync + local chapter = { uid = "11", content_url = "11" } + local produced + cfg.show_paragraph_reviews = true + Client.textAsync = function(_aid, _start, _ending, cb) + cb("Original text") + return { cancel = function() end } + end + Chapter.openAsync = function(_source, ref, _book, _opts, ops, _cb) + return ops.fetchContent(ref, chapter, function(value) produced = value end) + end + source:openBookAsync(identity, { chapter_idx = 1 }, function() end) + Assert.matches(produced.html, 'id="moon%-chapter%-reviews"', "专栏正文给章評预留空间") + Assert.matches(produced.html, "Original text") + chapter.slice = true + source:openBookAsync(identity, { chapter_idx = 1 }, function() end) + Assert.is_nil(produced.html:find('id="moon-chapter-reviews"', 1, true), + "出版书没有章评入口,不增加空白区域") + Chapter.openAsync, Client.textAsync = original_open, original_text +end diff --git a/tests/douban/login_spec.lua b/tests/douban/login_spec.lua new file mode 100644 index 0000000..9444330 --- /dev/null +++ b/tests/douban/login_spec.lua @@ -0,0 +1,128 @@ +--[[-- +豆瓣登录会话:取消、坏跳转、换号和迟到响应不能污染有效账号。 + +@module tests.moonsource_douban.login_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +package.preload["json"] = function() return require("support.json_stub") end +local cfg = { cookie = "session=old", logged_in = true, user_id = "42" } +local cleared = 0 +package.loaded["source.logout"] = { clear = function(_id, clear) + clear(); cleared = cleared + 1; return true +end } +local requests, delayed, status, body, location = {}, false, 200, nil, nil +local next_status +package.preload["utils.settings"] = function() + return { getSource = function() return cfg end, saveSource = function() end } +end +package.preload["http.request"] = function() + return { + headerAll = function() return { "session=new; Path=/; Secure; HttpOnly" } end, + header = function() return location end, + request = function(opts, cb) + local req = { opts = opts } + requests[#requests + 1] = req + local res = { code = status, body = body or 'Ark.user = {"id":"42","isAnonymous":false,"name":"测试"}' } + status, next_status = next_status or status, nil + req.reply = function() cb(res, status == 0 and "network failed" or nil) end + if not delayed then req.reply() end + return { cancel = function() req.cancelled = true end } + end, + } +end +local Client = require("moonsource_douban.client") +Client.load() +local ok, err +local function signIn(cookie, cb) + local login = Client.newLogin(cookie) + return login:checkCookieAsync(function(valid, reason, user) + if valid then valid, reason = login:commit(user) end + cb(valid == true, reason) + end) +end +Client.newLogin("session=pasted"):checkCookieAsync(function(valid, reason, user) + Assert.is_true(valid) + Assert.is_nil(reason) + Assert.eq(user.id, "42") + Assert.eq(cfg.cookie, "session=old", "校验候选不写当前登录") +end) +signIn("session=pasted", function(value, reason) ok, err = value, reason end) +Assert.is_true(ok) +Assert.eq(cfg.cookie, "session=new") +Assert.is_nil(cfg.cookie:find("Path", 1, true)) +Assert.is_nil(cfg.cookie:find("HttpOnly", 1, true)) +Assert.eq(requests[1].opts.headers.Cookie, "session=pasted") + +body = 'Ark.user = {"id":"99","isAnonymous":false}' +signIn("session=other", function(value, reason) ok, err = value, reason end) +Assert.is_true(ok) +Assert.is_nil(err) +Assert.eq(cfg.user_id, "99") +Assert.eq(cleared, 1) +Assert.eq(cfg.cookie, "session=new") + +status, body = 0, nil +signIn("session=bad", function(value, reason) ok, err = value, reason end) +Assert.eq(ok, false) +Assert.eq(err, "network failed") +Assert.eq(cfg.logged_in, true) + +status, location = 302, "https://untrusted.invalid/collect" +local before = #requests +signIn("session=bad", function(value, reason) ok, err = value, reason end) +Stubs.flush() +Assert.eq(ok, false) +Assert.eq(#requests, before + 1) +Assert.eq(cfg.cookie, "session=new") + +status, location, next_status = 302, "https://accounts.arkread.com/oidc/login", 200 +signIn("session=bad", function(value, reason) ok, err = value, reason end) +status, location = 200, nil +Stubs.flush() +Assert.eq(ok, false) +Assert.eq(cfg.cookie, "session=new") + +body = 'Ark.user = {"id":"","isAnonymous":false}' +signIn("session=bad", function(value) ok = value end) +Assert.eq(ok, false) +body = 'Ark.user = {"id":{},"isAnonymous":false}' +signIn("session=bad", function(value) ok = value end) +Assert.eq(ok, false) +body = nil + +status, location, delayed = 200, nil, true +local calls = 0 +local login = Client.newLogin("session=cancel") +local job = login:checkCookieAsync(function() calls = calls + 1 end) +job.cancel() +login:cancel() +requests[#requests].reply() +Assert.eq(calls, 0) +Assert.eq(cfg.cookie, "session=new") + +local stale = Client.newLogin("session=stale") +stale:checkCookieAsync(function(value, reason) ok, err = value, reason end) +local old = requests[#requests] +delayed = false +signIn("session=recent", function(value) Assert.is_true(value) end) +old.reply() +Assert.eq(ok, false) +Assert.eq(err, "登录状态已变化,请重试") +Assert.eq(cfg.cookie, "session=new") + +cfg.user_id = nil +signIn("session=migration", function(value, reason) ok, err = value, reason end) +Assert.is_true(ok) +Assert.is_nil(err) +Assert.eq(cfg.user_id, "42", "旧配置缺用户标识也直接换号") + +package.loaded["source.registry"] = { reload = function() end } +local Setting = require("moonsource_douban.setting") +Setting.browser.apply({ cookies = { { domain = ".douban.com", name = "session", value = "browser" } } }, + function(value, reason) ok, err = value, reason end) +Assert.is_true(ok, "浏览器校验与提交分阶段,不误判正常登录为账号已变化") +Assert.is_nil(err) +Assert.eq(cfg.user_id, "42") diff --git a/tests/douban/phone_login_spec.lua b/tests/douban/phone_login_spec.lua new file mode 100644 index 0000000..b4e2c55 --- /dev/null +++ b/tests/douban/phone_login_spec.lua @@ -0,0 +1,176 @@ +--[[-- +豆瓣短信登录协议及输入窗口生命周期。 + +@module tests.moonsource_douban.phone_login_spec +--]] +---@diagnostic disable: undefined-field, missing-fields + +local Assert = require("support.assert") +local Json = require("support.json_stub") +local Themed = require("support.theme_stubs") +local cfg, requests = {}, {} +local deferred, verified, transfer, broken, network_error = false, false, false, false, false +local phone = "+8600000000000" +package.preload["json"] = function() return Json end +package.preload["utils.settings"] = function() + return { getSource = function() return cfg end, saveSource = function() end, get = function() return {} end } +end +package.preload["http.request"] = function() + return { + header = function(res, name) return res.headers[name] end, + headerAll = function(res, name) return res.headers[name] and { res.headers[name] } or {} end, + request = function(opts, cb) + local req = { opts = opts } + requests[#requests + 1] = req + local res = { code = 200, headers = {}, body = "{}" } + if opts.url:find("/oidc/login", 1, true) then + res.code, res.headers.Location = 302, "https://accounts.arkread.com/oauth2/authorize?client_id=test" + elseif opts.url:find("/oauth2/authorize", 1, true) then + if verified then res.code, res.headers.Location = 302, "https://read.douban.com/" + else + res.body = '' + res.headers["Set-Cookie"] = "candidate=test; Path=/" + end + elseif opts.url:find("/phone/verify_code", 1, true) then + res.body = broken and "{}" or Json.encode({ retry_after = 60 }) + elseif opts.url:find("/phone/verify", 1, true) then + if broken then + res.code, res.body = 400, Json.encode({ code = 1001, message = "invalid code" }) + elseif transfer then res.body = Json.encode({ transfer_info = { user_type = 0 } }) + else verified = true end + elseif opts.url == "https://read.douban.com/" then + res.body = 'Ark.user={"id":"42","name":"测试","isAnonymous":false}' + res.headers["Set-Cookie"] = "session=test; Path=/" + end + req.reply = function() cb(not network_error and res or nil, network_error and "network failed" or nil) end + if not deferred then req.reply() end + return { cancel = function() req.cancelled = true end } + end, + } +end +local Client = require("moonsource_douban.client") +local session = Client.newLogin() +local ready, wait, user, failure +session:beginAsync(function(authorize, err) ready, failure = authorize ~= nil, err end) +Assert.is_true(ready) +Assert.is_nil(failure) +session:sendPhoneCodeAsync(phone, function(value, err) wait, failure = value, err end) +Assert.eq(wait, 60) +Assert.is_nil(failure) +local sent = requests[#requests].opts +Assert.eq(Json.decode(sent.body).phone_number, phone) +Assert.eq(sent.headers.Referer, "https://accounts.arkread.com/") +Assert.eq(sent.headers["X-CSRF-Token"], "csrf-test") +Assert.eq(sent.headers.Cookie, "candidate=test") +Assert.eq(sent.cache_ttl, 0) +broken = true +session:sendPhoneCodeAsync(phone, function(value, err) wait, failure = value, err end) +Assert.is_nil(wait) +Assert.eq(failure, "响应无效") +session:verifyPhoneAsync(phone, "000001", function(value, err) user, failure = value, err end) +Assert.is_nil(user) +Assert.eq(failure, "invalid code") +Assert.is_nil(cfg.cookie) +broken, transfer = false, true +session:verifyPhoneAsync(phone, "000001", function(value, err) user, failure = value, err end) +Assert.is_nil(user) +Assert.is_true(failure:find("历史数据授权", 1, true) ~= nil) +Assert.is_nil(cfg.cookie) +transfer = false +session:verifyPhoneAsync(phone, "000001", function(value, err) user, failure = value, err end) +Assert.eq(user.id, "42") +Assert.is_nil(failure) +Assert.is_true(Client.loggedIn()) +Assert.eq(cfg.cookie, "session=test") + +for cancel_at = 0, 2 do + cfg, verified, deferred = {}, false, false + Client.reset() + session = Client.newLogin() + session:beginAsync(function() end) + deferred = true + local calls = 0 + local job = session:verifyPhoneAsync(phone, "000001", function() calls = calls + 1 end) + for _step = 1, cancel_at do requests[#requests].reply() end + local current = requests[#requests] + job.cancel() + Assert.is_true(current.cancelled) + current.reply() + Assert.eq(calls, 0) + Assert.is_nil(cfg.cookie) + session:cancel() +end +deferred, verified, cfg = false, false, {} +Client.reset() +session = Client.newLogin() +session:beginAsync(function() end) +network_error = true +session:sendPhoneCodeAsync(phone, function(value, err) wait, failure = value, err end) +Assert.is_nil(wait) +Assert.eq(failure, "network failed") + +Themed.install() +local pending, submitted, connected = {}, {}, true +package.loaded["moonsource_douban.client"] = { + newLogin = function() + local candidate = {} + function candidate:beginAsync(cb) + self.authorize = "https://accounts.arkread.com/oauth2/authorize" + cb(self.authorize) + return { cancel = function() end } + end + function candidate:sendPhoneCodeAsync(number, cb) + submitted[#submitted + 1] = number + pending.send = cb + return { cancel = function() pending.cancelled = true end } + end + function candidate:verifyPhoneAsync(number, code, cb) + submitted[#submitted + 1] = number .. ":" .. code + pending.verify = cb + return { cancel = function() pending.cancelled = true end } + end + function candidate:cancel() self.cancelled = true end + return candidate + end, +} +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +local PhoneLogin = require("moonsource_douban.phone_login") +local logins = 0 +local dialog = PhoneLogin:new(function() logins = logins + 1 end) +dialog:start() +local input = Themed.last("input") +Assert.is_true(input.keep_open) +Assert.eq(input.fields[1].text, "+86") +input.actions[1].callback("+86", "invalid") +Assert.eq(#submitted, 0) +connected = false +input.actions[1].callback("+86", "00000000000") +Assert.eq(#submitted, 0) +connected = true +input.actions[1].callback("+86", "00000000000") +Assert.eq(submitted[1], phone) +pending.send(60) +Assert.eq(Themed.last("toast").text, "验证码已发送") +input.actions[1].callback("+86", "00000000000") +Assert.eq(#submitted, 1) +dialog:verify("+86", "different", "000001") +Assert.eq(#submitted, 1) +input.callback("+86", "00000000000", "000001") +Assert.eq(#submitted, 1) +Themed.last("confirm").ok_callback() +Assert.eq(submitted[2], phone .. ":000001") +input.cancel_callback() +Assert.is_true(pending.cancelled) +pending.verify({ id = "42" }) +Assert.eq(logins, 0) +Assert.is_true(dialog.session.cancelled) + +pending = {} +dialog = PhoneLogin:new(function() logins = logins + 1 end) +dialog:start() +dialog:send("+86", "00000000000") +pending.send(0) +dialog:verify("+86", "00000000000", "000001") +pending.verify({ id = "42" }) +Assert.eq(logins, 1) +Assert.is_true(dialog.dialog.closed) diff --git a/tests/douban/progress_spec.lua b/tests/douban/progress_spec.lua new file mode 100644 index 0000000..035fcb5 --- /dev/null +++ b/tests/douban/progress_spec.lua @@ -0,0 +1,65 @@ +--[[-- +豆瓣进度按正文分段索引上传;专栏只写章节 article,不伪造整部作品进度。 + +@module tests.moonsource_douban.progress_spec +--]] +---@diagnostic disable: undefined-field, missing-fields +local Assert = require("support.assert") +package.preload["json"] = function() return require("support.json_stub") end +local Mapper = require("moonsource_douban.mapper") +local article = { posts = { + { contents = { { type = "illus", id = 8 }, { type = "headline", id = 10 }, { type = "paragraph", id = 11, data = { text = "甲" } } } }, + { contents = { { type = "pagebreak", id = 20 }, { type = "paragraph", id = 22, data = { text = "乙" } } } }, +} } +local position = Mapper.progressPosition(article, "22") +Assert.eq(position.part_sequence, 1) +Assert.eq(position.part_paragraph_sequence, 1) +Assert.eq(Mapper.progressPosition(article, "10").part_paragraph_sequence, 2) +Assert.is_nil(Mapper.progressPosition(article, "10", "11")) +Assert.is_nil(Mapper.progressPosition(article, "missing")) + +local writes, fail_article = {}, false +package.preload["moonsource_douban.client"] = function() + return { + loggedIn = function() return true end, + articleAsync = function(_aid, cb) + cb(not fail_article and article or nil, fail_article and "network failed" or nil) + return { cancel = function() end } + end, + putProgressAsync = function(works_id, pid, _idx, _total, percentage, cb, actual) + writes[#writes + 1] = { works_id = works_id, pid = pid, percentage = percentage, position = actual } + cb(true) + return { cancel = function() end } + end, + } +end +local source = require("moonsource_douban.source").new() +local slice = false +function source:loadTocAsync(_identity, cb) + cb({ + { uid = "10", content_url = "200" }, + { uid = slice and "22" or "200", content_url = "200", slice = slice }, + }) + return { cancel = function() end } +end +local ok, failure +source:putProgressAsync({ stable_id = "book", chapter_idx = 2 }, {}, function(value, err) ok, failure = value, err end) +Assert.is_true(ok) +Assert.is_nil(failure) +Assert.eq(#writes, 1) +Assert.eq(writes[1].works_id, "200") +Assert.eq(writes[1].pid, "11") +Assert.eq(writes[1].position.part_sequence, 0) +Assert.eq(writes[1].position.part_paragraph_sequence, 2) +Assert.eq(writes[1].percentage, false) +slice = true +source:putProgressAsync({ stable_id = "ebook", chapter_idx = 2 }, {}, function(value) ok = value end) +Assert.eq(writes[2].works_id, "ebook") +Assert.eq(writes[2].pid, "22") +Assert.eq(writes[2].position.part_paragraph_sequence, 1) +Assert.is_true(writes[2].percentage) +fail_article = true +source:putProgressAsync({ stable_id = "ebook", chapter_idx = 2 }, {}, function(value, err) ok, failure = value, err end) +Assert.is_nil(ok) +Assert.eq(failure, "network failed") +Assert.eq(#writes, 2) diff --git a/tests/douban/qrlogin_spec.lua b/tests/douban/qrlogin_spec.lua new file mode 100644 index 0000000..a112081 --- /dev/null +++ b/tests/douban/qrlogin_spec.lua @@ -0,0 +1,58 @@ +--[[-- +豆瓣扫码窗口:同步前段回调不能覆盖在途句柄,关闭后不再登录。 + +@module tests.moonsource_douban.qrlogin_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Themed = require("support.theme_stubs") +Themed.install() +local pending, session, calls = nil, nil, 0 +package.preload["moonsource_douban.client"] = function() + return { + newLogin = function() + session = { + cancel = function(self) self.cancelled = true end, + beginQrAsync = function(_self, cb) + cb({ qr = "https://accounts.arkread.com/oidc/qrcode/confirm?code=test", code = "test", + authorize = "https://accounts.arkread.com/oauth2/authorize", expires_in = 300 }) + return { cancel = function() end } + end, + qrStatusAsync = function(_self, code, cb) + Assert.eq(code, "test") + pending = { callback = cb } + return { cancel = function() pending.cancelled = true end } + end, + finishQrAsync = function(_self, _authorize, cb) + cb({ id = "test", name = "测试" }) + return { cancel = function() end } + end, + } + return session + end, + } +end +local QRLogin = require("moonsource_douban.qrlogin") +local login = QRLogin:new(function() calls = calls + 1 end) +login:start() +local dialog = Themed.last("qr") +Assert.is_true(dialog.shown) +dialog:close() +Assert.is_true(pending.cancelled) +Assert.is_true(session.cancelled) +pending.callback("ok") +Assert.eq(calls, 0) + +login:start() +dialog = Themed.last("qr") +pending.callback("ok") +Assert.eq(calls, 1) +Assert.is_true(dialog.closed) +Assert.eq(#Themed.all("toast"), 1) + +login:start() +pending.callback(nil, "network failed") +Assert.eq(Themed.last("confirm").text, "network failed") +Assert.is_true(Themed.last("qr").closed) +Assert.eq(calls, 1) diff --git a/tests/douban/reviews_spec.lua b/tests/douban/reviews_spec.lua new file mode 100644 index 0000000..1562b8d --- /dev/null +++ b/tests/douban/reviews_spec.lua @@ -0,0 +1,57 @@ +--[[-- +豆瓣段评的取消、同步正文回调和坏响应。 + +@module tests.moonsource_douban.reviews_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local pending, calls = nil, 0 +package.preload["moonsource_douban.client"] = function() + return { + articleAsync = function(_aid, cb) + cb({ posts = { { contents = { { type = "paragraph", id = 10, data = { text = "测试段落" } } } } } }) + return { cancel = function() end } + end, + annotationsAsync = function(_aid, _pids, cb) + pending = { callback = cb } + return { cancel = function() pending.cancelled = true end } + end, + } +end +package.preload["json"] = function() return require("support.json_stub") end +local Reviews = require("moonsource_douban.reviews") +local job = Reviews.hotspotsAsync({ content_url = "test" }, function() calls = calls + 1 end) +job.cancel() +Assert.is_true(pending.cancelled) +pending.callback({ { note = "测试批注", startContainerId = "10" } }) +Assert.eq(calls, 0) + +local result, err +Reviews.pageAsync({ content_url = "test" }, "1", function(value, reason) result, err = value, reason end) +pending.callback(nil, "network failed") +Assert.is_nil(result) +Assert.eq(err, "network failed") +Reviews.pageAsync({ content_url = "test" }, "1", function(value) result = value end) +pending.callback({}) +Assert.eq(#result.items, 0) +Assert.eq(result.more, false) + +local source = require("moonsource_douban.source").new() +function source:loadTocAsync(_identity, cb) + cb({ { content_url = "test" } }) + return { cancel = function() end } +end +for _idx, method in ipairs({ "paragraphHotspotsAsync", "paragraphReviewPageAsync" }) do + local identity = { source_id = "ext.douban", stable_id = "test", chapter_idx = 1 } + local handle + if method == "paragraphHotspotsAsync" then + handle = source:paragraphHotspotsAsync(identity, function() calls = calls + 1 end) + else + handle = source:paragraphReviewPageAsync(identity, "1", 1, function() calls = calls + 1 end) + end + handle.cancel() + Assert.is_true(pending.cancelled) + pending.callback({}) + Assert.eq(calls, 0) +end diff --git a/tests/douban/setting_spec.lua b/tests/douban/setting_spec.lua new file mode 100644 index 0000000..7acad15 --- /dev/null +++ b/tests/douban/setting_spec.lua @@ -0,0 +1,42 @@ +--[[-- +豆瓣设置开关必须重绘当前桌面,不能只写配置后留着旧的开关状态。 + +@module tests.moonsource_douban.setting_spec +--]] +local Assert = require("support.assert") +local cfg, saved, refreshed = {}, 0, 0 +package.preload["utils.settings"] = function() + return { + getSource = function() return cfg end, + saveSource = function() saved = saved + 1 end, + get = function() return {} end, + } +end +package.preload["moonsource_douban.client"] = function() return { loggedIn = function() return false end } end +package.preload["ui.themes.widgets.row"] = function() return { widget = function(opts) return opts end } end +local Setting = require("moonsource_douban.setting") +local plugin = { desktop = { updateView = function() refreshed = refreshed + 1 end } } +local function find(title) + for _idx, factory in ipairs(Setting.rows(plugin)) do + local row = factory(540) + if row.title == title then return row end + end + error("setting row missing: " .. title) +end +local row = find("显示段评") +Assert.eq(row.status, "关") +row.callback() +Assert.is_true(cfg.show_paragraph_reviews) +Assert.eq(refreshed, 1) +row = find("显示段评") +Assert.eq(row.status, "开") +row.callback() +Assert.eq(cfg.show_paragraph_reviews, false) +Assert.eq(refreshed, 2) +row = find("使用自定义分组代替分类") +Assert.eq(row.status, "开") +row.callback() +Assert.eq(cfg.category_as_group, false) +Assert.eq(refreshed, 3) +Assert.eq(find("使用自定义分组代替分类").status, "关") +Assert.eq(saved, 3) diff --git a/tests/douban/shelf_spec.lua b/tests/douban/shelf_spec.lua new file mode 100644 index 0000000..5011ccc --- /dev/null +++ b/tests/douban/shelf_spec.lua @@ -0,0 +1,135 @@ +--[[-- +豆瓣书架分组、分类口径和多阶段取消。 + +@module tests.moonsource_douban.shelf_spec +--]] +---@diagnostic disable: undefined-field, missing-fields + +local Assert = require("support.assert") +local Json = require("support.json_stub") +local cfg = { logged_in = true, user_id = "42", cookie = "session=test" } +package.preload["json"] = function() return Json end +package.preload["utils.settings"] = function() + return { getSource = function() return cfg end, get = function() return {} end } +end + +local Mapper = require("moonsource_douban.mapper") +local folders = { data = { user = { bookshelf = { folders = { list = { + { id = 20, name = "另一组", libraryList = { list = { { worksId = "1" }, { worksId = "3" } } } }, + { id = 10, name = "收藏", libraryList = { list = { { worksId = "1" } } } }, +} } } } } } +local works = { data = { worksList = { + { id = "1", title = "甲", isOrigin = true }, + { id = "2", title = "乙", isOrigin = false }, + { id = "3", title = "丙", kinds = { { shortName = "科幻" } } }, +} } } +local groups = Mapper.shelfGroups(folders, { 10, 20 }) +Assert.eq(groups["1"], "收藏") +Assert.eq(groups["3"], "另一组") +local books = Mapper.shelfWorks(works, groups, { "1", "2", "3" }) +Assert.eq(books[1].category, "收藏") +Assert.is_nil(books[2].category) +Assert.is_true(books[2].category_authoritative) +Assert.eq(books[3].category, "另一组") +cfg.category_as_group = false +books = Mapper.shelfWorks(works, groups) +Assert.eq(books[1].category, "原创") +Assert.eq(books[2].category, "出版") +Assert.eq(books[3].category, "科幻") +cfg.category_as_group = nil +Assert.is_nil(Mapper.folderIds({ folderIds = { "10", false } })) +Assert.is_nil(Mapper.folderIds({ folderIds = { unexpected = true } })) +Assert.is_nil(Mapper.folderIds({})) +Assert.eq(#Mapper.folderIds({ folderIds = {} }), 0) +Assert.is_nil(Mapper.shelfGroups(folders, { 10, 30 })) +Assert.is_nil(Mapper.shelfGroups({ errors = { { message = "denied" } }, data = folders.data }, { 10, 20 })) +Assert.is_nil(Mapper.shelfGroups({ data = { user = { bookshelf = { folders = { list = { + { id = 10, name = "收藏", libraryList = {} }, +} } } } } }, { 10 })) +Assert.is_nil(Mapper.shelfWorks({ errors = { { message = "partial" } }, data = works.data }, groups)) +Assert.is_nil(Mapper.shelfWorks(works, groups, { "1", "missing" })) +Assert.is_nil(Mapper.shelfIds({ worksIds = { "1", false } })) + +local BookDB = require("book.books_db") +Assert.is_true(BookDB.upsertRemote({ source_id = "ext.douban", stable_id = "2", title = "乙", category = "旧题材" })) +Assert.is_true(BookDB.upsertRemote(Mapper.shelfWorks(works, groups)[2])) +Assert.is_nil(BookDB.get("ext.douban", "2").category) + +local requests, deferred, defer_works = {}, false, false +local folder_wire, folder_error = { folderIds = { 10, 20 } }, nil +package.preload["http.request"] = function() + return { + header = function() end, headerAll = function() return {} end, + request = function(opts, cb) + local req = { opts = opts } + requests[#requests + 1] = req + local wire, body, err + if opts.url == "https://read.douban.com/" then body = "CSRF_TOKEN='test';" + elseif opts.url:find("/folder/", 1, true) then wire, err = folder_wire, folder_error + elseif opts.url:find("/j/bookshelf/", 1, true) then wire = { worksIds = { "1", "2", "3" } } + else + local payload = Json.decode(opts.body) + wire = payload.extensions.persistedQuery.sha256Hash == Mapper.SHELF_FOLDERS_HASH and folders or works + end + req.reply = function() cb(not err and { code = 200, body = body or Json.encode(wire) } or nil, err) end + if not deferred and not (defer_works and opts.body and opts.body:find(Mapper.SHELF_WORKS_HASH, 1, true)) then + req.reply() + end + return { cancel = function() req.cancelled = true end } + end, + } +end +local Client = require("moonsource_douban.client") +local result, failure +Client.shelfAsync(function(rows, err) result, failure = rows, err end) +Assert.eq(#result, 3) +Assert.is_nil(failure) +Assert.eq(result[1].category, "收藏") +for _idx, req in ipairs(requests) do + Assert.is_true(req.opts.method == "GET" or req.opts.url == "https://read.douban.com/j/graphql") +end +cfg.category_as_group, requests = false, {} +Client.shelfAsync(function(rows) result = rows end) +Assert.eq(result[1].category, "原创") +Assert.eq(#requests, 2) +cfg.category_as_group = nil +folder_wire = { folderIds = {} } +Client.shelfAsync(function(rows) result = rows end) +Assert.is_nil(result[1].category) +folder_wire = {} +Client.shelfAsync(function(rows, err) result, failure = rows, err end) +Assert.is_nil(result) +Assert.is_true(failure ~= nil) +folder_error = "network failed" +Client.shelfAsync(function(rows, err) result, failure = rows, err end) +Assert.is_nil(result) +Assert.eq(failure, "network failed") +folder_error, folder_wire, deferred = nil, { folderIds = { 10, 20 } }, true +for cancel_at = 0, 4 do + Client.reset() + local calls = 0 + local job = Client.shelfAsync(function() calls = calls + 1 end) + for _step = 1, cancel_at do requests[#requests].reply() end + local current, count = requests[#requests], #requests + job.cancel() + Assert.is_true(current.cancelled) + current.reply() + Assert.eq(calls, 0) + Assert.eq(#requests, count) +end +deferred, defer_works = false, true +Client.reset() +local calls = 0 +local job = Client.shelfAsync(function() calls = calls + 1 end) +local pending = requests[#requests] +job.cancel() +Assert.is_true(pending.cancelled) +pending.reply() +Assert.eq(calls, 0) +deferred, defer_works = true, false +job = Client.shelfAsync(function(rows, err) result, failure = rows, err end) +cfg.cookie = "session=other" +requests[#requests].reply() +Assert.is_nil(result) +Assert.eq(failure, "登录状态已变化,请重试") +job.cancel() diff --git a/tests/douban/stats_spec.lua b/tests/douban/stats_spec.lua new file mode 100644 index 0000000..4e19723 --- /dev/null +++ b/tests/douban/stats_spec.lua @@ -0,0 +1,82 @@ +--[[-- +豆瓣阅读时长:秒级账户快照、日期窗口、重复同步和本地未上传时长。 + +@module tests.moonsource_douban.stats_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +package.preload["json"] = function() return require("support.json_stub") end +local Mapper = require("moonsource_douban.mapper") +local StatsDB = require("book.stats_db") +local now = os.time({ year = 2026, month = 11, day = 7, hour = 15 }) +local wire = { data = { user = { + readingTimeTotal = { duration = 7200, normalDuration = 6000, textToSpeechDuration = 1200 }, + readingTimeHistory = { + { date = "2026-11-06", readingTime = { duration = 600 } }, + { date = "2026-11-07", readingTime = { duration = 1200 } }, + }, +} } } +local snapshot = Mapper.readingStats(wire, "2026-10-09", now) +Assert.eq(#snapshot.rows, 3) +Assert.eq(snapshot.rows[1].record_type, "total") +Assert.eq(snapshot.rows[1].duration, 7200) +Assert.eq(snapshot.rows[1].event_count, 0) +Assert.eq(snapshot.rows[2].duration, 600) +Assert.is_nil(Mapper.readingStats({ errors = { { message = "failed" } } }, "2026-10-09", now)) +wire.errors = { { message = "partial response" } } +Assert.is_nil(Mapper.readingStats(wire, "2026-10-09", now)) +wire.errors = nil +wire.data.user.readingTimeHistory[2].date = "2026-02-30" +Assert.is_nil(Mapper.readingStats(wire, "2026-10-09", now)) +wire.data.user.readingTimeHistory[2].date = "2026-11-06" +Assert.is_nil(Mapper.readingStats(wire, "2026-10-09", now)) +wire.data.user.readingTimeHistory[2].date = "2026-11-07" +wire.data.user.readingTimeHistory[2].readingTime.duration = -1 +Assert.is_nil(Mapper.readingStats(wire, "2026-10-09", now)) +wire.data.user.readingTimeHistory[2].readingTime.duration = 1200 + +Assert.is_true(StatsDB.removeSource("ext.douban")) +Assert.is_true(StatsDB.add({ + source_id = "ext.douban", stable_id = "test-book", record_type = "page", + start_time = now - 600, duration = 60, page = 1, total_pages = 10, +}, StatsDB.PENDING)) +Assert.is_true(StatsDB.replaceSynced("ext.douban", snapshot.replace, snapshot.rows) ~= nil) +Assert.eq(StatsDB.summaryBySource("ext.douban").total_seconds, 7260) +Assert.eq(StatsDB.dailyBySource("ext.douban")[2].seconds, 1260) +Assert.eq(#StatsDB.unsyncedBySource("ext.douban", 200), 1) +Assert.is_true(StatsDB.replaceSynced("ext.douban", snapshot.replace, snapshot.rows) ~= nil) +Assert.eq(StatsDB.summaryBySource("ext.douban").total_seconds, 7260) +wire.data.user.readingTimeHistory[1].readingTime.duration = 0 +snapshot = Mapper.readingStats(wire, "2026-10-09", now) +Assert.is_true(StatsDB.replaceSynced("ext.douban", snapshot.replace, snapshot.rows) ~= nil) +Assert.eq(#StatsDB.dailyBySource("ext.douban"), 1) +Assert.eq(StatsDB.summaryBySource("ext.douban").total_pages, 1) + +local request +package.preload["utils.settings"] = function() + return { getSource = function() return { cookie = "session=test", logged_in = true, user_id = "42" } end } +end +package.preload["http.request"] = function() + return { + headerAll = function() return {} end, + request = function(opts, cb) + request = opts + if opts.method == "GET" then cb({ code = 200, body = "CSRF_TOKEN = 'test';" }) + else cb({ code = 200, body = require("support.json_stub").encode(wire) }) end + return { cancel = function() end } + end, + } +end +local source = require("moonsource_douban.source").new() +package.loaded["utils.settings"] = nil +Assert.eq(source:capabilities().stats_pull, true) +local result +source:pullStatsAsync(function(value) result = value end) +Assert.is_true(result ~= nil) +local payload = require("support.json_stub").decode(request.body) +Assert.eq(payload.variables.userId, "42") +Assert.is_true(payload.variables.beginDate:match("^%d%d%d%d%-%d%d%-%d%d$") ~= nil) +Assert.eq(request.headers["X-CSRF-Token"], "test") +Assert.eq(payload.extensions.persistedQuery.sha256Hash, Mapper.READING_TIME_HASH) +StatsDB.removeSource("ext.douban") diff --git a/tests/douban/toc_cache_spec.lua b/tests/douban/toc_cache_spec.lua new file mode 100644 index 0000000..07c1c39 --- /dev/null +++ b/tests/douban/toc_cache_spec.lua @@ -0,0 +1,53 @@ +--[[-- +豆瓣文字格式升级:联网刷新旧的可读标记,离线继续使用旧目录。 + +@module tests.moonsource_douban.toc_cache_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +package.preload["json"] = function() return require("support.json_stub") end +local Mapper = require("moonsource_douban.mapper") +local connected, calls, saved = false, 0, 0 +local old = { { uid = "1", toc_version = Mapper.TOC_VERSION - 1, vip = true } } +local fresh = { { uid = "1", toc_version = Mapper.TOC_VERSION, vip = false } } +local cached = old +package.preload["ui/network/manager"] = function() + return { isConnected = function() return connected end } +end +package.preload["moonsource_douban.client"] = function() + return { + load = function() end, + tocAsync = function(_id, cb) + calls = calls + 1 + cb(fresh) + return { cancel = function() end } + end, + } +end +package.preload["source.toc"] = function() + return { + read = function() return cached end, + put = function(_source, _id, toc) + saved = saved + 1 + cached = toc + return true + end, + } +end +local source = require("moonsource_douban.source").new() +local identity = { source_id = "ext.douban", stable_id = "test" } +local result +source:loadTocAsync(identity, function(toc) result = toc end) +Stubs.flush() +Assert.eq(result, old) +Assert.eq(calls, 0) +Assert.eq(saved, 0) + +connected = true +source:loadTocAsync(identity, function(toc) result = toc end) +Assert.eq(result, fresh) +Assert.eq(result[1].vip, false) +Assert.eq(calls, 1) +Assert.eq(saved, 1)