commit 7273cef5e75334b2e2c1b47084a21f6721f4a9f6 Author: Garfield Date: Mon Nov 16 12:07:59 2026 +0800 ✨ 初始提交:月读第三方书源插件集合 每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> diff --git a/moonsource-qimao.koplugin/README.md b/moonsource-qimao.koplugin/README.md new file mode 100644 index 0000000..3d32a47 --- /dev/null +++ b/moonsource-qimao.koplugin/README.md @@ -0,0 +1,18 @@ +# 七猫小说 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 手机短信登录 | 已实现,未实测 | 发码前由远程网页完成数美滑块 | +| Token 导入 | 已实现,未实测 | 浏览器登录态导入或手动粘贴,保存前校验 | +| 密码与扫码登录 | 不支持 | 未提供设备入口 | +| 书架拉取 | 支持 | 登录后分页读取;真实账号流程未实测 | +| 书架新增与移出 | 已实现,未实测 | 本地先生效,联网后推送;远端删除没有读回确认 | +| 搜索 | 部分支持 | 仅第一页 | +| 分类书城 | 支持 | 动态频道、分类、子分类、排序、字数、更新时间和完结状态,支持续页 | +| 目录与正文 | 已实现,未实测 | 目录排序和章节缓存;App 风格正文解密未完成实测 | +| 已购与未购权限 | 未验证 | 不承诺付费章节可读,不绕过购买 | +| 章节缓存与离线阅读 | 支持 | 仅已成功缓存的目录和章节;设备阅读流程未实测 | +| 阅读进度同步 | 部分支持 | 仅章节位置,无章内位置;远端写入与回读未实测 | +| 笔记与统计同步 | 不支持 | 仅本地保存 | +| 书评、章评、段评与回复 | 不支持 | 当前 Web 协议未找到可验证接口,不代表 App 没有评论 | +| 账号切换 | 不支持隔离 | 缺少稳定账号绑定,换 Token 后旧待同步数据有串号风险 | diff --git a/moonsource-qimao.koplugin/_meta.lua b/moonsource-qimao.koplugin/_meta.lua new file mode 100644 index 0000000..70ca7ef --- /dev/null +++ b/moonsource-qimao.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:七猫小说"), + description = _("给月读增加「七猫小说」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-qimao.koplugin/main.lua b/moonsource-qimao.koplugin/main.lua new file mode 100644 index 0000000..caf6121 --- /dev/null +++ b/moonsource-qimao.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_qimao", + is_doc_only = false, +} diff --git a/moonsource-qimao.koplugin/moon_source.lua b/moonsource-qimao.koplugin/moon_source.lua new file mode 100644 index 0000000..0afedbb --- /dev/null +++ b/moonsource-qimao.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_qimao.source").meta() end, + new = function() return require("moonsource_qimao.source").new() end, + setting = lazy("moonsource_qimao.setting"), +} diff --git a/moonsource-qimao.koplugin/moonsource_qimao/_meta.lua b/moonsource-qimao.koplugin/moonsource_qimao/_meta.lua new file mode 100644 index 0000000..71f5ba1 --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/_meta.lua @@ -0,0 +1,15 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +@module moonsource_qimao._meta +--]] + +local _ = require("l10n").get("moonsource_qimao") + +return { + id = "ext.qimao", + name = _("七猫小说"), + type = "chapter", + description = _("七猫小说书架与在线阅读"), + abilities = { _("搜索与发现"), _("书架同步"), _("进度同步") }, +} diff --git a/moonsource-qimao.koplugin/moonsource_qimao/client.lua b/moonsource-qimao.koplugin/moonsource_qimao/client.lua new file mode 100644 index 0000000..b07beea --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/client.lua @@ -0,0 +1,249 @@ +--[[-- +七猫 App 接口 HTTP 客户端(匿名,无账号;仅异步)。 + +账号 / 书架走 PC 网页接口(`Authorization: ` + 表单,无签名);搜索、目录、正文走匿名 App 接口。 +接口回包形如 `{ data = … }`,出错为 `{ errors = { code, title } }`(HTTP 状态仍是 200)。 + +@module koplugin.book.moonsource_qimao.client +--]] + +local JSON = require("json") +local Protocol = require("moonsource_qimao.protocol") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_qimao") + +local Client = {} + +--- 解回包:data 在才算成功;errors.title 是服务端给的人话。 +---@param raw string|nil +---@param err any +---@return table|nil, string|nil +function Client.decode(raw, err) + if not raw then return nil, err and tostring(err) or _("请求失败") end + local ok, wire = pcall(JSON.decode, raw) + if not ok or type(wire) ~= "table" then return nil, _("响应无效") end + if type(wire.data) ~= "table" then + return nil, wire.errors and wire.errors.title or _("请求失败") + end + return wire +end + +local SOURCE_ID = "ext.qimao" +local USER = "https://xiaoshuo.wtzw.com" +local SHELF = "https://api-bs.wtzw.com" +local SHELF_PAGE_SIZE = 50 +-- 服务端拒绝登录态的错误码(见网页拦截器)与文案。 +local AUTH_CODES = { ["40001002"] = true, ["40003002"] = true } + +---@return string|nil +function Client.token() + local token = require("utils.settings").getSource(SOURCE_ID).token + return type(token) == "string" and token ~= "" and token or nil +end + +--- 账号接口回包:无 errors.code 即成功(同步类接口 data 可能为空串)。 +---@param token_checked string|nil 本次请求用的 token;登录请求不带 token,不改变已有登录态。 +---@param raw string|nil +---@param err any +---@return table|nil, string|nil +local function decodeAccount(raw, err, token_checked) + if not raw then return nil, err and tostring(err) or _("请求失败") end + local ok, wire = pcall(JSON.decode, raw) + if not ok or type(wire) ~= "table" then return nil, _("响应无效") end + local errors = wire.errors + if type(errors) == "table" and errors.code then + local title = errors.title or _("请求失败") + if token_checked and token_checked == Client.token() + and (AUTH_CODES[tostring(errors.code)] or tostring(title):find("登录", 1, true)) then + return nil, require("source.auth").expire(SOURCE_ID, + require("source.cookie_login").relogin(_("七猫小说"), "https://www.qimao.com/login") + .. "\n\n" .. _("点「重新登录」或打开「设置 → 书库 → 账号 → 七猫小说 → 七猫账号」,填写手机号,点「发送验证码」。扫码只做滑块,短信验证码回到设备填写。也可点「用 token 登录」保留原来的登录方式。")) + end + return nil, title + end + if token_checked and token_checked == Client.token() then require("source.auth").ok(SOURCE_ID) end + return wire +end + +---@param url string +---@param form table +---@param token string|nil +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +local function post(url, form, token, cb) + return Request.post(url, Text.formEncode(form), { + accept = "application/json", + headers = { Authorization = token }, + content_type = "application/x-www-form-urlencoded", + timeout = require("http.timeout").net(0.5), + }, function(raw, err) cb(decodeAccount(raw, err, token)) end) +end + +---@param phone string +---@param rid string 数美滑块返回的凭据;手机号留在设备。 +---@param cb fun(ok: boolean, err: string|nil) +---@return HttpJob +function Client.sendCodeAsync(phone, rid, cb) + return post(USER .. "/api/pc/v1/login/send-code", { phone = phone, rid = rid }, nil, function(wire, err) + cb(wire ~= nil, err) + end) +end + +---@param phone string +---@param code string 设备上填写的短信验证码。 +---@param cb fun(token: string|nil, err: string|nil) +---@return HttpJob +function Client.loginAsync(phone, code, cb) + return post(USER .. "/api/pc/v1/login/index", { phone = phone, code = code }, nil, function(wire, err) + if not wire then return cb(nil, err) end + local token = type(wire.data) == "table" and wire.data.token + if type(token) ~= "string" or token == "" then return cb(nil, _("七猫登录响应缺少 token")) end + cb(token) + end) +end + +--- 校验 token 并取账号信息(登录入口用,token 由调用方显式给)。 +---@param token string +---@param cb fun(user: table|nil, err: string|nil) +---@return HttpJob +function Client.userInfoAsync(token, cb) + return post(USER .. "/api/pc/v1/user/get-user-info", {}, token, function(wire, err) + if not wire then cb(nil, err); return end + if type(wire.data) ~= "table" then cb(nil, _("七猫账号信息为空")); return end + cb(wire.data) + end) +end + +--- 拉完整个人书架(分页),回调书行数组。 +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client.shelfSyncAsync(cb) + local token = Client.token() + if not token then return require("source.base").defer(cb, nil, _("未登录七猫")) end + local cancelled, job, rows = false, nil, {} + local function page(n) + job = post(SHELF .. "/pcapi/v1/user/local", { page = n, size = SHELF_PAGE_SIZE }, token, function(wire, err) + if cancelled then return end + if not wire then cb(nil, err); return end + local data = type(wire.data) == "table" and wire.data or {} + for _idx, row in ipairs(type(data.books) == "table" and data.books or {}) do rows[#rows + 1] = row end + local total = type(data.meta) == "table" and tonumber(data.meta.total_pages) or 0 + if n < total then page(n + 1) else cb(rows) end + end) + end + page(1) + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 书架增删上行;items 是网页同款条目(push_type 1 = 加 / 改,2 = 删)。 +---@param items table[] +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client.shelfPushAsync(items, cb) + local token = Client.token() + if not token then return require("source.base").defer(cb, nil, _("未登录七猫")) end + return post(SHELF .. "/pcapi/v2/user/sync", { items = JSON.encode(items) }, token, cb) +end + +---@param base string +---@param path string +---@param params table +---@param book_id string|nil 请求头版本号按它挑 +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +local function get(base, path, params, book_id, cb, cache_ttl) + return Request.get(Protocol.url(base, path, params), { + accept = "application/json", + headers = Protocol.headers(book_id), + allow_redirects = true, + timeout = require("http.timeout").net(0.5), + cache_ttl = cache_ttl, + }, function(raw, err) cb(Client.decode(raw, err)) end) +end + +---@param keyword string +---@param page integer +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +function Client.searchAsync(keyword, page, cb) + return get(Protocol.BC, "/search/v1/words", { + extend = "", tab = "0", gender = "0", refresh_state = "8", + page = page, wd = keyword, is_short_story_user = "0", + }, nil, cb) +end + +local WWW = "https://www.qimao.com" + +---@param path string +---@param params table|nil +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +local function wwwGet(path, params, cb) + local url = WWW .. path + if params then url = url .. "?" .. Text.formEncode(params) end + return Request.get(url, { + accept = "application/json", + headers = { Referer = WWW .. "/shuku/a-a-a-a-a-a-a-click-1/" }, + timeout = require("http.timeout").net(0.5), + }, function(raw, err) cb(Client.decode(raw, err)) end) +end + +--- 书库筛选项:频道、排序、分类树(匿名网页接口)。 +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +function Client.classifyOptionsAsync(cb) + return wwwGet("/api/classify/select-option", nil, cb) +end + +--- 书库列表一页(15 本)。query: channel / category1 / category2 / order / page。 +---@param query table +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +function Client.classifyAsync(query, cb) + return wwwGet("/api/classify/book-list", { + channel = query.channel, category1 = query.category1, category2 = query.category2, + order = query.order, page = query.page, words = query.words or "a", update_time = query.update_time or "a", + is_vip = "a", is_over = query.is_over or "a", + }, cb) +end + +---@param book_id string +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +function Client.detailAsync(book_id, cb) + return get(Protocol.BC, "/api/v4/book/detail", { id = book_id, imei_ip = "2937357107", teeny_mode = "0" }, book_id, cb) +end + +---@param book_id string +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +function Client.chaptersAsync(book_id, cb) + return get(Protocol.KS, "/api/v1/chapter/chapter-list", { chapter_ver = "0", id = book_id }, book_id, cb) +end + +--- 一章正文,已解密的纯文本(段落以换行分隔)。 +---@param book_id string +---@param chapter_id string +---@param cb fun(text: string|nil, err: string|nil) +---@return HttpJob +function Client.contentAsync(book_id, chapter_id, cb) + return get(Protocol.KS, "/api/v1/chapter/content", { id = book_id, chapterId = chapter_id }, book_id, function(wire, err) + local content = wire and wire.data.content + if type(content) ~= "string" or content == "" then + cb(nil, err or _("七猫章节内容为空")) + return + end + local text, decrypt_err = Protocol.decrypt(content) + if not text then + require("utils.log").warn("qimao decrypt failed", book_id, chapter_id, decrypt_err) + cb(nil, decrypt_err); return + end + cb(text) + end) +end + +return Client diff --git a/moonsource-qimao.koplugin/moonsource_qimao/l10n/en.lua b/moonsource-qimao.koplugin/moonsource_qimao/l10n/en.lua new file mode 100644 index 0000000..587e3dc --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/l10n/en.lua @@ -0,0 +1,46 @@ +return { + ["子分类"] = "Subcategory", + ["滑块加载失败,请检查网络后刷新网页"] = "Could not load the slider. Check your connection and refresh the page.", + ["更新时间"] = "Updated", + ["频道"] = "Channel", + ["字数"] = "Word count", + ["验证已过期,请重新发起验证"] = "Verification expired. Please start again", + ["点「重新登录」或打开「设置 → 书库 → 账号 → 七猫小说 → 七猫账号」,填写手机号,点「发送验证码」。扫码只做滑块,短信验证码回到设备填写。也可点「用 token 登录」保留原来的登录方式。"] = "Tap Sign in again, or open Settings → Library → Account → Qimao Novels → Qimao account. Enter your phone number and tap Send code. Scan only to solve the slider, then enter the SMS code on the device. Sign in with token remains available.", + ["正在登录…"] = "Signing in…", + ["章节目录保存失败"] = "Failed to save chapter list", + ["请先填写验证码"] = "Enter the verification code first", + ["七猫登录 token"] = "Qimao login token", + ["七猫目录为空"] = "Qimao table of contents is empty", + ["缺少七猫章节位置"] = "Missing Qimao chapter position", + ["这本书不在七猫书架上"] = "This book is not on the Qimao shelf", + ["七猫章节内容为空"] = "Qimao chapter is empty", + ["七猫账号"] = "Qimao account", + ["七猫登录响应缺少 token"] = "The Qimao sign-in response contains no token", + ["七猫滑块验证"] = "Qimao slider verification", + ["拖动下方滑块完成拼图"] = "Drag the slider below to complete the puzzle", + ["用同一 Wi-Fi 下的手机扫码,只完成滑块;短信验证码请回到设备填写。"] = "Scan with a phone on the same Wi-Fi to solve only the slider. Enter the SMS code on the device.", + ["验证通过,短信已发送,请回到设备填写验证码。"] = "Verified. The SMS has been sent. Enter the code on the device.", + ["短信已发送,请在设备上填写验证码"] = "SMS sent. Enter the code on the device", + ["手机号"] = "Phone number", + ["请填写正确的手机号"] = "Enter a valid phone number", + ["发送验证码"] = "Send code", + ["用 token 登录"] = "Sign in with token", + ["同意并继续"] = "Agree and continue", + ["未注册的手机号将自动注册七猫账号。继续即同意七猫用户协议和隐私政策。"] = "Unregistered phone numbers will create a Qimao account. Continuing means you agree to Qimao's User Agreement and Privacy Policy.", + ["七猫账号信息为空"] = "Qimao account info is empty", + ["按 F12,点「应用」里的本地存储,复制 ls_qimao_global_userinfo_data 中的 token"] = "Press F12, open Application → Local Storage, and copy the token inside ls_qimao_global_userinfo_data", + ["未登录七猫"] = "Not signed in to Qimao", + ["本地没有这本书"] = "This book is not in the local library", + ["没有读到 token"] = "No token found", + ["确定退出七猫账号?"] = "Sign out of Qimao?", + ["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "Cannot open remote verification. Connect to Wi-Fi and enable Remote management first.", + ["验证已取消"] = "Verification cancelled", + ["验证失败,请重新滑动验证"] = "Verification failed. Try the slider again.", + ["验证凭据无效"] = "Invalid verification proof", + ["正在提交验证…"] = "Submitting verification…", + ["重试"] = "Retry", + ["七猫小说书架与在线阅读"] = "Qimao shelf and online reading", + ["书架同步"] = "Shelf sync", + ["搜索与发现"] = "Search and discover", + ["进度同步"] = "Progress sync", +} diff --git a/moonsource-qimao.koplugin/moonsource_qimao/l10n/zh_TW.lua b/moonsource-qimao.koplugin/moonsource_qimao/l10n/zh_TW.lua new file mode 100644 index 0000000..eabe2dd --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/l10n/zh_TW.lua @@ -0,0 +1,46 @@ +return { + ["子分类"] = "子分類", + ["滑块加载失败,请检查网络后刷新网页"] = "滑塊載入失敗,請檢查網路後重新整理網頁", + ["更新时间"] = "更新時間", + ["频道"] = "頻道", + ["字数"] = "字數", + ["验证已过期,请重新发起验证"] = "驗證已過期,請重新發起驗證", + ["点「重新登录」或打开「设置 → 书库 → 账号 → 七猫小说 → 七猫账号」,填写手机号,点「发送验证码」。扫码只做滑块,短信验证码回到设备填写。也可点「用 token 登录」保留原来的登录方式。"] = "點「重新登入」或打開「設定 → 書庫 → 帳號 → 七貓小說 → 七貓帳號」,填寫手機號碼,點「傳送驗證碼」。掃碼只做滑塊,簡訊驗證碼回到裝置填寫。也可點「用 token 登入」保留原來的登入方式。", + ["正在登录…"] = "正在登入…", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["请先填写验证码"] = "請先填寫驗證碼", + ["七猫登录 token"] = "七貓登入 token", + ["七猫目录为空"] = "七貓目錄為空", + ["缺少七猫章节位置"] = "缺少七貓章節位置", + ["这本书不在七猫书架上"] = "這本書不在七貓書架上", + ["七猫章节内容为空"] = "七貓章節內容為空", + ["七猫账号"] = "七貓帳號", + ["七猫登录响应缺少 token"] = "七貓登入回應缺少 token", + ["七猫滑块验证"] = "七貓滑塊驗證", + ["拖动下方滑块完成拼图"] = "拖動下方滑塊完成拼圖", + ["用同一 Wi-Fi 下的手机扫码,只完成滑块;短信验证码请回到设备填写。"] = "用同一 Wi-Fi 下的手機掃碼,只完成滑塊;簡訊驗證碼請回到裝置填寫。", + ["验证通过,短信已发送,请回到设备填写验证码。"] = "驗證通過,簡訊已傳送,請回到裝置填寫驗證碼。", + ["短信已发送,请在设备上填写验证码"] = "簡訊已傳送,請在裝置上填寫驗證碼", + ["手机号"] = "手機號碼", + ["请填写正确的手机号"] = "請填寫正確的手機號碼", + ["发送验证码"] = "傳送驗證碼", + ["用 token 登录"] = "用 token 登入", + ["同意并继续"] = "同意並繼續", + ["未注册的手机号将自动注册七猫账号。继续即同意七猫用户协议和隐私政策。"] = "未註冊的手機號碼將自動註冊七貓帳號。繼續即同意七貓使用者協議和隱私政策。", + ["七猫账号信息为空"] = "七貓帳號資訊為空", + ["按 F12,点「应用」里的本地存储,复制 ls_qimao_global_userinfo_data 中的 token"] = "按 F12,點「應用」裡的本機儲存,複製 ls_qimao_global_userinfo_data 中的 token", + ["未登录七猫"] = "未登入七貓", + ["本地没有这本书"] = "本機沒有這本書", + ["没有读到 token"] = "沒有讀到 token", + ["确定退出七猫账号?"] = "確定登出七貓帳號?", + ["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "無法打開遠端驗證,請先連接 Wi-Fi 並啟用遠端管理功能", + ["验证已取消"] = "驗證已取消", + ["验证失败,请重新滑动验证"] = "驗證失敗,請重新滑動驗證", + ["验证凭据无效"] = "驗證憑據無效", + ["正在提交验证…"] = "正在提交驗證…", + ["重试"] = "重試", + ["七猫小说书架与在线阅读"] = "七貓小說書架與線上閱讀", + ["书架同步"] = "書架同步", + ["搜索与发现"] = "搜尋與發現", + ["进度同步"] = "進度同步", +} diff --git a/moonsource-qimao.koplugin/moonsource_qimao/loadmeta.lua b/moonsource-qimao.koplugin/moonsource_qimao/loadmeta.lua new file mode 100644 index 0000000..c047b0c --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_qimao._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-qimao.koplugin/moonsource_qimao/mapper.lua b/moonsource-qimao.koplugin/moonsource_qimao/mapper.lua new file mode 100644 index 0000000..75b922c --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/mapper.lua @@ -0,0 +1,150 @@ +--[[-- +七猫 App 接口数据映射(纯函数)。 + +@module koplugin.book.moonsource_qimao.mapper +--]] + +local Text = require("utils.text") + +local Mapper = {} + +local SOURCE_ID = "ext.qimao" + +local CDN = "https://cdn.wtzw.com" + +--- 书架行的封面是 `/bookimg/…` 相对路径。 +---@param link string|nil +---@return string|nil +local function cover(link) + if type(link) == "string" and link:sub(1, 1) == "/" then return CDN .. link end + return link +end + +--- 搜索 / 详情行用 id、title;个人书架行用 book_id、book_title。 +---@param row table +---@return Book|nil +local function book(row) + local raw = row.id or row.book_id + local id = raw and tostring(raw) + if not id or id == "" then return nil end + return { + source_id = SOURCE_ID, + stable_id = id, + title = row.original_title or row.title or row.book_title, + authors = row.original_author or row.author, + category = row.category2_name or row.ptags, + intro = row.intro and Text.stripHtml(row.intro), + cover = cover(row.image_link), + } +end + +--- 个人书架行 → Book[]。 +---@param rows table[] +---@return Book[] +function Mapper.shelfList(rows) + local out = {} + for _idx, row in ipairs(rows) do out[#out + 1] = book(row) end + return out +end + +--- 本地书 → 书架同步条目(网页「加入书架」同款字段,图片只留 /bookimg/ 路径)。 +---@param stable_id string +---@param row Book +---@param push_type "1"|"2" +---@return table +function Mapper.shelfItem(stable_id, row, push_type) + local image = tostring(row.cover or ""):match("/bookimg/.*$") or "" + return { + book_id = stable_id, + book_title = row.title or "", + author = row.authors or "", + image_link = image, + push_type = push_type, + add_type = "1", + is_voice = "0", + page_offset = "", + alias_title = "", + group_name = "", + chapter_ver = "0", + latest_read_chapter_id = "", + latest_read_chapter_name = "", + updated_at = tostring(os.time()), + } +end + +--- 书架行里的阅读位置。没有章号就是没读过。 +---@param row table|nil +---@return { uid: string, title: string|nil }|nil +function Mapper.readChapter(row) + if type(row) ~= "table" then return nil end + local uid = row.latest_read_chapter_id + if uid == nil or tostring(uid) == "" or tonumber(uid) == 0 then return nil end + local title = row.latest_read_chapter_name + return { uid = tostring(uid), title = type(title) == "string" and title or nil } +end + +--- 用书架上的原行改阅读位置再上行,避免空字段把书名、分组清掉。 +--- 章没变就留着原来的段内偏移;换章则清掉,段内位置同步不了。 +---@param row table +---@param chapter { uid: string, title: string|nil, idx: integer } +---@return table +function Mapper.progressItem(row, chapter) + local item = {} + for key, value in pairs(row) do item[key] = value end + local same = tostring(row.latest_read_chapter_id or "") == chapter.uid + item.push_type = "1" + item.latest_read_chapter_id = chapter.uid + item.latest_read_chapter_name = chapter.title or "" + item.latest_read_chapter_index = tostring(chapter.idx) + item.updated_at = tostring(os.time()) + if not same then + item.page_offset = "" + item.paragraph_index = "0" + end + return item +end + +--- 搜索回包。高亮标签只出现在 title / author,原始值在 original_*。 +---@param wire table|nil +---@return Book[] +function Mapper.search(wire) + local rows = wire and wire.data and wire.data.books + local out = {} + for _idx, row in ipairs(type(rows) == "table" and rows or {}) do + out[#out + 1] = book(row) + end + return out +end + +--- 书库列表 → Book[],并给出是否还有下一页。 +---@param wire table|nil +---@return Book[], boolean +function Mapper.classify(wire) + local data = wire and wire.data or {} + local out = {} + for _idx, row in ipairs(type(data.book_list) == "table" and data.book_list or {}) do + out[#out + 1] = book(row) + end + local paging = data.page_data or {} + return out, (tonumber(paging.page) or 0) * (tonumber(paging.page_size) or 0) < (tonumber(paging.count) or 0) +end + +--- 目录:按 chapter_sort 排,idx 连续;章节 id 是 uid。 +---@param wire table|nil +---@return BookChapter[] +function Mapper.toc(wire) + local rows = wire and wire.data and wire.data.chapter_lists + rows = type(rows) == "table" and rows or {} + local sorted = {} + for _idx, row in ipairs(rows) do + if row.id then sorted[#sorted + 1] = row end + end + table.sort(sorted, function(a, b) return (tonumber(a.chapter_sort) or 0) < (tonumber(b.chapter_sort) or 0) end) + local toc = {} + for i, row in ipairs(sorted) do + toc[i] = { idx = i, uid = tostring(row.id), title = row.title, words = tonumber(row.words) } + end + return toc +end + +return Mapper diff --git a/moonsource-qimao.koplugin/moonsource_qimao/protocol.lua b/moonsource-qimao.koplugin/moonsource_qimao/protocol.lua new file mode 100644 index 0000000..901e759 --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/protocol.lua @@ -0,0 +1,78 @@ +--[[-- +七猫 App 接口协议:请求签名与正文解密(纯函数,零 KOReader 依赖)。 + +签名 = md5(按键名排序的 `k=v` 直接拼接 .. SIGN_KEY),请求头和查询参数各签一次(请求头里的 sign 不参与查询签名)。 +正文 content 是 base64,前 16 字节为 IV,其余为 AES-128-CBC(PKCS7) 密文,密钥固定。 + +@module koplugin.book.moonsource_qimao.protocol +--]] + +local Aes = require("crypto.aes") +local Hex = require("crypto.hex") +local Text = require("utils.text") +local md5 = require("ffi/sha2").md5 + +local Protocol = {} + +local SIGN_KEY = "d3dGiJc651gSQ8w1" +local AES_KEY = Hex.from_hex("32343263636238323330643730396531") +local VERSIONS = { "73720", "73700", "73620", "73600", "73500", "73420", "73400", "73328", "73325", "73320" } + +Protocol.BC = "https://api-bc.wtzw.com" +Protocol.KS = "https://api-ks.wtzw.com" + +---@param params table +---@return string +function Protocol.sign(params) + local keys = {} + for k in pairs(params) do keys[#keys + 1] = k end + table.sort(keys) + local parts = {} + for i, k in ipairs(keys) do parts[i] = k .. "=" .. tostring(params[k]) end + return md5(table.concat(parts) .. SIGN_KEY) --[[@as string]] +end + +--- 带签名的请求头。版本号只是风控里的取值,按书号稳定挑一个,同一本书请求头不变。 +---@param book_id string|nil +---@return table +function Protocol.headers(book_id) + local seed = 0 + for i = 1, #(book_id or "") do seed = seed + book_id:byte(i) end + local headers = { + ["AUTHORIZATION"] = "", + ["app-version"] = VERSIONS[seed % #VERSIONS + 1], + ["application-id"] = "com.****.reader", + ["channel"] = "unknown", + ["net-env"] = "1", + ["platform"] = "android", + ["qm-params"] = "", + ["reg"] = "0", + } + headers.sign = Protocol.sign(headers) + return headers +end + +--- 带签名的完整 URL。 +---@param base string +---@param path string +---@param params table +---@return string +function Protocol.url(base, path, params) + local query = {} + for k, v in pairs(params) do query[k] = tostring(v) end + query.sign = Protocol.sign(query) + return base .. path .. "?" .. Text.formEncode(query) +end + +--- 解密 chapter/content 的 data.content。 +---@param content string base64 +---@return string|nil, string|nil +function Protocol.decrypt(content) + local raw = Text.base64Decode(content) + if #raw <= 16 or (#raw - 16) % 16 ~= 0 then return nil, "bad content" end + local ok, plain = pcall(Aes.cbc_decrypt, raw:sub(17), AES_KEY, raw:sub(1, 16)) + if not ok then return nil, "decrypt failed" end + return plain +end + +return Protocol diff --git a/moonsource-qimao.koplugin/moonsource_qimao/setting.lua b/moonsource-qimao.koplugin/moonsource_qimao/setting.lua new file mode 100644 index 0000000..839b67d --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/setting.lua @@ -0,0 +1,219 @@ +--[[-- +七猫源设置:登录。 + +手机号与短信验证码在设备上填写,发送短信前的数美滑块经远程管理桥接。 +登录态仍是网页 token(`Authorization`);保留原来的 token 导入,保存前向服务端校验。 + +@module koplugin.book.moonsource_qimao.setting +--]] + +local _ = require("l10n").get("moonsource_qimao") + +local SOURCE_ID = "ext.qimao" +local Setting = {} + +---@return boolean +local function loggedIn() + return require("moonsource_qimao.client").token() ~= nil +end + +---@return string, boolean +function Setting.rowStatus() + local on = loggedIn() + return on and _("已登录") or _("未登录 · 点此登录"), on +end + +--- 接受裸 token,或浏览器 localStorage `ls_qimao_global_userinfo_data` 的整段 JSON。 +---@param input string +---@return string +function Setting.parseToken(input) + local text = require("utils.text").trim(input) + if text:sub(1, 1) == "{" then + local ok, data = pcall(require("json").decode, text) + return ok and type(data) == "table" and type(data.token) == "string" and data.token or "" + end + return (text:gsub("^[Bb]earer%s+", "")) +end + +--- 向服务端校验 token,通过才保存并重载源。 +---@param token string +---@param cb fun(ok: boolean, err: string|nil) +local function saveToken(token, cb) + require("moonsource_qimao.client").userInfoAsync(token, function(user, err) + if not user then return cb(false, err or _("登录失败")) end + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + local function commit() + cfg.token = token + settings.saveSource(SOURCE_ID, cfg) + end + if cfg.token ~= token then + if not require("source.logout").replaceLibrary(SOURCE_ID, commit) then + return cb(false, _("准备本地同步失败")) + end + else + commit() + end + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() + cb(true) + end) +end + +---@param token string +local function verify(token) + local Toast = require("ui.themes.widgets.toast") + require("ui/network/manager"):runWhenConnected(function() + local waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("七猫账号"), text = _("正在校验登录…"), dismissable = false, + } + waiting:show() + saveToken(token, function(ok, err) + waiting:close() + Toast:new{ text = ok and _("登录成功") or err, timeout = ok and 2 or 3 }:show() + end) + end) +end + +--- 浏览器扩展登录(features/cookie):登录态在 localStorage 的用户信息里。 +Setting.browser = { + domain = "www.qimao.com", + scope = "local", + login = "https://www.qimao.com/login", + check = "https://www.qimao.com/user/bookshelf", + icon = "https://cdn-front.qimao.com/global/static/images/favicon2022.ico", + isAuthorized = function() + return loggedIn() and not require("source.auth").expired(SOURCE_ID) + end, + apply = function(payload, cb) + local storage = payload["local"] + local raw = type(storage) == "table" and storage.ls_qimao_global_userinfo_data + local token = type(raw) == "string" and Setting.parseToken(raw) or "" + if token == "" then return cb(false, _("没有读到 token")) end + saveToken(token, cb) + end, +} + +local function showTokenLogin() + require("ui.themes.widgets.input"):new{ + title = _("七猫登录 token"), + fields = { { text = "", hint = _("按 F12,点「应用」里的本地存储,复制 ls_qimao_global_userinfo_data 中的 token") } }, + ok_text = _("登录"), + callback = function(value) + local token = Setting.parseToken(value or "") + if token == "" then + require("ui.themes.widgets.toast"):new{ text = _("没有读到 token"), timeout = 3 }:show() + return + end + verify(token) + end, + }:show() +end + +local function showLogin() + local Toast = require("ui.themes.widgets.toast") + local verification, dialog + local agreed, closed = false, false + local function consent(run) + if agreed then return run() end + require("ui.themes.widgets.confirm"):new{ + title = _("七猫账号"), + text = _("未注册的手机号将自动注册七猫账号。继续即同意七猫用户协议和隐私政策。") + .. "\nhttps://www.qimao.com/user_agreed.html\nhttps://www.qimao.com/privacy_agreed.html", + ok_text = _("同意并继续"), + ok_callback = function() agreed = true; run() end, + }:show() + end + local function validPhone(phone) + if #phone == 11 and phone:match("^1%d+$") then return true end + Toast:new{ text = _("请填写正确的手机号"), timeout = 3 }:show() + return false + end + dialog = require("ui.themes.widgets.input"):new{ + title = _("七猫账号"), + fields = { + { label = _("手机号"), text = "", input_type = "number" }, + { label = _("验证码"), text = "", input_type = "number" }, + }, + ok_text = _("登录"), + close_callback = function() + closed = true + if verification then verification:cancel() end + end, + actions = { + { text = _("发送验证码"), callback = function(phone) + phone = require("utils.text").trim(phone) + if not validPhone(phone) then return end + consent(function() + require("ui/network/manager"):runWhenConnected(function() + if closed then return end + if verification then verification:cancel() end + verification = require("moonsource_qimao.verify").new(phone, function(ok, err) + Toast:new{ text = ok and _("短信已发送,请在设备上填写验证码") or err, timeout = 3 }:show() + end) + end) + end) + end }, + }, + callback = function(phone, code) + phone, code = require("utils.text").trim(phone), require("utils.text").trim(code) + if not validPhone(phone) then return end + if code == "" then + Toast:new{ text = _("请先填写验证码"), timeout = 3 }:show() + return + end + consent(function() + require("ui/network/manager"):runWhenConnected(function() + local waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("七猫账号"), text = _("正在登录…"), dismissable = false, + } + waiting:show() + require("moonsource_qimao.client").loginAsync(phone, code, function(token, err) + if not token then + waiting:close() + Toast:new{ text = err, timeout = 3 }:show() + return + end + saveToken(token, function(ok, message) + waiting:close() + Toast:new{ text = ok and _("登录成功") or message, timeout = ok and 2 or 3 }:show() + end) + end) + end) + end) + end, + } + dialog:show() +end + +---@return table[] +function Setting.rows() + local Row = require("ui.themes.widgets.row") + local CookieLogin = require("source.cookie_login") + local rows = { + function(iw) + local status, status_on = Setting.rowStatus() + return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "account_circle", + title = _("七猫账号"), status = status, status_on = status_on, + callback = function() showLogin() end }) + end, + CookieLogin.browserRow(), + function(iw) + return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "key", + title = _("用 token 登录"), callback = showTokenLogin }) + end, + } + if not loggedIn() then return rows end + rows[#rows + 1] = require("source.logout").row(SOURCE_ID, _("确定退出七猫账号?"), function() + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + cfg.token = nil + settings.saveSource(SOURCE_ID, cfg) + end) + return rows +end + +--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。 +Setting.login = showLogin + +return Setting diff --git a/moonsource-qimao.koplugin/moonsource_qimao/source.lua b/moonsource-qimao.koplugin/moonsource_qimao/source.lua new file mode 100644 index 0000000..323f3cf --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/source.lua @@ -0,0 +1,324 @@ +--[[-- +七猫免费小说数据源。 + +搜索 / 目录 / 正文走匿名 App 接口(protocol / client,正文解密,按章落盘走公共 source/chapter); +登录是 PC 网页的 token(setting.lua),登录后书架双向同步(source.shelf,网页书架接口)。 +进度只到章:开书从书架行的 latest_read_chapter_id 拉,关书用同一条书架同步接口改这一行。 +笔记和统计没有接口。书由书城页按源搜索后加入本地书库。 + +@module moonsource_qimao +--]] + +local Browse = require("source.browse") +local Client = require("moonsource_qimao.client") +local Mapper = require("moonsource_qimao.mapper") +local Shelf = require("source.shelf") +local SourceBase = require("source.base") +local Toc = require("source.toc") +local _ = require("l10n").get("moonsource_qimao") + +local Qimao = {} + +-- 匿名接口按 IP 限流,预取与整本缓存逐章间隔请求。 +local FETCH_INTERVAL = 1 + +---@class QimaoRequestState +---@field cancelled boolean +---@field step integer +---@field job { cancel: fun() }|nil +--- 同步回调启动下一阶段时,旧请求返回后不能覆盖新句柄。 +---@param state QimaoRequestState +---@param request fun(): { cancel: fun() }|nil +local function startStep(state, request) + state.step = state.step + 1 + local step = state.step + local job = request() + if state.step == step then state.job = job end +end + +---@return BookSourceMeta +function Qimao.meta() + return require("moonsource_qimao.loadmeta")() +end + +---@class QimaoSource : SourceBase +local Source = setmetatable({ shelf_add = true }, { __index = SourceBase }) +Source.__index = Source + +---@return QimaoSource +function Qimao.new() + local meta = Qimao.meta() + return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source) +end + +---@return boolean +function Source:configured() + return Client.token() ~= nil +end + +--- 书架远端:Shelf.syncAsync 要的三个冒号方法,都是 Client 的网页书架接口。 +local Remote = {} + +function Remote:shelfSyncAsync(cb) return Client.shelfSyncAsync(cb) end + +function Remote:addToShelfAsync(stable_id, cb) + local row = require("book.books_db").get(Qimao.meta().id, stable_id) + if not row then return SourceBase.defer(cb, nil, _("本地没有这本书")) end + return Client.shelfPushAsync({ Mapper.shelfItem(stable_id, row, "1") }, cb) +end + +function Remote:removeFromShelfAsync(stable_id, cb) + return Client.shelfPushAsync({ { book_id = stable_id, updated_at = tostring(os.time()), push_type = "2" } }, cb) +end + +function Source:syncBooksAsync(opts, cb) + if not self:configured() then return SourceBase.skipped(cb, "qimao not logged in") end + return Shelf.syncAsync(self.id, Remote, Mapper.shelfList, opts, cb) +end + +function Source:getProgressAsync(identity, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录七猫")) end + ---@type QimaoRequestState + local state = { cancelled = false, step = 0 } + startStep(state, function() return Client.shelfSyncAsync(function(rows, err) + if state.cancelled then return end + if not rows then cb(nil, err); return end + local row + for _idx, item in ipairs(rows) do + if tostring(item.book_id) == tostring(identity.stable_id) then row = item; break end + end + local read = Mapper.readChapter(row) + if not read then cb(nil, nil, { empty = true }); return end + startStep(state, function() return self:loadTocAsync(identity, function(toc, reason) + if state.cancelled then return end + if not toc or #toc == 0 then cb(nil, reason or _("七猫目录为空")); return end + local idx = Toc.index(self.id, identity.stable_id, read.uid) + if not idx then cb(nil, nil, { empty = true }); return end + cb({ + chapter_idx = idx, + chapter_title = read.title, + fraction = (idx - 1) / #toc, + extra = { chapter_uid = read.uid, chapter_idx = idx }, + }) + end) end) + end) end) + return { cancel = function() + state.cancelled = true + if state.job and state.job.cancel then state.job.cancel() end + end } +end + +function Source:putProgressAsync(identity, pos, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录七猫")) end + ---@type QimaoRequestState + local state = { cancelled = false, step = 0 } + startStep(state, function() return self:loadTocAsync(identity, function(toc, err) + if state.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 or not chapter.uid then + cb(nil, _("缺少七猫章节位置")) + return + end + startStep(state, function() return Client.shelfSyncAsync(function(rows, reason) + if state.cancelled then return end + if not rows then cb(nil, reason); return end + local row + for _item, item in ipairs(rows) do + if tostring(item.book_id) == tostring(identity.stable_id) then row = item; break end + end + if not row then cb(nil, _("这本书不在七猫书架上")); return end + startStep(state, function() return Client.shelfPushAsync({ Mapper.progressItem(row, { + uid = chapter.uid, title = chapter.title, idx = idx, + }) }, function(wire, push_err) + if state.cancelled then return end + cb(wire and true or nil, push_err) + end) end) + end) end) + end) end) + return { cancel = function() + state.cancelled = true + if state.job and state.job.cancel then state.job.cancel() end + end } +end + +--- 书城搜索:匿名接口,只取第一页。 +---@param keyword string +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Source:searchAsync(keyword, cb) + return Client.searchAsync(keyword, 1, function(wire, err) + if not wire then + cb(nil, err) + return + end + cb({ data = Mapper.search(wire) }) + end) +end + +--- 书城浏览:筛选项来自书库接口,节点是「频道:分类:子分类:排序:字数:更新时间:状态」, +--- 缺省男生原创按点击量;选项每次都调 client,新鲜度由数据获取层缓存(source.store_cache)管。 +---@param opts { node?: string, limit?: integer } +---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil) +---@return { cancel: fun() } +function Source:browseAsync(opts, cb) + local handle = {} + -- 回调同步完成时 load 已换上在途句柄,外层赋值不能再覆盖(同 jdread 的 mine 记法)。 + local step = 0 + local function load(options) + step = step + 1 + -- 七段:频道:分类:子分类:排序:字数:更新时间:状态;兼容旧的四段节点。 + local channel, cat1, cat2, order, words, update_time, is_over = + (opts.node or ""):match("^([%w_]+):([%w_]+):([%w_]+):([%w_]+):([%w_]+):([%w_]+):([%w_]+)$") + if not channel then + channel, cat1, cat2, order = (opts.node or ""):match("^([%w_]+):([%w_]+):([%w_]+):([%w_]+)$") + words, update_time, is_over = "a", "a", "a" + end + if not channel then + channel, cat1, cat2, order, words, update_time, is_over = "0", "a", "a", "click", "a", "a", "a" + end + local function nodeFor(_channel, _cat1, _cat2, _order, _words, _update_time, _is_over) + return table.concat({ _channel, _cat1, _cat2, _order, _words, _update_time, _is_over }, ":") + end + local function chips(rows, id_of, include_all) + local out = {} + for _idx, row in ipairs(rows) do + if include_all or row.value ~= "a" then + out[#out + 1] = { id = id_of(row.value), title = row.label } + end + end + return out + end + local orders = chips(options.filters.order, function(v) return nodeFor(channel, cat1, cat2, v, words, update_time, is_over) end) + local channels = chips(options.filters.channel, function(v) return nodeFor(v, "a", "a", order, words, update_time, is_over) end) + local word_counts = chips(options.filters.words, function(v) return nodeFor(channel, cat1, cat2, order, v, update_time, is_over) end, true) + local update_times = chips(options.filters.update_time, function(v) return nodeFor(channel, cat1, cat2, order, words, v, is_over) end, true) + local completion = chips(options.filters.is_over, function(v) return nodeFor(channel, cat1, cat2, order, words, update_time, v) end, true) + local tops, subs = { { id = nodeFor(channel, "a", "a", order, words, update_time, is_over), title = _("全部") } }, nil + for _idx, cat in ipairs(options.category) do + if cat.type == channel then + tops[#tops + 1] = { id = nodeFor(channel, cat.id, "a", order, words, update_time, is_over), title = cat.name } + if cat.id == cat1 then + subs = { { id = nodeFor(channel, cat1, "a", order, words, update_time, is_over), title = _("全部") } } + for _idx2, sub in ipairs(cat.children) do + subs[#subs + 1] = { id = nodeFor(channel, cat1, sub.id, order, words, update_time, is_over), title = sub.name } + end + end + end + end + local node = nodeFor(channel, cat1, cat2, order, words, update_time, is_over) + local groups = { Browse.group(orders, node), + Browse.group(channels, nodeFor(channel, "a", "a", order, words, update_time, is_over)), + Browse.group(tops, nodeFor(channel, cat1, "a", order, words, update_time, is_over)) } + groups[1].title, groups[2].title, groups[3].title = _("排序"), _("频道"), _("分类") + if subs then groups[4] = Browse.group(subs, node) end + if subs then groups[4].title = _("子分类") end + groups[#groups + 1] = Browse.group(word_counts, node) + groups[#groups].title = _("字数") + groups[#groups + 1] = Browse.group(update_times, node) + groups[#groups].title = _("更新时间") + groups[#groups + 1] = Browse.group(completion, node) + groups[#groups].title = _("状态") + handle.inner = Browse.pages(function(page, done) + return Client.classifyAsync({ + channel = channel, category1 = cat1, category2 = cat2, order = order, + words = words, update_time = update_time, is_over = is_over, page = page, + }, + function(wire, err) + if not wire then + done(nil, err) + return + end + local books, more = Mapper.classify(wire) + done(books, nil, more) + end) + end, opts.limit or 60, groups, cb) + end + local first = Client.classifyOptionsAsync(function(wire, err) + if not wire then + cb(nil, err) + return + end + load(wire.data) + end) + if step == 0 then handle.inner = first end + function handle.cancel() + if handle.inner then handle.inner.cancel() end + end + return handle +end + +--- 书库里已有的元数据;详情只在书城预览时才需要拉。 +function Source:getDetailAsync(identity, cb) + return SourceBase.defer(cb, identity.book or require("book.books_db").get(self.id, identity.stable_id)) +end + +--- 强制拉目录并写回;失败由调用方继续用旧缓存。 +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +---@return { cancel: fun() } +local function fetchTocAsync(self, identity, cb) + local cancelled, job = false, nil + job = Client.chaptersAsync(identity.stable_id, function(wire, err) + if cancelled then return end + local toc = wire and Mapper.toc(wire) + 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) + return { cancel = function() + cancelled = true + job.cancel() + end } +end + +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +---@param force boolean|nil 真=跳过缓存强制拉 +---@return { cancel: fun() } +function Source:loadTocAsync(identity, cb, force) + if not force then + local cached = Toc.read(self.id, identity.stable_id) + if cached and #cached > 0 then + return SourceBase.defer(cb, cached) + end + end + return fetchTocAsync(self, identity, cb) +end + +Source.refreshTocAsync = fetchTocAsync + +---@return ChapterFetchContent +local function contentFetcher() + return function(identity, chapter, done) + return Client.contentAsync(identity.stable_id, chapter.uid, function(text, err) + if not text then done(nil, err); return end + done({ title = chapter.title, html = require("utils.text").chapterHtml(chapter.title, text) }) + end) + 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 = contentFetcher(), + }, cb) +end + +function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb) + return require("source.chapter").prefetchAsync(identity, identity.book, toc, from_idx, count, { + fetchContent = contentFetcher(), + interval_seconds = FETCH_INTERVAL, + }, cb) +end + +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + return require("source.chapter").cacheAllAsync(self, identity, contentFetcher(), on_progress, cb, + FETCH_INTERVAL, range) +end + +return Qimao diff --git a/moonsource-qimao.koplugin/moonsource_qimao/verify.lua b/moonsource-qimao.koplugin/moonsource_qimao/verify.lua new file mode 100644 index 0000000..7b5b64d --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/verify.lua @@ -0,0 +1,117 @@ +--[[-- +七猫发送短信前的数美滑块:浏览器只交 rid,手机号与短信码留在设备。 +一次发送拥有一张五分钟票据,关闭输入窗或二维码即取消;成功发送后票据作废。 + +@module koplugin.book.moonsource_qimao.verify +--]] + + +local Ext = require("utils.extension") +local Client = require("moonsource_qimao.client") +local _ = require("l10n").get("moonsource_qimao") + +---@class QimaoVerification +---@field ticket string +---@field phone string +---@field token string|nil +---@field callback fun(ok: boolean, err: string|nil) +---@field expires integer +---@field dialog BookThemeQR|nil +---@field pending table|nil +---@field timeout function +---@field done boolean|nil +local Verification = {} +Verification.__index = Verification + +---@type table +local sessions = {} + +function Verification:cancel() + if self.done then return end + self.done = true + sessions[self.ticket] = nil + require("ui/uimanager"):unschedule(self.timeout) + if self.pending and self.pending.job then self.pending.job:cancel() end + if self.dialog then self.dialog:close() end +end + +function Verification:finish(ok, err) + if self.done then return end + self:cancel() + self.callback(ok, err) +end + +---@param phone string +---@param cb fun(ok: boolean, err: string|nil) +---@return QimaoVerification +function Verification.new(phone, cb) + local self = setmetatable({ + ticket = require("utils.random").hex(24), phone = phone, token = Client.token(), + callback = cb, expires = os.time() + 300, + }, Verification) + self.timeout = require("ui.guard").wrap("qimao verification timeout", function() + self:finish(false, _("验证已过期,请重新发起验证")) + end) + sessions[self.ticket] = self + require("ui/uimanager"):scheduleIn(300, self.timeout) + self.dialog = Ext.call("web.open_page", "/qimao_verify.html#" .. self.ticket, + _("七猫滑块验证"), _("用同一 Wi-Fi 下的手机扫码,只完成滑块;短信验证码请回到设备填写。"), { + close_callback = function() self:finish(false, _("验证已取消")) end, + }) + if not self.dialog then + self:finish(false, _("无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能")) + end + return self +end + +---@param method string +---@param action string +---@param params table +---@param cb fun(status: integer, body: table, headers: string[]|nil) +local function handle(method, action, params, cb) + local function reply(status, body) + cb(status, body, { "Cache-Control: no-store" }) + end + if method ~= "POST" then return reply(405, { error = "Method Not Allowed" }) end + if action ~= "config" and action ~= "verify" then return reply(404, { error = "Not Found" }) end + local session = type(params.ticket) == "string" and sessions[params.ticket] + if not session or os.time() >= session.expires or session.token ~= Client.token() then + return reply(403, { error = _("验证已过期,请重新发起验证") }) + end + if action == "config" then + return reply(200, { + title = _("七猫滑块验证"), instruction = _("拖动下方滑块完成拼图"), + pending = _("正在提交验证…"), + success = _("验证通过,短信已发送,请回到设备填写验证码。"), + failure = _("验证失败,请重新滑动验证"), + load_error = _("滑块加载失败,请检查网络后刷新网页"), retry = _("重试"), + }) + end + if type(params.rid) ~= "string" or params.rid == "" or #params.rid > 1024 then + return reply(400, { error = _("验证凭据无效") }) + end + if session.pending then return reply(409, { error = _("正在提交验证…") }) end + local operation = {} + session.pending = operation + operation.job = Client.sendCodeAsync(session.phone, params.rid, function(ok, err) + if session.done then return reply(403, { error = _("验证已过期,请重新发起验证") }) end + if session.pending ~= operation then return end + if os.time() >= session.expires or session.token ~= Client.token() then + session:finish(false, _("验证已过期,请重新发起验证")) + return reply(403, { error = _("验证已过期,请重新发起验证") }) + end + session.pending = nil + if not ok then return reply(400, { error = err or _("验证失败,请重新滑动验证") }) end + reply(200, { ok = true }) + session:finish(true) + end) +end + +local dir = debug.getinfo(1, "S").source:sub(2):match("(.*/)") +Ext.add("web.routes", { + name = "qimao_verify", dir = dir .. "web", + assets = { "qimao_verify.html", "qimao_verify.js" }, + public = { config = true, verify = true }, handle = handle, +}) + +return Verification diff --git a/moonsource-qimao.koplugin/moonsource_qimao/web/qimao_verify.html b/moonsource-qimao.koplugin/moonsource_qimao/web/qimao_verify.html new file mode 100644 index 0000000..72237ea --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/web/qimao_verify.html @@ -0,0 +1,25 @@ + + + + + + +月读 + + + + +
+

