✨ 初始提交:月读第三方书源插件集合
每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <[email protected]>
This commit is contained in:
commit
0956063d06
44 files changed
+21495
No files matched your search
@@ -0,0 +1,115 @@
|
||||
--[[-- 起点分类:动态菜单、男 / 女频筛选、去重分页、错误与取消。 @module tests.moonsource_qidian.browse_spec --]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local requests, pages, failure, delayed, late, cancelled = {}, {}, nil, false, nil, nil
|
||||
local metadata = {
|
||||
orderBy = { items = { { text = "人气", value = "" }, { text = "时间", value = "4" } } },
|
||||
filters = {
|
||||
{ key = "subCatId", title = "子分类", items = { { text = "全部", value = "" }, { text = "东方玄幻", value = 8 } } },
|
||||
{ key = "isvip", title = "资费", items = { { text = "全部", value = "" }, { text = "VIP", value = 1 } } },
|
||||
{ key = "isfinish", title = "状态", items = { { text = "全部", value = "" }, { text = "完本", value = 1 } } },
|
||||
},
|
||||
}
|
||||
package.preload["moonsource_qidian.client"] = function()
|
||||
return {
|
||||
categoryAsync = function(cat, cb)
|
||||
requests[#requests + 1] = cat or "index"
|
||||
cb(cat and metadata or { info = { { catId = 21, catName = "玄幻" }, { catId = 22, catName = "仙侠" } } })
|
||||
return { cancel = function() cancelled = "metadata" end }
|
||||
end,
|
||||
categoryListAsync = function(params, cb)
|
||||
requests[#requests + 1] = params
|
||||
local function done()
|
||||
if failure == params.pageNum then cb(nil, "offline")
|
||||
else cb({ records = pages[params.pageNum] or {}, pageNum = params.pageNum,
|
||||
isLast = params.pageNum >= #pages and 1 or 0, pageMax = 50 }) end
|
||||
end
|
||||
if delayed then late = done else done() end
|
||||
return { cancel = function() cancelled = "page" end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
local Library = require("moonsource_qidian.browse")
|
||||
local function row(id) return { bid = id, bName = "书" .. id } end
|
||||
local function reset()
|
||||
requests, failure, delayed, late, cancelled = {}, nil, false, nil, nil
|
||||
pages = { { row(1), row(2) }, { row(2), row(3) }, { row(4), row(5) } }
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
local source, result = {}, nil
|
||||
Library.run(source, { limit = 5 }, function(value) result = value end)
|
||||
Assert.len(result.data, 5, "合并后续页并按稳定身份去重")
|
||||
Assert.eq(result.data[3].stable_id, "3")
|
||||
Assert.eq(requests[1], "index")
|
||||
Assert.eq(requests[2], "21")
|
||||
Assert.eq(requests[5].pageNum, 3)
|
||||
Assert.len(source.category_info, 2, "动态分类归源实例所有")
|
||||
Assert.len(result.groups, 6, "资费、状态各自成组,不再把选中标记写进标题")
|
||||
Assert.eq(result.groups[4].title, "子分类")
|
||||
Assert.eq(result.groups[5].title, "资费")
|
||||
Assert.eq(result.groups[6].title, "状态")
|
||||
Assert.eq(result.groups[5].chips[2].title, "VIP")
|
||||
Assert.eq(result.groups[1].chips[3].id, "yuepiao:-1", "分类页仍可进入原榜单")
|
||||
Assert.matches(result.groups[2].chips[2].id, "catId=22")
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
local result
|
||||
Library.run({}, { node = "category?catId=80&gender=female&isvip=1&isfinish=1&orderBy=4", limit = 2 },
|
||||
function(value) result = value end)
|
||||
Assert.eq(requests[3].gender, "female")
|
||||
Assert.eq(requests[3].catId, "80")
|
||||
Assert.eq(requests[3].isvip, "1")
|
||||
Assert.eq(requests[3].isfinish, "1")
|
||||
Assert.eq(requests[3].orderBy, "4")
|
||||
Assert.eq(result.groups[2].chips[1].title, "古代言情")
|
||||
Assert.matches(result.groups[1].chips[1].id, "catId=21")
|
||||
Assert.matches(result.groups[1].chips[1].id, "isvip=1", "跨频道保留兼容条件")
|
||||
Assert.eq(result.groups[5].chips[2].title, "VIP")
|
||||
Assert.eq(result.groups[5].active, result.groups[5].chips[2].id, "资费用 group.active 标选中")
|
||||
Assert.eq(result.groups[6].chips[2].title, "完本")
|
||||
Assert.eq(result.groups[6].active, result.groups[6].chips[2].id)
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
failure = 2
|
||||
local result, err
|
||||
Library.run({}, { limit = 5 }, function(value, reason) result, err = value, reason end)
|
||||
Assert.is_nil(result, "中间页失败不能伪装成完整列表")
|
||||
Assert.eq(err, "offline")
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
pages = { { row(1) }, { row(1) }, { row(2) } }
|
||||
local result, err
|
||||
Library.run({}, { limit = 5 }, function(value, reason) result, err = value, reason end)
|
||||
Assert.is_nil(result, "源重复整页不能无限循环")
|
||||
Assert.is_true(err ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
delayed = true
|
||||
local called = false
|
||||
local job = Library.run({}, { limit = 5 }, function() called = true end)
|
||||
job.cancel()
|
||||
Assert.eq(cancelled, "page", "同步目录回调不能覆盖在飞分页的句柄")
|
||||
late()
|
||||
Assert.is_false(called)
|
||||
Assert.len(requests, 3)
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
pages = { {} }
|
||||
local result
|
||||
Library.run({}, { limit = 60 }, function(value) result = value end)
|
||||
Assert.len(result.data, 0)
|
||||
Assert.len(requests, 3)
|
||||
end
|
||||
@@ -0,0 +1,39 @@
|
||||
--[[-- 起点升级离线缓存不删章节,启用章评时原地追加入口。 @module tests.moonsource_qidian.cache_spec --]]
|
||||
local Assert = require("support.assert")
|
||||
local Config = require("support.config")
|
||||
Config.setupNativePath()
|
||||
local lfs = require("libs/libkoreader-lfs")
|
||||
local Paths = require("utils.paths")
|
||||
local source = require("moonsource_qidian.source").new()
|
||||
local dir = Config.dir() .. "/qidian-cache-preserve"
|
||||
lfs.mkdir(dir)
|
||||
local path = dir .. "/1.html"
|
||||
local file = assert(io.open(path, "wb"))
|
||||
file:write("<html><body><p>离线可读正文</p></body></html>")
|
||||
file:close()
|
||||
local work_dir = Paths.bookWorkDir
|
||||
Paths.bookWorkDir = function() return dir end
|
||||
source.paragraphReviewsEnabled = function() return true end
|
||||
package.loaded["source.chapter"] = nil
|
||||
package.preload["source.chapter"] = function()
|
||||
return {
|
||||
vipFetcher = function() return function() error("缓存命中不应拉正文") end end,
|
||||
openAsync = function(_source, _identity, _book, _opts, ops, cb)
|
||||
Assert.is_true(ops.reuse(path))
|
||||
cb(path)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
local opened
|
||||
source:openBookAsync({ source_id = "ext.qidian", stable_id = "fixture" }, { chapter_idx = 1 },
|
||||
function(value) opened = value end)
|
||||
Assert.eq(opened, path)
|
||||
file = assert(io.open(path, "rb"))
|
||||
local html = file:read("*a")
|
||||
file:close()
|
||||
Assert.matches(html, "<p>离线可读正文</p>")
|
||||
Assert.matches(html, 'id="moon%-chapter%-reviews"')
|
||||
Paths.bookWorkDir = work_dir
|
||||
os.remove(path)
|
||||
lfs.rmdir(dir)
|
||||
@@ -0,0 +1,119 @@
|
||||
--[[-- 起点短信候选会话:图形 / 短信 key、官方兑换、取消与同步回调。 @module tests.moonsource_qidian.login_spec --]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local JSON = require("support.json_stub")
|
||||
local Text = require("utils.text")
|
||||
package.preload["json"] = function() return JSON end
|
||||
local responses, requests, cancelled, late = {}, {}, {}, nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
request = function(opts, cb)
|
||||
requests[#requests + 1] = opts
|
||||
local index, res = #requests, table.remove(responses, 1)
|
||||
if res.defer then late = function() cb(res, res.err) end else cb(res, res.err) end
|
||||
return { cancel = function() cancelled[#cancelled + 1] = index end }
|
||||
end,
|
||||
header = function(res, key) return (res.headers or {})[key] end,
|
||||
headerAll = function(res, key)
|
||||
local value = (res.headers or {})[key]
|
||||
return type(value) == "table" and value or (value and { value } or {})
|
||||
end,
|
||||
}
|
||||
end
|
||||
local Login = require("moonsource_qidian.login")
|
||||
local function wire(data)
|
||||
return { code = 200, body = JSON.encode({ code = 0, data = data }) }
|
||||
end
|
||||
local function params(index)
|
||||
local result = {}
|
||||
for key, value in requests[index].url:match("%?(.*)"):gmatch("([^&=]+)=([^&]*)") do
|
||||
result[key] = Text.urlDecode(value)
|
||||
end
|
||||
return result
|
||||
end
|
||||
local function reset() responses, requests, cancelled, late = {}, {}, {}, nil end
|
||||
|
||||
do
|
||||
reset()
|
||||
local init = wire({ sessionKey = "image-key", imgSrc = "https://ptlogin.yuewen.com/image" })
|
||||
init.headers = { ["Set-Cookie"] = { "al=anonymous; Path=/", "session=anonymous-session; Path=/" } }
|
||||
responses = { init, wire({ nextAction = 0, sessionKey = "sms-key" }),
|
||||
wire({ nextAction = 0, ticket = "ticket", ywGuid = "raw-guid", ywKey = "raw-key" }),
|
||||
{ code = 302, headers = { Location = "/done", ["Set-Cookie"] = { "ywguid=321; Path=/", "ywkey=site-key; Path=/" } } },
|
||||
{ code = 200, body = "OK" } }
|
||||
local session, cookie = Login.new()
|
||||
session:beginAsync(function(data) Assert.is_true(data ~= nil) end)
|
||||
session:sendCodeAsync("+86", "13800000000", "image-code", function(data) Assert.eq(data.nextAction, 0) end)
|
||||
session:verifyAsync("13800000000", "123456", function(value) cookie = value end)
|
||||
Assert.eq(params(2).sessionKey, "image-key")
|
||||
Assert.eq(params(2).validateCode, "image-code")
|
||||
Assert.eq(params(2).inputUserId, "+8613800000000")
|
||||
Assert.eq(params(2).phoneIsAbroad, "0")
|
||||
Assert.eq(params(2).auto, "anonymous")
|
||||
Assert.eq(params(3).sessionKey, "sms-key")
|
||||
Assert.eq(params(3).inputUserId, "13800000000", "官方短信提交不带国际区号")
|
||||
Assert.matches(cookie, "ywguid=321")
|
||||
Assert.matches(cookie, "ywkey=site%-key")
|
||||
Assert.is_nil(cookie:find("_csrfToken", 1, true), "短信登录也不造假 csrf,交给 loginCheck 合并")
|
||||
Assert.is_nil(cookie:find("anonymous", 1, true), "匿名登录域 Cookie 不保存为书源凭据")
|
||||
Assert.is_nil(requests[1].headers.Cookie:find("ywkey", 1, true), "候选会话不读已保存账号")
|
||||
Assert.eq(requests[3].allow_redirects, false)
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
responses = { wire({ nextAction = 11, sessionKey = "captcha-key",
|
||||
imgSrc = "https://turing.captcha.qcloud.com/TCaptcha.js?aid=1600000770" }),
|
||||
wire({ nextAction = 0, sessionKey = "sms" }) }
|
||||
local session = Login.new()
|
||||
session:sendCodeAsync("+852", "12345678", nil, function(data) Assert.eq(data.nextAction, 11) end)
|
||||
session:sendCodeAsync("+852", "12345678", "random;proof", function(data) Assert.eq(data.nextAction, 0) end)
|
||||
Assert.eq(params(2).sessionKey, "captcha-key")
|
||||
Assert.eq(params(2).validateCode, "random;proof")
|
||||
Assert.eq(params(1).phoneIsAbroad, "1")
|
||||
Assert.eq(session.sms_key, "sms")
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
responses = { { code = 200, body = "not json" }, wire({ nextAction = 99 }) }
|
||||
local session, err = Login.new()
|
||||
session:beginAsync(function(value, reason) Assert.is_nil(value); err = reason end)
|
||||
Assert.matches(err, "响应无效")
|
||||
session:sendCodeAsync("+86", "13800000000", nil, function(value, reason) Assert.is_nil(value); err = reason end)
|
||||
Assert.matches(err, "未支持")
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
responses = { wire({ nextAction = 0, ticket = "ticket", ywGuid = "123", ywKey = "raw" }),
|
||||
{ code = 302, headers = { Location = "/done" } }, { code = 200, body = "OK", defer = true } }
|
||||
local session, called = Login.new(), false
|
||||
session.sms_key = "sms"
|
||||
session:verifyAsync("13800000000", "123456", function() called = true end)
|
||||
session:cancel()
|
||||
Assert.eq(cancelled[1], 3, "同步首段回调不能覆盖后续兑换的取消句柄")
|
||||
late()
|
||||
Assert.is_false(called)
|
||||
Assert.is_nil(session.sms_key)
|
||||
Assert.is_nil(next(session.webjar))
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
responses = { wire({ nextAction = 0, ["302url"] = "https://qidian.com.evil.example/x", ywGuid = "1", ywKey = "k" }) }
|
||||
local session, err = Login.new()
|
||||
session.sms_key = "sms"
|
||||
session:verifyAsync("13800000000", "123456", function(value, reason) Assert.is_nil(value); err = reason end)
|
||||
Assert.matches(err, "跳转地址无效")
|
||||
Assert.len(requests, 1)
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
responses = { { code = 200, body = "\137PNG\r\n\26\nimage" } }
|
||||
local image
|
||||
Login.new():imageAsync("/image", function(value) image = value end)
|
||||
Assert.matches(image, "^data:image/png;base64,")
|
||||
end
|
||||
@@ -0,0 +1,64 @@
|
||||
--[[-- 起点短信窗口:同意协议、断网、冷却、绑定手机号与取消。 @module tests.moonsource_qidian.phone_login_spec --]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Theme = require("support.theme_stubs")
|
||||
Theme.install()
|
||||
local connected, begins, sends, verifies, cancelled, deferred, late = true, 0, 0, 0, 0, false, nil
|
||||
package.preload["ui/network/manager"] = function() return { isConnected = function() return connected end } end
|
||||
package.preload["moonsource_qidian.login"] = function()
|
||||
return { new = function() return {
|
||||
beginAsync = function(self, cb) begins = begins + 1; self.initialized = true; cb({}) end,
|
||||
sendCodeAsync = function(_self, country, phone, proof, cb)
|
||||
sends = sends + 1
|
||||
Assert.eq(country, "+86"); Assert.eq(phone, "13800000000"); Assert.is_nil(proof)
|
||||
cb({ nextAction = 0 })
|
||||
end,
|
||||
verifyAsync = function(_self, phone, code, cb)
|
||||
verifies = verifies + 1
|
||||
Assert.eq(phone, "13800000000"); Assert.eq(code, "123456")
|
||||
if deferred then late = function() cb("candidate") end else cb("candidate") end
|
||||
end,
|
||||
cancel = function() cancelled = cancelled + 1 end,
|
||||
} end }
|
||||
end
|
||||
local Phone = require("moonsource_qidian.phone_login")
|
||||
local cookie
|
||||
local phone = Phone.new(function(value) cookie = value end)
|
||||
phone:start()
|
||||
Assert.eq(Theme.last("input").title, "起点手机号验证码登录")
|
||||
Assert.is_true(Theme.last("input").keep_open)
|
||||
|
||||
connected = false
|
||||
phone:send("+86", "13800000000")
|
||||
Assert.eq(sends, 0)
|
||||
Assert.matches(Theme.last("toast").text, "网络不可用")
|
||||
connected = true
|
||||
phone:send("+86", "invalid")
|
||||
Assert.eq(sends, 0)
|
||||
phone:send("+86", "13800000000")
|
||||
Assert.eq(begins, 0, "同意协议前不初始化或发送短信")
|
||||
Theme.last("confirm").ok_callback()
|
||||
Assert.eq(begins, 1)
|
||||
Assert.eq(sends, 1)
|
||||
phone:send("+86", "13800000000")
|
||||
Assert.eq(sends, 1, "冷却期不重复发短信")
|
||||
phone:verify("+86", "13900000000", "123456")
|
||||
Assert.eq(verifies, 0, "不能把验证码用于另一个手机号")
|
||||
phone:verify("+86", "13800000000", "abc")
|
||||
Assert.eq(verifies, 0)
|
||||
phone:verify("+86", "13800000000", "123456")
|
||||
Assert.eq(cookie, "candidate")
|
||||
Assert.is_true(Theme.last("input").closed)
|
||||
Assert.eq(cancelled, 1)
|
||||
|
||||
phone = Phone.new(function() Assert.is_true(false, "取消后不得保存迟到候选") end)
|
||||
phone:start()
|
||||
phone.agreed = true
|
||||
phone:send("+86", "13800000000")
|
||||
deferred = true
|
||||
phone:verify("+86", "13800000000", "123456")
|
||||
phone:cancel()
|
||||
late()
|
||||
Assert.eq(cancelled, 2)
|
||||
Assert.is_nil(phone.phone)
|
||||
@@ -0,0 +1,193 @@
|
||||
--[[--
|
||||
起点正文流程:cES=2 先下字体再解密,cES=0/fEnS=0 直接出文本。
|
||||
|
||||
@module tests.source.qidian_content_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local JSONStub = require("support.json_stub")
|
||||
local Text = require("utils.text")
|
||||
|
||||
package.preload["json"] = function()
|
||||
return { decode = JSONStub.decode, encode = JSONStub.encode }
|
||||
end
|
||||
|
||||
local cfg = { cookie = "ywguid=123; ywkey=k" }
|
||||
package.preload["utils.settings"] = function()
|
||||
return { getSource = function() return cfg end }
|
||||
end
|
||||
|
||||
local replies, deferred, requested_cookie = {}, nil, nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, opts, cb)
|
||||
requested_cookie = opts.headers and opts.headers.Cookie
|
||||
local reply = table.remove(replies, 1)
|
||||
if reply and reply.defer then deferred = function() cb(reply.body, reply.err, reply.res) end
|
||||
else cb(reply and reply.body, reply and reply.err, reply and reply.res) end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
local FONT_BYTES = "\0\1\0\0FONTBYTES"
|
||||
local fock_calls = {}
|
||||
package.preload["moonsource_qidian.fock"] = function()
|
||||
return {
|
||||
chapterAsync = function(info, font, chapter_id, keypool, version, uid, cb)
|
||||
fock_calls[#fock_calls + 1] = {
|
||||
kind = "chapter", font = font, chapter_id = chapter_id,
|
||||
keypool = keypool, version = version, uid = uid,
|
||||
}
|
||||
cb("RESTORED")
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
restoreAsync = function(html, info, font, cb)
|
||||
fock_calls[#fock_calls + 1] = { kind = "restore", font = font, html = html }
|
||||
cb("RESTORED")
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
decryptAsync = function(content, chapter_id, keypool, version, uid, cb)
|
||||
fock_calls[#fock_calls + 1] = { kind = "decrypt", uid = uid }
|
||||
cb("<p>甲</p>")
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.loaded["moonsource_qidian.client"] = nil
|
||||
package.loaded["moonsource_qidian.mapper"] = nil
|
||||
local Client = require("moonsource_qidian.client")
|
||||
|
||||
local function page(info, user)
|
||||
return '<script id="vite-plugin-ssr_pageContext" type="application/json">'
|
||||
.. JSONStub.encode({ pageContext = { pageProps = { pageData = { chapterInfo = info, user = user } } } }) .. "</script>"
|
||||
end
|
||||
|
||||
local function fkp()
|
||||
return Text.base64Encode('window.onkeyfocus("KEYPOOL", 1635757421)')
|
||||
end
|
||||
|
||||
local function info(extra)
|
||||
local out = {
|
||||
chapterName = "第一章", chapterId = 9, vipStatus = 1, isBuy = 1,
|
||||
content = "CIPHER", fkp = fkp(), cES = 0, fEnS = 0,
|
||||
}
|
||||
for k, v in pairs(extra or {}) do out[k] = v end
|
||||
return out
|
||||
end
|
||||
|
||||
do
|
||||
-- 扫码 Cookie 的 GUID 不一定是章节响应的解码身份;用响应确认的 GUID。
|
||||
local html = page(info({ fEnS = 1 })):gsub('"pageData":{', '"pageData":{"user":{"guid":1234567890123456},')
|
||||
replies = { { body = html } }
|
||||
fock_calls = {}
|
||||
local text
|
||||
Client.contentAsync("1", "2", function(value) text = value end)
|
||||
Assert.is_true(text ~= nil)
|
||||
Assert.eq(fock_calls[1].uid, "1234567890123456", "LuaJIT tostring 会把长整数变成科学计数法")
|
||||
end
|
||||
|
||||
do
|
||||
-- 请求发出后换账号,旧响应仍绑定原请求,不重新读新 Cookie。
|
||||
cfg.cookie = "ywguid=123; ywkey=old"
|
||||
replies = { { defer = true, body = page(info({ fEnS = 1 })) } }
|
||||
fock_calls = {}
|
||||
Client.contentAsync("1", "2", function() end)
|
||||
Assert.eq(requested_cookie, cfg.cookie)
|
||||
cfg.cookie = "ywguid=999; ywkey=new"
|
||||
deferred()
|
||||
Assert.eq(fock_calls[1].uid, "123")
|
||||
cfg.cookie = "ywguid=123; ywkey=k"
|
||||
end
|
||||
|
||||
do
|
||||
replies = { { defer = true, body = page(info({ fEnS = 1 })) } }
|
||||
fock_calls = {}
|
||||
local called = false
|
||||
local job = Client.contentAsync("1", "2", function() called = true end)
|
||||
job.cancel()
|
||||
deferred()
|
||||
Assert.is_false(called, "取消后不交付迟到正文")
|
||||
Assert.len(fock_calls, 0)
|
||||
end
|
||||
|
||||
do
|
||||
-- 免费 / 普通章:不走 Fock,也不下字体。
|
||||
replies = { { body = page(info({ content = "<p>甲</p>" })) } }
|
||||
fock_calls = {}
|
||||
local text
|
||||
Client.contentAsync("1", "2", function(v) text = v end)
|
||||
Assert.eq(text, "\n甲\n")
|
||||
Assert.len(fock_calls, 0)
|
||||
end
|
||||
|
||||
do
|
||||
-- Fock + cES=2:先拉 fixedFontTtf,再把字节交给解密 + 字体还原。
|
||||
replies = {
|
||||
{ body = page(info({ fEnS = 1, cES = 2, fixedFontTtf = "https://font/fixed.ttf", randomFont = "{}", css = "" })) },
|
||||
{ body = FONT_BYTES },
|
||||
}
|
||||
fock_calls = {}
|
||||
local text
|
||||
Client.contentAsync("1", "2", function(v) text = v end)
|
||||
Assert.eq(text, "RESTORED")
|
||||
Assert.len(fock_calls, 1)
|
||||
Assert.eq(fock_calls[1].kind, "chapter")
|
||||
Assert.eq(fock_calls[1].font, FONT_BYTES)
|
||||
Assert.eq(fock_calls[1].uid, "123")
|
||||
Assert.eq(fock_calls[1].keypool, "KEYPOOL")
|
||||
Assert.eq(fock_calls[1].version, "1635757421")
|
||||
end
|
||||
|
||||
do
|
||||
-- 只有字体层(fEnS=0):直接还原 HTML,不做 Fock。
|
||||
replies = {
|
||||
{ body = page(info({ fEnS = 0, cES = 2, fixedFontTtf = "https://font/fixed.ttf", randomFont = "{}", css = "" })) },
|
||||
{ body = FONT_BYTES },
|
||||
}
|
||||
fock_calls = {}
|
||||
local text
|
||||
Client.contentAsync("1", "2", function(v) text = v end)
|
||||
Assert.eq(text, "RESTORED")
|
||||
Assert.len(fock_calls, 1)
|
||||
Assert.eq(fock_calls[1].kind, "restore")
|
||||
Assert.eq(fock_calls[1].font, FONT_BYTES)
|
||||
end
|
||||
|
||||
do
|
||||
-- 未识别的 cES 明确报错,不能把密文当正文。
|
||||
replies = { { body = page(info({ fEnS = 0, cES = 1 })) } }
|
||||
fock_calls = {}
|
||||
local text, err
|
||||
Client.contentAsync("1", "2", function(v, e) text, err = v, e end)
|
||||
Assert.is_nil(text)
|
||||
Assert.is_true(err ~= nil and err:find("不受支持", 1, true) ~= nil)
|
||||
Assert.len(fock_calls, 0)
|
||||
end
|
||||
|
||||
do
|
||||
-- CDN 返回 HTML 错误页而不是字体:按下载失败处理。
|
||||
replies = {
|
||||
{ body = page(info({ fEnS = 1, cES = 2, fixedFontTtf = "https://font/fixed.ttf", randomFont = "{}", css = "" })) },
|
||||
{ body = "<html>403</html>" },
|
||||
}
|
||||
fock_calls = {}
|
||||
local text, err
|
||||
Client.contentAsync("1", "2", function(v, e) text, err = v, e end)
|
||||
Assert.is_nil(text)
|
||||
Assert.is_true(err ~= nil and err:find("字体下载失败", 1, true) ~= nil)
|
||||
Assert.len(fock_calls, 0)
|
||||
end
|
||||
|
||||
do
|
||||
-- cES=2 但没有字体地址:明确报错,不把错字当正文。
|
||||
replies = { { body = page(info({ fEnS = 1, cES = 2, randomFont = "{}", css = "" })) } }
|
||||
fock_calls = {}
|
||||
local text, err
|
||||
Client.contentAsync("1", "2", function(v, e) text, err = v, e end)
|
||||
Assert.is_nil(text)
|
||||
Assert.is_true(err ~= nil and err:find("字体", 1, true) ~= nil)
|
||||
Assert.len(fock_calls, 0)
|
||||
end
|
||||
@@ -0,0 +1,120 @@
|
||||
--[[--
|
||||
起点 VIP 章节解密(Fock 转译版)离线用例。
|
||||
|
||||
@module tests.source.qidian_fock_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Sample = require("support.qidian_fock_sample")
|
||||
local Fock = require("moonsource_qidian.fock")
|
||||
|
||||
local plain, err = Fock.decrypt(Sample.content, Sample.chapter_id, Sample.keypool, Sample.version, Sample.uid)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(#plain, 13654)
|
||||
Assert.eq(plain:sub(1, 3), "<p>")
|
||||
Assert.matches(plain, "光王街")
|
||||
|
||||
-- 子进程任务:worker 结果经 on_done 交回
|
||||
local Job = require("workers.job")
|
||||
local real_run = Job.run
|
||||
Job.run = function(worker, opts) opts.on_done(worker(function() end)); return {} end
|
||||
local async_text
|
||||
Fock.decryptAsync(Sample.content, Sample.chapter_id, Sample.keypool, Sample.version, Sample.uid,
|
||||
function(text) async_text = text end)
|
||||
Job.run = real_run
|
||||
Assert.eq(async_text, plain)
|
||||
|
||||
-- 共用宿主 moonsource_qidian.yuewen_fock:decrypt 期间关 JIT、完事恢复原状;jobAsync 子进程抛错经 cb(nil, err) 交回
|
||||
do
|
||||
local Shared = require("moonsource_qidian.yuewen_fock")
|
||||
local Text = require("utils.text")
|
||||
local was_on = jit.status()
|
||||
local seen_off
|
||||
local decode = Text.base64Decode
|
||||
Text.base64Decode = function(...)
|
||||
seen_off = not jit.status()
|
||||
return decode(...)
|
||||
end
|
||||
|
||||
-- 字体路径由主进程持有:取消只清自己的文件,失败 / 成功也清理,退出前不抢删。
|
||||
do
|
||||
local Shared = require("moonsource_qidian.yuewen_fock")
|
||||
local lfs = require("libs/libkoreader-lfs")
|
||||
local pending = {}
|
||||
Job.run = function(worker, opts)
|
||||
local job = { poll = 0.5 }
|
||||
pending[#pending + 1] = { worker = worker, opts = opts, job = job }
|
||||
return job
|
||||
end
|
||||
local files = {}
|
||||
local function worker(paths)
|
||||
files[#files + 1] = paths
|
||||
for index, path in ipairs(paths) do
|
||||
local file = assert(io.open(path, "wb"))
|
||||
assert(file:write("font-" .. index))
|
||||
assert(file:close())
|
||||
end
|
||||
return { text = "restored" }
|
||||
end
|
||||
local text, err
|
||||
local function done(value, reason) text, err = value, reason end
|
||||
Shared.jobAsync("font_cancel", worker, done)
|
||||
Shared.jobAsync("font_failed", worker, done)
|
||||
pending[1].worker()
|
||||
pending[2].worker()
|
||||
pending[1].opts.on_cancelled(pending[1].job)
|
||||
Assert.is_nil(text)
|
||||
for _idx, path in ipairs(files[1]) do Assert.is_nil(lfs.attributes(path)) end
|
||||
for _idx, path in ipairs(files[2]) do Assert.eq(lfs.attributes(path, "mode"), "file") end
|
||||
pending[2].opts.on_failed("timeout")
|
||||
Assert.is_nil(text)
|
||||
Assert.eq(err, "timeout")
|
||||
for _idx, path in ipairs(files[2]) do Assert.is_nil(lfs.attributes(path)) end
|
||||
|
||||
Shared.jobAsync("font_done", worker, done)
|
||||
pending[3].opts.on_done(pending[3].worker())
|
||||
Assert.eq(text, "restored")
|
||||
Assert.is_nil(err)
|
||||
for _idx, path in ipairs(files[3]) do Assert.is_nil(lfs.attributes(path)) end
|
||||
|
||||
Shared.jobAsync("font_exiting", worker, done)
|
||||
pending[4].worker()
|
||||
pending[4].job.pid = 123
|
||||
local ffiUtil = require("ffi/util")
|
||||
local UIManager = require("ui/uimanager")
|
||||
local real_done, real_schedule = ffiUtil.isSubProcessDone, UIManager.scheduleIn
|
||||
local exited, tick = false, nil
|
||||
ffiUtil.isSubProcessDone = function() return exited end
|
||||
UIManager.scheduleIn = function(_self, _delay, fn) tick = fn end
|
||||
pending[4].opts.on_cancelled(pending[4].job)
|
||||
for _idx, path in ipairs(files[4]) do Assert.eq(lfs.attributes(path, "mode"), "file") end
|
||||
Assert.eq(type(tick), "function")
|
||||
exited = true
|
||||
tick()
|
||||
for _idx, path in ipairs(files[4]) do Assert.is_nil(lfs.attributes(path)) end
|
||||
ffiUtil.isSubProcessDone, UIManager.scheduleIn = real_done, real_schedule
|
||||
Job.run = real_run
|
||||
end
|
||||
local text = Fock.decrypt(Sample.content, Sample.chapter_id, Sample.keypool, Sample.version, Sample.uid)
|
||||
Text.base64Decode = decode
|
||||
Assert.eq(#text, 13654)
|
||||
Assert.is_true(seen_off, "解密期间 JIT 关着")
|
||||
Assert.eq(jit.status(), was_on, "解密完 JIT 开关恢复")
|
||||
|
||||
local Job = require("workers.job")
|
||||
local real_run = Job.run
|
||||
Job.run = function(worker, opts)
|
||||
local ok, res = pcall(worker)
|
||||
if ok then opts.on_done(res) else opts.on_failed(res) end
|
||||
return {}
|
||||
end
|
||||
local got_text, got_err
|
||||
Shared.jobAsync("t", function() return { text = "ok" } end, function(t, e) got_text, got_err = t, e end)
|
||||
Assert.eq(got_text, "ok")
|
||||
Assert.is_nil(got_err)
|
||||
Shared.jobAsync("t", function() error("boom", 0) end, function(t, e) got_text, got_err = t, e end)
|
||||
Assert.is_nil(got_text)
|
||||
Assert.eq(got_err, "boom")
|
||||
Job.run = real_run
|
||||
end
|
||||
@@ -0,0 +1,92 @@
|
||||
--[[--
|
||||
起点 cES=2 字体层:字段判定、诱饵副本裁剪、无字体时的兜底。
|
||||
|
||||
@module tests.source.qidian_font_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local FontRestore = require("moonsource_qidian.yuewen_fonts")
|
||||
local Mapper = require("moonsource_qidian.mapper")
|
||||
|
||||
-- Fock 与字体层是两个独立标记,不能再用 cES 非 0 一把抓。
|
||||
Assert.is_true(Mapper.fockEncrypted({ fEnS = "1" }))
|
||||
Assert.is_false(Mapper.fockEncrypted({ fEnS = "0", cES = "2" }))
|
||||
Assert.is_true(Mapper.fontProtected({ cES = "2" }))
|
||||
Assert.is_false(Mapper.fontProtected({ cES = "1" }))
|
||||
|
||||
-- 起点把同一章再追加一份同长度的诱饵副本;长度一一对应时丢掉后半。
|
||||
local duplicate = { "甲甲乙乙", "乙乙乙乙乙", "甲甲乙乙", "乙乙乙乙丁" }
|
||||
local trimmed = FontRestore.dropDecoyHalf(duplicate)
|
||||
Assert.eq(#trimmed, 2)
|
||||
Assert.eq(trimmed[1], "甲甲乙乙")
|
||||
Assert.eq(trimmed[2], "乙乙乙乙乙")
|
||||
|
||||
local uneven = { "甲甲", "乙乙乙", "丙丙", "丁丁" }
|
||||
Assert.eq(#FontRestore.dropDecoyHalf(uneven), 4)
|
||||
|
||||
local odd = { "甲甲", "乙乙乙", "丙丙" }
|
||||
Assert.eq(#FontRestore.dropDecoyHalf(odd), 3)
|
||||
|
||||
-- 没有 fixedFont 时不进入 FreeType;仍应按 CSS 解析段落并裁剪诱饵。
|
||||
local html = "<p> 甲甲</p><p> 乙乙乙</p><p> 甲甲</p><p> 乙乙乙</p>"
|
||||
local text = FontRestore.restore(html, { css = "", randomFont = { data = {} } }, nil, { dedupe = true })
|
||||
Assert.eq(text, " 甲甲\n 乙乙乙")
|
||||
|
||||
-- 于/干、责/贵 只修固定搭配;“干部/干活/干事/干劲”保留。
|
||||
Assert.eq(FontRestore.fixConfusions("关干《链法总纲》终干敲定了"),
|
||||
"关于《链法总纲》终于敲定了")
|
||||
Assert.eq(FontRestore.fixConfusions("对干宗门,对干部,在干活,等干事"),
|
||||
"对于宗门,对干部,在干活,等干事")
|
||||
Assert.eq(FontRestore.fixConfusions("职贵、担贵、负贵、贵任"),
|
||||
"职责、担责、负责、责任")
|
||||
Assert.eq(FontRestore.fixConfusions("同泮支援,泮随着,汇聚干此"),
|
||||
"同伴支援,伴随着,汇聚于此")
|
||||
|
||||
-- restore 内部也要能调用到 fixConfusions(不能是未赋值的全局)。
|
||||
local text2 = FontRestore.restore("<p>关干《链法总纲》</p>", { css = "", randomFont = { data = {} } }, nil,
|
||||
{ confusions = true })
|
||||
Assert.eq(text2, "关于《链法总纲》")
|
||||
|
||||
-- 前后半字数相同但内容不同的真实对称段落不能被当诱饵删掉。
|
||||
Assert.eq(#FontRestore.dropDecoyHalf({ "春风来", "夏雨至", "秋叶落", "冬雪飘" }), 4)
|
||||
|
||||
-- 常见搭配里的“干”不能被改成“于”。
|
||||
Assert.eq(FontRestore.fixConfusions("在干什么,对干净的"), "在干什么,对干净的")
|
||||
|
||||
-- 识别使用主进程交下来的两条路径,正常 / glyph 抛错都及时删除。
|
||||
do
|
||||
local Paths = require("utils.paths")
|
||||
local lfs = require("libs/libkoreader-lfs")
|
||||
local dir = Paths.tmpDir() .. "/font_restore_spec"
|
||||
assert(Paths.ensureDir(dir .. "/noto"))
|
||||
local ref = dir .. "/noto/NotoSansCJKsc-Regular.otf"
|
||||
local file = assert(io.open(ref, "wb"))
|
||||
assert(file:write("reference"))
|
||||
assert(file:close())
|
||||
local old_fontlist, old_glyph = package.loaded["fontlist"], package.loaded["utils.glyph"]
|
||||
package.loaded["fontlist"] = { fontdir = dir }
|
||||
local paths = { Paths.tmpname(".font"), Paths.tmpname(".font") }
|
||||
local fixed = "\0\1\0\0fixed"
|
||||
package.loaded["utils.glyph"] = {
|
||||
recognize = function(_ref, _cache, tasks)
|
||||
Assert.eq(tasks[1].font_path, paths[1])
|
||||
Assert.eq(tasks[2].font_path, paths[2])
|
||||
local font = assert(io.open(tasks[2].font_path, "rb"))
|
||||
Assert.eq(font:read("*a"), fixed)
|
||||
font:close()
|
||||
return { { [0x4909] = "乙" }, { [0x7532] = "丙" } }
|
||||
end,
|
||||
}
|
||||
local font = { css = "", randomFont = { data = { 0, 1, 0, 0 } } }
|
||||
Assert.eq(FontRestore.restore("<p>甲䤉</p>", font, fixed, { temp_paths = paths }), "丙乙")
|
||||
for _idx, path in ipairs(paths) do Assert.is_nil(lfs.attributes(path)) end
|
||||
package.loaded["utils.glyph"].recognize = function() error("glyph failed", 0) end
|
||||
Assert.errors(function()
|
||||
FontRestore.restore("<p>甲䤉</p>", font, fixed, { temp_paths = paths })
|
||||
end, "glyph failed")
|
||||
for _idx, path in ipairs(paths) do Assert.is_nil(lfs.attributes(path)) end
|
||||
package.loaded["fontlist"], package.loaded["utils.glyph"] = old_fontlist, old_glyph
|
||||
os.remove(ref)
|
||||
lfs.rmdir(dir .. "/noto")
|
||||
lfs.rmdir(dir)
|
||||
end
|
||||
@@ -0,0 +1,351 @@
|
||||
--[[--
|
||||
起点书架分页、目录 / 正文映射与 Cookie 解析离线用例。
|
||||
|
||||
@module tests.source.qidian_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local JSONStub = require("support.json_stub")
|
||||
|
||||
package.preload["json"] = function()
|
||||
return { decode = JSONStub.decode, encode = JSONStub.encode }
|
||||
end
|
||||
|
||||
local cfg = {}
|
||||
package.preload["utils.settings"] = function()
|
||||
return { getSource = function() return cfg end }
|
||||
end
|
||||
|
||||
local expired
|
||||
package.preload["source.auth"] = function()
|
||||
return { expire = function(_, msg) expired = msg; return msg end, ok = function() end }
|
||||
end
|
||||
|
||||
local requests, replies = {}, {}
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, opts, cb)
|
||||
requests[#requests + 1] = { url = url, opts = opts }
|
||||
local reply = table.remove(replies, 1)
|
||||
cb(reply.body, reply.err, reply.res)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
post = function(url, body, opts, cb)
|
||||
requests[#requests + 1] = { url = url, body = body, opts = opts }
|
||||
local reply = table.remove(replies, 1)
|
||||
cb(reply.body, reply.err, reply.res)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
headerAll = function(res, key)
|
||||
if not res or not res.headers then return {} end
|
||||
local value = res.headers[key]
|
||||
return type(value) == "table" and value or (value and { value } or {})
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.loaded["moonsource_qidian.client"] = nil
|
||||
package.loaded["moonsource_qidian.mapper"] = nil
|
||||
package.loaded["moonsource_qidian.setting"] = nil
|
||||
local Client = require("moonsource_qidian.client")
|
||||
local Mapper = require("moonsource_qidian.mapper")
|
||||
local Setting = require("moonsource_qidian.setting")
|
||||
|
||||
local function page(data)
|
||||
return '<script id="vite-plugin-ssr_pageContext" type="application/json">'
|
||||
.. JSONStub.encode({ pageContext = { pageProps = { pageData = data } } }) .. "</script>"
|
||||
end
|
||||
|
||||
do
|
||||
local data = Mapper.pageData(page({ bookInfo = { bookId = 9 } }))
|
||||
Assert.eq(data.bookInfo.bookId, 9)
|
||||
Assert.is_nil(Mapper.pageData("<html>登录</html>"))
|
||||
end
|
||||
|
||||
do
|
||||
local book = Mapper.book({
|
||||
bookId = 101, bookName = "诡秘", authorName = "乌贼", chanName = "玄幻",
|
||||
wordsCnt = 100, desc = " 甲<br>乙",
|
||||
})
|
||||
Assert.eq(book.stable_id, "101")
|
||||
Assert.eq(book.cover, "https://bookcover.yuewen.com/qdbimg/349573/101/180")
|
||||
Assert.eq(book.meta.words, 100)
|
||||
Assert.eq(book.intro, " 甲\n乙")
|
||||
end
|
||||
|
||||
do
|
||||
local books = Mapper.shelfList({
|
||||
{ bid = 1, bName = "短", info = { bookId = 1, bookName = "全名", authorName = "甲", wordsCnt = 3 } },
|
||||
{ bid = 2, bName = "截断", local_book = { stable_id = "2", title = "本地", cover = "" } },
|
||||
{ bid = 3, bName = "兜底", bAuth = "乙" },
|
||||
})
|
||||
Assert.eq(books[1].title, "全名")
|
||||
Assert.eq(books[2].cover, "https://bookcover.yuewen.com/qdbimg/349573/2/180")
|
||||
Assert.eq(books[3].title, "兜底")
|
||||
Assert.eq(books[3].authors, "乙")
|
||||
end
|
||||
|
||||
-- 分类开关:关 = 题材;开 = 自定义分组(互斥,不混合)。
|
||||
do
|
||||
cfg.category_as_group = false
|
||||
local off = Mapper.shelfList({
|
||||
{ bid = 1, cateName = "玄幻", _group_name = "追更", info = { bookId = 1, bookName = "甲", chanName = "玄幻" } },
|
||||
{ bid = 2, cateName = "都市", info = { bookId = 2, bookName = "乙", chanName = "都市" } },
|
||||
})
|
||||
Assert.eq(off[1].category, "玄幻", "关:进组仍用题材")
|
||||
Assert.eq(off[2].category, "都市", "关:没进组用题材")
|
||||
cfg.category_as_group = true
|
||||
local on = Mapper.shelfList({
|
||||
{ bid = 1, cateName = "玄幻", _group_name = "追更", info = { bookId = 1, bookName = "甲", chanName = "玄幻" } },
|
||||
{ bid = 2, cateName = "都市", info = { bookId = 2, bookName = "乙", chanName = "都市" } },
|
||||
})
|
||||
Assert.eq(on[1].category, "追更", "开:进组用分组名")
|
||||
Assert.is_nil(on[2].category, "开:没进组不写题材")
|
||||
cfg.category_as_group = false
|
||||
end
|
||||
|
||||
do
|
||||
local toc = Mapper.toc({ vs = {
|
||||
{ vN = "卷一", cs = { { id = 11, cN = "第一章", cnt = 10, sS = 1, uT = "2022-10-07 10:22:55" } } },
|
||||
{ vN = "卷二", cs = { { id = 22, cN = "VIP", cnt = 20, sS = 0, uT = "bad" } } },
|
||||
} })
|
||||
Assert.len(toc, 2)
|
||||
Assert.eq(toc[1].uid, "11")
|
||||
Assert.eq(toc[1].updated, 1665109375)
|
||||
Assert.is_false(toc[1].vip)
|
||||
Assert.eq(toc[2].idx, 2)
|
||||
Assert.eq(toc[2].title, "VIP")
|
||||
Assert.is_nil(toc[2].updated)
|
||||
Assert.is_true(toc[2].vip)
|
||||
Assert.eq(Mapper.chapterTime("2022-10-07 10:22"), 1665109320)
|
||||
Assert.is_nil(Mapper.chapterTime("2022-10-07"))
|
||||
local read = Mapper.readChapter({ readCid = 730944635, readCname = "第一章" })
|
||||
Assert.eq(read.uid, "730944635")
|
||||
Assert.eq(read.title, "第一章")
|
||||
Assert.is_nil(Mapper.readChapter({ readCid = 0 }))
|
||||
Assert.is_nil(Mapper.readChapter({}))
|
||||
end
|
||||
|
||||
do
|
||||
Assert.eq(Mapper.chapterText("<p> 甲<p> 乙&丙"), "\n 甲\n 乙&丙")
|
||||
Assert.is_nil(Mapper.chapterText(""))
|
||||
Assert.is_false(Mapper.locked({ vipStatus = 0, isBuy = 0, content = "<p>甲" }))
|
||||
Assert.is_true(Mapper.locked({ vipStatus = 1, isBuy = 0 }))
|
||||
Assert.is_false(Mapper.locked({ vipStatus = 1, isBuy = 1 }))
|
||||
end
|
||||
|
||||
do
|
||||
Assert.eq(Setting.parseCookie("_csrfToken=t; ywkey=k; bad name=1"), "_csrfToken=t; ywkey=k")
|
||||
Assert.eq(Client.csrf("_csrfToken=t; ywkey=k"), "t")
|
||||
Assert.is_nil(Client.csrf("ywkey=k"))
|
||||
Assert.eq(Setting.browser.domain, "m.qidian.com")
|
||||
Assert.eq(Setting.browser.login:match("^https://([^/]+)"), Setting.browser.domain)
|
||||
Assert.eq(Setting.browser.check:match("^https://([^/]+)"), Setting.browser.domain)
|
||||
Assert.eq(Setting.fromPayload({ cookies = {
|
||||
{ domain = ".qidian.com", name = "_csrfToken", value = "t" },
|
||||
{ domain = "m.qidian.com", name = "ywkey", value = "k" },
|
||||
{ domain = "evil.com", name = "x", value = "y" },
|
||||
} }), "_csrfToken=t; ywkey=k")
|
||||
end
|
||||
|
||||
-- 默认分组翻完再拉其它分组,请求带 _csrfToken。
|
||||
do
|
||||
cfg.cookie = "ywkey=k; _csrfToken=tok"
|
||||
requests, replies = {}, {
|
||||
{ body = '{"code":0,"data":{"list":[{"bid":1,"bName":"甲"}],"groups":[{"groupId":-100,"bookCount":1},{"groupId":2,"bookCount":1}],"page":{"isLast":1}}}' },
|
||||
{ body = '{"code":0,"data":{"list":[{"bid":1,"bName":"甲"},{"bid":2,"bName":"乙"}],"page":{"isLast":1}}}' },
|
||||
}
|
||||
local rows, err
|
||||
Client.shelfAsync(cfg.cookie, function(v, e) rows, err = v, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(rows, 2)
|
||||
Assert.eq(rows[2].bid, 2)
|
||||
Assert.len(requests, 2)
|
||||
Assert.matches(requests[1].url, "gid=%-100")
|
||||
Assert.matches(requests[1].url, "_csrfToken=tok")
|
||||
Assert.matches(requests[2].url, "gid=2")
|
||||
end
|
||||
|
||||
-- 书架页 302:已保存的 Cookie 标失效。
|
||||
do
|
||||
expired = nil
|
||||
requests, replies = {}, { { body = nil, err = "HTTP 302", res = { code = 302 } } }
|
||||
local ok, err
|
||||
Client.loginCheckAsync(cfg.cookie, function(v, e) ok, err = v, e end)
|
||||
Assert.is_nil(ok)
|
||||
Assert.matches(err, "QQ阅读或起点 App 扫码")
|
||||
Assert.eq(expired, err)
|
||||
end
|
||||
|
||||
-- 扫码只有 ywguid/ywkey:书架页 Set-Cookie 合并成真 csrf 后再回传 account.cookie。
|
||||
do
|
||||
requests, replies = {}, {
|
||||
{
|
||||
body = page({ user = { isLogin = true, guid = 12345 } }),
|
||||
res = {
|
||||
code = 200,
|
||||
headers = {
|
||||
["Set-Cookie"] = {
|
||||
"_csrfToken=real-csrf; Path=/",
|
||||
"newstatisticUUID=uuid-1; Path=/",
|
||||
"fu=1; Path=/",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
local ok, err, account
|
||||
Client.loginCheckAsync("ywguid=12345; ywkey=site-key", function(v, e, a) ok, err, account = v, e, a end)
|
||||
Assert.is_true(ok)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(account.id, "12345")
|
||||
Assert.matches(account.cookie, "_csrfToken=real%-csrf")
|
||||
Assert.matches(account.cookie, "ywguid=12345")
|
||||
Assert.matches(account.cookie, "ywkey=site%-key")
|
||||
Assert.matches(account.cookie, "newstatisticUUID=uuid%-1")
|
||||
end
|
||||
|
||||
-- 登录态在,但书架页没给 csrf:拒绝落盘,免得 VIP 正文一直空。
|
||||
do
|
||||
requests, replies = {}, {
|
||||
{ body = page({ user = { isLogin = true, guid = 9 } }), res = { code = 200, headers = {} } },
|
||||
}
|
||||
local ok, err, account
|
||||
Client.loginCheckAsync("ywguid=9; ywkey=k", function(v, e, a) ok, err, account = v, e, a end)
|
||||
Assert.is_nil(ok)
|
||||
Assert.matches(err, "缺少登录凭证")
|
||||
Assert.is_nil(account)
|
||||
end
|
||||
|
||||
-- 书架响应明确删除 csrf:不能保留旧值继续判成功、回传过期凭据。
|
||||
do
|
||||
requests, replies = {}, {
|
||||
{ body = page({ user = { isLogin = true, guid = 9 } }),
|
||||
res = { code = 200, headers = { ["Set-Cookie"] = "_csrfToken=; Max-Age=0; Path=/" } } },
|
||||
}
|
||||
local ok, err, account
|
||||
Client.loginCheckAsync("ywguid=9; ywkey=k; _csrfToken=old", function(v, e, a) ok, err, account = v, e, a end)
|
||||
Assert.is_nil(ok)
|
||||
Assert.matches(err, "缺少登录凭证")
|
||||
Assert.is_nil(account)
|
||||
end
|
||||
|
||||
-- 非 csrf Cookie 删除、覆盖仍保留可用登录态。
|
||||
do
|
||||
requests, replies = {}, {
|
||||
{ body = page({ user = { isLogin = true, guid = 9 } }),
|
||||
res = { code = 200, headers = { ["Set-Cookie"] = {
|
||||
"old=; Max-Age=0", "_csrfToken=new; Path=/",
|
||||
} } } },
|
||||
}
|
||||
local ok, account
|
||||
Client.loginCheckAsync("ywguid=9; ywkey=k; _csrfToken=old; old=gone", function(v, _err, a) ok, account = v, a end)
|
||||
Assert.is_true(ok)
|
||||
Assert.eq(account.cookie, "_csrfToken=new; ywguid=9; ywkey=k")
|
||||
end
|
||||
|
||||
-- 加入书架走 POST,书号在表单里。
|
||||
do
|
||||
requests, replies = {}, { { body = '{"code":0,"data":{"9":{"code":0,"message":"操作成功"}}}' } }
|
||||
local ok
|
||||
Client.addAsync("9", function(v) ok = v end)
|
||||
Assert.is_true(ok)
|
||||
Assert.matches(requests[1].url, "/webcommon/bookshelf/addbooks%?")
|
||||
Assert.eq(requests[1].body, "bookId=9")
|
||||
end
|
||||
|
||||
-- 进度上传带章节更新时间的 unix 秒。空时间不发请求,避免把阅读状态写坏。
|
||||
do
|
||||
local Stubs = require("support.stubs")
|
||||
cfg.cookie = "ywkey=k; _csrfToken=tok"
|
||||
requests, replies = {}, {}
|
||||
local ok, err
|
||||
Client.updateReadAsync("9", "11", "c1", false, "", function(v, e) ok, err = v, e end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(ok)
|
||||
Assert.eq(err, "起点章节时间缺失")
|
||||
Assert.len(requests, 0)
|
||||
|
||||
requests, replies = {}, { { body = '{"code":0}' } }
|
||||
Client.updateReadAsync("9", "11", "c1", true, 1665109375, function(v, e) ok, err = v, e end)
|
||||
Assert.is_true(ok)
|
||||
Assert.matches(requests[1].url, "/webcommon/chapter/updReadStatus%?")
|
||||
Assert.matches(requests[1].body, "chapterUpdateTime=1665109375")
|
||||
Assert.matches(requests[1].body, "isVip=1")
|
||||
Assert.matches(requests[1].body, "chapterId=11")
|
||||
|
||||
requests, replies, expired = {}, { { body = '{"code":1403,"msg":"登录失效"}' } }, nil
|
||||
Client.updateReadAsync("9", "11", "c1", 0, "1665109375", function(v, e) ok, err = v, e end)
|
||||
Assert.is_nil(ok)
|
||||
Assert.matches(err, "QQ阅读或起点 App 扫码")
|
||||
Assert.eq(expired, err)
|
||||
end
|
||||
|
||||
do
|
||||
requests, replies = {}, { { body = page({ records = { { bid = 7, bName = "甲", bAuth = "乙", cat = "玄幻" } } }) } }
|
||||
local got
|
||||
Client.rankAsync("/rank/yuepiao/catid21/", function(v) got = v end)
|
||||
Assert.matches(requests[1].url, "/rank/yuepiao/catid21/$")
|
||||
local books = Mapper.rank(got)
|
||||
Assert.eq(books[1].stable_id, "7")
|
||||
Assert.eq(books[1].authors, "乙")
|
||||
|
||||
replies = { { body = "<html>nope</html>" } }
|
||||
local err
|
||||
Client.rankAsync("/rank/x/", function(v, e) got, err = v, e end)
|
||||
Assert.is_nil(got)
|
||||
Assert.is_true(err ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
local books = Mapper.search({ bookInfo = { records = {
|
||||
{ bid = 7, bName = "甲", bAuth = "乙...", cat = "玄幻", desc = "简<br>介" },
|
||||
{ bid = 8, bName = "丙", bAuth = "丁" },
|
||||
} } })
|
||||
Assert.len(books, 2)
|
||||
Assert.eq(books[1].stable_id, "7")
|
||||
Assert.is_nil(books[1].authors)
|
||||
Assert.eq(books[1].intro, "简\n介")
|
||||
Assert.eq(books[2].authors, "丁")
|
||||
|
||||
requests, replies = {}, { { body = JSONStub.encode({ code = 0, data = { bookInfo = { records = {} } } }) } }
|
||||
local got
|
||||
Client.searchAsync("斗罗", function(v) got = v end)
|
||||
Assert.matches(requests[1].url, "/webcommon/search/list%?")
|
||||
Assert.matches(requests[1].url, "kw=%%E6%%96%%97%%E7%%BD%%97")
|
||||
Assert.is_true(got.bookInfo ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
requests, replies = {}, { { body = JSONStub.encode({ code = 0, data = { records = {}, isLast = 0 } }) } }
|
||||
local got
|
||||
Client.rankPageAsync("readindex", "21", 2, function(data) got = data end)
|
||||
Assert.matches(requests[1].url, "/webcommon/rank/readIndexlist%?")
|
||||
Assert.matches(requests[1].url, "pageNum=2")
|
||||
Assert.matches(requests[1].url, "catId=21")
|
||||
Assert.matches(requests[1].url, "gender=male")
|
||||
Assert.is_false((requests[1].opts.headers.Cookie or ""):find("ywguid", 1, true) ~= nil)
|
||||
Assert.len(got.records, 0)
|
||||
|
||||
replies = { { body = JSONStub.encode({ code = 0, data = {} }) } }
|
||||
local err
|
||||
Client.rankPageAsync("yuepiao", "-1", 1, function(data, reason) got, err = data, reason end)
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(err, "起点榜单响应无效")
|
||||
end
|
||||
|
||||
do
|
||||
requests, replies = {}, { { body = page({ bookCirclePost = {
|
||||
bookCirclePostCount = 8, bookCirclePostList = {},
|
||||
} }) } }
|
||||
local got, err
|
||||
Client.bookCircleAsync("7", function(data, reason) got, err = data, reason end)
|
||||
Assert.matches(requests[1].url, "/readersCircle/7/$")
|
||||
Assert.is_true(requests[1].opts.headers.Cookie == nil, "公共整书讨论不发送账号 Cookie")
|
||||
Assert.eq(got.bookCirclePostCount, 8)
|
||||
replies = { { body = page({}) } }
|
||||
Client.bookCircleAsync("7", function(data, reason) got, err = data, reason end)
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(err, "起点书友圈响应无效")
|
||||
end
|
||||
@@ -0,0 +1,35 @@
|
||||
--[[-- 起点旧榜单节点的聚合分页与失败。 @module tests.moonsource_qidian.rank_spec --]]
|
||||
local Assert = require("support.assert")
|
||||
local pages, fail = {}, false
|
||||
package.preload["moonsource_qidian.client"] = function()
|
||||
return {
|
||||
rankPageAsync = function(key, cat, page, cb)
|
||||
pages[#pages + 1] = { key = key, cat = cat, page = page }
|
||||
if fail and page == 2 then cb(nil, "offline")
|
||||
else
|
||||
local rows = {}
|
||||
for i = 1, 20 do rows[i] = { bid = (page - 1) * 20 + i, bName = "测试" .. i } end
|
||||
cb({ records = rows, isLast = 0 })
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
local source = require("moonsource_qidian.source").new()
|
||||
local result, err
|
||||
source:browseAsync({ node = "yuepiao:-1", limit = 60 }, function(value, reason) result, err = value, reason end)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(result.data, 60)
|
||||
Assert.eq(result.data[60].stable_id, "60")
|
||||
Assert.len(pages, 3)
|
||||
Assert.eq(pages[3].page, 3)
|
||||
Assert.eq(pages[1].cat, "-1")
|
||||
Assert.eq(result.groups[1].chips[1].title, "分类书库")
|
||||
|
||||
fail, pages = true, {}
|
||||
source:browseAsync({ node = "readindex:21", limit = 60 }, function(value, reason) result, err = value, reason end)
|
||||
Assert.is_nil(result, "后续页失败不能把榜单第一页报成完整结果")
|
||||
Assert.eq(err, "offline")
|
||||
Assert.len(pages, 2)
|
||||
Assert.eq(pages[1].key, "readindex")
|
||||
Assert.eq(pages[1].cat, "21")
|
||||
@@ -0,0 +1,129 @@
|
||||
--[[--
|
||||
起点段评:统计 → 热点、评论页 → 展示项(页码翻页)、段落按段序定位到章节 HTML。
|
||||
|
||||
@module tests.moonsource_qidian.reviews_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
local asked
|
||||
package.preload["moonsource_qidian.client"] = function()
|
||||
return {
|
||||
reviewSummaryAsync = function(book, chapter, cb)
|
||||
asked = { book = book, chapter = chapter }
|
||||
cb({ enableReview = package.enabled and 1 or 0, list = {
|
||||
{ paragraphId = -1, textCount = 99 },
|
||||
{ paragraphId = 3, textCount = 7 },
|
||||
{ paragraphId = 1, textCount = 4942 },
|
||||
{ paragraphId = 2, textCount = 0 },
|
||||
} })
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
reviewListAsync = function(book, chapter, pid, page, cb)
|
||||
asked = { book = book, chapter = chapter, pid = pid, page = page }
|
||||
cb({ total = 25, list = { { reviewId = "9", nickName = "甲", content = "好[fn=47]看", likeCount = 6,
|
||||
createTimestamp = 1725596312, hasImage = 1, imagePre = "https://x/y.jpg", status = 1 } } })
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["moonsource_qidian.reviews"] = nil
|
||||
local Reviews = require("moonsource_qidian.reviews")
|
||||
|
||||
-- 统计:保留章末总评,0 评论不标,按段序排;没开段评的书当没有
|
||||
do
|
||||
package.enabled = true
|
||||
local hot
|
||||
Reviews.hotspotsAsync("1", "2", function(list) hot = list end)
|
||||
Assert.eq(asked.chapter, "2")
|
||||
Assert.len(hot, 3)
|
||||
Assert.eq(hot[1].range, "-1")
|
||||
Assert.eq(hot[2].range, "1")
|
||||
Assert.eq(hot[3].range, "3")
|
||||
Assert.eq(hot[3].total, 7)
|
||||
|
||||
package.enabled = false
|
||||
Reviews.hotspotsAsync("1", "2", function(list) hot = list end)
|
||||
Assert.len(hot, 0)
|
||||
end
|
||||
|
||||
-- 评论页:max_idx 是已取页数,请求页码 = max_idx + 1;表情码去掉;配图带上
|
||||
do
|
||||
local page
|
||||
Reviews.pageAsync("1", "2", 3, 0, function(p) page = p end)
|
||||
Assert.eq(asked.page, 1)
|
||||
Assert.eq(asked.pid, 3)
|
||||
Assert.eq(page.max_idx, 1)
|
||||
Assert.eq(page.total, 25)
|
||||
Assert.is_true(page.more)
|
||||
Assert.eq(page.items[1].content, "好看")
|
||||
Assert.eq(page.items[1].author, "甲")
|
||||
Assert.eq(page.items[1].time, 1725596312)
|
||||
Assert.eq(page.items[1].images[1].url, "https://x/y.jpg")
|
||||
|
||||
Assert.is_false(Reviews.page({ total = 1, list = { { reviewId = "1", content = "a" } } }, 1).more)
|
||||
Assert.is_false(Reviews.page({ total = 5, list = {} }, 2).more)
|
||||
Assert.is_nil((Reviews.page({}, 1)))
|
||||
Assert.is_false(Reviews.page({ total = 25, isEnd = 1, list = { { reviewId = "1" } } }, 2).more)
|
||||
Assert.is_true(Reviews.page({ total = 25, isEnd = 0, list = { { reviewId = "1" } } }, 3).more,
|
||||
"不等长的页不能用页码乘本页条数猜末页")
|
||||
local primary = Reviews.item({ content = "原评", rootReviewReplyCount = 65,
|
||||
replyList = {
|
||||
{ reviewId = "r1", nickName = "乙", content = "回复[fn=3]", createTime = "1725596312000",
|
||||
quoteNickName = "丙", rootReviewReplyCount = 4,
|
||||
replyList = { { content = "不递归生成三级列表" } } },
|
||||
{ reviewId = "r2", nickName = "丁", content = "另一条", likeCount = 2 },
|
||||
} })
|
||||
Assert.eq(primary.content, "原评", "不能把内嵌的两条回复预览拼进主评论")
|
||||
Assert.eq(primary.replies, 65)
|
||||
Assert.len(primary.reply_preview, 2)
|
||||
Assert.eq(primary.reply_preview[1].id, "r1")
|
||||
Assert.eq(primary.reply_preview[1].content, "回复")
|
||||
Assert.eq(primary.reply_preview[1].author, "乙")
|
||||
Assert.eq(primary.reply_preview[1].reply_to, "丙")
|
||||
Assert.eq(primary.reply_preview[1].time, 1725596312)
|
||||
Assert.is_nil(primary.reply_preview[1].reply_preview, "二级预览不继续生成三级列表")
|
||||
Assert.eq(primary.reply_preview[2].likes, 2)
|
||||
Assert.is_nil(Reviews.item({ rootReviewReplyCount = 65, replyList = {} }).reply_preview)
|
||||
Assert.is_nil(Reviews.item({ rootReviewReplyCount = 65 }).reply_preview)
|
||||
Assert.eq(Reviews.item({ replyList = { { content = "已有回复" } } }).replies, 1,
|
||||
"未给总数时至少显示实际预览数")
|
||||
end
|
||||
|
||||
-- 定位:第 n 个非空 <p> 即 paragraphId = n,xpointer 覆盖整段
|
||||
do
|
||||
local html = '<h1>标题</h1><p>开头一段话。</p>\n<p>第二段里有一句被很多人评论的话。</p>'
|
||||
local spots = Reviews.locate({
|
||||
{ range = "2", text = "", total = 4 },
|
||||
{ range = "9", text = "", total = 1 },
|
||||
}, html)
|
||||
Assert.len(spots, 1)
|
||||
Assert.eq(spots[1].range, "2")
|
||||
Assert.eq(spots[1].badge, "4")
|
||||
Assert.eq(spots[1].text, "第二段里有一句被很多人评论的话。")
|
||||
end
|
||||
|
||||
do
|
||||
local page, err = Reviews.bookPage({
|
||||
bookCirclePostCount = 9, bookCirclePostList = {
|
||||
{ title = "帖子标题", circleReviewDesc = "<p>正文 & 预览</p>", userName = "测试作者" },
|
||||
},
|
||||
})
|
||||
Assert.is_nil(err)
|
||||
Assert.len(page.items, 1)
|
||||
Assert.eq(page.items[1].text, "帖子标题\n正文 & 预览")
|
||||
Assert.eq(page.items[1].author, "测试作者")
|
||||
Assert.eq(page.total, 9)
|
||||
Assert.eq(page.title, "书友圈预览(1/9)")
|
||||
Assert.is_nil(page.pages, "不捏造官网未提供的整书帖子分页")
|
||||
page, err = Reviews.bookPage({ bookCirclePostCount = 0, bookCirclePostList = {} })
|
||||
Assert.is_nil(err)
|
||||
Assert.len(page.items, 0)
|
||||
page, err = Reviews.bookPage({ bookCirclePostCount = 9,
|
||||
bookCirclePostList = { { title = "坏帖" } } })
|
||||
Assert.is_nil(page)
|
||||
Assert.eq(err, "起点书友圈响应无效")
|
||||
end
|
||||
|
||||
return true
|
||||
@@ -0,0 +1,95 @@
|
||||
--[[-- 起点账号:续期不动同步标记;换号保留记录,不询问、不查询旧账号。 @module tests.moonsource_qidian.setting_spec --]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
local Assert = require("support.assert")
|
||||
local Theme = require("support.theme_stubs")
|
||||
Theme.install()
|
||||
local Auth = require("source.auth")
|
||||
local beginLogin = Auth.beginLogin
|
||||
local cfg, checks, cleared, closed = {}, 0, 0, 0
|
||||
local clear_ok, delayed, late = true, false, nil
|
||||
package.preload["utils.settings"] = function()
|
||||
return { getSource = function() return cfg end, saveSource = function() end }
|
||||
end
|
||||
package.preload["moonsource_qidian.client"] = function()
|
||||
return {
|
||||
cookie = function() return cfg.cookie end,
|
||||
loginCheckAsync = function(cookie, cb)
|
||||
checks = checks + 1
|
||||
Assert.is_true(cookie ~= "old", "换号不能查询旧凭据")
|
||||
local function done()
|
||||
cb(cookie ~= "bad", cookie == "bad" and "expired" or nil,
|
||||
{ id = cookie == "same" and "111" or "222" })
|
||||
end
|
||||
if delayed then late = done else done() end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["source.auth"] = nil
|
||||
package.preload["source.auth"] = function()
|
||||
return { beginLogin = beginLogin, changeAccount = Auth.changeAccount,
|
||||
ok = function() end, expired = function() return false end }
|
||||
end
|
||||
package.preload["source.registry"] = function()
|
||||
return { reload = function() end, invalidate = function() end,
|
||||
resolve = function() return { capabilities = function() return { shelf_add = true } end } end }
|
||||
end
|
||||
package.preload["book.books_db"] = function()
|
||||
return { prepareAccountSync = function(id, shelf_add)
|
||||
Assert.eq(id, "ext.qidian", "只准备当前源")
|
||||
Assert.is_true(shelf_add)
|
||||
Assert.not_nil(cfg.cookie, "成功准备同步之后才替换凭据")
|
||||
cleared = cleared + 1
|
||||
return clear_ok
|
||||
end }
|
||||
end
|
||||
package.preload["reader.session"] = function()
|
||||
return { current = function() return {
|
||||
identity = { source_id = "ext.qidian" }, ui = { onClose = function() closed = closed + 1 end },
|
||||
} end }
|
||||
end
|
||||
local CookieLogin = require("source.cookie_login")
|
||||
CookieLogin.fromPayload = function(payload) return payload.cookie end
|
||||
local Setting = require("moonsource_qidian.setting")
|
||||
local function apply(cookie)
|
||||
local ok, err
|
||||
local job = Setting.browser.apply({ cookie = cookie }, function(value, reason) ok, err = value, reason end)
|
||||
return ok, err, job
|
||||
end
|
||||
|
||||
cfg = { cookie = "old", account_id = "111" }
|
||||
Assert.is_true(apply("same"))
|
||||
Assert.eq(cleared, 0, "同账号续期保留本地")
|
||||
cfg = { cookie = "old", account_id = "111" }
|
||||
Assert.is_true(apply("new"))
|
||||
Assert.eq(cfg.cookie, "new")
|
||||
Assert.eq(cfg.account_id, "222")
|
||||
Assert.eq(cleared, 1)
|
||||
Assert.eq(closed, 1)
|
||||
Assert.is_nil(Theme.last("confirm"), "换号不弹确认")
|
||||
cfg = { cookie = "old" }
|
||||
local before = checks
|
||||
Assert.is_true(apply("same"))
|
||||
Assert.eq(checks, before + 1, "旧配置缺身份时不多查一次")
|
||||
Assert.eq(cleared, 2)
|
||||
cfg = { cookie = "new", account_id = "111" }
|
||||
Assert.is_true(apply("new"))
|
||||
Assert.eq(cleared, 3, "账号身份变了,即使 Cookie 字符串相同也准备同步")
|
||||
cfg, clear_ok = { cookie = "old", account_id = "111" }, false
|
||||
local ok, err = apply("new")
|
||||
Assert.is_false(ok)
|
||||
Assert.eq(err, "准备本地同步失败")
|
||||
Assert.eq(cfg.cookie, "old", "准备失败仍保留旧凭据")
|
||||
clear_ok = true
|
||||
cfg = { cookie = "old", account_id = "111" }
|
||||
ok, err = apply("bad")
|
||||
Assert.is_false(ok)
|
||||
Assert.eq(err, "expired")
|
||||
Assert.eq(cfg.cookie, "old", "无效新凭据不清旧账号")
|
||||
delayed = true
|
||||
local called = false
|
||||
local job = Setting.browser.apply({ cookie = "same" }, function() called = true end)
|
||||
job.cancel()
|
||||
late()
|
||||
Assert.is_false(called, "取消后的校验回包不提交")
|
||||
Assert.eq(cfg.cookie, "old")
|
||||
@@ -0,0 +1,96 @@
|
||||
--[[--
|
||||
起点书架分组:拉书架时记住自定义分组(默认分组 -100 不算,一本书多个组取第一个),
|
||||
开「分组代替分类」时进组书的分类用分组名、没进组不写分类;移出分组后本地旧行也要落回题材。
|
||||
|
||||
@module tests.moonsource_qidian.shelf_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
package.loaded["json"] = nil
|
||||
package.preload["json"] = function()
|
||||
local stub = require("support.json_stub")
|
||||
return { decode = stub.decode, encode = stub.encode }
|
||||
end
|
||||
package.preload["moonsource_qidian.fock"] = function() return {} end
|
||||
|
||||
local PAGES = {
|
||||
["-100"] = '{"code":0,"data":{"count":3,"page":{"isLast":1},'
|
||||
.. '"groups":[{"groupId":-100,"groupName":"默认分组","bookCount":3},'
|
||||
.. '{"groupId":7,"groupName":"追更","bookCount":2}],'
|
||||
.. '"list":[{"bid":1,"bName":"甲","cateName":"玄幻"},{"bid":2,"bName":"乙","cateName":"都市"}]}}',
|
||||
["7"] = '{"code":0,"data":{"count":2,"page":{"isLast":1},'
|
||||
.. '"groups":[{"groupId":7,"groupName":"追更","bookCount":2}],'
|
||||
.. '"list":[{"bid":2,"bName":"乙","cateName":"都市"},{"bid":3,"bName":"丙","cateName":"科幻"}]}}',
|
||||
}
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, _opts, cb)
|
||||
local gid = url:match("gid=([^&]+)")
|
||||
cb(PAGES[gid] or PAGES["-100"])
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
local cfg = { category_as_group = true }
|
||||
package.loaded["utils.settings"] = nil
|
||||
package.preload["utils.settings"] = function()
|
||||
return { getSource = function() return cfg end }
|
||||
end
|
||||
package.loaded["moonsource_qidian.client"] = nil
|
||||
package.loaded["moonsource_qidian.mapper"] = nil
|
||||
local Client = require("moonsource_qidian.client")
|
||||
local Mapper = require("moonsource_qidian.mapper")
|
||||
|
||||
do -- 逐组拉取后按 bookId 记组:乙在默认组先出现,进了「追更」仍要记上
|
||||
local rows
|
||||
Client.shelfAsync("_csrfToken=tok; other=1", function(r, err)
|
||||
rows = r
|
||||
Assert.is_nil(err)
|
||||
end)
|
||||
Assert.len(rows, 3)
|
||||
Assert.is_nil(rows[1]._group_name, "只在默认组的书不算分组")
|
||||
Assert.eq(rows[2]._group_name, "追更")
|
||||
Assert.eq(rows[3]._group_name, "追更")
|
||||
|
||||
local books = Mapper.shelfList(rows)
|
||||
Assert.is_nil(books[1].category, "开:没进组不写题材")
|
||||
Assert.eq(books[2].category, "追更")
|
||||
Assert.eq(books[3].category, "追更")
|
||||
end
|
||||
|
||||
do -- 移出分组:本地旧行分类是旧分组名,书架行题材要把它刷新回来
|
||||
local books = Mapper.shelfList({
|
||||
{ bid = 9, bName = "丁", cateName = "历史",
|
||||
local_book = { stable_id = "9", title = "丁", category = "追更", cover = "c" } },
|
||||
{ bid = 10, bName = "戊", cateName = "游戏", _group_name = "在读",
|
||||
local_book = { stable_id = "10", title = "戊", category = "历史", cover = "c" } },
|
||||
})
|
||||
Assert.is_nil(books[1].category, "开:移出分组后不再沿用旧分组名")
|
||||
Assert.is_true(books[1].category_authoritative, "移出分组要能清掉库里的旧分类")
|
||||
Assert.eq(books[2].category, "在读", "进了组用分组名覆盖本地旧分类")
|
||||
end
|
||||
|
||||
do -- 分页没有页数上限:超过 50 页照样翻到末页
|
||||
local n = 0
|
||||
local list = {}
|
||||
for i = 1, 20 do list[#list + 1] = ('{"bid":%d,"bName":"书","cateName":"玄幻"}'):format(i) end
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return { get = function(_url, _opts, cb)
|
||||
n = n + 1
|
||||
cb('{"code":0,"data":{"count":9999,"page":{"isLast":' .. (n > 60 and "1" or "0")
|
||||
.. '},"groups":[],"list":[' .. table.concat(list, ",") .. "]}}")
|
||||
return { cancel = function() end }
|
||||
end }
|
||||
end
|
||||
package.loaded["moonsource_qidian.client"] = nil
|
||||
local Deep = require("moonsource_qidian.client")
|
||||
local rows, err
|
||||
Deep.shelfAsync("_csrfToken=tok", function(r, e) rows, err = r, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(rows, 20)
|
||||
Assert.eq(n, 61)
|
||||
end
|
||||
@@ -0,0 +1,69 @@
|
||||
--[[-- 起点验证码桥:仅 proof、时效、取消和候选会话存活。 @module tests.moonsource_qidian.verify_spec --]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Ext = require("utils.extension")
|
||||
local seq, interrupted = 0, 0
|
||||
package.preload["utils.random"] = function() return { hex = function() seq = seq + 1; return "ticket" .. seq end } end
|
||||
package.preload["ui/uimanager"] = function() return { scheduleIn = function() end, unschedule = function() end } end
|
||||
package.preload["ui.guard"] = function() return { wrap = function(_label, fn) return fn end } end
|
||||
Ext.add("web.open_page", function(path, _title, _text, opts)
|
||||
Assert.matches(path, "^/qidian_verify%.html#ticket")
|
||||
return { close = function() opts.close_callback() end }
|
||||
end)
|
||||
local Verification = require("moonsource_qidian.verify")
|
||||
local route
|
||||
for _idx, item in ipairs(Ext.list("web.routes")) do if item.name == "qidian_verify" then route = item end end
|
||||
local session = {
|
||||
interrupt = function() interrupted = interrupted + 1 end,
|
||||
imageAsync = function(_self, _url, cb) cb("data:image/png;base64,example") end,
|
||||
}
|
||||
local challenge = { nextAction = 11, imgSrc = "https://turing.captcha.qcloud.com/TCaptcha.js?aid=1600000770" }
|
||||
local submitted, finished, late = nil, false, nil
|
||||
local verification = Verification.new(session, challenge, function(proof, cb)
|
||||
submitted, late = proof, cb
|
||||
end, function(data) finished = data ~= nil end)
|
||||
local function request(action, fields, method)
|
||||
fields = fields or {}
|
||||
fields.ticket = fields.ticket or verification.ticket
|
||||
local status, data, headers
|
||||
route.handle(method or "POST", action, fields, function(code, body, extra) status, data, headers = code, body, extra end)
|
||||
return status, data, headers
|
||||
end
|
||||
|
||||
Assert.eq((request("config", nil, "GET")), 405)
|
||||
local status, data, headers = request("config")
|
||||
Assert.eq(status, 200)
|
||||
Assert.eq(data.appid, "1600000770")
|
||||
Assert.eq(headers[1], "Cache-Control: no-store")
|
||||
Assert.is_nil(data.phone)
|
||||
Assert.is_nil(data.cookie)
|
||||
Assert.eq((request("verify", { captcha_ticket = "trerror_invalid", randstr = "random" })), 400)
|
||||
Assert.is_nil(submitted)
|
||||
request("verify", { captcha_ticket = "proof", randstr = "random" })
|
||||
Assert.eq(submitted, "random;proof", "顺序与官方 randstr + 分号 + ticket 一致")
|
||||
Assert.eq((request("verify", { captcha_ticket = "proof", randstr = "random" })), 409)
|
||||
late({ nextAction = 0 })
|
||||
Assert.is_true(finished)
|
||||
Assert.eq(interrupted, 0, "成功后候选会话必须继续用于短信提交")
|
||||
Assert.eq((request("config")), 403, "验证票据用完即撤销")
|
||||
|
||||
verification = Verification.new(session, challenge, function(_proof, cb) late = cb end, function() end)
|
||||
request("verify", { captcha_ticket = "proof", randstr = "random" })
|
||||
verification:cancel()
|
||||
late({ nextAction = 0 })
|
||||
Assert.eq(interrupted, 1)
|
||||
Assert.eq((request("config")), 403)
|
||||
|
||||
verification = Verification.new(session, { nextAction = 8, imgSrc = "/image" },
|
||||
function(proof, cb) Assert.eq(proof, "abcd"); cb({ nextAction = 0 }) end, function() end)
|
||||
status, data = request("config")
|
||||
Assert.eq(status, 200)
|
||||
Assert.eq(data.mode, "image")
|
||||
Assert.matches(data.image, "^data:image/png;")
|
||||
Assert.eq((request("verify", { code = "abcd" })), 200)
|
||||
|
||||
verification = Verification.new(session, challenge, function() end, function() end)
|
||||
verification.expires = os.time() - 1
|
||||
Assert.eq((request("verify", { captcha_ticket = "proof", randstr = "random" })), 403)
|
||||
verification:cancel()
|
||||
@@ -0,0 +1,69 @@
|
||||
'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-qidian.koplugin/moonsource_qidian/web/qidian_verify.js', 'utf8');
|
||||
|
||||
async function page(options = {}) {
|
||||
const nodes = Object.fromEntries(['title', 'instruction', 'status', 'retry', 'captcha', 'image-form', 'image', 'code', 'submit']
|
||||
.map(id => [id, { textContent: '', hidden: false, value: '' }]));
|
||||
const requests = [];
|
||||
let callback;
|
||||
const messages = { mode: options.image ? 'image' : 'tencent', image: 'data:image/png;base64,fixture',
|
||||
appid: '1600000770', title: 'Qidian', instruction: 'Verify', pending: 'Pending',
|
||||
success: 'Done', failure: 'Failed', retry: 'Refresh', submit: 'Submit' };
|
||||
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() {} }),
|
||||
head: { appendChild(script) {
|
||||
context.window.TencentCaptcha = function(element, appid, cb, opts) {
|
||||
assert.equal(element, nodes.captcha);
|
||||
assert.equal(appid, '1600000770');
|
||||
assert.equal(opts.type, 'embed');
|
||||
callback = cb;
|
||||
this.destroy = this.show = () => {};
|
||||
if (options.auto) cb({ ret: 0, ticket: 'proof', randstr: 'random' });
|
||||
};
|
||||
script.onload();
|
||||
} },
|
||||
},
|
||||
fetch: async (url, opts) => {
|
||||
requests.push({ url, body: JSON.parse(opts.body) });
|
||||
const config = !url.endsWith('/verify');
|
||||
return { ok: config || !options.rejected, json: async () =>
|
||||
config ? messages : options.rejected ? { error: 'Rejected' } : { ok: true } };
|
||||
},
|
||||
};
|
||||
await vm.runInNewContext(source, context);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
return { nodes, requests, get callback() { return callback; } };
|
||||
}
|
||||
|
||||
(async () => {
|
||||
let p = await page();
|
||||
await p.callback({ ret: 2 });
|
||||
await p.callback({ ret: 0, ticket: 'trerror_fixture', randstr: 'random' });
|
||||
await p.callback({ ret: 0, ticket: 'proof', randstr: 'random', errorCode: 1 });
|
||||
assert.equal(p.requests.length, 1, 'Invalid challenges never submit proof');
|
||||
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');
|
||||
await p.callback({ ret: 0, ticket: 'late', randstr: 'random' });
|
||||
assert.equal(p.requests.length, 2, 'Completed proof cannot be replayed');
|
||||
p = await page({ auto: true });
|
||||
assert.equal(p.requests.length, 2, 'Synchronous SDK completion is not lost while loading');
|
||||
p = await page({ rejected: true });
|
||||
await p.callback({ ret: 0, ticket: 'proof', randstr: 'random' });
|
||||
assert.equal(p.nodes.status.textContent, 'Rejected');
|
||||
await p.nodes.retry.onclick();
|
||||
assert.equal(p.requests[2].url, '/api/qidian_verify/refresh');
|
||||
p = await page({ image: true });
|
||||
assert.equal(p.nodes.image.src, 'data:image/png;base64,fixture');
|
||||
p.nodes.code.value = 'abcd';
|
||||
await p.nodes['image-form'].onsubmit({ preventDefault() {} });
|
||||
assert.deepEqual(p.requests[1].body, { ticket: 'fixture', code: 'abcd' });
|
||||
console.log('qidian web: OK');
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,8 @@
|
||||
--[[-- 起点验证码网页回归,使用已有 Node。 @module tests.moonsource_qidian.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("qidian web: OK", 1, true) ~= nil, output)
|
||||
@@ -0,0 +1,102 @@
|
||||
--[[--
|
||||
阅文三源的设备扫码入口:各用自己的应用参数,先校验再保存。
|
||||
起点真 csrf 由 loginCheck 合并书架 Set-Cookie,扫码回调不再造假。
|
||||
|
||||
@module tests.moonsource_qidian.yuewen_qr_setting_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local beginLogin = require("source.auth").beginLogin
|
||||
local Themed = require("support.theme_stubs")
|
||||
Themed.install()
|
||||
package.preload["ui.themes.widgets.row"] = function()
|
||||
return { widget = function(spec) return spec end }
|
||||
end
|
||||
package.preload["ui/network/manager"] = function()
|
||||
return { runWhenConnected = function(_self, fn) fn() end }
|
||||
end
|
||||
package.preload["source.review_setting"] = function()
|
||||
return { row = function() return function() return {} end end }
|
||||
end
|
||||
package.preload["source.category_setting"] = package.preload["source.review_setting"]
|
||||
local configs, saved_id, authorized, reloads = {}, nil, nil, 0
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function(id) configs[id] = configs[id] or {}; return configs[id] end,
|
||||
saveSource = function(id) saved_id = id end,
|
||||
}
|
||||
end
|
||||
package.loaded["source.auth"] = nil
|
||||
package.preload["source.auth"] = function()
|
||||
return { beginLogin = beginLogin, ok = function(id) authorized = id end, expired = function() return false end }
|
||||
end
|
||||
package.preload["source.registry"] = function()
|
||||
return { reload = function() reloads = reloads + 1 end }
|
||||
end
|
||||
local options, on_cookie, started, checked, reject
|
||||
for _idx, name in ipairs({ "qqreader", "qidian", "xiaoxiang" }) do
|
||||
package.preload["moonsource_" .. name .. ".yuewen_qr"] = function()
|
||||
return { new = function(_self, spec, cb)
|
||||
options, on_cookie = spec, cb
|
||||
return { start = function() started = true end }
|
||||
end }
|
||||
end
|
||||
end
|
||||
for _idx, name in ipairs({ "qqreader", "qidian", "xiaoxiang" }) do
|
||||
local id = "ext." .. name
|
||||
package.preload["moonsource_" .. name .. ".client"] = function()
|
||||
return {
|
||||
cookie = function() return configs[id] and configs[id].cookie end,
|
||||
loginCheckAsync = function(cookie, cb)
|
||||
checked = cookie
|
||||
cb(not reject, reject and "rejected" or nil, { id = "123" })
|
||||
end,
|
||||
userAsync = function(cookie, cb)
|
||||
checked = cookie
|
||||
cb(not reject and { id = "123" } or nil, reject and "rejected" or nil)
|
||||
end,
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
for _idx, source in ipairs({
|
||||
{ id = "ext.qqreader", app_id = "1450000220", area_id = "1" },
|
||||
{ id = "ext.qidian", app_id = "13", area_id = "31" },
|
||||
{ id = "ext.xiaoxiang", app_id = "57", area_id = "5" },
|
||||
}) do
|
||||
local Setting = require("moonsource_" .. source.id:sub(5) .. ".setting")
|
||||
started, checked, saved_id, authorized = nil, nil, nil, nil
|
||||
local rows = Setting.rows()
|
||||
rows[1](400).callback()
|
||||
Assert.is_true(started, "账号行直接启动设备扫码")
|
||||
Assert.eq(options.app_id, source.app_id)
|
||||
Assert.eq(options.area_id, source.area_id)
|
||||
Assert.is_nil(saved_id, "仅获取二维码不能保存登录态")
|
||||
reject = true
|
||||
on_cookie("ywguid=guid; ywkey=bad")
|
||||
Assert.is_nil(saved_id, "各源的账号校验失败时不保存")
|
||||
Assert.is_nil(authorized)
|
||||
Assert.eq(Themed.last("toast").text, "rejected")
|
||||
Assert.is_true(Themed.last("progress_dialog").closed)
|
||||
reject = false
|
||||
on_cookie("ywguid=guid; ywkey=key")
|
||||
Assert.eq(saved_id, source.id)
|
||||
Assert.eq(authorized, source.id)
|
||||
Assert.eq(configs[source.id].cookie, checked)
|
||||
Assert.eq(checked, "ywguid=guid; ywkey=key")
|
||||
Assert.eq(Themed.last("toast").text, "登录成功")
|
||||
started = nil
|
||||
Setting.login()
|
||||
Assert.is_true(started, "登录失效的直达入口也走设备扫码")
|
||||
if source.id ~= "ext.qqreader" then
|
||||
local paste
|
||||
for _idx, factory in ipairs(Setting.rows()) do
|
||||
local row = factory(400)
|
||||
if row.title == "粘贴 Cookie" then paste = row; break end
|
||||
end
|
||||
Assert.not_nil(paste)
|
||||
paste.callback()
|
||||
Assert.eq(Themed.last("input").title, source.id == "ext.qidian" and "起点登录 Cookie" or "潇湘登录 Cookie")
|
||||
end
|
||||
end
|
||||
Assert.eq(reloads, 3)
|
||||
@@ -0,0 +1,335 @@
|
||||
--[[--
|
||||
moonsource_qidian.yuewen_qr:取码 → 轮询 → ywguid/ywkey 或跟跳 Set-Cookie。
|
||||
过期、关窗、手机取消刷新不把迟到的登录态交给 on_cookie。
|
||||
浏览器扩展绑定仍指向 book.qq.com。
|
||||
@module tests.moonsource_qidian.yuewen_qr_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Stubs = require("support.stubs")
|
||||
|
||||
package.preload["json"] = function()
|
||||
return { decode = require("support.json_stub").decode, encode = function() return "{}" end }
|
||||
end
|
||||
|
||||
package.preload["http.timeout"] = function()
|
||||
return { net = function() return 15 end }
|
||||
end
|
||||
|
||||
local script, requested = {}, {}
|
||||
local function respond(prefix, res) script[#script + 1] = { prefix = prefix, res = res } end
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
request = function(opts, cb)
|
||||
requested[#requested + 1] = opts
|
||||
for i, item in ipairs(script) do
|
||||
if opts.url:sub(1, #item.prefix) == item.prefix then
|
||||
table.remove(script, i)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
if item.res.hook then item.res.hook() end
|
||||
cb(item.res)
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
end
|
||||
require("ui/uimanager"):nextTick(function() cb(nil, "no script") end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
header = function(res, name) return res and res.headers and res.headers[name] end,
|
||||
headerAll = function(res, name)
|
||||
local value = res and res.headers and res.headers[name]
|
||||
return type(value) == "table" and value or (value and { value } or {})
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
local shown = {}
|
||||
local function widget(kind)
|
||||
return function()
|
||||
return { new = function(_, o)
|
||||
o.kind = kind
|
||||
function o:show() shown[#shown + 1] = self end
|
||||
function o:close()
|
||||
self.closed = true
|
||||
if self.close_callback then self.close_callback() end
|
||||
end
|
||||
return o
|
||||
end }
|
||||
end
|
||||
end
|
||||
package.preload["ui.themes.widgets.qr"] = widget("qr")
|
||||
package.preload["ui.themes.widgets.confirm"] = widget("confirm")
|
||||
package.preload["ui.themes.widgets.toast"] = widget("toast")
|
||||
package.preload["ui.themes.widgets.progress_dialog"] = widget("busy")
|
||||
|
||||
local QRLogin = require("moonsource_qidian.yuewen_qr")
|
||||
local SPEC = {
|
||||
app_id = "1450000220", area_id = "1", return_url = "https://book.qq.com/",
|
||||
referer = "https://login.book.qq.com/login.html",
|
||||
title = "QQ阅读扫码登录", caption = "用 QQ阅读或起点 App 扫一扫",
|
||||
}
|
||||
|
||||
local QR_PREFIX = "https://ptlogin.yuewen.com/login/qrcode?"
|
||||
local POLL_PREFIX = "https://ptlogin.yuewen.com/login/qrcodelogin?"
|
||||
|
||||
local function reset()
|
||||
script, requested, shown = {}, {}, {}
|
||||
end
|
||||
|
||||
local function find(kind)
|
||||
for i = #shown, 1, -1 do if shown[i].kind == kind then return shown[i] end end
|
||||
end
|
||||
|
||||
local function toastCount(text)
|
||||
local n = 0
|
||||
for i = 1, #shown do
|
||||
if shown[i].kind == "toast" and shown[i].text == text then n = n + 1 end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
local function qrcode(session)
|
||||
return { code = 200, body = '{"code":0,"data":{"sessionKey":"' .. session .. '"}}' }
|
||||
end
|
||||
|
||||
local function poll(body, extra)
|
||||
local res = { code = 200, body = body }
|
||||
if extra then
|
||||
for k, v in pairs(extra) do res[k] = v end
|
||||
end
|
||||
return res
|
||||
end
|
||||
|
||||
do -- 扫码 URL 与官方同一组参数,顺序由 formEncode 排定
|
||||
Assert.eq(QRLogin:new(SPEC, function() end):scanUrl("sk/1"),
|
||||
"https://ptlogin.yuewen.com/mobile/scanlogin?appid=1450000220&areaid=1"
|
||||
.. "&bookId=0&chapterId=0&sessionkey=sk%2F1")
|
||||
end
|
||||
|
||||
do -- 等待是字符串 "0",成功后 JSON 里的 ywGuid/ywKey 排成 Cookie
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":-11019,"scanStatus":"0"}'))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","data":{"ywGuid":"g1","ywKey":"k1","ywOpenId":"o1"}}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(find("qr").text,
|
||||
"https://ptlogin.yuewen.com/mobile/scanlogin?appid=1450000220&areaid=1"
|
||||
.. "&bookId=0&chapterId=0&sessionkey=sk1")
|
||||
Assert.eq(find("qr").caption, "用 QQ阅读或起点 App 扫一扫")
|
||||
Assert.eq(got, "ywguid=g1; ywkey=k1; ywopenid=o1")
|
||||
Assert.is_true(find("qr").closed)
|
||||
Assert.eq(toastCount("已取消登录"), 0)
|
||||
Assert.is_true(requested[1].allow_redirects == false)
|
||||
Assert.is_true(requested[2].url:find("qrcode=sk1", 1, true) ~= nil)
|
||||
Assert.len(script, 0)
|
||||
end
|
||||
|
||||
do -- 数字 GUID 要完整十进制;LuaJIT tostring 的科学计数法会毁掉 Fock 身份
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("long-guid"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":5,"data":{"ywGuid":1234567890123456,"ywKey":"key"}}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=1234567890123456; ywkey=key")
|
||||
end
|
||||
|
||||
do -- 已扫码只提示一次,确认后仍把登录态交出去
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"1"}'))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":1}'))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","ywGuid":"g2","ywKey":"k2"}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=g2; ywkey=k2")
|
||||
Assert.eq(toastCount("已扫码,请在手机上确认"), 1)
|
||||
end
|
||||
|
||||
do -- 过期:重试框,不交登录态
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"4"}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(find("confirm").text, "二维码已过期")
|
||||
Assert.eq(find("confirm").ok_text, "重新获取")
|
||||
Assert.eq(#requested, 2)
|
||||
end
|
||||
|
||||
do -- 用户关掉二维码:迟到的成功不交登录态,也不再轮询
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","data":{"ywGuid":"late","ywKey":"no"}}', {
|
||||
hook = function() find("qr"):close() end,
|
||||
}))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(#requested, 2, "关闭后不再轮询")
|
||||
Assert.eq(toastCount("已取消登录"), 1)
|
||||
end
|
||||
|
||||
do -- 只有 302url:跟跳收 Set-Cookie,相对 Location 拼回原 host;属性不当 cookie
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","data":{"302url":"https://ptlogin.yuewen.com/jump"}}'))
|
||||
respond("https://ptlogin.yuewen.com/jump", {
|
||||
code = 302, headers = { Location = "/done", ["Set-Cookie"] = "ywguid=g3; Path=/; HttpOnly" },
|
||||
})
|
||||
respond("https://ptlogin.yuewen.com/done", {
|
||||
code = 200, headers = { ["Set-Cookie"] = "ywkey=k3; Path=/, ywopenid=o3; Secure" },
|
||||
})
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=g3; ywkey=k3; ywopenid=o3")
|
||||
Assert.is_nil(got and got:find("Path", 1, true))
|
||||
Assert.len(script, 0)
|
||||
end
|
||||
|
||||
do -- 非 https 跳转不跟,不交登录态
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","data":{"302url":"http://evil.example/x"}}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(find("confirm").text, "登录失败:未获取到登录态")
|
||||
Assert.eq(#requested, 2)
|
||||
end
|
||||
|
||||
do -- 已拿到临时凭据仍须走 302url,不能把跨站身份当本站会话保存
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("exchange"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":5,"data":{"ywGuid":"temporary","ywKey":"old",'
|
||||
.. '"302url":"https://ptlogin.yuewen.com/exchange"}}'))
|
||||
respond("https://ptlogin.yuewen.com/exchange", {
|
||||
code = 302, headers = { Location = "https://m.qidian.com/finish",
|
||||
["Set-Cookie"] = { "ywguid=intermediate; Path=/", "ywkey=intermediate; Path=/" } },
|
||||
})
|
||||
respond("https://m.qidian.com/finish", {
|
||||
code = 200, headers = { ["Set-Cookie"] = { "ywguid=321; Path=/", "ywkey=web; Path=/" } },
|
||||
})
|
||||
local spec = { app_id = "13", area_id = "31", return_url = "https://m.qidian.com/", ticket = "1" }
|
||||
local got
|
||||
QRLogin:new(spec, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=321; ywkey=web")
|
||||
Assert.len(requested, 4)
|
||||
Assert.is_nil(requested[3].headers.Cookie, "第三方扫码域不带书源 Cookie")
|
||||
Assert.matches(requested[1].url, "ticket=1")
|
||||
end
|
||||
|
||||
do -- 官网 ticket 路径必须兑换,本站回包替换扫码 JSON 中的身份
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("ticket"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":5,"data":{"ticket":"one-use","ywGuid":"temporary","ywKey":"old"}}'))
|
||||
respond("https://m.qidian.com/?ticket=", {
|
||||
code = 200, headers = { ["Set-Cookie"] = { "ywguid=456; Path=/", "ywkey=web; Path=/" } },
|
||||
})
|
||||
local spec = { app_id = "13", area_id = "31", return_url = "https://m.qidian.com/", ticket = "1" }
|
||||
local got
|
||||
QRLogin:new(spec, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=456; ywkey=web")
|
||||
Assert.len(requested, 3)
|
||||
end
|
||||
|
||||
do -- ticket=1 时忽略裸 302url,强制带 ticket 兑换;否则会吃到空壳首页却「登录成功」
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("bare-home"))
|
||||
respond(POLL_PREFIX, poll(
|
||||
'{"code":0,"scanStatus":5,"data":{"ticket":"t1","ywGuid":"temporary","ywKey":"old",'
|
||||
.. '"302url":"https://m.qidian.com/"}}'))
|
||||
respond("https://m.qidian.com/?ticket=", {
|
||||
code = 200, headers = { ["Set-Cookie"] = { "ywguid=789; Path=/", "ywkey=web; Path=/" } },
|
||||
})
|
||||
local spec = { app_id = "13", area_id = "31", return_url = "https://m.qidian.com/", ticket = "1" }
|
||||
local got
|
||||
QRLogin:new(spec, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=789; ywkey=web")
|
||||
Assert.matches(requested[3].url, "ticket=t1")
|
||||
Assert.is_nil(requested[3].url:match("^https://m%.qidian%.com/?$"))
|
||||
end
|
||||
|
||||
do -- 本站常常不 Set-Cookie ywkey(只有 abPolicies);ticket 落到本站且 JSON 身份齐全就算完成
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("no-set-cookie"))
|
||||
respond(POLL_PREFIX, poll(
|
||||
'{"code":0,"scanStatus":5,"data":{"ticket":"t2","ywGuid":"temporary","ywKey":"old"}}'))
|
||||
respond("https://m.qidian.com/?ticket=", {
|
||||
code = 200, body = "<html>shell</html>",
|
||||
headers = { ["Set-Cookie"] = "abPolicies=%7B%7D; Path=/" },
|
||||
})
|
||||
local spec = { app_id = "13", area_id = "31", return_url = "https://m.qidian.com/", ticket = "1" }
|
||||
local got
|
||||
QRLogin:new(spec, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=temporary; ywkey=old")
|
||||
end
|
||||
|
||||
do -- 即使临时凭据完整,也不跟陌生 HTTPS 地址
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("foreign"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":5,"data":{"ywGuid":"g","ywKey":"k",'
|
||||
.. '"302url":"https://qidian.com.evil.example/steal"}}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.is_nil(got)
|
||||
Assert.len(requested, 2)
|
||||
end
|
||||
|
||||
do -- 手机取消:关掉旧码不提示已取消,再要一张新码
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("old"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"3"}'))
|
||||
respond(QR_PREFIX, qrcode("new"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","data":{"ywGuid":"g4","ywKey":"k4"}}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=g4; ywkey=k4")
|
||||
Assert.eq(toastCount("已取消登录"), 0)
|
||||
Assert.eq(requested[1].url:sub(1, #QR_PREFIX), QR_PREFIX)
|
||||
Assert.eq(requested[3].url:sub(1, #QR_PREFIX), QR_PREFIX)
|
||||
Assert.is_true(requested[4].url:find("qrcode=new", 1, true) ~= nil)
|
||||
Assert.len(script, 0)
|
||||
end
|
||||
|
||||
for _idx, spec in ipairs({
|
||||
{ app_id = "13", area_id = "31", return_url = "https://m.qidian.com/",
|
||||
referer = "https://passport.qidian.com/mobile/login", title = "起点扫码登录", caption = SPEC.caption },
|
||||
{ app_id = "57", area_id = "5", return_url = "https://www.xxsypro.com/",
|
||||
referer = "https://passport.yuewen.com/yuewen.html", title = "潇湘扫码登录", caption = SPEC.caption },
|
||||
}) do
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("source-session"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":5,"data":{"ywGuid":"source-guid","ywKey":"source-key"}}'))
|
||||
local got
|
||||
QRLogin:new(spec, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(find("qr").title, spec.title)
|
||||
Assert.matches(find("qr").text, "appid=" .. spec.app_id .. "&areaid=" .. spec.area_id)
|
||||
Assert.matches(requested[1].url, "appId=" .. spec.app_id .. "&areaId=" .. spec.area_id)
|
||||
Assert.matches(requested[2].url, "appId=" .. spec.app_id .. "&areaId=" .. spec.area_id)
|
||||
Assert.eq(requested[1].headers.Referer, spec.referer)
|
||||
Assert.eq(got, "ywguid=source-guid; ywkey=source-key")
|
||||
end
|
||||
|
||||
do -- 浏览器扩展绑定不改到 passport
|
||||
local Setting = require("moonsource_qqreader.setting")
|
||||
Assert.eq(Setting.browser.domain, "book.qq.com")
|
||||
Assert.eq(Setting.browser.login, "https://book.qq.com/book-shelf")
|
||||
Assert.eq(Setting.browser.check, "https://book.qq.com/book-shelf")
|
||||
Assert.eq(type(Setting.login), "function")
|
||||
end
|
||||
Reference in new issue
Block a user