From b41273ef9b08672cdd92e732da4a93f7cc1720c6 Mon Sep 17 00:00:00 2001 From: Garfield Date: Mon, 16 Nov 2026 12:07:59 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=E5=88=9D=E5=A7=8B=E6=8F=90?= =?UTF-8?q?=E4=BA=A4=EF=BC=9A=E6=9C=88=E8=AF=BB=E7=AC=AC=E4=B8=89=E6=96=B9?= =?UTF-8?q?=E4=B9=A6=E6=BA=90=E6=8F=92=E4=BB=B6=E9=9B=86=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- moonsource-kuaikan.koplugin/README.md | 21 + moonsource-kuaikan.koplugin/_meta.lua | 5 + moonsource-kuaikan.koplugin/main.lua | 9 + moonsource-kuaikan.koplugin/moon_source.lua | 15 + .../moonsource_kuaikan/_meta.lua | 15 + .../moonsource_kuaikan/chapter.lua | 162 +++++ .../moonsource_kuaikan/client.lua | 584 ++++++++++++++++++ .../moonsource_kuaikan/l10n/en.lua | 74 +++ .../moonsource_kuaikan/l10n/zh_TW.lua | 74 +++ .../moonsource_kuaikan/loadmeta.lua | 5 + .../moonsource_kuaikan/login.lua | 258 ++++++++ .../moonsource_kuaikan/mapper.lua | 341 ++++++++++ .../moonsource_kuaikan/page.lua | 239 +++++++ .../moonsource_kuaikan/phone_login.lua | 149 +++++ .../moonsource_kuaikan/qrlogin.lua | 104 ++++ .../moonsource_kuaikan/setting.lua | 134 ++++ .../moonsource_kuaikan/source.lua | 397 ++++++++++++ .../moonsource_kuaikan/verify.lua | 113 ++++ .../web/kuaikan_verify.html | 25 + .../moonsource_kuaikan/web/kuaikan_verify.js | 98 +++ tests/kuaikan/browse_spec.lua | 103 +++ tests/kuaikan/chapter_spec.lua | 92 +++ tests/kuaikan/client_spec.lua | 307 +++++++++ tests/kuaikan/login_spec.lua | 245 ++++++++ tests/kuaikan/mobile_spec.lua | 128 ++++ tests/kuaikan/operations_spec.lua | 69 +++ tests/kuaikan/phone_login_spec.lua | 109 ++++ tests/kuaikan/qrlogin_spec.lua | 88 +++ tests/kuaikan/reviews_spec.lua | 72 +++ tests/kuaikan/setting_spec.lua | 91 +++ tests/kuaikan/shelf_spec.lua | 109 ++++ tests/kuaikan/sync_spec.lua | 241 ++++++++ tests/kuaikan/verify_spec.lua | 93 +++ tests/kuaikan/web_spec.js | 85 +++ tests/kuaikan/web_spec.lua | 11 + 35 files changed, 4665 insertions(+) create mode 100644 moonsource-kuaikan.koplugin/README.md create mode 100644 moonsource-kuaikan.koplugin/_meta.lua create mode 100644 moonsource-kuaikan.koplugin/main.lua create mode 100644 moonsource-kuaikan.koplugin/moon_source.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/_meta.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/chapter.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/client.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/l10n/en.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/l10n/zh_TW.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/loadmeta.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/login.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/mapper.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/page.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/phone_login.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/qrlogin.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/setting.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/source.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/verify.lua create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/web/kuaikan_verify.html create mode 100644 moonsource-kuaikan.koplugin/moonsource_kuaikan/web/kuaikan_verify.js create mode 100644 tests/kuaikan/browse_spec.lua create mode 100644 tests/kuaikan/chapter_spec.lua create mode 100644 tests/kuaikan/client_spec.lua create mode 100644 tests/kuaikan/login_spec.lua create mode 100644 tests/kuaikan/mobile_spec.lua create mode 100644 tests/kuaikan/operations_spec.lua create mode 100644 tests/kuaikan/phone_login_spec.lua create mode 100644 tests/kuaikan/qrlogin_spec.lua create mode 100644 tests/kuaikan/reviews_spec.lua create mode 100644 tests/kuaikan/setting_spec.lua create mode 100644 tests/kuaikan/shelf_spec.lua create mode 100644 tests/kuaikan/sync_spec.lua create mode 100644 tests/kuaikan/verify_spec.lua create mode 100644 tests/kuaikan/web_spec.js create mode 100644 tests/kuaikan/web_spec.lua diff --git a/moonsource-kuaikan.koplugin/README.md b/moonsource-kuaikan.koplugin/README.md new file mode 100644 index 0000000..cbe0280 --- /dev/null +++ b/moonsource-kuaikan.koplugin/README.md @@ -0,0 +1,21 @@ +# 快看漫画 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 微信扫码登录 | 支持 | 独立候选会话,保存前校验账号 | +| 密码与短信登录 | 已实现,未实测 | 手机扫码完成腾讯安全验证;新登录完整链路未分别验证 | +| 浏览器登录与 Cookie 导入 | 支持 | 手动粘贴或扩展回传,扩展完整握手未实测 | +| 书架拉取 | 支持 | 分页读取官网收藏 | +| 书架新增与移出 | 已实现,未实测 | 本地先生效,写后完整回读;失败保留脏行或墓碑 | +| 搜索与分类书城 | 支持 | 动态题材、地区、资费、状态和排序,默认聚合 60 本 | +| 详情与完整目录 | 支持 | 保留作品及每话 ID、官网顺序和缓存路径 | +| 免费与已购漫画 | 支持 | 以服务端权限为准,下载为 CBZ;未购明确拒绝 | +| 章节与全本缓存 | 支持 | 已完成话可复用,失败可重试;整部作品下载未实测 | +| 离线阅读 | 支持 | 已缓存 CBZ、目录及本地位置可用 | +| 阅读进度同步 | 部分支持 | 回读只能确认话 ID,不支持云端页内比例;本地页内位置保留 | +| 笔记与统计同步 | 不支持 | 仅本地保存 | +| 独立整书书评 | 不支持 | 详情「书评」实际是话题页的首话评论,窗口明确标注 | +| 每话章评 | 支持 | 开启「章节评论」后在 CBZ 末页显示,支持分页、切话隔离和离线缓存 | +| 段评 | 不支持 | 当前 Web 协议未找到段落定位接口 | +| 评论回复与写操作 | 不支持 | 未接回复分页、发评、点赞或删评 | +| 账号切换 | 部分支持 | 同账号可续期;换号须先退出清理旧数据,未同步记录会丢失 | diff --git a/moonsource-kuaikan.koplugin/_meta.lua b/moonsource-kuaikan.koplugin/_meta.lua new file mode 100644 index 0000000..a2db52c --- /dev/null +++ b/moonsource-kuaikan.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:快看漫画"), + description = _("给月读增加「快看漫画」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-kuaikan.koplugin/main.lua b/moonsource-kuaikan.koplugin/main.lua new file mode 100644 index 0000000..e525d69 --- /dev/null +++ b/moonsource-kuaikan.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_kuaikan", + is_doc_only = false, +} diff --git a/moonsource-kuaikan.koplugin/moon_source.lua b/moonsource-kuaikan.koplugin/moon_source.lua new file mode 100644 index 0000000..9e929a4 --- /dev/null +++ b/moonsource-kuaikan.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_kuaikan.source").meta() end, + new = function() return require("moonsource_kuaikan.source").new() end, + setting = lazy("moonsource_kuaikan.setting"), +} diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/_meta.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/_meta.lua new file mode 100644 index 0000000..29e3e42 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/_meta.lua @@ -0,0 +1,15 @@ +--[[-- +书源元信息。 + +@module moonsource_kuaikan._meta +--]] + +local _ = require("l10n").get("moonsource_kuaikan") + +return { + id = "ext.kuaikan", + name = _("快看漫画"), + type = "chapter", + description = _("快看漫画在线阅读"), + abilities = { _("微信扫码登录"), _("密码登录"), _("短信登录"), _("书架同步"), _("阅读进度同步"), _("搜索与发现"), _("话题页评论(首话)"), _("章节评论"), _("缓存章节") }, +} diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/chapter.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/chapter.lua new file mode 100644 index 0000000..44d46c9 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/chapter.lua @@ -0,0 +1,162 @@ +--[[-- +快看漫画章节图片下载与 CBZ 打包。 + +@module moonsource_kuaikan.chapter +--]] + +local Cbz = require("source.cbz") +local Client = require("moonsource_kuaikan.client") +local Image = require("utils.image") +local Paths = require("utils.paths") +local _ = require("l10n").get("moonsource_kuaikan") + +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 .. ".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 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("kuaikan callback", function() + if not state.cancelled then cb(archive_path) 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 i, url in ipairs(urls) do + paths[i] = image_dir .. "/" .. string.format("%04d%s", i, 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 + if on_progress then on_progress(current, #urls) end + current = current + 1 + require("ui/uimanager"):nextTick(require("ui.guard").wrap("kuaikan 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 + if on_progress then on_progress(current, #urls) end + current = current + 1 + require("ui/uimanager"):nextTick(require("ui.guard").wrap("kuaikan 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("kuaikan step", step)) + else + UIManager:nextTick(require("ui.guard").wrap("kuaikan step", step)) + end + end) + end + UIManager:nextTick(require("ui.guard").wrap("kuaikan step", step)) + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +return Chapter diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/client.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/client.lua new file mode 100644 index 0000000..7b6944d --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/client.lua @@ -0,0 +1,584 @@ +--[[-- +快看漫画网页接口。 + +搜索和首页是 JSON。目录在话题页 HTML 里。页图要先拿挑战接口的 `kk_s_t`, +再按页面脚本的算法算出 `answer`。公共请求不携带账号 Cookie。 + +@module moonsource_kuaikan.client +--]] + +local JSON = require("json") +local Mapper = require("moonsource_kuaikan.mapper") +local Page = require("moonsource_kuaikan.page") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_kuaikan") + +local Client = {} +Client.login_revision = 0 + +local HOST = "https://www.kuaikanmanhua.com" +Client.LOGIN_URL = HOST .. "/webs/loginh" +Client.ACCOUNT_URL = HOST .. "/v2/pweb/user_info/get" +local ALPHA = "BtMTUlesLXPIFjfcbGYWyqQxROzAHNDCwmiKpdhvkSrEungZoJaV" +local PREFIX = "20200820" + +---@return table +local function opts(extra) + local out = { timeout = require("http.timeout").net(1) } + if extra then + for key, value in pairs(extra) do out[key] = value end + end + return out +end + +---@param res table|nil +---@return string|nil +local function cookieOf(res) + local lines = {} + if Request.headerAll then + lines = Request.headerAll(res, "set-cookie") or {} + else + local line = Request.header(res, "set-cookie") + if type(line) == "string" then lines = { line } end + end + for _idx, line in ipairs(lines) do + local value = type(line) == "string" and line:match("kk_s_t=([^;]+)") or nil + if value and value ~= "" then return value end + end + return nil +end + +--- 页面 `getSign` 的结果。indexes 是 16 个 0..15 的下标,缺省用随机数。 +---@param cookie string +---@param indexes integer[]|nil +---@return string +function Client.answer(cookie, indexes) + local rand = {} + for slot = 1, 16 do + local index = indexes and indexes[slot] or math.random(0, 15) + rand[#rand + 1] = tostring(index) .. ALPHA:sub(index + 1, index + 1) + end + local rand_s = table.concat(rand) + local body = PREFIX .. rand_s .. cookie + if #body % 2 ~= 0 then body = body .. "0" end + local mid = #body / 2 + local slice = body:sub(mid - 16 + 1, mid + 16) + return Text.base64Encode(table.concat({ PREFIX, rand_s, cookie, slice }, "_")) +end + +--- 登录态在 settings.cookie。页图还要拼上挑战接口的 kk_s_t。 +---@param headers table|nil +---@return table|nil +local function withCookie(headers, cookie) + if cookie == nil then cookie = require("utils.settings").getSource("ext.kuaikan").cookie end + local saved = type(cookie) == "string" and cookie or "" + if saved == "" then return headers end + headers = headers or {} + if type(headers.Cookie) == "string" and headers.Cookie ~= "" then + local pairs = {} + for pair in saved:gmatch("[^;]+") do + if pair:match("^%s*([^=%s]+)%s*=") ~= "kk_s_t" then + pairs[#pairs + 1] = Text.trim(pair) + end + end + saved = table.concat(pairs, "; ") + if saved ~= "" then headers.Cookie = saved .. "; " .. headers.Cookie end + else + headers.Cookie = saved + end + return headers +end + +---@param url string +---@param headers table|nil +---@param cb fun(raw: string|nil, err: string|nil, res: table|nil) +---@return HttpJob +local function get(url, headers, cb, uncached) + headers = headers or {} + -- 默认 UA 会被收藏接口挂住,网页 UA 才能回包。 + if not headers["User-Agent"] then headers["User-Agent"] = "Mozilla/5.0" end + headers["User-Agent-PC"] = "PCKuaikan/1.0.0/100000(Mac;10.15.7;Chrome;pckuaikan;1800*2880;564)" + return Request.get(url, opts({ headers = headers, cache_ttl = (uncached or headers.Cookie) and 0 or nil }), cb) +end + +--- 登录会话只访问官网和微信开放平台;第三方域绝不附带快看 Cookie。 +---@param url string +---@param cookie string|nil +---@param cb fun(raw: string|nil, err: any, res: table|nil) +---@param fields table|nil POST 表单;nil 为 GET +---@return HttpJob +function Client.loginRequestAsync(url, cookie, cb, fields, method) + method = method or (fields and "POST" or "GET") + local official = url:sub(1, #HOST + 1) == HOST .. "/" + if not official and not url:match("^https://open%.weixin%.qq%.com/") + and not url:match("^https://long%.open%.weixin%.qq%.com/") then + return require("source.base").defer(cb, nil, _("登录响应无效")) + end + local headers = { + ["User-Agent"] = "Mozilla/5.0", + ["User-Agent-PC"] = "PCKuaikan/1.0.0/100000(Mac;10.15.7;Chrome;pckuaikan;1800*2880;564)", + Referer = official and Client.LOGIN_URL or "https://open.weixin.qq.com/", + } + if official and cookie and cookie ~= "" then headers.Cookie = cookie end + local options = opts({ headers = headers, cache_ttl = 0, + timeout = math.min(require("http.timeout").net(1), 30) }) + local callback = require("ui.guard").wrap("kuaikan login", cb) + if method == "DELETE" and official then + options.url, options.method, options.body = url, method, "" + return Request.request(options, function(res, err) + callback(not err and res and res.body or nil, err, res) + end) + end + if method ~= "GET" and method ~= "POST" then + return require("source.base").defer(cb, nil, _("响应无效")) + end + if fields then + if not official then return require("source.base").defer(cb, nil, _("登录响应无效")) end + options.content_type = "application/x-www-form-urlencoded" + return Request.post(url, Text.formEncode(fields), options, callback) + end + return Request.get(url, options, callback) +end + +--- 账号校验响应;登录失效与临时网络错误分开。 +---@param raw string|nil +---@param err any +---@param res table|nil +---@return { user_id: string }|nil +---@return string|nil +---@return boolean|nil +function Client.accountResponse(raw, err, res) + local status = res and tonumber(res.code) + local location = Request.header(res, "Location") + if status == 401 or (status and status >= 300 and status < 400 + and type(location) == "string" + and (location == "/webs/loginh" or location:sub(1, #"/webs/loginh?") == "/webs/loginh?" + or location == Client.LOGIN_URL or location:sub(1, #Client.LOGIN_URL + 1) == Client.LOGIN_URL .. "?")) then + return nil, _("快看登录已失效,请重新登录"), true + end + if not raw or raw == "" or err then return nil, err and tostring(err) or _("请求失败") end + local ok, wire = pcall(JSON.decode, raw) + if not ok then return nil, _("登录响应无效") end + local account, reason = Mapper.account(wire) + if reason == "unauthorized" then return nil, _("快看登录已失效,请重新登录"), true end + if not account then return nil, _("登录响应无效") end + return account +end + +---@param keyword string +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return HttpJob +function Client.searchAsync(keyword, cb) + local url = HOST .. "/search/web/complex?f=3&q=" .. Text.urlEncode(keyword) + return get(url, nil, function(raw, err) + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then cb(nil, _("请求失败")); return end + local books = Mapper.search(wire) + if not books then cb(nil, _("请求失败")); return end + cb(books) + end) +end + +---@param cb fun(books: Book[]|nil, err: string|nil) +---@param cookie string|nil 本轮已校验的 Cookie;缺省取当前配置 +---@return { cancel: fun() } +function Client.favAsync(cb, cookie) + if cookie == nil then cookie = require("utils.settings").getSource("ext.kuaikan").cookie or "" end + local cancelled, active = false, nil + local offset, collected, seen = 0, {}, {} + local function nextPage() + local pending = true + local job = get(HOST .. "/v2/pweb/fav/topics?since=" .. offset .. "&limit=20", + withCookie({ Referer = HOST .. "/webs/booklist" }, cookie), function(raw, err) + pending, active = false, nil + if cancelled then return end + if not raw or raw == "" or err then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then cb(nil, _("响应无效")); return end + local books, total = Mapper.fav(wire) + if not books or not total or offset + #books > total or (#books == 0 and offset < total) then + cb(nil, _("响应无效")); return + end + local added = 0 + for _index, book in ipairs(books) do + if not seen[book.stable_id] then + seen[book.stable_id] = true + collected[#collected + 1] = book + added = added + 1 + end + end + if #books > 0 and added == 0 then cb(nil, _("响应无效")); return end + offset = offset + #books + if offset >= total then cb(collected); return end + nextPage() + end, true) + if pending then active = job end + end + nextPage() + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +--- 有稳定账号身份的登录态默认同步,真实有效性由请求前的账号校验确认。 +---@return boolean +function Client.hasAccount() + local cfg = require("utils.settings").getSource("ext.kuaikan") + return type(cfg.cookie) == "string" and cfg.cookie ~= "" + and type(cfg.user_id) == "string" and cfg.user_id ~= "" +end + +---@class KuaikanSync +---@field cookie string +---@field previous_cookie string|nil +---@field user_id string|nil +---@field revision integer +---@field writing boolean +---@field cancelled boolean|nil +---@field job CancelHandle|nil +---@field push_error string|nil +local Sync = {} +Sync.__index = Sync + +---@param writing boolean|nil +---@return KuaikanSync +function Client.newSync(writing) + local cfg = require("utils.settings").getSource("ext.kuaikan") + return setmetatable({ + cookie = cfg.cookie or "", previous_cookie = cfg.cookie, user_id = cfg.user_id, + revision = Client.login_revision, writing = writing == true, + }, Sync) +end + +---@return boolean +function Sync:current() + local cfg = require("utils.settings").getSource("ext.kuaikan") + return not self.cancelled and self.revision == Client.login_revision + and cfg.cookie == self.previous_cookie and cfg.user_id == self.user_id + and (not self.writing or self.user_id ~= nil) +end + +function Sync:cancel() + self.cancelled = true + if self.job then self.job:cancel(); self.job = nil end +end + +---@param path string +---@param cb fun(raw: string|nil, err: any, res: table|nil) +---@param fields table|nil +---@param method string|nil +---@param anonymous boolean|nil +function Sync:request(path, cb, fields, method, anonymous) + if not self:current() then cb(nil, _("登录状态已变化,请重试")); return end + local pending = true + local job = Client.loginRequestAsync(HOST .. path, anonymous and "" or self.cookie, function(raw, err, res) + pending, self.job = false, nil + if self.cancelled then return end + if not self:current() then cb(nil, _("登录状态已变化,请重试")); return end + cb(raw, err, res) + end, fields, method) + if pending then self.job = job end +end + +---@param cb fun(account: table|nil, err: string|nil) +function Sync:checkAsync(cb) + if not require("ui/network/manager"):isConnected() then + return require("source.base").defer(cb, nil, _("网络不可用,请先连接 Wi-Fi")) + end + self:request("/v2/pweb/user_info/get", function(raw, err, res) + local account, reason, expired = Client.accountResponse(raw, err, res) + if not account then + if expired then require("source.auth").expire("ext.kuaikan", reason) end + cb(nil, reason) + elseif self.user_id and tostring(self.user_id) ~= account.user_id then + cb(nil, _("登录状态已变化,请重试")) + else + require("source.auth").ok("ext.kuaikan") + cb(account) + end + end) + return self +end + +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return KuaikanSync +function Sync:shelfSyncAsync(cb) + if not self:current() then cb(nil, _("登录状态已变化,请重试")); return self end + local pending = true + local job = Client.favAsync(function(books, err) + pending, self.job = false, nil + if self.cancelled then return end + if not self:current() then cb(nil, _("登录状态已变化,请重试")); return end + cb(books, err) + end, self.cookie) + if pending then self.job = job end + return self +end + +---@param raw string|nil +---@param err any +---@return table|nil +---@return string|nil +local function syncResponse(raw, err) + if err or not raw or raw == "" then return nil, err and tostring(err) or _("请求失败") end + local ok, wire = pcall(JSON.decode, raw) + if not ok or type(wire) ~= "table" then return nil, _("响应无效") end + if tonumber(wire.code) ~= 200 then + return nil, type(wire.message) == "string" and wire.message ~= "" and wire.message or _("请求失败") + end + return wire +end + +---@param stable_id string +---@param adding boolean +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return KuaikanSync +function Sync:changeShelfAsync(stable_id, adding, cb) + local function finish(ok, err) + if not ok then self.push_error = self.push_error or err or _("请求失败") end + cb(ok, err) + end + if not self.writing then finish(nil, _("登录状态已变化,请重试")); return self end + self:request("/v1/aegis/api/web/challenge?callback=callback_1", function(raw, err, res) + local challenge = not err and raw and cookieOf(res) + if not challenge then finish(nil, err and tostring(err) or _("响应无效")); return end + self.cookie = withCookie({ Cookie = "kk_s_t=" .. challenge }, self.cookie).Cookie + local path = "/web/topic/" .. Text.urlEncode(stable_id) .. "/fav?answer=" .. Text.urlEncode(Client.answer(challenge)) + self:request(path, function(body, write_err) + local wire, reason = syncResponse(body, write_err) + if not wire then finish(nil, reason); return end + self:shelfSyncAsync(function(books, read_err) + if not books then finish(nil, read_err); return end + local found = false + for _index, book in ipairs(books) do + if book.stable_id == stable_id then found = true; break end + end + if found ~= adding then finish(nil, _("快看收藏变更尚未确认")); return end + finish(true) + end) + end, adding and {} or nil, adding and "POST" or "DELETE") + end, nil, nil, true) + return self +end + +function Sync:addToShelfAsync(stable_id, cb) + return self:changeShelfAsync(stable_id, true, cb) +end + +function Sync:removeFromShelfAsync(stable_id, cb) + return self:changeShelfAsync(stable_id, false, cb) +end + +--- history.read_count 是已读话数,不是章内图片数。 +---@param stable_id string +---@param cb fun(comic_id: string|nil, err: string|nil) +---@return KuaikanSync +function Sync:historyAsync(stable_id, cb) + local offset, seen = 0, {} + local function nextPage() + self:request("/v2/pweb/read/history/list?since=" .. offset .. "&limit=20", function(raw, err) + local wire, reason = syncResponse(raw, err) + if not wire then cb(nil, reason); return end + local data = wire.data + local rows = type(data) == "table" and data.topics + local total = type(data) == "table" and data.total + if type(rows) ~= "table" or type(total) ~= "number" or total < 0 or total % 1 ~= 0 + or offset + #rows > total or #rows == 0 and offset < total then + cb(nil, _("响应无效")); return + end + local added = 0 + for _index, row in ipairs(rows) do + if type(row) ~= "table" or row.topic_id == nil or row.comic_id == nil then + cb(nil, _("响应无效")); return + end + local key = tostring(row.topic_id) + if not seen[key] then seen[key], added = true, added + 1 end + if key == stable_id then cb(tostring(row.comic_id)); return end + end + if #rows > 0 and added == 0 then cb(nil, _("响应无效")); return end + offset = offset + #rows + if offset >= total then cb(nil); return end + nextPage() + end) + end + nextPage() + return self +end + +---@param record table +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return KuaikanSync +function Sync:reportProgressAsync(record, cb) + if not self.writing then cb(nil, _("登录状态已变化,请重试")); return self end + self:request("/v2/pweb/read/history/report", function(raw, err) + local wire, reason = syncResponse(raw, err) + if not wire then cb(nil, reason); return end + self:historyAsync(tostring(record.topic_id), function(comic_id, read_err) + if read_err then cb(nil, read_err) + elseif comic_id ~= tostring(record.comic_id) then cb(nil, _("快看进度变更尚未确认")) + else cb(true) end + end) + end, { view_rate = JSON.encode({ record }) }) + return self +end + +function Client.homeAsync(cb) + return get(HOST .. "/v2/pweb/home", nil, function(raw, err) + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then cb(nil, _("请求失败")); return end + local books = Mapper.home(wire) + if not books then cb(nil, _("请求失败")); return end + cb(books) + end) +end + +---@param node string +---@param page integer +---@param cb fun(books: Book[]|nil, err: string|nil, more: boolean|nil, groups: StoreChipGroup[]|nil) +function Client.storeAsync(node, page, cb) + local tag, region, pays, state, sort = Mapper.storeNode(node):match("^(%d+):(%d+):(%d+):(%d+):(%d+)$") + local url = HOST .. "/search/mini/topic/multi_filter?page=" .. page + .. "&size=48&tag_id=" .. tag .. "&label_dimension_origin=" .. region + .. "&pay_status=" .. pays .. "&update_status=" .. state .. "&sort=" .. sort + return get(url, nil, function(raw, err) + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then cb(nil, _("响应无效")); return end + local books, groups, more = Mapper.store(wire, node, page) + if not books then cb(nil, _("响应无效")); return end + cb(books, nil, more, groups) + end) +end + +---@param stable_id string +---@param cb fun(page: table|nil, err: string|nil) +---@return HttpJob +function Client.topicAsync(stable_id, cb) + local url = HOST .. "/web/topic/" .. Text.urlEncode(stable_id) .. "/" + return get(url, { Referer = HOST .. "/" }, function(raw, err) + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local page = Page.topic(raw) + if not page then cb(nil, _("漫画目录为空")); return end + cb(page) + end) +end + +--- 一话的页图。锁定的话返回「本章未购买」。 +---@param comic_id string +---@param cb fun(urls: string[]|nil, err: string|nil) +---@return HttpJob +function Client.imagesAsync(comic_id, cb) + local state = { cancelled = false, job = nil } + local cfg = require("utils.settings").getSource("ext.kuaikan") + local saved_cookie, saved_id, logged_in = cfg.cookie or "", cfg.user_id, cfg.logged_in == true + local challenged = false + local challenge = get(HOST .. "/v1/aegis/api/web/challenge?callback=callback_1", nil, function(_body, err, res) + challenged = true + if state.cancelled then return end + state.job = nil + local cookie = cookieOf(res) + if not cookie then cb(nil, err and tostring(err) or _("请求失败")); return end + local answer = Client.answer(cookie) + local url = HOST .. "/v2/pweb/comic/" .. comic_id .. "?source=&answer=" .. Text.urlEncode(answer) + local loaded = false + local image_job = get(url, withCookie({ + Cookie = "kk_s_t=" .. cookie, + Referer = HOST .. "/webs/comic-next/" .. comic_id, + width = "564", + }, saved_cookie), function(raw, image_err) + loaded = true + if state.cancelled then return end + state.job = nil + if not raw or raw == "" then cb(nil, image_err and tostring(image_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 + if not logged_in then cb(nil, _("本章未购买")); return end + local checked = false + local account_job = Client.loginRequestAsync(Client.ACCOUNT_URL, saved_cookie, function(account_raw, account_err, account_res) + checked = true + if state.cancelled then return end + state.job = nil + local account, reason, expired = Client.accountResponse(account_raw, account_err, account_res) + if expired then + local current = require("utils.settings").getSource("ext.kuaikan") + if current.cookie == saved_cookie and current.user_id == saved_id then + require("source.auth").expire("ext.kuaikan", reason) + else + reason = _("登录状态已变化,请重试") + end + end + cb(nil, account and _("本章未购买") or reason) + end) + if not checked then state.job = account_job end + return + end + if not urls then cb(nil, _("章节图片解析失败")); return end + cb(urls) + end) + if not loaded then state.job = image_job end + end, true) + if not challenged then state.job = challenge end + return { cancel = function() + state.cancelled = true + if state.job then state.job.cancel() end + end } +end + +---@param comic_id string +---@param offset integer +---@param cb fun(items: table[]|nil, err: string|nil, pages: integer|nil, pagination: {total: integer, max_idx: integer, more: boolean}|nil) +function Client.commentPageAsync(comic_id, offset, cb) + local url = HOST .. "/v2/comments/comic/" .. Text.urlEncode(comic_id) + .. "/order/score?offset=" .. offset .. "&limit=50&total=true" + return get(url, { Referer = HOST .. "/webs/comic-next/" .. Text.urlEncode(comic_id) }, function(raw, err) + if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if not ok then cb(nil, _("响应无效")); return end + local items, total = Mapper.comments(wire) + if not items or not total then cb(nil, _("快看漫画书评加载失败")); return end + local next_idx = offset + #wire.data.comments + cb(items, nil, math.max(1, math.ceil(total / 50)), { + total = total, max_idx = next_idx, more = #wire.data.comments > 0 and next_idx < total, + }) + end) +end + +--- 话题页评论。目标是话题信息里的 first_comic_id,按热度取第一页 50 条。 +---@param stable_id string +---@param cb fun(items: table[]|nil, err: string|nil, pages: integer|nil) +---@return { cancel: fun() } +function Client.commentsAsync(stable_id, cb) + local state = { cancelled = false, job = nil } + local loaded = false + local topic_job = Client.topicAsync(stable_id, function(page, err) + loaded = true + if state.cancelled then return end + state.job = nil + if not page then cb(nil, err or _("快看漫画书评加载失败")); return end + local info = page.info + local comic_id = type(info) == "table" and info.first_comic_id or nil + local id = (type(comic_id) == "number" or type(comic_id) == "string") and tostring(comic_id) or "" + if id == "" or id == "0" then cb(nil, _("快看漫画书评加载失败")); return end + local fetched = false + local comment_job = Client.commentPageAsync(id, 0, function(items, get_err, pages) + fetched = true + if state.cancelled then return end + state.job = nil + cb(items, get_err, pages) + end) + if not fetched then state.job = comment_job end + end) + if not loaded then state.job = topic_job end + return { cancel = function() + state.cancelled = true + if state.job and state.job.cancel then state.job.cancel() end + end } +end + +return Client diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/l10n/en.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/l10n/en.lua new file mode 100644 index 0000000..f0bd6af --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/l10n/en.lua @@ -0,0 +1,74 @@ +return { + ["在章末显示本章讨论,不是段落评论"] = "Show this chapter's discussion at the end, not paragraph comments.", + ["密码登录"] = "Password sign-in", + ["短信登录"] = "SMS sign-in", + ["快看密码登录"] = "Kuaikan password sign-in", + ["快看短信登录"] = "Kuaikan SMS sign-in", + ["快看安全验证"] = "Kuaikan security verification", + ["请输入密码"] = "Enter your password.", + ["登录前请阅读并同意快看用户协议和隐私协议"] = "Before signing in, read and agree to the Kuaikan terms and privacy policy.", + ["用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"] = "Scan with a phone on the same Wi-Fi to complete security verification. Enter your phone number, password and SMS code only on the device.", + ["请完成下方安全验证"] = "Complete the security verification below.", + ["验证已提交,请回到设备查看结果。"] = "Verification submitted. Return to the device to see the result.", + ["验证或登录失败,请回到设备查看并重试"] = "Verification or sign-in failed. Return to the device for details and try again.", + ["滑块加载失败,请检查网络后刷新网页"] = "Could not load the slider. Check your connection and refresh the page.", + ["快看漫画账号"] = "Kuaikan account", + ["快看登录 Cookie"] = "Kuaikan login Cookie", + ["在快看官网登录后,复制请求标头里的完整 Cookie"] = "Sign in on the official Kuaikan website and copy the complete Cookie request header.", + ["快看登录已失效,请重新登录"] = "Your Kuaikan session has expired. Please sign in again.", + ["旧快看账号身份无法确认,请先退出旧登录后重试"] = "The previous Kuaikan account could not be identified. Sign out of the old session before retrying.", + ["快看收藏变更尚未确认"] = "The Kuaikan favourite change could not be confirmed.", + ["快看进度变更尚未确认"] = "The Kuaikan progress change could not be confirmed.", + ["快看云端章节不在当前目录中"] = "The cloud chapter is not in the current Kuaikan table of contents.", + ["阅读进度同步"] = "Reading progress sync", + ["请先退出旧快看账号,再登录其他账号"] = "Sign out of the previous Kuaikan account before signing in to another account.", + ["确定退出快看账号?"] = "Sign out of Kuaikan?", + ["地区"] = "Region", + ["国漫"] = "Chinese comics", + ["韩漫"] = "Korean comics", + ["日漫"] = "Japanese comics", + ["VIP抢先看"] = "VIP early access", + ["最火热"] = "Most popular", + ["新上架"] = "New arrivals", + ["话题页评论(首话)"] = "Topic comments (first episode)", + ["国际区号"] = "Country calling code", + ["请输入有效的手机号和国际区号"] = "Enter a valid phone number and country calling code.", + ["请稍后再获取验证码"] = "Please wait before requesting another code.", + ["验证码已发送"] = "Verification code sent", + ["正在处理,请稍候"] = "Processing, please wait.", + ["请先获取该手机号的验证码,再填写验证码登录"] = "Request a code for this phone number, then enter it to sign in.", + ["登录状态已变化,请重试"] = "The login session changed. Please retry.", + ["登录响应无效"] = "Invalid sign-in response", + ["章节评论"] = "Chapter comments", + ["快看漫画"] = "Kuaikan", + ["快看漫画在线阅读"] = "Kuaikan comics", + ["快看漫画书评加载失败"] = "Could not load Kuaikan reviews", + ["获取验证码"] = "Get code", + ["用微信扫一扫"] = "Scan with WeChat", + ["本章未购买"] = "This chapter has not been purchased", + ["价格"] = "Price", + ["免费"] = "Free", + ["付费"] = "Paid", + ["连载中"] = "Ongoing", + ["已完结"] = "Completed", + ["验证已过期,请重新发起验证"] = "Verification expired. Please start again", + ["重新获取二维码"] = "Get a new QR code", + ["微信扫码登录"] = "WeChat QR login", + ["正在准备漫画…"] = "Preparing comic…", + ["正在获取二维码…"] = "Fetching QR code…", + ["漫画目录为空"] = "Comic chapter list is empty", + ["章节目录保存失败"] = "Failed to save chapter list", + ["章节图片解析失败"] = "Failed to parse chapter images", + ["已在微信中拒绝登录"] = "Login declined in WeChat", + ["手机号"] = "Phone number", + ["同意并继续"] = "Agree and continue", + ["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "Cannot open remote verification. Connect to Wi-Fi and enable Remote management first.", + ["验证已取消"] = "Verification cancelled", + ["验证凭据无效"] = "Invalid verification proof", + ["正在提交验证…"] = "Submitting verification…", + ["验证失败,请重新验证"] = "Verification failed. Please try again", + ["重试"] = "Retry", + ["书架同步"] = "Shelf sync", + ["搜索与发现"] = "Search and discover", + ["登录后,在远程管理的「浏览器登录」中授权快看漫画;也可回到快看账号页粘贴 Cookie。"] = "After signing in, authorize Kuaikan under Browser login in Remote management, or paste the Cookie on the Kuaikan account page.", +} diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/l10n/zh_TW.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/l10n/zh_TW.lua new file mode 100644 index 0000000..0197627 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/l10n/zh_TW.lua @@ -0,0 +1,74 @@ +return { + ["在章末显示本章讨论,不是段落评论"] = "在章末顯示本章討論,不是段落評論", + ["密码登录"] = "密碼登入", + ["短信登录"] = "簡訊登入", + ["快看密码登录"] = "快看密碼登入", + ["快看短信登录"] = "快看簡訊登入", + ["快看安全验证"] = "快看安全驗證", + ["请输入密码"] = "請輸入密碼", + ["登录前请阅读并同意快看用户协议和隐私协议"] = "登入前請閱讀並同意快看使用者協議和隱私協議", + ["用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"] = "用同一 Wi-Fi 下的手機掃碼完成安全驗證;手機號碼、密碼和簡訊碼只在裝置填寫。", + ["请完成下方安全验证"] = "請完成下方安全驗證", + ["验证已提交,请回到设备查看结果。"] = "驗證已提交,請回到裝置查看結果。", + ["验证或登录失败,请回到设备查看并重试"] = "驗證或登入失敗,請回到裝置查看並重試", + ["滑块加载失败,请检查网络后刷新网页"] = "滑塊載入失敗,請檢查網路後重新整理網頁", + ["快看漫画账号"] = "快看漫畫帳號", + ["快看登录 Cookie"] = "快看登入 Cookie", + ["在快看官网登录后,复制请求标头里的完整 Cookie"] = "在快看官網登入後,複製請求標頭裡的完整 Cookie", + ["快看登录已失效,请重新登录"] = "快看登入已失效,請重新登入", + ["旧快看账号身份无法确认,请先退出旧登录后重试"] = "舊快看帳號身分無法確認,請先登出舊登入後重試", + ["快看收藏变更尚未确认"] = "快看收藏變更尚未確認", + ["快看进度变更尚未确认"] = "快看進度變更尚未確認", + ["快看云端章节不在当前目录中"] = "快看雲端章節不在目前目錄中", + ["阅读进度同步"] = "閱讀進度同步", + ["请先退出旧快看账号,再登录其他账号"] = "請先登出舊快看帳號,再登入其他帳號", + ["确定退出快看账号?"] = "確定登出快看帳號?", + ["地区"] = "地區", + ["国漫"] = "國漫", + ["韩漫"] = "韓漫", + ["日漫"] = "日漫", + ["VIP抢先看"] = "VIP搶先看", + ["最火热"] = "最熱門", + ["新上架"] = "新上架", + ["话题页评论(首话)"] = "話題頁評論(首話)", + ["国际区号"] = "國際區碼", + ["请输入有效的手机号和国际区号"] = "請輸入有效的手機號碼和國際區碼", + ["请稍后再获取验证码"] = "請稍後再取得驗證碼", + ["验证码已发送"] = "驗證碼已發送", + ["正在处理,请稍候"] = "正在處理,請稍候", + ["请先获取该手机号的验证码,再填写验证码登录"] = "請先取得該手機號碼的驗證碼,再填寫驗證碼登入", + ["登录状态已变化,请重试"] = "登入狀態已改變,請重試", + ["登录响应无效"] = "登入回應無效", + ["章节评论"] = "章節評論", + ["快看漫画"] = "快看漫畫", + ["快看漫画在线阅读"] = "快看漫畫線上閱讀", + ["快看漫画书评加载失败"] = "快看漫畫書評載入失敗", + ["获取验证码"] = "取得驗證碼", + ["用微信扫一扫"] = "用微信掃一掃", + ["本章未购买"] = "本章未購買", + ["价格"] = "價格", + ["免费"] = "免費", + ["付费"] = "付費", + ["连载中"] = "連載中", + ["已完结"] = "已完結", + ["验证已过期,请重新发起验证"] = "驗證已過期,請重新發起驗證", + ["重新获取二维码"] = "重新取得二維碼", + ["微信扫码登录"] = "微信掃碼登入", + ["正在准备漫画…"] = "正在準備漫畫…", + ["正在获取二维码…"] = "正在取得二維碼…", + ["漫画目录为空"] = "漫畫目錄為空", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["章节图片解析失败"] = "章節圖片解析失敗", + ["已在微信中拒绝登录"] = "已在微信中拒絕登入", + ["手机号"] = "手機號碼", + ["同意并继续"] = "同意並繼續", + ["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "無法打開遠端驗證,請先連接 Wi-Fi 並啟用遠端管理功能", + ["验证已取消"] = "驗證已取消", + ["验证凭据无效"] = "驗證憑據無效", + ["正在提交验证…"] = "正在提交驗證…", + ["验证失败,请重新验证"] = "驗證失敗,請重新驗證", + ["重试"] = "重試", + ["书架同步"] = "書架同步", + ["搜索与发现"] = "搜尋與發現", + ["登录后,在远程管理的「浏览器登录」中授权快看漫画;也可回到快看账号页粘贴 Cookie。"] = "登入後,在遠端管理的「瀏覽器登入」中授權快看漫畫;也可回到快看帳號頁貼上 Cookie。", +} diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/loadmeta.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/loadmeta.lua new file mode 100644 index 0000000..54bad4e --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_kuaikan._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/login.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/login.lua new file mode 100644 index 0000000..e46b8e4 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/login.lua @@ -0,0 +1,258 @@ +--[[-- +快看电脑端登录会话。匿名 Cookie、在飞请求和微信 state 归本次操作所有; +账号校验成功才保存。不同账号必须先经退出确认清理旧记录。 + +@module moonsource_kuaikan.login +--]] + +local Client = require("moonsource_kuaikan.client") +local Mapper = require("moonsource_kuaikan.mapper") +local Request = require("http.request") +local CookieLogin = require("source.cookie_login") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_kuaikan") + +local HOST = "https://www.kuaikanmanhua.com" + +---@class KuaikanLogin +---@field cookies table +---@field job HttpJob|nil +---@field serial integer +---@field revision integer +---@field previous_cookie string|nil +---@field previous_id string|nil +---@field state string|nil +---@field sms_phone string|nil +---@field sms_retry_at integer|nil +local Login = {} +Login.__index = Login + +function Login.new() + local cfg = require("utils.settings").getSource("ext.kuaikan") + return setmetatable({ + cookies = {}, serial = 0, revision = Client.login_revision, + previous_cookie = cfg.cookie, previous_id = cfg.user_id, + }, Login) +end + +function Login:cancel() + self.serial = self.serial + 1 + if self.job then self.job.cancel(); self.job = nil end +end + +---@param url string +---@return string +function Login:cookie(url) + local path = url:match("^https://www%.kuaikanmanhua%.com([^?]*)") + if not path then return "" end + local parts = {} + for name, item in pairs(self.cookies) do + if path:sub(1, #item.path) == item.path + and (path == item.path or item.path:sub(-1) == "/" or path:sub(#item.path + 1, #item.path + 1) == "/") then + parts[#parts + 1] = name .. "=" .. item.value + end + end + table.sort(parts) + return table.concat(parts, "; ") +end + +---@param url string +---@param cb fun(raw: string|nil, err: any, res: table|nil) +---@param cookie string|nil 旧配置校验不合并其响应 Cookie +---@param fields table|nil +function Login:request(url, cb, cookie, fields) + self:cancel() + local serial, pending = self.serial, true + local job = Client.loginRequestAsync(url, cookie or self:cookie(url), function(raw, err, res) + pending = false + if serial ~= self.serial then return end + self.job = nil + if self.revision ~= Client.login_revision then cb(nil, _("登录状态已变化,请重试")); return end + if cookie == nil and url:sub(1, #HOST + 1) == HOST .. "/" then + local default_path = url:match("^https://[^/]+([^?]*)"):match("^(.*)/") or "/" + if default_path == "" then default_path = "/" end + for _idx, line in ipairs(Request.headerAll(res, "Set-Cookie")) do + local name, value = line:match("^%s*([^=;%s]+)=([^;]*)") + local domain = line:lower():match(";%s*domain=([^;]+)") + domain = domain and Text.trim(domain):gsub("^%.", "") + local path = Text.trim(line:match(";%s*[Pp][Aa][Tt][Hh]=([^;]*)") or default_path) + if path:sub(1, 1) ~= "/" then path = default_path end + if name and (not domain or domain == "kuaikanmanhua.com" or domain == "www.kuaikanmanhua.com") then + local max_age = tonumber(line:lower():match(";%s*max%-age=([%-]?%d+)")) + if value == "" or (max_age and max_age <= 0) then self.cookies[name] = nil + elseif CookieLogin.parse(name .. "=" .. value) ~= "" then + self.cookies[name] = { value = value, path = path } + end + end + end + end + cb(raw, err, res) + end, fields) + if pending then self.job = job end +end + +---@param path string +---@param fields table +---@param cb fun(ok: boolean|nil, err: string|nil) +function Login:submit(path, fields, cb) + self:request(HOST .. path, function(raw, err) + if not raw or err then cb(nil, err and tostring(err) or _("请求失败")); return end + local decoded, wire = pcall(require("json").decode, raw) + if not decoded or type(wire) ~= "table" or not tonumber(wire.code) then + cb(nil, _("登录响应无效")) + elseif tonumber(wire.code) == 200 then + cb(true) + else + cb(nil, type(wire.message) == "string" and wire.message ~= "" and wire.message or _("登录失败")) + end + end, nil, fields) +end + +---@param phone string +---@param captcha { ticket: string, random: string } +---@param cb fun(ok: boolean|nil, err: string|nil) +function Login:sendCodeAsync(phone, captcha, cb) + if self.sms_retry_at and os.time() < self.sms_retry_at then + cb(nil, _("请稍后再获取验证码")) + return + end + self:submit("/v2/passport/pc/v2/get_sms_code", { + phone = phone, ticket = captcha.ticket, random = captcha.random, verify_provider = "tencent", + }, function(ok, err) + if ok then self.sms_phone, self.sms_retry_at = phone, os.time() + 60 end + cb(ok, err) + end) +end + +---@param phone string +---@param password string +---@param captcha { ticket: string, random: string } +---@param cb fun(account: table|nil, err: string|nil) +function Login:passwordAsync(phone, password, captcha, cb) + self:submit("/v2/passport/pc/v2/mobile_pwd_login_encrypted", Mapper.passwordFields(phone, password, captcha), + function(ok, err) + if not ok then cb(nil, err); return end + self:confirm(cb) + end) +end + +---@param phone string +---@param code string +---@param cb fun(account: table|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:submit("/v2/passport/pc/mobile_code_login", { phone = phone, code = code, remember = 1 }, + function(ok, err) + if not ok then cb(nil, err); return end + self:confirm(cb) + end) +end + +---@param account { user_id: string } +---@param cb fun(account: table|nil, err: string|nil) +function Login:accept(account, cb) + local settings = require("utils.settings") + local cfg = settings.getSource("ext.kuaikan") + if self.revision ~= Client.login_revision or cfg.cookie ~= self.previous_cookie or cfg.user_id ~= self.previous_id then + cb(nil, _("登录状态已变化,请重试")) + return + end + local cookie = self:cookie(Client.ACCOUNT_URL) + if cookie == "" then cb(nil, _("没有读到 Cookie")); return end + if (self.previous_id and tostring(self.previous_id) ~= account.user_id) + or (not self.previous_id and self.previous_cookie and cookie ~= CookieLogin.parse(self.previous_cookie)) then + local cleared = require("source.logout").clear("ext.kuaikan", function() + cfg.cookie, cfg.user_id, cfg.logged_in = nil, nil, nil + Client.login_revision = Client.login_revision + 1 + settings.saveSource("ext.kuaikan") + end) + if not cleared then cb(nil, _("准备本地同步失败")); return end + end + cfg.cookie, cfg.user_id, cfg.logged_in = cookie, account.user_id, true + settings.saveSource("ext.kuaikan") + Client.login_revision = Client.login_revision + 1 + self.revision = Client.login_revision + require("source.auth").ok("ext.kuaikan") + cb(account) +end + +---@param cb fun(account: table|nil, err: string|nil) +function Login:confirm(cb) + self:request(Client.ACCOUNT_URL, function(raw, err, res) + local account, reason = Client.accountResponse(raw, err, res) + if not account then cb(nil, reason); return end + self:accept(account, cb) + end) +end + +---@param cookie string +---@param cb fun(account: table|nil, err: string|nil) +function Login:cookieAsync(cookie, cb) + local parsed = CookieLogin.parse(cookie) + if parsed == "" then cb(nil, _("没有读到 Cookie")); return end + for name, value in parsed:gmatch("([^=;%s]+)=([^;]+)") do + self.cookies[name] = { value = Text.trim(value), path = "/" } + end + self:confirm(cb) +end + +---@param cb fun(uuid: string|nil, err: string|nil) +function Login:qrCreateAsync(cb) + self:request(HOST .. "/v1/passport/login/pc/user_wechat_login?redirect_uri=" .. Text.urlEncode(Client.LOGIN_URL), + function(_raw, err, res) + local redirect = Mapper.qrLocation(Request.header(res, "Location")) + if not res or tonumber(res.code) ~= 302 or not redirect then + cb(nil, err and tostring(err) or _("获取二维码失败")) + return + end + self.state = redirect.state + self:request(redirect.url, function(raw, reason) + local uuid = raw and raw:match("/connect/qrcode/([%w_%-]+)") + if not uuid then cb(nil, reason and tostring(reason) or _("获取二维码失败")); return end + cb(uuid) + end) + end) +end + +---@param uuid string +---@param last integer|nil +---@param cb fun(status: integer|nil, code: string|nil, err: string|nil) +function Login:qrPollAsync(uuid, last, cb) + self:request("https://long.open.weixin.qq.com/connect/l/qrconnect?" + .. Text.formEncode({ uuid = uuid, last = last or 408, f = "json" }), function(raw, err) + if not raw then cb(nil, nil, err and tostring(err) or _("请求失败")); return end + local status, code = Mapper.qrStatus(raw) + cb(status, code, not status and _("登录响应无效") or nil) + end) +end + +---@param code string +---@param cb fun(account: table|nil, err: string|nil) +function Login:exchangeAsync(code, cb) + local function follow(url, remaining) + self:request(url, function(raw, err, res) + local status = res and tonumber(res.code) + if status and status >= 300 and status < 400 then + local location = Request.header(res, "Location") + if type(location) == "string" and location:sub(1, 1) == "/" and location:sub(1, 2) ~= "//" then + location = HOST .. location + end + if remaining == 0 or type(location) ~= "string" or location:sub(1, #HOST + 1) ~= HOST .. "/" then + cb(nil, _("登录响应无效")) + return + end + follow(location, remaining - 1) + return + end + if not raw or err then cb(nil, err and tostring(err) or _("登录失败")); return end + self:confirm(cb) + end) + end + if not self.state or type(code) ~= "string" or code == "" then cb(nil, _("登录响应无效")); return end + follow(Mapper.WECHAT_CALLBACK .. "?" .. Text.formEncode({ code = code, state = self.state }), 5) +end + +return Login diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/mapper.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/mapper.lua new file mode 100644 index 0000000..ca21165 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/mapper.lua @@ -0,0 +1,341 @@ +--[[-- +快看漫画响应到书籍、目录和页图。 + +目录不在 JSON 里。话题页把章节嵌进 `window.__NUXT__`,由 page.lua 拆开后再交给这里。 +未解锁章节 `locked == true`,不给页图。 + +@module moonsource_kuaikan.mapper +--]] + +local Text = require("utils.text") + +local Mapper = {} + +Mapper.TOC_VERSION = 1 +local SOURCE_ID = "ext.kuaikan" + +---@param topic_id string +---@param comic_id string +---@param pos ProgressPosition +---@param fraction number 章内比例 +---@param count integer 图片页数 +---@param now integer 毫秒时间 +---@return table|nil +function Mapper.progressReport(topic_id, comic_id, pos, fraction, count, now) + local topic, comic = tonumber(topic_id), tonumber(comic_id) + if not topic or not comic or topic <= 0 or comic <= 0 or topic % 1 ~= 0 or comic % 1 ~= 0 then return nil end + local read_count = math.max(1, math.min(count, pos.page or math.ceil(fraction * count))) + return { + topic_id = topic, comic_id = comic, total_count = count, + read_count = read_count, max_read_count = read_count, + read_time = now, max_read_count_time = now, + } +end + +---@param value any +---@return string +local function clean(value) + if type(value) ~= "string" then return "" end + return Text.trim(value) +end + +---@param row table +---@return string +local function author(row) + if type(row.author_name) == "string" then return clean(row.author_name) end + local user = row.user + if type(user) == "table" then return clean(user.nickname) end + return "" +end + +---@param row table +---@return string|nil +local function cover(row) + local url = row.vertical_image_url or row.cover_image_url + if type(url) ~= "string" or url == "" then return nil end + return url +end + +---@param row table +---@return Book|nil +local function book(row) + if type(row) ~= "table" or row.id == nil or clean(row.title) == "" then return nil end + return { + source_id = SOURCE_ID, + stable_id = tostring(row.id), + title = clean(row.title), + authors = author(row), + cover = cover(row), + intro = clean(row.description), + } +end + +---@param rows table|nil +---@return Book[] +local function books(rows) + local out = {} + if type(rows) ~= "table" then return out end + for _idx, row in ipairs(rows) do + local item = book(row) + if item then out[#out + 1] = item end + end + return out +end + +---@param node string|nil +---@return string +function Mapper.storeNode(node) + if type(node) ~= "string" or not node:match("^%d+:%d+:%d+:%d+:%d+$") then return "0:1:0:0:1" end + -- 各筛选维度的枚举与官网 /tag/ 链接一致。 + local parts = {} + for value in node:gmatch("%d+") do parts[#parts + 1] = value end + if tonumber(parts[2]) < 1 or tonumber(parts[2]) > 4 + or tonumber(parts[3]) > 3 or tonumber(parts[4]) > 2 + or tonumber(parts[5]) < 1 or tonumber(parts[5]) > 3 then return "0:1:0:0:1" end + return node +end + +---@param wire table|nil +---@param node string +---@param page integer +---@return Book[]|nil, StoreChipGroup[]|nil, boolean|nil +function Mapper.store(wire, node, page) + if type(wire) ~= "table" or tonumber(wire.code) ~= 200 or type(wire.hits) ~= "table" then return nil end + local rows, tags, total = wire.hits.topicMessageList, wire.hits.topicCategories, tonumber(wire.total) + if type(rows) ~= "table" or type(tags) ~= "table" or not total or total < 0 then return nil end + local _ = require("l10n").get("moonsource_kuaikan") + local parts = {} + for value in Mapper.storeNode(node):gmatch("%d+") do parts[#parts + 1] = value end + local categories = {} + for _idx, tag in ipairs(tags) do + local id = type(tag) == "table" and (tag.tag_id or tag.tagId) + if id == nil or not tostring(id):match("^%d+$") or clean(tag.title) == "" then return nil end + categories[#categories + 1] = { tostring(id), tag.title } + end + local dimensions = { + { _("分类"), categories }, + { _("地区"), { { "1", _("全部") }, { "2", _("国漫") }, { "3", _("韩漫") }, { "4", _("日漫") } } }, + { _("价格"), { { "0", _("全部") }, { "1", _("免费") }, { "2", _("付费") }, { "3", _("VIP抢先看") } } }, + { _("状态"), { { "0", _("全部") }, { "1", _("连载中") }, { "2", _("已完结") } } }, + { _("排序"), { { "1", _("推荐") }, { "2", _("最火热") }, { "3", _("新上架") } } }, + } + local groups = {} + for index, dimension in ipairs(dimensions) do + local chips = {} + local saved = parts[index] + for _idx, choice in ipairs(dimension[2]) do + parts[index] = choice[1] + chips[#chips + 1] = { id = table.concat(parts, ":"), title = choice[2] } + end + parts[index] = saved + local group = require("source.browse").group(chips, table.concat(parts, ":")) + group.title = dimension[1] + groups[#groups + 1] = group + end + local list = books(rows) + if #list ~= #rows then return nil end + return list, groups, page * 48 < total +end + +---@param wire table|nil +---@return Book[]|nil +function Mapper.search(wire) + if type(wire) ~= "table" or tonumber(wire.code) ~= 200 then return nil end + local topics = type(wire.data) == "table" and wire.data.topics or nil + local hit = type(topics) == "table" and topics.hit or nil + if type(hit) ~= "table" then return nil end + return books(hit) +end + +---@param wire table|nil +---@return Book[]|nil +function Mapper.home(wire) + if type(wire) ~= "table" or tonumber(wire.code) ~= 200 then return nil end + local rows = type(wire.data) == "table" and wire.data.popularity_topics or nil + if type(rows) ~= "table" then return nil end + return books(rows) +end + +--- 收藏列表。`data.topics` 是书卡数组,空数组是空收藏。 +---@param wire table|nil +---@return Book[]|nil, integer|nil +function Mapper.fav(wire) + if type(wire) ~= "table" or tonumber(wire.code) ~= 200 then return nil end + local data = type(wire.data) == "table" and wire.data or nil + local rows = data and data.topics or nil + local total = data and tonumber(data.total) + if type(rows) ~= "table" or not total or total < 0 or total ~= math.floor(total) then return nil end + local list = books(rows) + if #list ~= #rows then return nil end + return list, total +end + +--- 话题页拆出来的章节行。 +---@param rows table[]|nil +---@return BookChapter[]|nil +function Mapper.chapters(rows) + if type(rows) ~= "table" then return nil end + local out = {} + for _idx, row in ipairs(rows) do + if type(row) == "table" and row.id ~= nil and clean(row.title) ~= "" then + out[#out + 1] = { + idx = #out + 1, + uid = tostring(row.id), + title = clean(row.title), + vip = row.locked == true, + } + end + end + if not out[1] then return nil end + out[1].toc_version = Mapper.TOC_VERSION + return out +end + +--- 详情。作者是页面脚本里单独赋的昵称。 +---@param info table|nil +---@param nickname string|nil +---@return Book|nil +function Mapper.detail(info, nickname) + local item = book(info or {}) + if item and type(nickname) == "string" and nickname ~= "" then item.authors = nickname end + return item +end + +--- 话题评论。网页只展示 `replied_comment_id` 为 0 的楼,字段是 user.nickname、content、created_at_info、likes_count。 +--- 第二返回值是 data.total。 +---@param wire table|nil +---@return { id: string|nil, author: string, text: string, time: string|nil, likes: number|nil }[]|nil +---@return integer|nil +function Mapper.comments(wire) + if type(wire) ~= "table" or tonumber(wire.code) ~= 200 or type(wire.data) ~= "table" then + return nil + end + local rows = wire.data.comments + local total = tonumber(wire.data.total) + if type(rows) ~= "table" or not total or total < 0 then return nil end + local out = {} + for _idx, row in ipairs(rows) do + if type(row) ~= "table" or type(row.content) ~= "string" or tonumber(row.replied_comment_id) == nil then + return nil + end + if tonumber(row.replied_comment_id) == 0 then + local user = type(row.user) == "table" and row.user or {} + local stamp = type(row.created_at_info) == "string" and row.created_at_info:match("^(%S+)") or nil + out[#out + 1] = { + id = (type(row.id) == "string" or type(row.id) == "number") and tostring(row.id) or nil, + author = type(user.nickname) == "string" and user.nickname or "", + text = row.content, + time = stamp, + likes = tonumber(row.likes_count), + } + end + end + return out, total +end + +--- 一话的页图 URL。locked 的章节没有图。 +---@param wire table|nil +---@return string[]|nil +---@return string|nil +function Mapper.images(wire) + if type(wire) ~= "table" or tonumber(wire.code) ~= 200 then return nil end + local info = type(wire.data) == "table" and wire.data.comic_info or nil + if type(info) ~= "table" then return nil end + if info.locked == true then return nil, "locked" end + local rows = info.comic_images + if type(rows) ~= "table" then return nil end + local urls = {} + for _idx, row in ipairs(rows) do + local url = type(row) == "table" + and (type(row.url1280) == "string" and row.url1280 ~= "" and row.url1280 or row.url) or nil + if type(url) ~= "string" or url == "" then return nil end + urls[#urls + 1] = url + end + if #urls == 0 then return nil end + return urls +end + +---@param wire table|nil +---@return { user_id: string }|nil +---@return string|nil +function Mapper.account(wire) + if type(wire) ~= "table" or tonumber(wire.code) ~= 200 then return nil, "invalid" end + if type(wire.data) ~= "table" or type(wire.data.user_info) ~= "table" then return nil, "invalid" end + ---@type table + local user = wire.data.user_info + local authenticated = tonumber(user.authenticate) + if authenticated == 0 then return nil, "unauthorized" end + if not authenticated or authenticated < 0 then return nil, "invalid" end + local id = user.user_id + if type(id) ~= "number" and type(id) ~= "string" then return nil, "invalid" end + id = tostring(id) + if not id:match("^%d+$") then return nil, "invalid" end + id = id:gsub("^0+", "") + if id == "" then return nil, "invalid" end + return { user_id = id } +end + +Mapper.WECHAT_CALLBACK = "https://www.kuaikanmanhua.com/v1/passport/login/pc/user_wechat_login_check" + +---@param country string +---@param number string +---@return string|nil +function Mapper.phone(country, number) + country, number = Text.trim(country), Text.trim(number) + if not country:match("^%+%d+$") or #country > 5 then return nil end + if country == "+86" then + if not number:match("^1[3-9]%d%d%d%d%d%d%d%d%d$") then return nil end + elseif not number:match("^%d+$") or #number < 7 or #number > 12 then + return nil + end + return country .. "-" .. number +end + +---@param phone string +---@param password string +---@param captcha { ticket: string, random: string } +---@return table +function Mapper.passwordFields(phone, password, captcha) + local AES = require("crypto.aes") + -- 官网公开脚本的 UTF-8 原始密钥、IV 与 PKCS7,不是 Base64 密钥或口令派生。 + local key, iv = "CRL66bnFXBaLt39tgU8GJrVymV/jBJqv", "vdjsaj42mxfkck39" + return { + phone = Text.base64Encode(AES.cbc_encrypt(phone, key, iv)), + password = Text.base64Encode(AES.cbc_encrypt(password, key, iv)), + remember = 1, ticket = captcha.ticket, random = captcha.random, verify_provider = "tencent", + } +end + +---@param location string|nil +---@return { url: string, state: string }|nil +function Mapper.qrLocation(location) + if type(location) ~= "string" or not location:match("^https://open%.weixin%.qq%.com/connect/qrconnect%?") then return nil end + local params = {} + for key, value in location:match("%?([^#]*)"):gmatch("([^&=]+)=([^&]*)") do + key = Text.urlDecode(key) + if params[key] then return nil end + params[key] = Text.urlDecode(value) + end + if params.appid ~= "wx92ba65b18ed55877" or params.scope ~= "snsapi_login" + or params.response_type ~= "code" or params.redirect_uri ~= Mapper.WECHAT_CALLBACK + or not params.state or params.state == "" then return nil end + return { url = location, state = params.state } +end + +---@param raw string +---@return integer|nil +---@return string|nil +function Mapper.qrStatus(raw) + local ok, wire = pcall(require("json").decode, raw) + local status, code + if ok and type(wire) == "table" then + status, code = tonumber(wire.wx_errcode), wire.wx_code + else + status = tonumber(raw:match("wx_errcode%s*=%s*(%d+)")) + code = raw:match("wx_code%s*=%s*['\"]([^'\"]*)['\"]") + end + if not status or (status == 405 and (type(code) ~= "string" or code == "")) then return nil end + return status, code +end + +return Mapper diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/page.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/page.lua new file mode 100644 index 0000000..6833523 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/page.lua @@ -0,0 +1,239 @@ +--[[-- +从话题页的 `window.__NUXT__` 里拆目录。 + +网页把接口响应编成一个函数调用:结构留在函数体,字符串和数字落在参数上。 +章节数组是 `comics:[{id:`,作者昵称是函数体里唯一的 `.nickname="..."` 赋值。 + +@module moonsource_kuaikan.page +--]] + +local Page = {} +local JSON = require("json") + +--- 参数位置上的对象 / null。不能把 nil 塞进数组,否则后面的参数整体错位。 +local HOLE = {} + +---@param source string +---@param index integer +---@return integer +local function skip(source, index) + return (source:match("^%s*()", index)) or index +end + +---@param source string +---@param index integer 引号所在位置 +---@return string|nil +---@return integer|nil +local function readString(source, index) + local quote = source:sub(index, index) + local cursor = index + 1 + while cursor <= #source do + local char = source:sub(cursor, cursor) + if char == "\\" then + cursor = cursor + 2 + elseif char == quote then + local literal = source:sub(index, cursor) + if quote ~= '"' then + literal = '"' .. literal:sub(2, -2):gsub("\\'", "'"):gsub('"', '\\"') .. '"' + end + local ok, value = pcall(JSON.decode, literal) + if not ok or type(value) ~= "string" then return nil end + return value, cursor + 1 + else + cursor = cursor + 1 + end + end + return nil +end + +--- 跳过从 index 开始的引号字符串,返回结束后的位置。 +---@param source string +---@param index integer +---@return integer|nil +local function skipString(source, index) + local _text, next_index = readString(source, index) + return next_index +end + +--- 配平 `{}` / `[]`,字符串里的括号不算。 +---@param source string +---@param index integer +---@return integer|nil +local function matchBlock(source, index) + local depth = 0 + while index <= #source do + local char = source:sub(index, index) + if char == '"' or char == "'" then + index = skipString(source, index) + if not index then return nil end + elseif char == "{" or char == "[" then + depth = depth + 1 + index = index + 1 + elseif char == "}" or char == "]" then + depth = depth - 1 + index = index + 1 + if depth == 0 then return index end + else + index = index + 1 + end + end + return nil +end + +---@param source string +---@param index integer +---@param env table +---@return any +---@return integer|nil +local function readValue(source, index, env) + index = skip(source, index) + local char = source:sub(index, index) + if char == '"' or char == "'" then return readString(source, index) end + if char == "{" or char == "[" then return nil, matchBlock(source, index) end + local ident = source:match("^[%a_$][%w_$]*", index) + if ident then + local after = index + #ident + if source:sub(after, after) == "(" then + local close = source:find(")", after + 1, true) + if not close then return nil end + return nil, close + 1 + end + if ident == "true" then return true, after end + if ident == "false" then return false, after end + if ident == "null" or ident == "undefined" then return nil, after end + return env[ident], after + end + local number = source:match("^-?%d+%.?%d*", index) + if number then return tonumber(number), index + #number end + return nil, index +end + +---@param source string +---@param index integer 指向 `{` +---@param env table +---@return table|nil +---@return integer|nil +local function readObject(source, index, env) + index = index + 1 + local fields = {} + while index <= #source do + index = skip(source, index) + if source:sub(index, index) == "}" then return fields, index + 1 end + local key = source:match("^[%w_]+", index) + if not key then return nil end + index = index + #key + if source:sub(index, index) ~= ":" then return nil end + local value, next_index = readValue(source, index + 1, env) + if not next_index or next_index <= index then return nil end + fields[key] = value + index = skip(source, next_index) + if source:sub(index, index) == "," then + index = index + 1 + elseif source:sub(index, index) ~= "}" then + return nil + end + end + return nil +end + +---@param source string +---@param index integer 指向 `(` +---@return any[]|nil +local function readArgs(source, index) + index = index + 1 + local args = {} + while index <= #source do + index = skip(source, index) + if source:sub(index, index) == ")" then return args end + local value, next_index = readValue(source, index, {}) + if not next_index or next_index <= index then return nil end + args[#args + 1] = value == nil and HOLE or value + index = skip(source, next_index) + local separator = source:sub(index, index) + if separator == "," then index = index + 1 + elseif separator ~= ")" then return nil end + end + return nil +end + +---@param script string +---@return table|nil +local function bind(script) + local params_at = script:find("function(", 1, true) + if not params_at then return nil end + local params_end = script:find(")", params_at + 9, true) + if not params_end then return nil end + local params = {} + for name in script:sub(params_at + 9, params_end - 1):gmatch("[%a_$][%w_$]*") do + params[#params + 1] = name + end + local body_at = skip(script, params_end + 1) + if script:sub(body_at, body_at) ~= "{" then return nil end + local after_body = matchBlock(script, body_at) + if not after_body then return nil end + local args_at = skip(script, after_body) + if script:sub(args_at, args_at) ~= "(" then return nil end + local args = readArgs(script, args_at) + if not args then return nil end + local env = {} + for index, name in ipairs(params) do + local value = args[index] + if value ~= HOLE and (type(value) == "string" or type(value) == "number" or type(value) == "boolean") then + env[name] = value + end + end + return env +end + +--- 拆话题页。失败返回 nil。 +---@param html string|nil +---@return { info: table, nickname: string, chapters: table[] }|nil +function Page.topic(html) + if type(html) ~= "string" then return nil end + local at = html:find("window.__NUXT__=", 1, true) + if not at then return nil end + local script = html:sub(at) + local env = bind(script) + if not env then return nil end + + local info_at = script:find("topicInfo:{", 1, true) + local info = {} + if info_at then + local object = readObject(script, info_at + #"topicInfo:" , env) + if object then info = object end + end + + local comics_at = script:find("comics:[{id:", 1, true) + if not comics_at then return nil end + local cursor = script:find("{", comics_at, true) + local chapters = {} + while cursor and script:sub(cursor, cursor) == "{" do + local row, next_cursor = readObject(script, cursor, env) + if not row then return nil end + if row.id == nil or type(row.title) ~= "string" or row.title == "" then return nil end + chapters[#chapters + 1] = { + id = row.id, + title = row.title, + locked = row.locked == true, + } + cursor = skip(script, next_cursor) + if script:sub(cursor, cursor) == "," then + cursor = skip(script, cursor + 1) + elseif script:sub(cursor, cursor) == "]" then + break + else + return nil + end + end + if #chapters == 0 or script:sub(cursor, cursor) ~= "]" then return nil end + + local nickname_at = script:find('%.nickname="') + local nickname = nickname_at and readString(script, nickname_at + #".nickname=") + return { + info = info, + nickname = nickname or "", + chapters = chapters, + } +end + +return Page diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/phone_login.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/phone_login.lua new file mode 100644 index 0000000..739ba1a --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/phone_login.lua @@ -0,0 +1,149 @@ +--[[-- +快看手机号密码与短信登录。输入窗、滑块和 HTTP 共用本次候选会话。 + +@module moonsource_kuaikan.phone_login +--]] + +local Mapper = require("moonsource_kuaikan.mapper") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_kuaikan") + +---@class KuaikanPhoneLogin +---@field mode string +---@field session KuaikanLogin +---@field generation integer +---@field busy boolean|nil +---@field agreed boolean|nil +---@field verification KuaikanVerification|nil +---@field dialog BookThemeInput|nil +---@field on_user fun(account: table) +local PhoneLogin = {} +PhoneLogin.__index = PhoneLogin + +function PhoneLogin.new(mode, on_user) + return setmetatable({ + mode = mode, on_user = on_user, generation = 0, + session = require("moonsource_kuaikan.login").new(), + }, PhoneLogin) +end + +function PhoneLogin:cancel() + self.generation = self.generation + 1 + if self.verification then self.verification:cancel(); self.verification = nil end + self.session:cancel() + self.busy, self.dialog = false, nil +end + +function PhoneLogin:ready(country, number) + local err + if self.busy then err = _("正在处理,请稍候") + elseif not require("ui/network/manager"):isConnected() then err = _("网络不可用,请先连接 Wi-Fi") end + local phone = Mapper.phone(country, number) + if not err and not phone then err = _("请输入有效的手机号和国际区号") end + if err then require("ui.themes.widgets.toast"):new{ text = err }:show(); return nil end + return phone +end + +function PhoneLogin:agree(fn) + if self.agreed then fn(); return end + local gen = self.generation + require("ui.themes.widgets.confirm"):new{ + text = _("登录前请阅读并同意快看用户协议和隐私协议") + .. "\nhttps://www.kuaikanmanhua.com/webs/agreement" + .. "\nhttps://h5.kuaikanmanhua.com/normal/protocol/?type=1" + .. "\nhttps://h5.kuaikanmanhua.com/normal/protocol/?type=2", + ok_text = _("同意并继续"), + ok_callback = function() + if gen ~= self.generation then return end + self.agreed = true + fn() + end, + }:show() +end + +function PhoneLogin:captcha(country, number, password) + local phone = self:ready(country, number) + if not phone then return end + if self.mode == "password" and password == "" then + require("ui.themes.widgets.toast"):new{ text = _("请输入密码") }:show() + return + end + if self.mode ~= "password" and self.session.sms_retry_at and os.time() < self.session.sms_retry_at then + require("ui.themes.widgets.toast"):new{ text = _("请稍后再获取验证码") }:show() + return + end + self:agree(function() + if not self:ready(country, number) then return end + self.busy = true + local dialog = self.dialog + self.dialog = nil + dialog:close() + local gen = self.generation + local verification = require("moonsource_kuaikan.verify").new(self.session, function(proof, cb) + if self.mode == "password" then self.session:passwordAsync(phone, password, proof, cb) + else self.session:sendCodeAsync(phone, proof, cb) end + end, function(result, err) + if gen ~= self.generation then return end + self.busy, self.verification = false, nil + if result and self.mode == "password" then + self:cancel() + self.on_user(result) + return + end + self:start(country, number) + require("ui.themes.widgets.toast"):new{ + text = result and _("验证码已发送") or err or _("登录失败"), timeout = 4, + }:show() + end) + if not verification.done then self.verification = verification end + end) +end + +function PhoneLogin:verify(country, number, code) + local phone = self:ready(country, number) + if not phone then return end + code = Text.trim(code) + if phone ~= self.session.sms_phone or not code:match("^%d+$") then + require("ui.themes.widgets.toast"):new{ + text = _("请先获取该手机号的验证码,再填写验证码登录"), + }:show() + return + end + self.busy = true + local gen = self.generation + self.session:codeAsync(phone, code, function(account, err) + if gen ~= self.generation then return end + self.busy = false + if not account then require("ui.themes.widgets.toast"):new{ text = err or _("登录失败") }:show(); return end + self.dialog:close() + self:cancel() + self.on_user(account) + end) +end + +function PhoneLogin:start(country, number) + local password = self.mode == "password" + local dialog + dialog = require("ui.themes.widgets.input"):new{ + title = password and _("快看密码登录") or _("快看短信登录"), + fields = { + { label = _("国际区号"), text = country or "+86" }, + { label = _("手机号"), text = number or "", input_type = "number" }, + { label = password and _("密码") or _("验证码"), + text_type = password and "password" or nil, input_type = not password and "number" or nil }, + }, + keep_open = true, ok_text = _("登录"), + actions = not password and { { text = _("获取验证码"), callback = function(cc, phone) + if self.dialog == dialog then self:captcha(cc, phone) end + end } } or nil, + callback = function(cc, phone, value) + if self.dialog ~= dialog then return end + if password then self:captcha(cc, phone, value) else self:verify(cc, phone, value) end + end, + close_callback = function() if self.dialog == dialog then self:cancel() end end, + } + self.dialog = dialog + dialog:show() +end + +return PhoneLogin diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/qrlogin.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/qrlogin.lua new file mode 100644 index 0000000..f866965 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/qrlogin.lua @@ -0,0 +1,104 @@ +--[[-- +快看微信扫码窗口。关闭取消在飞请求和轮询;确认后仅通过官方回调兑换会话。 + +@module moonsource_kuaikan.qrlogin +--]] + +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_kuaikan") + +---@class KuaikanQRLogin +---@field generation integer +---@field session KuaikanLogin|nil +---@field poll function|nil +---@field waiting table|nil +---@field dialog table|nil +---@field deadline number +---@field on_user fun() +local QRLogin = {} +QRLogin.__index = QRLogin + +function QRLogin.new(on_user) + return setmetatable({ on_user = on_user, generation = 0 }, QRLogin) +end + +function QRLogin:cancel() + self.generation = self.generation + 1 + if self.session then self.session:cancel() end + if self.poll then require("ui/uimanager"):unschedule(self.poll); self.poll = nil end + 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 QRLogin:retry(text) + self:cancel() + require("ui.themes.widgets.confirm"):new{ + text = text, ok_text = _("重新获取二维码"), ok_callback = function() self:start() end, + }:show() +end + +function QRLogin:pollAsync(gen, uuid, last) + if gen ~= self.generation then return end + if not require("ui/network/manager"):isConnected() then self:retry(_("网络不可用,请先连接 Wi-Fi")); return end + if os.time() >= self.deadline then self:retry(_("二维码已过期")); return end + self.session:qrPollAsync(uuid, last, function(status, code, err) + if gen ~= self.generation then return end + if status == 405 then + self.session:exchangeAsync(code, function(account, reason) + if gen ~= self.generation then return end + if not account then self:retry(reason or _("登录失败")); return end + self:cancel() + self.on_user() + end) + return + end + if status ~= 404 and status ~= 408 then + self:retry(err or (status == 403 and _("已在微信中拒绝登录") or _("二维码已过期"))) + return + end + if status == 404 and last ~= 404 then + require("ui.themes.widgets.toast"):new{ text = _("已扫码,请在手机上确认") }:show() + end + self.poll = require("ui.guard").wrap("kuaikan QR poll", function() + self.poll = nil + self:pollAsync(gen, uuid, status) + end) + require("ui/uimanager"):scheduleIn(1, self.poll) + end) +end + +function QRLogin:start() + self:cancel() + if not require("ui/network/manager"):isConnected() then + require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi") }:show() + return + end + local gen = self.generation + self.session = require("moonsource_kuaikan.login").new() + self.deadline = os.time() + 300 + self.waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("微信扫码登录"), text = _("正在获取二维码…"), + on_cancel = function() self:cancel() end, + } + self.waiting:show() + self.session:qrCreateAsync(function(uuid, err) + if gen ~= self.generation then return end + self.waiting:close() + self.waiting = nil + if not uuid then self:retry(err or _("获取二维码失败")); return end + self.dialog = require("ui.themes.widgets.qr"):new{ + title = _("微信扫码登录"), caption = _("用微信扫一扫"), + text = "https://open.weixin.qq.com/connect/confirm?uuid=" .. Text.urlEncode(uuid), + actions = { { text = _("重新获取二维码"), callback = function() self:start() end } }, + close_callback = function() if gen == self.generation then self:cancel() end end, + } + self.dialog:show() + self:pollAsync(gen, uuid) + end) +end + +return QRLogin diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/setting.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/setting.lua new file mode 100644 index 0000000..a55c98d --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/setting.lua @@ -0,0 +1,134 @@ +--[[-- +快看账号:微信扫码、手机号密码、短信、官网浏览器授权与 Cookie 导入。 + +@module moonsource_kuaikan.setting +--]] + +local Client = require("moonsource_kuaikan.client") +local CookieLogin = require("source.cookie_login") +local _ = require("l10n").get("moonsource_kuaikan") + +local Setting = {} +local COOKIE_PATHS = { ["/"] = true, ["/v2"] = true, ["/v2/"] = true, ["/v2/pweb"] = true, ["/v2/pweb/"] = true } + +function Setting.rowStatus() + local cfg = require("utils.settings").getSource("ext.kuaikan") + local on = cfg.logged_in == true and type(cfg.cookie) == "string" and cfg.cookie ~= "" + and type(cfg.user_id) == "string" and cfg.user_id ~= "" and not require("source.auth").expired("ext.kuaikan") + return on and _("已登录") or _("未登录 · 点此登录"), on +end + +local function onLogin() + require("source.registry").reload() + require("ui.themes.widgets.toast"):new{ text = _("登录成功"), timeout = 2 }:show() +end + +local function pasteCookie() + local Toast = require("ui.themes.widgets.toast") + require("ui.themes.widgets.input"):new{ + title = _("快看登录 Cookie"), + fields = { { text = "", hint = _("在快看官网登录后,复制请求标头里的完整 Cookie") } }, + ok_text = _("登录"), + callback = function(cookie) + if not require("ui/network/manager"):isConnected() then + Toast:new{ text = _("网络不可用,请先连接 Wi-Fi") }:show() + return + end + local session = require("moonsource_kuaikan.login").new() + local cancelled = false + local waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("快看漫画账号"), text = _("正在校验登录…"), + on_cancel = function() cancelled = true; session:cancel() end, + } + waiting:show() + session:cookieAsync(cookie, function(account, err) + if cancelled then return end + waiting:close() + if account then onLogin() + else Toast:new{ text = err or _("登录失败"), timeout = 3 }:show() end + end) + end, + }:show() +end + +Setting.browser = { + domain = "www.kuaikanmanhua.com", scope = "cookie", + login = Client.LOGIN_URL, check = Client.ACCOUNT_URL, + check_json = { path = "data.user_info.authenticate", ok = { 1 } }, + icon = "https://festatic.v3mh.com/static-resource/img/32x32/favicon.ico", + isAuthorized = function() local _status, on = Setting.rowStatus(); return on end, + apply = function(payload, cb) + local cookies = {} + for _idx, cookie in ipairs(type(payload.cookies) == "table" and payload.cookies or {}) do + local host = type(cookie) == "table" and type(cookie.domain) == "string" + and cookie.domain:gsub("^%.", ""):lower() + local path = type(cookie) == "table" and cookie.path or "/" + if (host == "kuaikanmanhua.com" or host == "www.kuaikanmanhua.com") + and COOKIE_PATHS[path] then + cookies[#cookies + 1] = cookie + end + end + local session = require("moonsource_kuaikan.login").new() + session:cookieAsync(CookieLogin.fromPayload({ cookies = cookies }, "kuaikanmanhua.com"), function(account, err) + if account then require("source.registry").reload() end + cb(account ~= nil, err) + end) + return { cancel = function() session:cancel() end } + end, +} + +function Setting.login() + require("moonsource_kuaikan.qrlogin").new(onLogin):start() +end + +function Setting.rows(plugin) + local Row = require("ui.themes.widgets.row") + local rows = { + function(iw) + local status, on = Setting.rowStatus() + return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "account_circle", + title = _("快看漫画账号"), status = status, status_on = on, + subtitle = _("微信扫码登录"), callback = Setting.login }) + end, + CookieLogin.browserRow(), + function(iw) + return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "content_paste", + title = _("粘贴 Cookie"), callback = pasteCookie }) + end, + function(iw) + return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "password", + title = _("密码登录"), callback = function() + require("moonsource_kuaikan.phone_login").new("password", onLogin):start() + end }) + end, + function(iw) + return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "sms", + title = _("短信登录"), callback = function() + require("moonsource_kuaikan.phone_login").new("sms", onLogin):start() + end }) + end, + function(iw) + local reviews = require("source.review_setting") + local on = reviews.enabled("ext.kuaikan") + return Row.widget({ width = iw, chevron = false, kind = "toggle", icon = "forum", + title = _("章节评论"), subtitle = _("在章末显示本章讨论,不是段落评论"), + status = on and _("开") or _("关"), status_on = on, + callback = function() + reviews.set("ext.kuaikan", not on) + if plugin and plugin.desktop then plugin.desktop:updateView() end + end }) + end, + } + local cfg = require("utils.settings").getSource("ext.kuaikan") + if type(cfg.cookie) == "string" and cfg.cookie ~= "" then + rows[#rows + 1] = require("source.logout").row("ext.kuaikan", _("确定退出快看账号?"), function() + cfg = require("utils.settings").getSource("ext.kuaikan") + cfg.cookie, cfg.user_id, cfg.logged_in = nil, nil, nil + Client.login_revision = Client.login_revision + 1 + require("utils.settings").saveSource("ext.kuaikan") + end) + end + return rows +end + +return Setting diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/source.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/source.lua new file mode 100644 index 0000000..ff9df20 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/source.lua @@ -0,0 +1,397 @@ +--[[-- +快看漫画数据源。 + +免费话不需要登录。登录后默认双向同步收藏与阅读进度。 +一话是一组图片,打成 CBZ。 + +@module source.kuaikan +--]] + +local Client = require("moonsource_kuaikan.client") +local Mapper = require("moonsource_kuaikan.mapper") +local SourceBase = require("source.base") +local Toc = require("source.toc") +local _ = require("l10n").get("moonsource_kuaikan") + +local Kuaikan = {} + +---@return BookSourceMeta +function Kuaikan.meta() + return require("moonsource_kuaikan.loadmeta")() +end + +---@class KuaikanSource : SourceBase +local Source = setmetatable({ shelf_add = true }, { __index = SourceBase }) +Source.__index = Source +local putProgressAsync + +---@return KuaikanSource +function Kuaikan.new() + local meta = Kuaikan.meta() + return setmetatable({ + id = meta.id, name = meta.name, type = meta.type, + putProgressAsync = Client.hasAccount() and putProgressAsync or nil, + }, Source) +end + +--- 未登录的收藏列表是空的,不能拿来对账。 +---@return SourceCapabilities +function Source:capabilities() + local caps = SourceBase.capabilities(self) + caps.shelf_push = Client.hasAccount() + return caps +end + +---@return boolean +function Source:configured() + return true +end + +---@param opts { force?: boolean, dirty_only?: boolean, on_progress?: fun(text: string, done: integer|nil, total: integer|nil) }|nil +---@param cb fun(result: SyncResult|nil, err: string|nil) +---@return { cancel: fun() } +function Source:syncBooksAsync(opts, cb) + opts = opts or {} + local remote, pipeline = Client.newSync(false), nil + if remote.cookie == "" then return SourceBase.skipped(cb, "not_logged_in") end + remote:checkAsync(function(account, err) + if remote.cancelled then return end + if not account then cb(nil, err); return end + local settings = require("utils.settings") + local cfg = settings.getSource(self.id) + if remote.user_id ~= account.user_id or cfg.logged_in ~= true then + cfg.user_id, cfg.logged_in = account.user_id, true + settings.saveSource(self.id) + remote.user_id = account.user_id + end + remote.writing = true + self.putProgressAsync = putProgressAsync + local pending = true + local job = require("source.shelf").syncAsync(self.id, remote, nil, opts, function(result, reason) + pending, pipeline = false, nil + if remote.cancelled then return end + if not remote:current() then cb(nil, _("登录状态已变化,请重试")); return end + if result and remote.push_error then + if not opts.dirty_only then cb(nil, remote.push_error); return end + result.push_error = remote.push_error + end + cb(result, reason) + end) + if pending then pipeline = job end + end) + return { cancel = function() + remote:cancel() + if pipeline then pipeline:cancel() end + end } +end + +---@param identity BookIdentity +---@param cb fun(pos: ProgressPosition|nil, err: string|nil, meta: table|nil) +function Source:getProgressAsync(identity, cb) + local cfg = require("utils.settings").getSource(self.id) + if not cfg.cookie or cfg.cookie == "" then return SourceBase.defer(cb, nil, nil, { empty = true }) end + local remote, toc_job = Client.newSync(false), nil + remote:checkAsync(function(account, err) + if remote.cancelled then return end + if not account then cb(nil, err); return end + remote:historyAsync(identity.stable_id, function(comic_id, reason) + if not comic_id then cb(nil, reason, not reason and { empty = true } or nil); return end + local function load(force) + local pending = true + local job = self:loadTocAsync(identity, function(toc, toc_err) + pending, toc_job = false, nil + if remote.cancelled then return end + if not remote:current() then cb(nil, _("登录状态已变化,请重试")); return end + if not toc then cb(nil, toc_err); return end + for idx, chapter in ipairs(toc) do + if chapter.uid == comic_id then + cb({ chapter_idx = idx, chapter_title = chapter.title, fraction = (idx - 1) / #toc }) + return + end + end + if not force then load(true); return end + cb(nil, _("快看云端章节不在当前目录中")) + end, force) + if pending then toc_job = job end + end + load(false) + end) + end) + return { cancel = function() + remote:cancel() + if toc_job then toc_job:cancel() end + end } +end + +---@param self KuaikanSource +---@param identity BookIdentity +---@param pos ProgressPosition +---@param cb fun(ok: boolean|nil, err: string|nil) +putProgressAsync = function(self, identity, pos, cb) + local remote, extra_job = Client.newSync(true), nil + remote:checkAsync(function(account, err) + if remote.cancelled then return end + if not account then cb(nil, err); return end + local pending = true + local job = self:loadTocAsync(identity, function(toc, toc_err) + pending, extra_job = false, nil + if remote.cancelled then return end + if not remote:current() then cb(nil, _("登录状态已变化,请重试")); return end + if not toc then cb(nil, toc_err); return end + local idx = pos.chapter_idx or identity.chapter_idx + if not idx then idx = math.min(#toc, math.floor(pos.fraction * #toc) + 1) end + if not toc[idx] then cb(nil, _("快看云端章节不在当前目录中")); return end + local function report(count) + if remote.cancelled then return end + if not remote:current() then cb(nil, _("登录状态已变化,请重试")); return end + local fraction = pos.chapter_fraction + if not fraction then fraction = math.max(0, math.min(1, pos.fraction * #toc - (idx - 1))) end + local record = Mapper.progressReport(identity.stable_id, toc[idx].uid, pos, fraction, count, os.time() * 1000) + if not record then cb(nil, _("响应无效")); return end + remote:reportProgressAsync(record, cb) + end + if pos.total_pages and pos.total_pages > 0 then report(pos.total_pages); return end + local fetching = true + local images_job = Client.imagesAsync(toc[idx].uid, function(urls, image_err) + fetching, extra_job = false, nil + if remote.cancelled then return end + if not urls then cb(nil, image_err); return end + report(#urls) + end) + if fetching then extra_job = images_job end + end) + if pending then extra_job = job end + end) + return { cancel = function() + remote:cancel() + if extra_job then extra_job:cancel() end + 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) + local node, limit = Mapper.storeNode(opts and opts.node), opts and opts.limit or 60 + local cancelled, active = false, nil + local loaded = false + local first = Client.storeAsync(node, 1, function(books, err, more, groups) + loaded = true + if cancelled then return end + active = nil + if not books then cb(nil, err); return end + local finished = false + local pages = require("source.browse").pages(function(page, done) + if page == 1 then done(books, nil, more); return end + return Client.storeAsync(node, page, done) + end, limit, groups, function(result, reason) + finished, active = true, nil + if cancelled then return end + if result then + for index = #result.data, limit + 1, -1 do result.data[index] = nil end + end + cb(result, reason) + end) + if not finished then active = pages end + end) + if not loaded then active = first end + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +---@param self KuaikanSource +---@param identity BookIdentity +---@param cb fun(page: table|nil, err: string|nil) +local function loadPage(self, identity, cb) + return Client.topicAsync(identity.stable_id, function(page, err) + if not page then cb(nil, err); return end + local chapters = Mapper.chapters(page.chapters) + if not chapters then cb(nil, _("漫画目录为空")); return end + if not Toc.put(self.id, identity.stable_id, chapters) then cb(nil, _("章节目录保存失败")); return end + page.chapters = chapters + page.book = Mapper.detail(page.info, page.nickname) + 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_kuaikan.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 loaded = false + local toc_job = self:loadTocAsync(identity, function(fresh, err) + loaded = true + active = nil + if cancelled then return end + if not fresh then closeDialog(); cb(nil, err); return end + local idx = startIndex(identity, opts, fresh) + local materialized = false + 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) + materialized = true + active = nil + closeDialog() + if cancelled then return end + if not path then cb(nil, materialize_err); return end + finish(path, idx) + end) + if not materialized then active = chapter_job end + end) + if not loaded then active = toc_job end + end) + return { cancel = function() + cancelled = true + if active then active.cancel() end + closeDialog() + end } +end + +function Source:bookReviewsAsync(identity, cb) + return Client.commentsAsync(identity.stable_id, function(items, err, pages) + if not items then cb(nil, err); return end + cb({ items = items, pages = pages, title = _("话题页评论(首话)") }) + end) +end + +function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb) + return require("moonsource_kuaikan.chapter").prefetchAsync(identity, toc, from_idx, count, nil, cb) +end + +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + local cancelled, active = false, nil + local loaded = false + local toc_job = self:loadTocAsync(identity, function(toc, err) + loaded = true + 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 finished = false + local cache_job = require("moonsource_kuaikan.chapter").prefetchAsync(identity, toc, from_idx, count, { + progress = on_progress, + interval_seconds = 1.5, + }, function(cached, total, failed, last_err) + finished, active = true, nil + if not cancelled then cb(failed == 0, cached, last_err, total, failed) end + end) + if not finished then active = cache_job end + end) + if not loaded then active = toc_job end + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +function Source:paragraphReviewsEnabled() + return require("source.review_setting").enabled(self.id) +end + +function Source:paragraphReviewPageAsync(identity, range, max_idx, cb) + return require("book.review_cache").pageAsync(identity, range, max_idx, function(done) + return require("source.with_chapter_uid").run(self, identity, _("目录为空"), + function(uid, finish) + return Client.commentPageAsync(uid, max_idx, function(items, err, _pages, page) + if not items then finish(nil, err); return end + for _idx, item in ipairs(items) do + if not item.id or item.id == "" or item.id == "0" then finish(nil, _("响应无效")); return end + item.content, item.replies = item.text, 0 + item.time = item.time or "" + end + finish({ items = items, total = page.total, max_idx = page.max_idx, more = page.more }) + end) + end, done) + end, cb) +end + +function Source:chapterReviewHotspotsAsync(identity, cb) + return self:paragraphReviewPageAsync(identity, "chapter", 0, function(page, err) + if not page then cb(nil, err); return end + cb({ { range = "chapter", text = identity.book and identity.book.title or "", + total = page.total, badge = tostring(page.total), heading = _("章节评论") } }) + end) +end + +return Kuaikan diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/verify.lua b/moonsource-kuaikan.koplugin/moonsource_kuaikan/verify.lua new file mode 100644 index 0000000..d6ff169 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/verify.lua @@ -0,0 +1,113 @@ +--[[-- +快看腾讯滑块。浏览器只交验证凭据,手机号、密码、短信码和候选 Cookie 留在设备。 +临时票据绑定本次输入与候选会话,五分钟截止,提交一次即收回。 + +@module moonsource_kuaikan.verify +--]] + +local Ext = require("utils.extension") +local _ = require("l10n").get("moonsource_kuaikan") + +---@class KuaikanVerification +---@field ticket string +---@field session KuaikanLogin +---@field submit (fun(captcha: table, cb: function))|nil +---@field callback fun(result: any, err: string|nil) +---@field expires integer +---@field dialog BookThemeQR|nil +---@field timeout function +---@field pending boolean|nil +---@field done boolean|nil +local Verification = {} +Verification.__index = Verification +---@type table +local sessions = {} + +function Verification:cancel() + if self.done then return end + self.done = true + sessions[self.ticket] = nil + require("ui/uimanager"):unschedule(self.timeout) + self.session:cancel() + local dialog = self.dialog + self.dialog = nil + if dialog then dialog:close() end + self.submit = nil +end + +function Verification:finish(result, err) + if self.done then return end + self:cancel() + self.callback(result, err) +end + +---@param session KuaikanLogin +---@param submit fun(captcha: table, cb: function) +---@param cb fun(result: any, err: string|nil) +---@return KuaikanVerification +function Verification.new(session, submit, cb) + local self = setmetatable({ + session = session, submit = submit, callback = cb, + ticket = require("utils.random").hex(24), expires = os.time() + 300, + }, Verification) + self.timeout = require("ui.guard").wrap("kuaikan verification timeout", function() + self:finish(nil, _("验证已过期,请重新发起验证")) + end) + sessions[self.ticket] = self + require("ui/uimanager"):scheduleIn(300, self.timeout) + self.dialog = Ext.call("web.open_page", "/kuaikan_verify.html#" .. self.ticket, + _("快看安全验证"), _("用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"), { + close_callback = function() self:finish(nil, _("验证已取消")) end, + }) + if not self.dialog then + self:finish(nil, _("无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能")) + end + return self +end + +local function handle(method, action, params, cb) + local function reply(status, body) + cb(status, body, { "Cache-Control: no-store" }) + end + if method ~= "POST" then return reply(405, { error = "Method Not Allowed" }) end + if action ~= "config" and action ~= "verify" then return reply(404, { error = "Not Found" }) end + local self = type(params.ticket) == "string" and sessions[params.ticket] + if not self or os.time() >= self.expires then + return reply(403, { error = _("验证已过期,请重新发起验证") }) + end + if action == "config" then + return reply(200, { + appid = "2034681882", title = _("快看安全验证"), instruction = _("请完成下方安全验证"), + pending = _("正在提交验证…"), success = _("验证已提交,请回到设备查看结果。"), + failure = _("验证失败,请重新验证"), load_error = _("滑块加载失败,请检查网络后刷新网页"), + cancelled = _("验证已取消"), retry = _("重试"), + }) + end + if type(params.captcha_ticket) ~= "string" or params.captcha_ticket == "" or #params.captcha_ticket > 4096 + or params.captcha_ticket:match("^trerror_") or type(params.randstr) ~= "string" + or params.randstr == "" or #params.randstr > 256 then + return reply(400, { error = _("验证凭据无效") }) + end + if self.pending then return reply(409, { error = _("正在提交验证…") }) end + self.pending = true + local submit = assert(self.submit, "active verification has no submission") + submit({ ticket = params.captcha_ticket, random = params.randstr }, function(result, err) + if self.done then return reply(403, { error = _("验证已过期,请重新发起验证") }) end + if os.time() >= self.expires then + self:finish(nil, _("验证已过期,请重新发起验证")) + return reply(403, { error = _("验证已过期,请重新发起验证") }) + end + if result then reply(200, { ok = true }) + else reply(400, { error = _("验证或登录失败,请回到设备查看并重试") }) end + self:finish(result, err) + end) +end + +local dir = debug.getinfo(1, "S").source:sub(2):match("(.*/)") +Ext.add("web.routes", { + name = "kuaikan_verify", dir = dir .. "web", + assets = { "kuaikan_verify.html", "kuaikan_verify.js" }, + public = { config = true, verify = true }, handle = handle, +}) + +return Verification diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/web/kuaikan_verify.html b/moonsource-kuaikan.koplugin/moonsource_kuaikan/web/kuaikan_verify.html new file mode 100644 index 0000000..ad274a2 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/web/kuaikan_verify.html @@ -0,0 +1,25 @@ + + + + + + +月读 + + + + +
+