月读

+

+
+

+ +
+ + + diff --git a/moonsource-qimao.koplugin/moonsource_qimao/web/qimao_verify.js b/moonsource-qimao.koplugin/moonsource_qimao/web/qimao_verify.js new file mode 100644 index 0000000..75817f5 --- /dev/null +++ b/moonsource-qimao.koplugin/moonsource_qimao/web/qimao_verify.js @@ -0,0 +1,80 @@ +(async function () { + 'use strict'; + const ticket = location.hash.slice(1); + const status = document.getElementById('status'); + const retry = document.getElementById('retry'); + let messages, captcha; + async function request(action, body) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 45000); + try { + const response = await fetch('/api/qimao_verify/' + action, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...body, ticket }), + signal: controller.signal, + }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || response.statusText); + return result; + } finally { + clearTimeout(timer); + } + } + function failed(error) { + status.textContent = error.message || messages.failure; + retry.hidden = false; + } + retry.onclick = () => { + retry.hidden = true; + status.textContent = ''; + if (captcha) captcha.reset(); + else loadCaptcha().catch(failed); + }; + async function verify(result) { + if (!result.pass || typeof result.rid !== 'string' || !result.rid) { + failed(new Error(messages.failure)); + return; + } + status.textContent = messages.pending; + try { + await request('verify', { rid: result.rid }); + status.textContent = messages.success; + document.getElementById('captcha-element').hidden = true; + retry.hidden = true; + } catch (error) { + failed(error); + } + } + async function loadCaptcha() { + if (!window.initSMCaptcha) { + await new Promise((resolve, reject) => { + const script = document.createElement('script'); + const timer = setTimeout(() => reject(new Error(messages.load_error)), 20000); + script.src = 'https://castatic.fengkongcloud.cn/pr/v1.0.1/smcp.min.js'; + script.onload = () => { clearTimeout(timer); resolve(); }; + script.onerror = () => { clearTimeout(timer); reject(new Error(messages.load_error)); }; + document.head.appendChild(script); + }); + } + window.initSMCaptcha({ + organization: 'KJNSBIdTWSOiYNEsCLS9', + mode: 'slide', product: 'embed', width: '100%', https: true, + }, instance => { + captcha = instance; + instance.onSuccess(verify); + instance.onError(() => failed(new Error(messages.load_error))); + instance.appendTo('captcha-element'); + }); + } + try { + messages = await request('config', {}); + document.title = document.getElementById('title').textContent = messages.title; + document.getElementById('instruction').textContent = messages.instruction; + retry.textContent = messages.retry; + await loadCaptcha(); + } catch (error) { + if (messages) failed(error); + else status.textContent = error.message; + } +})(); diff --git a/tests/qimao/login_spec.lua b/tests/qimao/login_spec.lua new file mode 100644 index 0000000..1469dc0 --- /dev/null +++ b/tests/qimao/login_spec.lua @@ -0,0 +1,130 @@ +--[[-- +七猫手机号 / 短信码留在本机;仅发送短信前的拼图桥接,保留 token 导入。 + +@module tests.moonsource_qimao.login_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Themed = require("support.theme_stubs") +require("source.logout").replaceLibrary = function(id, commit) + Assert.eq(id, "ext.qimao") + commit() + return true +end +Themed.install() +package.preload["ui.themes.widgets.row"] = function() + return { widget = function(spec) return spec end } +end +local Progress = require("ui.themes.widgets.progress_dialog") +local newProgress = Progress.new +function Progress:new(spec) + local dialog = newProgress(self, spec) + dialog.show = function(self) self.shown = true end + return dialog +end +local cfg = { token = "old-token" } +local saved, reloaded, authorized +package.preload["utils.settings"] = function() + return { + getSource = function() return cfg end, + saveSource = function(_id, value) saved = value.token end, + } +end +package.preload["source.auth"] = function() + return { ok = function(id) authorized = id end, expired = function() return false end } +end +package.preload["source.registry"] = function() return { reload = function() reloaded = true end } end +local pending_network, defer_network +package.preload["ui/network/manager"] = function() + return { runWhenConnected = function(_self, fn) + if defer_network then pending_network = fn else fn() end + end } +end +local sessions = {} +package.preload["moonsource_qimao.verify"] = function() + return { new = function(phone, cb) + local session = { phone = phone, callback = cb } + session.cancel = function() session.cancelled = true end + sessions[#sessions + 1] = session + return session + end } +end +local login_phone, login_code, checked_token +local login_error +package.preload["moonsource_qimao.client"] = function() + return { + token = function() return cfg.token end, + loginAsync = function(phone, code, cb) + login_phone, login_code = phone, code + cb(login_error and nil or "new-token", login_error) + end, + userInfoAsync = function(token, cb) checked_token = token; cb({}) end, + } +end +local Setting = require("moonsource_qimao.setting") +Setting.login() +local input = Themed.last("input") +Assert.len(input.fields, 2) +Assert.eq(input.fields[1].label, "手机号") +Assert.eq(input.fields[2].label, "验证码") +Assert.len(input.actions, 1, "手机号登录只留发码动作,避免四个按钮挤在一行") +input.actions[1].callback("invalid") +Assert.len(sessions, 0) +Assert.eq(Themed.last("toast").text, "请填写正确的手机号") +input.actions[1].callback(" 13800000000 ") +Assert.len(sessions, 0, "用户同意协议之前不启动发短信验证") +Themed.last("confirm").ok_callback() +Assert.len(sessions, 1) +Assert.eq(sessions[1].phone, "13800000000") +sessions[1].callback(true) +Assert.eq(Themed.last("toast").text, "短信已发送,请在设备上填写验证码") +Assert.is_nil(input.closed, "滑块完成后仍在设备填写短信码") +input.actions[1].callback("13800000000") +Assert.is_true(sessions[1].cancelled, "重复点击只保留最新一次发送") +Assert.len(sessions, 2) +input:close() +input.callback("13800000000", "001234") +Assert.is_true(sessions[2].cancelled) +Assert.eq(login_phone, "13800000000") +Assert.eq(login_code, "001234") +Assert.eq(checked_token, "new-token", "登录返回的 token 仍先校验") +Assert.eq(saved, "new-token") +Assert.eq(authorized, "ext.qimao") +Assert.is_true(reloaded) +Assert.is_nil(cfg.phone, "不持久化手机号或短信码") +Assert.is_nil(cfg.code) +Assert.is_true(Themed.last("progress_dialog").closed) + +local token_row +for _idx, make_row in ipairs(Setting.rows()) do + local row = make_row(400) + if row.title == "用 token 登录" then + token_row = row + break + end +end +Assert.not_nil(token_row, "保留 token 登录入口,不依赖账号页行顺序") +token_row.callback() +local imported = Themed.last("input") +Assert.eq(imported.title, "七猫登录 token") +Assert.len(imported.fields, 1) +imported.callback("manual-token") +Assert.eq(saved, "manual-token", "保留旧 token 登录入口") + +Setting.login() +input = Themed.last("input") +defer_network = true +input.actions[1].callback("13800000000") +Themed.last("confirm").ok_callback() +Assert.not_nil(pending_network) +input:close() +pending_network() +Assert.len(sessions, 2, "等待联网时关闭输入窗不能再弹出二维码") + +defer_network = false +Setting.login() +input = Themed.last("input") +input:close() +input.callback("13800000000", "") +Assert.eq(Themed.last("toast").text, "请先填写验证码") diff --git a/tests/qimao/progress_spec.lua b/tests/qimao/progress_spec.lua new file mode 100644 index 0000000..03a7b05 --- /dev/null +++ b/tests/qimao/progress_spec.lua @@ -0,0 +1,64 @@ +--[[-- +七猫的多阶段进度请求必须保留当前阶段的取消句柄。 + +@module tests.moonsource_qimao.progress_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") + +local client = { token = function() return "token" end } +package.preload["moonsource_qimao.client"] = function() return client end +package.preload["moonsource_qimao.mapper"] = function() + return { + readChapter = function(row) + return row and { uid = row.latest_read_chapter_id, title = row.latest_read_chapter_name } + end, + progressItem = function(row, chapter) return { row = row, chapter = chapter } end, + } +end +package.preload["source.base"] = function() + return { loadMeta = function() return { id = "ext.qimao", name = "七猫", type = "chapter" } end } +end +package.preload["source.browse"] = function() return {} end +package.preload["source.shelf"] = function() return {} end +package.preload["source.toc"] = function() return { index = function() return 3 end } end +package.loaded["moonsource_qimao.source"] = nil + +local Source = require("moonsource_qimao.source") +local identity = { stable_id = "book" } +local source = Source.new() +local toc_cancelled, shelf_cancelled = false, false +local shelf_job = { cancel = function() shelf_cancelled = true end } +local toc_job = { cancel = function() toc_cancelled = true end } +local toc_callback + +client.shelfSyncAsync = function(cb) + cb({ { book_id = "book", latest_read_chapter_id = "chapter", latest_read_chapter_name = "第3章" } }) + return shelf_job +end +source.loadTocAsync = function(_self, _identity, cb) + toc_callback = cb + return toc_job +end +local result_called = false +local get_job = source:getProgressAsync(identity, function() result_called = true end) +get_job.cancel() +Assert.is_true(toc_cancelled, "cancel targets the in-flight TOC request") +Assert.is_false(shelf_cancelled, "cancel does not retain the completed shelf request") +toc_callback({ { uid = "chapter", title = "第3章" } }) +Assert.is_false(result_called, "a cancelled request ignores a late callback") + +local push_cancelled = false +local push_job = { cancel = function() push_cancelled = true end } +toc_cancelled, shelf_cancelled = false, false +source.loadTocAsync = function(_self, _identity, cb) + cb({ { uid = "chapter", title = "第3章" } }) + return toc_job +end +client.shelfPushAsync = function(_items, _cb) return push_job end +local put_job = source:putProgressAsync(identity, { chapter_idx = 1 }, function() end) +put_job.cancel() +Assert.is_true(push_cancelled, "cancel targets the in-flight progress upload") +Assert.is_false(toc_cancelled) +Assert.is_false(shelf_cancelled) diff --git a/tests/qimao/qimao_spec.lua b/tests/qimao/qimao_spec.lua new file mode 100644 index 0000000..3338b96 --- /dev/null +++ b/tests/qimao/qimao_spec.lua @@ -0,0 +1,271 @@ +--[[-- +七猫登录 token、书架分页 / 增删上行与映射离线用例。 + +@module tests.source.qimao_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") +local JSONStub = require("support.json_stub") + +package.preload["json"] = function() + return { decode = JSONStub.decode, encode = JSONStub.encode } +end + +local cfg = { token = "tk-1" } +package.preload["utils.settings"] = function() + return { getSource = function() return cfg end } +end + +local expired +package.preload["source.auth"] = function() + return { expire = function(_, msg) expired = msg; return msg end, ok = function() end } +end + +local requests, replies = {}, {} +package.preload["http.request"] = function() + return { + get = function(url, opts, cb) + requests[#requests + 1] = { url = url, opts = opts } + cb(table.remove(replies, 1)) + return { cancel = function() end } + end, + post = function(url, body, opts, cb) + requests[#requests + 1] = { url = url, body = body, opts = opts } + cb(table.remove(replies, 1)) + return { cancel = function() end } + end, + } +end + +package.loaded["moonsource_qimao.client"] = nil +package.loaded["moonsource_qimao.mapper"] = nil +package.loaded["moonsource_qimao.setting"] = nil +local Client = require("moonsource_qimao.client") +local Mapper = require("moonsource_qimao.mapper") +local Setting = require("moonsource_qimao.setting") + +-- 滑块只交 rid;设备发短信、再用短信码登录,不提前覆盖已有账号。 +do + requests, replies = {}, { '{"data":""}', '{"data":{"token":"new-token"}}' } + local sent, token, err + Client.sendCodeAsync("13800000000", "slider-proof", function(ok, message) sent, err = ok, message end) + Assert.is_true(sent) + Assert.is_nil(err) + Assert.matches(requests[1].url, "/api/pc/v1/login/send%-code$") + Assert.matches(requests[1].body, "phone=13800000000") + Assert.matches(requests[1].body, "rid=slider%-proof") + Assert.is_nil(requests[1].opts.headers.Authorization, "登录请求不携带已登录账号的 token") + Client.loginAsync("13800000000", "001234", function(value, message) token, err = value, message end) + Assert.eq(token, "new-token") + Assert.is_nil(err) + Assert.matches(requests[2].url, "/api/pc/v1/login/index$") + Assert.matches(requests[2].body, "code=001234", "短信码保留前导零") + Assert.eq(cfg.token, "tk-1", "新 token 经设置页校验后才保存") + + expired, replies = nil, { '{"errors":{"code":"40001002","title":"短信验证码错误"}}', '{"data":{}}' } + Client.loginAsync("13800000000", "wrong", function(value, message) token, err = value, message end) + Assert.is_nil(token) + Assert.eq(err, "短信验证码错误") + Assert.is_nil(expired, "尝试新登录不能把原账号标记失效") + Client.loginAsync("13800000000", "001234", function(value, message) token, err = value, message end) + Assert.is_nil(token) + Assert.eq(err, "七猫登录响应缺少 token") + requests = {} +end + +-- 书架分页:按 meta.total_pages 翻完,请求带 Authorization。 +do + replies = { + '{"data":{"books":[{"book_id":"1"}],"meta":{"total_pages":"2"}}}', + '{"data":{"books":[{"book_id":"2"}],"meta":{"total_pages":"2"}}}', + } + local rows, err + Client.shelfSyncAsync(function(v, e) rows, err = v, e end) + Assert.is_nil(err) + Assert.len(rows, 2) + Assert.eq(rows[2].book_id, "2") + Assert.len(requests, 2) + Assert.eq(requests[1].opts.headers.Authorization, "tk-1") + Assert.matches(requests[1].url, "api%-bs%.wtzw%.com/pcapi/v1/user/local$") + Assert.matches(requests[2].body, "page=2") +end + +-- 书库列表:分页字段决定是否还有下一页,书取书库行字段。 +do + requests, replies = {}, { '{"data":{"book_list":[{"book_id":"9","title":"甲","author":"乙","image_link":"http://c/x.jpg"}],' + .. '"page_data":{"count":"31","page":"2","page_size":"15"}}}' } + local wire + Client.classifyAsync({ + channel = "0", category1 = "202", category2 = "a", order = "click", + words = "3", update_time = "2", is_over = "1", page = 2, + }, + function(v) wire = v end) + Assert.matches(requests[1].url, "^https://www%.qimao%.com/api/classify/book%-list%?") + Assert.matches(requests[1].url, "category1=202") + Assert.matches(requests[1].url, "words=3") + Assert.matches(requests[1].url, "update_time=2") + Assert.matches(requests[1].url, "is_over=1") + local books, more = Mapper.classify(wire) + Assert.eq(books[1].stable_id, "9") + Assert.eq(books[1].authors, "乙") + Assert.is_true(more) + wire.data.page_data.page = "3" + Assert.is_true(not select(2, Mapper.classify(wire))) +end + +-- 登录态被拒:标失效;弹窗用人话,不原样塞服务端 title。 +do + requests, expired = {}, nil + replies = { '{"errors":{"code":"40001002","title":"请先登录"}}' } + local wire, err + Client.shelfPushAsync({ { book_id = "1" } }, function(v, e) wire, err = v, e end) + Assert.is_nil(wire) + Assert.matches(err, "moon%-cookie%-storage") + Assert.eq(expired, err) +end + +-- 没 token 不发请求。 +do + requests, cfg.token = {}, nil + local queue = {} + package.preload["ui/uimanager"] = function() return { nextTick = function(_, f) queue[#queue + 1] = f end } end + package.loaded["source.base"] = nil + package.loaded["ui.guard"] = nil + package.preload["ui.guard"] = function() return { call = function(_, f, ...) return f(...) end } end + local err + Client.shelfPushAsync({}, function(_, e) err = e end) + for _idx, f in ipairs(queue) do f() end + Assert.eq(err, "未登录七猫") + Assert.len(requests, 0) + cfg.token = "tk-1" +end + +-- 校验新 token 的失败不能把已有登录态标失效。 +do + expired = nil + replies = { '{"errors":{"code":"40001002","title":"请先登录"}}' } + local user, err + Client.userInfoAsync("other-token", function(v, e) user, err = v, e end) + Assert.is_nil(user) + Assert.eq(err, "请先登录") + Assert.is_nil(expired) +end + +-- 映射:书架行用 book_*,封面补 CDN;上行条目只留 /bookimg/ 路径。 +do + local books = Mapper.shelfList({ { book_id = 7, book_title = "书", author = "作者", image_link = "/bookimg/a.jpg" } }) + Assert.eq(books[1].stable_id, "7") + Assert.eq(books[1].title, "书") + Assert.eq(books[1].cover, "https://cdn.wtzw.com/bookimg/a.jpg") + local item = Mapper.shelfItem("7", books[1], "1") + Assert.eq(item.image_link, "/bookimg/a.jpg") + Assert.eq(item.push_type, "1") + Assert.is_nil(Mapper.readChapter({ latest_read_chapter_id = "" })) + local row = { + book_id = "7", book_title = "书", group_name = "在读", + latest_read_chapter_id = "19", latest_read_chapter_name = "第19章", + page_offset = "12", paragraph_index = "3", + } + Assert.eq(Mapper.readChapter(row).uid, "19") + local same = Mapper.progressItem(row, { uid = "19", title = "第19章", idx = 19 }) + Assert.eq(same.book_title, "书") + Assert.eq(same.group_name, "在读") + Assert.eq(same.page_offset, "12") + Assert.eq(same.paragraph_index, "3") + Assert.eq(same.push_type, "1") + local moved = Mapper.progressItem(row, { uid = "20", title = "第20章", idx = 20 }) + Assert.eq(moved.latest_read_chapter_id, "20") + Assert.eq(moved.latest_read_chapter_index, "20") + Assert.eq(moved.page_offset, "") + Assert.eq(moved.paragraph_index, "0") + Assert.eq(moved.book_title, "书") +end + +-- 登录输入:裸 token、Bearer 前缀、浏览器 userinfo JSON。 +do + Assert.eq(Setting.parseToken(" abc "), "abc") + Assert.eq(Setting.parseToken("Bearer abc"), "abc") + Assert.eq(Setting.parseToken('{"token":"xyz","is_vip":"0"}'), "xyz") + Assert.eq(Setting.parseToken("{坏"), "") +end + +-- 书城浏览:默认节点是「频道:分类:子分类:排序」四段;三段正则会让 cat2/order 为 nil 拼崩。 +do + local classify_q + package.loaded["moonsource_qimao.client"] = nil + package.preload["moonsource_qimao.client"] = function() + return { + classifyOptionsAsync = function(cb) + cb({ + data = { + filters = { + order = { { value = "click", label = "点击" }, { value = "a", label = "全部" } }, + channel = { { value = "0", label = "男生" }, { value = "a", label = "全部" } }, + words = { { value = "a", label = "全部" }, { value = "3", label = "50万-100万" } }, + update_time = { { value = "a", label = "全部" }, { value = "2", label = "7天内" } }, + is_over = { { value = "a", label = "全部" }, { value = "1", label = "已完结" } }, + }, + category = { + { id = "202", name = "玄幻奇幻", type = "0", children = { + { id = "37", name = "东方玄幻", type = "0" }, + } }, + }, + }, + }) + return { cancel = function() end } + end, + classifyAsync = function(q, cb) + classify_q = q + cb({ data = { book_list = {}, page_data = { page = "1", page_size = "15", count = "0" } } }) + return { cancel = function() end } + end, + } + end + package.loaded["source.browse"] = nil + package.preload["source.browse"] = function() + return { + group = function(items, selected) return { items = items, selected = selected } end, + pages = function(fetch, _limit, groups, cb) + fetch(1, function(books, err, more) + cb({ data = books or {}, groups = groups, more = more }, err) + end) + return { cancel = function() end } + end, + } + end + package.loaded["moonsource_qimao.source"] = nil + package.loaded["moonsource_qimao.init"] = nil + local Source = require("moonsource_qimao.source").new() + local res, err + Source:browseAsync({}, function(r, e) res, err = r, e end) + Assert.is_nil(err) + Assert.is_true(res ~= nil) + Assert.eq(classify_q.channel, "0") + Assert.eq(classify_q.category1, "a") + Assert.eq(classify_q.category2, "a") + Assert.eq(classify_q.order, "click") + Assert.eq(classify_q.words, "a") + Assert.eq(classify_q.update_time, "a") + Assert.eq(classify_q.is_over, "a") + Assert.eq(res.groups[1].selected, "0:a:a:click:a:a:a") + Assert.eq(res.groups[4].title, "字数") + Assert.eq(res.groups[4].items[1].id, "0:a:a:click:a:a:a") + + Source:browseAsync({ node = "0:202:37:words_num:3:2:1" }, function(r, e) res, err = r, e end) + Assert.is_nil(err) + Assert.eq(classify_q.order, "words_num", "排序值包含下划线") + Assert.eq(classify_q.category1, "202") + Assert.eq(classify_q.category2, "37") + Assert.eq(classify_q.words, "3") + Assert.eq(classify_q.update_time, "2") + Assert.eq(classify_q.is_over, "1") + Assert.eq(res.groups[1].selected, "0:202:37:words_num:3:2:1") + Assert.eq(res.groups[5].title, "字数") + + Source:browseAsync({ node = "0:202:37:words_num" }, function(r, e) res, err = r, e end) + Assert.eq(classify_q.order, "words_num", "兼容已有四段筛选节点") + Assert.eq(classify_q.words, "a") + Assert.eq(classify_q.update_time, "a") + Assert.eq(classify_q.is_over, "a") +end diff --git a/tests/qimao/verify_spec.lua b/tests/qimao/verify_spec.lua new file mode 100644 index 0000000..ab9a9e4 --- /dev/null +++ b/tests/qimao/verify_spec.lua @@ -0,0 +1,121 @@ +--[[-- +七猫滑块仅提交 rid;手机号隔离、一次性票据、异步取消与过期。 + +@module tests.moonsource_qimao.verify_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Themed = require("support.theme_stubs") +Themed.install() +local Ext = require("utils.extension") +Ext.reset() +local token +local submit, submitted_phone, submitted_rid, cancelled +package.preload["moonsource_qimao.client"] = function() + return { + token = function() return token end, + sendCodeAsync = function(phone, rid, cb) + submitted_phone, submitted_rid, submit = phone, rid, cb + return { cancel = function() cancelled = true end } + end, + } +end +local timers = {} +package.preload["ui/uimanager"] = function() + return { + scheduleIn = function(_self, _delay, fn) timers[fn] = true end, + unschedule = function(_self, fn) timers[fn] = nil end, + } +end +package.preload["ui.guard"] = function() return { wrap = function(_label, fn) return fn end } end +local path +Ext.add("web.open_page", function(url, _title, _text, opts) + path = url + return require("ui.themes.widgets.qr"):new{ close_callback = opts.close_callback }:show() +end) +local Verification = require("moonsource_qimao.verify") +local route = Ext.list("web.routes")[1] +local status, response, headers +local function request(action, params, method) + route.handle(method or "POST", action, params, function(code, body, extra) + status, response, headers = code, body, extra + end) +end +local finished, finish_err +local function newSession() + finished, finish_err = nil, nil + return Verification.new("13800000000", function(ok, err) finished, finish_err = ok, err end) +end +local session = newSession() +local ticket = path:match("#(.+)$") +Assert.matches(path, "^/qimao_verify%.html#%x+$") +request("config", { ticket = ticket }) +Assert.eq(status, 200) +Assert.is_nil(response.phone, "网页不能读到设备手机号") +Assert.is_nil(response.token, "网页不能读到登录 token") +Assert.is_nil(response.fields, "不是远程账号 / 短信输入表单") +Assert.eq(headers[1], "Cache-Control: no-store") +request("verify", { ticket = "wrong", rid = "proof" }) +Assert.eq(status, 403) +request("verify", { ticket = ticket, rid = {} }) +Assert.eq(status, 400) +request("verify", { ticket = ticket, rid = string.rep("a", 1025) }) +Assert.eq(status, 400) +request("config", { ticket = ticket }, "GET") +Assert.eq(status, 405) +request("other", { ticket = ticket }) +Assert.eq(status, 404) + +request("verify", { ticket = ticket, rid = "proof", phone = "another-phone", code = "browser-code" }) +Assert.eq(submitted_phone, "13800000000", "浏览器不能换掉目标手机号") +Assert.eq(submitted_rid, "proof") +request("verify", { ticket = ticket, rid = "another-proof" }) +Assert.eq(status, 409) +submit(false, "验证码发送频繁") +Assert.eq(status, 400) +Assert.eq(response.error, "验证码发送频繁") +Assert.is_nil(finished, "发短信失败不能报告验证成功") +request("verify", { ticket = ticket, rid = "retry-proof" }) +submit(true) +Assert.eq(status, 200) +Assert.is_true(finished) +Assert.is_true(session.dialog.closed) +Assert.is_nil(next(timers)) +request("verify", { ticket = ticket, rid = "replay" }) +Assert.eq(status, 403, "一次验证只允许成功发送一次短信") + +session = newSession() +ticket = path:match("#(.+)$") +request("verify", { ticket = ticket, rid = "pending" }) +session.dialog:close() +Assert.is_false(finished) +Assert.eq(finish_err, "验证已取消") +Assert.is_true(cancelled) +submit(true) +Assert.eq(status, 403) +Assert.is_false(finished, "关窗后不能接收迟到的成功") + +session = newSession() +ticket = path:match("#(.+)$") +session.expires = os.time() - 1 +request("config", { ticket = ticket }) +Assert.eq(status, 403) +session.timeout() +Assert.eq(finish_err, "验证已过期,请重新发起验证") +Assert.is_nil(next(timers)) + +session = newSession() +ticket = path:match("#(.+)$") +request("verify", { ticket = ticket, rid = "pending" }) +token = "new-account" +submit(true) +Assert.eq(status, 403) +Assert.is_false(finished, "换账号后不能把旧手机号的验证报为成功") + +Ext.reset() +session = newSession() +Assert.is_true(session.done) +Assert.is_false(finished) +Assert.eq(finish_err, "无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能") +Assert.is_nil(next(timers))