commit 7a09f7c834cbc3230401b8287990aa3f94973b94 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-zymk.koplugin/README.md b/moonsource-zymk.koplugin/README.md new file mode 100644 index 0000000..d4b1b83 --- /dev/null +++ b/moonsource-zymk.koplugin/README.md @@ -0,0 +1,21 @@ +# 知音漫客 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 密码与短信登录 | 支持 | 保存前兑换/校验账号;短信触发点字验证时由用户完成 | +| 手动 Cookie 导入 | 支持 | 只保存校验后的必要会话字段 | +| 微信、App 扫码与浏览器扩展登录 | 不支持 | 未提供对应入口 | +| 远端书架拉取 | 支持 | 登录后读取完整收藏并对账 | +| 远端收藏新增与移出 | 不支持 | 未接入上行;本地删除留墓碑,不删除官网收藏 | +| 搜索 | 支持 | 聚合后续页,最多约 200 本 | +| 分类书城 | 支持 | 完整分类库、动态标签及多种排序;不提供未经验证的资费筛选 | +| 详情与目录 | 支持 | 知音漫客作品跳转官方看漫画,保持章节顺序和身份 | +| 免费漫画阅读 | 支持 | 下载页图为 CBZ,由 KOReader 阅读 | +| 已购与 VIP 漫画 | 不支持 | 未实现账号阅读权限;标价章节提示未购买 | +| 章节与全本缓存 | 支持 | 支持预取、范围和后台缓存,失败不生成成功 CBZ | +| 离线阅读 | 支持 | 已缓存目录、CBZ 和本地位置可用 | +| 进度、笔记与统计同步 | 不支持 | 仅本地保存;远端进度写入不能回读确认 | +| 整书书评 | 部分支持 | 详情仅最新第一页;传输可续页,界面没有后续页入口 | +| 每话章评与段评 | 不支持 | 当前 Web 协议未找到可验证接口 | +| 评论回复与写操作 | 不支持 | 未接入 | +| 账号切换 | 部分支持 | 身份不同须先退出清理旧本地数据,未同步记录会丢失 | diff --git a/moonsource-zymk.koplugin/_meta.lua b/moonsource-zymk.koplugin/_meta.lua new file mode 100644 index 0000000..d9d079a --- /dev/null +++ b/moonsource-zymk.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:知音漫客"), + description = _("给月读增加「知音漫客」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-zymk.koplugin/main.lua b/moonsource-zymk.koplugin/main.lua new file mode 100644 index 0000000..583dcb4 --- /dev/null +++ b/moonsource-zymk.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_zymk", + is_doc_only = false, +} diff --git a/moonsource-zymk.koplugin/moon_source.lua b/moonsource-zymk.koplugin/moon_source.lua new file mode 100644 index 0000000..06af1ca --- /dev/null +++ b/moonsource-zymk.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_zymk.source").meta() end, + new = function() return require("moonsource_zymk.source").new() end, + setting = lazy("moonsource_zymk.setting"), +} diff --git a/moonsource-zymk.koplugin/moonsource_zymk/_meta.lua b/moonsource-zymk.koplugin/moonsource_zymk/_meta.lua new file mode 100644 index 0000000..462963c --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/_meta.lua @@ -0,0 +1,16 @@ +--[[-- +书源元信息。 + +@module moonsource_zymk._meta +--]] + +local _ = require("l10n").get("moonsource_zymk") + +return { + id = "ext.zymk", + name = _("知音漫客"), + type = "chapter", + description = _("知音漫客在线阅读"), + abilities = { _("短信验证码登录"), _("密码登录"), _("Cookie 登录"), _("书架同步"), + _("搜索与发现"), _("章节缓存"), _("书评") }, +} diff --git a/moonsource-zymk.koplugin/moonsource_zymk/browse.lua b/moonsource-zymk.koplugin/moonsource_zymk/browse.lua new file mode 100644 index 0000000..a8e724f --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/browse.lua @@ -0,0 +1,118 @@ +--[[-- +知音漫客分类库:官网动态标签与完整 allComic 数据,过滤后按官网字段降序。 + +@module moonsource_zymk.browse +--]] + +local Client = require("moonsource_zymk.client") +local Mapper = require("moonsource_zymk.mapper") +local Browse = require("source.browse") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_zymk") + +local Library = {} +local SORTS = { + { key = "update_time", title = _("新更") }, + { key = "total_click", title = _("人气") }, + { key = "dashang", title = _("打赏") }, + { key = "pingfen", title = _("评分") }, + { key = "zongpiao", title = _("月票") }, +} +local LABELS = { + ["题材"] = _("题材"), ["受众"] = _("受众"), ["媒体"] = _("媒体"), + ["热血"] = _("热血"), ["搞笑"] = _("搞笑"), ["生活"] = _("生活"), ["恋爱"] = _("恋爱"), + ["动作"] = _("动作"), ["战争"] = _("战争"), ["穿越"] = _("穿越"), ["后宫"] = _("后宫"), + ["萝莉"] = _("萝莉"), ["漫改"] = _("漫改"), ["修真"] = _("修真"), ["霸总"] = _("霸总"), + ["古风"] = _("古风"), ["真人"] = _("真人"), ["完结"] = _("完结"), ["少男"] = _("少男"), + ["少女"] = _("少女"), ["青年"] = _("青年"), ["神漫"] = _("神漫"), ["飒漫画"] = _("飒漫画"), + ["漫客栈"] = _("漫客栈"), ["飒漫乐画"] = _("飒漫乐画"), +} + +local function node(params) + return "library?" .. Text.formEncode(params) +end + +local function change(params, key, value) + local out = {} + for name, current in pairs(params) do out[name] = current end + out[key] = value ~= "" and value or nil + return node(out) +end + +---@param opts { node?: string, limit?: integer } +---@param cb fun(result: table|nil, err: string|nil) +---@return { cancel: fun() } +function Library.run(opts, cb) + return Client.libraryAsync(function(data, err) + if not data then cb(nil, err); return end + local params = { sort = "update_time" } + local keys, tags = { sort = true }, {} + for index, filter in ipairs(data.filters) do + local key = "tag" .. index + keys[key], tags[key] = true, {} + for _idx, item in ipairs(filter.items) do tags[key][item.id] = true end + end + if opts.node then + if not opts.node:match("^library%?") then cb(nil, _("响应无效")); return end + for key, value in opts.node:sub(9):gmatch("([^&=]+)=([^&]*)") do + if not keys[key] then cb(nil, _("响应无效")); return end + params[key] = Text.urlDecode(value) + end + end + local sort_valid = false + for _idx, sort in ipairs(SORTS) do + if params.sort == sort.key then sort_valid = true end + end + if not sort_valid then cb(nil, _("响应无效")); return end + for key, allowed in pairs(tags) do + if params[key] and not allowed[params[key]] then cb(nil, _("响应无效")); return end + end + local rows = {} + for _idx, row in ipairs(data.rows) do + if type(row) ~= "table" or type(row.class_idlist) ~= "string" + or type(row.update_time) ~= "string" or not row.comic_id + or type(row.comic_name) ~= "string" or row.comic_name == "" then + cb(nil, _("响应无效")); return + end + local matches = true + for key in pairs(tags) do + if params[key] and not row.class_idlist:find("," .. params[key] .. ",", 1, true) then + matches = false + end + end + if matches then rows[#rows + 1] = row end + end + table.sort(rows, function(left, right) + local a, b + if params.sort == "update_time" then + a, b = left.update_time, right.update_time + else + a, b = tonumber(left[params.sort]) or 0, tonumber(right[params.sort]) or 0 + end + if a == b then return (tonumber(left.total_click) or 0) > (tonumber(right.total_click) or 0) end + return a > b + end) + local current, groups, sort_chips = node(params), {}, {} + for _idx, sort in ipairs(SORTS) do + sort_chips[#sort_chips + 1] = { id = change(params, "sort", sort.key), title = sort.title } + end + groups[1] = Browse.group(sort_chips, current) + groups[1].title = _("排序") + for index, filter in ipairs(data.filters) do + local key = "tag" .. index + local chips = { { id = change(params, key, ""), title = _("全部") } } + for _idx, item in ipairs(filter.items) do + chips[#chips + 1] = { id = change(params, key, item.id), title = LABELS[item.title] or _(item.title) } + end + local group = Browse.group(chips, current) + group.title = LABELS[filter.title] or _(filter.title) + groups[#groups + 1] = group + end + local result = Mapper.list({ status = 0, data = { page = { comic_list = rows } } }) + if not result then cb(nil, _("响应无效")); return end + while #result > (opts.limit or 60) do result[#result] = nil end + cb({ data = result, groups = groups }) + end) +end + +return Library diff --git a/moonsource-zymk.koplugin/moonsource_zymk/chapter.lua b/moonsource-zymk.koplugin/moonsource_zymk/chapter.lua new file mode 100644 index 0000000..4fef3cd --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/chapter.lua @@ -0,0 +1,183 @@ +--[[-- +知音漫客章节图片下载与 CBZ 打包。 + +页图地址不带后缀。接口要求 JPEG,落盘后再按文件头改后缀。 + +@module moonsource_zymk.chapter +--]] + +local Cbz = require("source.cbz") +local Client = require("moonsource_zymk.client") +local Image = require("utils.image") +local Paths = require("utils.paths") +local _ = require("l10n").get("moonsource_zymk") + +local Chapter = {} + +---@param identity BookIdentity +---@param chapter BookChapter +---@return string +function Chapter.archivePath(identity, chapter) + return Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/" .. chapter.uid:gsub("/", "_") .. ".cbz" +end + +---@param identity BookIdentity +---@param chapter BookChapter +---@return string|nil +function Chapter.existing(identity, chapter) + local path = Chapter.archivePath(identity, chapter) + return Cbz.ready(path) and path or nil +end + +---@param path string +---@return string +local function withRealSuffix(path) + local ext = Image.file(path) + if not ext or path:sub(-#ext) == ext then return path end + local renamed = path:gsub("%.%w+$", "") .. ext + if renamed ~= path and os.rename(path, renamed) then return renamed end + return path +end + +---@param identity BookIdentity +---@param chapter BookChapter +---@param on_progress fun(done: integer, total: integer)|nil +---@param cb fun(path: string|nil, err: string|nil) +---@return { cancel: fun() } +function Chapter.materializeAsync(identity, chapter, on_progress, cb) + Paths.ensureBookWork(identity.stable_id, identity.source_id) + local archive_path = Chapter.archivePath(identity, chapter) + ---@type { cancelled: boolean, active: CancelHandle|nil, writer: ArchiverWriter|nil } + local state = { cancelled = false, active = nil, writer = nil } + if Cbz.ready(archive_path) then + require("ui/uimanager"):nextTick(require("ui.guard").wrap("zymk callback", function() + if not state.cancelled then cb(archive_path) end + end)) + return { cancel = function() state.cancelled = true end } + end + if chapter.vip then + require("ui/uimanager"):nextTick(require("ui.guard").wrap("zymk callback", function() + if not state.cancelled then cb(nil, _("本章未购买")) end + end)) + return { cancel = function() state.cancelled = true end } + end + + local fetched = false + local image_job = Client.imagesAsync(chapter.uid, function(urls, err) + fetched = true + state.active = nil + if state.cancelled then return end + if not urls then cb(nil, err); return end + local image_dir = archive_path:gsub("%.cbz$", "") + Paths.ensureDir(image_dir) + local paths, current = {}, 1 + for index, url in ipairs(urls) do + paths[index] = image_dir .. "/" .. string.format("%04d%s", index, Image.suffix(url) or ".jpg") + end + + local function nextImage() + if state.cancelled then return end + local url = urls[current] + if not url then + Cbz.build(paths, archive_path, state, cb) + return + end + local path = paths[current] + if Image.ok(path) then + paths[current] = withRealSuffix(path) + if on_progress then on_progress(current, #urls) end + current = current + 1 + require("ui/uimanager"):nextTick(require("ui.guard").wrap("zymk image", nextImage)) + return + end + local downloaded = false + local handle = require("http.request").download({ + url = url, + timeout = require("http.timeout").net(3), + max_bytes = 32 * 1024 * 1024, + }, path, function(ok, download_err) + downloaded = true + state.active = nil + if state.cancelled then return end + if not ok or not Image.ok(path) then + os.remove(path) + cb(nil, download_err and tostring(download_err) or _("章节图片解析失败")) + return + end + paths[current] = withRealSuffix(path) + if on_progress then on_progress(current, #urls) end + current = current + 1 + require("ui/uimanager"):nextTick(require("ui.guard").wrap("zymk image", nextImage)) + end) + if not downloaded then state.active = handle end + end + nextImage() + end) + if not fetched then state.active = image_job end + + return { cancel = function() + if state.cancelled then return end + state.cancelled = true + if state.active then state.active.cancel() end + if state.writer then state.writer:close() end + os.remove(archive_path .. ".part") + end } +end + +---@param identity BookIdentity +---@param toc BookChapter[] +---@param from_idx integer +---@param count integer +---@param ops { progress: fun(done: integer, total: integer)|nil, interval_seconds: number|nil }|nil +---@param cb fun(cached: integer, total: integer, failed: integer, err: any)|nil +---@return { cancel: fun() } +function Chapter.prefetchAsync(identity, toc, from_idx, count, ops, cb) + ops = ops or {} + local cancelled, active = false, nil + local cached_count, failed_count, last_error = 0, 0, nil + local chapters = {} + for idx = from_idx + 1, math.min(#toc, from_idx + count) do + chapters[#chapters + 1] = toc[idx] + end + local pos = 1 + local interval = ops.interval_seconds or 0 + local UIManager = require("ui/uimanager") + local function step() + if cancelled then return end + local chapter = chapters[pos] + local chapter_idx = from_idx + pos + pos = pos + 1 + if not chapter then + if cb then cb(cached_count, #chapters, failed_count, last_error) end + return + end + active = Chapter.materializeAsync(identity, chapter, nil, function(path, err) + active = nil + if cancelled then return end + if path and not require("book.chapters_db").upsert({ + path = path, source_id = identity.source_id, + stable_id = identity.stable_id, chapter_idx = chapter_idx, + }) then + path, err = nil, _("书籍信息保存失败") + end + if path then cached_count = cached_count + 1 + else + failed_count = failed_count + 1 + last_error = err or last_error + end + if ops.progress then ops.progress(cached_count + failed_count, #chapters) end + if interval > 0 then + UIManager:scheduleIn(interval, require("ui.guard").wrap("zymk step", step)) + else + UIManager:nextTick(require("ui.guard").wrap("zymk step", step)) + end + end) + end + UIManager:nextTick(require("ui.guard").wrap("zymk step", step)) + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +return Chapter diff --git a/moonsource-zymk.koplugin/moonsource_zymk/client.lua b/moonsource-zymk.koplugin/moonsource_zymk/client.lua new file mode 100644 index 0000000..fb53b03 --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/client.lua @@ -0,0 +1,257 @@ +--[[-- +知音漫客网页接口。 + +搜索是本站 `/apinew/getsortlist/`,分类库来自 `/apinew/allComic/`。 +漫画页的章节链接 301 到看漫画,目录和页图都在那边;整书评论来自官方公共评论服务。 +公开阅读不附带账号凭证;账号请求只向知音漫客自己的接口提交。 + +@module moonsource_zymk.client +--]] + +local JSON = require("json") +local Mapper = require("moonsource_zymk.mapper") +local Page = require("moonsource_zymk.page") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_zymk") +local Browse = require("source.browse") +local SourceBase = require("source.base") + +local Client = {} + +local HOST = "https://www.zymk.cn" +local READER = "https://www.kanman.com" +Client.LOGIN_URL = HOST .. "/login.htm" + +---@param path string +---@param fields table +---@param cb fun(data: table|nil, err: string|nil) +---@return HttpJob +function Client.authAsync(path, fields, cb) + return Request.post(HOST .. path, Text.formEncode(fields), { + timeout = require("http.timeout").net(1), + content_type = "application/x-www-form-urlencoded; charset=UTF-8", + headers = { + Origin = HOST, + Referer = Client.LOGIN_URL, + ["X-Requested-With"] = "XMLHttpRequest", + }, + allow_redirects = false, + }, function(raw, err) + if err or not raw then cb(nil, err and tostring(err) or _("请求失败")); return end + local decoded, wire = pcall(JSON.decode, raw) + if not decoded or type(wire) ~= "table" or tonumber(wire.status) == nil then + cb(nil, _("登录响应无效")) + elseif path == "/apinew/sendsms/" and tonumber(wire.status) == 0 then + cb({ sent = true }) + elseif path == "/apinew/sendsms/" and (tonumber(wire.status) == 1031 or tonumber(wire.status) == 1028) then + local captcha = Mapper.captcha(wire.data) + cb(captcha, not captcha and _("图形验证码加载失败") or nil) + elseif tonumber(wire.status) ~= 0 then + cb(nil, type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("登录失败")) + elseif type(wire.data) ~= "table" then + cb(nil, _("登录响应无效")) + else + cb(wire.data) + end + end) +end + +---@param account ZymkAccount|nil +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client.shelfAsync(account, cb) + local Settings = require("utils.settings") + if not Mapper.account(account) or require("source.auth").expired("ext.zymk") then + return SourceBase.defer(cb, nil, _("请先登录知音漫客")) + end + if Settings.getSource("ext.zymk").account ~= account then + return SourceBase.defer(cb, nil, _("登录状态已变化,请重试")) + end + if not require("ui/network/manager"):isConnected() then + return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi")) + end + local fields = { type = account.type, openid = account.openid } + local cancelled = false + local job = Client.authAsync("/apinew/getuserrecord/", fields, function(data, err) + if cancelled then return end + if Settings.getSource("ext.zymk").account ~= account then + cb(nil, _("登录状态已变化,请重试")); return + end + local books = data and Mapper.shelf(data) + cb(books, err or (not books and _("响应无效") or nil)) + end) + return { cancel = function() + cancelled = true + job.cancel() + end } +end + +---@param url string +---@param cb fun(body: string|nil, err: any, res: table|nil) +---@return HttpJob +local function get(url, cb) + return Request.get(url, { timeout = require("http.timeout").net(1) }, cb) +end + +---@param res table|nil +---@return string|nil +local function comicId(res) + local code = res and tonumber(res.code) + if code ~= 301 and code ~= 302 and code ~= 303 and code ~= 307 and code ~= 308 then return nil end + local location = Request.header(res, "location") + if type(location) ~= "string" then return nil end + return location:match("^https?://www%.kanman%.com/(%d+)/") +end + +---@param keyword string +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return HttpJob +function Client.searchAsync(keyword, cb) + return Browse.pages(function(page, done) + local url = HOST .. "/apinew/getsortlist/?key=" .. Text.urlEncode(keyword) .. "&page=" .. page + return get(url, function(raw, err) + if not raw or raw == "" then done(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then done(nil, _("响应无效")); return end + local books = Mapper.list(wire) + if not books then done(nil, _("响应无效")); return end + local total_page = tonumber(wire.data.page.total_page) + done(books, nil, not total_page or page < total_page) + end) + end, 200, {}, function(result, err) + cb(result and result.data or nil, err) + end) +end + +---@param cb fun(data: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client.libraryAsync(cb) + local cancelled, active, pending = false, nil, true + local job = get(HOST .. "/sort/all.html", function(html, err) + pending = false + if cancelled then return end + active = nil + local filters = html and Page.filters(html) + if not filters then cb(nil, err and tostring(err) or _("响应无效")); return end + local loading = true + local inner = get(HOST .. "/apinew/allComic/", function(raw, list_err) + loading = false + if cancelled then return end + active = nil + if not raw then cb(nil, list_err and tostring(list_err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok or type(wire) ~= "table" or tonumber(wire.status) ~= 0 + or type(wire.data) ~= "table" then cb(nil, _("响应无效")); return end + cb({ filters = filters, rows = wire.data }) + end) + if loading then active = inner end + end) + if pending then active = job end + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +--- 整本漫画评论,ssidType=0;不是章评或段评。该服务成功码为 1。 +---@param stable_id string +---@param page integer +---@param cb fun(page: table|nil, err: string|nil) +---@return HttpJob +function Client.reviewsAsync(stable_id, page, cb) + local cancelled = false + local query = Text.formEncode({ + platformname = "pc", appid = 11, appId = 11, + ssid = stable_id, ssidtype = 0, ssidType = 0, + page = page, pagesize = 20, filter = 1, contenttype = 0, relateid = 0, fatherid = 0, + }) + local job = get("https://community-hots.321mh.com/comment/newgets?" .. query, function(raw, err) + if cancelled then return end + if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then cb(nil, _("响应无效")); return end + local result = Mapper.reviews(stable_id, page, wire) + if not result then cb(nil, _("响应无效")); return end + cb(result) + end) + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 详情页 → 一话跳转 → 看漫画目录。 +---@param stable_id string +---@param cb fun(page: { book: Book, chapters: BookChapter[] }|nil, err: string|nil) +---@return { cancel: fun() } +function Client.catalogAsync(stable_id, cb) + local state = { cancelled = false, job = nil } + local id = Text.urlEncode(tostring(stable_id)) + local pending = true + local job = get(HOST .. "/" .. id .. "/", function(raw, err) + pending = false + if state.cancelled then return end + state.job = nil + local page = raw and Page.detail(raw) or nil + if not page then cb(nil, err and tostring(err) or _("漫画目录为空")); return end + local probing = true + local probe = get(HOST .. "/" .. id .. "/" .. page.chapter_file .. ".html", function(_body, probe_err, res) + probing = false + if state.cancelled then return end + state.job = nil + local comic_id = comicId(res) + if not comic_id then cb(nil, probe_err and tostring(probe_err) or _("漫画目录为空")); return end + local listing = true + local list_job = get(READER .. "/api/getchapterlist?comic_id=" .. comic_id, function(list_raw, list_err) + listing = false + if state.cancelled then return end + state.job = nil + if not list_raw or list_raw == "" then cb(nil, list_err and tostring(list_err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, list_raw) + local chapters = ok and type(wire) == "table" and tonumber(wire.status) == 0 + and Mapper.chapters(comic_id, wire.data) or nil + local book = Mapper.detail(page, stable_id) + if not chapters or not book then cb(nil, _("响应无效")); return end + cb({ book = book, chapters = chapters }) + end) + if listing then state.job = list_job end + end) + if probing then state.job = probe end + end) + if pending then state.job = job end + return { cancel = function() + state.cancelled = true + if state.job then state.job.cancel() end + end } +end + +--- uid 是 `看漫画id/chapter_newid`。要 JPEG,阅读器不解 webp。 +---@param uid string +---@param cb fun(urls: string[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client.imagesAsync(uid, cb) + local comic_id, newid = tostring(uid):match("^(%d+)/(.+)$") + if not comic_id or not newid then + return SourceBase.defer(cb, nil, _("章节图片解析失败")) + end + local url = READER .. "/api/getchapterinfov2?product_id=1&productname=kmh&platformname=pc&comic_id=" + .. comic_id .. "&chapter_newid=" .. Text.urlEncode(newid) .. "&isWebp=0&quality=middle" + local state = { cancelled = false, job = nil } + state.job = get(url, function(raw, err) + if state.cancelled then return end + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then cb(nil, _("请求失败")); return end + local urls, locked = Mapper.images(wire) + if locked == "locked" then cb(nil, _("本章未购买")); return end + if not urls then cb(nil, _("章节图片解析失败")); return end + cb(urls) + end) + return { cancel = function() + state.cancelled = true + if state.job then state.job.cancel() end + end } +end + +return Client diff --git a/moonsource-zymk.koplugin/moonsource_zymk/l10n/en.lua b/moonsource-zymk.koplugin/moonsource_zymk/l10n/en.lua new file mode 100644 index 0000000..6268244 --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/l10n/en.lua @@ -0,0 +1,70 @@ +return { + ["请先登录知音漫客"] = "Sign in to Zhiyinmanke first.", + ["章节缓存"] = "Chapter caching", + ["新更"] = "Recently updated", + ["打赏"] = "Tips", + ["题材"] = "Genre", + ["受众"] = "Audience", + ["媒体"] = "Publisher", + ["热血"] = "Hot-blooded", + ["搞笑"] = "Comedy", + ["恋爱"] = "Romance", + ["生活"] = "Slice of life", + ["动作"] = "Action", + ["战争"] = "War", + ["穿越"] = "Time travel", + ["后宫"] = "Harem", + ["萝莉"] = "Loli", + ["漫改"] = "Comic adaptations", + ["修真"] = "Cultivation", + ["霸总"] = "CEO romance", + ["古风"] = "Historical style", + ["真人"] = "Live action", + ["完结"] = "Completed", + ["少男"] = "Boys", + ["少女"] = "Girls", + ["青年"] = "Young adults", + ["神漫"] = "Shenman", + ["飒漫画"] = "Samanhua", + ["漫客栈"] = "Mankezhan", + ["飒漫乐画"] = "Samanlehua", + ["人气"] = "Popularity", + ["月票"] = "Monthly votes", + ["密码登录"] = "Password sign-in", + ["请稍后再获取验证码"] = "Please wait before requesting another code.", + ["正在获取验证码…"] = "Requesting a verification code…", + ["请先获取该手机号的验证码,再填写验证码登录"] = "Request a code for this phone number, then enter it to sign in.", + ["登录状态已变化,请重试"] = "The login session changed. Please retry.", + ["登录响应无效"] = "Invalid sign-in response", + ["知音漫客"] = "Zhiyinmanke", + ["知音漫客在线阅读"] = "Zhiyinmanke comics", + ["知音漫客登录 Cookie"] = "Zhiyinmanke sign-in Cookie", + ["Cookie 登录"] = "Cookie sign-in", + ["没有读到知音漫客登录 Cookie"] = "No valid Zhiyinmanke sign-in Cookie was found.", + ["在知音漫客官网登录后,复制请求标头里的完整 Cookie"] = "Sign in on the official Zhiyinmanke website, then copy the complete Cookie request header.", + ["通行证账号、手机号码或邮箱"] = "Passport account, phone number, or email", + ["短信验证码登录"] = "SMS verification sign-in", + ["短信已发送"] = "SMS sent", + ["图形验证码"] = "Image verification", + ["已选择 %1/2 个位置"] = "Selected %1/2 positions", + ["按顺序点选图片中的文字:"] = "Tap these characters in the image in order: ", + ["请按顺序选择两个文字位置"] = "Select the two character positions in order.", + ["请输入正确的手机号"] = "Enter a valid phone number.", + ["请重新点选图片中的文字"] = "Select the characters in the image again.", + ["请重新获取图形验证码"] = "Request a new image verification challenge.", + ["请先退出旧知音漫客账号,再登录其他账号"] = "Sign out of the previous Zhiyinmanke account before signing in to another account.", + ["确定退出知音漫客账号?"] = "Sign out of your Zhiyinmanke account?", + ["图形验证码加载失败"] = "Could not load the image code", + ["获取验证码"] = "Get code", + ["本章未购买"] = "This chapter has not been purchased", + ["正在准备漫画…"] = "Preparing comic…", + ["漫画目录为空"] = "Comic chapter list is empty", + ["章节目录保存失败"] = "Failed to save chapter list", + ["章节图片解析失败"] = "Failed to parse chapter images", + ["请输入账号和密码"] = "Enter account and password", + ["重新选择"] = "Pick again", + ["手机号"] = "Phone number", + ["书架同步"] = "Shelf sync", + ["搜索与发现"] = "Search and discover", + ["刷新"] = "Refresh", +} diff --git a/moonsource-zymk.koplugin/moonsource_zymk/l10n/zh_TW.lua b/moonsource-zymk.koplugin/moonsource_zymk/l10n/zh_TW.lua new file mode 100644 index 0000000..9c779d8 --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/l10n/zh_TW.lua @@ -0,0 +1,70 @@ +return { + ["请先登录知音漫客"] = "請先登入知音漫客", + ["章节缓存"] = "章節快取", + ["新更"] = "最新更新", + ["打赏"] = "打賞", + ["题材"] = "題材", + ["受众"] = "受眾", + ["媒体"] = "媒體", + ["热血"] = "熱血", + ["搞笑"] = "搞笑", + ["恋爱"] = "戀愛", + ["生活"] = "生活", + ["动作"] = "動作", + ["战争"] = "戰爭", + ["穿越"] = "穿越", + ["后宫"] = "後宮", + ["萝莉"] = "蘿莉", + ["漫改"] = "漫改", + ["修真"] = "修真", + ["霸总"] = "霸總", + ["古风"] = "古風", + ["真人"] = "真人", + ["完结"] = "完結", + ["少男"] = "少男", + ["少女"] = "少女", + ["青年"] = "青年", + ["神漫"] = "神漫", + ["飒漫画"] = "颯漫畫", + ["漫客栈"] = "漫客棧", + ["飒漫乐画"] = "颯漫樂畫", + ["人气"] = "人氣", + ["月票"] = "月票", + ["密码登录"] = "密碼登入", + ["请稍后再获取验证码"] = "請稍後再取得驗證碼", + ["正在获取验证码…"] = "正在取得驗證碼…", + ["请先获取该手机号的验证码,再填写验证码登录"] = "請先取得該手機號碼的驗證碼,再填寫驗證碼登入", + ["登录状态已变化,请重试"] = "登入狀態已改變,請重試", + ["登录响应无效"] = "登入回應無效", + ["知音漫客"] = "知音漫客", + ["知音漫客在线阅读"] = "知音漫客線上閱讀", + ["知音漫客登录 Cookie"] = "知音漫客登入 Cookie", + ["Cookie 登录"] = "Cookie 登入", + ["没有读到知音漫客登录 Cookie"] = "未讀到知音漫客登入 Cookie", + ["在知音漫客官网登录后,复制请求标头里的完整 Cookie"] = "在知音漫客官網登入後,複製請求標頭裡的完整 Cookie", + ["通行证账号、手机号码或邮箱"] = "通行證帳號、手機號碼或電子郵件", + ["短信验证码登录"] = "簡訊驗證碼登入", + ["短信已发送"] = "簡訊已發送", + ["图形验证码"] = "圖形驗證碼", + ["已选择 %1/2 个位置"] = "已選擇 %1/2 個位置", + ["按顺序点选图片中的文字:"] = "依序點選圖片中的文字:", + ["请按顺序选择两个文字位置"] = "請依序選擇兩個文字位置", + ["请输入正确的手机号"] = "請輸入正確的手機號碼", + ["请重新点选图片中的文字"] = "請重新點選圖片中的文字", + ["请重新获取图形验证码"] = "請重新取得圖形驗證碼", + ["请先退出旧知音漫客账号,再登录其他账号"] = "請先登出舊知音漫客帳號,再登入其他帳號", + ["确定退出知音漫客账号?"] = "確定登出知音漫客帳號?", + ["图形验证码加载失败"] = "圖形驗證碼載入失敗", + ["获取验证码"] = "取得驗證碼", + ["本章未购买"] = "本章未購買", + ["正在准备漫画…"] = "正在準備漫畫…", + ["漫画目录为空"] = "漫畫目錄為空", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["章节图片解析失败"] = "章節圖片解析失敗", + ["请输入账号和密码"] = "請輸入帳號和密碼", + ["重新选择"] = "重新選擇", + ["手机号"] = "手機號碼", + ["书架同步"] = "書架同步", + ["搜索与发现"] = "搜尋與發現", + ["刷新"] = "重新整理", +} diff --git a/moonsource-zymk.koplugin/moonsource_zymk/loadmeta.lua b/moonsource-zymk.koplugin/moonsource_zymk/loadmeta.lua new file mode 100644 index 0000000..d2e7082 --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_zymk._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-zymk.koplugin/moonsource_zymk/login.lua b/moonsource-zymk.koplugin/moonsource_zymk/login.lua new file mode 100644 index 0000000..04f5a2c --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/login.lua @@ -0,0 +1,154 @@ +--[[-- +知音漫客短信验证码、密码与 Cookie 登录会话。密码不落盘,appToken 只用于兑换; +服务端校验成功才保存 type/openid。公开阅读仍可匿名使用。 + +@module moonsource_zymk.login +--]] + +local Client = require("moonsource_zymk.client") +local Mapper = require("moonsource_zymk.mapper") +local Settings = require("utils.settings") +local JSON = require("json") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_zymk") + +---@class ZymkLogin +---@field previous ZymkAccount|nil +---@field serial integer +---@field job HttpJob|nil +---@field sms_phone string|nil +---@field retry_at number|nil +---@field captcha ZymkCaptcha|nil +local Login = {} +Login.__index = Login + +function Login.new() + return setmetatable({ previous = Settings.getSource("ext.zymk").account, serial = 0 }, Login) +end + +function Login.hasAccount() + return Mapper.account(Settings.getSource("ext.zymk").account) ~= nil + and not require("source.auth").expired("ext.zymk") +end + +function Login:cancel() + self.serial = self.serial + 1 + if self.job then self.job.cancel(); self.job = nil end +end + +---@param path string +---@param fields table +---@param cb fun(data: table|nil, err: string|nil) +function Login:request(path, fields, cb) + self:cancel() + local serial, pending = self.serial, true + local function done(data, err) + pending = false + if self.serial ~= serial then return end + self.job = nil + if Settings.getSource("ext.zymk").account ~= self.previous then + cb(nil, _("登录状态已变化,请重试")); return + end + cb(data, err and tostring(err) or nil) + end + local job = Client.authAsync(path, fields, done) + if pending then self.job = job end +end + +---@param fields table +---@param cb fun(account: ZymkAccount|nil, err: string|nil) +function Login:confirm(fields, cb) + self:request("/apinew/getuserinfo/", fields, function(data, err) + if not data then cb(nil, err); return end + local account = Mapper.account(data) + if not account then cb(nil, _("登录响应无效")); return end + if fields.openid and (account.openid ~= fields.openid or account.type ~= fields.type) then + cb(nil, _("登录响应无效")); return + end + if self.previous and (self.previous.openid ~= account.openid or self.previous.type ~= account.type) then + local cleared = require("source.logout").clear("ext.zymk", function() + Settings.getSource("ext.zymk").account = nil + Settings.saveSource("ext.zymk") + end) + if not cleared then cb(nil, _("准备本地同步失败")); return end + end + Settings.getSource("ext.zymk").account = account + Settings.saveSource("ext.zymk") + require("source.auth").ok("ext.zymk") + require("source.registry").reload() + cb(account) + end) +end + +---@param phone string +---@param points table[]|nil 用户点选的原图坐标 +---@param refresh boolean +---@param cb fun(data: table|nil, err: string|nil) +function Login:sendSmsAsync(phone, points, refresh, cb) + if not phone:match("^1%d%d%d%d%d%d%d%d%d%d$") then cb(nil, _("请输入正确的手机号")); return end + if self.retry_at and os.time() < self.retry_at then cb(nil, _("请稍后再获取验证码")); return end + local img_code = "" + if points then + if not self.captcha or #points ~= 2 then cb(nil, _("请重新获取图形验证码")); return end + for _index, point in ipairs(points) do + if type(point.x) ~= "number" or type(point.y) ~= "number" + or point.x < 0 or point.x >= self.captcha.width + or point.y < 0 or point.y >= self.captcha.height then + cb(nil, _("请重新获取图形验证码")); return + end + end + img_code = JSON.encode({ appId = 11, fontPoints = points, userIdentifier = phone, verificaType = 2 }) + end + self.captcha = nil + self:request("/apinew/sendsms/", { + mobile = phone, service = "ext.zymk", imgCode = img_code, refresh = refresh and 1 or 0, + }, function(data, err) + if data and data.sent then self.sms_phone, self.retry_at = phone, os.time() + 60 + elseif data then self.captcha = data end + cb(data, err) + end) +end + +---@param phone string +---@param code string +---@param cb fun(account: ZymkAccount|nil, err: string|nil) +function Login:codeAsync(phone, code, cb) + if phone ~= self.sms_phone or not code:match("^%d+$") then + cb(nil, _("请先获取该手机号的验证码,再填写验证码登录")); return + end + self:request("/apinew/mobilevclogin/", { mobile = phone, vcode = code }, function(data, err) + if not data then cb(nil, err); return end + if type(data.appToken) ~= "string" or data.appToken == "" then + cb(nil, _("登录响应无效")); return + end + self:confirm({ type = "mkxq", token = data.appToken }, cb) + end) +end + +---@param identity string +---@param password string +---@param cb fun(account: ZymkAccount|nil, err: string|nil) +function Login:passwordAsync(identity, password, cb) + if identity == "" or password == "" then cb(nil, _("请输入账号和密码")); return end + self:request("/userapi/login/", { identity = identity, pwd = password }, function(data, err) + if not data then cb(nil, err); return end + if type(data.appToken) ~= "string" or data.appToken == "" then + cb(nil, _("登录响应无效")); return + end + self:confirm({ type = "mkxq", token = data.appToken }, cb) + end) +end + +---@param cookie string +---@param cb fun(account: ZymkAccount|nil, err: string|nil) +function Login:cookieAsync(cookie, cb) + local header = require("source.cookie_login").parse(cookie) + local value = header:match("^user=([^;]+)") or header:match("; user=([^;]+)") + if not value then cb(nil, _("没有读到知音漫客登录 Cookie")); return end + local decoded, data = pcall(JSON.decode, Text.urlDecode(value)) + local account = decoded and Mapper.account(data) + if not account then cb(nil, _("没有读到知音漫客登录 Cookie")); return end + self:confirm(account, cb) +end + +return Login diff --git a/moonsource-zymk.koplugin/moonsource_zymk/mapper.lua b/moonsource-zymk.koplugin/moonsource_zymk/mapper.lua new file mode 100644 index 0000000..faea5f9 --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/mapper.lua @@ -0,0 +1,213 @@ +--[[-- +知音漫客响应到书籍、目录和页图。 + +搜索走 `/apinew/getsortlist/`。章节列表是看漫画的 `getchapterlist`, +`order_num` 小的在前。`price > 0` 且没有页图的话是未购买。 + +@module moonsource_zymk.mapper +--]] + +local Text = require("utils.text") + +local Mapper = {} + +Mapper.TOC_VERSION = 1 +local SOURCE_ID = "ext.zymk" +local COVER = "https://chapter-cover.yyhao.com/file/cover/%s.jpg-300x400" + +---@class ZymkAccount +---@field openid string +---@field type string + +--- 官网用 type + openid 访问账号;device 是匿名身份,不能算登录。 +---@param data any +---@return ZymkAccount|nil +function Mapper.account(data) + if type(data) ~= "table" or type(data.openid) ~= "string" or data.openid == "" + or type(data.type) ~= "string" or data.type == "" or data.type == "device" then return nil end + return { openid = data.openid, type = data.type } +end + +---@class ZymkCaptcha +---@field image string +---@field width number +---@field height number +---@field content string + +---@param data any +---@return ZymkCaptcha|nil +function Mapper.captcha(data) + if type(data) ~= "table" or type(data.Image) ~= "string" or data.Image == "" + or type(data.Content) ~= "string" or data.Content == "" then return nil end + local width, height = tonumber(data.Width), tonumber(data.Height) + if not width or width <= 0 or not height or height <= 0 then return nil end + return { image = data.Image, width = width, height = height, content = data.Content } +end + + +---@param value any +---@return string +local function clean(value) + if type(value) ~= "string" then return "" end + return Text.trim(value) +end + +--- 封面路径把漫画 id 补成 9 位再按 3 位切开。4982 → `000/004/982`。 +---@param comic_id string|number +---@return string|nil +function Mapper.cover(comic_id) + local number = tonumber(comic_id) + if not number or number < 0 then return nil end + local digits = string.format("%09d", number) + local path = digits:sub(1, 3) .. "/" .. digits:sub(4, 6) .. "/" .. digits:sub(7, 9) + return COVER:format(path) +end + +---@param wire table|nil +---@return Book[]|nil +function Mapper.list(wire) + if type(wire) ~= "table" or tonumber(wire.status) ~= 0 then return nil end + local page = type(wire.data) == "table" and wire.data.page or nil + local rows = type(page) == "table" and page.comic_list or nil + if type(rows) ~= "table" then return nil end + local out = {} + for _idx, row in ipairs(rows) do + if type(row) ~= "table" or row.comic_id == nil or clean(row.comic_name) == "" then return nil end + out[#out + 1] = { + source_id = SOURCE_ID, + stable_id = tostring(row.comic_id), + title = clean(row.comic_name), + authors = "", + cover = Mapper.cover(row.comic_id), + intro = clean(row.comic_feature), + } + end + return out +end + +--- 官网空收藏可能省略 ubook;非空的坏行不能变成空书架。 +---@param data any +---@return Book[]|nil +function Mapper.shelf(data) + if type(data) ~= "table" then return nil end + local rows = data.ubook + if rows == nil then + if next(data) == nil or type(data.urecord) == "table" then return {} end + return nil + end + if type(rows) ~= "table" then return nil end + local count = 0 + for index, row in pairs(rows) do + count = count + 1 + if type(index) ~= "number" or index % 1 ~= 0 or index < 1 or index > #rows + or type(row) ~= "table" or not tostring(row.comic_id):match("^%d+$") + or clean(row.comic_name) == "" then return nil end + end + if count ~= #rows then return nil end + local books = {} + for _index, row in ipairs(rows) do + local added = tonumber(row.addtime) + books[#books + 1] = { + source_id = SOURCE_ID, stable_id = tostring(row.comic_id), + title = clean(row.comic_name), cover = Mapper.cover(row.comic_id), + inserted_at = added and math.floor(added / 1000) or nil, + } + end + return books +end + +---@param page table|nil +---@param stable_id string|number +---@return Book|nil +function Mapper.detail(page, stable_id) + if type(page) ~= "table" or clean(page.title) == "" or stable_id == nil then return nil end + local cover = clean(page.cover) + return { + source_id = SOURCE_ID, + stable_id = tostring(stable_id), + title = clean(page.title), + authors = clean(page.authors), + cover = cover ~= "" and cover or Mapper.cover(stable_id), + intro = clean(page.description), + } +end + +--- 看漫画章节。uid 带上漫画 id,页图接口两个都要。 +---@param comic_id string|number +---@param rows table|nil +---@return BookChapter[]|nil +function Mapper.chapters(comic_id, rows) + if comic_id == nil or type(rows) ~= "table" then return nil end + local copy = {} + for index, row in ipairs(rows) do + if type(row) ~= "table" or not tonumber(row.order_num) + or type(row.chapter_newid) ~= "string" or row.chapter_newid == "" + or clean(row.chapter_name) == "" then return nil end + copy[index] = row + end + table.sort(copy, function(left, right) + return tonumber(left.order_num) < tonumber(right.order_num) + end) + local prefix = tostring(comic_id) .. "/" + local out = {} + for _idx, row in ipairs(copy) do + out[#out + 1] = { + idx = #out + 1, + uid = prefix .. row.chapter_newid, + title = clean(row.chapter_name), + vip = (tonumber(row.price) or 0) > 0, + } + end + if not out[1] then return nil end + out[1].toc_version = Mapper.TOC_VERSION + return out +end + +--- 一话的页图。没有图且标了价格或会员,就是未购买。 +---@param wire table|nil +---@return string[]|nil +---@return string|nil +function Mapper.images(wire) + if type(wire) ~= "table" or tonumber(wire.status) ~= 0 then return nil end + local chapter = type(wire.data) == "table" and wire.data.current_chapter or nil + if type(chapter) ~= "table" then return nil end + local urls = {} + if type(chapter.chapter_img_list) == "table" then + for _idx, url in ipairs(chapter.chapter_img_list) do + if type(url) ~= "string" or not url:match("^https?://") then return nil end + urls[#urls + 1] = url + end + end + if #urls == 0 then + if (tonumber(chapter.price) or 0) > 0 or tonumber(chapter.is_vip) == 1 then + return nil, "locked" + end + return nil + end + return urls +end + +---@param stable_id string +---@param page integer +---@param wire table +---@return table|nil +function Mapper.reviews(stable_id, page, wire) + if type(wire) ~= "table" or tonumber(wire.status) ~= 1 or type(wire.data) ~= "table" then return nil end + local items = {} + for _idx, row in ipairs(wire.data) do + if type(row) ~= "table" or row.id == nil or tostring(row.ssid) ~= stable_id or tonumber(row.ssidtype) ~= 0 + or type(row.content) ~= "string" or type(row.uname) ~= "string" then return nil end + local timestamp = tonumber(row.createtime) or 0 + if timestamp >= 1e12 then timestamp = timestamp / 1000 end + items[#items + 1] = { + id = tostring(row.id), + author = row.uname, + text = Text.stripHtml(row.content), + time = timestamp > 0 and os.date("%Y-%m-%d", timestamp) or "", + } + end + -- 列表没有总数;满页只表明可能还有下一页,不能伪造精确页数。 + return { items = items, more = #wire.data == 20, pages = #wire.data == 20 and page + 1 or page } +end + +return Mapper diff --git a/moonsource-zymk.koplugin/moonsource_zymk/page.lua b/moonsource-zymk.koplugin/moonsource_zymk/page.lua new file mode 100644 index 0000000..bd05de8 --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/page.lua @@ -0,0 +1,55 @@ +--[[-- +知音漫客漫画页元信息与分类页标签。目录不在漫画页 HTML 里,只取书名和任意一话的文件名。 + +那一话的地址会 301 到看漫画,真正的章节列表在那边。 + +@module moonsource_zymk.page +--]] + +local Text = require("utils.text") +local Page = {} + +---@param html string +---@param property string +---@return string +local function meta(html, property) + local content = html:match('property="' .. property .. '"%s+content="([^"]*)"') + or html:match('content="([^"]*)"%s+property="' .. property .. '"') + return Text.xmlDecode(content or "") +end + +--- 详情页。没有书名或一话链接就无法定位到看漫画。 +---@param html string|nil +---@return table|nil +function Page.detail(html) + if type(html) ~= "string" or html == "" then return nil end + local title = meta(html, "og:novel:book_name") + local chapter_file = html:match('href="(%d+)%.html"') + if title == "" or not chapter_file then return nil end + return { + title = title, + authors = meta(html, "og:novel:author"), + cover = meta(html, "og:image"), + description = meta(html, "og:description"), + chapter_file = chapter_file, + } +end + +--- 官网分类标签,保留分组;不维护本地分类 ID 表。 +---@param html string +---@return table[]|nil +function Page.filters(html) + local groups = {} + for title, body in html:gmatch('
(.-)
(.-)
') do + local items = {} + for tag, label in body:gmatch('data%-tag="(%d+)"%s+title="([^"]+)"') do + items[#items + 1] = { id = tag, title = Text.xmlDecode(label) } + end + if #items > 0 then + groups[#groups + 1] = { title = Text.xmlDecode(title), items = items } + end + end + return #groups > 0 and groups or nil +end + +return Page diff --git a/moonsource-zymk.koplugin/moonsource_zymk/phone_login.lua b/moonsource-zymk.koplugin/moonsource_zymk/phone_login.lua new file mode 100644 index 0000000..d08a190 --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/phone_login.lua @@ -0,0 +1,176 @@ +--[[-- +知音漫客短信登录窗口:手机号 → 官网点字验证 → 短信码 → 账号兑换。 +验证码由用户按官网示例顺序点选,不自动识别或绕过验证。 + +@module moonsource_zymk.phone_login +--]] + +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_zymk") + +---@class ZymkPhoneLogin +---@field session ZymkLogin +---@field on_user fun() +---@field phone string|nil +---@field done boolean|nil +---@field dialog table|nil +---@field waiting table|nil +local Phone = {} +Phone.__index = Phone + +function Phone.new(on_user) + return setmetatable({ session = require("moonsource_zymk.login").new(), on_user = on_user }, Phone) +end + +function Phone:cancel() + self.done = true + self.session:cancel() + if self.waiting then self.waiting:close(); self.waiting = nil end + if self.dialog then local dialog = self.dialog; self.dialog = nil; dialog:close() end +end + +function Phone:showCaptcha(captcha) + local raw = Text.base64Decode(captcha.image) + local bitmap = raw and require("ui/renderimage"):renderImageData(raw, #raw, false) + if not bitmap then + self:cancel() + require("ui.themes.widgets.toast"):new{ text = _("图形验证码加载失败") }:show(); return + end + local Modal = require("ui.themes.widgets.modal") + local ImageWidget = require("ui/widget/imagewidget") + local InputContainer = require("ui/widget/container/inputcontainer") + local GestureRange = require("ui/gesturerange") + local ThemeText = require("ui.themes.widgets.text") + local T = require("ffi/util").template + local owner, points = self, {} + local Captcha = Modal:extend{} + function Captcha:init() + Modal.init(self) + local width = self:innerWidth() + local height = math.floor(width * captcha.height / captcha.width) + local TapImage = InputContainer:extend{} + function TapImage:init() + self.ges_events = { TapCaptcha = { + GestureRange:new{ ges = "tap", range = function() return self.dimen end }, + } } + end + function TapImage:onTapCaptcha(_event, gesture) + if #points < 2 then + points[#points + 1] = { + x = math.floor((gesture.pos.x - self.dimen.x) / width * captcha.width), + y = math.floor((gesture.pos.y - self.dimen.y) / height * captcha.height), + } + require("ui.themes.widgets.toast"):new{ + text = T(_("已选择 %1/2 个位置"), #points), timeout = 1, + }:show() + end + return true + end + self:setDialog{ + title = _("图形验证码"), + body = require("ui/widget/verticalgroup"):new{ + align = "left", + ThemeText.box("body", _("按顺序点选图片中的文字:") .. captcha.content, width, { transparent = true }), + TapImage:new{ ImageWidget:new{ + image = bitmap, width = width, height = height, scale_factor = 0, alpha = true, + } }, + }, + buttons = { + { text = _("取消"), callback = function() owner:cancel() end }, + { text = _("刷新"), callback = function() + self:close(); owner.dialog = nil; owner:send(nil, true) + end }, + { text = _("重新选择"), callback = function() + points = {} + require("ui.themes.widgets.toast"):new{ text = _("请重新点选图片中的文字") }:show() + end }, + { text = _("确定"), variant = "primary", callback = function() + if #points ~= 2 then + require("ui.themes.widgets.toast"):new{ text = _("请按顺序选择两个文字位置") }:show(); return + end + self:close(); owner.dialog = nil; owner:send(points, false) + end }, + }, + } + end + function Captcha:dismiss() owner:cancel() end + self.dialog = Captcha:new{} + self.dialog:show() +end + +function Phone:send(points, refresh) + if self.done then return end + if not require("ui/network/manager"):isConnected() then + require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi") }:show(); return + end + self.waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("短信验证码登录"), text = _("正在获取验证码…"), + on_cancel = function() self:cancel() end, + } + self.waiting:show() + self.session:sendSmsAsync(self.phone, points, refresh, function(data, err) + if self.done then return end + self.waiting:close(); self.waiting = nil + if not data then + require("ui.themes.widgets.toast"):new{ text = err, timeout = 3 }:show() + if not self.dialog then self:start() end + else + if self.dialog then self.dialog:close(); self.dialog = nil end + if data.sent then + require("ui.themes.widgets.toast"):new{ text = _("短信已发送") }:show() + self:enterCode() + else + self:showCaptcha(data) + end + end + end) +end + +function Phone:enterCode() + self.dialog = require("ui.themes.widgets.input"):new{ + title = _("短信验证码登录"), + fields = { { label = _("验证码"), input_type = "number" } }, + actions = { { text = _("获取验证码"), callback = function() self:send(nil, false) end } }, + cancel_callback = function() self:cancel() end, + callback = function(code) + self.dialog = nil + if not require("ui/network/manager"):isConnected() then + require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi") }:show() + self:enterCode(); return + end + self.waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("短信验证码登录"), text = _("正在校验登录…"), + on_cancel = function() self:cancel() end, + } + self.waiting:show() + self.session:codeAsync(self.phone, code, function(account, err) + if self.done then return end + self.waiting:close(); self.waiting = nil + if account then self:cancel(); self.on_user() + else + require("ui.themes.widgets.toast"):new{ text = err, timeout = 3 }:show() + self:enterCode() + end + end) + end, + } + self.dialog:show() +end + +function Phone:start() + if self.done then return end + self.dialog = require("ui.themes.widgets.input"):new{ + title = _("短信验证码登录"), + fields = { { label = _("手机号"), text = self.phone or "", input_type = "number" } }, + ok_text = _("获取验证码"), + cancel_callback = function() self:cancel() end, + callback = function(phone) + self.dialog = nil + self.phone = Text.trim(phone) + self:send(nil, false) + end, + } + self.dialog:show() +end + +return Phone diff --git a/moonsource-zymk.koplugin/moonsource_zymk/setting.lua b/moonsource-zymk.koplugin/moonsource_zymk/setting.lua new file mode 100644 index 0000000..76aaf20 --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/setting.lua @@ -0,0 +1,100 @@ +--[[-- +知音漫客账号设置:短信验证码、密码与 Cookie 登录。 + +@module moonsource_zymk.setting +--]] + +local Login = require("moonsource_zymk.login") +local Client = require("moonsource_zymk.client") +local CookieLogin = require("source.cookie_login") +local _ = require("l10n").get("moonsource_zymk") +local Setting = {} + +function Setting.rowStatus() + local on = Login.hasAccount() + return on and _("已登录") or _("未登录 · 点此登录"), on +end + +Setting.browser = { + domain = "www.zymk.cn", + scope = "cookie", + login = Client.LOGIN_URL, + check = "https://www.zymk.cn/", + icon = "https://www.zymk.cn/static/images/default/favicon.ico", + isAuthorized = function() return Login.hasAccount() end, + apply = function(payload, cb) + local cookie = CookieLogin.fromPayload(payload, "zymk.cn") + if cookie == "" then cookie = CookieLogin.fromPayload(payload, "kanman.com") end + if cookie == "" then return cb(false, _("没有读到 Cookie")) end + return Login.new():cookieAsync(cookie, function(account, err) + cb(account ~= nil, err) + end) + end, +} + +local function onLogin() + require("ui.themes.widgets.toast"):new{ text = _("登录成功"), timeout = 2 }:show() +end + +---@param password_mode boolean +function Setting.prompt(password_mode) + require("ui.themes.widgets.input"):new{ + title = password_mode and _("密码登录") or _("知音漫客登录 Cookie"), + fields = password_mode and { + { label = _("账号"), hint = _("通行证账号、手机号码或邮箱") }, + { label = _("密码"), text_type = "password" }, + } or { { hint = _("在知音漫客官网登录后,复制请求标头里的完整 Cookie") } }, + ok_text = _("登录"), + callback = function(value, password) + local Toast = require("ui.themes.widgets.toast") + if not require("ui/network/manager"):isConnected() then + Toast:new{ text = _("网络不可用,请先连接 Wi-Fi") }:show(); return + end + local session, cancelled = Login.new(), false + local waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = password_mode and _("密码登录") or _("知音漫客登录 Cookie"), text = _("正在校验登录…"), + on_cancel = function() cancelled = true; session:cancel() end, + } + waiting:show() + local function done(account, err) + if cancelled then return end + waiting:close() + if account then onLogin() + else Toast:new{ text = err, timeout = 3 }:show() end + end + if password_mode then session:passwordAsync(value, password, done) + else session:cookieAsync(value, done) end + end, + }:show() +end + +function Setting.rows() + local Row = require("ui.themes.widgets.row") + local rows = { + function(iw) + local status, on = Setting.rowStatus() + return Row.widget({ width = iw, kind = "nav", title = _("短信验证码登录"), + icon = "sms", status = status, status_on = on, + callback = function() require("moonsource_zymk.phone_login").new(onLogin):start() end }) + end, + function(iw) + return Row.widget({ width = iw, kind = "nav", title = _("密码登录"), icon = "password", + callback = function() Setting.prompt(true) end }) + end, + CookieLogin.browserRow(), + function(iw) + return Row.widget({ width = iw, kind = "nav", title = _("粘贴 Cookie"), icon = "content_paste", + callback = function() Setting.prompt(false) end }) + end, + } + if require("utils.settings").getSource("ext.zymk").account then + rows[#rows + 1] = require("source.logout").row("ext.zymk", _("确定退出知音漫客账号?"), function() + local Settings = require("utils.settings") + Settings.getSource("ext.zymk").account = nil + Settings.saveSource("ext.zymk") + end) + end + return rows +end + +return Setting diff --git a/moonsource-zymk.koplugin/moonsource_zymk/source.lua b/moonsource-zymk.koplugin/moonsource_zymk/source.lua new file mode 100644 index 0000000..a33a3c8 --- /dev/null +++ b/moonsource-zymk.koplugin/moonsource_zymk/source.lua @@ -0,0 +1,235 @@ +--[[-- +知音漫客数据源。 + +阅读发生在站点跳过去的看漫画。账号登录与公开阅读分离;登录后拉取收藏。 +一话是一组图片,打成 CBZ。 + +@module source.zymk +--]] + +local Client = require("moonsource_zymk.client") +local Mapper = require("moonsource_zymk.mapper") +local SourceBase = require("source.base") +local Toc = require("source.toc") +local _ = require("l10n").get("moonsource_zymk") + +local Zhiyinmanke = {} + +---@return BookSourceMeta +function Zhiyinmanke.meta() + return require("moonsource_zymk.loadmeta")() +end + +---@class ZhiyinmankeSource : SourceBase +---@field account ZymkAccount|nil +local Source = setmetatable({}, { __index = SourceBase }) +Source.__index = Source + +---@return ZhiyinmankeSource +function Zhiyinmanke.new() + local meta = Zhiyinmanke.meta() + return setmetatable({ + id = meta.id, name = meta.name, type = meta.type, + account = require("utils.settings").getSource("ext.zymk").account, + }, Source) +end + +--- 只拉收藏,不推本地成员变更。 +---@return SourceCapabilities +function Source:capabilities() + local caps = SourceBase.capabilities(self) + caps.shelf_push = false + return caps +end + +---@return boolean +function Source:configured() + return true +end + +---@param opts { force?: boolean, dirty_only?: boolean, on_progress?: ShelfReport }|nil +---@param cb fun(result: SyncResult|nil, err: string|nil) +function Source:syncBooksAsync(opts, cb) + opts = opts or {} + if opts.dirty_only then return SourceBase.skipped(cb, "unsupported") end + if not self.account then return SourceBase.skipped(cb, "zymk not logged in") end + if opts.on_progress then opts.on_progress(_("正在拉取书架…")) end + local cancelled = false + local job = Client.shelfAsync(self.account, function(books, err) + if cancelled then return end + if not books then cb(nil, err); return end + local result, reason = require("source.shelf").reconcile(self.id, books, opts.force, true) + cb(result, reason) + end) + return { cancel = function() + cancelled = true + job.cancel() + end } +end + +---@param keyword string +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +function Source:searchAsync(keyword, cb) + return Client.searchAsync(keyword, function(books, err) + if not books then cb(nil, err or _("请求失败")); return end + cb({ data = books }) + end) +end + +---@param opts table|nil +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +function Source:browseAsync(opts, cb) + return require("moonsource_zymk.browse").run(opts or {}, cb) +end + +function Source:bookReviewsAsync(identity, cb) + return Client.reviewsAsync(identity.stable_id, 1, cb) +end + +---@param self ZhiyinmankeSource +---@param identity BookIdentity +---@param cb fun(page: table|nil, err: string|nil) +local function loadPage(self, identity, cb) + return Client.catalogAsync(identity.stable_id, function(page, err) + if not page then cb(nil, err); return end + if not Toc.put(self.id, identity.stable_id, page.chapters) then cb(nil, _("章节目录保存失败")); return end + cb(page) + end) +end + +function Source:getDetailAsync(identity, cb) + return loadPage(self, identity, function(page, err) + if page and page.book then cb(require("book.store").rememberDetail(page.book)); return end + local row = identity.book or require("book.books_db").get(self.id, identity.stable_id) + if row then cb(row); return end + cb(nil, err or _("请求失败")) + end) +end + +function Source:loadTocAsync(identity, cb, force) + if not force then + local cached = Toc.read(self.id, identity.stable_id) + if cached and #cached > 0 and cached[1].toc_version == Mapper.TOC_VERSION then + return SourceBase.defer(cb, cached) + end + end + return loadPage(self, identity, function(page, err) + if not page then cb(nil, err); return end + cb(page.chapters) + end) +end + +Source.refreshTocAsync = function(self, identity, cb) + return self:loadTocAsync(identity, cb, true) +end + +---@param identity BookIdentity +---@param opts table +---@param toc BookChapter[] +---@return integer +local function startIndex(identity, opts, toc) + local idx = opts.chapter_idx + if not idx then + local pending = require("book.progress_db").get(identity.source_id, identity.stable_id) + idx = pending and (pending.chapter_idx or math.floor((pending.fraction or 0) * #toc) + 1) + end + return math.max(1, math.min(#toc, idx or 1)) +end + +---@param identity BookIdentity +---@param opts table|nil +---@param cb fun(path: string|nil, err: string|nil) +---@return { cancel: fun() } +function Source:openBookAsync(identity, opts, cb) + opts = opts or {} + local Chapter = require("moonsource_zymk.chapter") + local function finish(path, idx) + local ok, err = require("book.store").touch(path, identity, { + chapter_idx = idx, + book = identity.book, + }) + cb(ok and path or nil, err) + end + local toc = Toc.read(identity.source_id, identity.stable_id) + if toc and #toc > 0 then + local idx = startIndex(identity, opts, toc) + local path = Chapter.existing(identity, toc[idx]) + if path then return SourceBase.defer(finish, path, idx) end + end + if not require("ui/network/manager"):isConnected() then + return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi")) + end + + local cancelled, active, dialog = false, nil, nil + local function closeDialog() + if dialog then dialog:close(); dialog = nil end + end + require("ui/uimanager"):nextTick(function() + if cancelled then return end + dialog = require("ui.themes.widgets.progress_dialog"):new{ + title = identity.book and identity.book.title or identity.stable_id, + dismissable = false, + } + dialog:show() + dialog:set(_("正在准备漫画…")) + local loading = true + local toc_job = self:loadTocAsync(identity, function(fresh, err) + loading = false + active = nil + if cancelled then return end + if not fresh then closeDialog(); cb(nil, err); return end + local idx = startIndex(identity, opts, fresh) + local preparing = true + local chapter_job = Chapter.materializeAsync(identity, fresh[idx], function(done, total) + if dialog and total > 0 then dialog:update(_("正在准备漫画…"), done, total) end + end, function(path, materialize_err) + preparing = false + active = nil + closeDialog() + if cancelled then return end + if not path then cb(nil, materialize_err); return end + finish(path, idx) + end) + if preparing then active = chapter_job end + end) + if loading then active = toc_job end + end) + return { cancel = function() + cancelled = true + if active then active.cancel() end + closeDialog() + end } +end + +function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb) + return require("moonsource_zymk.chapter").prefetchAsync(identity, toc, from_idx, count, nil, cb) +end + +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + local cancelled, active = false, nil + local loading = true + local toc_job = self:loadTocAsync(identity, function(toc, err) + loading = false + active = nil + if cancelled then return end + if not toc then cb(false, 0, err, 0, 0); return end + local from_idx, count = require("source.chapter").cacheRange(toc, range) + local caching = true + local cache_job = require("moonsource_zymk.chapter").prefetchAsync(identity, toc, from_idx, count, { + progress = on_progress, + interval_seconds = 1.5, + }, function(cached, total, failed, last_err) + caching = false + active = nil + if not cancelled then cb(failed == 0, cached, last_err, total, failed) end + end) + if caching then active = cache_job end + end) + if loading then active = toc_job end + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +return Zhiyinmanke diff --git a/tests/zymk/async_spec.lua b/tests/zymk/async_spec.lua new file mode 100644 index 0000000..41b5461 --- /dev/null +++ b/tests/zymk/async_spec.lua @@ -0,0 +1,100 @@ +--[[-- +知音漫客:同步前级与异步后级的取消句柄、搜索分页与失败语义。 + +@module tests.moonsource_zymk.async_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local JSON = require("support.json_stub") +package.loaded["json"] = JSON +local pending, cancelled, mode = nil, {}, "catalog" +local html = '首话' +local filters = '
题材
热血
' +package.loaded["http.request"] = { + header = function(res, key) return res.headers[key] end, + get = function(url, _opts, cb) + local kind + if url:find("/getchapterlist", 1, true) or url:find("/allComic/", 1, true) then + kind = "list" + pending = cb + elseif url:find("/sort/all.html", 1, true) then + kind = "filters" + cb(filters) + elseif url:find("/1.html", 1, true) then + kind = "redirect" + cb(nil, "HTTP 301", { code = 301, headers = { + location = mode == "bad_redirect" and "https://evil.test/kanman.com/123/" + or "https://www.kanman.com/123/first.html", + } }) + elseif url:find("getsortlist", 1, true) then + local page = tonumber(url:match("page=(%d+)")) + kind = "page" .. page + if mode == "search_error" and page == 2 then cb(nil, "网络故障") + elseif mode == "search_async" and page == 2 then pending = cb + else + cb(JSON.encode({ status = 0, data = { page = { total_page = 2, comic_list = { + { comic_id = page, comic_name = "结果" .. page }, + } } } })) + end + else + kind = "detail" + cb(html) + end + return { cancel = function() cancelled[kind] = true end } + end, +} +local Client = require("moonsource_zymk.client") +local called = false +local handle = Client.catalogAsync("1", function() called = true end) +handle.cancel() +Assert.is_true(cancelled.list) +Assert.is_nil(cancelled.detail) +Assert.is_nil(cancelled.redirect) +pending(JSON.encode({ status = 0, data = {} })) +Assert.is_false(called) + +cancelled = {} +handle = Client.libraryAsync(function() called = true end) +handle.cancel() +Assert.is_true(cancelled.list) +Assert.is_nil(cancelled.filters) +pending(JSON.encode({ status = 0, data = {} })) +Assert.is_false(called) + +mode = "bad_redirect" +Client.catalogAsync("1", function(data, err) + Assert.is_nil(data) + Assert.eq(err, "HTTP 301") +end) +mode = "catalog" +Client.catalogAsync("1", function(data, err) + Assert.is_nil(data) + Assert.eq(err, "响应无效") +end) +pending(JSON.encode({ status = 1, data = { { chapter_name = "首话", chapter_newid = "first", order_num = 1 } } })) + +mode = "search" +Client.searchAsync("结果", function(data, err) + Assert.is_nil(err) + Assert.len(data, 2) + Assert.eq(data[2].stable_id, "2") +end) +mode = "search_error" +Client.searchAsync("结果", function(data, err) + Assert.is_nil(data) + Assert.eq(err, "网络故障") +end) +mode, cancelled = "search_async", {} +handle = Client.searchAsync("结果", function() called = true end) +handle.cancel() +Assert.is_true(cancelled.page2) +Assert.is_nil(cancelled.page1) +pending(JSON.encode({ status = 0, data = { page = { comic_list = {} } } })) +Assert.is_false(called) + +handle = Client.imagesAsync("bad", function() called = true end) +handle.cancel() +Stubs.flush() +Assert.is_false(called) diff --git a/tests/zymk/browse_spec.lua b/tests/zymk/browse_spec.lua new file mode 100644 index 0000000..a35c285 --- /dev/null +++ b/tests/zymk/browse_spec.lua @@ -0,0 +1,63 @@ +--[[-- +知音漫客分类:动态分组、组合筛选、排序、limit 和异常响应。 + +@module tests.moonsource_zymk.browse_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Page = require("moonsource_zymk.page") +local filters = Page.filters([[ +
题材
热血玄幻
+
进度
连载完结
+]]) +Assert.len(filters, 2) +Assert.eq(filters[1].items[2].id, "7") +Assert.is_nil(Page.filters("风控页")) + +local wire = { filters = filters, rows = { + { comic_id = 1, comic_name = "热血连载", class_idlist = ",5,23,", update_time = "2026-11-07", total_click = 5, pingfen = "9.8" }, + { comic_id = 2, comic_name = "玄幻完结", class_idlist = ",7,24,", update_time = "2026-11-06", total_click = 30, pingfen = "9.7" }, + { comic_id = 3, comic_name = "双题材完结", class_idlist = ",5,7,24,", update_time = "2026-11-05", total_click = 10, pingfen = "9.9" }, +} } +package.loaded["moonsource_zymk.client"] = { + libraryAsync = function(cb) cb(wire); return { cancel = function() end } end, +} +local Library = require("moonsource_zymk.browse") +local function load(opts) + local result, reason + Library.run(opts or {}, function(data, err) result, reason = data, err end) + return result, reason +end +local result = load({ limit = 2 }) +Assert.len(result.data, 2) +Assert.eq(result.data[1].stable_id, "1") +Assert.len(result.groups, 3) +Assert.eq(result.groups[2].title, "题材") +local category_node = result.groups[2].chips[2].id +result = load({ node = category_node }) +Assert.len(result.data, 2) +Assert.eq(result.groups[2].active, category_node) +local finished_node = result.groups[3].chips[3].id +result = load({ node = finished_node }) +Assert.len(result.data, 1) +Assert.eq(result.data[1].stable_id, "3") +Assert.eq(result.groups[3].active, finished_node) + +result = load({ node = "library?sort=total_click" }) +Assert.eq(result.data[1].stable_id, "2") +result = load({ node = "library?sort=pingfen" }) +Assert.eq(result.data[1].stable_id, "3") +result = load({ node = "library?tag1=7&tag2=23" }) +Assert.len(result.data, 0) +Assert.is_nil(load({ node = "library?tag1=999" })) +Assert.is_nil(load({ node = "library?sort=invalid" })) +Assert.is_nil(load({ node = "library?account=1" })) +wire.rows = { { comic_name = "坏行" } } +local broken, err = load() +Assert.is_nil(broken) +Assert.eq(err, "响应无效") +require("moonsource_zymk.client").libraryAsync = function(cb) cb(nil, "网络故障") end +broken, err = load() +Assert.is_nil(broken) +Assert.eq(err, "网络故障") diff --git a/tests/zymk/chapter_spec.lua b/tests/zymk/chapter_spec.lua new file mode 100644 index 0000000..dd0c55f --- /dev/null +++ b/tests/zymk/chapter_spec.lua @@ -0,0 +1,80 @@ +--[[-- +知音漫客图片下载:同步目录回调后取消在飞下载;失败不打包、VIP 明确拒绝。 + +@module tests.moonsource_zymk.chapter_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local Config = require("support.config") +local downloaded, pending, cancelled, built = {}, nil, {}, nil +package.loaded["utils.paths"] = { + bookWorkDir = function() return Config.dir() .. "/zymk-chapter" end, + ensureBookWork = function() end, + ensureDir = function() end, +} +package.loaded["source.cbz"] = { + ready = function() return false end, + build = function(files, archive, _state, cb) built = files; cb(archive) end, +} +package.loaded["utils.image"] = { + suffix = function() return ".jpg" end, + file = function() return ".jpg" end, + ok = function(path) return downloaded[path] == true end, +} +package.loaded["moonsource_zymk.client"] = { + imagesAsync = function(_uid, cb) + cb({ "https://img/1.jpg", "https://img/2.jpg" }) + return { cancel = function() cancelled.images = true end } + end, +} +package.loaded["http.request"] = { + download = function(_opts, path, cb) + pending = function(ok, err) downloaded[path] = ok; cb(ok, err) end + return { cancel = function() cancelled.download = true end } + end, +} +local Chapter = require("moonsource_zymk.chapter") +local called = false +local identity = { source_id = "ext.zymk", stable_id = "book" } +local handle = Chapter.materializeAsync(identity, { uid = "123/first" }, nil, function() called = true end) +handle.cancel() +Assert.is_true(cancelled.download) +Assert.is_nil(cancelled.images) +pending(true) +Stubs.flush() +Assert.is_false(called) +Assert.is_nil(built) + +downloaded = {} +Chapter.materializeAsync(identity, { uid = "123/failed" }, nil, function(path, err) + Assert.is_nil(path) + Assert.eq(err, "下载失败") +end) +pending(false, "下载失败") +Assert.is_nil(built) + +local count, progress, result = 0, {}, nil +require("http.request").download = function(_opts, path, cb) + count = count + 1 + downloaded[path] = true + cb(true) + return { cancel = function() end } +end +Chapter.materializeAsync(identity, { uid = "123/second" }, function(done, total) + progress[#progress + 1] = { done, total } +end, function(path) result = path end) +Stubs.flush() +Assert.eq(count, 2) +Assert.len(built, 2) +Assert.len(progress, 2) +Assert.eq(progress[2][1], 2) +Assert.eq(progress[2][2], 2) +Assert.matches(result, "/123_second%.cbz$") + +Chapter.materializeAsync(identity, { uid = "123/vip", vip = true }, nil, function(path, err) + Assert.is_nil(path) + Assert.eq(err, "本章未购买") +end) +Stubs.flush() diff --git a/tests/zymk/client_spec.lua b/tests/zymk/client_spec.lua new file mode 100644 index 0000000..3cbf3de --- /dev/null +++ b/tests/zymk/client_spec.lua @@ -0,0 +1,135 @@ +--[[-- +知音漫客:封面路径、目录排序、跳转和页图。 + +@module tests.moonsource_zymk.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_zymk.mapper") +local Page = require("moonsource_zymk.page") + +Assert.eq( + Mapper.cover(4982), + "https://chapter-cover.yyhao.com/file/cover/000/004/982.jpg-300x400" +) +Assert.is_nil(Mapper.cover("nope")) + +local found = Mapper.list({ + status = 0, + data = { page = { comic_list = { + { comic_id = 4982, comic_name = "长相思", comic_feature = "简介" }, + } } }, +}) +Assert.eq(found[1].stable_id, "4982") +Assert.eq(found[1].title, "长相思") +Assert.eq(found[1].intro, "简介") +Assert.eq(found[1].cover, Mapper.cover(4982)) +Assert.eq(#Mapper.list({ status = 0, data = { page = { comic_list = {} } } }), 0) +Assert.is_nil(Mapper.list({ status = 1 })) +Assert.is_nil(Mapper.list({ status = 0, data = { page = { comic_list = { { comic_name = "缺身份" } } } } })) + +local html = [[ + + + + +少女漫画 +202话 +]] +local parsed = Page.detail(html) +Assert.eq(parsed.title, "长相思") +Assert.eq(parsed.authors, "飒飒动漫") +Assert.eq(parsed.chapter_file, "434454") +Assert.eq(parsed.cover, "https://img/cover.jpg") +Assert.is_nil(Page.detail("")) + +local detail = Mapper.detail(parsed, 4982) +Assert.eq(detail.authors, "飒飒动漫") +Assert.eq(detail.cover, "https://img/cover.jpg") +Assert.eq(detail.source_id, "ext.zymk") +Assert.eq(detail.intro, "简介") + +local toc = Mapper.chapters(25289, { + { chapter_name = "后一话", chapter_newid = "hou", order_num = 10, price = 5 }, + { chapter_name = "序章", chapter_newid = "xu", order_num = 3, price = 0 }, +}) +Assert.eq(#toc, 2) +Assert.eq(toc[1].uid, "25289/xu") +Assert.eq(toc[1].title, "序章") +Assert.eq(toc[1].vip, false) +Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION) +Assert.eq(toc[2].vip, true) +Assert.is_nil(Mapper.chapters(25289, {})) + +local urls = Mapper.images({ + status = 0, + data = { current_chapter = { price = 0, is_vip = 0, chapter_img_list = { "https://img/1.jpg", "https://img/2.jpg" } } }, +}) +Assert.eq(#urls, 2) +Assert.eq(select(2, Mapper.images({ + status = 0, + data = { current_chapter = { price = 5, is_vip = 0, chapter_img_list = {} } }, +})), "locked") +Assert.is_nil(Mapper.images({ status = 1 })) + +local requests = {} +package.preload["http.request"] = function() + return { + header = function(res, name) + local headers = res and res.headers + return headers and headers[name] + end, + get = function(url, _options, callback) + requests[#requests + 1] = url + if url:find("key=", 1, true) then + callback(Json.encode({ status = 0, data = { page = { total_page = 1, comic_list = { { comic_id = 4982, comic_name = "长相思" } } } } }), nil, nil) + elseif url:find("/apinew/getsortlist/", 1, true) then + callback(Json.encode({ status = 0, data = { page = { comic_list = { { comic_id = 101, comic_name = "凤逆天下" } } } } }), nil, nil) + elseif url:find(".html", 1, true) then + callback(nil, "HTTP 301", { code = 301, headers = { location = "https://www.kanman.com/25289/di202hua.html" } }) + elseif url:find("/4982/", 1, true) then + callback(html, nil, nil) + elseif url:find("/api/getchapterlist", 1, true) then + callback(Json.encode({ status = 0, data = { + { chapter_name = "后一话", chapter_newid = "hou", order_num = 10, price = 0 }, + { chapter_name = "序章", chapter_newid = "xu", order_num = 3, price = 0 }, + } }), nil, nil) + elseif url:find("/api/getchapterinfov2", 1, true) then + callback(Json.encode({ status = 0, data = { current_chapter = { chapter_img_list = { "https://img/1.jpg" } } } }), nil, nil) + else + callback(nil, "miss", nil) + end + return { cancel = function() end } + end, + } +end +package.loaded["http.request"] = nil +package.loaded["moonsource_zymk.client"] = nil + +local Client = require("moonsource_zymk.client") +local books +Client.searchAsync("长相思", function(list) books = list end) +Assert.eq(books[1].stable_id, "4982") + +local loaded +Client.catalogAsync("4982", function(value) loaded = value end) +Assert.eq(loaded.book.title, "长相思") +Assert.eq(loaded.chapters[1].uid, "25289/xu") +Assert.is_true(requests[#requests]:find("comic_id=25289", 1, true) ~= nil) + +local images +Client.imagesAsync("25289/xu", function(list) images = list end) +Assert.eq(images[1], "https://img/1.jpg") +Assert.is_true(requests[#requests]:find("isWebp=0", 1, true) ~= nil) +Assert.is_true(requests[#requests]:find("chapter_newid=xu", 1, true) ~= nil) + +Assert.is_nil(Mapper.chapters(25289, { { chapter_name = "无序号", chapter_newid = "xu" } })) +Assert.is_nil(Mapper.images({ + status = 0, data = { current_chapter = { chapter_img_list = { "https://img/1.jpg", false } } }, +})) +local escaped = Page.detail(html:gsub('content="长相思"', 'content="A & B"')) +Assert.eq(escaped.title, "A & B") diff --git a/tests/zymk/login_spec.lua b/tests/zymk/login_spec.lua new file mode 100644 index 0000000..e367859 --- /dev/null +++ b/tests/zymk/login_spec.lua @@ -0,0 +1,206 @@ +--[[-- +知音漫客短信、密码与 Cookie 登录:官网字段、账号兑换、取消和换号隔离。 + +@module tests.moonsource_zymk.login_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +local Text = require("utils.text") +local Themed = require("support.theme_stubs") +Themed.install() +package.loaded["json"] = JSON +local cfg, requests, reloads, expired, connected = {}, {}, 0, false, true +local cleared = 0 +package.loaded["source.logout"] = { clear = function(_id, clear) + clear(); cleared = cleared + 1; return true +end } +local synchronous +package.loaded["utils.settings"] = { getSource = function() return cfg end, saveSource = function() end } +package.loaded["source.registry"] = { reload = function() reloads = reloads + 1 end } +package.loaded["source.auth"] = { + expired = function() return expired end, ok = function() expired = false end, +} +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +package.loaded["ui.themes.widgets.row"] = { widget = function(opts) return opts end } +local function request(url, body, opts, cb) + local r = { url = url, body = body, opts = opts, cb = cb } + requests[#requests + 1] = r + if synchronous then local answer = synchronous; synchronous = nil; cb(answer) end + return { cancel = function() r.cancelled = true end } +end +package.loaded["http.request"] = { + post = request, +} +local Login = require("moonsource_zymk.login") +local Setting = require("moonsource_zymk.setting") +local Mapper = require("moonsource_zymk.mapper") +local response = JSON.encode({ status = 0, data = { openid = "account-a", type = "mkxq" } }) +local token = JSON.encode({ status = 0, data = { appToken = "temporary-token" } }) +local phone = "13800000000" +local account, reason +local function done(value, err) account, reason = value, err end +local session = Login.new() +Assert.is_false(Login.hasAccount()) +Assert.is_nil(Mapper.account({ openid = "guest", type = "device" })) +session:sendSmsAsync(phone, nil, false, done) +Assert.matches(requests[#requests].url, "/apinew/sendsms/$") +Assert.matches(requests[#requests].body, "service=ext.zymk") +Assert.matches(requests[#requests].body, "refresh=0") +local captcha = { Image = "image", Width = 320, Height = 120, Content = "文字" } +requests[#requests].cb(JSON.encode({ status = 1031, data = captcha })) +Assert.eq(account.width, 320) +Assert.is_nil(session.sms_phone) +session:sendSmsAsync(phone, { { x = 10, y = 20 }, { x = 50, y = 30 } }, false, done) +local body = Text.urlDecode(requests[#requests].body) +Assert.matches(body, '"appId":11') +Assert.matches(body, '"verificaType":2') +requests[#requests].cb(JSON.encode({ status = 0 })) +Assert.eq(session.sms_phone, phone) +Assert.is_true(account.sent) +local count = #requests +session:sendSmsAsync(phone, nil, false, done) +Assert.eq(#requests, count) +Assert.eq(reason, "请稍后再获取验证码") +session:codeAsync("13900000000", "123456", done) +Assert.eq(#requests, count) +Assert.eq(reason, "请先获取该手机号的验证码,再填写验证码登录") +session:codeAsync(phone, "123456", done) +Assert.matches(requests[#requests].url, "/apinew/mobilevclogin/$") +Assert.matches(requests[#requests].body, "vcode=123456") +Assert.is_nil(cfg.account) +requests[#requests].cb(token) +Assert.matches(requests[#requests].url, "/apinew/getuserinfo/$") +Assert.matches(requests[#requests].body, "token=temporary%-token") +Assert.is_false(requests[#requests].opts.allow_redirects) +Assert.eq(requests[#requests].opts.headers.Origin, "https://www.zymk.cn") +Assert.eq(requests[#requests].opts.headers.Referer, "https://www.zymk.cn/login.htm") +Assert.eq(requests[#requests].opts.headers["X-Requested-With"], "XMLHttpRequest") +Assert.is_nil(cfg.account) +requests[#requests].cb(response) +Assert.eq(account.openid, "account-a") +Assert.is_nil(cfg.account.appToken) +Assert.is_nil(cfg.password) +Assert.eq(reloads, 1) +Assert.is_true(Login.hasAccount()) +expired = true +Assert.is_false(Login.hasAccount()) +expired = false +local previous = cfg.account +Login.new():confirm({ type = "mkxq", token = "expired" }, done) +requests[#requests].cb(nil, "network failed") +Assert.eq(reason, "network failed") +Assert.eq(cfg.account, previous) +Login.new():confirm({ type = "mkxq", token = "bad" }, done) +requests[#requests].cb("login") +Assert.eq(reason, "登录响应无效") +Assert.eq(cfg.account, previous) +Login.new():confirm({ type = "mkxq", token = "other" }, done) +requests[#requests].cb(JSON.encode({ status = 0, data = { openid = "account-b", type = "mkxq" } })) +Assert.is_nil(reason) +Assert.eq(cfg.account.openid, "account-b") +Assert.eq(cleared, 1) +local stale = Login.new() +stale:confirm({ type = "mkxq", token = "old" }, done) +cfg.account = nil +requests[#requests].cb(response) +Assert.eq(reason, "登录状态已变化,请重试") +Assert.is_nil(cfg.account) + +session = Login.new() +session.sms_phone = phone +synchronous = token +session:codeAsync(phone, "123456", done) +local pending = requests[#requests] +session:cancel() +Assert.is_true(pending.cancelled) +account = nil +pending.cb(response) +Assert.is_nil(account) +Assert.is_nil(cfg.account) + +session = Login.new() +session:passwordAsync("reader@example.test", " p+a&ss ", done) +Assert.matches(requests[#requests].url, "/userapi/login/$") +Assert.eq(requests[#requests].body, Text.formEncode({ identity = "reader@example.test", pwd = " p+a&ss " })) +requests[#requests].cb(token) +Assert.is_nil(cfg.account) +requests[#requests].cb(response) +Assert.is_true(Login.hasAccount()) +Assert.is_nil(cfg.password) +Assert.is_nil(Mapper.captcha({ Width = 320, Height = 120 })) + +package.loaded["source.logout"] = { row = function() return function() return { title = "退出登录" } end end } +local rows = Setting.rows() +Assert.eq(#rows, 5) +Assert.eq(rows[1](400).title, "短信验证码登录") +Assert.eq(rows[2](400).title, "密码登录") +Assert.eq(rows[3](400).title, "浏览器登录") +Assert.eq(rows[4](400).title, "粘贴 Cookie") +for _index, row in ipairs(rows) do + local title = row(400).title + Assert.is_true(title ~= "微信扫码登录" and title ~= "电脑浏览器登录") +end +rows[2](400).callback() +Assert.eq(Themed.last("input").fields[2].text_type, "password") +Themed.last("input").callback("reader", "password") +pending = requests[#requests] +Themed.last("progress_dialog").on_cancel() +Assert.is_true(pending.cancelled) +pending.cb(token) +Assert.eq(#Setting.rows(), 5) +local cookie = "user=" .. Text.urlEncode(JSON.encode({ openid = "account-a", type = "mkxq" })) +local cookie_previous = cfg.account +Login.new():cookieAsync(cookie, done) +requests[#requests].cb(nil, "network failed") +Assert.eq(cfg.account, cookie_previous) +Assert.eq(reason, "network failed") +Login.new():cookieAsync(cookie, done) +Assert.matches(requests[#requests].body, "openid=account%-a") +Assert.matches(requests[#requests].body, "type=mkxq") +requests[#requests].cb(response) +Assert.is_true(Login.hasAccount()) +Login.new():cookieAsync(cookie, done) +requests[#requests].cb(JSON.encode({ status = 0, data = { openid = "wrong-account", type = "mkxq" } })) +Assert.eq(reason, "登录响应无效") +rows[3](400).callback() +Themed.last("input").callback(cookie) +pending = requests[#requests] +Themed.last("progress_dialog").on_cancel() +Assert.is_true(pending.cancelled) +local cookie_count = #requests +pending.cb(response) +Assert.eq(#requests, cookie_count) +count = #requests +Login.new():cookieAsync("unrelated=1", done) +Assert.eq(#requests, count) +Assert.eq(reason, "没有读到知音漫客登录 Cookie") +local sms = require("moonsource_zymk.phone_login").new(function() end) +sms:start() +Assert.eq(Themed.last("input").fields[1].input_type, "number") +count = #requests +connected = false +Themed.last("input").callback(phone) +Assert.eq(#requests, count) +Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi") +connected = true +sms:start() +Themed.last("input").callback(phone) +pending = requests[#requests] +Themed.last("progress_dialog").on_cancel() +Assert.is_true(pending.cancelled) +pending.cb(JSON.encode({ status = 0 })) +Assert.is_nil(sms.session.sms_phone) +sms = require("moonsource_zymk.phone_login").new(function() end) +sms:start() +Themed.last("input").callback(phone) +requests[#requests].cb(JSON.encode({ status = 0 })) +local code_input = Themed.last("input") +Assert.eq(code_input.fields[1].label, "验证码") +count = #requests +code_input.actions[1].callback() +Assert.eq(#requests, count) +Assert.eq(Themed.last("input"), code_input) +Assert.eq(Themed.last("toast").text, "请稍后再获取验证码") +sms:cancel() diff --git a/tests/zymk/operations_spec.lua b/tests/zymk/operations_spec.lua new file mode 100644 index 0000000..98457da --- /dev/null +++ b/tests/zymk/operations_spec.lua @@ -0,0 +1,85 @@ +--[[-- +知音漫客开书与缓存:同步目录桩后取消在飞章节,旧缓存离线可用,空目录不崩。 + +@module tests.moonsource_zymk.operations_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local Themed = require("support.theme_stubs") +Themed.install() +local toc = { { idx = 1, uid = "123/first", toc_version = 1 }, { idx = 2, uid = "123/second" } } +local connected, cached, touched = true, false, nil +package.loaded["source.toc"] = { read = function() return toc end } +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +package.loaded["book.progress_db"] = { get = function() return { chapter_idx = 2 } end } +package.loaded["book.store"] = { + touch = function(path, _identity, meta) touched = { path, meta.chapter_idx }; return true end, +} +local pending, cancelled = nil, {} +package.loaded["moonsource_zymk.chapter"] = { + existing = function(_identity, chapter) return cached and "/" .. chapter.uid .. ".cbz" or nil end, + materializeAsync = function(_identity, _chapter, _progress, cb) + pending = cb + return { cancel = function() cancelled.chapter = true end } + end, + prefetchAsync = function(_identity, _toc, from, count, _opts, cb) + Assert.eq(from, 0) + Assert.eq(count, 2) + pending = cb + return { cancel = function() cancelled.cache = true end } + end, +} +local source = require("moonsource_zymk.source").new() +source.loadTocAsync = function(_self, _identity, cb) + cb(toc) + return { cancel = function() cancelled.toc = true end } +end +local identity = { source_id = "ext.zymk", stable_id = "book" } +local called = false +local handle = source:openBookAsync(identity, nil, function() called = true end) +Stubs.flush() +handle.cancel() +Assert.is_true(cancelled.chapter) +Assert.is_nil(cancelled.toc) +Assert.is_true(Themed.last("progress_dialog").closed) +pending("/first.cbz") +Assert.is_false(called) +Assert.is_nil(touched) + +handle = source:cacheAllChaptersAsync(identity, nil, function() called = true end) +handle.cancel() +Assert.is_true(cancelled.cache) +Assert.is_nil(cancelled.toc) +pending(2, 2, 0) +Assert.is_false(called) + +connected, cached = false, true +source:openBookAsync(identity, nil, function(path) Assert.eq(path, "/123/second.cbz") end) +Stubs.flush() +Assert.eq(touched[2], 2) +cached = false +source:openBookAsync(identity, nil, function(path, err) + Assert.is_nil(path) + Assert.eq(err, "网络不可用,请先连接 Wi-Fi") +end) +Stubs.flush() +toc, cached = {}, true +source:openBookAsync(identity, nil, function(path, err) + Assert.is_nil(path) + Assert.eq(err, "网络不可用,请先连接 Wi-Fi") +end) +Stubs.flush() + +source.loadTocAsync = function(_self, _identity, cb) + pending = cb + return { cancel = function() cancelled.toc = true end } +end +cancelled = {} +handle = source:cacheAllChaptersAsync(identity, nil, function() called = true end) +handle.cancel() +Assert.is_true(cancelled.toc) +Assert.is_nil(cancelled.cache) +pending(toc) +Assert.is_false(called) diff --git a/tests/zymk/reviews_spec.lua b/tests/zymk/reviews_spec.lua new file mode 100644 index 0000000..6a838ca --- /dev/null +++ b/tests/zymk/reviews_spec.lua @@ -0,0 +1,62 @@ +--[[-- +知音漫客整书评论:真实成功码、归属、空页、分页、网络与取消。 + +@module tests.moonsource_zymk.reviews_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +local Mapper = require("moonsource_zymk.mapper") +local row = { id = 1, ssid = 101, ssidtype = 0, uname = "测试读者", content = "

书评 & 文字

", createtime = 1700000000 } +local page = Mapper.reviews("101", 1, { status = 1, data = { row } }) +Assert.eq(page.items[1].text, "书评 & 文字") +Assert.eq(page.items[1].author, "测试读者") +Assert.matches(page.items[1].time, "^%d%d%d%d%-%d%d%-%d%d$") +Assert.is_false(page.more) +Assert.len(Mapper.reviews("101", 2, { status = 1, data = {} }).items, 0) +Assert.is_nil(Mapper.reviews("101", 1, { status = 0, data = { row } })) +Assert.is_nil(Mapper.reviews("102", 1, { status = 1, data = { row } })) +row.ssidtype = 1 +Assert.is_nil(Mapper.reviews("101", 1, { status = 1, data = { row } })) +row.ssidtype = 0 +local full = {} +for index = 1, 20 do full[index] = row end +page = Mapper.reviews("101", 2, { status = 1, data = full }) +Assert.is_true(page.more) +Assert.eq(page.pages, 3) + +package.loaded["json"] = JSON +local pending, cancelled = nil, false +package.loaded["http.request"] = { + get = function(url, _opts, cb) + Assert.matches(url, "^https://community%-hots%.321mh%.com/comment/newgets%?") + Assert.matches(url, "ssid=101") + Assert.matches(url, "ssidtype=0") + Assert.matches(url, "page=2") + pending = cb + return { cancel = function() cancelled = true end } + end, +} +local Client = require("moonsource_zymk.client") +Client.reviewsAsync("101", 2, function(data, err) + Assert.is_nil(err) + Assert.len(data.items, 1) +end) +pending(JSON.encode({ status = 1, data = { row } })) +Client.reviewsAsync("101", 2, function(data, err) + Assert.is_nil(data) + Assert.eq(err, "网络故障") +end) +pending(nil, "网络故障") +Client.reviewsAsync("101", 2, function(data, err) + Assert.is_nil(data) + Assert.eq(err, "响应无效") +end) +pending("bad json") +local called = false +local handle = Client.reviewsAsync("101", 2, function() called = true end) +handle.cancel() +Assert.is_true(cancelled) +pending(JSON.encode({ status = 1, data = { row } })) +Assert.is_false(called) diff --git a/tests/zymk/shelf_spec.lua b/tests/zymk/shelf_spec.lua new file mode 100644 index 0000000..6decba2 --- /dev/null +++ b/tests/zymk/shelf_spec.lua @@ -0,0 +1,118 @@ +--[[-- +知音漫客收藏:只读拉取、空快照、坏响应、离线、取消与换号隔离。 + +@module tests.moonsource_zymk.shelf_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local JSON = require("support.json_stub") +local Text = require("utils.text") +package.loaded["json"] = JSON +local cfg = { account = { type = "mkxq", openid = "synthetic-account" } } +local connected, expired, automatic = true, false, true +package.loaded["utils.settings"] = { getSource = function() return cfg end } +package.loaded["source.auth"] = { expired = function() return expired end } +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +local requests = {} +local data = { ubook = { { comic_id = 4982, comic_name = "测试漫画", addtime = 1700000000123 } } } +package.loaded["http.request"] = { post = function(url, body, opts, cb) + local request = { url = url, body = body, opts = opts, cb = cb } + requests[#requests + 1] = request + if automatic then cb(JSON.encode({ status = 0, data = data })) end + return { cancel = function() request.cancelled = true end } +end } +local written, options, calls = nil, nil, 0 +package.loaded["book.books_db"] = { + reconcile = function(source_id, books, opts) + Assert.eq(source_id, "ext.zymk") + written, options, calls = books, opts, calls + 1 + return true, 0 + end, +} +local Mapper = require("moonsource_zymk.mapper") +local Source = require("moonsource_zymk.source") +local source = Source.new() +local result, reason +local function done(value, err) result, reason = value, err end + +Assert.len(Mapper.shelf({}), 0) +Assert.len(Mapper.shelf({ urecord = {} }), 0) +Assert.is_nil(Mapper.shelf({ wrong = {} })) +Assert.is_nil(Mapper.shelf({ ubook = false })) +Assert.is_nil(Mapper.shelf({ ubook = { [2] = data.ubook[1] } })) +Assert.is_nil(Mapper.shelf({ ubook = { { comic_id = "bad", comic_name = "坏身份" } } })) +Assert.is_nil(Mapper.shelf({ ubook = { { comic_id = 1 } } })) + +source:syncBooksAsync({ force = true }, done) +Assert.eq(result.pulled, 1) +Assert.eq(result.pushed, 0) +Assert.is_false(result.skipped) +Assert.eq(written[1].stable_id, "4982") +Assert.eq(written[1].cover, Mapper.cover(4982)) +Assert.eq(written[1].inserted_at, 1700000000) +Assert.is_true(options.force) +Assert.is_true(options.inserted_at_from_row) +Assert.is_nil(options.allow_empty) +Assert.eq(requests[1].body, Text.formEncode(cfg.account), "不带 sync,不合并浏览器本地记录") +Assert.is_nil(requests[1].opts.headers.Cookie) +Assert.is_false(requests[1].opts.allow_redirects) +Assert.matches(requests[1].url, "^https://www%.zymk%.cn/apinew/getuserrecord/$") +local count = #requests +source:syncBooksAsync({ dirty_only = true }, done) +Stubs.flush() +Assert.is_true(result.skipped) +Assert.eq(#requests, count) + +data = {} +source:syncBooksAsync({ force = true }, done) +Assert.eq(result.pulled, 0) +Assert.is_nil(options.allow_empty, "空快照不能清空本地书架") +automatic = false +local reconciled = calls +source:syncBooksAsync(nil, done) +requests[#requests].cb("login") +Assert.is_nil(result) +Assert.eq(calls, reconciled) +Assert.eq(reason, "登录响应无效") +source:syncBooksAsync(nil, done) +requests[#requests].cb(nil, "network failed") +Assert.eq(reason, "network failed") +Assert.eq(calls, reconciled) +local handle = source:syncBooksAsync(nil, done) +local pending = requests[#requests] +handle.cancel() +pending.cb(JSON.encode({ status = 0, data = data })) +Assert.is_true(pending.cancelled) +Assert.eq(calls, reconciled) + +source:syncBooksAsync(nil, done) +pending = requests[#requests] +local account = cfg.account +cfg.account = { type = "mkxq", openid = "another-account" } +pending.cb(JSON.encode({ status = 0, data = data })) +Assert.eq(reason, "登录状态已变化,请重试") +Assert.eq(calls, reconciled) +count = #requests +source:syncBooksAsync(nil, done) +Stubs.flush() +Assert.eq(#requests, count) +Assert.eq(reason, "登录状态已变化,请重试") +cfg.account = account +connected = false +source:syncBooksAsync(nil, done) +Stubs.flush() +Assert.eq(reason, "网络不可用,请先连接 Wi-Fi") +Assert.eq(#requests, count) +connected, expired = true, true +source:syncBooksAsync(nil, done) +Stubs.flush() +Assert.eq(reason, "请先登录知音漫客") +Assert.eq(#requests, count) +cfg.account = nil +Source.new():syncBooksAsync(nil, done) +Stubs.flush() +Assert.is_true(result.skipped) +Assert.eq(#requests, count) +Assert.is_false(source:capabilities().shelf_push)