commit d08a5b45c064491465f4f488eb6846646a1c8a53 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-shuqi.koplugin/README.md b/moonsource-shuqi.koplugin/README.md new file mode 100644 index 0000000..b69ae76 --- /dev/null +++ b/moonsource-shuqi.koplugin/README.md @@ -0,0 +1,22 @@ +# 书旗小说 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 手机短信登录 | 已实现,未实测 | 通过远程网页完成官方安全验证,保存前校验账号 | +| 浏览器登录与 Cookie 导入 | 支持 | 手动粘贴或扩展回传,只保存必要会话字段 | +| 设备密码与扫码登录 | 不支持 | 未提供入口 | +| 书架拉取 | 支持 | 读取书签书架,账号请求串行执行 | +| 书架新增与移出 | 已实现,未实测 | 本地先生效,另一次请求回读确认;失败保留脏行或墓碑 | +| 搜索 | 部分支持 | 首批约 20 本,没有搜索翻页 | +| 分类书城 | 支持 | 动态频道、分类、状态、字数、更新时间及后续页,默认聚合 60 本 | +| 详情与目录 | 支持 | 保留书籍、章节 ID 和缓存路径 | +| 免费正文 | 支持 | 未购或缺正文地址时提示购买,不缓存提示页 | +| 已购正文 | 已实现,未实测 | 需目录提供有效的已购正文地址 | +| 章节与全本缓存 | 支持 | 支持预取、范围和后台缓存,下载失败记为失败 | +| 离线阅读 | 支持 | 已缓存正文可续章、关书重开 | +| 阅读进度同步 | 部分支持 | 章节位置及全书比例,回读确认;无精确章内坐标 | +| 笔记与统计同步 | 不支持 | 仅本地保存 | +| 整书书评 | 部分支持 | 详情仅第一页;客户端可续页,界面未接后续页 | +| 章评与段评 | 不支持 | 当前 Web 协议未找到可验证接口 | +| 评论回复与写操作 | 不支持 | 未接入 | +| 账号切换 | 部分支持 | 同账号可续期;换号须先退出清理旧数据,未同步记录会丢失 | diff --git a/moonsource-shuqi.koplugin/_meta.lua b/moonsource-shuqi.koplugin/_meta.lua new file mode 100644 index 0000000..fc1bf3f --- /dev/null +++ b/moonsource-shuqi.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:书旗小说"), + description = _("给月读增加「书旗小说」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-shuqi.koplugin/main.lua b/moonsource-shuqi.koplugin/main.lua new file mode 100644 index 0000000..34d0276 --- /dev/null +++ b/moonsource-shuqi.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_shuqi", + is_doc_only = false, +} diff --git a/moonsource-shuqi.koplugin/moon_source.lua b/moonsource-shuqi.koplugin/moon_source.lua new file mode 100644 index 0000000..233b679 --- /dev/null +++ b/moonsource-shuqi.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_shuqi.source").meta() end, + new = function() return require("moonsource_shuqi.source").new() end, + setting = lazy("moonsource_shuqi.setting"), +} diff --git a/moonsource-shuqi.koplugin/moonsource_shuqi/_meta.lua b/moonsource-shuqi.koplugin/moonsource_shuqi/_meta.lua new file mode 100644 index 0000000..a92278d --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/_meta.lua @@ -0,0 +1,17 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +书旗网页(t.shuqi.com)搜索和免费章节不需要登录。书架可用验证码或官网 Cookie 登录,滑块在远程管理页完成。 + +@module moonsource_shuqi._meta +--]] + +local _ = require("l10n").get("moonsource_shuqi") + +return { + id = "ext.shuqi", + name = _("书旗小说"), + type = "chapter", + description = _("书旗书架与在线阅读"), + abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("书评"), _("VIP 章节") }, +} diff --git a/moonsource-shuqi.koplugin/moonsource_shuqi/client.lua b/moonsource-shuqi.koplugin/moonsource_shuqi/client.lua new file mode 100644 index 0000000..5c8aab3 --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/client.lua @@ -0,0 +1,665 @@ +--[[-- +书旗网页接口。 + +搜索、分类、目录、免费正文不登录。登录支持手机验证码与官网 Cookie。 +书架增删和阅读位置走书签同步,写入后另拉快照确认。 + +@module moonsource_shuqi.client +--]] + +local JSON = require("json") +local Mapper = require("moonsource_shuqi.mapper") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_shuqi") + +local Client = {} + +local SOURCE_ID = "ext.shuqi" +local NOVEL = "https://read.xiaoshuo1-sm.com/novel/i.php" +local CONTENT = "https://content.shuqireader.com" +local OCEAN = "https://ocean.shuqireader.com" +local BOOKMARK = "https://jbookmark.shuqireader.com/api/v1/sync/bookmarks" +local ANON_USER = "8000000" + +local env = {} +local login_epoch = 0 + +---@class ShuqiBookmarkRequest +---@field pending boolean +---@field start fun() +---@field job HttpJob|nil + +---@class ShuqiBookmarkSession +---@field epoch integer +---@field requests ShuqiBookmarkRequest[] +local BookmarkSession = {} +BookmarkSession.__index = BookmarkSession + +---@return ShuqiBookmarkSession +function BookmarkSession.new() + return setmetatable({ epoch = login_epoch, requests = {} }, BookmarkSession) +end + +---@param entry ShuqiBookmarkRequest +function BookmarkSession:remove(entry) + for index, request in ipairs(self.requests) do + if request == entry then + table.remove(self.requests, index) + if index == 1 and self.requests[1] then + require("ui/uimanager"):nextTick( + require("ui.guard").wrap("shuqi.bookmarks.start", self.requests[1].start)) + end + return + end + end +end + +-- 同一账号的书签接口拒绝并发请求(10006);队列归登录会话所有。 +---@param url string +---@param body string +---@param options HttpRequestOpts +---@param cb fun(raw: string|nil, err: any) +---@return HttpJob +function BookmarkSession:post(url, body, options, cb) + ---@type ShuqiBookmarkRequest + local entry + entry = { + pending = true, + start = function() + if not entry.pending then return end + if self.epoch ~= login_epoch then + entry.pending = false + self:remove(entry) + cb(nil, _("登录状态已变化,请重试")) + return + end + local job = Request.post(url, body, options, function(raw, err) + if not entry.pending then return end + entry.pending = false + self:remove(entry) + cb(raw, err) + end) + if entry.pending then entry.job = job end + end, + } + self.requests[#self.requests + 1] = entry + if #self.requests == 1 then entry.start() end + return { cancel = function() + if not entry.pending then return end + entry.pending = false + if entry.job then entry.job.cancel() end + self:remove(entry) + end } +end + +function Client.reset() + env = {} + login_epoch = login_epoch + 1 +end + +function Client.load() + env = { bookmarks = env.bookmarks } + local cfg = require("utils.settings").getSource(SOURCE_ID) + env.token = cfg.token + env.user_id = cfg.user_id + env.imei = cfg.imei + env.umidtoken = cfg.umidtoken + env.wua = cfg.wua +end + +---@return boolean +function Client.loggedIn() + if not env.token then Client.load() end + local cfg = require("utils.settings").getSource(SOURCE_ID) + return cfg.logged_in == true and type(cfg.token) == "string" and cfg.token ~= "" +end + +---@param session { token: string, user_id: string|nil, name: string } +---@param browser { fingerprint: string|nil, umidtoken: string|nil, wua: string|nil }|nil +function Client.persist(session, browser) + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + cfg.token = session.token + cfg.user_id = session.user_id + cfg.name = session.name + cfg.logged_in = true + cfg.imei = browser and browser.fingerprint or nil + cfg.umidtoken = browser and browser.umidtoken or nil + cfg.wua = browser and browser.wua or nil + settings.saveSource(SOURCE_ID) + login_epoch = login_epoch + 1 + Client.load() +end + +---@param cb fun(wire: table|nil, err: string|nil) +local function decode(cb) + return function(raw, err) + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok or type(wire) ~= "table" then cb(nil, _("响应无效")); return end + cb(wire) + end +end + +---@return table +local function opts() + return { + accept = "application/json", + headers = { Accept = "application/json", Referer = "https://t.shuqi.com/" }, + timeout = require("http.timeout").net(1), + } +end + +---@param url string +---@param cb fun(wire: table|nil, err: string|nil) +local function get(url, cb) + return Request.get(url, opts(), decode(cb)) +end + +---@param book_id string +---@return string timestamp +---@return table fields +local function contentFields(book_id) + if env.token == nil then Client.load() end + local timestamp = tostring(os.time()) + local user_id = env.user_id + if type(user_id) ~= "string" or user_id == "" then user_id = ANON_USER end + return timestamp, { user_id = user_id, bookId = book_id, timestamp = timestamp } +end + +---@param keyword string +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return HttpJob +function Client.searchAsync(keyword, cb) + local timestamp = tostring(os.time()) + local url = NOVEL .. "?" .. Text.formEncode({ + ["do"] = "is_search", + userId = ANON_USER, + platform = "3", + p = "3", + q = keyword, + page = "1", + size = "20", + filterMigu = "1", + ver = "", + timestamp = timestamp, + sign = Mapper.searchSign(timestamp), + }) + return get(url, function(wire, err) + if not wire then cb(nil, err); return end + local books, reason = Mapper.searchBooks(wire) + if not books then cb(nil, reason or _("请求失败")); return end + cb(books) + end) +end + +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +function Client.categoriesAsync(cb) + local timestamp = tostring(os.time()) + local url = CONTENT .. "/openapi/rankv2/class?" .. Text.formEncode({ + user_Id = ANON_USER, + timestamp = timestamp, + imei = "", + sn = "", + tk = "", + platform = "3", + p = "3", + sign = Mapper.rankSign(timestamp), + }) + return get(url, cb) +end + +---@param tag string|nil +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return HttpJob +function Client.rankAsync(tag, cb) + local timestamp = tostring(os.time()) + local query = { + ["do"] = "is_caterank", + userId = ANON_USER, + platform = "3", + p = "3", + page = "1", + size = "20", + filterMigu = "1", + timestamp = timestamp, + sign = Mapper.rankSign(timestamp), + } + if type(tag) == "string" and tag ~= "" then query.tag = tag end + return get(NOVEL .. "?" .. Text.formEncode(query), function(wire, err) + if not wire then cb(nil, err); return end + local books, reason = Mapper.searchBooks(wire) + if not books then cb(nil, reason or _("请求失败")); return end + cb(books) + end) +end + +---@param node string|nil +---@param page integer +---@param cb fun(html: string|nil, err: string|nil) +---@return HttpJob +function Client.storeAsync(node, page, cb) + local query = node and Mapper.storeNode(node) + if node and not query then return require("source.base").defer(cb, nil, _("响应无效")) end + local options = opts() + options.accept = "text/html" + options.headers = { Accept = "text/html", Referer = "https://www.shuqi.com/store" } + return Request.get("https://www.shuqi.com/store?" .. (query and query .. "&" or "") .. "page=" .. page, options, cb) +end + +---@param book_id string +---@param page integer +---@param cb fun(page: table|nil, err: string|nil) +---@return HttpJob +function Client.reviewsAsync(book_id, page, cb) + local url = "https://comment.alwx.alibaba.com/novel/i.php?" .. Text.formEncode({ + ["do"] = "sp_get", bookId = book_id, fetch = "merge", + sqUid = ANON_USER, source = "store", size = 20, page = page, score = "yes", + }) + return get(url, function(wire, err) + if not wire then cb(nil, err); return end + local result = Mapper.reviews(wire, book_id) + cb(result, not result and _("响应无效") or nil) + end) +end + +---@param book_id string +---@param cb fun(book: Book|nil, err: string|nil) +---@return HttpJob +function Client.detailAsync(book_id, cb) + local _timestamp, fields = contentFields(book_id) + fields.sign = Mapper.contentSign(fields) + fields.platform = "0" + return Request.post(CONTENT .. "/openapi/book/info", Text.formEncode(fields), opts(), function(raw, err) + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + local book = ok and Mapper.detail(wire) or nil + if not book then cb(nil, _("请求失败")); return end + cb(book) + end) +end + +---@param book_id string +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +---@return HttpJob +function Client.chaptersAsync(book_id, cb) + local _timestamp, fields = contentFields(book_id) + fields.sign = Mapper.contentSign(fields) + fields.platform = "0" + fields.tk = env.token or "" + fields.imei = env.imei or "" + fields.sn = env.imei or "" + local url = CONTENT .. "/openapi/book/chapterlist?" .. Text.formEncode(fields) + return get(url, function(wire, err) + if not wire then cb(nil, err); return end + local toc = Mapper.chapters(wire) + if not toc then cb(nil, _("请求失败")); return end + cb(toc) + end) +end + +---@param url string|nil +---@param cb fun(text: string|nil, err: string|nil) +---@return HttpJob|nil +function Client.contentAsync(url, cb) + if type(url) ~= "string" or url == "" then cb(nil, _("本章未购买")); return nil end + return get(url, function(wire, err) + if not wire then cb(nil, err); return end + local text, reason = Mapper.chapterText(wire) + if not text then cb(nil, reason and _(reason) or _("请求失败")); return end + cb(text) + end) +end + +---@param fields table +---@return string +local function gatewayBody(fields) + fields.sign = Mapper.gatewaySign(fields) + fields.key = "sq_h5_gateway" + return Text.formEncode(fields) +end + +---@param session table +---@param browser table|nil +---@param cb fun(session: table|nil, err: string|nil) +local function acceptSession(session, browser, cb) + if not session.user_id then cb(nil, _("书旗账号缺少用户编号")); return end + local cfg = require("utils.settings").getSource(SOURCE_ID) + if cfg.logged_in and cfg.user_id ~= session.user_id then + local cleared = require("source.logout").clear(SOURCE_ID, function() + cfg.token, cfg.user_id, cfg.name = nil, nil, nil + cfg.logged_in, cfg.imei, cfg.umidtoken, cfg.wua = nil, nil, nil, nil + require("utils.settings").saveSource(SOURCE_ID) + Client.reset() + end) + if not cleared then cb(nil, _("准备本地同步失败")); return end + end + Client.persist(session, browser) + cb(session) +end + +---@param wire table|nil +---@return string +local function loginError(wire) + if type(wire) ~= "table" then return _("登录响应无效") end + local message = wire.message or wire.msg + if type(message) == "string" and message ~= "" then return message end + local status = wire.status or wire.state + if tonumber(status) == 200 then return _("登录响应无效") end + if type(status) == "string" or type(status) == "number" then + return string.format(_("书旗登录失败(状态:%s)"), tostring(status)) + end + return _("登录响应无效") +end + +--- 只向官方账号接口提交 Cookie 中的会话,不发送其他 Cookie,不缓存账号响应。 +---@param cookie string +---@param cb fun(session: table|nil, err: string|nil) +---@return HttpJob|nil +function Client.loginCookieAsync(cookie, cb) + local candidate = Mapper.cookieSession(require("source.cookie_login").parse(cookie)) + if not candidate then return require("source.base").defer(cb, nil, _("书旗 Cookie 缺少有效的登录凭证")) end + local epoch, cancelled = login_epoch, false + local fields = { userId = candidate.user_id, sqSv = "1.0" } + fields.sign = Mapper.gatewaySign(fields) + fields.key = "sq_h5_gateway" + fields._public = Text.formEncode({ + platform = "0", user_id = candidate.user_id, + imei = candidate.fingerprint or "", sn = candidate.fingerprint or "", + }) + local options = opts() + options.cache_ttl = 0 + options.headers.Authorization = "Bearer " .. candidate.token + local job = Request.get(OCEAN .. "/webapi/jaccount/accountapi/v1/sapi/account/userBaseInfo?" + .. Text.formEncode(fields), options, function(raw, err) + if cancelled then return end + if epoch ~= login_epoch then cb(nil, _("登录状态已变化,请重试")); return end + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then cb(nil, _("登录响应无效")); return end + local account = Mapper.account(wire, candidate.user_id) + if not account then cb(nil, loginError(wire)); return end + candidate.name = account.name + acceptSession(candidate, { fingerprint = candidate.fingerprint }, cb) + end) + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 发送登录短信。手机号只在设备上,滑块字符串由远程页交回。 +---@param phone string +---@param captcha string +---@param cb fun(ok: boolean|nil, err: string|nil) +---@param browser { user_agent: string|nil }|nil +---@return HttpJob +function Client.sendCodeAsync(phone, captcha, cb, browser) + local timestamp = tostring(os.time()) + local fields = { + mobile = phone, + captcha = captcha, + aliyunCheck = "1", + type = "1010", + userId = ANON_USER, + platform = "0", + appVer = "", + placeId = "", + timestamp = timestamp, + sqSv = "1.0", + _public = Text.formEncode({ + platform = "0", + priority = "code", + redirect_uri = "https://t.shuqi.com/myself", + }), + } + local options = opts() + if browser and browser.user_agent and browser.user_agent ~= "" then options.headers["User-Agent"] = browser.user_agent end + return Request.post(OCEAN .. "/api/jaccount/sso/captcha/sendCode", gatewayBody(fields), options, function(raw, err) + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then cb(nil, _("请求失败")); return end + local sent, reason = Mapper.sent(wire) + if not sent then cb(nil, reason or _("请求失败")); return end + cb(true) + end) +end + +--- 验证码登录。browser 是远程页带回来的设备指纹,没有就空着。 +---@param phone string +---@param code string +---@param browser { fingerprint: string|nil, umidtoken: string|nil, wua: string|nil, user_agent: string|nil }|nil +---@param cb fun(session: table|nil, err: string|nil) +---@return HttpJob +function Client.loginAsync(phone, code, browser, cb) + local cancelled, epoch = false, login_epoch + local mark = browser or {} + local fingerprint = type(mark.fingerprint) == "string" and mark.fingerprint or "" + local fields = { + imei = fingerprint, + sn = fingerprint, + umidtoken = type(mark.umidtoken) == "string" and mark.umidtoken or "", + wua = type(mark.wua) == "string" and mark.wua or "", + timestamp = tostring(os.time()), + sqSv = "1.0", + platform = "0", + mobile = phone, + vcode = code, + loginToken = "", + pageSource = "", + appName = "sqH5", + agent = "chrome", + } + local options = opts() + if mark.user_agent and mark.user_agent ~= "" then options.headers["User-Agent"] = mark.user_agent end + local job = Request.post(OCEAN .. "/api/jaccount/sso/vcode/login", gatewayBody(fields), options, function(raw, err) + if cancelled then return end + if epoch ~= login_epoch then cb(nil, _("登录状态已变化,请重试")); return end + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then + cb(nil, raw:match("^%s*<") and _("书旗登录触发安全验证,请在官网登录后导入 Cookie。") or _("登录响应无效")) + return + end + local session, reason = Mapper.session(wire) + if not session then cb(nil, reason or loginError(wire)); return end + acceptSession(session, mark, cb) + end) + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +---@param bookmark table[] +---@param cb fun(books: Book[]|nil, err: string|nil, wire: table|nil) +---@return HttpJob|nil +local function syncAsync(bookmark, cb) + if not Client.loggedIn() then cb(nil, _("未登录书旗")); return nil end + if type(env.user_id) ~= "string" or env.user_id == "" then + cb(nil, _("书旗账号缺少用户编号")) + return nil + end + -- 页面把 user.id 按数字放进 data.userid。字符串对不上账号,同步回空书架。 + -- 空表会被编成 {}。书签接口认 bookmark 是数组,对象的话直接回空书架。 + local marks = bookmark + if JSON.util and JSON.util.InitArray then marks = JSON.util.InitArray(bookmark) end + local epoch = login_epoch + local data = JSON.encode({ + userid = tonumber(env.user_id) or env.user_id, + t = os.time(), + get_data = "1", + bookmark = marks, + coverType = "0", + client_bid_set = {}, + placeid = "", + }) + local body = Text.formEncode({ + platform = "0", + imei = env.imei or "", + sn = env.imei or "", + tk = env.token, + user_id = env.user_id, + data = data, + }) + local url = BOOKMARK .. "?" .. Text.formEncode({ ["_"] = tostring(os.time()), nom9 = "1" }) + if not env.bookmarks or env.bookmarks.epoch ~= epoch then + env.bookmarks = BookmarkSession.new() + end + return env.bookmarks:post(url, body, opts(), function(raw, err) + if epoch ~= login_epoch then cb(nil, _("登录状态已变化,请重试")); return end + if not raw or raw == "" then + cb(nil, err and tostring(err) or _("书旗登录已失效,请点「重新登录」,用手机验证码登录。")) + return + end + local ok, wire = pcall(JSON.decode, raw) + if not ok then cb(nil, _("请求失败")); return end + local books, reason = Mapper.shelf(wire) + if not books then + local status = type(wire) == "table" and tonumber(wire.status) + if status then reason = (reason or _("请求失败")) .. " (" .. status .. ")" end + cb(nil, reason or _("书旗登录已失效,请点「重新登录」,用手机验证码登录。")) + return + end + cb(books, nil, wire) + end) +end + +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return HttpJob|nil +function Client.shelfAsync(cb) + return syncAsync({}, cb) +end + +---@param stable_id string +---@param action integer +---@param extra { title: string|nil, author: string|nil, cover: string|nil }|nil +---@param cb fun(ok: boolean|nil, err: string|nil) +local function changeAsync(stable_id, action, extra, cb) + -- 页面 add_time 是 13 位毫秒,last_update 是秒字符串,书签行带书名。 + local now_ms = os.time() * 1000 + local row = { + bid = tonumber(stable_id) or stable_id, + action = action, + percent = 0, + source = 1, + offset = 0, + state = "", + offsetType = "", + add_time = now_ms, + last_update = tostring(os.time()), + } + if type(extra) == "table" then + if type(extra.title) == "string" and extra.title ~= "" then row.title = extra.title end + if type(extra.author) == "string" and extra.author ~= "" then row.author = extra.author end + if type(extra.cover) == "string" and extra.cover ~= "" then row.cover = extra.cover end + end + local cancelled, job, pending = false, nil, true + local first = syncAsync({ row }, function(books, err) + pending = false + if cancelled then return end + if not books then cb(nil, err or (action == 3 and _("移出书旗书架失败") or _("加入书旗书架失败"))); return end + job = Client.shelfAsync(function(fresh, reason) + if cancelled then return end + if not fresh then cb(nil, reason); return end + local present = false + for _idx, book in ipairs(fresh) do + if book.stable_id == stable_id then present = true; break end + end + if present ~= (action == 1) then cb(nil, _("同步结果未确认,请重试")); return end + cb(true) + end) + end) + if pending then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +---@param stable_id string +---@param cb fun(ok: boolean|nil, err: string|nil) +function Client.addAsync(stable_id, cb) + local cancelled, job, pending = false, nil, true + local first = Client.detailAsync(stable_id, function(book, err) + pending = false + if cancelled then return end + if not book then cb(nil, err); return end + job = changeAsync(stable_id, 1, { title = book.title, author = book.authors, cover = book.cover }, cb) + end) + if pending then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +---@param stable_id string +---@param cb fun(ok: boolean|nil, err: string|nil) +function Client.removeAsync(stable_id, cb) + return changeAsync(stable_id, 3, nil, cb) +end + +--- 阅读位置和书架是同一条书签。拉取是空书签同步,按 bid 取 chapterid。 +---@param stable_id string +---@param cb fun(mark: { chapter_id: string, title: string|nil, fraction: number }|nil, err: string|nil) +---@return HttpJob|nil +function Client.progressAsync(stable_id, cb) + return syncAsync({}, function(books, err, wire) + if not books then cb(nil, err); return end + cb(Mapper.mark(wire, stable_id)) + end) +end + +--- 更新阅读位置用 action 2。percent 是万分比,和网页 `(章序 / 总章数) * 10000` 一致。 +--- 加入书架仍是 action 1,那时候还没有章节位置。 +---@param stable_id string +---@param chapter_id string +---@param title string|nil +---@param fraction number +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return HttpJob|nil +function Client.putProgressAsync(stable_id, chapter_id, title, fraction, cb) + local now = os.time() + local percent = math.floor((tonumber(fraction) or 0) * 10000 + 0.5) + if percent < 1 then percent = 1 end + if percent > 10000 then percent = 10000 end + local row = { + bid = tonumber(stable_id) or stable_id, + action = 2, + percent = percent, + source = 1, + offset = 0, + state = "", + chapterid = tonumber(chapter_id) or chapter_id, + cname = title or "", + add_time = now * 1000, + last_update = tostring(now), + } + local cancelled, job, pending = false, nil, true + local first = syncAsync({ row }, function(books, err) + pending = false + if cancelled then return end + if not books then cb(nil, err or _("书旗进度保存失败")); return end + job = Client.progressAsync(stable_id, function(mark, reason) + if cancelled then return end + if reason then cb(nil, reason); return end + -- 服务端回读只保留三位小数,按同一精度确认,不能把舍入当成上传失败。 + if not mark or mark.chapter_id ~= chapter_id + or math.floor(mark.fraction * 1000 + 0.5) ~= math.floor(percent / 10 + 0.5) then + cb(nil, _("同步结果未确认,请重试")) + return + end + cb(true) + end) + end) + 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-shuqi.koplugin/moonsource_shuqi/l10n/en.lua b/moonsource-shuqi.koplugin/moonsource_shuqi/l10n/en.lua new file mode 100644 index 0000000..32cb9be --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/l10n/en.lua @@ -0,0 +1,58 @@ +return { + ["登录状态已变化,请重试"] = "The login session changed. Please retry.", + ["更新时间"] = "Updated", + ["同步结果未确认,请重试"] = "The remote change could not be confirmed. Please retry.", + ["请先退出旧书旗账号再换号;退出会清除本机该源的书架、进度、笔记和缓存。"] = "Log out of the previous Shuqi account before switching. Logging out clears this source's local shelf, progress, notes and cache.", + ["书旗登录 Cookie"] = "Shuqi sign-in Cookie", + ["在官网登录后,复制 t.shuqi.com 请求标头里的完整 Cookie"] = "Sign in on the official website, then copy the complete Cookie request header from t.shuqi.com.", + ["书旗 Cookie 缺少有效的登录凭证"] = "The Shuqi Cookie does not contain valid sign-in credentials.", + ["登录响应无效"] = "Invalid sign-in response", + ["书旗登录失败(状态:%s)"] = "Shuqi sign-in failed (status: %s)", + ["书旗登录触发安全验证,请在官网登录后导入 Cookie。"] = "Shuqi requires a security check. Sign in on the official website, then import its Cookie.", + ["登录环境初始化失败,请刷新重试"] = "Could not initialize the sign-in environment. Reload and try again.", + ["频道"] = "Channel", + ["字数"] = "Word count", + ["书旗小说"] = "Shuqi Novel", + ["书旗书架与在线阅读"] = "Shuqi shelf and online reading", + ["书旗账号"] = "Shuqi account", + ["未登录书旗"] = "Not signed in to Shuqi", + ["书旗目录为空"] = "Shuqi chapter list is empty", + ["书旗登录已失效,请点「重新登录」,用手机验证码登录。"] = "Shuqi sign-in has expired. Tap Sign in again and use the SMS code.", + ["确定退出书旗账号?"] = "Sign out of Shuqi?", + ["书旗滑块验证"] = "Shuqi slider verification", + ["拖动下方滑块完成验证"] = "Drag the slider to finish verification", + ["正在发送短信…"] = "Sending the SMS…", + ["验证失败,请重新滑动"] = "Verification failed. Slide again", + ["未注册的手机号将自动注册书旗账号。继续即同意书旗用户协议和隐私政策。"] = "An unregistered phone number will register a Shuqi account. Continuing means you agree to the Shuqi terms and privacy policy.", + ["滑块在同一 Wi-Fi 的浏览器里完成"] = "Complete the slider in a browser on the same Wi-Fi", + ["书旗账号缺少用户编号"] = "The Shuqi account has no user id", + ["移出书旗书架失败"] = "Could not remove the book from the Shuqi shelf", + ["加入书旗书架失败"] = "Could not add the book to the Shuqi shelf", + ["书旗进度保存失败"] = "Could not save the Shuqi position", + ["缺少书旗章节位置"] = "Missing the Shuqi chapter position", + ["正文为空"] = "Chapter text is empty", + ["正文解密失败"] = "Could not decrypt the chapter", + ["本章未购买"] = "This chapter has not been purchased", + ["验证已过期,请重新发起验证"] = "Verification expired. Please start again", + ["正在登录…"] = "Signing in…", + ["章节目录保存失败"] = "Failed to save chapter list", + ["请先填写验证码"] = "Enter the verification code first", + ["用同一 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", + ["同意并继续"] = "Agree and continue", + ["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "Cannot open remote verification. Connect to Wi-Fi and enable Remote management first.", + ["验证已取消"] = "Verification cancelled", + ["验证凭据无效"] = "Invalid verification proof", + ["登录验证脚本加载失败,可能被广告拦截插件阻止。请检查插件设置或网络,也可改用 Cookie 登录。"] = "Could not load a sign-in verification script. An ad blocker may be blocking it. Check your extension settings or connection, or use Cookie sign-in instead.", + ["登录验证脚本加载超时,可能被广告拦截插件阻止。请检查插件设置或网络后重试,也可改用 Cookie 登录。"] = "A sign-in verification script timed out. An ad blocker may be blocking it. Check your extension settings or connection and retry, or use Cookie sign-in instead.", + ["重试"] = "Retry", + ["VIP 章节"] = "VIP chapters", + ["书架同步"] = "Shelf sync", + ["搜索与发现"] = "Search and discover", + ["进度同步"] = "Progress sync", + ["书旗"] = "Shuqi", +} diff --git a/moonsource-shuqi.koplugin/moonsource_shuqi/l10n/zh_TW.lua b/moonsource-shuqi.koplugin/moonsource_shuqi/l10n/zh_TW.lua new file mode 100644 index 0000000..8688889 --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/l10n/zh_TW.lua @@ -0,0 +1,58 @@ +return { + ["登录状态已变化,请重试"] = "登入狀態已改變,請重試", + ["更新时间"] = "更新時間", + ["同步结果未确认,请重试"] = "同步結果尚未確認,請重試", + ["请先退出旧书旗账号再换号;退出会清除本机该源的书架、进度、笔记和缓存。"] = "請先登出舊書旗帳號再換帳號;登出會清除本機此書源的書架、進度、筆記和快取。", + ["书旗登录 Cookie"] = "書旗登入 Cookie", + ["在官网登录后,复制 t.shuqi.com 请求标头里的完整 Cookie"] = "在官網登入後,複製 t.shuqi.com 請求標頭裡的完整 Cookie", + ["书旗 Cookie 缺少有效的登录凭证"] = "書旗 Cookie 缺少有效的登入憑證", + ["登录响应无效"] = "登入回應無效", + ["书旗登录失败(状态:%s)"] = "書旗登入失敗(狀態:%s)", + ["书旗登录触发安全验证,请在官网登录后导入 Cookie。"] = "書旗登入觸發安全驗證,請在官網登入後匯入 Cookie。", + ["登录环境初始化失败,请刷新重试"] = "登入環境初始化失敗,請重新整理後重試", + ["频道"] = "頻道", + ["字数"] = "字數", + ["书旗小说"] = "書旗小說", + ["书旗书架与在线阅读"] = "書旗書架與線上閱讀", + ["书旗账号"] = "書旗帳號", + ["未登录书旗"] = "未登入書旗", + ["书旗目录为空"] = "書旗目錄為空", + ["书旗登录已失效,请点「重新登录」,用手机验证码登录。"] = "書旗登入已失效,請點「重新登入」,用手機驗證碼登入。", + ["确定退出书旗账号?"] = "確定退出書旗帳號?", + ["书旗滑块验证"] = "書旗滑塊驗證", + ["拖动下方滑块完成验证"] = "拖動下方滑塊完成驗證", + ["正在发送短信…"] = "正在發送簡訊…", + ["验证失败,请重新滑动"] = "驗證失敗,請重新滑動", + ["未注册的手机号将自动注册书旗账号。继续即同意书旗用户协议和隐私政策。"] = "未註冊的手機號將自動註冊書旗帳號。繼續即同意書旗使用者協議和隱私權政策。", + ["滑块在同一 Wi-Fi 的浏览器里完成"] = "滑塊在同一個 Wi-Fi 的瀏覽器裡完成", + ["书旗账号缺少用户编号"] = "書旗帳號缺少使用者編號", + ["移出书旗书架失败"] = "移出書旗書架失敗", + ["加入书旗书架失败"] = "加入書旗書架失敗", + ["书旗进度保存失败"] = "書旗進度保存失敗", + ["缺少书旗章节位置"] = "缺少書旗章節位置", + ["正文为空"] = "正文為空", + ["正文解密失败"] = "正文解密失敗", + ["本章未购买"] = "本章未購買", + ["验证已过期,请重新发起验证"] = "驗證已過期,請重新發起驗證", + ["正在登录…"] = "正在登入…", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["请先填写验证码"] = "請先填寫驗證碼", + ["用同一 Wi-Fi 下的手机扫码,只完成滑块;短信验证码请回到设备填写。"] = "用同一 Wi-Fi 下的手機掃碼,只完成滑塊;簡訊驗證碼請回到裝置填寫。", + ["验证通过,短信已发送,请回到设备填写验证码。"] = "驗證通過,簡訊已傳送,請回到裝置填寫驗證碼。", + ["短信已发送,请在设备上填写验证码"] = "簡訊已傳送,請在裝置上填寫驗證碼", + ["手机号"] = "手機號碼", + ["请填写正确的手机号"] = "請填寫正確的手機號碼", + ["发送验证码"] = "傳送驗證碼", + ["同意并继续"] = "同意並繼續", + ["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "無法打開遠端驗證,請先連接 Wi-Fi 並啟用遠端管理功能", + ["验证已取消"] = "驗證已取消", + ["验证凭据无效"] = "驗證憑據無效", + ["登录验证脚本加载失败,可能被广告拦截插件阻止。请检查插件设置或网络,也可改用 Cookie 登录。"] = "登入驗證腳本載入失敗,可能被廣告攔截外掛阻擋。請檢查外掛設定或網路,也可改用 Cookie 登入。", + ["登录验证脚本加载超时,可能被广告拦截插件阻止。请检查插件设置或网络后重试,也可改用 Cookie 登录。"] = "登入驗證腳本載入逾時,可能被廣告攔截外掛阻擋。請檢查外掛設定或網路後重試,也可改用 Cookie 登入。", + ["重试"] = "重試", + ["VIP 章节"] = "VIP 章節", + ["书架同步"] = "書架同步", + ["搜索与发现"] = "搜尋與發現", + ["进度同步"] = "進度同步", + ["书旗"] = "書旗", +} diff --git a/moonsource-shuqi.koplugin/moonsource_shuqi/loadmeta.lua b/moonsource-shuqi.koplugin/moonsource_shuqi/loadmeta.lua new file mode 100644 index 0000000..2937fa8 --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_shuqi._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-shuqi.koplugin/moonsource_shuqi/mapper.lua b/moonsource-shuqi.koplugin/moonsource_shuqi/mapper.lua new file mode 100644 index 0000000..eb44222 --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/mapper.lua @@ -0,0 +1,438 @@ +--[[-- +书旗网页响应 → 领域对象。纯函数,不发请求。 + +搜索签名把缺省的密钥参数拼进字符串,网页因此得到字面量 "undefined"。 +正文是 ROT13 后再 Base64 的 HTML。 + +@module moonsource_shuqi.mapper +--]] + +local Text = require("utils.text") + +local Mapper = {} + +local SOURCE_ID = "ext.shuqi" +local WALDEN_KEY = "37e81a9d8f02596e1b895d07c171d5c9" +local AND_KEY = "4b283ed2f94f02242415cc49fc4e3616" +local OCEAN_KEY = "eefc4798f28ea41622487ad80ef7e81c" + +--- 目录缓存格式。首章携带,变了就当缓存失效。 +Mapper.TOC_VERSION = 1 + +---@type fun(text: string): string +local md5 = require("ffi/sha2").md5 + +--- encodeURIComponent 后按网页 forceJava 再编码。 +---@param value any +---@return string +function Mapper.javaEncode(value) + local encoded = tostring(value):gsub("([^%w%-_%.!*'%(%)~])", function(char) + return string.format("%%%02X", char:byte()) + end) + encoded = encoded:gsub("%%20", "+") + encoded = encoded:gsub("%(", "%%28") + encoded = encoded:gsub("%)", "%%29") + encoded = encoded:gsub("~", "%%7E") + encoded = encoded:gsub("!", "%%21") + return (encoded:gsub("'", "%%27")) +end + +--- 书旗网关签名:排序后 key=javaEncode(value),末尾 &skey=。 +---@param fields table +---@param skey string|nil +---@return string +function Mapper.gatewaySign(fields, skey) + local keys = {} + for key, value in pairs(fields) do + if value ~= nil and key ~= "sign" and key ~= "key" and key ~= "_public" then + keys[#keys + 1] = key + end + end + table.sort(keys) + local parts = {} + for _idx, key in ipairs(keys) do + parts[#parts + 1] = key .. "=" .. Mapper.javaEncode(fields[key]) + end + return md5(table.concat(parts, "&") .. "&skey=" .. (skey or OCEAN_KEY)) +end + +--- 搜索签名。网页签名函数的密钥参数是 undefined,拼进字符串后就是这六个字母。 +---@param timestamp string|number +---@return string +function Mapper.searchSign(timestamp) + return md5(tostring(timestamp) .. "undefined") +end + +--- 正文接口签名:参与签名的字段按键名排序,只拼接值,再加密钥。 +---@param fields table +---@return string +function Mapper.contentSign(fields) + local keys = {} + for key in pairs(fields) do keys[#keys + 1] = key end + table.sort(keys) + local parts = {} + for _idx, key in ipairs(keys) do parts[#parts + 1] = tostring(fields[key]) end + return md5(table.concat(parts) .. WALDEN_KEY) +end + +--- 分类榜签名。参与的 imei、sn 为空,user_id 不在请求里,只剩时间戳加密钥。 +---@param timestamp string|number +---@return string +function Mapper.rankSign(timestamp) + return md5(tostring(timestamp) .. AND_KEY) +end + +---@param id any +---@param title any +---@param author any +---@param intro any +---@param cover any +---@return Book +local function book(id, title, author, intro, cover) + local function clean(value) + if type(value) ~= "string" then return "" end + return Text.trim(Text.xmlDecode(value)) + end + local picture = type(cover) == "string" and cover ~= "" and Text.xmlDecode(cover) or nil + if picture and picture:sub(1, 2) == "//" then picture = "https:" .. picture end + return { + source_id = SOURCE_ID, + stable_id = tostring(id), + title = clean(title), + authors = clean(author), + intro = clean(intro), + cover = picture, + } +end + +---@param rows table|nil +---@return Book[] +local function books(rows) + local out = {} + if type(rows) ~= "table" then return out end + for _idx, row in ipairs(rows) do + if type(row) == "table" and (row.bid or row.bookId or row.bookid) then + out[#out + 1] = book( + row.bid or row.bookId or row.bookid, + row.title or row.bookName, + row.author or row.authorName, + row.desc or row.intro, + row.cover or row.imgUrl) + end + end + return out +end + +--- 搜索 / 分类榜。status 为 1 才是成功。 +---@param wire table|nil +---@return Book[]|nil +---@return string|nil err +function Mapper.searchBooks(wire) + if type(wire) ~= "table" or tonumber(wire.status) ~= 1 then + local info = type(wire) == "table" and wire.info or nil + return nil, type(info) == "table" and info.message or nil + end + if type(wire.data) ~= "table" then return nil, "响应无效" end + return books(wire.data) +end + +--- 节点只允许官网书库的筛选参数,不接受任意 URL。 +---@param node string|nil +---@return string|nil +function Mapper.storeNode(node) + if type(node) ~= "string" or node == "" then return nil end + local fields = {} + for part in node:gmatch("[^&]+") do + local key, value = part:match("^([%w]+)=(.+)$") + if not key or not ({ sz = true, fc = true, wd = true, tm = true, st = true })[key] + or fields[key] then return nil end + value = Text.urlDecode(value) + if not value:match("^%d+[,%d]*$") then return nil end + fields[key] = value + end + if not fields.sz then return nil end + return Text.formEncode(fields) +end + +---@param html string +---@return Book[]|nil, StoreChipGroup[]|nil, boolean|nil +function Mapper.store(html) + local list = html:match('
    ]*>(.-)
