✨ 初始提交:月读第三方书源插件集合

每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。

Co-authored-by: Copilot <[email protected]>
This commit is contained in:
GarfieldandCopilot committed 2026-11-16 12:08:03 +08:00
commit f7c9afb9ca
22 files changed
+3104

No files matched your search

+146
View File
@@ -0,0 +1,146 @@
--[[--
得到书城:服务器分类、子分类、排序、分页和旧目录离线兼容。
@module tests.moonsource_dedao.browse_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Json = require("support.json_stub")
local queries, pages = {}, {}
local progress, pushed, read_cancelled, write_cancelled, async_progress = nil, nil, false, false, true
local cached = { { uid = "legacy-chapter", title = "旧目录" } }
package.preload["json"] = function() return Json end
package.preload["source.base"] = function()
return {
loadMeta = function() return { id = "ext.dedao", name = "得到阅读", type = "chapter" } end,
defer = function(done, ...)
done(...)
return { cancel = function() end }
end,
}
end
package.preload["source.shelf"] = function() return {} end
package.preload["source.toc"] = function() return { read = function() return cached end } end
package.preload["moonsource_dedao.client"] = function()
return {
loggedIn = function() return true end,
progressAsync = function(_id, done)
progress = done
if not async_progress then done({ findex = "legacy-chapter" }) end
return { cancel = function() read_cancelled = true end }
end,
putProgressAsync = function(_id, _chapter, _title, done)
pushed = done
return { cancel = function() write_cancelled = true end }
end,
browseFiltersAsync = function(query, done)
queries[#queries + 1] = query
done({
request = { navigation_id = query.navigation_id or "novel", label_id = query.label_id or "all",
sort_strategy = query.sort_strategy or "HOT", tags_ids = {} },
filter = {
navigations = { title = "分类", options = {
{ name = "小说", value = "novel", sub_options = {
{ name = "全部", value = "all" }, { name = "推理", value = "mystery" },
} },
{ name = "历史", value = "history" },
} },
sort_strategy = { title = "排序", options = {
{ name = "最热", value = "HOT" }, { name = "最新", value = "NEW" },
} },
buy_strategy = { is_hide = true, options = {} },
},
})
return { cancel = function() error("cancelled completed filter request") end }
end,
browsePageAsync = function(query, page, done)
pages[#pages + 1] = { query = query, page = page }
local rows = {}
for idx = 1, 20 do
rows[#rows + 1] = {
id_out = tostring((page - 1) * 20 + idx), item_type = 2,
name = "测试书", author_list = { "甲", "乙" }, index_img = "https://example.test/cover",
}
end
done({ product_list = rows, is_more = 1, request_id = "public-page-session" })
return { cancel = function() end }
end,
searchAsync = function(_keyword, done, page)
done({ data = { isMore = page < 2, moduleList = { { layerDataList = {
{ type = 2, title = "搜索书", extra = { enid = "search-" .. page } },
} } } } })
return { cancel = function() end }
end,
}
end
local source = require("moonsource_dedao.source").new()
local result, err
source:browseAsync({}, function(value, reason) result, err = value, reason end)
Assert.is_nil(err)
Assert.len(result.data, 60)
Assert.len(pages, 3)
Assert.len(result.groups, 3)
Assert.eq(result.data[1].authors, "甲、乙")
Assert.eq(result.groups[1].chips[1].title, "小说")
Assert.eq(result.groups[2].chips[2].title, "推理")
Assert.eq(result.groups[3].chips[2].title, "最新")
Assert.eq(pages[2].query.request_id, "public-page-session")
Assert.is_nil(pages[1].query.tags_ids)
local latest = result.groups[3].chips[2].id
source:browseAsync({ node = latest }, function(value) result = value end)
Assert.eq(queries[#queries].sort_strategy, "NEW")
Assert.eq(queries[#queries].navigation_id, "novel")
Assert.eq(queries[#queries].product_types, "2")
source:browseAsync({ node = "invalid json" }, function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "响应无效")
source:searchAsync("test", function(value) result = value end)
Assert.len(result.data, 2)
source:loadTocAsync({ stable_id = "legacy-book" }, function(value) result = value end)
Assert.eq(result, cached)
local progress_result
local job = source:getProgressAsync({ stable_id = "legacy-book" }, function(value) progress_result = value end)
job.cancel()
Assert.is_true(read_cancelled, "读进度的第一步异步请求可取消")
progress({ findex = "legacy-chapter" })
Assert.is_nil(progress_result)
local toc_callback, toc_cancelled
source.loadTocAsync = function(_source, _identity, done)
toc_callback = done
return { cancel = function() toc_cancelled = true end }
end
async_progress, read_cancelled = false, false
job = source:getProgressAsync({ stable_id = "legacy-book" }, function(value) progress_result = value end)
job.cancel()
Assert.is_true(toc_cancelled, "同步读进度后应取消异步目录,不是已完成的读进度")
Assert.is_true(not read_cancelled)
toc_callback(cached)
Assert.is_nil(progress_result)
toc_cancelled = false
job = source:putProgressAsync({ stable_id = "legacy-book" }, { chapter_idx = 1 }, function(value) progress_result = value end)
job.cancel()
Assert.is_true(toc_cancelled, "推送前的异步目录可取消")
toc_callback(cached)
Assert.is_nil(pushed)
source.loadTocAsync = function(_source, _identity, done)
done(cached)
return { cancel = function() toc_cancelled = true end }
end
toc_cancelled = false
job = source:putProgressAsync({ stable_id = "legacy-book" }, { chapter_idx = 1 }, function(value) progress_result = value end)
job.cancel()
Assert.is_true(write_cancelled, "同步目录后应取消真正的进度写请求")
Assert.is_true(not toc_cancelled)
pushed(true)
Assert.is_nil(progress_result)
+295
View File
@@ -0,0 +1,295 @@
--[[--
得到:扫码链接、已购书架、搜索、目录章节号、SVG 解密。
@module tests.moonsource_dedao.client_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
package.preload["json"] = function() return require("support.json_stub") end
package.preload["ui/uimanager"] = function()
return { nextTick = function(_ui, fn) fn() end, scheduleIn = function(_ui, _delay, fn) fn() end }
end
package.preload["ui.guard"] = function()
return { call = function(_label, fn, ...) return fn(...) end }
end
local Assert = require("support.assert")
local Json = require("support.json_stub")
local Mapper = require("moonsource_dedao.mapper")
Assert.eq(Mapper.qrText("igetweb1"), "https://m.igetget.com/oauth/qrcode/v2/authorize?token=igetweb1&source=igetweb&dv=")
Assert.eq(Mapper.login({ data = { status = 0 } }), "wait")
Assert.eq(Mapper.login({ data = { status = 1 } }), "ok")
Assert.eq(Mapper.login({ data = { status = 2 } }), "fail")
local shelf = Mapper.shelf({
list = {
{ type = 2, enid = "e1", title = "三体", author = "刘慈欣", icon = "https://c" },
{ type = 13, enid = "e2", title = "听书" },
{ type = 230, enid = "e3", title = "本地上传" },
},
})
Assert.eq(#shelf, 1)
Assert.eq(shelf[1].stable_id, "e1")
Assert.eq(shelf[1].source_id, "ext.dedao")
local found = Mapper.search({
data = { moduleList = { { layerDataList = {
{ type = 2, Title = "<hl>三体</hl>全集", author = "刘慈欣", image = "https://img", extra = { enid = "e1" } },
{ type = 2, Title = "重复", extra = { enid = "e1" } },
{ type = 66, Title = "课程", extra = { enid = "e9" } },
} } } },
})
Assert.eq(#found, 1)
Assert.eq(found[1].title, "三体全集")
Assert.eq(found[1].cover, "https://img")
local toc = Mapper.chapters({
bookInfo = {
orders = { { pathInEpub = "chapter01.xhtml", chapterId = "c1" } },
toc = {
{ href = "chapter01.xhtml#sigil", text = "序", level = 0, playOrder = 2 },
{ href = "chapter02.xhtml", text = "第二章", level = 1, playOrder = 1 },
},
},
})
Assert.eq(#toc, 2)
Assert.eq(toc[1].uid, "chapter02.xhtml")
Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION)
Assert.eq(toc[2].uid, "c1")
Assert.eq(toc[2].depth, 1)
Assert.eq(Mapper.progressUid("c1"), "c1")
Assert.is_nil(Mapper.progressUid(""))
local cipher = "UzX9+34+GWS32TeZD7pKPYHRf4jS1JHrdgxu4mR6gj5QxmZ0tAASG61dGrB/0C0+"
Assert.eq(Mapper.pageText(cipher), "第一段\n第二段")
local settings = { cookie = "csrfToken=c; token=t", logged_in = true }
package.loaded["source.logout"] = { clear = function(_id, clear) clear(); return true end }
local requests = {}
local cookies, qr_status = {}, 0
local pages_reply, remove_reply
local function reply(url, payload)
if url:find("/loginapi/getAccessToken", 1, true) then return '"oauth-token"' end
if url:find("/qrcode/check_login", 1, true) then
return Json.encode({ errCode = 0, data = { status = qr_status } })
end
if url:find("/oauth/api/embedded/qrcode", 1, true) then
return Json.encode({ errCode = 0, data = { qrCodeString = "igetweb9" } })
end
if url:find("/api/hades/v2/product/list", 1, true) then
return Json.encode({ h = { c = 0 }, c = { is_more = false, list = {
{ type = 2, enid = "e1", title = "三体", author = "刘慈欣" },
} } })
end
if url:find("/bookshelf/add", 1, true) then
return Json.encode({ h = { c = 0 }, c = { data = { n = 1 } } })
end
if url:find("/product/pcremove", 1, true) then
return remove_reply or Json.encode({ h = { c = 0 }, c = { n = 0 } })
end
if url:find("/api/pc/user/info", 1, true) then
return Json.encode({ h = { c = 0 }, c = { uid_hazy = "test-user" } })
end
if url:find("/api/search/pc/tophits", 1, true) then
return Json.encode({ h = { c = 0 }, c = { data = { moduleList = { { layerDataList = {
{ type = 2, Title = "<hl>三体</hl>", author = "刘", extra = { enid = "e1" } },
} } } } } })
end
if url:find("/pc/ebook2/v1/pc/detail", 1, true) then
return Json.encode({ h = { c = 0 }, c = { enid = "e1", title = "三体", book_author = "刘慈欣", cover = "https://c" } })
end
if url:find("/read/token", 1, true) then
return Json.encode({ h = { c = 0 }, c = { token = "read-token" } })
end
if url:find("/get_pages", 1, true) then
if pages_reply then return pages_reply() end
if payload and payload:find('"chapter_id":"vip"', 1, true) then
return Json.encode({ h = { c = 4000, e = "user no legal!" } })
end
return Json.encode({ h = { c = 0 }, c = { is_end = true, pages = { { svg = cipher, is_last = true } } } })
end
if url:find("/getread", 1, true) then
return Json.encode({ h = { c = 0 }, c = { data = { findex = "c1", windex = 0 } } })
end
if url:find("/addread", 1, true) then
return Json.encode({ h = { c = 0 }, c = { status = 1 } })
end
return payload
end
package.preload["utils.settings"] = function()
return {
getSource = function() return settings end,
saveSource = function() end,
}
end
package.preload["http.request"] = function()
return {
headerAll = function() return cookies end,
get = function(url, options, callback)
requests[#requests + 1] = { method = "GET", url = url, headers = options.headers }
callback(reply(url), nil, {})
return { cancel = function() end }
end,
post = function(url, payload, options, callback)
requests[#requests + 1] = { method = "POST", url = url, body = payload, headers = options.headers }
local raw, err = reply(url, payload)
callback(raw, err, {})
return { cancel = function() end }
end,
}
end
local Client = require("moonsource_dedao.client")
local token
Client.accessTokenAsync(function(value) token = value end)
Assert.eq(token, "oauth-token")
Assert.eq(requests[#requests].headers["Xi-DT"], "web")
Assert.eq(requests[#requests].headers["Xi-Csrf-Token"], "c")
local code
Client.qrCreateAsync("oauth-token", function(value) code = value end)
Assert.eq(code, "igetweb9")
Assert.eq(requests[#requests].headers["X-Oauth-Access-Token"], "oauth-token")
local rows
Client:shelfSyncAsync(function(body) rows = Mapper.shelf(body) end)
Assert.eq(#rows, 1)
Assert.is_true(requests[#requests].body:find('"category":"ebook"', 1, true) ~= nil)
local added
Client:addToShelfAsync("e1", function(ok) added = ok end)
Assert.eq(added, true)
Assert.is_true(requests[#requests].body:find('"book_enids":["e1"]', 1, true) ~= nil)
Assert.is_true(requests[#requests].body:find('"ptype":2', 1, true) ~= nil)
local books
Client.searchAsync("三体", function(body) books = Mapper.search(body) end)
Assert.eq(books[1].title, "三体")
Assert.is_true(requests[#requests].body:find('"tab_type":2', 1, true) ~= nil)
local fallback = Mapper.detail({
title = "", operating_title = "得到书", book_author = "甲", book_intro = "简介",
}, "e1")
Assert.eq(fallback.title, "得到书")
Assert.eq(fallback.authors, "甲")
Assert.eq(fallback.stable_id, "e1")
local detail
Client.detailAsync("e1", function(body) detail = Mapper.detail(body, "e1") end)
Assert.eq(detail.title, "三体")
Assert.eq(detail.authors, "刘慈欣")
local text, terr, kind
Client.contentAsync("e1", "c1", function(value, err, content_kind) text, terr, kind = value, err, content_kind end)
Assert.eq(text, "第一段\n第二段")
Assert.is_nil(terr)
Assert.is_true(requests[#requests].url:find("/ebk_web_go/v2/get_pages", 1, true) ~= nil)
Assert.is_true(requests[#requests].body:find('"token":"read-token"', 1, true) ~= nil)
Client.contentAsync("e1", "vip", function(value, err, content_kind) text, terr, kind = value, err, content_kind end)
Assert.is_nil(text)
Assert.eq(terr, "本章未购买")
Assert.eq(kind, "unpaid")
local progress
Client.progressAsync("e1", function(item) progress = item end)
Assert.eq(progress.findex, "c1")
local posted
Client.putProgressAsync("e1", "c1", "序", function(ok) posted = ok end)
Assert.eq(posted, true)
Assert.is_true(requests[#requests].body:find('"findex":"c1"', 1, true) ~= nil)
cookies, qr_status = { "session=new-login; Path=/" }, 1
local login
local candidate = { csrfToken = "candidate" }
local old_cookie = settings.cookie
Client.qrPollAsync("oauth-token", "igetweb9", function(wire) login = wire end, candidate)
Assert.eq(login.data.status, 1)
Assert.eq(settings.cookie, old_cookie)
Assert.eq(candidate.session, "new-login")
Client.confirmLoginAsync(candidate, function(ok) Assert.is_true(ok) end)
Assert.matches(settings.cookie, "session=new%-login")
Assert.matches(Client.cookie(), "session=new%-login")
Client.loggedIn()
Assert.matches(Client.cookie(), "session=new%-login")
cookies = {}
local removed, remove_err
for _idx, bad in ipairs({ "<html>upstream unavailable</html>", "broken", "{}", '{"h":{},"c":{}}',
'{"h":{"c":401},"c":{}}' }) do
remove_reply = bad
Client:removeFromShelfAsync("e1", function(ok, err) removed, remove_err = ok, err end)
Assert.is_nil(removed)
Assert.is_true(remove_err ~= nil)
end
settings.logged_in = true
remove_reply = nil
Client:removeFromShelfAsync("e1", function(ok, err) removed, remove_err = ok, err end)
Assert.is_true(removed)
Assert.is_nil(remove_err)
Assert.eq(Json.decode(requests[#requests].body).data[1].pid, "e1")
Assert.eq(Json.decode(requests[#requests].body).data[1].ptype, 2)
local function chapterResult()
text, terr = nil, nil
Client.contentAsync("e1", "c1", function(value, err) text, terr = value, err end)
end
local page_count = 0
pages_reply = function()
page_count = page_count + 1
if page_count > 1 then return nil, "network timeout" end
return Json.encode({ h = { c = 0 }, c = { pages = { { svg = cipher } } } })
end
chapterResult()
Assert.is_nil(text)
Assert.eq(terr, "network timeout")
for _idx, body in ipairs({
{ is_end = true, pages = { { svg = cipher }, { svg = "broken" } } },
{ is_end = true },
{ pages = {} },
}) do
pages_reply = function() return Json.encode({ h = { c = 0 }, c = body }) end
chapterResult()
Assert.is_nil(text)
Assert.eq(terr, "响应无效")
end
page_count = 0
pages_reply = function()
page_count = page_count + 1
return Json.encode({ h = { c = 0 }, c = { pages = { { svg = cipher } } } })
end
chapterResult()
Assert.eq(page_count, 40)
Assert.is_nil(text)
Assert.eq(terr, "响应无效")
local Aes = require("crypto.aes")
local Text = require("utils.text")
local SVG_KEY, SVG_IV = "3e4r06tjkpjcevlbslr3d96gdb5ahbmo", "6fd89a1b3a7f48fb"
local function svgCipher(svg)
return Text.base64Encode(Aes.cbc_encrypt(svg, SVG_KEY, SVG_IV))
end
local blank = svgCipher("<svg></svg>")
Assert.eq(Mapper.pageText(blank), "")
-- 同一基线的字拼成一行。上一行没排满就换段;排满的行和页边续行合成一段。
Assert.eq(Mapper.pageText(svgCipher('<text x="10" y="20">膝</text><text x="40" y="20">盖</text>')), "膝盖")
Assert.eq(Mapper.pageText(svgCipher([[<text x="80" y="20">甲</text>
<text x="30" y="56">乙</text><text x="50" y="56">丙</text><text x="740" y="56">。</text>
<text x="30" y="92">下</text>]])), "甲\n乙丙。下")
Assert.eq(Mapper.pageText(svgCipher('<text x="70" y="20">A</text><text x="740" y="20">c</text><text x="30" y="56">D</text>')), "Ac D")
page_count = 0
pages_reply = function()
page_count = page_count + 1
return Json.encode({ h = { c = 0 }, c = {
is_end = page_count == 2, pages = { { svg = page_count == 1 and blank or cipher } },
} })
end
chapterResult()
Assert.eq(text, "第一段\n第二段")
Assert.is_nil(terr)
+251
View File
@@ -0,0 +1,251 @@
--[[--
得到多阶段请求:同步回调、取消、完整书架、账号归属与登录提交。
@module tests.moonsource_dedao.operations_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local beginLogin = require("source.auth").beginLogin
local Json = require("support.json_stub")
local cfg = { cookie = "csrfToken=old; session=old", logged_in = true }
local cleared = 0
package.loaded["source.logout"] = { clear = function(id, clear)
beginLogin(id)
clear()
cleared = cleared + 1
return true
end }
local fixtures, held, async, requests = {}, {}, {}, {}
local expired = 0
local warnings = {}
package.preload["utils.log"] = function()
return { warn = function(...)
local fields = {}
for idx = 1, select("#", ...) do fields[idx] = tostring(select(idx, ...)) end
warnings[#warnings + 1] = table.concat(fields, " ")
end }
end
package.loaded["utils.log"] = nil
package.preload["json"] = function() return Json end
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end, saveSource = function() end }
end
package.loaded["source.auth"] = nil
package.preload["source.auth"] = function()
return {
ok = function() end,
beginLogin = beginLogin,
expire = function(_id, message) expired = expired + 1; return message end,
}
end
package.preload["source.base"] = function()
return { defer = function(done, ...)
done(...)
return { cancel = function() end }
end }
end
local function wire(body)
return Json.encode({ h = { c = 0 }, c = body })
end
local function request(url, body, options, done)
local path = url:match("https://[^/]+([^?]+)")
local item = { path = path, body = body and body ~= "" and Json.decode(body) or nil, options = options, done = done }
requests[#requests + 1] = item
if async[path] then
held[path] = item
else
done(fixtures[path](item.body), nil, path == "/" and { cookies = { "csrfToken=candidate; Path=/" } } or {})
end
return { cancel = function() item.cancelled = true end }
end
package.preload["http.request"] = function()
return {
headerAll = function(res) return res.cookies or {} end,
get = function(url, options, done) return request(url, nil, options, done) end,
post = request,
}
end
local Client = require("moonsource_dedao.client")
local search_path = "/api/search/pc/tophits"
async[search_path] = true
local completed = false
local job = Client.searchAsync("test", function() completed = true end)
job.cancel()
Assert.is_true(held[search_path].cancelled)
held[search_path].done(wire({ data = { moduleList = {} } }), nil, {})
Assert.is_false(completed)
fixtures["/api/pc/ebook2/v1/pc/read/token"] = function(body)
Assert.is_nil(body.ptype)
return wire({ token = "test-token" })
end
local info_path = "/ebk_web/v1/get_book_info"
async[info_path] = true
completed = false
job = Client.bookInfoAsync("test-book", function() completed = true end)
job.cancel()
Assert.is_true(held[info_path].cancelled)
held[info_path].done(wire({ bookInfo = {} }), nil, {})
Assert.is_false(completed)
local oauth_path = "/loginapi/getAccessToken"
async[oauth_path] = true
completed = false
job = Client.accessTokenAsync(function() completed = true end)
job.cancel()
Assert.is_true(held[oauth_path].cancelled)
held[oauth_path].done('"test-oauth"', nil, {})
Assert.is_false(completed)
local shelf_path = "/api/hades/v2/product/list"
fixtures[shelf_path] = function(body)
return wire({ list = { { enid = "book-" .. body.page, type = 2 } }, is_more = body.page < 44 })
end
local shelf, shelf_err
Client:shelfSyncAsync(function(body, err) shelf, shelf_err = body, err end)
Assert.len(shelf.list, 44)
Assert.is_false(shelf.is_more)
Assert.is_nil(shelf_err)
fixtures[shelf_path] = function() return wire({}) end
Client:shelfSyncAsync(function(body, err) shelf, shelf_err = body, err end)
Assert.is_nil(shelf)
Assert.eq(shelf_err, "响应无效")
fixtures[shelf_path] = function()
return wire({ list = { { enid = "same", type = 2 } }, is_more = true })
end
Client:shelfSyncAsync(function(body, err) shelf, shelf_err = body, err end)
Assert.is_nil(shelf)
Assert.eq(shelf_err, "响应无效")
local progress_path = "/api/pc/ebook2/v1/pc/getread"
async[progress_path] = true
Client.progressAsync("test-book", function() end)
cfg.cookie = "csrfToken=new; session=new"
held[progress_path].done(Json.encode({ h = { c = 401, e = "expired old account" } }), nil,
{ cookies = { "session=stale; Path=/" } })
Assert.eq(expired, 0)
Assert.eq(cfg.cookie, "csrfToken=new; session=new")
Client.load()
Assert.matches(Client.cookie(), "session=new")
fixtures["/api/pc/user/info"] = function() return wire({ uid_hazy = "user-one" }) end
fixtures["/"] = function() return "<html></html>" end
local logged, login_err
local candidate = { csrfToken = "candidate", session = "candidate-session" }
Client.confirmLoginAsync(candidate, function(ok, err) logged, login_err = ok, err end)
Assert.is_true(logged)
Assert.is_nil(login_err)
Assert.eq(cfg.uid, "user-one")
Assert.eq(cfg.cookie, "csrfToken=candidate; session=candidate-session")
fixtures["/api/pc/user/info"] = function() return wire({ uid_hazy = "user-two" }) end
Client.confirmLoginAsync({ session = "other" }, function(ok, err) logged, login_err = ok, err end)
Assert.is_true(logged)
Assert.is_nil(login_err)
Assert.eq(cfg.uid, "user-two")
Assert.eq(cfg.cookie, "session=other")
Assert.eq(cleared, 2, "包括旧配置缺账号标识时,直接清旧源再换号")
local review_path = "/pc/ebook2/v1/comment/list"
fixtures[review_path] = function(body)
local list = {}
for idx = 1, body.page == 1 and 20 or 3 do
list[#list + 1] = { note_id_hazy = "note-" .. ((body.page - 1) * 20 + idx), note = "test" }
end
return wire({ list = list, total = 23 })
end
local reviews
Client.reviewsAsync("test-book", function(body) reviews = body end)
Assert.len(reviews.list, 23)
Assert.eq(reviews.total, 23)
Assert.eq(requests[#requests].body.page, 2)
Assert.eq(requests[#requests].body.ptype, 2)
fixtures[review_path] = function() return wire({ total = 1, list = {} }) end
Client.reviewsAsync("test-book", function(body, err) reviews = body; Assert.eq(err, "响应无效") end)
Assert.is_nil(reviews)
fixtures["/"] = function() return "<html></html>" end
async[oauth_path] = false
fixtures[oauth_path] = function() return '"sms-test-oauth"' end
local sms_path = "/oauth/api/embedded/auth_code/send"
fixtures[sms_path] = function(body)
Assert.is_nil(body.captcha)
return Json.encode({ errCode = 0, data = { needCaptcha = true, captchaId = "official-captcha" } })
end
local sms, sms_err, challenge
local account_cookie = cfg.cookie
Client.sendCodeAsync("13800000000", function(value, err, next_step) sms, sms_err, challenge = value, err, next_step end)
Assert.is_nil(sms, "需要滑块不能当作短信已发送")
Assert.is_nil(sms_err)
Assert.eq(challenge.captcha_id, "official-captcha")
Assert.eq(challenge.session.oauth, "sms-test-oauth")
Assert.eq(cfg.cookie, account_cookie, "候选验证不能替换当前账号")
fixtures[sms_path] = function(body)
Assert.eq(body.phone, "13800000000")
Assert.eq(body.captcha.captchaId, "official-captcha")
Assert.eq(body.captcha.validate, "test-proof")
return Json.encode({ errCode = 0, data = {} })
end
Client.sendSessionCodeAsync(challenge.session, { captchaId = challenge.captcha_id, validate = "test-proof" },
function(ok, err) Assert.is_true(ok); Assert.is_nil(err) end)
Assert.eq(requests[#requests].options.headers["X-Oauth-Access-Token"], "sms-test-oauth")
fixtures[sms_path] = function() return Json.encode({ errCode = 0, data = { needCaptcha = true } }) end
Client.sendSessionCodeAsync(challenge.session, nil, function(ok, err)
Assert.is_nil(ok)
Assert.eq(err, "响应无效")
end)
local mapped = require("moonsource_dedao.mapper").reviews({ list = {
{ note_id_hazy = "review", note = "", content = "", note_line = "<p>实际书评</p>",
notes_owner = { name = "测试作者" }, extra = { score_str = "4.0" } },
} })
Assert.len(mapped, 1)
Assert.eq(mapped[1].text, "实际书评")
Assert.eq(mapped[1].grade, 4)
local failure, failure_err
Client.bookInfoAsync("test-book", function(value, err) failure, failure_err = value, err end)
local timeout_error = "Request timeout: https://www.dedao.cn/ebk_web/v1/get_book_info?token=private-proof"
held[info_path].done(nil, timeout_error, { code = 0 })
Assert.is_nil(failure)
Assert.eq(failure_err, timeout_error)
Assert.len(warnings, 1)
Assert.matches(warnings[1], "GET /ebk_web/v1/get_book_info timeout")
Assert.matches(warnings[1], "timeout_seconds")
Assert.is_nil(warnings[1]:find("token", 1, true), "失败日志不记录查询参数或原始错误里的凭证")
Assert.is_nil(warnings[1]:find("private-proof", 1, true))
-- 校验只交回候选账号;退出使此前的提交请求失效。
do
local path = "/api/pc/user/info"
async[path] = true
local before_cookie, before_uid = cfg.cookie, cfg.uid
local user
Client.checkLoginAsync({ session = "candidate" }, function(value) user = value end)
held[path].done(wire({ uid_hazy = "late-user" }), nil, {})
Assert.eq(user.uid_hazy, "late-user")
Assert.eq(cfg.cookie, before_cookie)
Assert.eq(cfg.uid, before_uid)
Client.confirmLoginAsync({ session = "late" }, function(ok, err) logged, login_err = ok, err end)
beginLogin("ext.dedao")
cfg.cookie, cfg.uid, cfg.logged_in = nil, nil, nil
Client.reset()
held[path].done(wire({ uid_hazy = "late-user" }), nil, {})
Assert.is_nil(logged)
Assert.eq(login_err, "账号已变化,请重新登录")
Assert.is_nil(cfg.cookie)
Assert.is_nil(cfg.uid)
Assert.is_nil(cfg.logged_in)
end
+65
View File
@@ -0,0 +1,65 @@
--[[--
得到扫码:候选会话归窗口所有,取消停掉当前轮询,校验后才完成登录。
@module tests.moonsource_dedao.qrlogin_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local poll, candidate, stopped, signed_in, toast
local statuses = { 0, 1 }
package.preload["moonsource_dedao.client"] = function()
return {
accessTokenAsync = function(done, jar)
candidate = jar
Assert.is_nil(jar.session)
done("oauth")
return { cancel = function() error("cancelled completed bootstrap") end }
end,
qrCreateAsync = function(_oauth, done, jar)
Assert.eq(jar, candidate)
done("qr")
return { cancel = function() error("cancelled completed QR request") end }
end,
qrPollAsync = function(_oauth, _code, done, jar)
Assert.eq(jar, candidate)
poll = done
return { cancel = function() stopped = true end }
end,
confirmLoginAsync = function(jar, done)
Assert.eq(jar, candidate)
done(true)
return { cancel = function() error("cancelled completed account verification") end }
end,
}
end
package.preload["moonsource_dedao.mapper"] = function()
return {
qrText = function() return "https://example.test/qr" end,
login = function(wire) return wire.data.status == 1 and "ok" or "wait" end,
}
end
package.preload["ui.themes.widgets.qr"] = function()
return { new = function(_class, opts)
return { show = function() end, close = function() opts.close_callback() end }
end }
end
package.preload["ui.themes.widgets.toast"] = function()
return { new = function(_class, opts) toast = opts.text; return { show = function() end } end }
end
local QRLogin = require("moonsource_dedao.qrlogin")
local login = QRLogin:new(function() signed_in = true end)
login:start()
login:cancel()
Assert.is_true(stopped)
poll({ data = { status = statuses[2] } })
Assert.is_nil(signed_in)
stopped = false
login:start()
poll({ data = { status = statuses[2] } })
Assert.is_true(signed_in)
Assert.is_nil(toast)
Assert.is_nil(login.dialog)
+156
View File
@@ -0,0 +1,156 @@
--[[--
短信安全验证接回原登录输入窗,保留候选会话并取消真正的在飞步骤。
@module tests.moonsource_dedao.setting_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local beginLogin = require("source.auth").beginLogin
local Theme = require("support.theme_stubs")
Theme.install()
local Input = require("ui.themes.widgets.input")
local make_input = Input.new
function Input:new(opts)
local window = make_input(self, opts)
local show = window.show
window.show = function(self) show(self) end
return window
end
local sent, verified, sms_session, sms_code
local login_ok, defer_login, login_callback
local request_cancelled, verification_cancelled
local candidate = { phone = "13800000000", oauth = "test-token", jar = {} }
local cfg, saves, reloads, accepted = {}, 0, 0, 0
package.preload["utils.settings"] = function()
return {
getSource = function(_id) return cfg end,
saveSource = function(_id) saves = saves + 1 end,
}
end
package.preload["source.registry"] = function() return { reload = function() reloads = reloads + 1 end } end
package.loaded["source.auth"] = nil
package.preload["source.auth"] = function()
return { beginLogin = beginLogin, ok = function(_id) accepted = accepted + 1 end }
end
package.preload["ui/network/manager"] = function()
return { runWhenConnected = function(_network, cb) cb() end }
end
package.preload["moonsource_dedao.client"] = function()
return {
sendCodeAsync = function(_phone, cb)
sent = cb
cb(nil, nil, { session = candidate, captcha_id = "test-id" })
return { cancel = function() request_cancelled = true end }
end,
smsLoginAsync = function(session, code, cb)
sms_session, sms_code = session, code
login_callback = cb
if not defer_login then cb(login_ok, not login_ok and "test-login-error" or nil) end
return { cancel = function() request_cancelled = true end }
end,
}
end
package.preload["moonsource_dedao.verify"] = function()
return { new = function(challenge, cb)
Assert.eq(challenge.session, candidate)
verified = cb
return { cancel = function() verification_cancelled = true end }
end }
end
local Setting = require("moonsource_dedao.setting")
local function open()
Setting.open()
Theme.choose(Theme.last("sheet"), 1)
local input = Theme.last("input")
input.actions[1].callback("13800000000")
Theme.last("confirm").ok_callback()
return input
end
local input = open()
Assert.is_true(Theme.last("progress_dialog").closed)
Assert.is_nil(Theme.last("toast"), "要求滑块时不能弹短信已发送")
Assert.is_true(not input.closed)
input:close()
Assert.is_true(verification_cancelled, "同步短信回调不能把网页取消句柄覆盖成旧请求")
Assert.is_nil(request_cancelled)
verified(candidate)
Assert.is_nil(Theme.last("toast"), "关输入窗后不显示迟到成功")
input = open()
verified(candidate)
Assert.eq(Theme.last("toast").text, "短信已发送,请在设备上填写验证码")
Assert.is_true(input.validate("13800000000", "123456"))
Assert.is_true(not input.validate("13900000000", "123456"))
input.callback("13800000000", "123456")
Assert.eq(sms_session, candidate)
Assert.eq(sms_code, "123456")
Assert.eq(Theme.last("toast").text, "test-login-error")
input:close()
Assert.is_nil(request_cancelled, "同步完成登录不留下旧取消句柄")
login_ok = true
input = open()
verified(candidate)
input.callback("13800000000", "123456")
Assert.is_true(input.closed, "show 不返回窗口时,成功登录仍能关闭真正的输入窗")
Assert.is_true(cfg.logged_in)
Assert.eq(saves, 1)
Assert.eq(reloads, 1)
Assert.eq(accepted, 1)
Assert.eq(Theme.last("toast").text, "登录成功")
defer_login = true
input = open()
verified(candidate)
input.callback("13800000000", "123456")
Assert.is_true(not input.closed)
login_callback(true)
Assert.is_true(input.closed, "HTTP 异步成功也关闭原输入窗")
Assert.eq(saves, 2)
Assert.eq(reloads, 2)
Assert.eq(Theme.last("toast").text, "登录成功")
-- Cookie / 浏览器登录行与校验保存
package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end }
local cookie_calls = {}
package.preload["moonsource_dedao.client"] = function()
return {
loggedIn = function() return cfg.logged_in == true and cfg.cookie ~= nil end,
reset = function() end,
checkLoginAsync = function(jar, cb)
cookie_calls[#cookie_calls + 1] = jar
cb({ uid_hazy = "browser-account" })
return { cancel = function() end }
end,
sendCodeAsync = function(_phone, cb)
sent = cb
cb(nil, nil, { session = candidate, captcha_id = "test-id" })
return { cancel = function() request_cancelled = true end }
end,
smsLoginAsync = function(session, code, cb)
sms_session, sms_code = session, code
login_callback = cb
if not defer_login then cb(login_ok, not login_ok and "test-login-error" or nil) end
return { cancel = function() request_cancelled = true end }
end,
}
end
package.loaded["moonsource_dedao.client"] = nil
package.loaded["moonsource_dedao.setting"] = nil
package.loaded["source.cookie_login"] = nil
Setting = require("moonsource_dedao.setting")
Assert.is_true(type(Setting.browser) == "table")
Assert.eq(Setting.browser.domain, "www.dedao.cn")
Assert.is_true(type(Setting.browser.icon) == "string" and Setting.browser.icon:match("^https://"))
cfg = {}
local rows = Setting.rows()
Assert.eq(rows[2](400).title, "浏览器登录")
Assert.eq(rows[3](400).title, "粘贴 Cookie")
rows[3](400).callback()
local paste = Theme.last("input")
Assert.eq(paste.title, "得到登录 Cookie")
paste.callback("csrfToken=abc; token=xyz")
Assert.eq(cookie_calls[1].csrfToken, "abc")
Assert.eq(cookie_calls[1].token, "xyz")
Assert.eq(cfg.cookie, "csrfToken=abc; token=xyz")
Assert.is_true(cfg.logged_in)
+101
View File
@@ -0,0 +1,101 @@
--[[--
得到滑块绑定候选会话:只交 validate,不泄露凭证,成功发短信才完成。
@module tests.moonsource_dedao.verify_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Theme = require("support.theme_stubs")
Theme.install()
local Ext = require("utils.extension")
Ext.reset()
local submit, sent_session, proof, cancelled
package.preload["moonsource_dedao.client"] = function()
return { sendSessionCodeAsync = function(session, captcha, done)
sent_session, proof, submit = session, captcha, done
return { cancel = function() cancelled = true end }
end }
end
local timers = {}
package.preload["ui/uimanager"] = function()
return {
scheduleIn = function(_ui, _delay, fn) timers[fn] = true end,
unschedule = function(_ui, fn) timers[fn] = nil end,
}
end
package.preload["ui.guard"] = function() return { wrap = function(_label, fn) return fn end } 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_dedao.verify")
local route = Ext.list("web.routes")[1]
local status, body, headers
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 login = { phone = "13800000000", oauth = "private-oauth", jar = { session = "private-cookie" } }
local completed, err
local function start()
completed, err = nil, nil
return Verification.new({ session = login, captcha_id = "official-id" }, function(value, reason) completed, err = value, reason end)
end
local verification = start()
local ticket = path:match("#(.+)$")
request("config", { ticket = ticket })
Assert.eq(status, 200)
Assert.eq(body.captcha_id, "official-id")
Assert.is_nil(body.phone)
Assert.is_nil(body.oauth)
Assert.is_nil(body.jar)
Assert.eq(headers[1], "Cache-Control: no-store")
request("verify", { ticket = "invalid", validate = "proof" })
Assert.eq(status, 403)
request("verify", { ticket = ticket, validate = {} })
Assert.eq(status, 400)
request("verify", { ticket = ticket, validate = string.rep("a", 16385) })
Assert.eq(status, 400)
request("config", { ticket = ticket }, "GET")
Assert.eq(status, 405)
request("unknown", { ticket = ticket })
Assert.eq(status, 404)
request("verify", { ticket = ticket, validate = "proof", captcha_id = "browser-id", phone = "other-phone" })
Assert.eq(sent_session, login)
Assert.eq(proof.captchaId, "official-id")
Assert.eq(proof.validate, "proof")
request("verify", { ticket = ticket, validate = "duplicate" })
Assert.eq(status, 409)
submit(nil, "SMS refused", "new-official-id")
Assert.eq(status, 400)
Assert.is_nil(completed)
request("config", { ticket = ticket })
Assert.eq(body.captcha_id, "new-official-id")
request("verify", { ticket = ticket, validate = "retry" })
submit(true)
Assert.eq(status, 200)
Assert.eq(completed, login)
Assert.is_true(verification.dialog == nil)
Assert.is_nil(next(timers))
request("verify", { ticket = ticket, validate = "replay" })
Assert.eq(status, 403)
verification = start()
ticket = path:match("#(.+)$")
request("verify", { ticket = ticket, validate = "pending" })
verification.dialog:close()
Assert.eq(err, "验证已取消")
Assert.is_true(cancelled)
submit(true)
Assert.eq(status, 403)
Assert.is_nil(completed)
verification = start()
ticket = path:match("#(.+)$")
verification.expires = os.time() - 1
request("config", { ticket = ticket })
Assert.eq(status, 403)
verification.timeout()
Assert.eq(err, "验证已过期,请重新发起验证")
Assert.is_nil(next(timers))