月读

+

+
+

+ +
+ + + diff --git a/moonsource-kuaikan.koplugin/moonsource_kuaikan/web/kuaikan_verify.js b/moonsource-kuaikan.koplugin/moonsource_kuaikan/web/kuaikan_verify.js new file mode 100644 index 0000000..6f5dfd4 --- /dev/null +++ b/moonsource-kuaikan.koplugin/moonsource_kuaikan/web/kuaikan_verify.js @@ -0,0 +1,98 @@ +(async function () { + 'use strict'; + const ticket = location.hash.slice(1); + const status = document.getElementById('status'); + const retry = document.getElementById('retry'); + let messages, captcha, loading = true, submitting = false, done = false; + async function request(action, body) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 90000); + try { + const response = await fetch('/api/kuaikan_verify/' + action, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...body, ticket }), + signal: controller.signal, + }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || response.statusText); + return result; + } finally { + clearTimeout(timer); + } + } + function failed(error) { + status.textContent = error.message || messages.failure; + retry.hidden = false; + } + async function submit(result) { + if (done || submitting) return; + if (!result || result.ret !== 0 || result.errorCode || typeof result.ticket !== 'string' + || !result.ticket || typeof result.randstr !== 'string' || !result.randstr + || result.ticket.startsWith('trerror_')) { + failed(new Error(result && result.ret === 2 ? messages.cancelled : messages.failure)); + return; + } + submitting = true; + retry.hidden = true; + status.textContent = messages.pending; + try { + await request('verify', { captcha_ticket: result.ticket, randstr: result.randstr }); + done = true; + status.textContent = messages.success; + document.getElementById('captcha').hidden = true; + } catch (error) { + failed(error); + } finally { + submitting = false; + } + } + function loadScript() { + if (typeof window.TencentCaptcha === 'function') return Promise.resolve(); + return new Promise((resolve, reject) => { + const script = document.createElement('script'); + const timer = setTimeout(() => finish(messages.load_error), 20000); + function finish(error) { + clearTimeout(timer); + script.onload = script.onerror = null; + if (error) { script.remove(); reject(new Error(error)); } + else resolve(); + } + script.src = 'https://turing.captcha.qcloud.com/TJCaptcha.js'; + script.onload = () => finish(typeof window.TencentCaptcha === 'function' ? null : messages.load_error); + script.onerror = () => finish(messages.load_error); + document.head.appendChild(script); + }); + } + async function load() { + await loadScript(); + if (captcha) captcha.destroy(); + document.getElementById('captcha').hidden = false; + document.getElementById('captcha').innerHTML = ''; + captcha = new window.TencentCaptcha(document.getElementById('captcha'), messages.appid, submit, { + type: 'embed', userLanguage: 'zh-cn', + }); + captcha.show(); + } + retry.onclick = async () => { + if (done || loading || submitting) return; + loading = true; + retry.hidden = true; + status.textContent = ''; + try { messages = await request('config', {}); await load(); } + catch (error) { failed(error); } + finally { loading = false; } + }; + try { + messages = await request('config', {}); + document.title = document.getElementById('title').textContent = messages.title; + document.getElementById('instruction').textContent = messages.instruction; + retry.textContent = messages.retry; + await load(); + } catch (error) { + if (messages) failed(error); + else status.textContent = error.message; + } finally { + loading = false; + } +})(); diff --git a/tests/kuaikan/browse_spec.lua b/tests/kuaikan/browse_spec.lua new file mode 100644 index 0000000..bc862d3 --- /dev/null +++ b/tests/kuaikan/browse_spec.lua @@ -0,0 +1,103 @@ +--[[-- +快看分类:官网动态题材、独立筛选、聚合分页与取消。 + +@module tests.moonsource_kuaikan.browse_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +package.loaded.json = JSON +local Mapper = require("moonsource_kuaikan.mapper") +local Request = require("http.request") +local calls, waiting, cancelled = {}, nil, {} +local failure +local function wire(page) + local rows = {} + for index = 1, page == 1 and 48 or 47 do + rows[index] = { + id = (page - 1) * 48 + index, title = "漫画 " .. index, + author_name = "作者", vertical_image_url = "https://img/cover.jpg", + } + end + return { + code = 200, total = 200, + hits = { topicCategories = { { tag_id = 0, title = "全部" }, { tagId = 20, title = "恋爱" } }, + topicMessageList = rows }, + } +end +Request.get = function(url, options, cb) + calls[#calls + 1] = url + Assert.is_nil(options.headers.Cookie) + local page = tonumber(url:match("page=(%d+)")) + if page == 2 and waiting then + waiting = cb + return { cancel = function() cancelled[page] = true end } + end + cb(page == 2 and failure or JSON.encode(wire(page))) + return { cancel = function() cancelled[page] = true end } +end +local Client = require("moonsource_kuaikan.client") +local source = require("moonsource_kuaikan.source").new() +local result, reason +source:browseAsync({ limit = 60 }, function(res, err) result, reason = res, err end) +Assert.is_nil(reason) +Assert.len(result.data, 60) +Assert.eq(result.data[49].stable_id, "49") +Assert.eq(result.data[1].authors, "作者") +Assert.len(calls, 2) +Assert.len(result.groups, 5) +Assert.eq(result.groups[1].chips[2].id, "20:1:0:0:1") + +local node = "20:3:2:1:2" +local list, groups, more = Mapper.store(wire(2), node, 2) +Assert.len(list, 47) +Assert.is_true(more) +Assert.eq(groups[1].active, node) +Assert.eq(groups[1].chips[1].id, "0:3:2:1:2") +Assert.eq(groups[2].chips[2].id, "20:2:2:1:2") +Assert.eq(groups[3].chips[2].id, "20:3:1:1:2") +Assert.eq(groups[4].chips[3].id, "20:3:2:2:2") +Assert.eq(groups[5].chips[3].id, "20:3:2:1:3") +source:browseAsync({ node = node, limit = 12 }, function(res) result = res end) +Assert.len(result.data, 12) +Assert.matches(calls[#calls], "tag_id=20") +Assert.matches(calls[#calls], "label_dimension_origin=3") +Assert.matches(calls[#calls], "pay_status=2") +Assert.matches(calls[#calls], "update_status=1") +Assert.matches(calls[#calls], "sort=2") + +local terminal = wire(3) +terminal.total = 100 +Assert.is_false(select(3, Mapper.store(terminal, node, 3))) +terminal.hits.topicMessageList = {} +Assert.len(Mapper.store(terminal, node, 3), 0) +terminal.hits.topicMessageList = { { id = 1 } } +Assert.is_nil(Mapper.store(terminal, node, 3)) +Assert.is_nil(Mapper.store({ code = 200, hits = {} }, node, 1)) +Assert.eq(Mapper.storeNode("20:9:0:0:1"), "0:1:0:0:1") +Assert.eq(Mapper.storeNode("旧热门榜单"), "0:1:0:0:1") + +failure = JSON.encode({ code = 500 }) +result, reason = nil, nil +source:browseAsync({ limit = 60 }, function(res, err) result, reason = res, err end) +Assert.is_nil(result) +Assert.is_true(reason ~= nil) +failure = nil +waiting = true +local called = false +local handle = source:browseAsync({ limit = 60 }, function() called = true end) +handle.cancel() +Assert.is_true(cancelled[2]) +Assert.is_nil(cancelled[1]) +waiting(JSON.encode(wire(2))) +Assert.is_false(called) + +Request.get = function(_url, _options, cb) + cb(nil, "network failure") + return { cancel = function() end } +end +Client.storeAsync(node, 1, function(books, err) + Assert.is_nil(books) + Assert.eq(err, "network failure") +end) diff --git a/tests/kuaikan/chapter_spec.lua b/tests/kuaikan/chapter_spec.lua new file mode 100644 index 0000000..f852c0b --- /dev/null +++ b/tests/kuaikan/chapter_spec.lua @@ -0,0 +1,92 @@ +--[[-- +快看章节:以服务端权限为准,分阶段取消不能覆盖在飞下载。 + +@module tests.moonsource_kuaikan.chapter_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local Config = require("support.config") +local paths = {} +package.loaded["utils.paths"] = { + bookWorkDir = function() return Config.dir() .. "/kuaikan-chapter" end, + ensureBookWork = function() end, + ensureDir = function() end, +} +package.loaded["source.cbz"] = { + ready = function() return false end, + build = function(files, archive, _state, cb) paths = files; cb(archive) end, +} +package.loaded["utils.image"] = { + suffix = function() return ".jpg" end, + ok = function(path) return paths[path] == true end, +} +local fetched, pending, cancelled = false, nil, {} +package.loaded["moonsource_kuaikan.client"] = { + imagesAsync = function(_uid, cb) + fetched = true + 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) paths[path] = ok; cb(ok, err) end + return { cancel = function() cancelled.download = true end } + end, +} +local Chapter = require("moonsource_kuaikan.chapter") +local called = false +local identity = { source_id = "ext.kuaikan", stable_id = "book" } +local handle = Chapter.materializeAsync(identity, { uid = "1", vip = true }, nil, function() called = true end) +Assert.is_true(fetched) +handle.cancel() +Assert.is_true(cancelled.download) +Assert.is_nil(cancelled.images) +pending(true) +Stubs.flush() +Assert.is_false(called) + +paths = {} +local downloaded, progress, result = 0, {}, nil +require("http.request").download = function(_opts, path, cb) + downloaded = downloaded + 1 + paths[path] = true + cb(true) + return { cancel = function() end } +end +Chapter.materializeAsync(identity, { uid = "1", vip = true }, function(done, total) + progress[#progress + 1] = { done, total } +end, function(path) result = path end) +Stubs.flush() +Assert.eq(downloaded, 2) +Assert.len(progress, 2) +Assert.eq(progress[2][1], 2) +Assert.eq(progress[2][2], 2) +Assert.matches(result, "/1%.cbz$") +Assert.len(paths, 2) + +require("moonsource_kuaikan.client").imagesAsync = function(_uid, cb) + cb(nil, "本章未购买") + return { cancel = function() end } +end +Chapter.materializeAsync(identity, { uid = "2", vip = true }, nil, function(path, err) + Assert.is_nil(path) + Assert.eq(err, "本章未购买") +end) + +-- 已有 CBZ 只复用缓存,不取页图、不重新组装。 +require("source.cbz").ready = function() return true end +require("source.cbz").build = function() error("缓存 CBZ 不得重新组装") end +require("moonsource_kuaikan.client").imagesAsync = function() error("缓存命中不得下载页图") end +local cached +Chapter.materializeAsync(identity, { uid = "cached" }, nil, function(path) cached = path end) +Stubs.flush() +Assert.matches(cached, "/cached%.cbz$") +local cancelled_cache = false +local cached_handle = Chapter.materializeAsync(identity, { uid = "cached" }, nil, + function() cancelled_cache = true end) +cached_handle.cancel() +Stubs.flush() +Assert.is_false(cancelled_cache, "缓存交接也尊重取消") diff --git a/tests/kuaikan/client_spec.lua b/tests/kuaikan/client_spec.lua new file mode 100644 index 0000000..cf39278 --- /dev/null +++ b/tests/kuaikan/client_spec.lua @@ -0,0 +1,307 @@ +--[[-- +快看:签名、话题页目录、搜索和页图。 + +@module tests.moonsource_kuaikan.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_kuaikan.mapper") +local Page = require("moonsource_kuaikan.page") + +local html = [[ + +]] +local page = Page.topic(html) +Assert.eq(page.nickname, "翘摇") +Assert.eq(page.info.id, 9) +Assert.eq(page.info.title, "错撩") +Assert.eq(page.info.cover_image_url, "https://c/a.jpg") +Assert.eq(page.info.first_comic_id, 42) +Assert.eq(#page.chapters, 2) +Assert.eq(page.chapters[1].title, "序章") +Assert.eq(page.chapters[1].locked, false) +Assert.eq(page.chapters[2].locked, true) +Assert.is_nil(Page.topic("")) +local escaped = Page.topic(html:gsub("简介", "第一行\\n第二行\\t\\\"引号\\\"")) +Assert.eq(escaped.info.description, '第一行\n第二行\t"引号"') +Assert.is_nil(Page.topic(html:gsub('title:"第二话"', 'title:'))) +Assert.is_nil(Page.topic(html:gsub("true,42", "true,@"))) + +local detail = Mapper.detail(page.info, page.nickname) +Assert.eq(detail.stable_id, "9") +Assert.eq(detail.authors, "翘摇") +Assert.eq(detail.cover, "https://c/a.jpg") +Assert.eq(detail.source_id, "ext.kuaikan") +Assert.eq(detail.intro, "简介") +local toc = Mapper.chapters(page.chapters) +Assert.eq(#toc, 2) +Assert.eq(toc[1].uid, "9") +Assert.eq(toc[1].vip, false) +Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION) +Assert.eq(toc[2].vip, true) + +local found = Mapper.search({ + code = 200, + data = { topics = { hit = { { id = 9, title = "错撩", user = { nickname = "翘摇" }, vertical_image_url = "https://img/a.webp" } } } }, +}) +Assert.eq(found[1].stable_id, "9") +Assert.eq(found[1].authors, "翘摇") +Assert.eq(found[1].cover, "https://img/a.webp") +Assert.is_nil(Mapper.search({ code = 403 })) + +local home = Mapper.home({ + code = 200, + data = { popularity_topics = { { id = 3, title = "榜上", cover_image_url = "https://img/b.webp" } } }, +}) +Assert.eq(home[1].stable_id, "3") +Assert.eq(home[1].cover, "https://img/b.webp") + +local fav = Mapper.fav({ + code = 200, + data = { total = 1, topics = { { id = 9, title = "错撩", user = { nickname = "翘摇" }, vertical_image_url = "https://img/a.webp" } } }, +}) +Assert.eq(fav[1].stable_id, "9") +Assert.eq(fav[1].title, "错撩") +Assert.eq(#Mapper.fav({ code = 200, data = { total = 0, topics = {} } }), 0) +Assert.is_nil(Mapper.fav({ code = 200, data = {} })) + +local urls = Mapper.images({ + code = 200, + data = { comic_info = { locked = false, comic_images = { { url = "https://img/1.jpg" }, { url = "https://img/2.jpg" } } } }, +}) +Assert.eq(#urls, 2) +Assert.eq(urls[1], "https://img/1.jpg") +Assert.eq(select(2, Mapper.images({ code = 200, data = { comic_info = { locked = true, comic_images = {} } } })), "locked") +Assert.eq(Mapper.images({ code = 200, data = { comic_info = { locked = false, comic_images = { + { url = "https://img/original.jpg", url1280 = "https://img/large.jpg" }, + { url = "https://img/fallback.jpg", url1280 = "" }, +} } } })[1], "https://img/large.jpg") +Assert.eq(Mapper.images({ code = 200, data = { comic_info = { comic_images = { + { url = "https://img/fallback.jpg", url1280 = "" }, +} } } })[1], "https://img/fallback.jpg") +Assert.is_nil(Mapper.fav({ code = 200, data = { total = 1, topics = { { id = 9 } } } })) +Assert.is_nil(Mapper.fav({ code = 200, data = { topics = {} } })) + +local Client = require("moonsource_kuaikan.client") +local indexes = {} +for slot = 0, 15 do indexes[#indexes + 1] = slot end +Assert.eq( + Client.answer("1793924589213", indexes), + "MjAyMDA4MjBfMEIxdDJNM1Q0VTVsNmU3czhMOVgxMFAxMUkxMkYxM2oxNGYxNWNfMTc5MzkyNDU4OTIxM18zVDRVNWw2ZTdzOEw5WDEwUDExSTEyRjEzajE0ZjE1Yw==" +) + +local requests, options = {}, {} +local cfg = { cookie = "session=saved" } +package.loaded["utils.settings"] = { getSource = function() return cfg end } +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, request_options, callback) + requests[#requests + 1] = url + options[#options + 1] = request_options + if url:find("/search/web/complex", 1, true) then + callback(Json.encode({ code = 200, data = { topics = { hit = { { id = 9, title = "错撩" } } } } }), nil, nil) + elseif url:find("/v2/pweb/fav/topics", 1, true) then + callback(Json.encode({ code = 200, data = { total = 1, topics = { { id = 9, title = "错撩" } } } }), nil, nil) + elseif url:find("/v2/pweb/home", 1, true) then + callback(Json.encode({ code = 200, data = { popularity_topics = { { id = 3, title = "榜上" } } } }), nil, nil) + elseif url:find("/web/topic/", 1, true) then + callback(html, nil, nil) + elseif url:find("/v1/aegis/", 1, true) then + callback("ok", nil, { headers = { ["set-cookie"] = "kk_s_t=1793924589213; Path=/" } }) + elseif url:find("/v2/comments/comic/", 1, true) then + callback(Json.encode({ + code = 200, + data = { + total = 80, + comments = { + { replied_comment_id = 0, content = "好看", likes_count = 3, created_at_info = "2020-01-02 12:00", user = { nickname = "甲" } }, + { replied_comment_id = 9, content = "回复", user = { nickname = "乙" } }, + }, + }, + }), nil, nil) + elseif url:find("/v2/pweb/comic/", 1, true) then + callback(Json.encode({ code = 200, data = { comic_info = { comic_images = { { url = "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_kuaikan.client"] = nil + +Client = require("moonsource_kuaikan.client") +local books +Client.searchAsync("错撩", function(list) books = list end) +Assert.eq(books[1].title, "错撩") +Assert.is_true(requests[#requests]:find("q=", 1, true) ~= nil) +Assert.is_nil(options[#options].headers.Cookie) +Assert.matches(options[#options].headers["User-Agent-PC"], "PCKuaikan/") + +local ranked +Client.homeAsync(function(list) ranked = list end) +Assert.eq(ranked[1].stable_id, "3") + +local fav_books +Client.favAsync(function(list) fav_books = list end) +Assert.eq(fav_books[1].title, "错撩") +Assert.is_true(requests[#requests]:find("/v2/pweb/fav/topics?since=0&limit=20", 1, true) ~= nil) +Assert.eq(options[#options].headers.Cookie, "session=saved") +Assert.eq(options[#options].cache_ttl, 0) + +local loaded +Client.topicAsync("9", function(value) loaded = value end) +Assert.eq(#loaded.chapters, 2) +Assert.is_nil(options[#options].headers.Cookie) + +local images +cfg.cookie = "session=saved; kk_s_t=stale" +Client.imagesAsync("9", function(list) images = list end) +Assert.eq(images[1], "https://img/1.jpg") +Assert.is_true(requests[#requests]:find("answer=", 1, true) ~= nil) +Assert.eq(options[#options].headers.Cookie, "session=saved; kk_s_t=1793924589213") +Assert.eq(options[#options].cache_ttl, 0) +Assert.eq(options[#options - 1].cache_ttl, 0) +Assert.is_nil(options[#options - 1].headers.Cookie) +Assert.eq(options[#options].headers.width, "564") +Assert.matches(options[#options].headers.Referer, "/webs/comic%-next/9") + +local reviews, total = Mapper.comments({ + code = 200, + data = { + total = 1, + comments = { { replied_comment_id = 0, content = "好看", user = { nickname = "甲" }, created_at_info = "2020-01-02 12:00", likes_count = 3 } }, + }, +}) +Assert.eq(#reviews, 1) +Assert.eq(reviews[1].author, "甲") +Assert.eq(reviews[1].time, "2020-01-02") +Assert.eq(reviews[1].likes, 3) +Assert.eq(total, 1) +Assert.is_nil(Mapper.comments({ code = 200, data = {} })) +Assert.is_nil(Mapper.comments({ code = 200, data = { total = 1, comments = { {} } } })) +Assert.is_nil(Mapper.images({ code = 200, data = { comic_info = { + comic_images = { { url = "https://img/1.jpg" }, {} }, +} } })) + +local loaded_reviews, review_err, pages +Client.commentsAsync("9", function(items, err, count) loaded_reviews, review_err, pages = items, err, count end) +Assert.is_nil(review_err) +Assert.eq(#loaded_reviews, 1) +Assert.eq(loaded_reviews[1].text, "好看") +Assert.eq(pages, 2) +Assert.eq(requests[#requests]:find("/v2/comments/comic/42/order/score?offset=0&limit=50&total=true", 1, true) ~= nil, true) +Assert.is_nil(options[#options].headers.Cookie) +Client.commentPageAsync("42", 50, function(items) loaded_reviews = items end) +Assert.eq(#loaded_reviews, 1) +Assert.matches(requests[#requests], "offset=50") + +local pending, cancelled = nil, {} +local Request = require("http.request") +Request.get = function(url, request_options, callback) + if url:find("/v1/aegis/", 1, true) then + callback("ok", nil, { headers = { ["set-cookie"] = "kk_s_t=test; Path=/" } }) + return { cancel = function() cancelled.challenge = true end } + end + pending = callback + return { cancel = function() cancelled.content = true end } +end +local called = false +local handle = Client.imagesAsync("42", function() called = true end) +handle.cancel() +Assert.is_true(cancelled.content) +Assert.is_nil(cancelled.challenge) +pending(Json.encode({ code = 200, data = { comic_info = { comic_images = { { url = "https://img/1.jpg" } } } } })) +Assert.is_false(called) + +Request.get = function(url, request_options, callback) + if url:find("/web/topic/", 1, true) then + callback(html) + return { cancel = function() cancelled.topic = true end } + end + pending = callback + return { cancel = function() cancelled.comments = true end } +end +handle = Client.commentsAsync("9", function() called = true end) +handle.cancel() +Assert.is_true(cancelled.comments) +Assert.is_nil(cancelled.topic) +pending(Json.encode({ code = 200, data = { total = 0, comments = {} } })) +Assert.is_false(called) + +for _idx, response in ipairs({ + { raw = "not-json" }, { raw = Json.encode({ code = 400 }) }, { err = "network failure" }, +}) do + Request.get = function(_url, _options, callback) + callback(response.raw, response.err) + return { cancel = function() end } + end + + local offset_queries = {} + Request.get = function(url, request_options, callback) + offset_queries[#offset_queries + 1] = url:match("since=(%d+)") + Assert.eq(request_options.headers.Cookie, "session=fixed") + Assert.eq(request_options.cache_ttl, 0) + local offset = tonumber(offset_queries[#offset_queries]) + local rows = offset == 0 and { { id = 1, title = "甲" }, { id = 2, title = "乙" } } + or { { id = 2, title = "乙" }, { id = 3, title = "丙" } } + callback(Json.encode({ code = 200, data = { total = 4, topics = rows } })) + return { cancel = function() end } + end + Client.favAsync(function(list, err) + Assert.is_nil(err) + Assert.len(list, 3) + Assert.eq(list[3].stable_id, "3") + end, "session=fixed") + Assert.eq(table.concat(offset_queries, ","), "0,2") + + for _idx, failure in ipairs({ + { raw = "bad-json" }, { err = "offline" }, + { raw = Json.encode({ code = 200, data = { total = 4, topics = {} } }) }, + { raw = Json.encode({ code = 200, data = { total = 4, topics = { { id = 1, title = "甲" }, { id = 2, title = "乙" } } } }) }, + }) do + Request.get = function(url, _options, callback) + if url:find("since=0", 1, true) then + callback(Json.encode({ code = 200, data = { total = 4, topics = { + { id = 1, title = "甲" }, { id = 2, title = "乙" }, + } } })) + else + callback(failure.raw, failure.err) + end + return { cancel = function() end } + end + Client.favAsync(function(list, err) + Assert.is_nil(list, "中间页失败不能发布半个书架") + Assert.is_true(type(err) == "string" and err ~= "") + end) + end + + local shelf_cancelled + Request.get = function(url, _options, callback) + if url:find("since=0", 1, true) then + callback(Json.encode({ code = 200, data = { total = 2, topics = { { id = 1, title = "甲" } } } })) + return { cancel = function() error("不能取消已结束的首页") end } + end + pending = callback + return { cancel = function() shelf_cancelled = true end } + end + called = false + handle = Client.favAsync(function() called = true end) + handle.cancel() + Assert.is_true(shelf_cancelled) + pending(Json.encode({ code = 200, data = { total = 2, topics = { { id = 2, title = "乙" } } } })) + Assert.is_false(called) + Client.commentPageAsync("42", 0, function(items, err) + Assert.is_nil(items) + Assert.is_true(type(err) == "string" and err ~= "") + end) +end diff --git a/tests/kuaikan/login_spec.lua b/tests/kuaikan/login_spec.lua new file mode 100644 index 0000000..c18a05b --- /dev/null +++ b/tests/kuaikan/login_spec.lua @@ -0,0 +1,245 @@ +--[[-- +快看登录:官方账号校验、取消、旧账号迁移和受限微信回调。 + +@module tests.moonsource_kuaikan.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") +package.loaded["json"] = JSON +local cfg, requests, saves = {}, {}, 0 +local cleared = 0 +package.loaded["source.logout"] = { clear = function(_id, clear) + clear(); cleared = cleared + 1; return true +end } +package.loaded["utils.settings"] = { + getSource = function() return cfg end, + saveSource = function() saves = saves + 1 end, +} +package.loaded["source.auth"] = { ok = function() end } +local Request = { + header = function(res, key) return res and res.headers and res.headers[key] end, + headerAll = function(res, key) return res and res.headers and res.headers[key] or {} end, + get = function(url, opts, cb) + local request = { url = url, opts = opts, cb = cb } + requests[#requests + 1] = request + return { cancel = function() request.cancelled = true end } + end, +} +package.loaded["http.request"] = Request +local Client = require("moonsource_kuaikan.client") +local Mapper = require("moonsource_kuaikan.mapper") +local Login = require("moonsource_kuaikan.login") +local function account(id, authenticate) + return JSON.encode({ code = 200, data = { user_info = { user_id = id, authenticate = authenticate or 1 } } }) +end +local value, reason +local function answer(result, err) value, reason = result, err end +local function cookie(text) + local session = Login.new() + session:cookieAsync(text, answer) + return session, requests[#requests] +end + +local session, request = cookie("Cookie: sid=first") +Assert.eq(request.url, Client.ACCOUNT_URL) +Assert.eq(request.opts.headers.Cookie, "sid=first") +Assert.eq(request.opts.cache_ttl, 0) +Assert.is_nil(request.url:find("sid", 1, true)) +Assert.is_nil(cfg.cookie) +request.cb(account(7)) +Assert.eq(value.user_id, "7") +Assert.eq(cfg.cookie, "sid=first") +Assert.is_true(cfg.logged_in) +Assert.eq(saves, 1) + +for _idx, response in ipairs({ + { raw = "broken" }, { raw = account(0) }, { raw = account(7, 0) }, + { raw = JSON.encode({ code = 200, data = { user_info = {} } }) }, + { raw = account("7.1") }, { raw = JSON.encode({ code = 500 }) }, { err = "offline" }, +}) do + session, request = cookie("sid=invalid") + request.cb(response.raw, response.err) + Assert.is_nil(value) + Assert.is_true(type(reason) == "string") + Assert.eq(cfg.cookie, "sid=first") +end +session, request = cookie("sid=other") +request.cb(account(8)) +Assert.is_nil(reason) +Assert.eq(cfg.user_id, "8") +Assert.eq(cleared, 1) + +local calls = 0 +session = Login.new() +session:cookieAsync("sid=cancelled", function() calls = calls + 1 end) +request = requests[#requests] +session:cancel() +Assert.is_true(request.cancelled) +request.cb(account(7)) +Assert.eq(calls, 0) +Assert.eq(cfg.cookie, "sid=other") + +local _old, late = cookie("sid=old") +session, request = cookie("sid=latest") +request.cb(account(7)) +late.cb(account(7)) +Assert.eq(cfg.cookie, "sid=latest") +Assert.eq(reason, "登录状态已变化,请重试") +session, request = cookie("sid=after-logout") +cfg.cookie, cfg.user_id, cfg.logged_in = nil, nil, nil +Client.login_revision = Client.login_revision + 1 +request.cb(account(7)) +Assert.is_nil(cfg.cookie) + +cfg = { cookie = "sid=legacy" } +session, request = cookie("sid=renewed") +local before = #requests +request.cb(account(7)) +Assert.eq(#requests, before, "不再查询旧 Cookie") +Assert.eq(cfg.cookie, "sid=renewed") +Assert.eq(cfg.user_id, "7") +cfg = { cookie = "sid=legacy-other" } +session, request = cookie("sid=new") +request.cb(account(8)) +Assert.eq(cfg.cookie, "sid=new") +Assert.eq(cfg.user_id, "8") +Assert.is_nil(reason) +cfg = { cookie = "sid=legacy-offline" } +session, request = cookie("sid=new") +request.cb(nil, "network") +Assert.eq(reason, "network") +Assert.eq(cfg.cookie, "sid=legacy-offline") +cfg = { cookie = "sid=legacy-expired" } +session, request = cookie("sid=new") +request.cb(account(8)) +Assert.eq(cfg.user_id, "8") +Assert.eq(cfg.cookie, "sid=new", "旧账号失效不妨碍新账号登录") +Assert.is_nil(reason) + +local redirect = "https://open.weixin.qq.com/connect/qrconnect?" .. Text.formEncode({ + appid = "wx92ba65b18ed55877", scope = "snsapi_login", response_type = "code", + redirect_uri = Mapper.WECHAT_CALLBACK, state = "opaque+state", +}) +Assert.eq(Mapper.qrLocation(redirect).state, "opaque+state") +Assert.is_nil(Mapper.qrLocation(redirect:gsub("wx92ba65b18ed55877", "wrong"))) +Assert.is_nil(Mapper.qrLocation(redirect:gsub("open.weixin.qq.com", "evil.test"))) +Assert.is_nil(Mapper.qrLocation(redirect .. "&state=another")) +Assert.eq(Mapper.qrStatus("window.wx_errcode=408; window.wx_code='';"), 408) +Assert.eq(Mapper.qrStatus(JSON.encode({ wx_errcode = 404 })), 404) +Assert.eq(select(2, Mapper.qrStatus(JSON.encode({ wx_errcode = 405, wx_code = "confirmed" }))), "confirmed") +Assert.is_nil(Mapper.qrStatus(JSON.encode({ wx_errcode = 405 }))) + +cfg = {} +session = Login.new() +local uuid +session:qrCreateAsync(function(id, err) uuid, reason = id, err end) +request = requests[#requests] +Assert.is_nil(request.opts.headers.Cookie) +request.cb(nil, "HTTP 302", { code = 302, headers = { + Location = redirect, + ["Set-Cookie"] = { "nonce=anonymous; Domain=.kuaikanmanhua.com; Path=/", + "scoped=callback; Path=/v1/passport", "nested=api; PATH=/v2/", + "evil=blocked; Domain=evil.test; Path=/" }, +} }) +request = requests[#requests] +Assert.eq(request.url, redirect) +Assert.is_nil(request.opts.headers.Cookie) +Assert.eq(request.opts.cache_ttl, 0) +request.cb('') +Assert.eq(uuid, "test-uuid") +session:qrPollAsync(uuid, nil, function(status) value = status end) +request = requests[#requests] +Assert.is_nil(request.opts.headers.Cookie) +request.cb("window.wx_errcode=408;") +Assert.eq(value, 408) +session:exchangeAsync("confirmed", answer) +request = requests[#requests] +Assert.matches(request.url, "^https://www%.kuaikanmanhua%.com/v1/passport/login/pc/user_wechat_login_check%?") +Assert.matches(request.url, "state=opaque%%2Bstate") +Assert.eq(request.opts.headers.Cookie, "nonce=anonymous; scoped=callback") +request.cb(nil, "HTTP 302", { code = 302, headers = { + Location = "/webs/loginh", + ["Set-Cookie"] = { "sid=authorized; Domain=.kuaikanmanhua.com; Path=/", + "nonce=; Path=/; Max-Age=0" }, +} }) +request = requests[#requests] +Assert.eq(request.opts.headers.Cookie, "sid=authorized") +request.cb("callback complete") +Assert.eq(requests[#requests].opts.headers.Cookie, "nested=api; sid=authorized") +requests[#requests].cb(account(7)) +Assert.eq(value.user_id, "7") +Assert.eq(cfg.cookie, "nested=api; sid=authorized") +Assert.is_nil(cfg.cookie:find("evil", 1, true)) +Assert.is_nil(cfg.cookie:find("scoped", 1, true)) + +cfg = {} +session = Login.new() +session.state = "test" +session:exchangeAsync("code", answer) +request = requests[#requests] +local count = #requests +request.cb(nil, "HTTP 302", { code = 302, headers = { Location = "https://evil.test/" } }) +Assert.eq(#requests, count) +Assert.eq(reason, "登录响应无效") +Assert.is_nil(cfg.cookie) + +local original_get = Request.get +Request.get = function(url, opts, cb) + if url:find("/user_wechat_login?", 1, true) then + cb(nil, "HTTP 302", { code = 302, headers = { Location = redirect } }) + return { cancel = function() error("cancelled completed initialization") end } + end + return original_get(url, opts, cb) +end +session = Login.new() +session:qrCreateAsync(function() calls = calls + 1 end) +request = requests[#requests] +session:cancel() +Assert.is_true(request.cancelled) +request.cb('') +Assert.eq(calls, 0) + +local expired +value, reason, expired = Client.accountResponse(nil, "HTTP 302", { code = 302, headers = { Location = "/webs/loginh?redirect=x" } }) +Assert.is_true(expired) +value, reason, expired = Client.accountResponse(nil, "HTTP 302", { code = 302, headers = { Location = "/webs/loginhacker" } }) +Assert.is_nil(expired) + +Request.get = original_get +local expired_calls, image_calls = 0, 0 +package.loaded["source.auth"] = { + ok = function() end, + expire = function() expired_calls = expired_calls + 1 end, +} +local function locked() + cfg = { cookie = "sid=reader", user_id = "7", logged_in = true } + local handle = Client.imagesAsync("locked", function(_urls, err) image_calls = image_calls + 1; reason = err end) + requests[#requests].cb("ok", nil, { headers = { ["set-cookie"] = { "kk_s_t=challenge; Path=/" } } }) + requests[#requests].cb(JSON.encode({ code = 200, data = { comic_info = { locked = true } } })) + Assert.eq(requests[#requests].opts.headers.Cookie, "sid=reader") + return handle, requests[#requests] +end +local handle +handle, request = locked() +request.cb(account(7)) +Assert.eq(reason, "本章未购买") +Assert.eq(expired_calls, 0) +handle, request = locked() +request.cb(account(0, 0)) +Assert.eq(expired_calls, 1) +Assert.eq(reason, "快看登录已失效,请重新登录") +handle, request = locked() +cfg.cookie, cfg.user_id = "sid=new-account", "8" +request.cb(account(0, 0)) +Assert.eq(expired_calls, 1) +Assert.eq(reason, "登录状态已变化,请重试") +handle, request = locked() +local before_calls = image_calls +handle.cancel() +Assert.is_true(request.cancelled) +request.cb(account(0, 0)) +Assert.eq(image_calls, before_calls) +Assert.eq(expired_calls, 1) diff --git a/tests/kuaikan/mobile_spec.lua b/tests/kuaikan/mobile_spec.lua new file mode 100644 index 0000000..cf5553f --- /dev/null +++ b/tests/kuaikan/mobile_spec.lua @@ -0,0 +1,128 @@ +--[[-- +快看密码加密与短信登录会话:实际 Web 字段、错误、冷却、账号确认及阶段取消。 + +@module tests.moonsource_kuaikan.mobile_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") +package.loaded["json"] = JSON +local cfg, requests, saves = { cookie = "sid=old", user_id = "7" }, {}, 0 +package.loaded["utils.settings"] = { + getSource = function() return cfg end, saveSource = function() saves = saves + 1 end, +} +package.loaded["source.auth"] = { ok = function() end } +local Request = { + header = function() end, + headerAll = function(res) return res and res.cookies or {} end, +} +local function record(url, body, opts, cb) + local fields = {} + for key, value in (body or ""):gmatch("([^&=]+)=([^&]*)") do fields[Text.urlDecode(key)] = Text.urlDecode(value) end + local r = { url = url, body = body, fields = fields, opts = opts, cb = cb } + requests[#requests + 1] = r + return { cancel = function() r.cancelled = true end } +end +Request.get = function(url, opts, cb) return record(url, nil, opts, cb) end +Request.post = record +package.loaded["http.request"] = Request +local Mapper = require("moonsource_kuaikan.mapper") +local Client = require("moonsource_kuaikan.client") +local Login = require("moonsource_kuaikan.login") +local phone, proof = "+86-13800000000", { ticket = "captcha-proof", random = "random-proof" } +Assert.eq(Mapper.phone(" +86 ", "13800000000 "), phone) +Assert.eq(Mapper.phone("+852", "12345678"), "+852-12345678") +Assert.is_nil(Mapper.phone("+86", "12345678")) +Assert.is_nil(Mapper.phone("86", "13800000000")) +Assert.is_nil(Mapper.phone("+1", "12")) +local fields = Mapper.passwordFields(phone, " pass测试 😀 ", proof) +Assert.eq(fields.phone, "YhyUbUo+Y1hLLsQUeDEwwg==") +Assert.eq(fields.password, "DNsZnApMIYKSb60EXagwMryIBWUDl2peUULxGpgYDOQ=") +Assert.eq(fields.verify_provider, "tencent") +local good = JSON.encode({ code = 200 }) +local account = JSON.encode({ code = 200, data = { user_info = { authenticate = 1, user_id = 7 } } }) +local value, reason +local function answer(v, err) value, reason = v, err end +local session = Login.new() +session:passwordAsync(phone, " pass测试 😀 ", proof, answer) +local r = requests[#requests] +Assert.matches(r.url, "/v2/passport/pc/v2/mobile_pwd_login_encrypted$") +Assert.eq(r.opts.content_type, "application/x-www-form-urlencoded") +Assert.eq(r.opts.cache_ttl, 0) +Assert.is_nil(r.opts.headers.Cookie) +Assert.is_nil(r.body:find(phone, 1, true)) +Assert.is_nil(r.body:find(Text.urlEncode(" pass测试 😀 "), 1, true)) +Assert.eq(r.fields.password, fields.password) +r.cb(good, nil, { cookies = { "sid=new; Path=/" } }) +Assert.eq(requests[#requests].url, Client.ACCOUNT_URL) +Assert.eq(cfg.cookie, "sid=old") +requests[#requests].cb(account) +Assert.eq(value.user_id, "7") +Assert.eq(cfg.cookie, "sid=new") +Assert.eq(saves, 1) +Assert.is_nil(cfg.password) + +session = Login.new() +session:passwordAsync(phone, "bad", proof, answer) +r = requests[#requests] +r.cb(JSON.encode({ code = 400, message = "password refused" })) +Assert.is_nil(value) +Assert.eq(reason, "password refused") +Assert.eq(cfg.cookie, "sid=new") +for _idx, response in ipairs({ "broken", "[]", "{}", '{"code":200}' }) do + session:passwordAsync(phone, "test", proof, answer) + r = requests[#requests] + r.cb(response) + if response == '{"code":200}' then requests[#requests].cb(nil, "offline") end + Assert.is_nil(value) + Assert.is_true(type(reason) == "string") + Assert.eq(saves, 1) +end + +cfg = {} +session = Login.new() +session:sendCodeAsync(phone, proof, answer) +r = requests[#requests] +Assert.matches(r.url, "/v2/passport/pc/v2/get_sms_code$") +Assert.eq(r.fields.phone, phone) +Assert.eq(r.fields.random, "random-proof") +r.cb(JSON.encode({ code = 400, message = "SMS refused" })) +Assert.is_nil(session.sms_phone) +Assert.eq(reason, "SMS refused") +session:sendCodeAsync(phone, proof, answer) +requests[#requests].cb(good, nil, { cookies = { "nonce=anonymous; Path=/" } }) +Assert.is_true(value) +Assert.eq(session.sms_phone, phone) +local count = #requests +session:sendCodeAsync(phone, proof, answer) +Assert.eq(#requests, count) +Assert.eq(reason, "请稍后再获取验证码") +session:codeAsync("+86-13900000000", "123456", answer) +Assert.eq(#requests, count) +session:codeAsync(phone, "invalid", answer) +Assert.eq(#requests, count) +session:codeAsync(phone, "123456", answer) +r = requests[#requests] +Assert.matches(r.url, "/v2/passport/pc/mobile_code_login$") +Assert.eq(r.fields.code, "123456") +Assert.eq(r.opts.headers.Cookie, "nonce=anonymous") +r.cb(good, nil, { cookies = { "sid=sms; Path=/" } }) +requests[#requests].cb(account) +Assert.eq(cfg.cookie, "nonce=anonymous; sid=sms") +Assert.is_nil(cfg.code) + +local get = Request.get +Request.post = function(url, body, opts, cb) + cb(good, nil, { cookies = { "sid=sync; Path=/" } }) + return { cancel = function() error("completed POST must not overwrite account request") end } +end +session = Login.new() +session:passwordAsync(phone, "test", proof, answer) +r = requests[#requests] +session:cancel() +Assert.is_true(r.cancelled) +r.cb(account) +Assert.eq(cfg.cookie, "nonce=anonymous; sid=sms") +Request.get = get diff --git a/tests/kuaikan/operations_spec.lua b/tests/kuaikan/operations_spec.lua new file mode 100644 index 0000000..13ed950 --- /dev/null +++ b/tests/kuaikan/operations_spec.lua @@ -0,0 +1,69 @@ +--[[-- +快看源操作:命中旧缓存可离线开书,同步目录桩后取消仍指向章节任务。 + +@module tests.moonsource_kuaikan.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 = "1", toc_version = 1 }, { idx = 2, uid = "2" } } +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_kuaikan.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_kuaikan.source").new() +source.loadTocAsync = function(_self, _identity, cb) + cb(toc) + return { cancel = function() cancelled.toc = true end } +end +local identity = { source_id = "ext.kuaikan", 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("/1.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 +local opened +source:openBookAsync(identity, nil, function(path) opened = path end) +Stubs.flush() +Assert.eq(opened, "/2.cbz") +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() diff --git a/tests/kuaikan/phone_login_spec.lua b/tests/kuaikan/phone_login_spec.lua new file mode 100644 index 0000000..e1847df --- /dev/null +++ b/tests/kuaikan/phone_login_spec.lua @@ -0,0 +1,109 @@ +--[[-- +快看手机号输入:官方格式、协议确认、密码原值、短信候选会话和取消。 + +@module tests.moonsource_kuaikan.phone_login_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field +local Assert = require("support.assert") +local Themed = require("support.theme_stubs") +Themed.install() +local connected, cancelled, proof_submit, proof_done, proof_session = true, 0, nil, nil, nil +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +local sessions = {} +package.loaded["moonsource_kuaikan.login"] = { + new = function() + local session = {} + function session:cancel() cancelled = cancelled + 1 end + function session:passwordAsync(phone, password, proof, cb) + self.phone, self.password, self.proof, self.pending = phone, password, proof, cb + end + function session:sendCodeAsync(phone, proof, cb) + self.phone, self.proof, self.pending = phone, proof, cb + end + function session:codeAsync(phone, code, cb) + self.phone, self.code, self.pending = phone, code, cb + end + sessions[#sessions + 1] = session + return session + end, +} +package.loaded["moonsource_kuaikan.verify"] = { + new = function(session, submit, cb) + proof_session, proof_submit, proof_done = session, submit, cb + return { cancel = function() cancelled = cancelled + 1 end } + end, +} +local Phone = require("moonsource_kuaikan.phone_login") +local logged = 0 +local function on_user() logged = logged + 1 end +local window = Phone.new("password", on_user) +window:start() +local input = Themed.last("input") +Assert.eq(input.title, "快看密码登录") +Assert.eq(input.fields[3].text_type, "password") +input.callback("+86", "13800000000", "") +Assert.eq(Themed.last("toast").text, "请输入密码") +input.callback("+86", "13800000000", " pass测试 ") +Assert.matches(Themed.last("confirm").text, "https://www%.kuaikanmanhua%.com/webs/agreement") +Themed.last("confirm").ok_callback() +Assert.is_true(input.closed) +Assert.eq(proof_session, window.session) +Assert.is_true(window.busy) +proof_submit({ ticket = "proof", random = "random" }, function() end) +Assert.eq(window.session.password, " pass测试 ") +Assert.eq(window.session.phone, "+86-13800000000") +proof_done(nil, "password refused") +Assert.eq(Themed.last("toast").text, "password refused") +Assert.is_nil(Themed.last("input").fields[3].text) +Assert.is_false(window.busy) +Themed.last("input").callback("+86", "13800000000", "new") +window:cancel() +proof_done({ user_id = "7" }) +Assert.eq(logged, 0) + +window = Phone.new("sms", on_user) +window:start() +input = Themed.last("input") +Assert.eq(input.title, "快看短信登录") +input.callback("+86", "13800000000", "123456") +Assert.matches(Themed.last("toast").text, "请先获取") +connected = false +input.actions[1].callback("+86", "13800000000") +Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi") +connected = true +input.actions[1].callback("+86", "123") +Assert.eq(Themed.last("toast").text, "请输入有效的手机号和国际区号") +input.actions[1].callback("+86", "13800000000") +Themed.last("confirm").ok_callback() +proof_submit({ ticket = "proof", random = "random" }, function() end) +Assert.eq(window.session.phone, "+86-13800000000") +window.session.sms_phone, window.session.sms_retry_at = "+86-13800000000", os.time() + 60 +proof_done(true) +Assert.eq(Themed.last("toast").text, "验证码已发送") +input = Themed.last("input") +Assert.eq(input.fields[2].text, "13800000000") +input.actions[1].callback("+86", "13800000000") +Assert.eq(Themed.last("toast").text, "请稍后再获取验证码") +input.callback("+86", "13900000000", "123456") +Assert.matches(Themed.last("toast").text, "请先获取") +input.callback("+86", "13800000000", " 123456 ") +Assert.eq(window.session.code, "123456") +Assert.is_true(window.busy) +window.session.pending({ user_id = "7" }) +Assert.eq(logged, 1) +Assert.is_true(input.closed) +Assert.is_true(cancelled > 0) + +window = Phone.new("sms", on_user) +window:start() +window.session.sms_phone = "+86-13800000000" +input = Themed.last("input") +input.callback("+86", "13800000000", "123456") +local pending = window.session.pending +input:close() +pending({ user_id = "7" }) +Assert.eq(logged, 1) +Assert.is_nil(window.dialog) +Assert.is_false(window.busy) +input.actions[1].callback("+86", "13800000000") +Assert.is_nil(window.verification) diff --git a/tests/kuaikan/qrlogin_spec.lua b/tests/kuaikan/qrlogin_spec.lua new file mode 100644 index 0000000..e59f49f --- /dev/null +++ b/tests/kuaikan/qrlogin_spec.lua @@ -0,0 +1,88 @@ +--[[-- +快看扫码窗口:已扫码、确认、拒绝、超时、刷新和关闭。 + +@module tests.moonsource_kuaikan.qrlogin_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 sessions, connected = {}, true +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +package.loaded["moonsource_kuaikan.login"] = { + new = function() + local session = { cancels = 0, polls = 0 } + function session:cancel() self.cancels = self.cancels + 1 end + function session:qrCreateAsync(cb) self.created = cb end + function session:qrPollAsync(_uuid, _last, cb) self.polls = self.polls + 1; self.polled = cb end + function session:exchangeAsync(code, cb) self.code, self.exchanged = code, cb end + sessions[#sessions + 1] = session + return session + end, +} +local QR = require("moonsource_kuaikan.qrlogin") +local logged = 0 +local window = QR.new(function() logged = logged + 1 end) +window:start() +local session = sessions[#sessions] +Assert.is_true(Themed.last("progress_dialog").shown) +session.created("uuid") +local dialog = Themed.last("qr") +Assert.eq(dialog.caption, "用微信扫一扫") +session.polled(404) +Assert.eq(Themed.last("toast").text, "已扫码,请在手机上确认") +Stubs.flush() +session.polled(405, "confirmed") +Assert.eq(session.code, "confirmed") +session.exchanged({ user_id = "7" }) +Assert.eq(logged, 1) +Assert.is_true(dialog.closed) +Assert.is_nil(window.poll) + +window:start() +session = sessions[#sessions] +window:cancel() +session.created("late") +Assert.is_nil(window.dialog) +Assert.eq(session.polls, 0) +window:start() +session = sessions[#sessions] +session.created("uuid") +dialog = Themed.last("qr") +dialog:close() +session.polled(405, "late") +Assert.is_nil(session.exchanged) +Assert.eq(logged, 1) + +window:start() +session = sessions[#sessions] +session.created("uuid") +Themed.last("qr").actions[1].callback() +local refreshed = sessions[#sessions] +Assert.is_true(refreshed ~= session) +session.polled(405, "old") +Assert.is_nil(session.exchanged) +refreshed.created("new") +refreshed.polled(403) +Assert.eq(Themed.last("confirm").text, "已在微信中拒绝登录") + +window:start() +session = sessions[#sessions] +session.created("uuid") +window.deadline = os.time() - 1 +session.polled(408) +Stubs.flush() +Assert.eq(Themed.last("confirm").text, "二维码已过期") +window:start() +session = sessions[#sessions] +session.created("uuid") +connected = false +session.polled(408) +Stubs.flush() +Assert.eq(Themed.last("confirm").text, "网络不可用,请先连接 Wi-Fi") +local count = #sessions +window:start() +Assert.eq(#sessions, count) +Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi") diff --git a/tests/kuaikan/reviews_spec.lua b/tests/kuaikan/reviews_spec.lua new file mode 100644 index 0000000..bb5bedf --- /dev/null +++ b/tests/kuaikan/reviews_spec.lua @@ -0,0 +1,72 @@ +--[[-- 快看每话章评:原始行游标、章节隔离、离线与取消。 @module tests.moonsource_kuaikan.reviews_spec --]] +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local JSON = require("support.json_stub") +package.loaded.json = JSON +local connected, requests, pending = true, {}, nil +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +---@type {code: integer, data: {total: integer, comments: {id: integer|string|table, content: string, replied_comment_id: integer, user?: table}[]}} +local result = { code = 200, data = { total = 4, comments = { + { id = 1, content = "First", replied_comment_id = 0, user = { nickname = "Reader" } }, + { id = 2, content = "Reply", replied_comment_id = 1 }, + { id = 3, content = "Second", replied_comment_id = 0 }, +} } } +package.loaded["http.request"] = { + get = function(url, opts, cb) + local request = { url = url, opts = opts } + requests[#requests + 1] = request + if pending then pending.cb, pending.request = cb, request + elseif url:find("offset=3", 1, true) then + cb(JSON.encode({ code = 200, data = { total = 4, comments = { + { id = 4, content = "Last", replied_comment_id = 0 }, + } } })) + else cb(JSON.encode(result)) end + return { cancel = function() request.cancelled = true end } + end, +} +local source = require("moonsource_kuaikan.source").new() +function source:loadTocAsync(_identity, cb) + cb({ { uid = "11", idx = 1, title = "One" }, { uid = "22", idx = 2, title = "Two" } }) + return { cancel = function() end } +end +local identity = { source_id = "ext.kuaikan", stable_id = "review-test", chapter_idx = 1 } +local page, err +source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end) +Assert.is_nil(err) +Assert.len(page.items, 2) +Assert.eq(page.items[1].id, "1") +Assert.eq(page.items[1].content, "First") +Assert.eq(page.max_idx, 3, "游标按原始三行推进,不按两个主楼推进") +Assert.is_true(page.more) +Assert.matches(requests[1].url, "/comic/11/") +Assert.is_nil(requests[1].opts.headers.Cookie) +source:paragraphReviewPageAsync(identity, "chapter", page.max_idx, function(value, reason) page, err = value, reason end) +Assert.is_nil(err) +Assert.eq(page.items[1].id, "4") +Assert.eq(page.max_idx, 4) +Assert.is_false(page.more) +connected = false +source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end) +Stubs.flush() +Assert.is_nil(err) +Assert.len(page.items, 2) +identity.chapter_idx = 2 +source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end) +Stubs.flush() +Assert.is_nil(page) +Assert.eq(err, "未联网,无法加载段评") +connected, pending = true, {} +local called = false +local job = source:paragraphReviewPageAsync(identity, "chapter", 0, function() called = true end) +Assert.matches(pending.request.url, "/comic/22/") +job.cancel() +Assert.is_true(pending.request.cancelled) +pending.cb(JSON.encode(result)) +Assert.is_false(called) +pending = nil +for _idx, invalid_id in ipairs({ {}, "" }) do + result.data.comments[1].id = invalid_id + source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end) + Assert.is_nil(page) + Assert.eq(err, "响应无效", "坏 ID 不转换为 Lua 表地址或无身份评论") +end diff --git a/tests/kuaikan/setting_spec.lua b/tests/kuaikan/setting_spec.lua new file mode 100644 index 0000000..f3ad384 --- /dev/null +++ b/tests/kuaikan/setting_spec.lua @@ -0,0 +1,91 @@ +--[[-- +快看账号设置、浏览器域隔离和可取消 Cookie 校验。 + +@module tests.moonsource_kuaikan.setting_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +local Themed = require("support.theme_stubs") +Themed.install() +package.loaded["json"] = JSON +local cfg, requests, reloads, expired, connected = {}, {}, 0, false, true +package.loaded["utils.settings"] = { getSource = function() return cfg end, saveSource = function() end } +package.loaded["source.auth"] = { ok = function() expired = false end, expired = function() return expired end } +package.loaded["source.registry"] = { reload = function() reloads = reloads + 1 end } +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +package.loaded["ui.themes.widgets.row"] = { widget = function(opts) return opts end } +package.loaded["http.request"] = { + get = function(url, opts, cb) + local r = { url = url, opts = opts, cb = cb } + requests[#requests + 1] = r + return { cancel = function() r.cancelled = true end } + end, + header = function() end, headerAll = function() return {} end, +} +local Setting = require("moonsource_kuaikan.setting") +local answer = JSON.encode({ code = 200, data = { user_info = { authenticate = 1, user_id = 7 } } }) +local ok, reason +Assert.eq(Setting.browser.check, "https://www.kuaikanmanhua.com/v2/pweb/user_info/get") +Assert.eq(Setting.browser.check_json.path, "data.user_info.authenticate") +Setting.browser.apply({ cookies = { + { domain = ".kuaikanmanhua.com", path = "/", name = "sid", value = "parent" }, + { domain = "www.kuaikanmanhua.com", path = "/", name = "uid", value = "web" }, + { domain = "other.kuaikanmanhua.com", name = "sid", value = "other" }, + { domain = "kuaikanmanhua.com.evil.test", name = "sid", value = "evil" }, + { domain = "www.kuaikanmanhua.com", path = "/unrelated", name = "sid", value = "wrong-path" }, +} }, function(value, err) ok, reason = value, err end) +Assert.eq(requests[#requests].opts.headers.Cookie, "sid=parent; uid=web") +requests[#requests].cb(answer) +Assert.is_true(ok) +Assert.eq(reloads, 1) +Assert.is_true(Setting.browser.isAuthorized()) +expired = true +Assert.is_false(Setting.browser.isAuthorized()) +expired = false + +local rows = Setting.rows() +Assert.eq(rows[1](400).title, "快看漫画账号") +Assert.eq(rows[1](400).status, "已登录") +Assert.eq(#rows, 7) +local refreshes = 0 +local review_rows = Setting.rows({ desktop = { updateView = function() refreshes = refreshes + 1 end } }) +Assert.eq(review_rows[6](400).title, "章节评论") +Assert.is_false(review_rows[6](400).status_on) +review_rows[6](400).callback() +Assert.is_true(review_rows[6](400).status_on) +Assert.eq(refreshes, 1) +Assert.eq(rows[4](400).title, "密码登录") +Assert.eq(rows[5](400).title, "短信登录") +rows[3](400).callback() +Assert.eq(Themed.last("input").title, "快看登录 Cookie") +Themed.last("input").callback("sid=cancelled") +local r = requests[#requests] +Themed.last("progress_dialog").on_cancel() +Assert.is_true(r.cancelled) +r.cb(answer) +Assert.eq(reloads, 1) +Assert.eq(cfg.cookie, "sid=parent; uid=web") + +connected = false +local count = #requests +rows[3](400).callback() +Themed.last("input").callback("sid=offline") +Assert.eq(#requests, count) +Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi") +local opened +package.loaded["utils.extension"] = { + call = function(name, path, title) + opened = { name = name, path = path, title = title } + return { close = function() end } + end, +} +Assert.eq(rows[2](400).title, "浏览器登录") +rows[2](400).callback() +Assert.eq(opened.name, "web.open_page") +Assert.eq(opened.path, "/cookie.html") +package.loaded["utils.extension"] = nil + +Assert.is_true(require("moonsource_kuaikan.client").hasAccount()) +for _index, row in ipairs(rows) do Assert.is_true(row(400).title ~= "快看云端同步") end diff --git a/tests/kuaikan/shelf_spec.lua b/tests/kuaikan/shelf_spec.lua new file mode 100644 index 0000000..688de75 --- /dev/null +++ b/tests/kuaikan/shelf_spec.lua @@ -0,0 +1,109 @@ +--[[-- +快看书架:先校验账号再拉完整快照,失败与取消不写库。 + +@module tests.moonsource_kuaikan.shelf_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field + +package.preload["json"] = function() return require("support.json_stub") end + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local Client = require("moonsource_kuaikan.client") +local Json = require("support.json_stub") +local connected = true +local cfg = { cookie = "session=current", user_id = "7" } +package.loaded["utils.settings"] = { + getSource = function() return cfg end, + get = function() return {} end, + saveSource = function() end, +} +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +local pending, cancelled, writes, expired = nil, nil, 0, false +package.loaded["source.auth"] = { + ok = function() end, + expire = function() expired = true end, +} +package.loaded["source.shelf"] = { syncAsync = function(id, remote, _mapper, opts, cb) + Assert.eq(id, "ext.kuaikan") + Assert.is_true(opts.force) + Assert.is_true(remote.writing) + return remote:shelfSyncAsync(function(books, err) + if not books then cb(nil, err); return end + writes = writes + 1 + cb({ pulled = #books, pushed = 0, hidden = 0, conflicts = 0, skipped = false }) + end) +end } +Client.loginRequestAsync = function(_url, cookie, cb) + Assert.eq(cookie, "session=current") + cb(Json.encode({ code = 200, data = { user_info = { authenticate = 1, user_id = 7 } } })) + return { cancel = function() error("已结束的校验不应覆盖书架句柄") end } +end +Client.favAsync = function(cb, cookie) + Assert.eq(cookie, "session=current") + pending = cb + return { cancel = function() cancelled = true end } +end +local source = require("moonsource_kuaikan.source").new() +local result, reason +local function done(value, err) result, reason = value, err end +local handle = source:syncBooksAsync({ force = true }, done) +pending({ { stable_id = "1", title = "甲" } }) +Assert.eq(result.pulled, 1) +Assert.eq(writes, 1) + +result = nil +handle = source:syncBooksAsync({ force = true }, done) +handle.cancel() +Assert.is_true(cancelled) +pending({ { stable_id = "2", title = "乙" } }) +Assert.is_nil(result) +Assert.eq(writes, 1) + +source:syncBooksAsync({ force = true }, done) +cfg = { cookie = "session=new", user_id = "8" } +pending({ { stable_id = "2", title = "乙" } }) +Assert.eq(reason, "登录状态已变化,请重试") +Assert.eq(writes, 1) + +cfg = { cookie = "session=current", user_id = "7" } +source:syncBooksAsync({ force = true }, done) +pending(nil, "offline") +Assert.eq(reason, "offline") +Assert.eq(writes, 1) + +Client.loginRequestAsync = function(_url, _cookie, cb) + cb(Json.encode({ code = 200, data = { user_info = { authenticate = 0 } } })) + return { cancel = function() end } +end +source:syncBooksAsync({ force = true }, done) +Assert.is_true(expired) +Assert.eq(reason, "快看登录已失效,请重新登录") +Assert.eq(writes, 1) + +connected = false +source:syncBooksAsync({ force = true }, done) +Stubs.flush() +Assert.eq(reason, "网络不可用,请先连接 Wi-Fi") +cfg = {} +source:syncBooksAsync(nil, done) +Stubs.flush() +Assert.is_true(result.skipped) +Assert.eq(result.reason, "not_logged_in") +source:syncBooksAsync({ dirty_only = true }, done) +Stubs.flush() +Assert.is_true(result.skipped) + +connected = true +cfg = { cookie = "session=current" } +Client.loginRequestAsync = function(_url, _cookie, cb) + cb(Json.encode({ code = 200, data = { user_info = { authenticate = 1, user_id = 7 } } })) + return { cancel = function() end } +end +local legacy = require("moonsource_kuaikan.source").new() +legacy:syncBooksAsync({ force = true }, done) +pending({ { stable_id = "3", title = "丙" } }) +Assert.eq(cfg.user_id, "7") +Assert.is_true(cfg.logged_in) +Assert.is_true(legacy:capabilities().shelf_push) +Assert.is_true(type(legacy.putProgressAsync) == "function") diff --git a/tests/kuaikan/sync_spec.lua b/tests/kuaikan/sync_spec.lua new file mode 100644 index 0000000..52e3b2d --- /dev/null +++ b/tests/kuaikan/sync_spec.lua @@ -0,0 +1,241 @@ +--[[-- +快看上行:账号归属、收藏读回确认、进度字段及取消。 + +@module tests.moonsource_kuaikan.sync_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") +package.loaded["json"] = JSON +local cfg = { cookie = "session=current; kk_s_t=old", user_id = "7" } +package.loaded["utils.settings"] = { + getSource = function() return cfg end, get = function() return {} end, saveSource = function() end, +} +package.loaded["ui/network/manager"] = { isConnected = function() return true end } +package.loaded["source.auth"] = { ok = function() end, currentAccount = require("source.auth").currentAccount } +local requests = {} +local function request(method, url, body, opts, cb) + local r = { method = method, url = url, body = body, opts = opts, cb = cb } + requests[#requests + 1] = r + return { cancel = function() r.cancelled = true end } +end +package.loaded["http.request"] = { + get = function(url, opts, cb) return request("GET", url, nil, opts, cb) end, + post = function(url, body, opts, cb) return request("POST", url, body, opts, cb) end, + request = function(opts, cb) return request(opts.method, opts.url, opts.body, opts, cb) end, + header = function(res, key) return res and res.headers and res.headers[key] end, + headerAll = function(res) return res and res.headers and res.headers.cookies or {} end, +} +local Client = require("moonsource_kuaikan.client") +local Text = require("utils.text") +local account = { code = 200, data = { user_info = { authenticate = 1, user_id = 7 } } } +local function reply(data, err) + local r = requests[#requests] + local body = type(data) == "string" and data or JSON.encode(data) + local res = { code = 200, body = body, headers = { cookies = { "kk_s_t=fresh; Path=/" } } } + if r.method == "DELETE" then r.cb(res, err) else r.cb(body, err, res) end +end +local ok, reason +local function done(value, err) ok, reason = value, err end +local remote = Client.newSync(true) +remote:checkAsync(function(value, err) + if not value then done(nil, err); return end + remote:addToShelfAsync("835", done) +end) +reply(account) +Assert.is_nil(requests[#requests].opts.headers.Cookie) +reply("callback_1({})") +local write = requests[#requests] +Assert.eq(write.method, "POST") +Assert.matches(write.url, "/web/topic/835/fav%?answer=") +Assert.matches(write.opts.headers.Cookie, "session=current") +Assert.matches(write.opts.headers.Cookie, "kk_s_t=fresh") +Assert.is_nil(write.opts.headers.Cookie:find("kk_s_t=old", 1, true)) +reply({ code = 200 }) +reply({ code = 200, data = { total = 0, topics = {} } }) +Assert.is_nil(ok) +Assert.eq(reason, "快看收藏变更尚未确认") +Assert.eq(remote.push_error, reason) + +remote = Client.newSync(true) +remote:removeFromShelfAsync("835", done) +reply("callback_1({})") +Assert.eq(requests[#requests].method, "DELETE") +reply({ code = 200 }) +reply({ code = 200, data = { total = 0, topics = {} } }) +Assert.is_true(ok) + +remote = Client.newSync(true) +remote:addToShelfAsync("835", done) +reply("callback_1({})") +local count = #requests +reply(nil, "network failed") +Assert.eq(reason, "network failed") +Assert.eq(#requests, count) + +remote = Client.newSync(true) +remote:addToShelfAsync("835", done) +local late = requests[#requests] +remote:cancel() +Assert.is_true(late.cancelled) +count = #requests +late.cb("challenge", nil, { headers = { cookies = { "kk_s_t=late; Path=/" } } }) +Assert.eq(#requests, count) + +remote = Client.newSync(true) +remote:addToShelfAsync("835", done) +cfg = { cookie = "session=new", user_id = "8" } +reply("callback_1({})") +Assert.eq(reason, "登录状态已变化,请重试") +cfg = { cookie = "session=current" } +local module = require("moonsource_kuaikan.source") +local readonly = module.new() +Assert.is_nil(readonly.putProgressAsync) +Assert.is_false(readonly:capabilities().shelf_push) +cfg.user_id = "7" +local source = module.new() +Assert.is_true(type(source.putProgressAsync) == "function") +Assert.is_true(source:capabilities().shelf_push) +local toc = { { idx = 1, uid = "10", title = "甲" }, { idx = 2, uid = "20", title = "乙" } } +source.loadTocAsync = function(_self, _identity, cb) + cb(toc) + return { cancel = function() error("已完成目录不得覆盖当前请求") end } +end +local identity = { source_id = "ext.kuaikan", stable_id = "9" } +local handle = source:putProgressAsync(identity, + { fraction = 0.6875, chapter_idx = 2, chapter_fraction = 0.375, page = 3, total_pages = 8 }, done) +reply(account) +write = requests[#requests] +Assert.eq(write.method, "POST") +Assert.matches(write.url, "/v2/pweb/read/history/report$") +local payload = JSON.decode(Text.urlDecode(write.body:match("view_rate=([^&]+)"))) +Assert.eq(#payload, 1) +Assert.eq(payload[1].topic_id, 9) +Assert.eq(payload[1].comic_id, 20) +Assert.eq(payload[1].read_count, 3) +Assert.eq(payload[1].max_read_count, 3) +Assert.eq(payload[1].total_count, 8) +Assert.eq(payload[1].read_time % 1000, 0) +Assert.eq(payload[1].max_read_count_time, payload[1].read_time) +reply({ code = 200 }) +reply({ code = 200, data = { total = 1, topics = { { topic_id = 9, comic_id = 10, read_count = 99 } } } }) +Assert.is_nil(ok) +Assert.eq(reason, "快看进度变更尚未确认") + +handle = source:putProgressAsync(identity, { fraction = 1, chapter_idx = 2, page = 8, total_pages = 8 }, done) +reply(account) +write = requests[#requests] +handle:cancel() +Assert.is_true(write.cancelled) + +source:getProgressAsync(identity, done) +reply(account) +reply({ code = 200, data = { total = 1, topics = { { topic_id = 9, comic_id = 20, read_count = 99 } } } }) +Assert.eq(ok.chapter_idx, 2) +Assert.eq(ok.fraction, 0.5) +Assert.is_nil(ok.chapter_fraction) +Assert.is_nil(ok.page) + +source:getProgressAsync(identity, function(value, err, meta) + ok, reason = value, err + Assert.is_true(meta.empty) +end) +reply(account) +reply({ code = 200, data = { total = 0, topics = {} } }) +Assert.is_nil(ok) +Assert.is_nil(reason) +Stubs.flush() + +local deleted, removed, added = true, 0, false +package.loaded["book.books_db"] = { + pendingDeleteIds = function() return deleted and { "30" } or {} end, + pendingShelfAddIds = function() return not added and { "9" } or {} end, + remove = function(_id, stable_id) + Assert.eq(stable_id, "30") + deleted, removed = false, removed + 1 + return true + end, + markSynced = function(_id, stable_id) Assert.eq(stable_id, "9"); added = true; return true end, +} +source:syncBooksAsync({ dirty_only = true }, done) +reply(account) +reply("challenge") +reply({ code = 200 }) +reply({ code = 200, data = { total = 1, topics = { { id = 30, title = "旧书" } } } }) +reply("challenge") +reply({ code = 200 }) +reply({ code = 200, data = { total = 2, topics = { { id = 30, title = "旧书" }, { id = 9, title = "新书" } } } }) +Assert.eq(ok.pushed, 1) +Assert.eq(ok.push_error, "快看收藏变更尚未确认") +Assert.is_true(deleted) +Assert.eq(removed, 0) +Assert.is_true(added) + +source:syncBooksAsync({ dirty_only = true }, done) +reply(account) +reply("challenge") +reply({ code = 200 }) +reply({ code = 200, data = { total = 0, topics = {} } }) +Stubs.flush() +Assert.is_false(deleted) +Assert.eq(removed, 1) +Assert.eq(ok.pushed, 1) +Assert.is_nil(ok.push_error) + +local row = { stable_id = "9", chapter_idx = 2, fraction = 0.75, page = 4, total_pages = 8, + sync_status = 0, updated_at = 1 } +local confirmed = 0 +package.loaded["book.progress_db"] = { + get = function() return row end, + unsynced = function() return { row } end, + markSynced = function(_id, stable_id, revision) + Assert.eq(stable_id, "9") + Assert.eq(revision, 1) + confirmed, row.sync_status = confirmed + 1, 1 + return true + end, +} +source:syncProgressAsync({ dirty_only = true }, done) +Stubs.flush() +reply(account) +reply(nil, "network failed") +Assert.eq(row.sync_status, 0) +Assert.eq(confirmed, 0) +Assert.eq(ok.push_error, "network failed") + +source:syncProgressAsync({ dirty_only = true }, done) +Stubs.flush() +reply(account) +reply({ code = 200 }) +reply({ code = 200, data = { total = 1, topics = { { topic_id = 9, comic_id = 20 } } } }) +Assert.eq(confirmed, 1) +Assert.eq(ok.pushed, 1) + +Client.imagesAsync = function(uid, cb) + Assert.eq(uid, "20") + cb({ "https://images/1.jpg", "https://images/2.jpg" }) + return { cancel = function() error("已完成的页图不得覆盖当前请求") end } +end +handle = source:putProgressAsync(identity, { fraction = 1 }, done) +reply(account) +write = requests[#requests] +payload = JSON.decode(Text.urlDecode(write.body:match("view_rate=([^&]+)"))) +Assert.eq(payload[1].comic_id, 20) +Assert.eq(payload[1].read_count, 2) +Assert.eq(payload[1].total_count, 2) +handle:cancel() +Assert.is_true(write.cancelled) + +local loads = 0 +source.loadTocAsync = function(_self, _identity, cb, force) + loads = loads + 1 + cb(force and toc or { toc[1] }) + return { cancel = function() end } +end +source:getProgressAsync(identity, done) +reply(account) +reply({ code = 200, data = { total = 1, topics = { { topic_id = 9, comic_id = 20 } } } }) +Assert.eq(loads, 2) +Assert.eq(ok.chapter_idx, 2) diff --git a/tests/kuaikan/verify_spec.lua b/tests/kuaikan/verify_spec.lua new file mode 100644 index 0000000..aecbabc --- /dev/null +++ b/tests/kuaikan/verify_spec.lua @@ -0,0 +1,93 @@ +--[[-- +快看远程滑块:临时票据、敏感字段隔离、取消、拒绝应急票据与重复提交。 + +@module tests.moonsource_kuaikan.verify_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field +local Assert = require("support.assert") +local Themed = require("support.theme_stubs") +Themed.install() +local Ext = require("utils.extension") +Ext.reset() +local timers = {} +package.loaded["ui/uimanager"] = { + scheduleIn = function(_ui, _delay, fn) timers[fn] = true end, + unschedule = function(_ui, fn) timers[fn] = nil end, +} +local path +Ext.add("web.open_page", function(url, _title, _text, opts) + path = url + return require("ui.themes.widgets.qr"):new{ close_callback = opts.close_callback }:show() +end) +local Verification = require("moonsource_kuaikan.verify") +local route = Ext.list("web.routes")[1] +local status, body, headers, completed, reason, submitted, proof, cancels = nil, nil, nil, nil, nil, nil, nil, 0 +local function request(action, params, method) + route.handle(method or "POST", action, params, function(code, data, extra) + status, body, headers = code, data, extra + end) +end +local function start() + completed, reason = nil, nil + return Verification.new({ cancel = function() cancels = cancels + 1 end }, function(fields, cb) + proof, submitted = fields, cb + end, function(result, err) completed, reason = result, err end) +end +local verification = start() +local ticket = path:match("#(.+)$") +request("config", { ticket = ticket }) +Assert.eq(status, 200) +Assert.eq(body.appid, "2034681882") +Assert.is_nil(body.phone) +Assert.is_nil(body.password) +Assert.is_nil(body.cookie) +Assert.eq(headers[1], "Cache-Control: no-store") +request("verify", { ticket = "invalid", captcha_ticket = "proof", randstr = "random" }) +Assert.eq(status, 403) +for _idx, value in ipairs({ "", {}, "trerror_1001_x", string.rep("a", 4097) }) do + request("verify", { ticket = ticket, captcha_ticket = value, randstr = "random" }) + Assert.eq(status, 400) +end +request("config", { ticket = ticket }, "GET") +Assert.eq(status, 405) +request("unknown", { ticket = ticket }) +Assert.eq(status, 404) +request("verify", { ticket = ticket, captcha_ticket = "proof", randstr = "random", password = "ignored" }) +Assert.eq(proof.ticket, "proof") +Assert.eq(proof.random, "random") +Assert.is_nil(proof.password) +request("verify", { ticket = ticket, captcha_ticket = "repeat", randstr = "random" }) +Assert.eq(status, 409) +submitted({ user_id = "7" }) +Assert.eq(status, 200) +Assert.is_true(body.ok) +Assert.is_nil(body.user_id) +Assert.eq(completed.user_id, "7") +Assert.is_nil(next(timers)) +Assert.is_nil(verification.submit) +request("verify", { ticket = ticket, captcha_ticket = "replay", randstr = "random" }) +Assert.eq(status, 403) + +verification = start() +ticket = path:match("#(.+)$") +request("verify", { ticket = ticket, captcha_ticket = "proof", randstr = "random" }) +submitted(nil, "private server detail") +Assert.eq(status, 400) +Assert.is_nil(body.error:find("private", 1, true)) +Assert.eq(reason, "private server detail") +verification = start() +ticket = path:match("#(.+)$") +request("verify", { ticket = ticket, captcha_ticket = "proof", randstr = "random" }) +verification.dialog:close() +submitted(true) +Assert.eq(status, 403) +Assert.is_nil(completed) +Assert.eq(reason, "验证已取消") +Assert.is_true(cancels > 0) +verification = start() +verification.expires = os.time() - 1 +request("config", { ticket = verification.ticket }) +Assert.eq(status, 403) +verification.timeout() +Assert.eq(reason, "验证已过期,请重新发起验证") +Assert.is_nil(next(timers)) diff --git a/tests/kuaikan/web_spec.js b/tests/kuaikan/web_spec.js new file mode 100644 index 0000000..0b41d09 --- /dev/null +++ b/tests/kuaikan/web_spec.js @@ -0,0 +1,85 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const source = fs.readFileSync(process.argv[2] + '/moonsource-kuaikan.koplugin/moonsource_kuaikan/web/kuaikan_verify.js', 'utf8'); + +async function page(options = {}) { + const nodes = Object.fromEntries(['title', 'instruction', 'status', 'retry', 'captcha'] + .map(id => [id, { textContent: '', hidden: false }])); + const requests = [], scripts = []; + let callback, shows = 0; + const messages = { appid: '2034681882', title: 'Kuaikan', instruction: 'Slide', + pending: 'Submitting', success: 'Done', failure: 'Failed', + load_error: 'Load failed', cancelled: 'Cancelled', retry: 'Retry' }; + const context = { + AbortController, setTimeout, clearTimeout, + location: { hash: '#fixture' }, + window: {}, + document: { + get cookie() { throw new Error('Must not read browser credentials'); }, + getElementById: id => nodes[id], + createElement: () => ({ remove() { this.removed = true; } }), + head: { appendChild(script) { + scripts.push(script); + if (options.blocked) return script.onerror(); + context.window.TencentCaptcha = function(element, appid, cb, opts) { + assert.equal(element, nodes.captcha); + assert.equal(appid, '2034681882'); + assert.equal(opts.type, 'embed'); + callback = cb; + this.show = () => { shows++; }; + this.destroy = () => {}; + }; + script.onload(); + } }, + }, + fetch: async (url, opts) => { + requests.push({ url, body: JSON.parse(opts.body) }); + return { + ok: url.endsWith('/config') || !options.rejected, + json: async () => url.endsWith('/config') ? messages : options.rejected ? { error: 'Rejected' } : { ok: true }, + }; + }, + }; + await vm.runInNewContext(source, context); + return { nodes, requests, scripts, get callback() { return callback; }, get shows() { return shows; } }; +} + +(async () => { + let p = await page(); + assert.equal(p.shows, 1); + await p.callback({ ret: 2 }); + assert.equal(p.requests.length, 1); + assert.equal(p.nodes.status.textContent, 'Cancelled'); + await p.callback({ ret: 0, ticket: 'trerror_1001_fixture', randstr: 'random' }); + assert.equal(p.requests.length, 1, 'SDK emergency tickets are never sent'); + await p.callback({ ret: 0, ticket: 'proof', randstr: 'random', errorCode: 1001 }); + assert.equal(p.requests.length, 1); + await p.callback({ ret: 0, ticket: {}, randstr: 'random' }); + assert.equal(p.requests.length, 1, 'Malformed SDK results do not start a login request'); + await p.callback({ ret: 0, ticket: 'proof', randstr: 'random' }); + assert.deepEqual(p.requests[1].body, { ticket: 'fixture', captcha_ticket: 'proof', randstr: 'random' }); + assert.equal(p.nodes.status.textContent, 'Done'); + assert.equal(p.nodes.captcha.hidden, true); + await p.callback({ ret: 0, ticket: 'late', randstr: 'random' }); + assert.equal(p.requests.length, 2, 'Success cannot be replayed by a late SDK callback'); + + p = await page({ rejected: true }); + await p.callback({ ret: 0, ticket: 'proof', randstr: 'random' }); + assert.equal(p.nodes.status.textContent, 'Rejected'); + assert.equal(p.nodes.retry.hidden, false); + await p.nodes.retry.onclick(); + assert.equal(p.shows, 2); + assert.equal(p.requests[2].url, '/api/kuaikan_verify/config'); + + const opts = { blocked: true }; + p = await page(opts); + assert.equal(p.nodes.status.textContent, 'Load failed'); + assert.equal(p.requests.length, 1); + assert.equal(p.scripts[0].removed, true); + opts.blocked = false; + await p.nodes.retry.onclick(); + assert.equal(p.shows, 1); + console.log('kuaikan web: OK'); +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tests/kuaikan/web_spec.lua b/tests/kuaikan/web_spec.lua new file mode 100644 index 0000000..f7b0fdf --- /dev/null +++ b/tests/kuaikan/web_spec.lua @@ -0,0 +1,11 @@ +--[[-- +快看腾讯滑块网页回归,使用本机 Node,不增加外部依赖。 +@module tests.moonsource_kuaikan.web_spec +--]] +local Assert = require("support.assert") +local here = debug.getinfo(1, "S").source:match("^@(.+)/[^/]+$") or "." +local root = here .. "/../.." +local pipe = assert(io.popen('node "' .. here .. '/web_spec.js" "' .. root .. '" 2>&1')) +local output = pipe:read("*a") +pipe:close() +Assert.is_true(output:find("kuaikan web: OK", 1, true) ~= nil, output)