commit ff11bb481a4b83ef9d922458bc6f9f977a53fd19 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-ireader.koplugin/README.md b/moonsource-ireader.koplugin/README.md new file mode 100644 index 0000000..34bccb0 --- /dev/null +++ b/moonsource-ireader.koplugin/README.md @@ -0,0 +1,21 @@ +# 掌阅 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| App 扫码登录 | 已实现,未实测 | 校验候选会话后保存 | +| 浏览器登录与 Cookie 导入 | 支持 | 从电脑站 Cookie 解析必要会话并校验 | +| 设备密码与短信登录 | 不支持 | 其他方式可在官网完成后导入 Cookie | +| 书架拉取 | 支持 | 过滤文件夹和本机上传书 | +| 加入远端书架 | 已实现,未实测 | 本地先生效,后续同步上传 | +| 移出远端书架 | 不支持 | 没有已接入的删除接口;本地清缓存并保留墓碑 | +| 搜索与分类书城 | 支持 | 男生、女生、出版;动态分类、排序与筛选,支持后续页 | +| 目录与正文 | 支持 | 分页目录、按章阅读、特殊字码还原及插图本地化 | +| 已购正文 | 已实现,未实测 | 以服务端权限为准;未购提示不计入正文缓存 | +| 章节与全本缓存 | 支持 | 支持预取;插图下载失败不算正文缓存成功 | +| 离线阅读 | 支持 | 已缓存正文和本地插图可读;旧远程插图需先联网补齐 | +| 阅读进度同步 | 部分支持 | 仅章节位置,无精确章内进度;真实写后回读未实测 | +| 笔记与统计同步 | 不支持 | 仅本地保存 | +| 整书书评 | 部分支持 | 仅手机 Web 首屏;本地翻阅已加载条目,不续拉 AJAX 页 | +| 章评、段评与回复 | 不支持 | 当前 Web 协议未找到可验证接口 | +| 评论写操作 | 不支持 | 不发评、不点赞、不删评 | +| 账号切换 | 部分支持 | 同账号可续期;换号须先退出清理旧数据,未同步记录会丢失 | diff --git a/moonsource-ireader.koplugin/_meta.lua b/moonsource-ireader.koplugin/_meta.lua new file mode 100644 index 0000000..57e5c6b --- /dev/null +++ b/moonsource-ireader.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:掌阅"), + description = _("给月读增加「掌阅」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-ireader.koplugin/main.lua b/moonsource-ireader.koplugin/main.lua new file mode 100644 index 0000000..f6c85fa --- /dev/null +++ b/moonsource-ireader.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_ireader", + is_doc_only = false, +} diff --git a/moonsource-ireader.koplugin/moon_source.lua b/moonsource-ireader.koplugin/moon_source.lua new file mode 100644 index 0000000..dedd691 --- /dev/null +++ b/moonsource-ireader.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_ireader.source").meta() end, + new = function() return require("moonsource_ireader.source").new() end, + setting = lazy("moonsource_ireader.setting"), +} diff --git a/moonsource-ireader.koplugin/moonsource_ireader/_meta.lua b/moonsource-ireader.koplugin/moonsource_ireader/_meta.lua new file mode 100644 index 0000000..e147cd8 --- /dev/null +++ b/moonsource-ireader.koplugin/moonsource_ireader/_meta.lua @@ -0,0 +1,17 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +掌阅 PC(pc.ireader.com)扫码登录后同步 App 书架;书城搜索与频道来自手机站 m.zhangyue.com。 + +@module moonsource_ireader._meta +--]] + +local _ = require("l10n").get("moonsource_ireader") + +return { + id = "ext.ireader", + name = _("掌阅书城"), + type = "chapter", + description = _("掌阅书架与在线阅读"), + abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("VIP 章节"), _("书评"), _("扫码登录"), _("浏览器登录") }, +} diff --git a/moonsource-ireader.koplugin/moonsource_ireader/client.lua b/moonsource-ireader.koplugin/moonsource_ireader/client.lua new file mode 100644 index 0000000..b90f8ed --- /dev/null +++ b/moonsource-ireader.koplugin/moonsource_ireader/client.lua @@ -0,0 +1,508 @@ +--[[-- +掌阅网页接口。 + +登录、书架、目录、进度、正文走 PC 站(api-pc.zhangyue.com,正文在 pc.ireader.com/nsr)。 +设备参数 p29/p2/p3/p4/p33 来自 PC 站运行时配置,每次请求都带,和网页 axios 拦截器一致。 +书城搜索与频道是手机站 m.zhangyue.com 的页面,不走这套 JSON。 + +插件保存扫码回包里的 usr(账号名)和 zysid(session_id),不依赖浏览器 Cookie。 + +@module moonsource_ireader.client +--]] + +local JSON = require("json") +local Mapper = require("moonsource_ireader.mapper") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_ireader") + +local Client = {} + +local SOURCE_ID = "ext.ireader" +local API = "https://api-pc.zhangyue.com" +local WEB = "https://pc.ireader.com" +local STORE = "https://m.zhangyue.com" +local SUCCESS = 0 +local LOGIN_EXPIRED = 600001 +local HAS_IN_SHELF = 100011 +local FEE_WHOLE = 10 +local DEVICE = { + p29 = "zye5b814", + p2 = "104583", + p3 = "101010010", + p4 = "501603", + p33 = "com.chaozh.iReaderFree", +} + +---@type table +local fee_unit = {} + +---@return { usr: string, zysid: string, name: string|nil, avatar: string|nil }|nil +function Client.session() + local cfg = require("utils.settings").getSource(SOURCE_ID) + local usr = type(cfg.usr) == "string" and cfg.usr or "" + local zysid = type(cfg.zysid) == "string" and cfg.zysid or "" + if usr == "" or zysid == "" then return nil end + return { usr = usr, zysid = zysid, name = cfg.name, avatar = cfg.avatar } +end + +---@param session table|nil +---@param params table|nil +---@return string +local function query(session, params) + local form = { + usr = session and session.usr or "", + zysid = session and session.zysid or "", + } + for key, value in pairs(DEVICE) do form[key] = value end + for key, value in pairs(params or {}) do form[key] = value end + return Text.formEncode(form) +end + +---@param path string +---@param session table|nil +---@param params table|nil +---@return string +local function url(path, session, params) + local base = path + if path:sub(1, 5) == "/nsr/" then + base = WEB .. path + elseif not path:find("^https?://") then + base = API .. path + end + return base .. "?" .. query(session, params) +end + +--- 解 PC 站统一封套。code 0 的 body 可能再套一层 JSON 字符串。 +---@param wire table +---@param session table|nil +---@return any|nil +---@return string|nil +local function bodyOf(wire, session) + local current = Client.session() + local active = session and current and current.usr == session.usr and current.zysid == session.zysid + local code = tonumber(wire.code) + if code == SUCCESS or (code == nil and type(wire.bookContent) == "string") then + if type(wire.bookContent) == "string" then return wire end + local body = wire.body + if type(body) == "string" then + local ok, inner = pcall(JSON.decode, body) + if ok and inner ~= nil then body = inner end + end + if active then require("source.auth").ok(SOURCE_ID) end + if body == nil then return true end + return body + end + if code == LOGIN_EXPIRED then + local message = _("掌阅登录已失效,请点「重新登录」,用掌阅 App 扫码。") + return nil, active and require("source.auth").expire(SOURCE_ID, message) or message + end + if code == 100001 and not session then return nil, _("未登录掌阅") end + return nil, type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("请求失败") +end + +---@param raw string|nil +---@param err any +---@return table|nil +---@return string|nil +local function envelope(raw, err) + if not raw then return nil, err and tostring(err) or _("请求失败") end + local ok, wire = pcall(JSON.decode, raw) + if not ok or type(wire) ~= "table" then return nil, _("响应无效") end + return wire +end + +---@param path string +---@param params table|nil +---@param session table|nil +---@param cb fun(body: any, err: string|nil) +---@return HttpJob +local function get(path, params, session, cb) + return Request.get(url(path, session, params), { + accept = "application/json", + cache_ttl = 0, + timeout = require("http.timeout").net(0.5), + }, function(raw, err) + local wire, reason = envelope(raw, err) + if not wire then cb(nil, reason); return end + local body, message = bodyOf(wire, session) + cb(body, message) + end) +end + +function Client.get(path, params, cb) + return get(path, params, Client.session(), cb) +end + +---@param path string +---@param params table|nil +---@param payload string +---@param content_type string +---@param cb fun(body: any, err: string|nil) +---@return HttpJob +local function post(path, params, payload, content_type, cb) + local session = Client.session() + return Request.post(url(path, session, params), payload, { + accept = "application/json", + content_type = content_type, + timeout = require("http.timeout").net(0.5), + }, function(raw, err) + local wire, reason = envelope(raw, err) + if not wire then cb(nil, reason); return end + local body, message = bodyOf(wire, session) + cb(body, message) + end) +end + +---@param fields { name: string, value: string }[] +---@return string body +---@return string content_type +local function multipart(fields) + local boundary = "----moonireader" + local parts = {} + for _idx, field in ipairs(fields) do + parts[#parts + 1] = "--" .. boundary + .. '\r\nContent-Disposition: form-data; name="' .. field.name .. '"\r\n\r\n' .. field.value + end + parts[#parts + 1] = "--" .. boundary .. "--\r\n" + return table.concat(parts, "\r\n"), "multipart/form-data; boundary=" .. boundary +end + +---@param cb fun(code: string|nil, err: string|nil) +---@return HttpJob +function Client.qrCreateAsync(cb) + return get("/bookstore/open/user/qrcode/get", nil, nil, function(body, err) + local code = Mapper.qrCode(body) + if not code then cb(nil, err or _("获取二维码失败")); return end + cb(code) + end) +end + +--- 轮询不把「还没扫」当成失败。回包原样交给调用方。 +---@param code string +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +function Client.qrPollAsync(code, cb) + return Request.get(url("/bookstore/open/user/qrcode/result", nil, { code = code }), { + accept = "application/json", + cache_ttl = 0, + timeout = require("http.timeout").net(0.5), + }, function(raw, err) + local wire, reason = envelope(raw, err) + cb(wire, reason) + end) +end + +---@param cb fun(body: table|nil, err: string|nil) +---@return HttpJob +function Client.shelfAsync(cb) + return Client.get("/bookstore/open/cloud/bookshelf/list", nil, function(body, err) + if type(body) ~= "table" or type(body.data) ~= "table" then cb(nil, err or _("响应无效")); return end + cb(body) + end) +end + +---@param session table +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return HttpJob +function Client.checkSessionAsync(session, cb) + return get("/bookstore/open/cloud/bookshelf/list", nil, session, function(body, err) + if type(body) ~= "table" or type(body.data) ~= "table" then cb(nil, err or _("响应无效")); return end + cb(true) + end) +end + +--- 新书插到未置顶书的最前:order 取当前最小再减一,和网页 insert 一致。 +---@param rows table[]|nil +---@return integer order +---@return integer version +local function shelfCursor(rows, version) + local order = nil + for _idx, row in ipairs(type(rows) == "table" and rows or {}) do + local value = tonumber(row.order) + if row.top ~= 1 and value and (not order or value < order) then order = value end + end + return (order or 999999) - 1, tonumber(version) or 0 +end + +Client.shelfCursor = shelfCursor + +---@param stable_id string +---@param title string +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return { cancel: fun() } +function Client.addAsync(stable_id, title, cb) + local session = Client.session() + if not session then return require("source.base").defer(cb, nil, _("未登录掌阅")) end + local handle, pending = {}, true + local initial = Client.shelfAsync(function(shelf, err) + pending = false + if handle.cancelled then return end + if not shelf then cb(nil, err); return end + local current = Client.session() + if not current or current.usr ~= session.usr or current.zysid ~= session.zysid then + cb(nil, _("登录状态已变化,请重试")) + return + end + local order, version = shelfCursor(shelf.data, shelf.current_version) + local data = JSON.encode({ { + dtype = 0, + order = order, + folder = "", + md5 = "", + top = 0, + top_sort = 0, + book_id = tostring(stable_id), + book_name = title, + book_type = 24, + cover_name = "", + is_local_book = false, + book_file_id = "", + book_file_size = 0, + cover_file_id = "", + cover_file_size = 0, + folder_hierarchy = "[]", + } }) + local payload, content_type = multipart({ + { name = "usr", value = session.usr }, + { name = "current_version", value = tostring(version) }, + { name = "type", value = "1" }, + { name = "data", value = data }, + }) + handle.job = Request.post(url("/bookstore/open/cloud/bookshelf/upsert", session), payload, { + accept = "application/json", + content_type = content_type, + timeout = require("http.timeout").net(0.5), + }, function(raw, post_err) + if handle.cancelled then return end + local wire, reason = envelope(raw, post_err) + if not wire then cb(nil, reason); return end + local code = tonumber(wire.code) + if code == SUCCESS or code == HAS_IN_SHELF then + local active = Client.session() + if active and active.usr == session.usr and active.zysid == session.zysid then + require("source.auth").ok(SOURCE_ID) + end + cb(true) + return + end + local _ignored, message = bodyOf(wire, session) + cb(nil, message) + end) + end) + if pending then handle.job = initial end + return { cancel = function() + handle.cancelled = true + if handle.job and handle.job.cancel then handle.job.cancel() end + end } +end + +---@param book_id string +---@param cb fun(body: table|nil, err: string|nil) +---@return HttpJob +function Client.detailAsync(book_id, cb) + return Client.get("/bookstore/open/book/detail", { book_id = book_id }, function(body, err) + if type(body) == "table" and body.fee_unit ~= nil then + fee_unit[tostring(book_id)] = tonumber(body.fee_unit) + end + cb(body, err) + end) +end + +---@param book_id string +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client.chaptersAsync(book_id, cb) + local handle, rows = {}, {} + local function nextPage(page) + local pending = true + local initial = Client.get("/bookstore/open/book/chapter/web/list", { + book_id = book_id, page = page, size = 50, + }, function(body, err) + pending = false + if handle.cancelled then return end + if type(body) ~= "table" or type(body.list) ~= "table" then cb(nil, err or _("响应无效")); return end + local list = body.list + local total = type(body.page) == "table" and tonumber(body.page.totalPage) + if not total or total < page or total % 1 ~= 0 or (#list == 0 and page < total) then + cb(nil, _("响应无效")) + return + end + for _idx, row in ipairs(list) do + if type(row) ~= "table" or (row.id == nil and row.chapter_id == nil) then + cb(nil, _("响应无效")) + return + end + rows[#rows + 1] = row + end + if page < total and #list > 0 then + nextPage(page + 1) + return + end + cb(rows) + end) + if pending then handle.job = initial end + end + nextPage(1) + return { cancel = function() + handle.cancelled = true + if handle.job and handle.job.cancel then handle.job.cancel() end + end } +end + +---@param book_id string +---@param chapter_id string +---@param cb fun(html: string|nil, err: string|nil, kind: "unpaid"|nil) +---@return HttpJob +function Client.contentAsync(book_id, chapter_id, cb) + local whole = fee_unit[tostring(book_id)] == FEE_WHOLE + return Client.get("/nsr/chapter-content", { + book_id = book_id, + chapter_id = chapter_id, + is_whole_book = whole and "true" or "false", + }, function(body, err) + if type(body) ~= "table" then cb(nil, err or _("响应无效")); return end + -- 免费章的 charging_info 是 JSON null,LuaJSON 解成函数,不能当成未购买。 + -- 未购买才是计费表,而且 is_buy 不为真。已购章也带这张表,正文仍在 bookContent。 + local info = body.charging_info + local bought = type(info) == "table" and (info.is_buy == true or tonumber(info.is_buy) == 1) + if type(info) == "table" and not bought then cb(nil, _("本章未购买"), "unpaid"); return end + if type(body.bookContent) ~= "string" or body.bookContent == "" then + cb(nil, _("响应无效")) + return + end + local html = Mapper.content(body.bookContent) + cb(html, not html and _("掌阅正文含未知字码,请更新插件后重试") or nil) + end) +end + +---@param book_id string +---@param cb fun(item: table|nil, err: string|nil) +---@return HttpJob +function Client.progressAsync(book_id, cb) + return Client.get("/bookstore/open/cloud/book/getProgress", { bookIds = book_id }, function(body, err) + if type(body) ~= "table" then cb(nil, err or _("响应无效")); return end + local key = tostring(book_id) + cb(body[key] or body[tonumber(key)]) + end) +end + +---@param book_id string +---@param chapter_uid string +---@param total integer +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return HttpJob +function Client.putProgressAsync(book_id, chapter_uid, total, cb) + local session = Client.session() + if not session then return require("source.base").defer(cb, nil, _("未登录掌阅")) end + local stored = math.max(0, (tonumber(chapter_uid) or 1) - 1) + local now = os.time() * 1000 + local payload = JSON.encode({ + bookId = tostring(book_id), + deviceName = "掌阅网页", + updateTime = now, + usr = session.usr, + readProcess = { + bookOverStatus = 0, + totalCount = total, + lastReadDate = now, + readingSource = "web", + chapterId = tostring(stored), + }, + }) + return post("/bookstore/open/cloud/book/progress", nil, payload, "application/json", function(body, err) + cb(body and true or nil, err) + end) +end + +local STORE_HEADERS = { + ["User-Agent"] = "Mozilla/5.0 (Linux; Android 12) AppleWebKit/537.36 Chrome/120.0.0.0 Mobile Safari/537.36", +} + +---@param book_id string +---@param cb fun(result: IReaderReviewPage|nil, err: string|nil) +---@return HttpJob +function Client.reviewsAsync(book_id, cb) + local target = STORE .. "/comment/" .. Text.urlEncode(book_id) + local cancelled = false + local job = Request.get(target, { + accept = "text/html", + headers = STORE_HEADERS, + timeout = require("http.timeout").net(0.5), + }, function(raw, err) + if cancelled then return end + if err or not raw then cb(nil, err and tostring(err) or _("请求失败")); return end + local result = Mapper.reviews(raw) + if not result then cb(nil, _("响应无效")); return end + cb(result) + end) + return { cancel = function() + cancelled = true + if job and job.cancel then job.cancel() end + end } +end + +---@param keyword string +---@param cb fun(html: string|nil, err: string|nil) +---@return HttpJob +function Client.searchAsync(keyword, cb) + return Request.get(STORE .. "/search?" .. Text.formEncode({ keyWord = keyword }), { + accept = "text/html", + headers = STORE_HEADERS, + timeout = require("http.timeout").net(0.5), + }, function(raw, err) cb(raw, err and tostring(err) or nil) end) +end + +---@param channel_id string +---@param cb fun(html: string|nil, err: string|nil) +---@return HttpJob +function Client.channelAsync(channel_id, cb) + return Request.get(STORE .. "/channel/" .. channel_id, { + accept = "text/html", + headers = STORE_HEADERS, + timeout = require("http.timeout").net(0.5), + }, function(raw, err) cb(raw, err and tostring(err) or nil) end) +end + +---@param parent string +---@param category string +---@param cb fun(page: table|nil, err: string|nil) +---@return HttpJob +function Client.categoriesAsync(parent, category, cb) + return Request.get(STORE .. "/category/" .. parent .. "/" .. category .. "?currentPage=1", { + accept = "text/html", headers = STORE_HEADERS, + timeout = require("http.timeout").net(0.5), + }, function(raw, err) + local page = raw and Mapper.categories(raw) + if not page then cb(nil, err and tostring(err) or _("响应无效")); return end + cb(page) + end) +end + +---@param opts table +---@param page integer +---@param cb fun(books: Book[]|nil, err: string|nil, more: boolean|nil) +---@return HttpJob +function Client.catalogAsync(opts, page, cb) + return Request.get(STORE .. "/category/" .. opts.parent .. "/" .. opts.category .. "?" .. Text.formEncode({ + isAjax = 1, currentPage = page, pageSize = 20, order = opts.order, status = opts.status, + }), { + accept = "application/json", headers = STORE_HEADERS, + timeout = require("http.timeout").net(0.5), + }, function(raw, err) + local wire, reason = envelope(raw, err) + if not wire then cb(nil, reason); return end + if tonumber(wire.code) ~= SUCCESS then cb(nil, wire.msg or _("请求失败")); return end + local body = wire.body + if type(wire.html) ~= "string" or type(body) ~= "table" + or tonumber(body.current_page) ~= page or not tonumber(body.page_total) then + cb(nil, _("响应无效")) + return + end + local books = Mapper.catalog(wire.html) + if #books == 0 and Text.trim(wire.html) ~= "" then cb(nil, _("响应无效")); return end + cb(books, nil, page < tonumber(body.page_total)) + end) +end + +return Client diff --git a/moonsource-ireader.koplugin/moonsource_ireader/l10n/en.lua b/moonsource-ireader.koplugin/moonsource_ireader/l10n/en.lua new file mode 100644 index 0000000..3c6fc97 --- /dev/null +++ b/moonsource-ireader.koplugin/moonsource_ireader/l10n/en.lua @@ -0,0 +1,85 @@ +return { + ["掌阅登录 Cookie"] = "iReader login Cookie", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie(须含 _zypps)"] = "Press F12, open Network, refresh the page and copy the complete Cookie request header (including _zypps).", + ["没有读到 _zypps(usr/zysid)"] = "Could not find _zypps (usr/zysid)", + ["登录状态已变化,请重试"] = "The login session changed. Please retry.", + ["扫码登录"] = "Sign in with QR code", + ["请先退出当前账号,再登录其他账号"] = "Sign out of the current account before signing in to another account", + ["掌阅"] = "iReader", + ["掌阅书城"] = "iReader Store", + ["掌阅书架与在线阅读"] = "iReader shelf and online reading", + ["掌阅扫码登录"] = "iReader QR sign-in", + ["用掌阅 App 扫一扫"] = "Scan with the iReader app", + ["在掌阅 App「我的」页右上角使用扫一扫"] = "Use the scanner at the top right of Me in the iReader app", + ["未登录掌阅"] = "Not signed in to iReader", + ["掌阅目录为空"] = "iReader chapter list is empty", + ["掌阅正文含未知字码,请更新插件后重试"] = "iReader content contains unknown character codes. Update the plugin and try again.", + ["掌阅插图下载失败,请重试"] = "Failed to download iReader illustrations. Please try again.", + ["掌阅登录已失效,请点「重新登录」,用掌阅 App 扫码。"] = "iReader sign-in has expired. Tap Sign in again and scan with the iReader app.", + ["确定退出掌阅账号?"] = "Sign out of iReader?", + ["掌阅网页不能把书移出书架"] = "The iReader website cannot remove a book from the shelf", + ["掌阅账号"] = "iReader account", + ["本章未购买"] = "This chapter has not been purchased", + ["缺少掌阅章节位置"] = "Missing iReader chapter position", + ["男生"] = "Male", + ["女生"] = "Female", + ["出版"] = "Published", + ["未登录 · 点此扫码"] = "Not signed in · tap to scan", + ["章节目录保存失败"] = "Failed to save chapter list", + ["VIP 章节"] = "VIP chapters", + ["书架同步"] = "Shelf sync", + ["搜索与发现"] = "Search and discover", + ["进度同步"] = "Progress sync", + ["100-200万字"] = "1–2 million words", + ["15天内"] = "Within 15 days", + ["20-50万字"] = "200,000–500,000 words", + ["200万字以上"] = "Over 2 million words", + ["20万字以下"] = "Under 200,000 words", + ["30天内"] = "Within 30 days", + ["3天内"] = "Within 3 days", + ["50-100万字"] = "500,000–1 million words", + ["7天内"] = "Within 7 days", + ["两性"] = "Relationships", + ["亲子"] = "Parenting", + ["休闲"] = "Leisure", + ["会员免费"] = "Free for members", + ["传记"] = "Biography", + ["公版"] = "Public domain", + ["养生"] = "Wellness", + ["农林"] = "Agriculture and forestry", + ["医学"] = "Medicine", + ["古籍"] = "Classics", + ["哲学"] = "Philosophy", + ["外语"] = "Foreign languages", + ["宗教"] = "Religion", + ["家居"] = "Home", + ["小说"] = "Fiction", + ["工业"] = "Industry", + ["工具"] = "Reference", + ["幻情"] = "Fantasy romance", + ["建筑"] = "Architecture", + ["心理"] = "Psychology", + ["手工"] = "Crafts", + ["投资"] = "Investing", + ["政治"] = "Politics", + ["教材教辅"] = "Textbooks and study guides", + ["文化"] = "Culture", + ["文学"] = "Literature", + ["旅游"] = "Travel", + ["时尚"] = "Fashion", + ["杂志"] = "Magazines", + ["法律"] = "Law", + ["漫画书"] = "Comics", + ["畅销"] = "Best-selling", + ["社科"] = "Social sciences", + ["科普"] = "Popular science", + ["童书"] = "Children's books", + ["管理"] = "Management", + ["经济"] = "Economics", + ["考试"] = "Exams", + ["自然"] = "Nature", + ["艺术"] = "Art", + ["英文图书"] = "English books", + ["计算机"] = "Computing", + ["青春"] = "Youth", +} diff --git a/moonsource-ireader.koplugin/moonsource_ireader/l10n/zh_TW.lua b/moonsource-ireader.koplugin/moonsource_ireader/l10n/zh_TW.lua new file mode 100644 index 0000000..c6cd550 --- /dev/null +++ b/moonsource-ireader.koplugin/moonsource_ireader/l10n/zh_TW.lua @@ -0,0 +1,85 @@ +return { + ["掌阅登录 Cookie"] = "掌閱登入 Cookie", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie(须含 _zypps)"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie(須含 _zypps)", + ["没有读到 _zypps(usr/zysid)"] = "沒有讀到 _zypps(usr/zysid)", + ["登录状态已变化,请重试"] = "登入狀態已改變,請重試", + ["扫码登录"] = "掃碼登入", + ["请先退出当前账号,再登录其他账号"] = "請先退出目前帳號,再登入其他帳號", + ["掌阅"] = "掌閱", + ["掌阅书城"] = "掌閱書城", + ["掌阅书架与在线阅读"] = "掌閱書架與線上閱讀", + ["掌阅扫码登录"] = "掌閱掃碼登入", + ["用掌阅 App 扫一扫"] = "用掌閱 App 掃一掃", + ["在掌阅 App「我的」页右上角使用扫一扫"] = "在掌閱 App「我的」頁右上角使用掃一掃", + ["未登录掌阅"] = "未登入掌閱", + ["掌阅目录为空"] = "掌閱目錄為空", + ["掌阅正文含未知字码,请更新插件后重试"] = "掌閱正文含未知字碼,請更新外掛後重試", + ["掌阅插图下载失败,请重试"] = "掌閱插圖下載失敗,請重試", + ["掌阅登录已失效,请点「重新登录」,用掌阅 App 扫码。"] = "掌閱登入已失效,請點「重新登入」,用掌閱 App 掃碼。", + ["确定退出掌阅账号?"] = "確定退出掌閱帳號?", + ["掌阅网页不能把书移出书架"] = "掌閱網頁不能把書移出書架", + ["掌阅账号"] = "掌閱帳號", + ["本章未购买"] = "本章未購買", + ["缺少掌阅章节位置"] = "缺少掌閱章節位置", + ["男生"] = "男生", + ["女生"] = "女生", + ["出版"] = "出版", + ["未登录 · 点此扫码"] = "未登入 · 點此掃碼", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["VIP 章节"] = "VIP 章節", + ["书架同步"] = "書架同步", + ["搜索与发现"] = "搜尋與發現", + ["进度同步"] = "進度同步", + ["100-200万字"] = "100–200萬字", + ["15天内"] = "15天內", + ["20-50万字"] = "20–50萬字", + ["200万字以上"] = "200萬字以上", + ["20万字以下"] = "20萬字以下", + ["30天内"] = "30天內", + ["3天内"] = "3天內", + ["50-100万字"] = "50–100萬字", + ["7天内"] = "7天內", + ["两性"] = "兩性", + ["亲子"] = "親子", + ["休闲"] = "休閒", + ["会员免费"] = "會員免費", + ["传记"] = "傳記", + ["公版"] = "公版", + ["养生"] = "養生", + ["农林"] = "農林", + ["医学"] = "醫學", + ["古籍"] = "古籍", + ["哲学"] = "哲學", + ["外语"] = "外語", + ["宗教"] = "宗教", + ["家居"] = "家居", + ["小说"] = "小說", + ["工业"] = "工業", + ["工具"] = "工具", + ["幻情"] = "幻情", + ["建筑"] = "建築", + ["心理"] = "心理", + ["手工"] = "手工", + ["投资"] = "投資", + ["政治"] = "政治", + ["教材教辅"] = "教材教輔", + ["文化"] = "文化", + ["文学"] = "文學", + ["旅游"] = "旅遊", + ["时尚"] = "時尚", + ["杂志"] = "雜誌", + ["法律"] = "法律", + ["漫画书"] = "漫畫書", + ["畅销"] = "暢銷", + ["社科"] = "社科", + ["科普"] = "科普", + ["童书"] = "童書", + ["管理"] = "管理", + ["经济"] = "經濟", + ["考试"] = "考試", + ["自然"] = "自然", + ["艺术"] = "藝術", + ["英文图书"] = "英文圖書", + ["计算机"] = "電腦", + ["青春"] = "青春", +} diff --git a/moonsource-ireader.koplugin/moonsource_ireader/loadmeta.lua b/moonsource-ireader.koplugin/moonsource_ireader/loadmeta.lua new file mode 100644 index 0000000..1e196df --- /dev/null +++ b/moonsource-ireader.koplugin/moonsource_ireader/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_ireader._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-ireader.koplugin/moonsource_ireader/mapper.lua b/moonsource-ireader.koplugin/moonsource_ireader/mapper.lua new file mode 100644 index 0000000..c9555ad --- /dev/null +++ b/moonsource-ireader.koplugin/moonsource_ireader/mapper.lua @@ -0,0 +1,271 @@ +--[[-- +掌阅网页响应 → 领域对象。纯函数,不发请求。 + +@module moonsource_ireader.mapper +--]] + +local Text = require("utils.text") + +local Mapper = {} + +local SOURCE_ID = "ext.ireader" + +-- 官网 FZYouH_509R_V1.10.ttf 的二十个私用字形;两个连续区间,中间 A–F 没有字形。 +local CONTENT_CHARS = {} +for first, chars in pairs({ + [0xF0000] = "的一是了在有他我这们", + [0xF0010] = "来去说就事你对也还但", +}) do + for idx, ch in ipairs(Text.chars(chars)) do + CONTENT_CHARS[Text.utf8char(first + idx - 1)] = ch + end +end + +--- 官网用补充私用区 A 代替常用字;还原为普通 Unicode,不要求用户安装官网字体。 +---@param html string +---@return string|nil 未知私用字码不能当作有效正文缓存 +function Mapper.content(html) + local unknown = false + local decoded = html:gsub("\243[\176-\191][\128-\191][\128-\191]", function(ch) + local plain = CONTENT_CHARS[ch] + if not plain then unknown = true end + return plain + end) + return not unknown and decoded or nil +end + +--- 只读取官网书评首屏。 +---@class IReaderReviewPage +---@field items { author: string, text: string, time: string, grade: number|nil }[] + +---@param html string +---@return IReaderReviewPage|nil +function Mapper.reviews(html) + local list = html:match(']*class="sns_commentlist"[^>]*>(.-)') + if not list then return nil end + local items = {} + for card in list:gmatch("]*>(.-)") do + local author = card:match(']*class="vm"[^>]*>(.-)') + local body = card:match(']*class="con_dec"[^>]*>(.-)