') + if not list then return nil end + local out, groups = {}, {} + for card in list:gmatch("]*>(.-)") do + local id = card:match('href="/book/(%d+)%.html"') + local title = card:match("]*>(.-)") + local author = card:match('href="/author/[^"]*"[^>]*>作者:(.-)') + local intro = card:match('

]*>(.-)

') + local cover = card:match(']*src="([^"]+)"') + if not id or not title then return nil end + out[#out + 1] = book(id, Text.stripHtml(title), author, intro, cover) + end + local filters = html:match('
]*>(.-)
]*>.-", ""):gsub("", "") + for title, block in filters:gmatch(']*>(.-)(.-)') do + local chips, active = {}, nil + for attrs, link, label in block:gmatch('<([%w]+[^>]-)>%s*]*href="([^"]+)"[^>]*>(.-)') do + local query = Text.xmlDecode(link):match("^/store%?(.+)$") + local node = Mapper.storeNode(query) + if node then + chips[#chips + 1] = { id = node, title = Text.trim(Text.stripHtml(label)) } + if attrs:find("active", 1, true) then active = node end + end + end + if #chips > 1 then + groups[#groups + 1] = { title = Text.trim(Text.stripHtml(title)):gsub(":$", ""), chips = chips, active = active } + end + end + if #groups == 0 then return nil end + return out, groups, html:find('>下一页', 1, true) ~= nil +end + +---@param wire table +---@param book_id string +---@return table|nil +function Mapper.reviews(wire, book_id) + if tonumber(wire.status) ~= 200 or type(wire.data) ~= "table" or type(wire.info) ~= "table" + or not tonumber(wire.info.total) or not tonumber(wire.info.count) then return nil end + local items = {} + for _idx, row in ipairs(wire.data) do + if type(row) ~= "table" or tostring(row.bookId) ~= book_id or not row.mid + or type(row.text) ~= "string" then return nil end + local timestamp = tonumber(row.pubTime) + if row.pubTime ~= nil and not timestamp then return nil end + items[#items + 1] = { + id = tostring(row.mid), author = row.nickName, + text = Text.trim(Text.stripHtml(Text.xmlDecode(row.text))), + time = timestamp and os.date("%Y-%m-%d %H:%M", timestamp) or nil, + } + end + return { items = items, total = tonumber(wire.info.total), pages = tonumber(wire.info.count) } +end + +---@param wire table|nil +---@return Book|nil +function Mapper.detail(wire) + if type(wire) ~= "table" or tostring(wire.state) ~= "200" or type(wire.data) ~= "table" then + return nil + end + local data = wire.data + if not data.bookId and not data.bookName then return nil end + return book(data.bookId, data.bookName, data.authorName, data.desc or data.intro, data.imgUrl) +end + +---@param value any +---@return boolean +local function flag(value) + return value == true or value == 1 or value == "1" or value == "true" +end + +--- 目录。免费章带上正文地址,未购买的 VIP 章不带地址。 +---@param wire table|nil +---@return BookChapter[]|nil +function Mapper.chapters(wire) + if type(wire) ~= "table" or tostring(wire.state) ~= "200" or type(wire.data) ~= "table" then + return nil + end + local data = wire.data + local free_prefix = type(data.freeContUrlPrefix) == "string" and data.freeContUrlPrefix or "" + local charge_prefix = type(data.chargeContUrlPrefix) == "string" and data.chargeContUrlPrefix or "" + local out = {} + local volumes = type(data.chapterList) == "table" and data.chapterList or {} + for _vol_idx, volume in ipairs(volumes) do + local list = nil + if type(volume) == "table" then + list = volume.volumeList or volume.chapterList + if type(list) ~= "table" and volume.chapterId then list = { volume } end + end + if type(list) == "table" then + for _idx, row in ipairs(list) do + if type(row) == "table" and row.chapterId then + local free = flag(row.isFreeRead) or row.payStatus == 0 or row.payStatus == "0" + local bought = flag(row.isBuy) + local suffix = type(row.contUrlSuffix) == "string" and row.contUrlSuffix or "" + local url = nil + if free and free_prefix ~= "" and suffix ~= "" then + url = free_prefix .. suffix + elseif bought and suffix ~= "" then + local prefix = charge_prefix ~= "" and charge_prefix or free_prefix + if prefix ~= "" then url = prefix .. suffix end + end + out[#out + 1] = { + idx = #out + 1, + uid = tostring(row.chapterId), + title = type(row.chapterName) == "string" and Text.trim(row.chapterName) or "", + source_idx = row.chapterOrdid and tostring(row.chapterOrdid) or nil, + vip = not free, + content_url = url, + } + end + end + end + end + if out[1] then out[1].toc_version = Mapper.TOC_VERSION end + return out +end + +--- 网页 rot13:非字母原样,A/a 都转到 N/n。 +---@param text string +---@return string +local function rot13(text) + return (text:gsub("[%a]", function(char) + local base = char:byte() >= 97 and 96 or 64 + local n = (char:lower():byte() - 83) % 26 + if n == 0 then n = 26 end + return string.char(n + base) + end)) +end + +--- 正文。先 ROT13 再 Base64,得到带 br 的 HTML,收成纯文本。 +---@param wire table|nil +---@return string|nil +---@return string|nil err +function Mapper.chapterText(wire) + if type(wire) ~= "table" or tostring(wire.state) ~= "200" then + return nil, type(wire) == "table" and (wire.message or wire.msg) or nil + end + local cipher = wire.ChapterContent + if type(cipher) ~= "string" or cipher == "" then return nil, "正文为空" end + local html = Text.base64Decode(rot13(cipher)) + html = html:gsub("<[Bb][Rr]%s*/?>", "\n") + html = html:gsub("<[^>]+>", "") + local text = Text.trim(Text.xmlDecode(html)) + if text == "" then return nil, "正文解密失败" end + return text +end + +---@param wire table|nil +---@return { male: table, female: table, press: table }|nil +function Mapper.channels(wire) + if type(wire) ~= "table" or tostring(wire.state) ~= "200" or type(wire.data) ~= "table" then + return nil + end + local function list(key) + local group = wire.data[key] + local rows = type(group) == "table" and group.groupList or {} + local chips = {} + if type(rows) ~= "table" then return chips end + for _idx, row in ipairs(rows) do + if type(row) == "table" and type(row.showName) == "string" and row.showName ~= "" then + chips[#chips + 1] = { id = row.showName, title = row.showName } + end + end + return chips + end + return { male = list("male"), female = list("female"), press = list("press") } +end + +--- 登录成功。token 在 data 里,用户号在 userInfo.userid。 +---@param wire table|nil +---@return { token: string, user_id: string|nil, name: string }|nil +---@return string|nil err +function Mapper.session(wire) + if type(wire) ~= "table" or tonumber(wire.status) ~= 200 or type(wire.data) ~= "table" then + return nil, type(wire) == "table" and wire.message or nil + end + local data = wire.data + if type(data.token) ~= "string" or data.token == "" then + return nil, wire.message + end + local info = type(data.userInfo) == "table" and data.userInfo or {} + local user_id = info.userid or info.userId or info.id + local name = "" + if type(info.nickName) == "string" and info.nickName ~= "" then name = info.nickName + elseif type(info.nickname) == "string" then name = info.nickname end + return { + token = data.token, + user_id = user_id and tostring(user_id) or nil, + name = name, + } +end + +--- 网页 Cookie 里的会话字段;只解析,不据此认定已登录。 +---@param cookie string +---@return table|nil +function Mapper.cookieSession(cookie) + local values = {} + for name, value in cookie:gmatch("([^;=%s]+)=([^;]*)") do + values[name] = Text.urlDecode(value:gsub("%+", "%%2B")) + end + local id, token = values.shuqi_user_id, values.shuqi_token + if not id or not id:match("^%d+$") or tonumber(id) == 0 or id == "8000000" + or not token or token == "" or token:find("[%s;\r\n]") then return nil end + return { user_id = id, token = token, name = "", fingerprint = values.shuqi_fingerprint } +end + +--- userBaseInfo 的 data 按用户编号索引;必须和待校验 Cookie 的账号一致。 +---@param wire table|nil +---@param user_id string +---@return table|nil +function Mapper.account(wire, user_id) + if type(wire) ~= "table" or (tonumber(wire.status) or tonumber(wire.state)) ~= 200 + or type(wire.data) ~= "table" then return nil end + local info = wire.data[user_id] + if type(info) ~= "table" or tostring(info.userId) ~= user_id then return nil end + return { user_id = user_id, name = type(info.nickName) == "string" and info.nickName or "" } +end + +--- 短信接口。status / state 为 200 算发送成功。 +---@param wire table|nil +---@return boolean +---@return string|nil err +function Mapper.sent(wire) + if type(wire) ~= "table" then return false, nil end + local status = tonumber(wire.status) or tonumber(wire.state) + if status == 200 then return true end + return false, wire.message or wire.msg +end + +--- 书签同步的书在 detail。网页把同一份包在 data 里,顶层只剩 status / message。 +---@param wire table|nil +---@return table|nil +local function shelfRows(wire) + if type(wire) ~= "table" then return nil end + if wire.status ~= nil and tonumber(wire.status) ~= 200 then return nil end + if type(wire.detail) == "table" then return wire.detail end + local data = wire.data + if type(data) == "table" and type(data.detail) == "table" then return data.detail end + return nil +end + +--- 没有 detail 视为失败,空数组是空书架。 +---@param wire table|nil +---@return Book[]|nil +---@return string|nil err +function Mapper.shelf(wire) + local rows = shelfRows(wire) + if not rows then return nil, type(wire) == "table" and (wire.message or wire.msg) or nil end + return books(rows) +end + +--- 书签行里的阅读位置。网页把服务端的 percent(0..1)乘 10000 再存。 +--- 没有章节号就是还没读过。 +---@param wire table|nil +---@param stable_id string +---@return { chapter_id: string, title: string|nil, fraction: number }|nil +function Mapper.mark(wire, stable_id) + local rows = shelfRows(wire) + if type(rows) ~= "table" then return nil end + for _idx, row in ipairs(rows) do + if type(row) == "table" and tostring(row.bid or "") == tostring(stable_id) then + local chapter_id = row.chapterid or row.chapterId + if chapter_id == nil or tostring(chapter_id) == "" or tostring(chapter_id) == "0" then return nil end + local percent = tonumber(row.percent) or 0 + if percent > 1 then percent = percent / 10000 end + if percent < 0 then percent = 0 end + if percent > 1 then percent = 1 end + return { + chapter_id = tostring(chapter_id), + title = type(row.cname) == "string" and row.cname ~= "" and row.cname or nil, + fraction = percent, + } + end + end + return nil +end + +return Mapper diff --git a/moonsource-shuqi.koplugin/moonsource_shuqi/setting.lua b/moonsource-shuqi.koplugin/moonsource_shuqi/setting.lua new file mode 100644 index 0000000..880a9a9 --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/setting.lua @@ -0,0 +1,209 @@ +--[[-- +书旗账号:手机验证码、官网浏览器授权和 Cookie 导入。 + +@module moonsource_shuqi.setting +--]] + +local _ = require("l10n").get("moonsource_shuqi") +local CookieLogin = require("source.cookie_login") + +local SOURCE_ID = "ext.shuqi" +local Setting = {} +local LOGIN_URL = "https://t2.shuqi.com/oauth/login?priority=code&redirect_uri=https%3A%2F%2Ft.shuqi.com%2Fmyself" + +---@return boolean +local function loggedIn() + return require("moonsource_shuqi.client").loggedIn() +end + +---@param cookie string +---@param cb fun(ok: boolean, err: string|nil) +local function saveCookie(cookie, cb) + return require("moonsource_shuqi.client").loginCookieAsync(cookie, function(session, err) + if session then + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() + end + cb(session ~= nil, err) + end) +end + +local function pasteCookie() + local Toast = require("ui.themes.widgets.toast") + if not require("ui/network/manager"):isConnected() then + Toast:new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show() + return + end + require("ui.themes.widgets.input"):new{ + title = _("书旗登录 Cookie"), + fields = { { text = "", hint = _("在官网登录后,复制 t.shuqi.com 请求标头里的完整 Cookie") } }, + ok_text = _("登录"), + callback = function(value) + if not require("ui/network/manager"):isConnected() then + Toast:new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show() + return + end + local job, cancelled + local waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("书旗账号"), text = _("正在校验登录…"), dismissable = false, + on_cancel = function() + cancelled = true + if job then job.cancel() end + end, + } + waiting:show() + job = saveCookie(value, function(ok, err) + if cancelled then return end + waiting:close() + Toast:new{ text = ok and _("登录成功") or err, timeout = ok and 2 or 3 }:show() + end) + end, + }:show() +end + +Setting.browser = { + domain = "t.shuqi.com", scope = "cookie", login = LOGIN_URL, + check = "https://t.shuqi.com/myself", + icon = "https://t.shuqi.com/favicon.ico", + isAuthorized = function() return loggedIn() and not require("source.auth").expired(SOURCE_ID) end, + apply = function(payload, cb) + local cookies = {} + for _idx, cookie in ipairs(type(payload.cookies) == "table" and payload.cookies or {}) do + local host = type(cookie) == "table" and type(cookie.domain) == "string" + and cookie.domain:gsub("^%.", ""):lower() + if host == "shuqi.com" or host == "t.shuqi.com" then cookies[#cookies + 1] = cookie end + end + return saveCookie(CookieLogin.fromPayload({ cookies = cookies }, "shuqi.com"), cb) + end, +} + +local function showLogin() + local Toast = require("ui.themes.widgets.toast") + local function connected(run) + if require("ui/network/manager"):isConnected() then return run() end + Toast:new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show() + end + if not require("ui/network/manager"):isConnected() then + Toast:new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show() + return + end + 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 = _("未注册的手机号将自动注册书旗账号。继续即同意书旗用户协议和隐私政策。"), + 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() + connected(function() + if closed then return end + if verification then verification:cancel() end + verification = require("moonsource_shuqi.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() + connected(function() + local job, cancelled = nil, false + local waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("书旗账号"), text = _("正在登录…"), dismissable = false, + on_cancel = function() + cancelled = true + if job then job.cancel() end + end, + } + waiting:show() + local browser = verification and verification.phone == phone and verification.browser or nil + job = require("moonsource_shuqi.client").loginAsync(phone, code, browser, function(session, err) + if cancelled then return end + waiting:close() + if not session then + Toast:new{ text = err or _("登录失败"), timeout = 3 }:show() + return + end + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() + Toast:new{ text = _("登录成功"), timeout = 2 }:show() + end) + end) + end) + end, + } + dialog:show() +end + +---@return string, boolean +function Setting.rowStatus() + local on = loggedIn() + return on and _("已登录") or _("未登录 · 点此登录"), on +end + +---@return table[] +function Setting.rows() + 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 = _("书旗账号"), + subtitle = not status_on and _("滑块在同一 Wi-Fi 的浏览器里完成") or nil, + 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 = "content_paste", + title = _("粘贴 Cookie"), callback = pasteCookie }) + 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, cfg.user_id, cfg.name = nil, nil, nil + cfg.logged_in, cfg.imei, cfg.umidtoken, cfg.wua = nil, nil, nil, nil + settings.saveSource(SOURCE_ID) + require("moonsource_shuqi.client").reset() + end) + return rows +end + +Setting.login = showLogin + +return Setting diff --git a/moonsource-shuqi.koplugin/moonsource_shuqi/source.lua b/moonsource-shuqi.koplugin/moonsource_shuqi/source.lua new file mode 100644 index 0000000..f372714 --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/source.lua @@ -0,0 +1,250 @@ +--[[-- +书旗数据源。 + +搜索、分类和免费章节不需要登录。书架在验证码登录后用书签同步。 +未购买的 VIP 章给一页提示,不当成缓存。 + +@module moonsource_shuqi +--]] + +local Browse = require("source.browse") +local Client = require("moonsource_shuqi.client") +local Mapper = require("moonsource_shuqi.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_shuqi") + +local Shuqi = {} + +---@return BookSourceMeta +function Shuqi.meta() + return require("moonsource_shuqi.loadmeta")() +end + +---@class ShuqiSource : SourceBase +local Source = setmetatable({ shelf_add = true }, { __index = SourceBase }) +Source.__index = Source + +---@return ShuqiSource +function Shuqi.new() + local meta = Shuqi.meta() + return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source) +end + +---@return boolean +function Source:configured() + return Client.loggedIn() +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, "shuqi 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 node = Mapper.storeNode(opts and opts.node) + local limit = opts and opts.limit or 60 + local handle = {} + local function firstPage() + local pending = true + local first = Client.storeAsync(node, 1, function(html, err) + pending = false + if handle.cancelled then return end + if not html then cb(nil, err); return end + local books, groups, more = Mapper.store(html) + if not books or not groups then cb(nil, _("响应无效")); return end + -- 旧版保存分类名;用官网当前链接迁移,不维护分类 ID 对照表。 + if not node and opts and opts.node then + for _idx, group in ipairs(groups) do + for _chip_idx, chip in ipairs(group.chips) do + if chip.title == opts.node then node = chip.id; firstPage(); return end + end + end + end + local titles = { + ["作品类型"] = _("频道"), ["作品分类"] = _("分类"), ["作品状态"] = _("状态"), + ["作品字数"] = _("字数"), ["更新时间"] = _("更新时间"), + } + for _idx, group in ipairs(groups) do group.title = titles[group.title] or group.title end + handle.inner = Browse.pages(function(page, done) + if page == 1 then done(books, nil, more); return end + return Client.storeAsync(node, page, function(raw, reason) + if not raw then done(nil, reason); return end + local list, _groups, has_more = Mapper.store(raw) + done(list, not list and _("响应无效") or nil, has_more) + end) + end, limit, groups, function(result, reason) + if result then + for index = #result.data, limit + 1, -1 do result.data[index] = nil end + end + cb(result, reason) + end) + end) + if pending then handle.inner = first end + end + firstPage() + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner.cancel() end + end + return handle +end + +function Source:bookReviewsAsync(identity, cb) + return Client.reviewsAsync(identity.stable_id, 1, cb) +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 ShuqiSource +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +local function fetchTocAsync(self, identity, cb) + return Client.chaptersAsync(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 then + return SourceBase.defer(cb, cached) + end + end + return fetchTocAsync(self, identity, cb) +end + +Source.refreshTocAsync = fetchTocAsync + +---@param self ShuqiSource +---@param open boolean +---@return ChapterFetchContent +local function fetcher(self, open) + return function(identity, chapter, done) + if chapter.vip and (type(chapter.content_url) ~= "string" or chapter.content_url == "") 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 + return Client.contentAsync(chapter.content_url, function(text, err) + if text then done({ title = chapter.title, html = Text.chapterHtml(chapter.title, text) }); return end + done(nil, err) + 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 = fetcher(self, true), + }, 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), + }, 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) +end + +function Source:getProgressAsync(identity, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录书旗")) end + local cancelled, job, pending = false, nil, true + local first = Client.progressAsync(identity.stable_id, function(mark, err) + pending = false + if cancelled then return end + if err then cb(nil, err); return end + if not mark then cb(nil, nil, { empty = true }); return end + 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 = Toc.index(self.id, identity.stable_id, mark.chapter_id) + if not idx then cb(nil, nil, { empty = true }); return end + local fraction = mark.fraction + if not fraction or fraction <= 0 then fraction = (idx - 1) / #toc end + cb({ + chapter_idx = idx, + chapter_title = toc[idx].title, + fraction = fraction, + extra = { chapter_uid = mark.chapter_id, chapter_idx = idx }, + }) + end) + end) + if pending then job = first end + return { cancel = function() + cancelled = true + if job and job.cancel then job.cancel() end + end } +end + +function Source:putProgressAsync(identity, pos, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录书旗")) end + local cancelled, job, pending = false, nil, true + local first = self:loadTocAsync(identity, function(toc, err) + pending = false + 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 + job = Client.putProgressAsync(identity.stable_id, chapter.uid, chapter.title, idx / #toc, function(ok, perr) + if cancelled then return end + cb(ok and true or nil, perr) + end) + end) + if pending then job = first end + return { cancel = function() + cancelled = true + if job and job.cancel then job.cancel() end + end } +end + +return Shuqi diff --git a/moonsource-shuqi.koplugin/moonsource_shuqi/verify.lua b/moonsource-shuqi.koplugin/moonsource_shuqi/verify.lua new file mode 100644 index 0000000..f0f439f --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/verify.lua @@ -0,0 +1,138 @@ +--[[-- +书旗发送短信前的阿里云滑块:浏览器只交滑块参数,手机号与短信码留在设备。 +一次发送拥有一张五分钟票据。 + +@module koplugin.book.moonsource_shuqi.verify +--]] + + +local Ext = require("utils.extension") +local Client = require("moonsource_shuqi.client") +local _ = require("l10n").get("moonsource_shuqi") + +---@class ShuqiVerification +---@field ticket string +---@field phone string +---@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 +---@field browser table|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 and self.pending.job.cancel 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 ShuqiVerification +function Verification.new(phone, cb) + local self = setmetatable({ + ticket = require("utils.random").hex(24), phone = phone, + callback = cb, expires = os.time() + 300, + }, Verification) + self.timeout = require("ui.guard").wrap("shuqi 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", "/shuqi_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 value any +---@param limit integer +---@return string|nil +local function bounded(value, limit) + if value == nil then return "" end + if type(value) ~= "string" or #value > limit then return nil end + return value +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 then + return reply(403, { error = _("验证已过期,请重新发起验证") }) + end + if action == "config" then + return reply(200, { + title = _("书旗滑块验证"), + instruction = _("拖动下方滑块完成验证"), + pending = _("正在发送短信…"), + success = _("验证通过,短信已发送,请回到设备填写验证码。"), + failure = _("验证失败,请重新滑动"), + load_error = _("登录验证脚本加载失败,可能被广告拦截插件阻止。请检查插件设置或网络,也可改用 Cookie 登录。"), + load_timeout = _("登录验证脚本加载超时,可能被广告拦截插件阻止。请检查插件设置或网络后重试,也可改用 Cookie 登录。"), + environment_error = _("登录环境初始化失败,请刷新重试"), + retry = _("重试"), + }) + end + local captcha = bounded(params.captcha, 8192) + local fingerprint = bounded(params.fingerprint, 256) + local umidtoken = bounded(params.umidtoken, 4096) + local wua = bounded(params.wua, 8192) + local user_agent = bounded(params.user_agent, 512) + if not captcha or captcha == "" or not fingerprint or not umidtoken or not wua then + return reply(400, { error = _("验证凭据无效") }) + end + if not user_agent or user_agent:find("[\r\n]") then return reply(400, { error = _("验证凭据无效") }) end + if session.pending then return reply(409, { error = _("正在发送短信…") }) end + local browser = { fingerprint = fingerprint, umidtoken = umidtoken, wua = wua, user_agent = user_agent } + local operation = {} + session.pending = operation + operation.job = Client.sendCodeAsync(session.phone, captcha, function(ok, err) + if session.done then return reply(403, { error = _("验证已过期,请重新发起验证") }) end + if session.pending ~= operation then return end + if os.time() >= session.expires then + session:finish(false, _("验证已过期,请重新发起验证")) + return reply(403, { error = _("验证已过期,请重新发起验证") }) + end + session.pending = nil + if not ok then return reply(400, { error = err or _("验证失败,请重新滑动") }) end + session.browser = browser + reply(200, { ok = true }) + session:finish(true) + end, browser) +end + +local dir = debug.getinfo(1, "S").source:sub(2):match("(.*/)") +Ext.add("web.routes", { + name = "shuqi_verify", dir = dir .. "web", + assets = { "shuqi_verify.html", "shuqi_verify.js" }, + public = { config = true, verify = true }, handle = handle, +}) + +return Verification diff --git a/moonsource-shuqi.koplugin/moonsource_shuqi/web/shuqi_verify.html b/moonsource-shuqi.koplugin/moonsource_shuqi/web/shuqi_verify.html new file mode 100644 index 0000000..04578f9 --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/web/shuqi_verify.html @@ -0,0 +1,25 @@ + + + + + + +月读 + + + + +
+

月读

+

+
+

+ +
+ + + diff --git a/moonsource-shuqi.koplugin/moonsource_shuqi/web/shuqi_verify.js b/moonsource-shuqi.koplugin/moonsource_shuqi/web/shuqi_verify.js new file mode 100644 index 0000000..944fa60 --- /dev/null +++ b/moonsource-shuqi.koplugin/moonsource_shuqi/web/shuqi_verify.js @@ -0,0 +1,148 @@ +(async function () { + 'use strict'; + const ticket = location.hash.slice(1); + const status = document.getElementById('status'); + const retry = document.getElementById('retry'); + let messages, captcha, browser; + let loading = true; + async function request(action, body) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 45000); + try { + const response = await fetch('/api/shuqi_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; + } + function loadScript(src, ready) { + if (ready()) return Promise.resolve(); + return new Promise((resolve, reject) => { + const script = document.createElement('script'); + const timer = setTimeout(() => finish(messages.load_timeout || messages.load_error), 20000); + function finish(error) { + clearTimeout(timer); + script.onload = script.onerror = null; + if (error) { + script.remove(); + reject(new Error(error + '\n' + src)); + } else resolve(); + } + script.src = src; + script.onload = () => finish(ready() ? null : messages.load_error); + script.onerror = () => finish(messages.load_error); + document.head.appendChild(script); + }); + } + async function prepareBrowser() { + const scripts = await Promise.allSettled([ + loadScript('https://render-resource.11222.cn/third/fingerprint2/fingerprint2.min.js', + () => typeof window.Fingerprint2 === 'function'), + loadScript('https://g.alicdn.com/AWSC/AWSC/awsc.js', () => typeof window.AWSC?.use === 'function'), + ]); + const failedScript = scripts.find(result => result.status === 'rejected'); + if (failedScript) throw failedScript.reason; + const fingerprint = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(messages.environment_error)), 20000); + new window.Fingerprint2().get((result) => { + clearTimeout(timer); + if (!result) reject(new Error(messages.environment_error)); + else resolve(result + '_shuqi_touch'); + }); + }); + function module(name) { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(messages.environment_error)), 20000); + window.AWSC.use(name, (state, sdk) => { + clearTimeout(timer); + if (state === 'loaded') resolve(sdk); + else reject(new Error(messages.environment_error)); + }); + }); + } + const [um, uab] = await Promise.all([module('um'), module('uab')]); + const umidtoken = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(messages.environment_error)), 20000); + um.init({ appName: 'wenxue-activity-proxy' }, (state, result) => { + clearTimeout(timer); + if (state === 'success' && result && result.tn) resolve(result.tn); + else reject(new Error(messages.environment_error)); + }); + }); + return { fingerprint, umidtoken, uab }; + } + async function loadCaptcha() { + if (!browser) browser = await prepareBrowser(); + await loadScript('https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js', + () => typeof window.initAliyunCaptcha === 'function'); + window.initAliyunCaptcha({ + SceneId: '1fujd071', + prefix: '1ff4ot', + mode: 'embed', + element: '#captcha-element', + immediate: true, + slideStyle: { width: Math.max(280, window.innerWidth - 40), height: 44 }, + language: 'cn', + timeout: 2000, + captchaVerifyCallback: async (captchaVerifyParam) => { + status.textContent = messages.pending; + try { + await request('verify', { + captcha: String(captchaVerifyParam || ''), + umidtoken: browser.umidtoken, + wua: browser.uab.getUA(), + fingerprint: browser.fingerprint, + user_agent: navigator.userAgent, + }); + status.textContent = messages.success; + document.getElementById('captcha-element').hidden = true; + retry.hidden = true; + return { captchaResult: true, bizResult: true }; + } catch (error) { + failed(error); + return { captchaResult: false, bizResult: false }; + } + }, + onBizResultCallback: () => {}, + getInstance: (instance) => { captcha = instance; }, + }); + } + retry.onclick = async () => { + if (loading) return; + retry.hidden = true; + status.textContent = ''; + document.getElementById('captcha-element').hidden = false; + loading = true; + try { + if (captcha && captcha.refresh) await captcha.refresh(); + else await loadCaptcha(); + } catch (error) { + failed(error); + } finally { + loading = false; + } + }; + 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; + } finally { + loading = false; + } +})(); diff --git a/tests/shuqi/browse_spec.lua b/tests/shuqi/browse_spec.lua new file mode 100644 index 0000000..006867e --- /dev/null +++ b/tests/shuqi/browse_spec.lua @@ -0,0 +1,86 @@ +--[[-- +书旗官网书库:动态筛选、分页、旧节点迁移和取消。 + +@module tests.moonsource_shuqi.browse_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Mapper = require("moonsource_shuqi.mapper") +local category = "fc=7&st=0&sz=0&tm=0&wd=10" +local filters = [[ +
+
作品类型:
+
+
作品分类:
+
+]] +local function pageHtml(page, next_page) + local cards = {} + for index = 1, 24 do + local id = (page - 1) * 24 + index + cards[#cards + 1] = '
  • 书' .. id + .. '

    作者:作者

    ' + .. '

    简介&摘要

  • ' + end + return filters .. '
      ' .. table.concat(cards) .. '
    ' + .. (next_page and '下一页' or "") +end +local books, groups, more = Mapper.store(pageHtml(1, true)) +Assert.len(books, 24) +Assert.eq(books[1].authors, "作者") +Assert.eq(books[1].intro, "简介&摘要") +Assert.eq(books[1].cover, "https://img.test/cover.jpg") +Assert.len(groups, 2) +Assert.eq(groups[1].active, "sz=0") +Assert.eq(groups[2].chips[2].id, category) +Assert.eq(groups[2].active, "fc=0&st=0&sz=0&tm=0&wd=10") +Assert.is_true(more) +Assert.is_nil(Mapper.store("维护")) +Assert.len(Mapper.store(filters .. '
      '), 0) +Assert.is_nil(Mapper.storeNode("sz=0&cookie=secret")) +Assert.is_nil(Mapper.storeNode("sz=0&sz=2")) +Assert.is_nil(Mapper.storeNode("../../myself")) +Assert.eq(Mapper.storeNode("sz=0&fc=34%2C102"), "fc=34%2C102&sz=0") + +local requests, delayed, failed = {}, false, false +package.loaded["http.request"] = { + get = function(url, options, cb) + local request = { url = url, options = options, cb = cb } + requests[#requests + 1] = request + local handle = { cancel = function() request.cancelled = true end } + local page = tonumber(url:match("page=(%d+)")) + if delayed and page == 2 then return handle end + if failed and page == 2 then cb(nil, "network down"); return handle end + cb(pageHtml(page, page < 3)) + return handle + end, +} +local source = require("moonsource_shuqi.source").new() +local result, reason +source:browseAsync({ limit = 60 }, function(value, err) result, reason = value, err end) +Assert.is_nil(reason) +Assert.len(result.data, 60) +Assert.eq(result.data[21].stable_id, "21") +Assert.is_nil(requests[1].options.headers.Cookie) +Assert.matches(requests[3].url, "page=3$") +requests = {} +source:browseAsync({ node = "都市", limit = 20 }, function(value) result = value end) +Assert.matches(requests[2].url, "fc=7") +Assert.len(result.data, 20) + +failed = true +source:browseAsync({}, function(value, err) result, reason = value, err end) +Assert.is_nil(result) +Assert.eq(reason, "network down") +failed, delayed = false, true +local calls = 0 +local handle = source:browseAsync({}, function() calls = calls + 1 end) +handle:cancel() +Assert.is_true(requests[#requests].cancelled, "同步第一页回调不能覆盖第二页句柄") +requests[#requests].cb(pageHtml(2, true)) +Assert.eq(calls, 0) diff --git a/tests/shuqi/client_spec.lua b/tests/shuqi/client_spec.lua new file mode 100644 index 0000000..b76dec5 --- /dev/null +++ b/tests/shuqi/client_spec.lua @@ -0,0 +1,241 @@ +--[[-- +书旗:搜索签名、正文解密、目录地址、验证码登录和书架同步体。 + +@module tests.moonsource_shuqi.client_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +package.preload["json"] = function() return require("support.json_stub") end + +local Assert = require("support.assert") +local Json = require("support.json_stub") +local Mapper = require("moonsource_shuqi.mapper") + +Assert.eq(Mapper.searchSign("1793900599"), "2988ab30d4114f664a6792c7962c3fdf") +Assert.eq(Mapper.contentSign({ bookId = "8016707", timestamp = "1", user_id = "8000000" }), + "bd9ab4f63403fd63fd3191ff23bc1731") +Assert.eq(Mapper.gatewaySign({ a = "1", b = "2" }, "eefc4798f28ea41622487ad80ef7e81c"), + "11c4ba6147c7d69ab433d71889f3d992") +Assert.eq(Mapper.gatewaySign({ a = "x y" }, "eefc4798f28ea41622487ad80ef7e81c"), + "687e16005410b369cf1f38c4459fbdc5") +Assert.eq(Mapper.javaEncode("x y"), "x+y") + +local found = Mapper.searchBooks({ + status = 1, + data = { { bid = 8062580, title = "三体", author = "刘慈欣", cover = "//img/a.jpg", desc = "科幻" } }, +}) +Assert.eq(#found, 1) +Assert.eq(found[1].stable_id, "8062580") +Assert.eq(found[1].title, "三体") +Assert.eq(found[1].authors, "刘慈欣") +Assert.eq(found[1].cover, "https://img/a.jpg") +Assert.eq(found[1].source_id, "ext.shuqi") +Assert.is_nil(Mapper.searchBooks({ status = -1, info = { message = "parameter is missing" } })) + +local detail = Mapper.detail({ + state = "200", + data = { bookId = 8016707, bookName = "不灭神王", authorName = "观棋", intro = "简介", imgUrl = "https://img/b.jpg" }, +}) +Assert.eq(detail.stable_id, "8016707") +Assert.eq(detail.title, "不灭神王") +Assert.eq(detail.authors, "观棋") +Assert.eq(detail.intro, "简介") +local described = Mapper.detail({ + state = "200", + data = { bookId = 8007543, bookName = "三体", authorName = "刘慈欣", desc = "科幻", imgUrl = "https://img/c.jpg" }, +}) +Assert.eq(described.intro, "科幻") + +local toc = Mapper.chapters({ + state = 200, + data = { + freeContUrlPrefix = "https://free/", + chargeContUrlPrefix = "https://charge/", + chapterList = { { + volumeList = { + { chapterId = 11, chapterName = "第一章", isFreeRead = true, contUrlSuffix = "?a=1", chapterOrdid = 1 }, + { chapterId = 12, chapterName = "第二章", isFreeRead = false, isBuy = false, contUrlSuffix = "?a=2" }, + { chapterId = 13, chapterName = "第三章", isFreeRead = false, isBuy = true, contUrlSuffix = "?a=3" }, + }, + } }, + }, +}) +Assert.eq(#toc, 3) +Assert.eq(toc[1].uid, "11") +Assert.eq(toc[1].content_url, "https://free/?a=1") +Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION) +Assert.eq(toc[1].vip, false) +Assert.eq(toc[2].vip, true) +Assert.is_nil(toc[2].content_url) +Assert.eq(toc[3].content_url, "https://charge/?a=3") + +local text = Mapper.chapterText({ + state = 200, + ChapterContent = "CTWlYm7aeXmxhVQzeeH8LaViChrfeBF6wBnhgD==", +}) +Assert.eq(text, "第一段\n第二段") +Assert.eq(select(2, Mapper.chapterText({ state = 200 })), "正文为空") + +local channels = Mapper.channels({ + state = 200, + data = { + male = { groupList = { { showName = "都市" }, { showName = "玄幻" } } }, + female = { groupList = { { showName = "现言" } } }, + press = { groupList = {} }, + cartoon = { groupList = { { showName = "漫画" } } }, + }, +}) +Assert.eq(channels.male[1].id, "都市") +Assert.eq(#channels.female, 1) +Assert.eq(#channels.press, 0) + +local session = Mapper.session({ + status = 200, + data = { token = "tok", userInfo = { userid = 42, nickName = "旗" } }, +}) +Assert.eq(session.token, "tok") +Assert.eq(session.user_id, "42") +Assert.eq(session.name, "旗") +Assert.is_nil(Mapper.session({ status = 500, message = "no" })) +Assert.is_true(Mapper.sent({ status = 200 })) +Assert.is_true(not Mapper.sent({ status = 400, message = "bad" })) + +local shelf = Mapper.shelf({ detail = { { bid = 9, title = "一书", author = "甲" } } }) +local nested = Mapper.shelf({ status = 200, message = "成功", data = { detail = { { bid = 9, title = "一书", author = "甲" } } } }) +Assert.eq(nested[1].stable_id, "9") +Assert.eq(nested[1].title, "一书") +Assert.eq(shelf[1].stable_id, "9") +Assert.is_nil(Mapper.shelf({ message = "fail" })) +local mark = Mapper.mark({ detail = { { bid = 9, chapterid = 11, cname = "第一章", percent = 0.25 } } }, "9") +Assert.eq(mark.chapter_id, "11") +Assert.eq(mark.title, "第一章") +Assert.eq(mark.fraction, 0.25) +Assert.is_nil(Mapper.mark({ detail = { { bid = 9, chapterid = 0, percent = 0.25 } } }, "9")) +Assert.eq(Mapper.mark({ detail = { { bid = 9, chapterid = 11, percent = 2500 } } }, "9").fraction, 0.25) +Assert.eq(Mapper.mark({ data = { detail = { { bid = 9, chapterid = 11, cname = "第一章", percent = 0.25 } } } }, "9").chapter_id, "11") + +local cfg = {} +local requests = {} +local shelf_rows = { { bid = 9, title = "书架书", author = "丁", chapterid = 11, cname = "第一章", percent = 0.5 } } +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 { + get = function(url, _options, callback) + requests[#requests + 1] = { method = "GET", url = url } + local body = "{}" + if url:find("do=is_search", 1, true) then + body = Json.encode({ status = 1, data = { { bid = 1, title = "三体", author = "刘慈欣" } } }) + elseif url:find("is_caterank", 1, true) then + body = Json.encode({ status = 1, data = { { bid = 2, title = "都市书", author = "乙" } } }) + elseif url:find("chapterlist", 1, true) then + body = Json.encode({ state = 200, data = { chapterList = {} } }) + elseif url:find("https://free/", 1, true) then + body = Json.encode({ state = 200, ChapterContent = "CTWlYm7aeXmxhVQzeeH8LaViChrfeBF6wBnhgD==" }) + end + callback(body, nil, nil) + return { cancel = function() end } + end, + post = function(url, payload, _options, callback) + requests[#requests + 1] = { method = "POST", url = url, body = payload } + local body = "{}" + if url:find("sendCode", 1, true) then + body = Json.encode({ status = 200 }) + elseif url:find("vcode/login", 1, true) then + body = Json.encode({ status = 200, data = { token = "tok", userInfo = { userid = 7, nickName = "旗" } } }) + elseif url:find("book/info", 1, true) then + body = Json.encode({ state = 200, data = { bookId = 3, bookName = "详情", authorName = "丙" } }) + elseif url:find("sync/bookmarks", 1, true) then + if payload:find("action%22%3A1", 1, true) then + shelf_rows = { { bid = 9, title = "书架书", author = "丁", chapterid = 11, cname = "第一章", percent = 0.5 } } + elseif payload:find("action%22%3A3", 1, true) then + shelf_rows = {} + elseif payload:find("action%22%3A2", 1, true) then + shelf_rows = { { bid = 9, title = "书架书", chapterid = 11, percent = 0.5 } } + end + body = Json.encode({ detail = shelf_rows }) + end + callback(body, nil, nil) + return { cancel = function() end } + end, + } +end + +local Client = require("moonsource_shuqi.client") + +local books +Client.searchAsync("三体", function(list) books = list end) +Assert.eq(books[1].title, "三体") +local search_url = requests[#requests].url +local timestamp = search_url:match("timestamp=(%d+)") +Assert.eq(search_url:match("sign=([0-9a-f]+)"), Mapper.searchSign(timestamp)) +Assert.is_true(search_url:find("platform=3", 1, true) ~= nil) +Assert.is_true(search_url:find("do=is_search", 1, true) ~= nil) + +local ranked +Client.rankAsync("都市", function(list) ranked = list end) +Assert.eq(ranked[1].title, "都市书") +Assert.is_true(requests[#requests].url:find("tag=", 1, true) ~= nil) + +local detail_book +Client.detailAsync("8016707", function(book) detail_book = book end) +Assert.eq(detail_book.title, "详情") +Assert.is_true(requests[#requests].body:find("platform=0", 1, true) ~= nil) +Assert.is_true(requests[#requests].body:find("sign=", 1, true) ~= nil) + +local chapter +Client.contentAsync("https://free/?a=1", function(value) chapter = value end) +Assert.eq(chapter, "第一段\n第二段") + +local denied +Client.shelfAsync(function(_books, err) denied = err end) +Assert.eq(denied, "未登录书旗") + +local sent +Client.sendCodeAsync("13800138000", "captcha", function(ok) sent = ok end) +Assert.eq(sent, true) +Assert.is_true(requests[#requests].body:find("mobile=13800138000", 1, true) ~= nil) +Assert.is_true(requests[#requests].body:find("type=1010", 1, true) ~= nil) +Assert.is_true(requests[#requests].body:find("key=sq_h5_gateway", 1, true) ~= nil) + +local logged +Client.loginAsync("13800138000", "1234", { fingerprint = "fp" }, function(value) logged = value end) +Assert.eq(logged.user_id, "7") +Assert.eq(cfg.logged_in, true) +Assert.eq(cfg.token, "tok") +Assert.eq(cfg.imei, "fp") +Assert.is_true(requests[#requests].body:find("imei=fp", 1, true) ~= nil) +Assert.is_true(requests[#requests].body:find("agent=chrome", 1, true) ~= nil) + +local shelf_books +Client.shelfAsync(function(list) shelf_books = list end) +Assert.eq(shelf_books[1].title, "书架书") +Assert.is_true(requests[#requests].body:find("get_data", 1, true) ~= nil) +Assert.is_true(requests[#requests].body:find("userid%22%3A7", 1, true) ~= nil) + +local added +Client.addAsync("9", function(ok) added = ok end) +Assert.eq(added, true) +Assert.is_true(requests[#requests - 1].body:find("action%22%3A1", 1, true) ~= nil) + +local removed +Client.removeAsync("9", function(ok) removed = ok end) +Assert.eq(removed, true) +Assert.is_true(requests[#requests - 1].body:find("action%22%3A3", 1, true) ~= nil) + +local mark_row +shelf_rows = { { bid = 9, chapterid = 11, percent = 0.5 } } +Client.progressAsync("9", function(value) mark_row = value end) +Assert.eq(mark_row.chapter_id, "11") +Assert.eq(mark_row.fraction, 0.5) + +local saved +Client.putProgressAsync("9", "11", "第一章", 0.5, function(ok) saved = ok end) +Assert.eq(saved, true) +Assert.is_true(requests[#requests - 1].body:find("action%22%3A2", 1, true) ~= nil) +Assert.is_true(requests[#requests - 1].body:find("percent%22%3A5000", 1, true) ~= nil) diff --git a/tests/shuqi/cookie_spec.lua b/tests/shuqi/cookie_spec.lua new file mode 100644 index 0000000..8e36bac --- /dev/null +++ b/tests/shuqi/cookie_spec.lua @@ -0,0 +1,117 @@ +--[[-- +书旗 Cookie 必须经官方账号校验,失败、取消与换号不覆盖旧会话。 +@module tests.moonsource_shuqi.cookie_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +local Themed = require("support.theme_stubs") +Themed.install() +package.loaded["json"] = JSON +local cfg, requests = {}, {} +local cleared = 0 +package.loaded["source.logout"] = { row = require("source.logout").row, clear = function(_id, clear) + clear(); cleared = cleared + 1; return true +end } +package.loaded["utils.settings"] = { getSource = function() return cfg end, saveSource = function() end } +package.loaded["http.request"] = { + get = function(url, opts, cb) + local request = { url = url, opts = opts, cb = cb } + requests[#requests + 1] = request + return { cancel = function() request.cancelled = true end } + end, +} +local Mapper = require("moonsource_shuqi.mapper") +Assert.eq(Mapper.cookieSession("shuqi_user_id=7; shuqi_token=one%2Btwo%3D").token, "one+two=") +Assert.eq(Mapper.cookieSession("shuqi_user_id=7; shuqi_token=one+two").token, "one+two") +Assert.is_nil(Mapper.cookieSession("shuqi_user_id=8000000; shuqi_token=token")) +Assert.is_nil(Mapper.cookieSession("shuqi_user_id=7; shuqi_token=bad%0D%0Atoken")) +Assert.is_nil(Mapper.cookieSession("shuqi_token=token")) +Assert.is_nil(Mapper.account({ status = 200, data = { ["7"] = { userId = 8 } } }, "7")) +local Client = require("moonsource_shuqi.client") +local result, reason +local function answer(token) + return JSON.encode({ status = 200, data = { ["7"] = { userId = 7, nickName = token } } }) +end +local function login(token) + return Client.loginCookieAsync("Cookie: shuqi_user_id=7; shuqi_token=" .. token + .. "; shuqi_fingerprint=browser; unrelated=private", function(value, err) result, reason = value, err end) +end +login("first") +local request = requests[#requests] +Assert.eq(request.opts.headers.Authorization, "Bearer first") +Assert.is_nil(request.opts.headers.Cookie) +Assert.eq(request.opts.cache_ttl, 0) +Assert.is_nil(request.url:find("first", 1, true), "令牌不进入 URL") +Assert.matches(request.url, "/userBaseInfo%?") +request.cb(answer("name")) +Assert.eq(cfg.token, "first") +Assert.eq(cfg.user_id, "7") +Assert.eq(cfg.imei, "browser") +Assert.eq(cfg.name, "name") +Assert.is_true(cfg.logged_in) +Assert.is_nil(cfg.cookie, "不保存无关 Cookie") + +login("bad") +requests[#requests].cb(nil, "offline") +Assert.eq(reason, "offline") +Assert.eq(cfg.token, "first") +login("bad") +requests[#requests].cb(JSON.encode({ status = 10003, message = "expired" })) +Assert.eq(reason, "expired") +Assert.eq(cfg.token, "first") +login("bad") +requests[#requests].cb("not json") +Assert.eq(reason, "登录响应无效") +Assert.eq(cfg.token, "first") +login("bad") +requests[#requests].cb(answer("wrong"):gsub('"userId":7', '"userId":8')) +Assert.is_nil(result) +Assert.eq(cfg.token, "first") + +local calls = 0 +local cancelled = Client.loginCookieAsync("shuqi_user_id=7; shuqi_token=cancelled", function() calls = calls + 1 end) +cancelled:cancel() +Assert.is_true(requests[#requests].cancelled) +requests[#requests].cb(answer("cancelled")) +Assert.eq(calls, 0) +Assert.eq(cfg.token, "first") +login("old") +local late = requests[#requests] +login("latest") +requests[#requests].cb(answer("latest")) +late.cb(answer("old")) +Assert.eq(cfg.token, "latest") +Assert.eq(reason, "登录状态已变化,请重试") +Client.loginCookieAsync("shuqi_user_id=8; shuqi_token=other", function(value, err) result, reason = value, err end) +requests[#requests].cb(JSON.encode({ status = 200, data = { ["8"] = { userId = 8 } } })) +Assert.is_true(result ~= nil) +Assert.is_nil(reason) +Assert.eq(cfg.token, "other") +Assert.eq(cleared, 1) + +local reloaded = 0 +package.loaded["source.auth"] = { ok = function() end, expired = function() return false end } +package.loaded["source.registry"] = { reload = function() reloaded = reloaded + 1 end } +package.loaded["ui/network/manager"] = { isConnected = function() return true end } +package.loaded["ui.themes.widgets.row"] = { widget = function(opts) return opts end } +local Setting = require("moonsource_shuqi.setting") +Setting.browser.apply({ cookies = { + { domain = ".shuqi.com", name = "shuqi_user_id", value = "7" }, + { domain = ".shuqi.com", name = "shuqi_token", value = "allowed" }, + { domain = "other.shuqi.com", name = "shuqi_token", value = "wrong" }, + { domain = "shuqi.com.evil.test", name = "shuqi_token", value = "wrong" }, +} }, function(ok) result = ok end) +Assert.eq(requests[#requests].opts.headers.Authorization, "Bearer allowed") +requests[#requests].cb(answer("allowed")) +Assert.is_true(result) +Assert.eq(reloaded, 1) +local rows = Setting.rows() +Assert.eq(rows[3](400).title, "粘贴 Cookie") +rows[3](400).callback() +Themed.last("input").callback("shuqi_user_id=7; shuqi_token=cancel-ui") +Themed.last("progress_dialog").on_cancel() +requests[#requests].cb(answer("cancel-ui")) +Assert.eq(cfg.token, "allowed") +Assert.eq(reloaded, 1) diff --git a/tests/shuqi/operations_spec.lua b/tests/shuqi/operations_spec.lua new file mode 100644 index 0000000..f60f6d8 --- /dev/null +++ b/tests/shuqi/operations_spec.lua @@ -0,0 +1,168 @@ +--[[-- +书旗写入必须回读确认,取消和换号不能污染旧登录。 + +@module tests.moonsource_shuqi.operations_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local JSON = require("support.json_stub") +package.loaded["json"] = JSON +local cfg = { logged_in = true, token = "old", user_id = "7" } +package.loaded["utils.settings"] = { getSource = function() return cfg end, saveSource = function() end } +local requests, delayed, rows = {}, false, {} +package.loaded["http.request"] = { + post = function(url, body, _opts, cb) + local request = { cb = cb, url = url, body = body } + requests[#requests + 1] = request + if not delayed then cb(JSON.encode({ detail = rows })) end + return { cancel = function() request.cancelled = true end } + end, +} +local Client = require("moonsource_shuqi.client") +local result, reason +Client.removeAsync("9", function(ok, err) result, reason = ok, err end) +Assert.is_true(result) +Assert.len(requests, 2, "写后另拉书架") +rows = { { bid = 9, chapterid = 11, percent = 0.5 } } +Client.removeAsync("9", function(ok, err) result, reason = ok, err end) +Assert.is_nil(result) +Assert.eq(reason, "同步结果未确认,请重试") +Client.putProgressAsync("9", "12", "", 0.5, function(ok, err) result, reason = ok, err end) +Assert.is_nil(result) +Assert.eq(reason, "同步结果未确认,请重试") +Client.putProgressAsync("9", "11", "", 0.5, function(ok, err) result, reason = ok, err end) +Assert.is_true(result) + +rows[1].percent = 0.168 +local write_index = #requests + 1 +Client.putProgressAsync("9", "11", "", 0.1676, function(ok, err) result, reason = ok, err end) +Assert.is_true(result, "服务端三位小数舍入不能误判为上传失败") +local data = JSON.decode(require("utils.text").urlDecode(requests[write_index].body:match("data=([^&]*)"))) +local mark = data.bookmark[1] +Assert.eq(type(mark.last_update), "string") +Assert.eq(tonumber(mark.last_update) * 1000, mark.add_time, "last_update 为秒,add_time 为毫秒") +Client.putProgressAsync("9", "11", "", 0.1675, function(ok, err) result, reason = ok, err end) +Assert.is_true(result, "三位小数半单位舍入边界") +Client.putProgressAsync("9", "11", "", 0.1674, function(ok, err) result, reason = ok, err end) +Assert.is_nil(result, "超出服务端舍入误差仍必须失败") +Assert.eq(reason, "同步结果未确认,请重试") +Client.putProgressAsync("9", "12", "", 0.1676, function(ok, err) result, reason = ok, err end) +Assert.is_nil(result, "比例匹配不能掩盖章节不匹配") + +local count = 0 +local read_count = 0 +package.loaded["http.request"].post = function(_url, _body, _opts, cb) + read_count = read_count + 1 + local request = { cb = cb } + requests[#requests + 1] = request + if read_count == 1 then cb(JSON.encode({ detail = rows })) end + return { cancel = function() request.cancelled = true end } +end +local handle = Client.removeAsync("9", function() count = count + 1 end) +handle:cancel() +Assert.is_true(requests[#requests].cancelled) +requests[#requests].cb(JSON.encode({ detail = {} })) +Assert.eq(count, 0) + +delayed = true +package.loaded["http.request"].post = function(_url, _body, options, cb) + local request = { cb = cb, options = options } + requests[#requests + 1] = request + return { cancel = function() request.cancelled = true end } +end + +local before = #requests +local completed = 0 +Client.shelfAsync(function(books) if books then completed = completed + 1 end end) +local cancelled = Client.shelfAsync(function() completed = completed + 10 end) +Client.load() +Client.progressAsync("9", function(pos) if pos then completed = completed + 1 end end) +Assert.len(requests, before + 1, "刷新与进度读取不能同时发书签请求,重新载入同账号也不能拆队列") +cancelled:cancel() +Assert.is_nil(requests[before + 1].cancelled, "取消排队请求不能取消正在执行的请求") +requests[before + 1].cb(JSON.encode({ detail = rows })) +Assert.eq(completed, 1) +Stubs.flush() +Assert.len(requests, before + 2, "取消的排队请求不得发网络请求") +requests[before + 2].cb(JSON.encode({ detail = rows })) +Assert.eq(completed, 2) + +before = #requests +completed = 0 +local active = Client.shelfAsync(function() completed = completed + 10 end) +local waiting = Client.shelfAsync(function() completed = completed + 10 end) +Client.shelfAsync(function(books) if books then completed = completed + 1 end end) +active:cancel() +Assert.is_true(requests[before + 1].cancelled) +waiting:cancel() +Stubs.flush() +Assert.len(requests, before + 2, "取消正在执行和即将执行的请求后,后续请求仍能继续") +requests[before + 1].cb(JSON.encode({ detail = rows })) +Assert.eq(completed, 0, "忽略已取消请求的迟到回调") +requests[before + 2].cb(JSON.encode({ detail = rows })) +Assert.eq(completed, 1) + +before = #requests +Client.shelfAsync(function(books, err) result, reason = books, err end) +Client.shelfAsync(function(books) if books then completed = completed + 1 end end) +requests[before + 1].cb(JSON.encode({ status = 10006, message = "未知状态码错误" })) +Assert.is_nil(result) +Assert.eq(reason, "未知状态码错误 (10006)", "业务错误保留原提示和状态码") +Stubs.flush() +Assert.len(requests, before + 2, "失败必须释放接口,不能把后续刷新挂死") +requests[before + 2].cb(JSON.encode({ detail = rows })) +Assert.eq(completed, 2) + +before = #requests +local changed = 0 +local function onChanged(books, err) + if not books and err == "登录状态已变化,请重试" then changed = changed + 1 end +end +Client.shelfAsync(onChanged) +Client.shelfAsync(onChanged) +Client.reset() +requests[before + 1].cb(JSON.encode({ detail = rows })) +Stubs.flush() +Assert.len(requests, before + 1, "账号失效后,旧会话排队请求不得再发出") +Assert.eq(changed, 2) + +local function session(id) + return JSON.encode({ status = 200, data = { token = "new", userInfo = { userid = id } } }) +end +package.loaded["source.logout"] = { clear = function(_id, clear) clear(); return true end } +Client.sendCodeAsync("13800138000", "captcha", function() end, { user_agent = "Test-UA" }) +Assert.eq(requests[#requests].options.headers["User-Agent"], "Test-UA") +Client.loginAsync("13800138000", "code", { user_agent = "Test-UA" }, function(ok, err) result, reason = ok, err end) +Assert.eq(requests[#requests].options.headers["User-Agent"], "Test-UA") +requests[#requests].cb(session(8)) +Assert.is_true(result ~= nil) +Assert.eq(cfg.token, "new") +Assert.eq(cfg.user_id, "8") +Assert.is_nil(reason) + +local login = Client.loginAsync("13800138000", "code", nil, function() count = count + 1 end) +login:cancel() +requests[#requests].cb(session(7)) +Assert.eq(cfg.token, "new") +Assert.eq(count, 0) + +Client.loginAsync("13800138000", "code", nil, function(ok, err) result, reason = ok, err end) +local late = requests[#requests] +Client.reset() +late.cb(session(7)) +Assert.is_nil(result) +Assert.eq(reason, "登录状态已变化,请重试") +Assert.eq(cfg.token, "new") +Client.loginAsync("13800138000", "code", nil, function(ok) result = ok end) +requests[#requests].cb(session(7)) +Assert.eq(cfg.token, "new", "同账号续期允许替换令牌") +Client.loginAsync("13800138000", "code", nil, function(ok, err) result, reason = ok, err end) +requests[#requests].cb("verification required") +Assert.is_nil(result) +Assert.matches(reason, "安全验证") +Assert.eq(cfg.token, "new") +Client.loginAsync("13800138000", "code", nil, function(ok, err) result, reason = ok, err end) +requests[#requests].cb(JSON.encode({ status = 10003 })) +Assert.eq(reason, "书旗登录失败(状态:10003)") diff --git a/tests/shuqi/progress_spec.lua b/tests/shuqi/progress_spec.lua new file mode 100644 index 0000000..7bd5101 --- /dev/null +++ b/tests/shuqi/progress_spec.lua @@ -0,0 +1,61 @@ +--[[-- +书旗进度的各阶段取消:同步桩不能覆盖下一阶段,异步首阶段也必须可取消。 + +@module tests.moonsource_shuqi.progress_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local pending +local function request(cb) + pending = { cb = cb } + local operation = pending + return { cancel = function() operation.cancelled = true end } +end +local sync = false +local client = { + loggedIn = function() return true end, + progressAsync = function(_id, cb) + if sync then + cb({ chapter_id = "11", fraction = 0.5 }) + return { cancel = function() error("stale first handle") end } + end + return request(cb) + end, + putProgressAsync = function(_id, _chapter, _title, fraction, cb) + Assert.eq(fraction, 0.5) + return request(cb) + end, +} +package.loaded["moonsource_shuqi.client"] = client +package.loaded["source.toc"] = { index = function() return 1 end } +local source = require("moonsource_shuqi.source").new() +local toc = { { uid = "11", title = "第一章" }, { uid = "12", title = "第二章" } } +source.loadTocAsync = function(_self, _identity, cb) return request(cb) end +local identity = { source_id = "ext.shuqi", stable_id = "9" } +local calls = 0 +local handle = source:getProgressAsync(identity, function() calls = calls + 1 end) +handle:cancel() +Assert.is_true(pending.cancelled, "异步书签请求必须可取消") +pending.cb({ chapter_id = "11", fraction = 0.5 }) +Assert.eq(calls, 0) +sync = true +handle = source:getProgressAsync(identity, function() calls = calls + 1 end) +handle:cancel() +Assert.is_true(pending.cancelled, "同步书签回调后取消目录请求") +pending.cb(toc) +Assert.eq(calls, 0) +handle = source:putProgressAsync(identity, { chapter_idx = 1 }, function() calls = calls + 1 end) +handle:cancel() +Assert.is_true(pending.cancelled, "异步目录请求必须可取消") +pending.cb(toc) +Assert.eq(calls, 0) +source.loadTocAsync = function(_self, _identity, cb) + cb(toc) + return { cancel = function() error("stale toc handle") end } +end +handle = source:putProgressAsync(identity, { chapter_idx = 1 }, function() calls = calls + 1 end) +handle:cancel() +Assert.is_true(pending.cancelled) +pending.cb(true) +Assert.eq(calls, 0) diff --git a/tests/shuqi/reviews_spec.lua b/tests/shuqi/reviews_spec.lua new file mode 100644 index 0000000..fc4bf6c --- /dev/null +++ b/tests/shuqi/reviews_spec.lua @@ -0,0 +1,47 @@ +--[[-- +书旗书评仅归属整本书;分页、空列表与坏响应保持不同语义。 + +@module tests.moonsource_shuqi.reviews_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +package.loaded["json"] = JSON +local Mapper = require("moonsource_shuqi.mapper") +local wire = { + status = "200", info = { total = 21, count = 2 }, + data = { { mid = 1, bookId = 9, nickName = "读者", text = "书评&感想", pubTime = 1700000000 } }, +} +local page = Mapper.reviews(wire, "9") +Assert.eq(page.items[1].text, "书评&感想") +Assert.eq(page.items[1].author, "读者") +Assert.eq(page.pages, 2) +Assert.is_nil(Mapper.reviews(wire, "10"), "不能把别的书评挂到本书") +Assert.is_nil(Mapper.reviews({ status = 200 }, "9")) +Assert.is_nil(Mapper.reviews({ status = 500, data = {}, info = { total = 0, count = 0 } }, "9")) +Assert.len(Mapper.reviews({ status = 200, data = {}, info = { total = 0, count = 0 } }, "9").items, 0) +local requests = {} +package.loaded["http.request"] = { + get = function(url, opts, cb) + local request = { url = url, opts = opts, cb = cb } + requests[#requests + 1] = request + return { cancel = function() request.cancelled = true end } + end, +} +local Client = require("moonsource_shuqi.client") +local result, reason +Client.reviewsAsync("9", 2, function(value, err) result, reason = value, err end) +Assert.matches(requests[1].url, "page=2") +Assert.matches(requests[1].url, "bookId=9") +Assert.is_nil(requests[1].opts.headers.Cookie) +requests[1].cb(JSON.encode(wire)) +Assert.eq(result.total, 21) +Client.reviewsAsync("9", 1, function(value, err) result, reason = value, err end) +requests[2].cb(nil, "network down") +Assert.is_nil(result) +Assert.eq(reason, "network down") +Client.reviewsAsync("9", 1, function(value, err) result, reason = value, err end) +requests[3].cb("维护") +Assert.is_nil(result) +Assert.eq(reason, "响应无效") diff --git a/tests/shuqi/verify_spec.lua b/tests/shuqi/verify_spec.lua new file mode 100644 index 0000000..b3a145c --- /dev/null +++ b/tests/shuqi/verify_spec.lua @@ -0,0 +1,61 @@ +--[[-- +书旗滑块票据隔离、取消与离线登录入口。 + +@module tests.moonsource_shuqi.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 route, sends = nil, {} +package.loaded["utils.extension"] = { + add = function(_point, provider) route = provider end, + call = function(_point, _path, _title, _text, options) + return { close = function() options.close_callback() end } + end, +} +package.loaded["ui/uimanager"] = { scheduleIn = function() end, unschedule = function() end } +package.loaded["moonsource_shuqi.client"] = { + sendCodeAsync = function(phone, captcha, cb, browser) + local send = { phone = phone, captcha = captcha, cb = cb, browser = browser } + sends[#sends + 1] = send + return { cancel = function() send.cancelled = true end } + end, +} +local Verification = require("moonsource_shuqi.verify") +local finished = 0 +local first = Verification.new("13800138000", function() finished = finished + 1 end) +local second = Verification.new("13900139000", function() finished = finished + 1 end) +local status, body +local function reply(code, response) status, body = code, response end +route.handle("POST", "config", { ticket = first.ticket }, reply) +Assert.matches(body.load_error, "可能被广告拦截插件") +Assert.matches(body.load_timeout, "超时") +Assert.matches(body.load_timeout, "可能被广告拦截插件") +route.handle("POST", "verify", { ticket = first.ticket, captcha = "one", fingerprint = "first", user_agent = "Test-UA" }, reply) +route.handle("POST", "verify", { ticket = second.ticket, captcha = "two", user_agent = "bad\r\nheader" }, reply) +Assert.eq(status, 400) +Assert.len(sends, 1) +route.handle("POST", "verify", { ticket = second.ticket, captcha = "two", fingerprint = "second" }, reply) +sends[2].cb(true) +sends[1].cb(true) +Assert.eq(first.browser.fingerprint, "first") +Assert.eq(first.browser.user_agent, "Test-UA") +Assert.eq(sends[1].browser.user_agent, "Test-UA") +Assert.eq(second.browser.fingerprint, "second") +Assert.eq(finished, 2) +route.handle("POST", "verify", { ticket = first.ticket, captcha = "replay" }, reply) +Assert.eq(status, 403) +local cancelled = Verification.new("13800138000", function() finished = finished + 1 end) +route.handle("POST", "verify", { ticket = cancelled.ticket, captcha = "three" }, reply) +cancelled:cancel() +Assert.is_true(sends[3].cancelled) +sends[3].cb(true) +Assert.is_nil(cancelled.browser) +Assert.eq(finished, 2) +Assert.eq(status, 403) +package.loaded["ui/network/manager"] = { isConnected = function() return false end } +require("moonsource_shuqi.setting").login() +Assert.is_nil(Themed.last("input")) +Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi") diff --git a/tests/shuqi/web_spec.js b/tests/shuqi/web_spec.js new file mode 100644 index 0000000..5ef6758 --- /dev/null +++ b/tests/shuqi/web_spec.js @@ -0,0 +1,117 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const source = fs.readFileSync(process.argv[2] + '/moonsource-shuqi.koplugin/moonsource_shuqi/web/shuqi_verify.js', 'utf8'); + +async function page(options = {}) { + const nodes = Object.fromEntries(['title', 'instruction', 'status', 'retry', 'captcha-element'] + .map(id => [id, { textContent: '', hidden: false }])); + const requests = [], loaded = [], modules = [], scripts = [], timers = []; + let captcha; + const messages = { title: 'Shuqi', pending: 'Sending', success: 'Sent', + failure: 'Failed', retry: 'Retry', environment_error: 'Environment failed', + load_error: 'Script may be blocked by an ad blocker; use Cookie sign-in', + load_timeout: 'Script timeout; may be blocked by an ad blocker; use Cookie sign-in' }; + const fingerprintSDK = function() { this.get = cb => cb(options.fingerprint || 'fingerprint'); }; + const awscSDK = { use(name, cb) { + modules.push(name); + if (options.sdkFailed) return cb('failed'); + cb('loaded', name === 'um' ? { init(_opts, done) { done('success', { tn: 'um-token' }); } } + : { getUA() { return 'wua-proof'; } }); + } }; + const context = { + AbortController, + setTimeout: options.timeoutScript ? (fn, ms) => { const timer = { fn, ms }; timers.push(timer); return timer; } : setTimeout, + clearTimeout: options.timeoutScript ? timer => { timer.cleared = true; } : clearTimeout, + location: { hash: '#fixture' }, + navigator: { userAgent: 'Test-UA' }, + document: { + get cookie() { throw new Error('Must not read cookies from the remote-management origin'); }, + getElementById: id => nodes[id], createElement: () => ({ remove() { this.removed = true; } }), + head: { appendChild(script) { + loaded.push(script.src); + scripts.push(script); + if (options.blockScript && script.src.includes(options.blockScript)) return script.onerror(); + if (options.timeoutScript && script.src.includes(options.timeoutScript)) { + queueMicrotask(() => timers.find(timer => timer.ms === 20000 && !timer.cleared).fn()); + return; + } + if (options.slowAwsc && script.src.includes('awsc.js')) { + setTimeout(() => { + context.window.AWSC = awscSDK; + script.onload(); + }, 10); + return; + } + if (script.src.includes('fingerprint2.min.js')) context.window.Fingerprint2 = fingerprintSDK; + if (script.src.includes('awsc.js')) context.window.AWSC = awscSDK; + if (script.src.includes('AliyunCaptcha.js')) context.window.initAliyunCaptcha = config => { captcha = config; }; + script.onload(); + } }, + }, + window: { + ...(options.preloaded ? { Fingerprint2: fingerprintSDK, AWSC: awscSDK } : {}), + }, + fetch: async (url, opts) => { + requests.push({ url, body: JSON.parse(opts.body) }); + return { ok: !options.rejected || url.endsWith('/config'), + json: async () => url.endsWith('/config') ? messages : options.rejected ? { error: 'Rejected' } : { ok: true } }; + }, + }; + await vm.runInNewContext(source, context); + return { nodes, requests, loaded, modules, scripts, get captcha() { return captcha; } }; +} + +(async () => { + let p = await page(); + assert.deepEqual(p.modules, ['um', 'uab']); + assert.equal(p.loaded.length, 3); + await p.captcha.captchaVerifyCallback('captcha-proof'); + assert.deepEqual(p.requests[1].body, { ticket: 'fixture', captcha: 'captcha-proof', + fingerprint: 'fingerprint_shuqi_touch', umidtoken: 'um-token', wua: 'wua-proof', user_agent: 'Test-UA' }); + assert.equal(p.nodes.status.textContent, 'Sent'); + assert.equal(p.nodes['captcha-element'].hidden, true); + + p = await page({ sdkFailed: true }); + assert.equal(p.captcha, undefined); + assert.equal(p.nodes.status.textContent, 'Environment failed'); + assert.equal(p.requests.length, 1); + assert.equal(p.nodes.retry.hidden, false); + + const blocked = { blockScript: 'fingerprint2.min.js', slowAwsc: true }; + p = await page(blocked); + assert.match(p.nodes.status.textContent, /may be blocked by an ad blocker/); + assert.match(p.nodes.status.textContent, /render-resource\.11222\.cn\/third\/fingerprint2\/fingerprint2\.min\.js/); + assert.equal(p.requests.length, 1, 'No verification request when a script is blocked'); + assert.equal(p.scripts[0].removed, true); + blocked.blockScript = null; + await p.nodes.retry.onclick(); + assert.ok(p.captcha, 'Retry can recover after the script is allowed'); + assert.equal(p.loaded.filter(src => src.includes('awsc.js')).length, 1, 'Retry reuses the loaded AWSC SDK'); + await p.captcha.captchaVerifyCallback('captcha-proof'); + assert.equal(p.nodes.status.textContent, 'Sent'); + + p = await page({ timeoutScript: 'fingerprint2.min.js' }); + assert.match(p.nodes.status.textContent, /Script timeout/); + assert.match(p.nodes.status.textContent, /may be blocked by an ad blocker/); + assert.match(p.nodes.status.textContent, /fingerprint2\.min\.js/); + assert.equal(p.requests.length, 1); + assert.equal(p.scripts[0].removed, true); + assert.equal(p.scripts[0].onload, null, 'Timed-out scripts cannot continue the login pipeline'); + + p = await page({ preloaded: true }); + assert.equal(p.loaded.length, 1, 'Already loaded environment SDKs are not fetched again'); + p.captcha.getInstance({ refresh() { throw new Error('Refresh failed'); } }); + await p.nodes.retry.onclick(); + assert.equal(p.nodes.status.textContent, 'Refresh failed'); + assert.equal(p.nodes.retry.hidden, false); + + p = await page({ rejected: true, fingerprint: 'second' }); + await p.captcha.captchaVerifyCallback('captcha-proof'); + assert.equal(p.requests[1].body.fingerprint, 'second_shuqi_touch'); + assert.equal(p.nodes.status.textContent, 'Rejected'); + assert.equal(p.nodes['captcha-element'].hidden, false); + assert.equal(p.nodes.retry.hidden, false); + console.log('shuqi web: OK'); +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tests/shuqi/web_spec.lua b/tests/shuqi/web_spec.lua new file mode 100644 index 0000000..2e32502 --- /dev/null +++ b/tests/shuqi/web_spec.lua @@ -0,0 +1,13 @@ +--[[-- +书旗滑块页的登录环境初始化与失败反馈,不依赖 npm。 +@module tests.moonsource_shuqi.web_spec +--]] +local Assert = require("support.assert") +local status = os.execute("command -v node >/dev/null 2>&1") +if status ~= 0 and status ~= true then Assert.skip("需要 Node 运行网页脚本回归") end +local here = debug.getinfo(1, "S").source:match("^@(.+)/[^/]+$") or "." +local root = here .. "/../.." +local pipe = assert(io.popen('node "' .. here .. '/web_spec.js" "' .. root .. '" 2>&1')) +local output = pipe:read("*a") +pipe:close() +Assert.is_true(output:find("shuqi web: OK", 1, true) ~= nil, output)