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

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

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

No files matched your search

+93
View File
@@ -0,0 +1,93 @@
--[[--
豆瓣分类书城:动态分类、协议筛选、跨页聚合和取消。
@module tests.moonsource_douban.browse_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Json = require("support.json_stub")
package.preload["json"] = function() return Json end
local Mapper = require("moonsource_douban.mapper")
local tree = Json.encode({
{ id = 0, children = { { id = 505, name = "科幻小说", children = {} } } },
{ id = 1, children = { { id = 100, name = "小说", children = {
{ id = 116, name = "科幻", children = {} },
} } } },
})
local cats = Mapper.categories("Ark.kindTree = " .. tree .. ";")
Assert.eq(cats.original[1].id, "505")
Assert.eq(cats.publish[2].id, "116")
Assert.is_nil(Mapper.categories("登录页面"))
Assert.is_nil(Mapper.categories("Ark.kindTree = [false]"))
local body = Mapper.catalogBody({ category = "505", sort = "new", pay = "free", state = "complete" }, 2)
Assert.eq(body.kind, 505)
Assert.eq(body.page, 2)
Assert.eq(body.minPrice, 0)
Assert.eq(body.maxPrice, 0)
Assert.eq(body.isFinished, true)
Assert.eq(body.variables.includePurchase, false)
local requests, delayed, fail_page = {}, false, nil
package.preload["utils.settings"] = function() return { getSource = function() return { cookie = "private=1" } end } end
package.preload["http.request"] = function()
return {
headerAll = function() return {} end,
request = function(opts, cb)
local record = { opts = opts }
requests[#requests + 1] = record
local wire
if opts.method == "GET" then
wire = "Ark.kindTree = " .. tree
else
local params = Json.decode(opts.body)
record.params = params
if params.page ~= fail_page then
local list = {}
for idx = 1, 20 do list[idx] = { id = (params.page - 1) * 20 + idx, title = "测试书" } end
wire = Json.encode({ list = list, total = 100 })
end
end
record.reply = function()
if wire then cb({ code = 200, body = wire }, nil) else cb(nil, "network failed") end
end
if not delayed or opts.method == "GET" then record.reply() end
return { cancel = function() record.cancelled = true end }
end,
}
end
local source = require("moonsource_douban.source").new()
local result
source:browseAsync({ node = "original:505:new:free:complete", limit = 60 }, function(value) result = value end)
Assert.eq(#result.data, 60)
Assert.eq(result.data[60].stable_id, "60")
Assert.eq(requests[2].params.kind, 505)
Assert.eq(requests[2].params.isFinished, true)
Assert.eq(result.groups[2].title, "分类")
Assert.eq(result.groups[2].active, "original:505:new:free:complete")
Assert.eq(result.groups[1].chips[2].id, "publish:1:hot:all:all")
for _idx, req in ipairs(requests) do Assert.is_nil(req.opts.headers.Cookie) end
source:browseAsync({ node = "publish:505:unknown:paid:serial", limit = 20 }, function(value) result = value end)
Assert.eq(requests[#requests].params.kind, 1)
Assert.eq(requests[#requests].params.sort, "hot")
Assert.eq(requests[#requests].params.minPrice, 1)
Assert.is_nil(requests[#requests].params.isFinished)
Assert.eq(#result.groups, 4)
source:browseAsync({ limit = 25 }, function(value) result = value end)
Assert.eq(#result.data, 25)
local err
fail_page = 2
source:browseAsync({ limit = 60 }, function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "network failed")
fail_page, delayed = nil, true
local calls = 0
local job = source:browseAsync({}, function() calls = calls + 1 end)
local active = requests[#requests]
job.cancel()
Assert.is_true(active.cancelled)
active.reply()
Assert.eq(calls, 0)
+511
View File
@@ -0,0 +1,511 @@
--[[--
豆瓣阅读:搜索体、正文解密、专栏目录、扫码登录和书架。
@module tests.moonsource_douban.client_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
package.preload["json"] = function() return require("support.json_stub") end
local Aes = require("crypto.aes")
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local Json = require("support.json_stub")
local Text = require("utils.text")
local Mapper = require("moonsource_douban.mapper")
local cfg = {}
package.preload["utils.settings"] = function()
return {
getSource = function() return cfg end,
saveSource = function() end,
get = function() return {} end,
}
end
local sha2 = require("ffi/sha2")
local iv = string.rep("\1", 16)
local plain = Json.encode({
posts = { {
title = "序",
contents = {
{ type = "headline", id = 10, data = { text = "标题" } },
{ type = "paragraph", id = 11, data = { text = {
{ kind = "plaintext", content = "第一" },
{ kind = "plaintext", content = "段" },
} } },
{ type = "pagebreak", id = 11.5, data = {} },
{ type = "paragraph", id = 12, data = { text = "第二段" } },
},
} },
toc = {
{ title = "开篇", paragraph_id = 10, level = 0 },
{ title = "", paragraph_id = 12, level = 1 },
},
})
local function seal(user_id)
local material = user_id or "anonymous"
local key = sha2.hex_to_bin(sha2.sha256(material))
return Text.base64Encode(Aes.cbc_encrypt(plain, key, iv) .. iv .. string.rep("z", 13))
end
local article = Mapper.decrypt(seal(nil), nil)
Assert.eq(article.posts[1].title, "序")
Assert.eq(Mapper.blocksText(article, 10, 12), "标题\n第一段")
Assert.eq(Mapper.paragraphIds(article, 10, 12)[1], "10")
Assert.eq(Mapper.paragraphIds(article, 10, 12)[2], "11")
Assert.eq(#Mapper.paragraphIds(article, 10, 12), 2)
local spots = Mapper.reviewHotspots({
{ id = "1", note = "好看", startContainerId = "11", n_favorites = 3, owner = { name = "甲" }, create_time = 1700000000000 },
{ note = "", startContainerId = "11" },
{ note = "章外", startContainerId = "99" },
}, { "10", "11" })
Assert.eq(#spots, 1)
Assert.eq(spots[1].range, "2")
Assert.eq(spots[1].total, 1)
local page = Mapper.reviewPage({
{ id = "1", note = "好看", startContainerId = "11", n_favorites = 3, owner = { name = "甲" }, create_time = 1700000000000 },
}, { "10", "11" }, "2")
Assert.eq(page.items[1].author, "甲")
Assert.eq(page.items[1].content, "好看")
Assert.eq(page.items[1].likes, 3)
Assert.eq(page.items[1].time, 1700000000)
local dated = Mapper.reviewPage({
{ id = "2", note = "日期", startContainerId = "10", owner = { name = "乙" }, create_time = "2024-01-02T00:00:00+00:00" },
}, { "10" }, "1")
Assert.eq(os.date("!%Y-%m-%d", dated.items[1].time), "2024-01-02")
Assert.eq(page.total, 1)
Assert.eq(Mapper.blocksText(article, nil, nil), "标题\n第一段\n第二段")
Assert.eq(Mapper.decrypt(seal("42"), "42").posts[1].title, "序")
Assert.is_nil(Mapper.decrypt(seal("42"), nil))
local chapters = Mapper.ebookChapters(article, "594929245")
Assert.eq(#chapters, 2)
Assert.eq(chapters[1].uid, "10")
Assert.eq(chapters[1].title, "开篇")
Assert.eq(chapters[1].vip, false)
Assert.eq(chapters[1].slice, true)
Assert.eq(chapters[1].end_pid, "12")
Assert.eq(chapters[1].toc_version, Mapper.TOC_VERSION)
Assert.eq(chapters[2].title, "第 2 章")
Assert.eq(chapters[2].vip, false)
Assert.is_nil(chapters[2].end_pid)
local rich = { posts = { { contents = {
{ id = 1, type = "paragraph", data = { text = {
{ kind = "plaintext", content = " 前文 " }, { kind = "plaintext", content = " 后文 " },
} } },
{ id = 2, type = "paragraph", data = { text = {} } },
{ id = 3, type = "paragraph", data = { text = { { kind = "plaintext", content = " \n " } } } },
{ id = 4, type = "paragraph", data = { text = "尾段" } },
} } }, toc = { { paragraph_id = 1, title = "开篇" }, { paragraph_id = 4, title = "结尾" } } }
Assert.eq(Mapper.blocksText(rich), "前文 后文\n尾段")
Assert.eq(Mapper.blocksText(rich, 1, 4), "前文 后文")
Assert.eq(Mapper.paragraphIds(rich)[1], "1")
Assert.eq(Mapper.paragraphIds(rich)[2], "4")
Assert.eq(#Mapper.paragraphIds(rich), 2)
Assert.eq(Mapper.ebookChapters(rich, "test")[1].vip, false)
local found = Mapper.searchBooks({
list = {
{ id = "594929245", title = "三体", author = { { name = "刘慈欣" } }, cover = "//pic/a.jpg", abstract = "科幻", url = "/ebook/594929245/", kinds = { { shortName = "科幻" } } },
{ id = "1", title = "有声", isAudio = true },
{ id = "699209652", title = "如果爱", isColumn = true, url = "/column/73610846/", author = { { name = "茉莉多丁" } } },
},
})
Assert.eq(#found, 2)
Assert.eq(found[1].stable_id, "594929245")
Assert.eq(found[1].authors, "刘慈欣")
Assert.eq(found[1].cover, "https://pic/a.jpg")
Assert.eq(found[1].category, "科幻")
Assert.eq(found[2].stable_id, "699209652")
Assert.is_nil(Mapper.searchBooks({ error = "PublishError" }))
local target = Mapper.reader("/reader/column/73610846/chapter/699210556/")
Assert.eq(target.kind, "column")
Assert.eq(target.column_id, "73610846")
Assert.eq(Mapper.reader("/reader/ebook/594929245/").kind, "ebook")
Assert.eq(Mapper.readerUrl({ data = { works = { readerUrl = "/reader/ebook/594929245/" } } }), "/reader/ebook/594929245/")
local column = Mapper.columnBook("699209652", {
type = "column",
title = "如果爱",
abstract = "简介",
cover = "https://pic/c.jpg",
category = "言情小说",
agent = { name = "茉莉多丁" },
chapters = {},
})
Assert.eq(column.stable_id, "699209652")
Assert.eq(column.authors, "茉莉多丁")
Assert.eq(column.category, "言情小说")
local toc = Mapper.columnChapters({
chapters = {
{ id = "699210556", title = "第一章", is_free = true },
{ id = "699210557", title = "第二章", is_free = false, is_paid = false, is_allowed_to_read = false },
{ id = "699210558", title = "第三章", is_paid = true },
},
})
Assert.eq(#toc, 3)
Assert.eq(toc[1].content_url, "699210556")
Assert.eq(toc[1].vip, false)
Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION)
Assert.eq(toc[2].vip, true)
Assert.eq(toc[3].vip, false)
local shelf = Mapper.shelf({ list = { { id = "9", title = "书架书", author = { { name = "甲" } } } } })
Assert.eq(shelf[1].stable_id, "9")
Assert.eq(#Mapper.shelf({}), 0)
Assert.eq(#Mapper.shelf({ worksIds = {} }), 0)
Assert.is_nil(Mapper.shelf({ worksIds = { "9" } }))
Assert.is_nil(Mapper.shelf({ error = "Nope" }))
Assert.is_nil(Mapper.shelf({ list = { { foo = 1 } } }))
Assert.eq(#Mapper.shelfIds({ worksIds = {} }), 0)
Assert.eq(Mapper.shelfIds({ worksIds = { "9" } })[1], "9")
Assert.eq(Mapper.shelfIds({ data = { user = { bookshelf = { libraryList = { list = { { worksId = "9" } } } } } } })[1], "9")
Assert.is_nil(Mapper.shelfIds({ error = "Nope" }))
local shelf_rows = Mapper.shelfWorks({
data = { worksList = { { id = "9", title = "书架书", author = { { name = "甲" } }, cover = "https://img/a.jpg" } } },
})
Assert.eq(shelf_rows[1].stable_id, "9")
Assert.eq(shelf_rows[1].title, "书架书")
Assert.eq(shelf_rows[1].authors, "甲")
Assert.eq(shelf_rows[1].cover, "https://img/a.jpg")
Assert.is_nil(Mapper.shelfWorks({ data = { worksList = { { id = "1", title = "听", isAudio = true } } } }))
Assert.eq(Mapper.readCsrf("CSRF_TOKEN = 'shelf-tok';"), "shelf-tok")
Assert.eq(Mapper.csrf('<meta name="csrf-token" content="tok123">'), "tok123")
local user = Mapper.user('Ark.user = {"id":"42","name":"读","isAnonymous":false}')
Assert.eq(user.id, "42")
Assert.eq(user.name, "读")
Assert.is_nil(Mapper.user('Ark.user = {"isAnonymous": true}'))
local ticket = Mapper.qr({ url = "/oidc/qrcode/confirm?code=abc", expires_in = 300 }, "https://accounts.arkread.com")
Assert.eq(ticket.qr, "https://accounts.arkread.com/oidc/qrcode/confirm?code=abc")
Assert.eq(ticket.code, "abc")
Assert.eq(Mapper.qrStatus({ confirmed = false }), "wait")
Assert.eq(Mapper.qrStatus({ confirmed = true }), "ok")
local progress = Mapper.progress({ r = 0, progress = { paragraph_id = 10, paragraph_offset = 0 } })
Assert.eq(progress.paragraph_id, "10")
Assert.eq(select(2, Mapper.progress({ r = 1 })), false)
Assert.eq(select(2, Mapper.progress({ progress = {} })), false)
Assert.eq(select(2, Mapper.progress({ r = 0 })), true)
Assert.eq(Mapper.firstParagraphId({
posts = { { contents = { { id = 3, type = "headline" }, { id = 4, type = "paragraph", data = { text = "正文" } } } } },
}), "4")
Assert.eq(Mapper.searchBody("三体").extensions.persistedQuery.sha256Hash, Mapper.SEARCH_HASH)
local requests = {}
local authorize_hits = 0
local deferred_requests, defer_column = false, false
local progress_write_body = Json.encode({ r = 0 })
package.preload["http.request"] = function()
return {
header = function(res, name)
local headers = res and res.headers or {}
for key, value in pairs(headers) do
if key:lower() == name:lower() then return value end
end
end,
headerAll = function(res, name)
local headers = res and res.headers or {}
local found = {}
for key, value in pairs(headers) do
if key:lower() == name:lower() and type(value) == "string" then found[#found + 1] = value end
end
return found
end,
request = function(opts, callback)
local request = { method = opts.method, url = opts.url, body = opts.body, headers = opts.headers }
requests[#requests + 1] = request
local res = { code = 200, body = "{}", headers = {} }
if opts.url:find("/j/search_v2", 1, true) then
res.body = Json.encode({ list = { { id = "594929245", title = "三体", author = { { name = "刘慈欣" } } } } })
elseif opts.url:find("/j/graphql", 1, true) and opts.body and opts.body:find(Mapper.ACCESS_HASH, 1, true) then
local works_id = opts.body:match('"worksId":"(%d+)"')
local reader = works_id == "699209652" and "/reader/column/73610846/chapter/699210556/" or "/reader/ebook/594929245/"
res.body = Json.encode({ data = { works = { readerUrl = reader } } })
elseif opts.url:find("/j/column/73610846/", 1, true) then
res.body = Json.encode({
type = "column", title = "如果爱", abstract = "简介", agent = { name = "茉莉多丁" },
chapters = { { id = "699210556", title = "第一章", is_free = true } },
})
elseif opts.body and opts.body:find(Mapper.INFO_HASH, 1, true) then
res.body = Json.encode({ data = { universalWorks = { id = "594929245", title = "三体", isColumn = false } } })
elseif opts.body and opts.body:find(Mapper.SHELF_WORKS_HASH, 1, true) then
res.body = Json.encode({
data = { worksList = { { id = "9", title = "书架书", author = { { name = "甲" } }, cover = "https://img/a.jpg" } } },
})
elseif opts.url:find("get_reader_data", 1, true) then
res.body = Json.encode({ r = 0, data = seal(nil), readerDataVersion = "v24" })
elseif opts.url:find("/oidc/login", 1, true) then
res.code = 302
res.headers.Location = "https://accounts.arkread.com/oauth2/authorize?client_id=public"
elseif opts.url:find("/oauth2/authorize", 1, true) then
authorize_hits = authorize_hits + 1
if authorize_hits == 1 then
res.body = '<meta name="csrf-token" content="tok123">Ark.user = {"isAnonymous": true}'
else
res.code = 302
res.headers.Location = "https://read.douban.com/"
end
elseif opts.url:find("/oidc/qrcode/generate", 1, true) then
if opts.headers.Referer ~= "https://accounts.arkread.com/" then
res.code = 400
res.body = Json.encode({ code = 1002, message = "The referrer header is missing." })
else
res.body = Json.encode({ url = "/oidc/qrcode/confirm?code=abc", expires_in = 300 })
end
elseif opts.url:find("/oidc/qrcode/status", 1, true) then
if opts.headers.Referer ~= "https://accounts.arkread.com/" then
res.code = 400
res.body = Json.encode({ code = 1002, message = "The referrer header is missing." })
else
res.body = Json.encode({ confirmed = false })
end
elseif opts.url == "https://read.douban.com/" then
res.body = 'CSRF_TOKEN = \'shelf-tok\'; Ark.user = {"id":"42","name":"读","isAnonymous":false}'
res.headers["Set-Cookie"] = "session=s1; Path=/"
elseif opts.url:find("/j/progress/", 1, true) and opts.method == "GET" then
res.body = Json.encode({ r = 0, progress = { paragraph_id = "10", paragraph_offset = 0 } })
elseif opts.url:find("/j/progress/", 1, true) then
res.body = progress_write_body
elseif opts.url:find("/j/reading_time", 1, true) then
res.body = ""
elseif opts.url:find("/annotations_by_paragraphs", 1, true) then
res.body = '['
.. '{"id":"1","note":"好看","startContainerId":"11","n_favorites":2,"owner":{"name":"甲"},"create_time":1700000000},'
.. '{"note":"","startContainerId":"10"}'
.. ']'
elseif opts.url:find("/j/bookshelf/folder/", 1, true) then
res.body = Json.encode({ folderIds = {} })
elseif opts.url:find("/j/bookshelf/", 1, true) and opts.method == "GET" then
res.body = Json.encode({ worksIds = { "9" } })
elseif opts.url:find("/j/bookshelf/", 1, true) then
res.body = Json.encode({ ok = true })
end
request.reply = function() callback(res, nil) end
if not deferred_requests and not (defer_column and opts.url:find("/j/column/", 1, true)) then
request.reply()
end
return { cancel = function() request.cancelled = true end }
end,
}
end
local Client = require("moonsource_douban.client")
local books
Client.searchAsync("三体", function(list) books = list end)
Assert.eq(books[1].title, "三体")
Assert.is_true(requests[#requests].body:find(Mapper.SEARCH_HASH, 1, true) ~= nil)
Assert.eq(requests[#requests].method, "POST")
local detail
Client.detailAsync("699209652", function(book) detail = book end)
Assert.eq(detail.title, "如果爱")
Assert.eq(detail.authors, "茉莉多丁")
Assert.eq(detail.stable_id, "699209652")
local ebook
Client.detailAsync("594929245", function(book) ebook = book end)
Assert.eq(ebook.title, "三体")
local toc_rows
Client.tocAsync("594929245", function(rows) toc_rows = rows end)
Assert.eq(toc_rows[1].title, "开篇")
local reader_hits = 0
for _idx, req in ipairs(requests) do
if req.url:find("get_reader_data", 1, true) then reader_hits = reader_hits + 1 end
end
Assert.eq(reader_hits, 1)
local text
Client.textAsync("594929245", 10, 12, function(value) text = value end)
Stubs.flush()
Assert.eq(text, "标题\n第一段")
local reader_hits_after = 0
for _idx, req in ipairs(requests) do
if req.url:find("get_reader_data", 1, true) then reader_hits_after = reader_hits_after + 1 end
end
Assert.eq(reader_hits_after, 1)
local denied
Client.shelfAsync(function(_rows, err) denied = err end)
Stubs.flush()
Assert.eq(denied, "未登录豆瓣阅读")
local ticket
local login = Client.newLogin()
login:beginQrAsync(function(value) ticket = value end)
Assert.eq(ticket.code, "abc")
Assert.eq(ticket.qr, "https://accounts.arkread.com/oidc/qrcode/confirm?code=abc")
Assert.eq(ticket.authorize, "https://accounts.arkread.com/oauth2/authorize?client_id=public")
Assert.eq(requests[#requests].headers["X-CSRF-Token"], "tok123")
local waiting
login:qrStatusAsync("abc", function(kind) waiting = kind end)
Assert.eq(waiting, "wait")
local logged
login:finishQrAsync(ticket.authorize, function(value) logged = value end)
Assert.eq(logged.id, "42")
Assert.eq(cfg.logged_in, true)
Assert.eq(cfg.user_id, "42")
Assert.eq(cfg.name, "读")
Assert.is_true(cfg.cookie:find("session=s1", 1, true) ~= nil)
local shelf_books
Client.shelfAsync(function(list) shelf_books = list end)
Assert.eq(shelf_books[1].title, "书架书")
Assert.eq(shelf_books[1].authors, "甲")
Assert.eq(requests[#requests].headers["X-CSRF-Token"], "shelf-tok")
Assert.is_true(requests[#requests].body:find(Mapper.SHELF_WORKS_HASH, 1, true) ~= nil)
local added
Client.addAsync("9", function(ok) added = ok end)
Assert.eq(added, true)
Assert.eq(requests[#requests].method, "POST")
Assert.is_true(requests[#requests].body:find("9", 1, true) ~= nil)
local removed
Client.removeAsync("9", function(ok) removed = ok end)
Assert.eq(removed, true)
Assert.eq(requests[#requests].method, "DELETE")
local progress_mark
Client.progressAsync("9", function(value) progress_mark = value end)
Assert.eq(progress_mark.paragraph_id, "10")
Assert.is_true(requests[#requests].url:find("works_id=9", 1, true) ~= nil)
local progress_saved
Client.putProgressAsync("9", "10", 2, 4, true, function(ok) progress_saved = ok end)
Assert.eq(progress_saved, true)
Assert.eq(requests[#requests].method, "POST")
Assert.is_true(requests[#requests].url:find("/j/progress/", 1, true) ~= nil)
Assert.is_true(requests[#requests].body:find("percentage=25", 1, true) ~= nil)
Assert.eq(requests[#requests].headers["Content-Type"], "application/x-www-form-urlencoded")
local progress_failure
progress_write_body = Json.encode({ r = 1 })
Client.putProgressAsync("9", "10", 2, 4, true, function(ok, err)
progress_saved, progress_failure = ok, err
end)
Assert.is_nil(progress_saved)
Assert.eq(progress_failure, "豆瓣阅读进度保存失败")
progress_write_body = "<html>upstream error</html>"
Client.putProgressAsync("9", "10", 2, 4, true, function(ok, err)
progress_saved, progress_failure = ok, err
end)
Assert.is_nil(progress_saved)
Assert.eq(progress_failure, "豆瓣阅读进度保存失败")
progress_write_body = Json.encode({ r = 0 })
local reading_saved
Client.pushReadingAsync({
{ worksId = 9, beginTime = "2020-01-01T00:00:00.000Z", endTime = "2020-01-01T00:01:00.000Z" },
}, function(ok) reading_saved = ok end)
Assert.eq(reading_saved, true)
Assert.is_true(requests[#requests].url:find("/j/reading_time", 1, true) ~= nil)
Assert.is_true(requests[#requests].body:find("worksId", 1, true) ~= nil)
local noted
Client.annotationsAsync("594929245", { "10", "11" }, function(rows) noted = rows end)
Assert.eq(#noted, 2)
Assert.eq(requests[#requests].method, "POST")
Assert.is_true(requests[#requests].url:find("/j/article_v2/594929245/annotations_by_paragraphs", 1, true) ~= nil)
Assert.eq(requests[#requests].body, "paragraph_ids=10%2C11")
Assert.eq(Mapper.reviewHotspots(noted, { "10", "11" })[1].range, "2")
cfg.cookie, cfg.logged_in, cfg.user_id = nil, nil, nil
Client.reset()
local cached_article
Client.articleAsync("cached", function(value) cached_article = value end)
Assert.is_true(cached_article ~= nil)
local cache_calls = 0
local cache_job = Client.articleAsync("cached", function() cache_calls = cache_calls + 1 end)
Assert.eq(cache_calls, 0)
cache_job.cancel()
Stubs.flush()
Assert.eq(cache_calls, 0)
Client.articleAsync("cached", function() cache_calls = cache_calls + 1 end)
Stubs.flush()
Assert.eq(cache_calls, 1)
deferred_requests = true
for _idx, method in ipairs({ "detailAsync", "tocAsync" }) do
for cancel_at = 0, 1 do
local calls = 0
local job = Client[method]("699209652", function() calls = calls + 1 end)
local active = requests[#requests]
if cancel_at == 1 then
active.reply()
active = requests[#requests]
end
local count = #requests
job.cancel()
Assert.is_true(active.cancelled)
active.reply()
Stubs.flush()
Assert.eq(calls, 0)
Assert.eq(#requests, count)
end
end
deferred_requests, defer_column = false, true
local sync_calls = 0
local sync_job = Client.detailAsync("699209652", function() sync_calls = sync_calls + 1 end)
local second = requests[#requests]
sync_job.cancel()
Assert.is_true(second.cancelled)
second.reply()
Assert.eq(sync_calls, 0)
defer_column, deferred_requests = false, true
cfg.cookie, cfg.logged_in, cfg.user_id = "session=s1", true, "42"
for cancel_at = 0, 2 do
Client.reset()
local calls = 0
local job = Client.shelfAsync(function() calls = calls + 1 end)
local active = requests[#requests]
for _step = 1, cancel_at do
active.reply()
active = requests[#requests]
end
local count = #requests
job.cancel()
Assert.is_true(active.cancelled)
active.reply()
Assert.eq(calls, 0)
Assert.eq(#requests, count)
end
for cancel_at = 0, 2 do
authorize_hits = 0
local calls = 0
local job = Client.newLogin():beginQrAsync(function() calls = calls + 1 end)
local active = requests[#requests]
for _step = 1, cancel_at do
active.reply()
active = requests[#requests]
end
local count = #requests
job.cancel()
Assert.is_true(active.cancelled)
active.reply()
Assert.eq(calls, 0)
Assert.eq(#requests, count)
end
authorize_hits = 1
local finish_calls = 0
local finish_job = Client.newLogin():finishQrAsync("https://accounts.arkread.com/oauth2/authorize?client_id=public",
function() finish_calls = finish_calls + 1 end)
requests[#requests].reply()
local final = requests[#requests]
finish_job.cancel()
Assert.is_true(final.cancelled)
final.reply()
Assert.eq(finish_calls, 0)
+160
View File
@@ -0,0 +1,160 @@
--[[-- 豆瓣书评和章评:真实归属、分页、取消和独立缓存。 @module tests.moonsource_douban.community_spec --]]
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local JSON = require("support.json_stub")
package.loaded.json = JSON
local cfg = { cookie = "sid=test-private-cookie", user_id = "test-user", logged_in = true }
package.loaded["utils.settings"] = {
getSource = function() return cfg end, get = function() return {} end,
saveSource = function() end,
}
local connected, requests, mode = true, {}, "ok"
---@type {cb: fun(res: table), request: table}|nil
local pending
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
local function wire(offset, chapter)
local rows = {}
for index = offset + 1, math.min(offset + 20, 21) do
rows[#rows + 1] = { id = tostring(index), content = "<p>Review<br>text</p>",
createTime = "2025-01-01T12:00:00Z", commentType = chapter and "Discussion" or "Review",
works = { isChapter = chapter ~= nil, id = chapter or "101" },
user = { name = "Reader" }, upvoteCount = 2 }
end
return { data = { works = { comments = { total = 21, list = rows } } } }
end
package.loaded["http.request"] = {
header = function() return nil end,
headerAll = function() return {} end,
request = function(opts, cb)
local request = { opts = opts }
requests[#requests + 1] = request
if opts.method == "GET" then
cb({ code = 200, headers = {}, body = "CSRF_TOKEN = 'test-csrf'" })
return { cancel = function() request.cancelled = true end }
end
local body = JSON.decode(opts.body)
if body.extensions.persistedQuery.sha256Hash:find("bf9257", 1, true) then
cb({ code = 200, headers = {}, body = JSON.encode({
data = { works = { readerUrl = "/reader/column/777/chapter/11/" } },
}) })
elseif mode == "wait" then
pending = { cb = cb, request = request }
elseif mode == "fail" then cb(nil, "network failed")
else
local result = wire(body.variables.start, body.variables.chapterId)
if mode == "wrong-chapter" then result.data.works.comments.list[1].works.id = "other" end
cb({ code = 200, headers = {}, body = JSON.encode(result) })
end
return { cancel = function() request.cancelled = true end }
end,
}
local Client = require("moonsource_douban.client")
local Mapper = require("moonsource_douban.mapper")
local source = require("moonsource_douban.source").new()
function source:loadTocAsync(_identity, cb)
cb({ { uid = "11", idx = 1, title = "One" }, { uid = "22", idx = 2, title = "Two" } })
return { cancel = function() end }
end
local page, err
source:bookReviewsAsync({ source_id = "ext.douban", stable_id = "101" }, function(value, reason)
page, err = value, reason
end)
Assert.is_nil(err)
Assert.len(page.items, 20)
Assert.matches(page.items[1].text, "Review")
Assert.is_false(page.items[1].text:find("<p>", 1, true) ~= nil)
Assert.is_nil(requests[1].opts.headers.Cookie)
Assert.eq(JSON.decode(requests[1].opts.body).variables.worksId, "101")
local identity = { source_id = "ext.douban", stable_id = "101", chapter_idx = 1 }
source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end)
Assert.is_nil(err)
Assert.len(page.items, 20)
Assert.eq(page.max_idx, 20)
Assert.is_true(page.more)
local body = JSON.decode(requests[#requests].opts.body)
Assert.eq(body.variables.columnId, "777", "专栏 ID 不等于作品 ID")
Assert.eq(body.variables.chapterId, "11")
Assert.is_nil(body.variables.worksId)
Assert.is_nil(requests[#requests].opts.headers.Cookie)
source:paragraphReviewPageAsync(identity, "chapter", 20, function(value, reason) page, err = value, reason end)
Assert.is_nil(err)
Assert.len(page.items, 1)
Assert.eq(page.max_idx, 21)
Assert.is_false(page.more)
Assert.eq(requests[#requests].opts.headers.Cookie, "sid=test-private-cookie")
Assert.eq(requests[#requests].opts.headers["X-CSRF-Token"], "test-csrf")
cfg.logged_in = false
local request_count = #requests
Client.communityAsync("101", "11", 20, function(value, reason) page, err = value, reason end)
Stubs.flush()
Assert.is_nil(page)
Assert.eq(err, "请先登录豆瓣阅读")
Assert.eq(#requests, request_count, "未登录时后续页立即说明权限,不发无效请求")
cfg.logged_in = true
Client.communityAsync("101", "11", 40, function(value, reason) page, err = value, reason end)
Assert.is_nil(err)
Assert.len(page.items, 0)
Assert.is_false(page.more)
mode = "wrong-chapter"
source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end)
Assert.is_nil(page)
Assert.eq(err, "响应无效")
connected = false
source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end)
Stubs.flush()
Assert.is_nil(err)
Assert.len(page.items, 20, "坏响应没有覆盖本章缓存")
identity.chapter_idx = 2
source:paragraphReviewPageAsync(identity, "chapter", 0, function(value, reason) page, err = value, reason end)
Stubs.flush()
Assert.is_nil(page, "换章不读上一章缓存")
Assert.eq(err, "未联网,无法加载段评")
connected, mode = true, "wait"
local called = false
local job = Client.communityAsync("101", "22", 0, function() called = true end)
job.cancel()
Assert.is_true(pending.request.cancelled, "同步入口回调后取消的是评论请求")
pending.cb({ code = 200, headers = {}, body = JSON.encode(wire(0, "22")) })
Assert.is_false(called, "取消后忽略迟到评论")
mode = "fail"
Client.communityAsync("101", nil, 0, function(value, reason) page, err = value, reason end)
Assert.is_nil(page)
Assert.eq(err, "network failed")
for _idx, bad in ipairs({ {}, { errors = { { message = "bad" } } }, { errors = "bad" } }) do
local value, reason = Mapper.communityPage(bad, 0)
Assert.is_nil(value)
Assert.eq(reason, "响应无效")
end
local denied, reason = Mapper.communityPage({ errors = { { message = "AnonymousError" } } }, 20, "11")
Assert.is_nil(denied)
Assert.eq(reason, "请先登录豆瓣阅读")
for _idx, invalid_id in ipairs({ {}, "" }) do
local invalid = wire(0, "11")
invalid.data.works.comments.list[1].id = invalid_id
local value, id_err = Mapper.communityPage(invalid, 0, "11")
Assert.is_nil(value)
Assert.eq(id_err, "响应无效")
end
do
local Chapter = require("source.chapter")
local original_open, original_text = Chapter.openAsync, Client.textAsync
local chapter = { uid = "11", content_url = "11" }
local produced
cfg.show_paragraph_reviews = true
Client.textAsync = function(_aid, _start, _ending, cb)
cb("Original text")
return { cancel = function() end }
end
Chapter.openAsync = function(_source, ref, _book, _opts, ops, _cb)
return ops.fetchContent(ref, chapter, function(value) produced = value end)
end
source:openBookAsync(identity, { chapter_idx = 1 }, function() end)
Assert.matches(produced.html, 'id="moon%-chapter%-reviews"', "专栏正文给章評预留空间")
Assert.matches(produced.html, "Original text")
chapter.slice = true
source:openBookAsync(identity, { chapter_idx = 1 }, function() end)
Assert.is_nil(produced.html:find('id="moon-chapter-reviews"', 1, true),
"出版书没有章评入口,不增加空白区域")
Chapter.openAsync, Client.textAsync = original_open, original_text
end
+128
View File
@@ -0,0 +1,128 @@
--[[--
豆瓣登录会话:取消、坏跳转、换号和迟到响应不能污染有效账号。
@module tests.moonsource_douban.login_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Stubs = require("support.stubs")
package.preload["json"] = function() return require("support.json_stub") end
local cfg = { cookie = "session=old", logged_in = true, user_id = "42" }
local cleared = 0
package.loaded["source.logout"] = { clear = function(_id, clear)
clear(); cleared = cleared + 1; return true
end }
local requests, delayed, status, body, location = {}, false, 200, nil, nil
local next_status
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end, saveSource = function() end }
end
package.preload["http.request"] = function()
return {
headerAll = function() return { "session=new; Path=/; Secure; HttpOnly" } end,
header = function() return location end,
request = function(opts, cb)
local req = { opts = opts }
requests[#requests + 1] = req
local res = { code = status, body = body or 'Ark.user = {"id":"42","isAnonymous":false,"name":"测试"}' }
status, next_status = next_status or status, nil
req.reply = function() cb(res, status == 0 and "network failed" or nil) end
if not delayed then req.reply() end
return { cancel = function() req.cancelled = true end }
end,
}
end
local Client = require("moonsource_douban.client")
Client.load()
local ok, err
local function signIn(cookie, cb)
local login = Client.newLogin(cookie)
return login:checkCookieAsync(function(valid, reason, user)
if valid then valid, reason = login:commit(user) end
cb(valid == true, reason)
end)
end
Client.newLogin("session=pasted"):checkCookieAsync(function(valid, reason, user)
Assert.is_true(valid)
Assert.is_nil(reason)
Assert.eq(user.id, "42")
Assert.eq(cfg.cookie, "session=old", "校验候选不写当前登录")
end)
signIn("session=pasted", function(value, reason) ok, err = value, reason end)
Assert.is_true(ok)
Assert.eq(cfg.cookie, "session=new")
Assert.is_nil(cfg.cookie:find("Path", 1, true))
Assert.is_nil(cfg.cookie:find("HttpOnly", 1, true))
Assert.eq(requests[1].opts.headers.Cookie, "session=pasted")
body = 'Ark.user = {"id":"99","isAnonymous":false}'
signIn("session=other", function(value, reason) ok, err = value, reason end)
Assert.is_true(ok)
Assert.is_nil(err)
Assert.eq(cfg.user_id, "99")
Assert.eq(cleared, 1)
Assert.eq(cfg.cookie, "session=new")
status, body = 0, nil
signIn("session=bad", function(value, reason) ok, err = value, reason end)
Assert.eq(ok, false)
Assert.eq(err, "network failed")
Assert.eq(cfg.logged_in, true)
status, location = 302, "https://untrusted.invalid/collect"
local before = #requests
signIn("session=bad", function(value, reason) ok, err = value, reason end)
Stubs.flush()
Assert.eq(ok, false)
Assert.eq(#requests, before + 1)
Assert.eq(cfg.cookie, "session=new")
status, location, next_status = 302, "https://accounts.arkread.com/oidc/login", 200
signIn("session=bad", function(value, reason) ok, err = value, reason end)
status, location = 200, nil
Stubs.flush()
Assert.eq(ok, false)
Assert.eq(cfg.cookie, "session=new")
body = 'Ark.user = {"id":"","isAnonymous":false}'
signIn("session=bad", function(value) ok = value end)
Assert.eq(ok, false)
body = 'Ark.user = {"id":{},"isAnonymous":false}'
signIn("session=bad", function(value) ok = value end)
Assert.eq(ok, false)
body = nil
status, location, delayed = 200, nil, true
local calls = 0
local login = Client.newLogin("session=cancel")
local job = login:checkCookieAsync(function() calls = calls + 1 end)
job.cancel()
login:cancel()
requests[#requests].reply()
Assert.eq(calls, 0)
Assert.eq(cfg.cookie, "session=new")
local stale = Client.newLogin("session=stale")
stale:checkCookieAsync(function(value, reason) ok, err = value, reason end)
local old = requests[#requests]
delayed = false
signIn("session=recent", function(value) Assert.is_true(value) end)
old.reply()
Assert.eq(ok, false)
Assert.eq(err, "登录状态已变化,请重试")
Assert.eq(cfg.cookie, "session=new")
cfg.user_id = nil
signIn("session=migration", function(value, reason) ok, err = value, reason end)
Assert.is_true(ok)
Assert.is_nil(err)
Assert.eq(cfg.user_id, "42", "旧配置缺用户标识也直接换号")
package.loaded["source.registry"] = { reload = function() end }
local Setting = require("moonsource_douban.setting")
Setting.browser.apply({ cookies = { { domain = ".douban.com", name = "session", value = "browser" } } },
function(value, reason) ok, err = value, reason end)
Assert.is_true(ok, "浏览器校验与提交分阶段,不误判正常登录为账号已变化")
Assert.is_nil(err)
Assert.eq(cfg.user_id, "42")
+176
View File
@@ -0,0 +1,176 @@
--[[--
豆瓣短信登录协议及输入窗口生命周期。
@module tests.moonsource_douban.phone_login_spec
--]]
---@diagnostic disable: undefined-field, missing-fields
local Assert = require("support.assert")
local Json = require("support.json_stub")
local Themed = require("support.theme_stubs")
local cfg, requests = {}, {}
local deferred, verified, transfer, broken, network_error = false, false, false, false, false
local phone = "+8600000000000"
package.preload["json"] = function() return Json end
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end, saveSource = function() end, get = function() return {} end }
end
package.preload["http.request"] = function()
return {
header = function(res, name) return res.headers[name] end,
headerAll = function(res, name) return res.headers[name] and { res.headers[name] } or {} end,
request = function(opts, cb)
local req = { opts = opts }
requests[#requests + 1] = req
local res = { code = 200, headers = {}, body = "{}" }
if opts.url:find("/oidc/login", 1, true) then
res.code, res.headers.Location = 302, "https://accounts.arkread.com/oauth2/authorize?client_id=test"
elseif opts.url:find("/oauth2/authorize", 1, true) then
if verified then res.code, res.headers.Location = 302, "https://read.douban.com/"
else
res.body = '<meta name="csrf-token" content="csrf-test">'
res.headers["Set-Cookie"] = "candidate=test; Path=/"
end
elseif opts.url:find("/phone/verify_code", 1, true) then
res.body = broken and "{}" or Json.encode({ retry_after = 60 })
elseif opts.url:find("/phone/verify", 1, true) then
if broken then
res.code, res.body = 400, Json.encode({ code = 1001, message = "invalid code" })
elseif transfer then res.body = Json.encode({ transfer_info = { user_type = 0 } })
else verified = true end
elseif opts.url == "https://read.douban.com/" then
res.body = 'Ark.user={"id":"42","name":"测试","isAnonymous":false}'
res.headers["Set-Cookie"] = "session=test; Path=/"
end
req.reply = function() cb(not network_error and res or nil, network_error and "network failed" or nil) end
if not deferred then req.reply() end
return { cancel = function() req.cancelled = true end }
end,
}
end
local Client = require("moonsource_douban.client")
local session = Client.newLogin()
local ready, wait, user, failure
session:beginAsync(function(authorize, err) ready, failure = authorize ~= nil, err end)
Assert.is_true(ready)
Assert.is_nil(failure)
session:sendPhoneCodeAsync(phone, function(value, err) wait, failure = value, err end)
Assert.eq(wait, 60)
Assert.is_nil(failure)
local sent = requests[#requests].opts
Assert.eq(Json.decode(sent.body).phone_number, phone)
Assert.eq(sent.headers.Referer, "https://accounts.arkread.com/")
Assert.eq(sent.headers["X-CSRF-Token"], "csrf-test")
Assert.eq(sent.headers.Cookie, "candidate=test")
Assert.eq(sent.cache_ttl, 0)
broken = true
session:sendPhoneCodeAsync(phone, function(value, err) wait, failure = value, err end)
Assert.is_nil(wait)
Assert.eq(failure, "响应无效")
session:verifyPhoneAsync(phone, "000001", function(value, err) user, failure = value, err end)
Assert.is_nil(user)
Assert.eq(failure, "invalid code")
Assert.is_nil(cfg.cookie)
broken, transfer = false, true
session:verifyPhoneAsync(phone, "000001", function(value, err) user, failure = value, err end)
Assert.is_nil(user)
Assert.is_true(failure:find("历史数据授权", 1, true) ~= nil)
Assert.is_nil(cfg.cookie)
transfer = false
session:verifyPhoneAsync(phone, "000001", function(value, err) user, failure = value, err end)
Assert.eq(user.id, "42")
Assert.is_nil(failure)
Assert.is_true(Client.loggedIn())
Assert.eq(cfg.cookie, "session=test")
for cancel_at = 0, 2 do
cfg, verified, deferred = {}, false, false
Client.reset()
session = Client.newLogin()
session:beginAsync(function() end)
deferred = true
local calls = 0
local job = session:verifyPhoneAsync(phone, "000001", function() calls = calls + 1 end)
for _step = 1, cancel_at do requests[#requests].reply() end
local current = requests[#requests]
job.cancel()
Assert.is_true(current.cancelled)
current.reply()
Assert.eq(calls, 0)
Assert.is_nil(cfg.cookie)
session:cancel()
end
deferred, verified, cfg = false, false, {}
Client.reset()
session = Client.newLogin()
session:beginAsync(function() end)
network_error = true
session:sendPhoneCodeAsync(phone, function(value, err) wait, failure = value, err end)
Assert.is_nil(wait)
Assert.eq(failure, "network failed")
Themed.install()
local pending, submitted, connected = {}, {}, true
package.loaded["moonsource_douban.client"] = {
newLogin = function()
local candidate = {}
function candidate:beginAsync(cb)
self.authorize = "https://accounts.arkread.com/oauth2/authorize"
cb(self.authorize)
return { cancel = function() end }
end
function candidate:sendPhoneCodeAsync(number, cb)
submitted[#submitted + 1] = number
pending.send = cb
return { cancel = function() pending.cancelled = true end }
end
function candidate:verifyPhoneAsync(number, code, cb)
submitted[#submitted + 1] = number .. ":" .. code
pending.verify = cb
return { cancel = function() pending.cancelled = true end }
end
function candidate:cancel() self.cancelled = true end
return candidate
end,
}
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
local PhoneLogin = require("moonsource_douban.phone_login")
local logins = 0
local dialog = PhoneLogin:new(function() logins = logins + 1 end)
dialog:start()
local input = Themed.last("input")
Assert.is_true(input.keep_open)
Assert.eq(input.fields[1].text, "+86")
input.actions[1].callback("+86", "invalid")
Assert.eq(#submitted, 0)
connected = false
input.actions[1].callback("+86", "00000000000")
Assert.eq(#submitted, 0)
connected = true
input.actions[1].callback("+86", "00000000000")
Assert.eq(submitted[1], phone)
pending.send(60)
Assert.eq(Themed.last("toast").text, "验证码已发送")
input.actions[1].callback("+86", "00000000000")
Assert.eq(#submitted, 1)
dialog:verify("+86", "different", "000001")
Assert.eq(#submitted, 1)
input.callback("+86", "00000000000", "000001")
Assert.eq(#submitted, 1)
Themed.last("confirm").ok_callback()
Assert.eq(submitted[2], phone .. ":000001")
input.cancel_callback()
Assert.is_true(pending.cancelled)
pending.verify({ id = "42" })
Assert.eq(logins, 0)
Assert.is_true(dialog.session.cancelled)
pending = {}
dialog = PhoneLogin:new(function() logins = logins + 1 end)
dialog:start()
dialog:send("+86", "00000000000")
pending.send(0)
dialog:verify("+86", "00000000000", "000001")
pending.verify({ id = "42" })
Assert.eq(logins, 1)
Assert.is_true(dialog.dialog.closed)
+65
View File
@@ -0,0 +1,65 @@
--[[--
豆瓣进度按正文分段索引上传;专栏只写章节 article,不伪造整部作品进度。
@module tests.moonsource_douban.progress_spec
--]]
---@diagnostic disable: undefined-field, missing-fields
local Assert = require("support.assert")
package.preload["json"] = function() return require("support.json_stub") end
local Mapper = require("moonsource_douban.mapper")
local article = { posts = {
{ contents = { { type = "illus", id = 8 }, { type = "headline", id = 10 }, { type = "paragraph", id = 11, data = { text = "甲" } } } },
{ contents = { { type = "pagebreak", id = 20 }, { type = "paragraph", id = 22, data = { text = "乙" } } } },
} }
local position = Mapper.progressPosition(article, "22")
Assert.eq(position.part_sequence, 1)
Assert.eq(position.part_paragraph_sequence, 1)
Assert.eq(Mapper.progressPosition(article, "10").part_paragraph_sequence, 2)
Assert.is_nil(Mapper.progressPosition(article, "10", "11"))
Assert.is_nil(Mapper.progressPosition(article, "missing"))
local writes, fail_article = {}, false
package.preload["moonsource_douban.client"] = function()
return {
loggedIn = function() return true end,
articleAsync = function(_aid, cb)
cb(not fail_article and article or nil, fail_article and "network failed" or nil)
return { cancel = function() end }
end,
putProgressAsync = function(works_id, pid, _idx, _total, percentage, cb, actual)
writes[#writes + 1] = { works_id = works_id, pid = pid, percentage = percentage, position = actual }
cb(true)
return { cancel = function() end }
end,
}
end
local source = require("moonsource_douban.source").new()
local slice = false
function source:loadTocAsync(_identity, cb)
cb({
{ uid = "10", content_url = "200" },
{ uid = slice and "22" or "200", content_url = "200", slice = slice },
})
return { cancel = function() end }
end
local ok, failure
source:putProgressAsync({ stable_id = "book", chapter_idx = 2 }, {}, function(value, err) ok, failure = value, err end)
Assert.is_true(ok)
Assert.is_nil(failure)
Assert.eq(#writes, 1)
Assert.eq(writes[1].works_id, "200")
Assert.eq(writes[1].pid, "11")
Assert.eq(writes[1].position.part_sequence, 0)
Assert.eq(writes[1].position.part_paragraph_sequence, 2)
Assert.eq(writes[1].percentage, false)
slice = true
source:putProgressAsync({ stable_id = "ebook", chapter_idx = 2 }, {}, function(value) ok = value end)
Assert.eq(writes[2].works_id, "ebook")
Assert.eq(writes[2].pid, "22")
Assert.eq(writes[2].position.part_paragraph_sequence, 1)
Assert.is_true(writes[2].percentage)
fail_article = true
source:putProgressAsync({ stable_id = "ebook", chapter_idx = 2 }, {}, function(value, err) ok, failure = value, err end)
Assert.is_nil(ok)
Assert.eq(failure, "network failed")
Assert.eq(#writes, 2)
+58
View File
@@ -0,0 +1,58 @@
--[[--
豆瓣扫码窗口:同步前段回调不能覆盖在途句柄,关闭后不再登录。
@module tests.moonsource_douban.qrlogin_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Themed = require("support.theme_stubs")
Themed.install()
local pending, session, calls = nil, nil, 0
package.preload["moonsource_douban.client"] = function()
return {
newLogin = function()
session = {
cancel = function(self) self.cancelled = true end,
beginQrAsync = function(_self, cb)
cb({ qr = "https://accounts.arkread.com/oidc/qrcode/confirm?code=test", code = "test",
authorize = "https://accounts.arkread.com/oauth2/authorize", expires_in = 300 })
return { cancel = function() end }
end,
qrStatusAsync = function(_self, code, cb)
Assert.eq(code, "test")
pending = { callback = cb }
return { cancel = function() pending.cancelled = true end }
end,
finishQrAsync = function(_self, _authorize, cb)
cb({ id = "test", name = "测试" })
return { cancel = function() end }
end,
}
return session
end,
}
end
local QRLogin = require("moonsource_douban.qrlogin")
local login = QRLogin:new(function() calls = calls + 1 end)
login:start()
local dialog = Themed.last("qr")
Assert.is_true(dialog.shown)
dialog:close()
Assert.is_true(pending.cancelled)
Assert.is_true(session.cancelled)
pending.callback("ok")
Assert.eq(calls, 0)
login:start()
dialog = Themed.last("qr")
pending.callback("ok")
Assert.eq(calls, 1)
Assert.is_true(dialog.closed)
Assert.eq(#Themed.all("toast"), 1)
login:start()
pending.callback(nil, "network failed")
Assert.eq(Themed.last("confirm").text, "network failed")
Assert.is_true(Themed.last("qr").closed)
Assert.eq(calls, 1)
+57
View File
@@ -0,0 +1,57 @@
--[[--
豆瓣段评的取消、同步正文回调和坏响应。
@module tests.moonsource_douban.reviews_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local pending, calls = nil, 0
package.preload["moonsource_douban.client"] = function()
return {
articleAsync = function(_aid, cb)
cb({ posts = { { contents = { { type = "paragraph", id = 10, data = { text = "测试段落" } } } } } })
return { cancel = function() end }
end,
annotationsAsync = function(_aid, _pids, cb)
pending = { callback = cb }
return { cancel = function() pending.cancelled = true end }
end,
}
end
package.preload["json"] = function() return require("support.json_stub") end
local Reviews = require("moonsource_douban.reviews")
local job = Reviews.hotspotsAsync({ content_url = "test" }, function() calls = calls + 1 end)
job.cancel()
Assert.is_true(pending.cancelled)
pending.callback({ { note = "测试批注", startContainerId = "10" } })
Assert.eq(calls, 0)
local result, err
Reviews.pageAsync({ content_url = "test" }, "1", function(value, reason) result, err = value, reason end)
pending.callback(nil, "network failed")
Assert.is_nil(result)
Assert.eq(err, "network failed")
Reviews.pageAsync({ content_url = "test" }, "1", function(value) result = value end)
pending.callback({})
Assert.eq(#result.items, 0)
Assert.eq(result.more, false)
local source = require("moonsource_douban.source").new()
function source:loadTocAsync(_identity, cb)
cb({ { content_url = "test" } })
return { cancel = function() end }
end
for _idx, method in ipairs({ "paragraphHotspotsAsync", "paragraphReviewPageAsync" }) do
local identity = { source_id = "ext.douban", stable_id = "test", chapter_idx = 1 }
local handle
if method == "paragraphHotspotsAsync" then
handle = source:paragraphHotspotsAsync(identity, function() calls = calls + 1 end)
else
handle = source:paragraphReviewPageAsync(identity, "1", 1, function() calls = calls + 1 end)
end
handle.cancel()
Assert.is_true(pending.cancelled)
pending.callback({})
Assert.eq(calls, 0)
end
+42
View File
@@ -0,0 +1,42 @@
--[[--
豆瓣设置开关必须重绘当前桌面,不能只写配置后留着旧的开关状态。
@module tests.moonsource_douban.setting_spec
--]]
local Assert = require("support.assert")
local cfg, saved, refreshed = {}, 0, 0
package.preload["utils.settings"] = function()
return {
getSource = function() return cfg end,
saveSource = function() saved = saved + 1 end,
get = function() return {} end,
}
end
package.preload["moonsource_douban.client"] = function() return { loggedIn = function() return false end } end
package.preload["ui.themes.widgets.row"] = function() return { widget = function(opts) return opts end } end
local Setting = require("moonsource_douban.setting")
local plugin = { desktop = { updateView = function() refreshed = refreshed + 1 end } }
local function find(title)
for _idx, factory in ipairs(Setting.rows(plugin)) do
local row = factory(540)
if row.title == title then return row end
end
error("setting row missing: " .. title)
end
local row = find("显示段评")
Assert.eq(row.status, "关")
row.callback()
Assert.is_true(cfg.show_paragraph_reviews)
Assert.eq(refreshed, 1)
row = find("显示段评")
Assert.eq(row.status, "开")
row.callback()
Assert.eq(cfg.show_paragraph_reviews, false)
Assert.eq(refreshed, 2)
row = find("使用自定义分组代替分类")
Assert.eq(row.status, "开")
row.callback()
Assert.eq(cfg.category_as_group, false)
Assert.eq(refreshed, 3)
Assert.eq(find("使用自定义分组代替分类").status, "关")
Assert.eq(saved, 3)
+135
View File
@@ -0,0 +1,135 @@
--[[--
豆瓣书架分组、分类口径和多阶段取消。
@module tests.moonsource_douban.shelf_spec
--]]
---@diagnostic disable: undefined-field, missing-fields
local Assert = require("support.assert")
local Json = require("support.json_stub")
local cfg = { logged_in = true, user_id = "42", cookie = "session=test" }
package.preload["json"] = function() return Json end
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end, get = function() return {} end }
end
local Mapper = require("moonsource_douban.mapper")
local folders = { data = { user = { bookshelf = { folders = { list = {
{ id = 20, name = "另一组", libraryList = { list = { { worksId = "1" }, { worksId = "3" } } } },
{ id = 10, name = "收藏", libraryList = { list = { { worksId = "1" } } } },
} } } } } }
local works = { data = { worksList = {
{ id = "1", title = "甲", isOrigin = true },
{ id = "2", title = "乙", isOrigin = false },
{ id = "3", title = "丙", kinds = { { shortName = "科幻" } } },
} } }
local groups = Mapper.shelfGroups(folders, { 10, 20 })
Assert.eq(groups["1"], "收藏")
Assert.eq(groups["3"], "另一组")
local books = Mapper.shelfWorks(works, groups, { "1", "2", "3" })
Assert.eq(books[1].category, "收藏")
Assert.is_nil(books[2].category)
Assert.is_true(books[2].category_authoritative)
Assert.eq(books[3].category, "另一组")
cfg.category_as_group = false
books = Mapper.shelfWorks(works, groups)
Assert.eq(books[1].category, "原创")
Assert.eq(books[2].category, "出版")
Assert.eq(books[3].category, "科幻")
cfg.category_as_group = nil
Assert.is_nil(Mapper.folderIds({ folderIds = { "10", false } }))
Assert.is_nil(Mapper.folderIds({ folderIds = { unexpected = true } }))
Assert.is_nil(Mapper.folderIds({}))
Assert.eq(#Mapper.folderIds({ folderIds = {} }), 0)
Assert.is_nil(Mapper.shelfGroups(folders, { 10, 30 }))
Assert.is_nil(Mapper.shelfGroups({ errors = { { message = "denied" } }, data = folders.data }, { 10, 20 }))
Assert.is_nil(Mapper.shelfGroups({ data = { user = { bookshelf = { folders = { list = {
{ id = 10, name = "收藏", libraryList = {} },
} } } } } }, { 10 }))
Assert.is_nil(Mapper.shelfWorks({ errors = { { message = "partial" } }, data = works.data }, groups))
Assert.is_nil(Mapper.shelfWorks(works, groups, { "1", "missing" }))
Assert.is_nil(Mapper.shelfIds({ worksIds = { "1", false } }))
local BookDB = require("book.books_db")
Assert.is_true(BookDB.upsertRemote({ source_id = "ext.douban", stable_id = "2", title = "乙", category = "旧题材" }))
Assert.is_true(BookDB.upsertRemote(Mapper.shelfWorks(works, groups)[2]))
Assert.is_nil(BookDB.get("ext.douban", "2").category)
local requests, deferred, defer_works = {}, false, false
local folder_wire, folder_error = { folderIds = { 10, 20 } }, nil
package.preload["http.request"] = function()
return {
header = function() end, headerAll = function() return {} end,
request = function(opts, cb)
local req = { opts = opts }
requests[#requests + 1] = req
local wire, body, err
if opts.url == "https://read.douban.com/" then body = "CSRF_TOKEN='test';"
elseif opts.url:find("/folder/", 1, true) then wire, err = folder_wire, folder_error
elseif opts.url:find("/j/bookshelf/", 1, true) then wire = { worksIds = { "1", "2", "3" } }
else
local payload = Json.decode(opts.body)
wire = payload.extensions.persistedQuery.sha256Hash == Mapper.SHELF_FOLDERS_HASH and folders or works
end
req.reply = function() cb(not err and { code = 200, body = body or Json.encode(wire) } or nil, err) end
if not deferred and not (defer_works and opts.body and opts.body:find(Mapper.SHELF_WORKS_HASH, 1, true)) then
req.reply()
end
return { cancel = function() req.cancelled = true end }
end,
}
end
local Client = require("moonsource_douban.client")
local result, failure
Client.shelfAsync(function(rows, err) result, failure = rows, err end)
Assert.eq(#result, 3)
Assert.is_nil(failure)
Assert.eq(result[1].category, "收藏")
for _idx, req in ipairs(requests) do
Assert.is_true(req.opts.method == "GET" or req.opts.url == "https://read.douban.com/j/graphql")
end
cfg.category_as_group, requests = false, {}
Client.shelfAsync(function(rows) result = rows end)
Assert.eq(result[1].category, "原创")
Assert.eq(#requests, 2)
cfg.category_as_group = nil
folder_wire = { folderIds = {} }
Client.shelfAsync(function(rows) result = rows end)
Assert.is_nil(result[1].category)
folder_wire = {}
Client.shelfAsync(function(rows, err) result, failure = rows, err end)
Assert.is_nil(result)
Assert.is_true(failure ~= nil)
folder_error = "network failed"
Client.shelfAsync(function(rows, err) result, failure = rows, err end)
Assert.is_nil(result)
Assert.eq(failure, "network failed")
folder_error, folder_wire, deferred = nil, { folderIds = { 10, 20 } }, true
for cancel_at = 0, 4 do
Client.reset()
local calls = 0
local job = Client.shelfAsync(function() calls = calls + 1 end)
for _step = 1, cancel_at do requests[#requests].reply() end
local current, count = requests[#requests], #requests
job.cancel()
Assert.is_true(current.cancelled)
current.reply()
Assert.eq(calls, 0)
Assert.eq(#requests, count)
end
deferred, defer_works = false, true
Client.reset()
local calls = 0
local job = Client.shelfAsync(function() calls = calls + 1 end)
local pending = requests[#requests]
job.cancel()
Assert.is_true(pending.cancelled)
pending.reply()
Assert.eq(calls, 0)
deferred, defer_works = true, false
job = Client.shelfAsync(function(rows, err) result, failure = rows, err end)
cfg.cookie = "session=other"
requests[#requests].reply()
Assert.is_nil(result)
Assert.eq(failure, "登录状态已变化,请重试")
job.cancel()
+82
View File
@@ -0,0 +1,82 @@
--[[--
豆瓣阅读时长:秒级账户快照、日期窗口、重复同步和本地未上传时长。
@module tests.moonsource_douban.stats_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
package.preload["json"] = function() return require("support.json_stub") end
local Mapper = require("moonsource_douban.mapper")
local StatsDB = require("book.stats_db")
local now = os.time({ year = 2026, month = 11, day = 7, hour = 15 })
local wire = { data = { user = {
readingTimeTotal = { duration = 7200, normalDuration = 6000, textToSpeechDuration = 1200 },
readingTimeHistory = {
{ date = "2026-11-06", readingTime = { duration = 600 } },
{ date = "2026-11-07", readingTime = { duration = 1200 } },
},
} } }
local snapshot = Mapper.readingStats(wire, "2026-10-09", now)
Assert.eq(#snapshot.rows, 3)
Assert.eq(snapshot.rows[1].record_type, "total")
Assert.eq(snapshot.rows[1].duration, 7200)
Assert.eq(snapshot.rows[1].event_count, 0)
Assert.eq(snapshot.rows[2].duration, 600)
Assert.is_nil(Mapper.readingStats({ errors = { { message = "failed" } } }, "2026-10-09", now))
wire.errors = { { message = "partial response" } }
Assert.is_nil(Mapper.readingStats(wire, "2026-10-09", now))
wire.errors = nil
wire.data.user.readingTimeHistory[2].date = "2026-02-30"
Assert.is_nil(Mapper.readingStats(wire, "2026-10-09", now))
wire.data.user.readingTimeHistory[2].date = "2026-11-06"
Assert.is_nil(Mapper.readingStats(wire, "2026-10-09", now))
wire.data.user.readingTimeHistory[2].date = "2026-11-07"
wire.data.user.readingTimeHistory[2].readingTime.duration = -1
Assert.is_nil(Mapper.readingStats(wire, "2026-10-09", now))
wire.data.user.readingTimeHistory[2].readingTime.duration = 1200
Assert.is_true(StatsDB.removeSource("ext.douban"))
Assert.is_true(StatsDB.add({
source_id = "ext.douban", stable_id = "test-book", record_type = "page",
start_time = now - 600, duration = 60, page = 1, total_pages = 10,
}, StatsDB.PENDING))
Assert.is_true(StatsDB.replaceSynced("ext.douban", snapshot.replace, snapshot.rows) ~= nil)
Assert.eq(StatsDB.summaryBySource("ext.douban").total_seconds, 7260)
Assert.eq(StatsDB.dailyBySource("ext.douban")[2].seconds, 1260)
Assert.eq(#StatsDB.unsyncedBySource("ext.douban", 200), 1)
Assert.is_true(StatsDB.replaceSynced("ext.douban", snapshot.replace, snapshot.rows) ~= nil)
Assert.eq(StatsDB.summaryBySource("ext.douban").total_seconds, 7260)
wire.data.user.readingTimeHistory[1].readingTime.duration = 0
snapshot = Mapper.readingStats(wire, "2026-10-09", now)
Assert.is_true(StatsDB.replaceSynced("ext.douban", snapshot.replace, snapshot.rows) ~= nil)
Assert.eq(#StatsDB.dailyBySource("ext.douban"), 1)
Assert.eq(StatsDB.summaryBySource("ext.douban").total_pages, 1)
local request
package.preload["utils.settings"] = function()
return { getSource = function() return { cookie = "session=test", logged_in = true, user_id = "42" } end }
end
package.preload["http.request"] = function()
return {
headerAll = function() return {} end,
request = function(opts, cb)
request = opts
if opts.method == "GET" then cb({ code = 200, body = "CSRF_TOKEN = 'test';" })
else cb({ code = 200, body = require("support.json_stub").encode(wire) }) end
return { cancel = function() end }
end,
}
end
local source = require("moonsource_douban.source").new()
package.loaded["utils.settings"] = nil
Assert.eq(source:capabilities().stats_pull, true)
local result
source:pullStatsAsync(function(value) result = value end)
Assert.is_true(result ~= nil)
local payload = require("support.json_stub").decode(request.body)
Assert.eq(payload.variables.userId, "42")
Assert.is_true(payload.variables.beginDate:match("^%d%d%d%d%-%d%d%-%d%d$") ~= nil)
Assert.eq(request.headers["X-CSRF-Token"], "test")
Assert.eq(payload.extensions.persistedQuery.sha256Hash, Mapper.READING_TIME_HASH)
StatsDB.removeSource("ext.douban")
+53
View File
@@ -0,0 +1,53 @@
--[[--
豆瓣文字格式升级:联网刷新旧的可读标记,离线继续使用旧目录。
@module tests.moonsource_douban.toc_cache_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Stubs = require("support.stubs")
package.preload["json"] = function() return require("support.json_stub") end
local Mapper = require("moonsource_douban.mapper")
local connected, calls, saved = false, 0, 0
local old = { { uid = "1", toc_version = Mapper.TOC_VERSION - 1, vip = true } }
local fresh = { { uid = "1", toc_version = Mapper.TOC_VERSION, vip = false } }
local cached = old
package.preload["ui/network/manager"] = function()
return { isConnected = function() return connected end }
end
package.preload["moonsource_douban.client"] = function()
return {
load = function() end,
tocAsync = function(_id, cb)
calls = calls + 1
cb(fresh)
return { cancel = function() end }
end,
}
end
package.preload["source.toc"] = function()
return {
read = function() return cached end,
put = function(_source, _id, toc)
saved = saved + 1
cached = toc
return true
end,
}
end
local source = require("moonsource_douban.source").new()
local identity = { source_id = "ext.douban", stable_id = "test" }
local result
source:loadTocAsync(identity, function(toc) result = toc end)
Stubs.flush()
Assert.eq(result, old)
Assert.eq(calls, 0)
Assert.eq(saved, 0)
connected = true
source:loadTocAsync(identity, function(toc) result = toc end)
Assert.eq(result, fresh)
Assert.eq(result[1].vip, false)
Assert.eq(calls, 1)
Assert.eq(saved, 1)