') + local time = card:match(']*class="sns_time"[^>]*>(.-)') + if not author or not body or not time then return nil end + items[#items + 1] = { + author = Text.stripHtml(author), + text = Text.stripHtml(body), + time = Text.stripHtml(time), + grade = tonumber(card:match('class="cur r(%d+)"')), + } + end + if #items == 0 and Text.trim(list) ~= "" then return nil end + return { items = items } +end + +--- 目录缓存格式。首章携带,变了就当缓存失效。 +Mapper.TOC_VERSION = 1 + +--- 扫码回包 body 是带引号的 JSON 字符串,网页用 replace 去掉引号。两种都认。 +---@param body any +---@return string|nil +function Mapper.qrCode(body) + if type(body) ~= "string" or body == "" then return nil end + local ok, inner = pcall(require("json").decode, body) + if ok and type(inner) == "string" and inner ~= "" then return inner end + local stripped = body:gsub('"', "") + if stripped == "" then return nil end + return stripped +end + +--- 轮询回包。等待是 30059(网页常量 WAIT_LOGIN),成功 body 里 name 是账号、session_id 是 zysid。 +---@param wire table|nil +---@return table|nil user +---@return "wait"|"fail"|nil kind +function Mapper.login(wire) + if type(wire) ~= "table" then return nil, "fail" end + local code = tonumber(wire.code) + if code == 30059 then return nil, "wait" end + local body = wire.body + if code == 0 and type(body) == "table" and type(body.name) == "string" and body.name ~= "" + and type(body.session_id) == "string" and body.session_id ~= "" then + local nick = type(body.nick) == "string" and body.nick ~= "" and body.nick or body.name + return { + usr = body.name, + zysid = body.session_id, + name = nick, + avatar = type(body.avatar) == "string" and body.avatar or nil, + } + end + return nil, "fail" +end + +---@param id string|number +---@param title string|nil +---@param author string|nil +---@param intro string|nil +---@param cover string|nil +---@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 + return { + source_id = SOURCE_ID, + stable_id = tostring(id), + title = clean(title), + authors = clean(author), + intro = clean(intro), + cover = picture, + } +end + +--- 书架行。文件夹和本机上传的书网页读不了,不进月读书架。 +---@param wire table|nil +---@return Book[] +function Mapper.shelf(wire) + local out = {} + local rows = type(wire) == "table" and wire.data or nil + if type(rows) ~= "table" then return out end + for _idx, row in ipairs(rows) do + if type(row) == "table" and row.book_id and row.dtype ~= 1 and row.is_local_book ~= true then + local item = book(row.book_id, row.book_name, row.author, nil, row.icon or row.cover) + if item.title ~= "" then out[#out + 1] = item end + end + end + return out +end + +--- 搜索结果页。卡片是 data-id + data-src + name / author / brief。 +---@param html string|nil +---@return Book[] +function Mapper.search(html) + local out, seen = {}, {} + if type(html) ~= "string" then return out end + local pos = 1 + while true do + local _start, stop, id = html:find('data%-id="(%d+)"', pos) + if not _start then break end + if not seen[id] then + seen[id] = true + local window = html:sub(stop, math.min(#html, stop + 1500)) + local cover = window:match('data%-src="([^"]+)"') + local title = window:match('class="name[^"]*"[^>]*>([^<]*)') + local author = window:match('class="author[^"]*"[^>]*>([^<]*)') + local intro = window:match('class="brief"[^>]*>([^<]*)') + if title and Text.trim(title) ~= "" then + out[#out + 1] = book(id, title, author, intro, cover) + end + end + pos = stop + end + return out +end + +--- 频道页 data-point 里的 cli_res_id / cli_res_name。同一本书滑块里会重复,只留第一次。 +---@param html string|nil +---@return Book[] +function Mapper.channel(html) + local out, seen = {}, {} + if type(html) ~= "string" then return out end + local pattern = '"cli_res_id"%s*:%s*(%d+)%s*,%s*"cli_res_name"%s*:%s*"([^"]*)"' + local pos = 1 + while true do + local _start, stop, id, title = html:find(pattern, pos) + if not _start then break end + if not seen[id] then + seen[id] = true + local cover = html:sub(stop, math.min(#html, stop + 500)):match('src="(https://[^"]+)"') + out[#out + 1] = book(id, title, nil, nil, cover) + end + + pos = stop + end + return out +end + +---@param html string +---@return Book[] +function Mapper.catalog(html) + local out, seen = {}, {} + for id, card in html:gmatch(']-data%-type="book"[^>]-data%-id="(%d+)"[^>]*>(.-)') do + local title = card:match("]*>(.-)") + if title and not seen[id] then + seen[id] = true + out[#out + 1] = book(id, title, card:match('class="author[^"]*"[^>]*>([^<]*)'), + card:match('class="content[^"]*"[^>]*>([^<]*)'), card:match('data%-src="([^"]+)"')) + end + end + return out +end + +---@param html string +---@return table|nil +function Mapper.categories(html) + local parent, category = html:match("var parentId%s*=%s*'(%d+)'%s*,%s*categoryId%s*=%s*'(%d+)'") + if not parent then return nil end + local result = { parent = parent, category = category, channels = {}, categories = {}, orders = {}, statuses = {} } + local seen = {} + for p, id, title in html:gmatch(']-href="[^"]-/category/(%d+)/(%d+)[^"]*"[^>]*>([^<]+)') do + local key = p .. ":" .. id + if not seen[key] then + seen[key] = true + if p == id then + result.channels[#result.channels + 1] = { id = p, title = Text.xmlDecode(title) } + elseif p == parent then + result.categories[#result.categories + 1] = { id = id, title = Text.xmlDecode(title) } + end + end + end + for field, list in pairs({ order = result.orders, status = result.statuses }) do + for id, title in html:gmatch(']-data%-' .. field .. '="([%w]+)"[^>]*>([^<]+)') do + list[#list + 1] = { id = id, title = Text.xmlDecode(title) } + end + end + if #result.channels == 0 or #result.categories == 0 or #result.orders == 0 or #result.statuses == 0 then return nil end + return result +end + +---@param body table|nil +---@param stable_id string +---@return Book|nil +function Mapper.detail(body, stable_id) + if type(body) ~= "table" then return nil end + local id = body.book_id or body.id or stable_id + if not id then return nil end + return book(id, body.name or body.book_name, body.author, body.description or body.brief, body.icon or body.cover or body.pic) +end + +--- 章节目录。网页列表项是 id + name,本地书才有 children。 +---@param rows table[]|nil +---@return BookChapter[] +function Mapper.chapters(rows) + local out = {} + local function walk(list, depth) + for _idx, row in ipairs(type(list) == "table" and list or {}) do + local id = row.id or row.chapter_id + if id ~= nil then + out[#out + 1] = { + uid = tostring(id), + title = Text.trim(tostring(row.name or row.title or "")), + depth = depth, + } + end + if type(row.children) == "table" then walk(row.children, depth + 1) end + end + end + walk(rows, 1) + for idx, chapter in ipairs(out) do chapter.idx = idx end + if out[1] then out[1].toc_version = Mapper.TOC_VERSION end + return out +end + +--- 进度接口把章节 id 存成「列表 id - 1」,读回来要加回去才能对上目录 uid。 +---@param chapter_id number|string|nil +---@return string|nil +function Mapper.progressUid(chapter_id) + local stored = tonumber(chapter_id) + if not stored then return nil end + return tostring(stored + 1) +end + +return Mapper diff --git a/moonsource-ireader.koplugin/moonsource_ireader/qrlogin.lua b/moonsource-ireader.koplugin/moonsource_ireader/qrlogin.lua new file mode 100644 index 0000000..52a6a10 --- /dev/null +++ b/moonsource-ireader.koplugin/moonsource_ireader/qrlogin.lua @@ -0,0 +1,147 @@ +--[[-- +掌阅扫码登录。 + +GET /bookstore/open/user/qrcode/get 的 body 是登录码,二维码内容是 web_login:<码>。 +每 1.5 秒轮询 /bookstore/open/user/qrcode/result,和 PC 站一样最多 160 次。 +30059 继续等;code 0 时 body.name 是账号、body.session_id 是后续请求的 zysid。 + +@module moonsource_ireader.qrlogin +--]] + +local Client = require("moonsource_ireader.client") +local Mapper = require("moonsource_ireader.mapper") +local _ = require("l10n").get("moonsource_ireader") + +local QRLogin = {} +QRLogin.__index = QRLogin + +local POLL_INTERVAL = 1.5 +local POLL_LIMIT = 160 + +---@param on_user fun(user: table) +---@return table +function QRLogin:new(on_user) + return setmetatable({ on_user = on_user, generation = 0 }, QRLogin) +end + +function QRLogin:cancel() + self.generation = self.generation + 1 + if self.job and self.job.cancel then self.job.cancel() end + self.job = nil +end + +---@param text string +function QRLogin:toast(text) + require("ui.themes.widgets.toast"):new{ text = text, timeout = 3 }:show() +end + +---@param text string +function QRLogin:_retry(text) + self:cancel() + if self.dialog then + local previous = self.dialog + self.dialog = nil + previous:close() + end + require("ui.themes.widgets.confirm"):new{ + text = text, + ok_text = _("重新获取"), + ok_callback = function() self:start() end, + }:show() +end + +---@param gen integer +---@param code string +---@param polls integer +function QRLogin:_poll(gen, code, polls) + if gen ~= self.generation then return end + if not require("ui/network/manager"):isConnected() then + self:_retry(_("网络不可用,请先连接 Wi-Fi")) + return + end + if polls > POLL_LIMIT or os.time() >= self.deadline then + self:_retry(_("二维码已过期")) + return + end + local pending = true + local job = Client.qrPollAsync(code, function(wire, err) + pending = false + if gen ~= self.generation then return end + self.job = nil + if not wire then + self:_retry(err or _("请求失败")) + return + end + local user, kind = Mapper.login(wire) + if user then + local checking = true + local check = Client.checkSessionAsync(user, function(ok, reason) + checking = false + if gen ~= self.generation then return end + if not ok then self:_retry(reason or _("登录失败")); return end + self:cancel() + if self.dialog then + local previous = self.dialog + self.dialog = nil + previous:close() + end + self.on_user(user) + end) + if checking then self.job = check end + return + end + if kind ~= "wait" then + self:_retry(type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("登录失败")) + return + end + require("ui/uimanager"):scheduleIn(POLL_INTERVAL, function() + if gen == self.generation then self:_poll(gen, code, polls + 1) end + end) + end) + if pending then self.job = job end +end + +function QRLogin:start() + self:cancel() + if self.dialog then + local previous = self.dialog + self.dialog = nil + previous:close() + end + if not require("ui/network/manager"):isConnected() then + self:toast(_("网络不可用,请先连接 Wi-Fi")) + return + end + local gen = self.generation + self.deadline = os.time() + POLL_INTERVAL * POLL_LIMIT + local pending = true + local job = Client.qrCreateAsync(function(code, err) + pending = false + if gen ~= self.generation then return end + self.job = nil + if not code then + self:toast(err or _("获取二维码失败")) + return + end + local dialog + dialog = require("ui.themes.widgets.qr"):new{ + title = _("掌阅扫码登录"), + text = "web_login:" .. code, + caption = _("用掌阅 App 扫一扫"), + actions = { { text = _("重新获取"), callback = function() self:start() end } }, + close_callback = function() + if self.dialog == dialog then + self.dialog = nil + self:cancel() + self:toast(_("已取消登录")) + end + end, + } + self.dialog = dialog + dialog:show() + self:_poll(gen, code, 1) + end) + if pending then self.job = job end +end + +return QRLogin diff --git a/moonsource-ireader.koplugin/moonsource_ireader/setting.lua b/moonsource-ireader.koplugin/moonsource_ireader/setting.lua new file mode 100644 index 0000000..9d2a454 --- /dev/null +++ b/moonsource-ireader.koplugin/moonsource_ireader/setting.lua @@ -0,0 +1,166 @@ +--[[-- +掌阅账号:App 扫码、官网浏览器登录及 Cookie 导入(`_zypps` → usr/zysid)。 + +@module moonsource_ireader.setting +--]] + +local _ = require("l10n").get("moonsource_ireader") +local CookieLogin = require("source.cookie_login") + +local SOURCE_ID = "ext.ireader" +local Setting = {} +local LOGIN_URL = "https://pc.ireader.com/login" + +---@return boolean +local function loggedIn() + return require("moonsource_ireader.client").session() ~= nil +end + +--- Cookie 请求头里的 `_zypps`(官网 qs 串)→ usr/zysid。 +---@param header string +---@return { usr: string, zysid: string, name: string|nil, avatar: string|nil }|nil +local function userFromCookie(header) + local Text = require("utils.text") + local raw + for part in tostring(header):gmatch("[^;]+") do + local name, value = part:match("^%s*([^=%s]+)%s*=%s*(.-)%s*$") + if name == "_zypps" and value and value ~= "" then + raw = value + break + end + end + if not raw then return nil end + raw = Text.urlDecode(raw) or raw + local fields = {} + for pair in raw:gmatch("[^&]+") do + local key, value = pair:match("^([^=]+)=(.*)$") + if key then + fields[Text.urlDecode(key) or key] = Text.urlDecode(value) or value + end + end + local usr, zysid = fields.usr, fields.zysid + if type(usr) ~= "string" or usr == "" or type(zysid) ~= "string" or zysid == "" then + return nil + end + return { usr = usr, zysid = zysid, name = fields.name, avatar = fields.avatar } +end + +---@param user table +---@return boolean ok +---@return string|nil err +local function commitUser(user) + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + if cfg.usr and cfg.usr ~= "" and cfg.usr ~= user.usr then + local cleared = require("source.logout").clear(SOURCE_ID, function() + cfg.usr, cfg.zysid, cfg.name, cfg.avatar = nil, nil, nil, nil + settings.saveSource(SOURCE_ID) + end) + if not cleared then return false, _("准备本地同步失败") end + end + cfg.usr = user.usr + cfg.zysid = user.zysid + cfg.name = user.name + cfg.avatar = user.avatar + settings.saveSource(SOURCE_ID) + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() + return true +end + +---@param user table +local function save(user) + local ok, err = commitUser(user) + if not ok then + require("ui.themes.widgets.toast"):new{ text = err, timeout = 3 }:show() + return + end + require("ui.themes.widgets.toast"):new{ text = _("登录成功"), timeout = 2 }:show() +end + +---@return string, boolean +function Setting.rowStatus() + local on = loggedIn() + return on and _("已登录") or _("未登录 · 点此扫码"), on +end + +function Setting.open() + require("moonsource_ireader.qrlogin"):new(save):start() +end + +local SPEC = { + id = SOURCE_ID, title = _("掌阅账号"), cookie_title = _("掌阅登录 Cookie"), + cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie(须含 _zypps)"), + logout_text = _("确定退出掌阅账号?"), + loggedIn = loggedIn, + checkAsync = function(cookie, cb) + local user = userFromCookie(cookie) + if not user then return cb(false, _("没有读到 _zypps(usr/zysid)")) end + return require("moonsource_ireader.client").checkSessionAsync(user, function(ok, err) + if not ok then return cb(false, err or _("登录失败")) end + cb(true, nil, user) + end) + end, + commit = function(_cookie, account, cb) + local ok, err = commitUser(account) + cb(ok, err) + end, + clear = function(cfg) + cfg.usr, cfg.zysid, cfg.name, cfg.avatar = nil, nil, nil, nil + end, +} + +--- 扩展 payload 里取 `_zypps`(pc.ireader.com / .zhangyue.com 任一即可)。 +---@param payload table +---@return string +local function cookieFromPayload(payload) + 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 and cookie.name == "_zypps" and type(cookie.value) == "string" and cookie.value ~= "" then + if host == "ireader.com" or host:match("%.ireader%.com$") + or host == "zhangyue.com" or host:match("%.zhangyue%.com$") then + return "_zypps=" .. cookie.value + end + end + end + return "" +end + +Setting.browser = { + domain = "pc.ireader.com", scope = "cookie", login = LOGIN_URL, + check = "https://pc.ireader.com/", + icon = "https://static-efe-front-h.zhangyuecdn.com/sfm-production/logos/bf7fe8aa-35e2-4961-9e1a-e2a095950ff2.png", + isAuthorized = function() return CookieLogin.authorized(SPEC) end, + apply = function(payload, cb) + return CookieLogin.save(SPEC, cookieFromPayload(payload), cb) + 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 = _("在掌阅 App「我的」页右上角使用扫一扫"), + status = status, status_on = status_on, + callback = function() Setting.open() end, + }) + end, + CookieLogin.browserRow(), + CookieLogin.pasteRow(SPEC), + } + if loggedIn() then + rows[#rows + 1] = CookieLogin.logoutRow(SPEC) + end + return rows +end + +Setting.login = Setting.open +Setting.userFromCookie = userFromCookie + +return Setting diff --git a/moonsource-ireader.koplugin/moonsource_ireader/source.lua b/moonsource-ireader.koplugin/moonsource_ireader/source.lua new file mode 100644 index 0000000..f360d72 --- /dev/null +++ b/moonsource-ireader.koplugin/moonsource_ireader/source.lua @@ -0,0 +1,335 @@ +--[[-- +掌阅数据源。 + +扫码登录(掌阅 App)后,书架、目录、正文、进度走 PC 站 JSON。 +书城搜索、分类和分页走手机站。本地删除留墓碑,不伪造远端删除成功。 + +@module moonsource_ireader +--]] + +local Assets = require("source.assets") +local Browse = require("source.browse") +local Client = require("moonsource_ireader.client") +local Mapper = require("moonsource_ireader.mapper") +local Paths = require("utils.paths") +local Shelf = require("source.shelf") +local SourceBase = require("source.base") +local Toc = require("source.toc") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_ireader") + +local IReader = {} + +local FETCH_INTERVAL = 0.5 + +local LEGACY_CHANNELS = { h5_ch_male = "10", h5_ch_female = "68", h5_ch_publish = "92" } +local CHANNEL_TITLES = { ["10"] = _("男生"), ["68"] = _("女生"), ["92"] = _("出版") } + +---@return BookSourceMeta +function IReader.meta() + return require("moonsource_ireader.loadmeta")() +end + +---@class IReaderSource : SourceBase +local Source = setmetatable({ shelf_add = true }, { __index = SourceBase }) +Source.__index = Source + +---@return IReaderSource +function IReader.new() + local meta = IReader.meta() + return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source) +end + +---@return boolean +function Source:configured() + return Client.session() ~= nil +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) + local row = require("book.books_db").get("ext.ireader", stable_id) + return Client.addAsync(stable_id, row and row.title or stable_id, cb) +end + +--- 未接入可验证的远端移架请求。返回失败,墓碑留着,下次拉书架也不会把这本书加回来。 +function Remote:removeFromShelfAsync(_stable_id, cb) + return SourceBase.defer(cb, nil, _("掌阅网页不能把书移出书架")) +end + +function Source:syncBooksAsync(opts, cb) + if not self:configured() then return SourceBase.skipped(cb, "ireader not logged in") end + return Shelf.syncAsync(self.id, Remote, Mapper.shelf, 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(html, err) + if not html then cb(nil, err or _("请求失败")); return end + cb({ data = Mapper.search(html) }) + end) +end + +---@param identity BookIdentity +---@param cb fun(page: IReaderReviewPage|nil, err: string|nil) +---@return HttpJob +function Source:bookReviewsAsync(identity, cb) + return Client.reviewsAsync(identity.stable_id, cb) +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 = opts and opts.node or "" + local parent, category, order, status = node:match("^(%d+):(%d+):(%w+):(%d+)$") + parent = parent or LEGACY_CHANNELS[node] or "10" + category, order, status = category or parent, order or "download", status or "0" + local limit = opts and opts.limit or 60 + local handle, pending = {}, true + local initial = Client.categoriesAsync(parent, category, function(page, err) + pending = false + if handle.cancelled then return end + if not page then cb(nil, err); return end + parent, category = page.parent, page.category + local function valid(rows, value, fallback) + for _idx, row in ipairs(rows) do if row.id == value then return value end end + return fallback + end + order = valid(page.orders, order, page.orders[1].id) + status = valid(page.statuses, status, page.statuses[1].id) + local values = { parent, category, order, status } + local function group(title, rows, position) + local chips, active = {}, nil + for _idx, row in ipairs(rows) do + local next_node = { unpack(values) } + next_node[position] = row.id + if position == 1 then + next_node[2] = row.id + if row.id == "92" and status == "3" then next_node[4] = "0" end + end + local id = table.concat(next_node, ":") + chips[#chips + 1] = { id = id, title = position == 1 and CHANNEL_TITLES[row.id] or row.title } + if row.id == values[position] then active = id end + end + return { title = title, chips = chips, active = active } + end + local groups = { + group(nil, page.channels, 1), group(_("分类"), page.categories, 2), + group(_("排序"), page.orders, 3), group(_("状态"), page.statuses, 4), + } + handle.job = Browse.pages(function(index, done) + return Client.catalogAsync({ parent = parent, category = category, order = order, status = status }, index, done) + end, limit, groups, function(result, reason) + if handle.cancelled then return end + 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.job = initial end + function handle.cancel() + handle.cancelled = true + if handle.job then handle.job.cancel() end + end + return handle +end + +function Source:getDetailAsync(identity, cb) + return Client.detailAsync(identity.stable_id, function(body, err) + local detail = Mapper.detail(body, identity.stable_id) + if detail then cb(require("book.store").rememberDetail(detail)); 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 IReaderSource +---@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(rows, err) + if not rows then cb(nil, err); return end + local toc = Mapper.chapters(rows) + if #toc == 0 then cb(nil, _("掌阅目录为空")); return end + if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end + cb(toc) + end) +end + +function Source:loadTocAsync(identity, cb, force) + if not force then + local cached = Toc.read(self.id, identity.stable_id) + if cached and #cached > 0 and (cached[1].toc_version == Mapper.TOC_VERSION + or not require("ui/network/manager"):isConnected()) then + return SourceBase.defer(cb, cached) + end + end + return fetchTocAsync(self, identity, cb) +end + +Source.refreshTocAsync = fetchTocAsync + +--- 已缓存正文离线原地还原字码,保留路径、节点和 sidecar;失败不覆盖旧文件。 +---@param path string +---@return boolean +local function reuse(path) + local file = assert(io.open(path, "rb")) + local raw, read_err = file:read("*a") + file:close() + assert(raw, read_err) + local html = assert(Mapper.content(raw), _("掌阅正文含未知字码,请更新插件后重试")) + if html == raw then return true end + local temp = path .. ".part" + file = assert(io.open(temp, "wb")) + local written, write_err = file:write(html) + local closed, close_err = file:close() + if not written or not closed then + os.remove(temp) + error(write_err or close_err) + end + local renamed, rename_err = os.rename(temp, path) + if not renamed then + os.remove(temp) + error(rename_err) + end + return true +end + +---@param open boolean +---@return ChapterFetchContent +local function fetcher(open) + return function(identity, chapter, done) + local cancelled, active, image_err = false, nil, nil + local pending = true + local initial = Client.contentAsync(identity.stable_id, chapter.uid, function(html, err, kind) + pending = false + if cancelled then return end + if html then + active = Assets.localizeAsync(html, + Paths.bookWorkDir(identity.stable_id, "ext.ireader") .. "/images", + function(url, cb) + return require("http.request").get(url, { + accept = "image/*", + headers = { Referer = "https://pc.ireader.com/" }, + cache_ttl = 0, + allow_redirects = true, + timeout = require("http.timeout").net(0.5), + }, function(raw, reason) + if reason then image_err = tostring(reason) end + cb(raw, reason) + end) + end, + function(localized) + if cancelled then return end + if Text.hasRemoteImageSrc(localized) then + done(nil, image_err or _("掌阅插图下载失败,请重试")) + return + end + done({ title = chapter.title, html = localized }) + end) + elseif open and kind == "unpaid" then + local notice = string.format(_("这是 VIP 章节,你还没有购买。\n请先在%s购买本章,再回来阅读。"), _("掌阅")) + done({ + title = chapter.title, + html = Text.chapterHtml(chapter.title, notice), + temporary = true, + }) + else + done(nil, err) + end + end) + if pending then active = initial end + return { cancel = function() + cancelled = true + if active and active.cancel then active.cancel() end + 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(true), + reuse = reuse, + }, 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(false), + interval_seconds = FETCH_INTERVAL, + reuse = reuse, + }, cb) +end + +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + local Chapter = require("source.chapter") + return Chapter.cacheAllAsync(self, identity, fetcher(false), on_progress, cb, FETCH_INTERVAL, range, reuse) +end + +function Source:getProgressAsync(identity, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录掌阅")) end + local cancelled, job = false, nil + local pending = true + local initial = Client.progressAsync(identity.stable_id, function(item, err) + pending = false + if cancelled then return end + if err then cb(nil, err); return end + ---@type { chapterId: string|number|nil, readPercent: string|number|nil }|nil + local process = type(item) == "table" and item.readProcess or nil + local uid = type(process) == "table" and Mapper.progressUid(process.chapterId) or nil + if not uid 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, uid) + if not idx then cb(nil, nil, { empty = true }); return end + cb({ + chapter_idx = idx, + chapter_title = toc[idx].title, + fraction = (idx - 1) / #toc, + extra = { chapter_uid = uid, chapter_idx = idx }, + }) + end) + end) + if pending then job = initial 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 = false, nil + local pending = true + local initial = 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, #toc, function(ok, perr) + if cancelled then return end + cb(ok and true or nil, perr) + end) + end) + if pending then job = initial end + return { cancel = function() + cancelled = true + if job and job.cancel then job.cancel() end + end } +end + +return IReader diff --git a/tests/ireader/async_spec.lua b/tests/ireader/async_spec.lua new file mode 100644 index 0000000..964600e --- /dev/null +++ b/tests/ireader/async_spec.lua @@ -0,0 +1,122 @@ +--[[-- +掌阅取消在途下一阶段、坏响应与旧会话认证状态隔离。 + +@module tests.moonsource_ireader.async_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 cfg = { usr = "old", zysid = "old-session" } +package.loaded["utils.settings"] = { getSource = function() return cfg end } +local requests, mode = {}, "delayed" +package.loaded["http.request"] = { + get = function(url, opts, cb) + local request = { url = url, opts = opts, cb = cb } + requests[#requests + 1] = request + if url:find("/bookshelf/list", 1, true) and mode == "sync-shelf" then + cb(JSON.encode({ code = 0, body = { data = {}, current_version = 1 } })) + elseif url:find("page=1", 1, true) and mode == "sync-toc" then + cb(JSON.encode({ code = 0, body = { list = { { id = 1 } }, page = { totalPage = 2 } } })) + end + return { cancel = function() request.cancelled = true end } + end, + post = function(url, body, opts, cb) + local request = { url = url, body = body, opts = opts, cb = cb } + requests[#requests + 1] = request + return { cancel = function() request.cancelled = true end } + end, +} +local Client = require("moonsource_ireader.client") +local result, reason, calls = nil, nil, 0 +local function done(value, err) result, reason, calls = value, err, calls + 1 end + +Client.qrCreateAsync(done) +Assert.is_nil(requests[#requests].url:find("usr=old", 1, true)) +Assert.eq(requests[#requests].opts.cache_ttl, 0) +Client.qrPollAsync("test-code", done) +Assert.is_nil(requests[#requests].url:find("old-session", 1, true)) +Assert.eq(requests[#requests].opts.cache_ttl, 0) + +mode = "sync-shelf" +local handle = Client.addAsync("42", "书", done) +local pending = requests[#requests] +local before = calls +handle:cancel() +Assert.is_true(pending.cancelled) +pending.cb(JSON.encode({ code = 0, body = true })) +Assert.eq(calls, before) + +mode = "delayed" +Client.addAsync("42", "书", done) +pending = requests[#requests] +local count = #requests +cfg.usr, cfg.zysid = "new", "new-session" +pending.cb(JSON.encode({ code = 0, body = { data = {}, current_version = 1 } })) +Assert.eq(#requests, count, "会话变化不能用旧账号发加架请求") +Assert.is_nil(result) +Assert.eq(reason, "登录状态已变化,请重试") + +local Auth = require("source.auth") +Auth.reset() +Client.get("/old-response", nil, done) +pending = requests[#requests] +cfg.zysid = "renewed" +pending.cb(JSON.encode({ code = 600001 })) +Assert.is_true(not Auth.expired("ext.ireader")) +Assert.is_nil(result) +Client.get("/expired", nil, done) +requests[#requests].cb(JSON.encode({ code = 600001 })) +Assert.is_true(Auth.expired("ext.ireader")) +Client.get("/stale-success", nil, done) +pending = requests[#requests] +cfg.zysid = "latest" +pending.cb(JSON.encode({ code = 0, body = {} })) +Assert.is_true(Auth.expired("ext.ireader"), "旧会话成功不能清新会话的失效标记") + +mode = "sync-toc" +handle = Client.chaptersAsync("42", done) +pending = requests[#requests] +before = calls +handle:cancel() +Assert.is_true(pending.cancelled) +pending.cb(JSON.encode({ code = 0, body = { list = {}, page = { totalPage = 2 } } })) +Assert.eq(calls, before) + +mode = "delayed" +Client.chaptersAsync("42", done) +requests[#requests].cb(JSON.encode({ code = 0, body = {} })) +Assert.is_nil(result) +Assert.eq(reason, "响应无效") +Client.chaptersAsync("42", done) +requests[#requests].cb(JSON.encode({ code = 0, body = { list = {}, page = { totalPage = 3 } } })) +Assert.is_nil(result) +Assert.eq(reason, "响应无效") +Client.contentAsync("42", "1", done) +requests[#requests].cb(JSON.encode({ code = 0, body = true })) +Assert.is_nil(result) +Assert.eq(reason, "响应无效") +Client.shelfAsync(done) +requests[#requests].cb(JSON.encode({ code = 0, body = {} })) +Assert.is_nil(result) +Assert.eq(reason, "响应无效") +Auth.expire("ext.ireader", "测试失效状态") +Client.checkSessionAsync({ usr = "candidate", zysid = "candidate-session" }, done) +Assert.is_true(requests[#requests].url:find("usr=candidate", 1, true) ~= nil) +requests[#requests].cb(JSON.encode({ code = 0, body = { data = {} } })) +Assert.is_true(result) +Assert.is_true(Auth.expired("ext.ireader"), "候选登录校验不改变现有账号的认证状态") + +local catalog_opts = { parent = "10", category = "11", order = "score", status = "0" } +Client.catalogAsync(catalog_opts, 2, done) +Assert.is_true(requests[#requests].url:find("currentPage=2", 1, true) ~= nil) +requests[#requests].cb(JSON.encode({ code = 0, html = "", body = { current_page = 2, page_total = 2 } })) +Assert.len(result, 0) +Client.catalogAsync(catalog_opts, 2, done) +requests[#requests].cb(JSON.encode({ code = 0, html = "captcha", body = { current_page = 2, page_total = 3 } })) +Assert.is_nil(result) +Assert.eq(reason, "响应无效") +Client.catalogAsync(catalog_opts, 2, done) +requests[#requests].cb(nil, "network failed") +Assert.eq(reason, "network failed") diff --git a/tests/ireader/browse_spec.lua b/tests/ireader/browse_spec.lua new file mode 100644 index 0000000..cd5d35c --- /dev/null +++ b/tests/ireader/browse_spec.lua @@ -0,0 +1,101 @@ +--[[-- +掌阅真实分类结构、频道切换、分页去重和失败传播。 + +@module tests.moonsource_ireader.browse_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Mapper = require("moonsource_ireader.mapper") +local html = [[ + +男频 +女频 +出版 +玄幻 +都市 +热门书籍评分最高 +全部完结 +]] +local page = Mapper.categories(html) +Assert.eq(page.parent, "10") +Assert.eq(page.category, "11") +Assert.len(page.channels, 3) +Assert.len(page.categories, 2) +Assert.eq(page.categories[2].id, "27") +Assert.eq(page.orders[2].id, "score") +Assert.is_nil(Mapper.categories("captcha")) +local card = [[ +
  • +
    书名
    作者
    简介
  • +]] +local books = Mapper.catalog(card .. card) +Assert.len(books, 1) +Assert.eq(books[1].title, "书名") +Assert.eq(books[1].authors, "作者") +Assert.eq(books[1].intro, "简介") +Assert.eq(books[1].cover, "https://img/42?a=1&b=2") + +local requests, mode = {}, "ok" +package.loaded["moonsource_ireader.client"] = { + categoriesAsync = function(parent, category, cb) + requests[#requests + 1] = { parent = parent, category = category } + if mode == "invalid" then cb(nil, "bad catalog"); return end + local current = Mapper.categories(html) + if parent == "92" then + current.parent, current.category = "92", "93" + current.categories = { { id = "93", title = "小说" } } + current.statuses = { { id = "0", title = "全部" } } + elseif category == "27" then current.category = category end + cb(current) + return { cancel = function() end } + end, + catalogAsync = function(opts, index, cb) + local request = { opts = opts, page = index, cb = cb } + requests[#requests + 1] = request + if mode == "delayed" and index == 2 then + return { cancel = function() request.cancelled = true end } + end + if mode == "failed" and index == 2 then cb(nil, "network failed"); return end + cb({ + { source_id = "ext.ireader", stable_id = tostring(index), title = "书" }, + { source_id = "ext.ireader", stable_id = "duplicate", title = "重复" }, + }, nil, index < 3) + return { cancel = function() request.cancelled = true end } + end, +} +local source = require("moonsource_ireader.source").new() +local result, reason, calls = nil, nil, 0 +local function done(value, err) result, reason, calls = value, err, calls + 1 end +source:browseAsync({ node = "h5_ch_female", limit = 4 }, done) +Assert.eq(requests[1].parent, "68", "兼容旧频道节点") +Assert.len(result.data, 4) +Assert.is_nil(reason) +Assert.len(result.groups, 4) +Assert.eq(result.groups[2].title, "分类") +Assert.eq(result.groups[3].chips[2].id, "10:11:score:0") + +source:browseAsync({ node = "10:27:score:3", limit = 2 }, done) +Assert.eq(requests[#requests].opts.category, "27") +Assert.eq(requests[#requests].opts.order, "score") +Assert.eq(requests[#requests].opts.status, "3") +Assert.eq(result.groups[1].chips[3].id, "92:92:score:0", "出版不保留不支持的完结筛选") +source:browseAsync({ node = "92:92:score:3", limit = 2 }, done) +Assert.eq(requests[#requests].opts.status, "0") +Assert.eq(requests[#requests].opts.category, "93") + +mode = "failed" +source:browseAsync({ limit = 4 }, done) +Assert.is_nil(result) +Assert.eq(reason, "network failed", "中间页失败不能伪装完整列表") +mode = "invalid" +source:browseAsync({}, done) +Assert.eq(reason, "bad catalog") +mode = "delayed" +local handle = source:browseAsync({ limit = 4 }, done) +local pending = requests[#requests] +local before = calls +handle:cancel() +Assert.is_true(pending.cancelled, "同步首阶段后取消当前分页请求") +pending.cb({}, nil, false) +Assert.eq(calls, before) diff --git a/tests/ireader/client_spec.lua b/tests/ireader/client_spec.lua new file mode 100644 index 0000000..1d1caa4 --- /dev/null +++ b/tests/ireader/client_spec.lua @@ -0,0 +1,233 @@ +--[[-- +掌阅:网页封套、扫码、书架插入位置、目录分页、正文计费、进度章节号。 + +@module tests.moonsource_ireader.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_ireader.mapper") + +Assert.eq(Mapper.qrCode('"abc"'), "abc", "扫码 body 是带引号的 JSON 字符串") +Assert.eq(Mapper.qrCode("abc"), "abc") +Assert.is_nil(Mapper.qrCode("")) + +local waiting = select(2, Mapper.login({ code = 30059, msg = "随机码未授权" })) +Assert.eq(waiting, "wait") +local user = Mapper.login({ + code = 0, + body = { name = "usr1", session_id = "sid1", nick = "读者", avatar = "http://a" }, +}) +Assert.eq(user.usr, "usr1") +Assert.eq(user.zysid, "sid1") +Assert.eq(user.name, "读者") +Assert.eq(select(2, Mapper.login({ code = 1, msg = "失败" })), "fail") + +local shelf = Mapper.shelf({ + data = { + { book_id = 1, book_name = "在架", dtype = 0, is_local_book = false }, + { book_id = 2, book_name = "文件夹", dtype = 1 }, + { book_id = 3, book_name = "本地上传", dtype = 0, is_local_book = true }, + }, +}) +Assert.eq(#shelf, 1) +Assert.eq(shelf[1].stable_id, "1") +Assert.eq(shelf[1].source_id, "ext.ireader") + +local found = Mapper.search([[ +
    三体 +刘慈欣

    科幻

    +
    重复
    +]]) +Assert.eq(#found, 1) +Assert.eq(found[1].title, "三体") +Assert.eq(found[1].authors, "刘慈欣") +Assert.eq(found[1].cover, "https://img/a.jpg") + +local channel = Mapper.channel([[ +{"cli_res_id": 9, "cli_res_name": "好书"} +{"cli_res_id": 9, "cli_res_name": "好书"} +]]) +Assert.eq(#channel, 1) +Assert.eq(channel[1].stable_id, "9") +Assert.eq(channel[1].title, "好书") +Assert.eq(channel[1].cover, "https://img/c.jpg") + +local toc = Mapper.chapters({ + { id = 1, name = "卷一", children = { { id = 2, name = "第一章" } } }, + { id = 3, name = "第二章" }, +}) +Assert.eq(#toc, 3) +Assert.eq(toc[1].uid, "1") +Assert.eq(toc[2].uid, "2") +Assert.eq(toc[2].depth, 2) +Assert.eq(toc[2].idx, 2) +Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION) +Assert.eq(Mapper.progressUid(0), "1") +Assert.eq(Mapper.progressUid("4"), "5") +Assert.is_nil(Mapper.progressUid("nope")) + +local settings = {} +local requests = {} +local function reply(url, payload) + if url:find("m.zhangyue.com/search", 1, true) then return "search-page" end + if url:find("/qrcode/get", 1, true) then + return Json.encode({ code = 0, body = '"abc"' }) + end + if url:find("/qrcode/result", 1, true) then + return Json.encode({ code = 30059, msg = "随机码未授权" }) + end + if url:find("/bookshelf/list", 1, true) then + return Json.encode({ code = 0, body = { data = { { order = 10, top = 0 }, { order = 3, top = 1 } }, current_version = 7 } }) + end + if url:find("/bookshelf/upsert", 1, true) then + return Json.encode({ code = 100011, msg = "已在书架" }) + end + if url:find("/book/detail", 1, true) then + if url:find("book_id=locked", 1, true) then + return Json.encode({ code = 100001, msg = "用户名不能为空" }) + end + return Json.encode({ code = 0, body = { id = "9", name = "好书", fee_unit = 10, author = "作者" } }) + end + if url:find("/chapter/web/list", 1, true) then + local page = url:match("page=(%d+)") + local row = page == "1" and { id = 1, name = "第一章" } or { id = 2, name = "第二章" } + return Json.encode({ code = 0, body = { list = { row }, page = { totalPage = 2 } } }) + end + if url:find("/chapter-content", 1, true) then + if url:find("chapter_id=vip", 1, true) then + return Json.encode({ code = 0, body = { bookContent = "

    锁

    ", charging_info = { price = 1, is_buy = false } } }) + end + if url:find("chapter_id=owned", 1, true) then + return Json.encode({ code = 0, body = { bookContent = "

    已购

    ", charging_info = { is_buy = true } } }) + end + if url:find("chapter_id=free", 1, true) then + return Json.encode({ code = 0, body = { bookContent = "

    免费

    ", charging_info = nil } }) + end + return Json.encode({ code = 0, body = { bookContent = "

    正文

    " } }) + end + if url:find("/getProgress", 1, true) then + return Json.encode({ code = 0, body = { ["9"] = { readProcess = { chapterId = 4, readPercent = 50 } } } }) + end + if url:find("/book/progress", 1, true) then + return Json.encode({ code = 0, body = true }) + end + if url:find("/expired", 1, true) then + return Json.encode({ code = 600001, msg = "登录已失效" }) + end + return payload +end + +package.preload["utils.settings"] = function() + return { + getSource = function() return settings end, + saveSource = function() end, + } +end +package.preload["http.request"] = function() + return { + get = function(url, _options, callback) + requests[#requests + 1] = { method = "GET", url = url } + callback(reply(url)) + return { cancel = function() end } + end, + post = function(url, payload, _options, callback) + requests[#requests + 1] = { method = "POST", url = url, body = payload } + callback(reply(url, payload)) + return { cancel = function() end } + end, + } +end + +local Client = require("moonsource_ireader.client") + +Assert.eq((Client.shelfCursor({ { order = 10, top = 0 }, { order = 3, top = 1 } }, 7)), 9) +Assert.eq(select(2, Client.shelfCursor({}, nil)), 0) +Assert.eq((Client.shelfCursor(nil, nil)), 999998) + +local code, qerr = nil, "unset" +Client.qrCreateAsync(function(value, err) code, qerr = value, err end) +Assert.eq(code, "abc") +Assert.is_nil(qerr) +Assert.is_true(requests[1].url:find("p29=zye5b814", 1, true) ~= nil, "设备号 p29") +Assert.is_true(requests[1].url:find("p33=com.chaozh.iReaderFree", 1, true) ~= nil, "包名 p33") +Assert.is_true(requests[1].url:find("https://api-pc.zhangyue.com/bookstore/open/user/qrcode/get?", 1, true) == 1) + +local polled +Client.qrPollAsync("abc", function(wire) polled = wire end) +Assert.eq(polled.code, 30059) +Assert.is_true(requests[#requests].url:find("code=abc", 1, true) ~= nil) + +---@type table|string|nil +local anon_body = "x" +local anon_err +Client.detailAsync("locked", function(body, err) anon_body, anon_err = body, err end) +Assert.is_nil(anon_body) +Assert.eq(anon_err, "未登录掌阅") + +settings.usr, settings.zysid = "usr1", "sid1" +local detail +Client.detailAsync("9", function(body) detail = body end) +Assert.eq(detail.name, "好书") +Assert.eq(Mapper.detail(detail, "9").title, "好书") +Assert.eq(Mapper.detail(detail, "9").stable_id, "9") + +local html, herr, kind +Client.contentAsync("9", "1", function(body, err, content_kind) html, herr, kind = body, err, content_kind end) +Assert.eq(html, "

    正文

    ") +Assert.is_nil(herr) +Assert.is_true(requests[#requests].url:find("https://pc.ireader.com/nsr/chapter-content?", 1, true) == 1) +Assert.is_true(requests[#requests].url:find("is_whole_book=true", 1, true) ~= nil, "按本计费整本标记") + +Client.contentAsync("9", "vip", function(body, err, content_kind) html, herr, kind = body, err, content_kind end) +Assert.is_nil(html) +Assert.eq(herr, "本章未购买") +Assert.eq(kind, "unpaid") + +Client.contentAsync("9", "free", function(body, err, content_kind) html, herr, kind = body, err, content_kind end) +Assert.eq(html, "

    免费

    ") +Assert.is_nil(herr) + +Client.contentAsync("9", "owned", function(body, err, content_kind) html, herr, kind = body, err, content_kind end) +Assert.eq(html, "

    已购

    ") +Assert.is_nil(herr) + +local rows +Client.chaptersAsync("9", function(list) rows = list end) +Assert.eq(#rows, 2) +Assert.eq(rows[2].name, "第二章") + +local added, aerr +Client.addAsync("9", "好书", function(ok, err) added, aerr = ok, err end) +Assert.eq(added, true) +Assert.is_nil(aerr) +local upsert = requests[#requests] +Assert.eq(upsert.method, "POST") +Assert.is_true(upsert.body:find('name="type"', 1, true) ~= nil) +Assert.is_true(upsert.body:find("\r\n\r\n1\r\n", 1, true) ~= nil, "插入 type=1") +Assert.is_true(upsert.body:find('"order":9', 1, true) ~= nil) +Assert.is_true(upsert.body:find('"is_local_book":false', 1, true) ~= nil) + +local progress +Client.progressAsync("9", function(item) progress = item end) +Assert.eq(progress.readProcess.chapterId, 4) +Assert.eq(Mapper.progressUid(progress.readProcess.chapterId), "5") + +local posted +Client.putProgressAsync("9", "5", 20, function(ok) posted = ok end) +Assert.eq(posted, true) +Assert.is_true(requests[#requests].body:find('"chapterId":"4"', 1, true) ~= nil, "进度存的是列表 id 减一") +Assert.is_true(requests[#requests].body:find('"deviceName":"掌阅网页"', 1, true) ~= nil) + +local expired +Client.get("/expired", nil, function(_body, err) expired = err end) +Assert.eq(expired, "掌阅登录已失效,请点「重新登录」,用掌阅 App 扫码。") + +local search_html +Client.searchAsync("三体", function(raw) search_html = raw end) +Assert.eq(search_html, "search-page") +Assert.is_true(requests[#requests].url:find("https://m.zhangyue.com/search?", 1, true) == 1) +Assert.is_true(requests[#requests].url:find("keyWord=", 1, true) ~= nil) diff --git a/tests/ireader/content_spec.lua b/tests/ireader/content_spec.lua new file mode 100644 index 0000000..35a556e --- /dev/null +++ b/tests/ireader/content_spec.lua @@ -0,0 +1,174 @@ +--[[-- +掌阅补充私用字码、正文插图、分阶段取消与旧章节离线升级。 + +@module tests.moonsource_ireader.content_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Config = require("support.config") +local JSON = require("support.json_stub") +local Text = require("utils.text") +local Mapper = require("moonsource_ireader.mapper") +local Fs = require("utils.fs") + +local encoded = {} +for cp = 0xF0000, 0xF0009 do encoded[#encoded + 1] = Text.utf8char(cp) end +for cp = 0xF0010, 0xF0019 do encoded[#encoded + 1] = Text.utf8char(cp) end +local attributes = ' id="keep" data-book="original"' +Assert.eq(Mapper.content("" .. table.concat(encoded) .. "

    "), + "的一是了在有他我这们来去说就事你对也还但

    ") +Assert.eq(Mapper.content("

    普通字、标点 & 😀

    "), "

    普通字、标点 & 😀

    ") +Assert.is_nil(Mapper.content("

    " .. Text.utf8char(0xF001A) .. "

    "), "新字码不能静默留下问号") + +local requests, content_async, images_sync = {}, false, false +local wire, image_data, image_error +local png = "\137PNG\r\n\026\n" .. string.rep("x", 32) +local url = "https://bookbk.img.zhangyue01.com/fixture.png?v=one&t=two" +local raw = '

    人' .. Text.utf8char(0xF0009) .. Text.utf8char(0xF0004) + .. '阅读。

    ' + +package.loaded["json"] = JSON +package.loaded["utils.settings"] = { getSource = function() return { usr = "test", zysid = "test" } end } +package.loaded["http.request"] = { + get = function(target, opts, cb) + local request = { url = target, opts = opts, cb = cb } + requests[#requests + 1] = request + if target:find("/nsr/chapter-content", 1, true) then + if not content_async then cb(JSON.encode(wire)) end + elseif images_sync then + cb(image_data, image_error) + end + return { cancel = function() request.cancelled = true end } + end, +} + +local captured_ops, captured_reuse +local identity = { source_id = "ext.ireader", stable_id = "content-fixture" } +local chapter = { idx = 1, uid = "1", title = "正文" } +package.loaded["source.chapter"] = { + openAsync = function(_source, ref, _book, _opts, ops, cb) + captured_ops = ops + return ops.fetchContent(ref, chapter, cb) + end, + prefetchAsync = function(ref, _book, _toc, _from, _count, ops, cb) + captured_ops = ops + return ops.fetchContent(ref, chapter, cb) + end, + cacheAllAsync = function(_source, ref, fetch, _progress, cb, _interval, _range, cache_reuse) + captured_reuse = cache_reuse + return fetch(ref, chapter, cb) + end, +} +local source = require("moonsource_ireader.source").new() +local Client = require("moonsource_ireader.client") +local payload, reason, calls = nil, nil, 0 +local function done(value, err) payload, reason, calls = value, err, calls + 1 end +local function reset() + requests, payload, reason, calls = {}, nil, nil, 0 + content_async, images_sync = false, false + image_data, image_error = png, nil + wire = { code = 0, body = { bookContent = raw } } +end +local function open() + return source:openBookAsync(identity, { chapter_idx = 1 }, done) +end + +reset() +open() +Assert.eq(#requests, 2, "正文同步返回后转入插图下载") +local image = requests[2] +Assert.eq(image.url, (url:gsub("&", "&"))) +Assert.eq(image.opts.headers.Referer, "https://pc.ireader.com/") +Assert.is_nil(image.opts.headers.Cookie) +Assert.is_nil(image.url:find("zysid=", 1, true)) +Assert.is_nil(image.url:find("usr=", 1, true), "正文凭证不发送到图片 CDN") +Assert.eq(calls, 0, "图片完成前不交出成功正文") +image.cb(png) +Assert.eq(calls, 1) +Assert.is_nil(reason) +Assert.eq(payload.title, chapter.title) +Assert.is_true(payload.html:find("人们在阅读。", 1, true) ~= nil) +Assert.is_false(Text.hasRemoteImageSrc(payload.html)) +Assert.eq(#requests, 2, "同一图片只下载一次") +local href = payload.html:match('src="([^"]+)"') +Assert.matches(href, "^images/[a-f0-9]+%.png$") +Assert.eq(Fs.read(require("utils.paths").bookWorkDir(identity.stable_id, "ext.ireader") .. "/" .. href), png) + +reset() +local handle = open() +image = requests[2] +handle:cancel() +Assert.is_true(image.cancelled, "正文同步回调不能用旧请求覆盖图片取消句柄") +image.cb(png) +Assert.eq(calls, 0) + +reset() +content_async = true +handle = open() +local initial = requests[1] +handle:cancel() +Assert.is_true(initial.cancelled) +initial.cb(JSON.encode(wire)) +Assert.eq(#requests, 1, "取消后的正文回包不能再下载插图") +Assert.eq(calls, 0) + +reset() +images_sync, image_data, image_error = true, nil, "network failed" +open() +Assert.is_nil(payload) +Assert.eq(reason, "network failed", "图片网络失败不能算全章缓存成功") + +reset() +images_sync, image_data = true, "not an image" +open() +Assert.is_nil(payload) +Assert.eq(reason, "掌阅插图下载失败,请重试") + +reset() +wire.body.bookContent = "

    " .. Text.utf8char(0xF001A) .. "

    " +Client.contentAsync("content-fixture", "1", done) +Assert.is_nil(payload) +Assert.eq(reason, "掌阅正文含未知字码,请更新插件后重试") + +reset() +wire.body = { bookContent = raw, charging_info = { is_buy = false } } +source:prefetchChaptersAsync(identity, { chapter }, 0, 1, done) +Assert.is_nil(payload) +Assert.eq(reason, "本章未购买") +Assert.eq(#requests, 1, "未购正文不能开始下载资源") + +reset() +wire.body.bookContent = '

    ' .. Text.utf8char(0xF0000) .. "正文。

    " +open() +local cache_reuse = captured_ops.reuse +local old = '书名

    旧' + .. Text.utf8char(0xF0000) .. "正文。

    " +local fixed = old:gsub(Text.utf8char(0xF0000), "的") +local path = Config.dir() .. "/ireader_content_fixture.html" +local function writeOld() + local file = assert(io.open(path, "wb")); assert(file:write(old)); assert(file:close()) +end +writeOld() +Assert.is_true(cache_reuse(path)) +Assert.eq(Fs.read(path), fixed, "不联网、不删目录、不改节点,原地修复旧缓存") +Assert.is_true(cache_reuse(path)) +Assert.eq(Fs.read(path), fixed, "升级幂等") +Assert.is_nil(io.open(path .. ".part", "rb")) + +writeOld() +local rename = os.rename +os.rename = function() return nil, "rename blocked" end +Assert.errors(function() cache_reuse(path) end, "rename blocked") +os.rename = rename +Assert.eq(Fs.read(path), old, "落盘失败保留旧正文") +Assert.is_nil(io.open(path .. ".part", "rb")) + +source:prefetchChaptersAsync(identity, { chapter }, 0, 1, done) +Assert.is_true(captured_ops.reuse(path)) +Assert.eq(Fs.read(path), fixed, "阅读预取也升级旧缓存") +writeOld() +source:cacheAllChaptersAsync(identity, nil, done) +Assert.is_true(captured_reuse(path)) +Assert.eq(Fs.read(path), fixed, "全本缓存不能把旧字码当作已处理") +os.remove(path) diff --git a/tests/ireader/progress_spec.lua b/tests/ireader/progress_spec.lua new file mode 100644 index 0000000..169dbbb --- /dev/null +++ b/tests/ireader/progress_spec.lua @@ -0,0 +1,88 @@ +--[[-- +掌阅章节进度、离线旧目录、写入失败与同步回调取消。 + +@module tests.moonsource_ireader.progress_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local requests, connected, read_async, toc_async = {}, false, false, false +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +local toc = { { uid = "1", title = "甲", toc_version = 0 }, { uid = "2", title = "乙" } } +package.loaded["source.toc"] = { + read = function() return toc end, + index = function(_sid, _bid, uid) return uid == "2" and 2 or nil end, +} +package.loaded["moonsource_ireader.client"] = { + session = function() return { usr = "test", zysid = "test" } end, + progressAsync = function(_id, cb) + if read_async then + local item = { cb = cb } + requests[#requests + 1] = item + return { cancel = function() item.cancelled = true end } + end + cb({ readProcess = { chapterId = "1", readPercent = "0.2" } }) + return { cancel = function() end } + end, + putProgressAsync = function(_id, uid, total, cb) + local item = { uid = uid, total = total, cb = cb } + requests[#requests + 1] = item + return { cancel = function() item.cancelled = true end } + end, +} +local source = require("moonsource_ireader.source").new() +local result, reason, calls = nil, nil, 0 +local function done(value, err) result, reason, calls = value, err, calls + 1 end +local identity = { source_id = "ext.ireader", stable_id = "test", chapter_idx = 2 } +source:loadTocAsync(identity, done) +require("support.stubs").flush() +Assert.eq(result, toc, "离线不强制刷新旧目录") +function source:loadTocAsync(_identity, cb) + if toc_async then + local item = { cb = cb } + requests[#requests + 1] = item + return { cancel = function() item.cancelled = true end } + end + cb(toc) + return { cancel = function() end } +end +source:getProgressAsync(identity, done) +Assert.eq(result.chapter_idx, 2) +Assert.eq(result.fraction, .5, "章式正文不使用只属于 TXT/PDF 的 readPercent") +local handle = source:putProgressAsync(identity, {}, done) +local pending = requests[#requests] +local before = calls +handle:cancel() +Assert.is_true(pending.cancelled) +pending.cb(true) +Assert.eq(calls, before) +source:putProgressAsync(identity, {}, done) +requests[#requests].cb(nil, "network failed") +Assert.is_nil(result) +Assert.eq(reason, "network failed") +Assert.eq(requests[#requests].uid, "2") +Assert.eq(requests[#requests].total, 2) + +read_async = true +handle = source:getProgressAsync(identity, done) +pending = requests[#requests] +before = calls +handle:cancel() +Assert.is_true(pending.cancelled, "取消初始异步进度查询") +pending.cb({ readProcess = { chapterId = "1" } }) +Assert.eq(calls, before) + +read_async, toc_async = false, true +handle = source:getProgressAsync(identity, done) +pending = requests[#requests] +handle:cancel() +Assert.is_true(pending.cancelled, "同步进度查询后取消异步目录") +pending.cb(toc) +Assert.eq(calls, before) + +handle = source:putProgressAsync(identity, {}, done) +pending = requests[#requests] +handle:cancel() +Assert.is_true(pending.cancelled, "取消上传前的异步目录") +pending.cb(toc) +Assert.eq(calls, before) diff --git a/tests/ireader/qrlogin_spec.lua b/tests/ireader/qrlogin_spec.lua new file mode 100644 index 0000000..57049d2 --- /dev/null +++ b/tests/ireader/qrlogin_spec.lua @@ -0,0 +1,86 @@ +--[[-- +掌阅扫码校验、刷新、失败、取消和同步回调的句柄所有权。 + +@module tests.moonsource_ireader.qrlogin_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Themed = require("support.theme_stubs") +local Stubs = require("support.stubs") +Themed.install() +local connected, mode, requests, logged = true, "delayed", {}, 0 +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +local function request(kind, cb) + local item = { kind = kind, cb = cb } + requests[#requests + 1] = item + if kind == "create" and mode == "sync" then cb("test-code") end + return { cancel = function() item.cancelled = true end } +end +package.loaded["moonsource_ireader.client"] = { + qrCreateAsync = function(cb) return request("create", cb) end, + qrPollAsync = function(_code, cb) return request("poll", cb) end, + checkSessionAsync = function(_user, cb) return request("check", cb) end, +} +local QR = require("moonsource_ireader.qrlogin") +local window = QR:new(function() logged = logged + 1 end) +local login = { code = 0, body = { name = "test-user", session_id = "test-session" } } +mode = "sync" +window:start() +local poll = requests[#requests] +Assert.eq(poll.kind, "poll") +window:cancel() +Assert.is_true(poll.cancelled) +poll.cb(login) +Assert.eq(logged, 0) + +window:start() +requests[#requests].cb({ code = 30059 }) +Stubs.flush() +Assert.eq(requests[#requests].kind, "poll") +requests[#requests].cb(login) +local checking = requests[#requests] +Assert.eq(checking.kind, "check") +Assert.eq(logged, 0, "校验成功前不保存新账号") +local dialog = Themed.last("qr") +checking.cb(true) +Assert.eq(logged, 1) +Assert.is_true(dialog.closed) +Assert.is_nil(Themed.last("toast"), "成功关闭二维码不能误报已取消") + +window:start() +dialog = Themed.last("qr") +dialog.actions[1].callback() +Assert.is_true(dialog.closed) +local old_poll = poll +old_poll.cb(login) +Assert.eq(logged, 1) +requests[#requests].cb(nil, "network failed") +Assert.eq(Themed.last("confirm").text, "network failed") +window:start() +requests[#requests].cb(login) +checking = requests[#requests] +dialog = Themed.last("qr") +dialog:close() +Assert.is_true(checking.cancelled) +checking.cb(true) +Assert.eq(logged, 1) + +window:start() +window.deadline = os.time() - 1 +requests[#requests].cb({ code = 30059 }) +Stubs.flush() +Assert.eq(Themed.last("confirm").text, "二维码已过期") +connected = false +local count = #requests +window:start() +Assert.eq(#requests, count) +Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi") + +connected, mode = true, "delayed" +window:start() +local creating = requests[#requests] +window:cancel() +creating.cb("late-code") +Assert.is_nil(window.dialog) +Assert.eq(logged, 1) diff --git a/tests/ireader/reviews_spec.lua b/tests/ireader/reviews_spec.lua new file mode 100644 index 0000000..b0b4309 --- /dev/null +++ b/tests/ireader/reviews_spec.lua @@ -0,0 +1,73 @@ +--[[-- +掌阅公开整书书评:只取首屏 HTML、异常与取消;不读取电脑账号。 + +@module tests.moonsource_ireader.reviews_spec +--]] + +local Assert = require("support.assert") +local Mapper = require("moonsource_ireader.mapper") +local card = [[
  • 读者 & 甲 +
    +

    好书
    值得<b>再读</b>。

    +昨天
  • ]] +local first = '
      ' .. card .. '
    ' +local parsed = Mapper.reviews("" .. first) +Assert.len(parsed.items, 1) +Assert.eq(parsed.items[1].author, "读者 & 甲") +Assert.eq(parsed.items[1].text, "好书\n值得 再读 。") +Assert.eq(parsed.items[1].time, "昨天") +Assert.eq(parsed.items[1].grade, 8) +Assert.len(Mapper.reviews('
      ').items, 0) +Assert.is_nil(Mapper.reviews("captcha")) +Assert.len(Mapper.reviews('
        ' .. card .. '
      ').items, 1, + "不依赖未使用的分页元数据") +Assert.is_nil(Mapper.reviews('
      • 坏卡片
      ')) +Assert.is_nil(Mapper.reviews('
        ' .. card .. '
      • 坏卡片
      '), + "不返回部分成功列表") +Assert.is_nil(Mapper.reviews('
        bad response
      ')) + +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_ireader.client") +Client.session = function() error("公开书评不能读取电脑账号") end +local source = require("moonsource_ireader.source").new() +---@type IReaderReviewPage|nil +local result +local reason, calls = nil, 0 +local identity = { source_id = "ext.ireader", stable_id = "42" } +local function done(page, err) result, reason, calls = page, err, calls + 1 end +source:bookReviewsAsync(identity, done) +local request = requests[#requests] +Assert.eq(request.url, "https://m.zhangyue.com/comment/42") +Assert.eq(request.opts.accept, "text/html") +Assert.is_nil(request.opts.headers.Cookie) +Assert.is_true(request.opts.headers["User-Agent"]:find("Mobile", 1, true) ~= nil) +request.cb(first) +Assert.is_nil(reason) +Assert.eq(result.items[1].author, "读者 & 甲") +Assert.len(requests, 1, "官网还有后续页也只请求一次") +request.cb("captcha") +Assert.is_nil(result) +Assert.eq(reason, "响应无效") +request.cb(nil, "网络不可用,请先连接 Wi-Fi") +Assert.eq(reason, "网络不可用,请先连接 Wi-Fi") +request.cb(first, "网络失败") +Assert.is_nil(result) +Assert.eq(reason, "网络失败") + +local handle = source:bookReviewsAsync(identity, done) +request = requests[#requests] +local before = calls +handle.cancel() +Assert.is_true(request.cancelled) +request.cb(first) +Assert.eq(calls, before) +for _idx, name in ipairs({ "paragraphHotspotsAsync", "chapterReviewHotspotsAsync" }) do + Assert.is_nil(source[name], "整书书评不伪装为章评或段评") +end diff --git a/tests/ireader/setting_spec.lua b/tests/ireader/setting_spec.lua new file mode 100644 index 0000000..0e65fbb --- /dev/null +++ b/tests/ireader/setting_spec.lua @@ -0,0 +1,96 @@ +--[[-- +掌阅同账号续期与换号保护;浏览器 / Cookie 从 `_zypps` 取 usr/zysid。 + +@module tests.moonsource_ireader.setting_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local beginLogin = require("source.auth").beginLogin +local Themed = require("support.theme_stubs") +Themed.install() +package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end } + +local cfg, saved, reloaded, callback = { usr = "old", zysid = "original" }, 0, 0, nil +local cleared = 0 +package.loaded["source.logout"] = { row = require("source.logout").row, clear = function(_id, clear) + clear(); cleared = cleared + 1; return true +end } +local checks = {} +package.loaded["utils.settings"] = { + getSource = function() return cfg end, + saveSource = function() saved = saved + 1 end, +} +package.loaded["source.registry"] = { reload = function() reloaded = reloaded + 1 end } +package.loaded["source.auth"] = { + beginLogin = beginLogin, + ok = function() end, + expired = function() return false end, +} +package.loaded["ui/network/manager"] = { + runWhenConnected = function(_network, cb) cb() end, + isConnected = function() return true end, +} +package.loaded["moonsource_ireader.qrlogin"] = { + new = function(_class, cb) + callback = cb + return { start = function() end } + end, +} +package.loaded["moonsource_ireader.client"] = { + session = function() + if cfg.usr and cfg.zysid then return { usr = cfg.usr, zysid = cfg.zysid } end + end, + checkSessionAsync = function(user, cb) + checks[#checks + 1] = user + cb(true) + return { cancel = function() end } + end, +} + +package.loaded["moonsource_ireader.setting"] = nil +package.loaded["source.cookie_login"] = nil +local Setting = require("moonsource_ireader.setting") + +Setting.open() +callback({ usr = "other", zysid = "candidate" }) +Assert.eq(cfg.usr, "other") +Assert.eq(cfg.zysid, "candidate") +Assert.eq(cleared, 1) +Assert.is_nil(Themed.last("confirm")) +callback({ usr = "other", zysid = "renewed" }) +Assert.eq(cfg.zysid, "renewed") +Assert.eq(saved, 3) +Assert.eq(reloaded, 2) +Assert.eq(cleared, 1, "同账号续期不清本地") +Assert.eq(Themed.last("toast").text, "登录成功") + +Assert.is_true(type(Setting.browser) == "table") +Assert.eq(Setting.browser.domain, "pc.ireader.com") +Assert.is_true(type(Setting.browser.icon) == "string" and Setting.browser.icon:match("^https://")) + +local user = Setting.userFromCookie("_zypps=usr%3Dold%26zysid%3Dfromcookie%26name%3D%E6%B5%8B") +Assert.eq(user.usr, "old") +Assert.eq(user.zysid, "fromcookie") + +cfg = { usr = "old", zysid = "original" } +saved, reloaded = 0, 0 +local rows = Setting.rows() +Assert.eq(rows[2](400).title, "浏览器登录") +Assert.eq(rows[3](400).title, "粘贴 Cookie") +rows[3](400).callback() +local input = Themed.last("input") +Assert.eq(input.title, "掌阅登录 Cookie") +input.callback("Cookie: _zypps=usr%3Dold%26zysid%3Dpasted%26name%3Dx") +Assert.eq(checks[1].usr, "old") +Assert.eq(checks[1].zysid, "pasted") +Assert.eq(cfg.zysid, "pasted") +Assert.eq(saved, 1) + +cfg = {} +Setting.browser.apply({ cookies = { + { domain = ".zhangyue.com", name = "_zypps", value = "usr=new&zysid=browser" }, + { domain = "evil.com", name = "_zypps", value = "usr=x&zysid=y" }, +} }, function(ok) Assert.is_true(ok) end) +Assert.eq(cfg.usr, "new") +Assert.eq(cfg.zysid, "browser")