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

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

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

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
--[[--
网易网页登录后重新检查匿名目录里的付费章,购买提示不进入后台缓存。
@module tests.moonsource_netease.auth_content_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local logged_in, downloads = true, 0
local html, content_error = "<p>已购正文</p>", nil
package.loaded["moonsource_netease.client"] = {
loggedIn = function() return logged_in end,
contentAsync = function(book_id, chapter_id, cb)
Assert.eq(book_id, "fixture")
Assert.eq(chapter_id.uid, "c1")
downloads = downloads + 1
cb(html, content_error)
return { cancel = function() end }
end,
}
local open_fetch, cache_fetch, paid
package.loaded["source.chapter"] = {
openAsync = function(_source, _identity, _book, _opts, ops) open_fetch = ops.fetchContent end,
cacheAllAsync = function(_source, _identity, fetch) cache_fetch = fetch end,
}
package.loaded["source.toc"] = {
markPaid = function(id, stable_id, uid, value)
Assert.eq(id, "ext.netease")
Assert.eq(stable_id, "fixture")
Assert.eq(uid, "c1")
paid = value
end,
}
local source = require("moonsource_netease.source").new()
local identity = { source_id = "ext.netease", stable_id = "fixture" }
local chapter = { idx = 1, uid = "c1", title = "第一章", vip = true }
source:openBookAsync(identity, { chapter_idx = 1 }, function() end)
local result, failure
open_fetch(identity, chapter, function(value, err) result, failure = value, err end)
Assert.eq(result.html, "<p>已购正文</p>")
Assert.is_nil(result.temporary)
Assert.is_true(paid)
Assert.is_nil(failure)
html, content_error = nil, "本章未购买"
open_fetch(identity, chapter, function(value) result = value end)
Assert.is_true(result.temporary)
source:cacheAllChaptersAsync(identity, nil, function() end)
cache_fetch(identity, chapter, function(value, err) result, failure = value, err end)
Assert.is_nil(result)
Assert.eq(failure, "本章未购买")
content_error = "network down"
open_fetch(identity, chapter, function(value, err) result, failure = value, err end)
Assert.is_nil(result)
Assert.eq(failure, "network down")
local before = downloads
logged_in = false
open_fetch(identity, chapter, function(value) result = value end)
Assert.is_true(result.temporary)
Assert.eq(downloads, before)
+121
View File
@@ -0,0 +1,121 @@
--[[--
电脑端密码 / 微信登录:隔离会话、错误分支、跳转、取消与 Cookie 替换。
@module tests.moonsource_netease.auth_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
package.loaded["json"] = require("support.json_stub")
local cfg, saves = { cookie = "OLD=valid", logged_in = true, csrf = "old" }, 0
package.loaded["utils.settings"] = {
getSource = function() return cfg end,
saveSource = function() saves = saves + 1 end,
}
local requests, cancelled = {}, 0
local sync_prepare = false
local function send(method, url, body, opts, cb)
requests[#requests + 1] = { method = method, url = url, body = body, opts = opts, cb = cb }
if sync_prepare and url:find("/loginForm.do", 1, true) then
cb('<div id="login-container"></div>', nil, { headers = { ["Set-Cookie"] = { "ANON=1; Path=/" } } })
end
return { cancel = function() cancelled = cancelled + 1 end }
end
package.loaded["http.request"] = {
get = function(url, opts, cb) return send("GET", url, nil, opts, cb) end,
post = function(url, body, opts, cb) return send("POST", url, body, opts, cb) end,
header = function(res, name) return res and res.headers[name] end,
headerAll = function(res, name) return res and res.headers and res.headers[name] or {} end,
}
local Login = require("moonsource_netease.auth")
local ok, err, needs_code, calls
local function done(value, reason, code) ok, err, needs_code, calls = value, reason, code, (calls or 0) + 1 end
local function reply(body, cookies, code, location)
requests[#requests].cb(body, nil, {
code = code or 200, headers = { ["Set-Cookie"] = cookies or {}, Location = location },
})
end
local account = '<title>个人资料--网易云阅读</title><a id="editNickName"></a>'
local function prepare(session)
session:passwordAsync("13800138000", " secret with spaces ", nil, done)
reply('<div id="login-container"></div>', { "ANON=first; Path=/; HttpOnly; SameSite=Lax" })
end
local session = Login.new()
prepare(session)
Assert.matches(requests[#requests].url, "yuedu%.163%.com/cellPhoneLogin%.do")
Assert.matches(requests[#requests].body, "cellPhone=13800138000")
Assert.is_true(requests[#requests].body:find("password=%20secret%20with%20spaces%20", 1, true) ~= nil)
Assert.eq(requests[#requests].opts.headers.Cookie, "ANON=first")
reply("<script>oWin.YD.Header.mobileCallback('authenticationFailed');</script>")
Assert.is_nil(ok)
Assert.eq(err, "网易云阅读密码错误")
Assert.eq(cfg.cookie, "OLD=valid")
Assert.eq(saves, 0)
session:passwordAsync("13800138000", "good", nil, done)
reply("<script>oWin.YD.Header.mobileCallback('authFailNeedCode');</script>")
Assert.is_true(needs_code)
session:passwordAsync("13800138000", "good", "ab12", done)
Assert.matches(requests[#requests].body, "checkCode=ab12")
reply("<script>oWin.YD.Header.mobileCallback('success');</script>", {
'ANON=""; Path=/', "NTES=desktop; Path=/; HttpOnly",
})
Assert.eq(cfg.cookie, "OLD=valid", "服务端声称成功后仍须校验")
Assert.eq(requests[#requests].opts.headers.Cookie, "NTES=desktop")
reply(account)
Assert.is_true(ok)
Assert.eq(cfg.cookie, "NTES=desktop")
Assert.is_nil(cfg.csrf)
Assert.eq(saves, 1)
session = Login.new()
prepare(session)
reply("<script>mobileCallback('success')</script>", { "NTES=invalid; Path=/" })
reply("<title>登录--网易云阅读</title>")
Assert.is_nil(ok)
Assert.eq(cfg.cookie, "NTES=desktop")
Assert.eq(saves, 1)
session = Login.new()
session:qrCreateAsync(done)
Assert.is_nil(requests[#requests].opts.headers, "微信不能收到网易 Cookie")
Assert.matches(requests[#requests].url, "appid=wxc662b4239bb6644e")
reply('<img src="/connect/qrcode/uuid_123">')
Assert.eq(ok, "uuid_123")
session:qrPollAsync("uuid_123", 404, done)
Assert.matches(requests[#requests].url, "last=404")
reply('{"wx_errcode":405,"wx_code":"code_123"}')
Assert.eq(ok, 405)
Assert.eq(err, "code_123")
session:qrPollAsync("uuid_123", nil, done)
reply('window.wx_errcode=408;window.wx_code="";')
Assert.eq(ok, 408)
session:qrPollAsync("uuid_123", nil, done)
reply('{"wx_errcode":405}')
Assert.is_nil(ok)
Assert.eq(needs_code, "响应无效")
session:exchangeAsync("code_123", done)
Assert.matches(requests[#requests].url, "site=7&from=login&fromHttps=true&code=code_123")
reply(nil, { "NTES=wechat; Path=/" }, 302, "/myinfor.do")
Assert.eq(requests[#requests].opts.headers.Cookie, "NTES=wechat")
reply(account)
reply(account)
Assert.is_true(ok)
Assert.eq(cfg.cookie, "NTES=wechat")
session:exchangeAsync("bad_redirect", done)
reply(nil, {}, 302, "https://example.com/steal")
Assert.is_nil(ok)
Assert.eq(cfg.cookie, "NTES=wechat")
Assert.is_nil(requests[#requests].url:find("example.com", 1, true))
sync_prepare = true
session = Login.new()
session:passwordAsync("13800138000", "good", nil, done)
Assert.matches(requests[#requests].url, "/cellPhoneLogin%.do")
local late, before = requests[#requests].cb, calls
session:cancel()
Assert.eq(cancelled, 1, "同步 prepare 回调不能覆盖在途 POST 的句柄")
late("<script>mobileCallback('success')</script>")
Assert.eq(calls, before)
Assert.eq(cfg.cookie, "NTES=wechat")
session:passwordAsync("13800138000", "good", nil, done)
reply("<script>mobileCallback('errorCaptcha')</script>")
Assert.is_true(needs_code, "取消一次请求后仍能在原登录窗重试")
+84
View File
@@ -0,0 +1,84 @@
--[[--
网易官网分类:频道、筛选、带封面的分页结果与取消。
@module tests.moonsource_netease.browse_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local JSON = require("support.json_stub")
package.loaded["json"] = JSON
local Mapper = require("moonsource_netease.mapper")
local html = [[
<a href="/category/original.do?gender=male&amp;id=7">都市</a>
<a href="/category/original.do?gender=female&amp;id=8">现言</a>
<a href="/category/publish.do?id=2000">小说作品</a>
<a href="/category/publish.do?id=2000">重复链接</a>
<a href="/category/publish.do?id=2300">人文社科</a>
]]
local categories = Mapper.categories(html)
Assert.len(categories.male, 1)
Assert.eq(categories.female[1].id, "8")
Assert.len(categories.publish, 2)
Assert.eq(categories.publish[2].title, "人文社科")
Assert.is_nil(Mapper.categories("<html>网站维护</html>"))
Assert.is_nil(Mapper.catalog({ code = 0, data = { books = {} } }), "缺失分页字段不能当成功空书城")
local requests, failure_page, delayed = {}, nil, false
package.loaded["http.request"] = {
get = function(url, opts, cb)
local request = { url = url, opts = opts, cb = cb }
requests[#requests + 1] = request
local handle = { cancel = function() request.cancelled = true end }
if url:match("/category$") then cb(html); return handle end
if delayed then return handle end
local page = tonumber(url:match("[?&]page=(%d+)"))
if page == failure_page then cb(nil, "network down"); return handle end
local books = {}
for i = 1, 20 do
books[i] = { sourceUrl = "/source/book_" .. page .. "_" .. i, title = "书 " .. i,
iconUrl = "//img/book.jpg", author = "作者" }
end
cb(JSON.encode({ code = 0, data = { books = books, pageQuery = { more = page < 3 } } }))
return handle
end,
}
local source = require("moonsource_netease.source").new()
local result, err
source:browseAsync({ node = "female:8:new:1:2", limit = 40 }, function(value, reason) result, err = value, reason end)
Assert.is_nil(err)
Assert.len(result.data, 40)
Assert.eq(result.data[1].cover, "https://img/book.jpg")
Assert.eq(result.data[21].stable_id, "book_2_1")
Assert.len(result.groups, 5)
Assert.eq(result.groups[1].active, "female:all:new:1:0", "切分类后仍须标亮当前频道")
Assert.eq(result.groups[2].active, "female:8:new:1:2")
Assert.eq(result.groups[1].chips[1].id, "male:all:new:1:0", "换频道清分类与完结状态,保留排序和资费")
Assert.eq(result.groups[3].title, "排序")
Assert.matches(requests[2].url, "/category/original/data%.json%?")
Assert.matches(requests[2].url, "gender=female")
Assert.matches(requests[2].url, "sort=1")
Assert.matches(requests[2].url, "pay=1")
Assert.matches(requests[2].url, "state=2")
Assert.is_nil(requests[2].opts.headers, "公开分类不能携带电脑端 Cookie")
Assert.matches(requests[3].url, "page=2")
source:browseAsync({ node = "publish:2300:hot:0:0" }, function(value, reason) result, err = value, reason end)
Assert.len(result.data, 60, "不是只取榜单第一页的十几本")
Assert.len(result.groups, 4)
Assert.matches(requests[#requests].url, "/category/publish/data%.json%?")
Assert.matches(requests[#requests].url, "sort=1", "出版和原创的排序编码相反")
Assert.matches(requests[#requests].url, "id=2300")
Assert.is_nil(requests[#requests].url:find("state=", 1, true))
source:browseAsync({ node = "male:999:new:0:0", limit = 20 }, function(value) result = value end)
Assert.eq(result.groups[2].active, "male:all:new:0:0", "分类已下线时回到全部分类")
Assert.matches(requests[#requests].url, "id=&")
source:browseAsync({ node = "female", limit = 20 }, function(value) result = value end)
Assert.eq(result.groups[1].active, "female:all:hot:0:0", "旧频道节点继续可用")
failure_page = 2
source:browseAsync({}, function(value, reason) result, err = value, reason end)
Assert.is_nil(result, "第二页失败不能缓存第一页面冒充完整结果")
Assert.eq(err, "network down")
failure_page, delayed = nil, true
local handle = source:browseAsync({}, function(value) result = value end)
handle:cancel()
Assert.is_true(requests[#requests].cancelled, "分类页同步命中后,必须取消在飞的列表而不是分类请求")
+266
View File
@@ -0,0 +1,266 @@
--[[--
电脑端目录、正文、书评与进度,公开搜索不泄露 Cookie。
@module tests.moonsource_netease.client_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local CookieOf = require("support.cookie")
local JSON = require("support.json_stub")
package.loaded["json"] = JSON
local Text = require("utils.text")
local Mapper = require("moonsource_netease.mapper")
local cfg = { cookie = "NTES=desktop", logged_in = true, csrf = "legacy" }
package.loaded["utils.settings"] = { getSource = function() return cfg end }
local requests, response, failure, profile, response_meta = {}, nil, nil, nil, nil
package.loaded["http.request"] = {
get = function(url, opts, cb)
requests[#requests + 1] = { url = url, opts = opts }
cb(url:find("/myinfor.do", 1, true) and profile or response, failure, response_meta)
return { cancel = function() end }
end,
post = function(url, body, opts, cb)
requests[#requests + 1] = { url = url, body = body, opts = opts }
cb(response, failure)
return { cancel = function() end }
end,
header = function(res, _name) return res.location end,
}
local Client = require("moonsource_netease.client")
local info = {
id = "book_4", title = "甲", author = "乙", coverImg = "//img/book.jpg", shareDescription = "简介",
curDate = 1000, curArticleUuid = "c2", curPagePercent = 25,
portions = {
{ id = "volume", title = "第一卷", leafNode = false, bigContentId = "10" },
{ id = "c1", title = "第一章", leafNode = true, bigContentId = "11", charSize = 100, needPay = 0 },
{ id = "c2", title = "第二章", leafNode = true, bigContentId = "12", charSize = 200, needPay = 1 },
{ id = "c3", title = "第三章", leafNode = true, bigContentId = "13", needPay = 1, isPaid = true },
},
}
local detail = Mapper.detail(info)
Assert.eq(detail.stable_id, "book_4")
Assert.eq(detail.cover, "https://img/book.jpg")
local toc = Mapper.chapters(info)
Assert.len(toc, 4)
Assert.is_false(toc[1].leaf)
Assert.eq(toc[2].big_content_id, "11")
Assert.eq(toc[2].word_count, 100)
Assert.is_true(toc[3].vip)
Assert.is_false(toc[4].vip)
Assert.eq(Mapper.progressIndex(info), 3)
info.curDate = 0
Assert.is_nil(Mapper.progressIndex(info), "默认章节不是云端阅读进度")
info.curDate = 1000
local result, err, pages
response = JSON.encode(info)
Client.infoAsync("book_4", function(value, reason) result, err = value, reason end)
Assert.eq(Mapper.detail(result).title, "甲")
Assert.is_nil(err)
Assert.eq(requests[#requests].url, "https://yuedu.163.com/getBook.do?id=book_4")
Assert.eq(CookieOf(requests[#requests]), "NTES=desktop")
response = JSON.encode({ code = 0, data = { books = { { sourceUuid = "book_4", title = "甲" } } } })
Client.searchAsync("甲", function(value) result = value end)
Assert.eq(result[1].stable_id, "book_4")
Assert.is_nil(requests[#requests].opts.headers, "电脑端 Cookie 不发往 3g 域名")
response = JSON.encode({ content = Text.base64Encode("<p>甲</p>"), resultCode = 0 })
Client.contentAsync("book_4", toc[2], function(value, reason) result, err = value, reason end)
Assert.eq(result, "<p>甲</p>")
Assert.matches(requests[#requests].url, "/getArticleContent%.do%?")
Assert.matches(requests[#requests].url, "bigContentId=11")
Client.contentAsync("book_4", toc[1], function(value) result = value end)
Assert.matches(requests[#requests].url, "/getChapterContent%.do%?")
response = JSON.encode({ resultCode = 1, content = "" })
Client.contentAsync("book_4", toc[3], function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "本章未购买")
response = JSON.encode({ resultCode = 0, content = "" })
Client.contentAsync("book_4", toc[2], function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "正文为空")
response = JSON.encode({ resultCode = 0, totalPage = 2,
data = { { username = "甲", text = "好看", posttime = "昨天", stars = 5, likes = 3 } } })
Client.commentsAsync("book_4", function(value, reason, count) result, err, pages = value, reason, count end)
Assert.eq(result[1].grade, 5)
Assert.eq(result[1].likes, 3)
Assert.eq(pages, 2)
Assert.is_nil(err)
Assert.matches(requests[#requests].url, "yuedu%.163%.com/snsComment%.do%?")
response = JSON.encode({ resultCode = 0 })
Client:addToShelfAsync("book/a,b", function(value, reason) result, err = value, reason end)
Assert.eq(result.resultCode, 0)
Assert.is_nil(err)
Assert.eq(requests[#requests].url, "https://guofeng.yuedu.163.com/subscribe.do")
Assert.matches(requests[#requests].body, "operation=addSub")
Assert.matches(requests[#requests].body, "id=book%%2Fa%%2Cb")
Assert.eq(CookieOf(requests[#requests]), "NTES=desktop")
Assert.eq(requests[#requests].opts.headers.Referer, "https://guofeng.yuedu.163.com/")
Client:removeFromShelfAsync("book/a,b", function(value, reason) result, err = value, reason end)
Assert.eq(result.resultCode, 0)
Assert.eq(requests[#requests].url,
"https://guofeng.yuedu.163.com/shelf.do?operation=unsub&source_uuids=book%2Fa%2Cb")
Assert.eq(requests[#requests].body, "")
for _idx, raw in ipairs({ "", "<html>登录</html>", JSON.encode({ code = 0 }) }) do
response = raw
Client:addToShelfAsync("book_4", function(value, reason) result, err = value, reason end)
Assert.is_nil(result, "空响应、坏 JSON 或缺少成功码不能当作加架成功")
Assert.eq(err, "响应无效")
end
response = JSON.encode({ resultCode = -1 })
Client:removeFromShelfAsync("book_4", function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "同步失败")
failure = "network down"
Client:addToShelfAsync("book_4", function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "network down")
Assert.is_true(Client.loggedIn())
failure, response = nil, JSON.encode({ resultCode = -999 })
Client:removeFromShelfAsync("book_4", function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "网易云阅读登录已失效")
Assert.is_false(Client.loggedIn())
require("source.auth").ok("ext.netease")
local fields = Mapper.readlog("book_4", toc, 3, 0.25, 1000)
Assert.eq(fields.articleUuid, "c2")
Assert.eq(fields.curPagePercent, 25)
Assert.eq(fields.date, 1000)
Assert.is_nil(Mapper.readlog("book_4", toc, 9, 0, 1000))
Assert.eq(Mapper.readlog("book_4", toc, 3, 2, 1000).curPagePercent, 100)
profile = '<title>个人资料--网易云阅读</title><a id="editNickName"></a>'
response = "1\n"
Client.putProgressAsync("book_4", toc, 3, 0.25, function(value, reason) result, err = value, reason end)
Assert.is_true(result)
Assert.matches(requests[#requests].url, "/addUserReadLog%.do")
Assert.matches(requests[#requests].body, "curPagePercent=25")
Assert.matches(requests[#requests].body, "articleUuid=c2")
Assert.is_nil(requests[#requests].body:find("csrf", 1, true))
response = "0"
Client.putProgressAsync("book_4", toc, 3, 0, function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "网易云阅读进度保存失败", "失败不能把本地脏进度标成已同步")
profile = '<title>登录--网易云阅读</title><div id="login-container"></div>'
response = "1"
local before = #requests
Client.putProgressAsync("book_4", toc, 3, 0, function(value, reason) result, err = value, reason end)
Assert.is_nil(result, "匿名接口也回 1,登录过期不能算同步成功")
Assert.not_nil(err)
Assert.eq(#requests, before + 1, "失效会话不发进度写请求")
Assert.is_false(Client.loggedIn())
Assert.is_true(require("source.auth").expired("ext.netease"))
require("source.auth").ok("ext.netease")
response_meta = { code = 302, location = "https://yuedu.163.com/loginForm.do?targetUrl=myinfor.do" }
failure = "HTTP 302"
Client.putProgressAsync("book_4", toc, 3, 0, function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "网易云阅读登录已失效")
Assert.is_false(Client.loggedIn(), "HTTP 层把 302 作为错误时仍要识别真正的登录重定向")
require("source.auth").ok("ext.netease")
response_meta = nil
failure = "network down"
Client.putProgressAsync("book_4", toc, 3, 0, function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "network down")
Assert.is_true(Client.loggedIn(), "网络失败不能被当成退出登录")
profile = nil
Client.infoAsync("book_4", function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "network down")
failure = nil
response = '<title>个人资料--网易云阅读</title><a id="editNickName"></a>'
Client.loginCheckAsync("NTES=new", function(value, reason) result, err = value, reason end)
Assert.is_true(result)
Assert.eq(cfg.cookie, "NTES=desktop", "校验不能直接替换当前会话")
Assert.eq(CookieOf(requests[#requests]), "NTES=new")
response = '<title>登录--网易云阅读</title><div id="login-container"></div>'
Client.loginCheckAsync("NTES=bad", function(value, reason) result, err = value, reason end)
Assert.is_false(result)
Assert.not_nil(err)
Assert.eq(cfg.cookie, "NTES=desktop")
Assert.is_true(Client.loggedIn(), "新 Cookie 校验失败不能注销当前有效账号")
local request_api = package.loaded["http.request"]
local get = request_api.get
local late_check
request_api.get = function(_url, _opts, cb)
late_check = cb
return { cancel = function() end }
end
Client.putProgressAsync("book_4", toc, 3, 0, function(value, reason) result, err = value, reason end)
cfg.cookie = "NTES=replacement"
late_check('<div id="login-container"></div>')
Assert.is_nil(result)
Assert.is_true(Client.loggedIn(), "旧请求迟到的登录失效不能注销刚换上的账号")
cfg.cookie = "NTES=desktop"
request_api.get = get
local stored_toc
package.loaded["source.toc"] = {
put = function(id, stable_id, chapters)
Assert.eq(id, "ext.netease")
Assert.eq(stable_id, "book_4")
stored_toc = chapters
return true
end,
}
local source = require("moonsource_netease.source").new()
local identity = { source_id = "ext.netease", stable_id = "book_4" }
response = JSON.encode(info)
source:getProgressAsync(identity, function(value, reason) result, err = value, reason end)
Assert.eq(result.chapter_idx, 3)
Assert.eq(result.chapter_fraction, 0.25)
Assert.eq(result.extra.chapter_fraction, 0.25)
Assert.eq(result.fraction, 0.5625)
Assert.len(stored_toc, 4)
Assert.is_nil(err)
info.curDate = 0
response = JSON.encode(info)
local meta
source:getProgressAsync(identity, function(value, reason, status) result, err, meta = value, reason, status end)
Assert.is_nil(result)
Assert.is_nil(err)
Assert.is_true(meta.empty)
local old_toc = { { idx = 1, uid = "legacy", title = "旧缓存章", toc_version = 1 } }
package.loaded["source.toc"].read = function() return old_toc end
local network = package.loaded["ui/network/manager"]
package.loaded["ui/network/manager"] = { isConnected = function() return false end }
before = #requests
source:loadTocAsync(identity, function(value, reason) result, err = value, reason end)
require("support.stubs").flush()
Assert.eq(result, old_toc, "协议升级不能让离线用户的旧缓存目录失效")
Assert.is_nil(err)
Assert.eq(#requests, before)
package.loaded["ui/network/manager"] = { isConnected = function() return true end }
source:loadTocAsync(identity, function(value, reason) result, err = value, reason end)
Assert.eq(result[1].toc_version, Mapper.TOC_VERSION, "恢复联网后刷新新协议需要的章节字段")
Assert.eq(result[2].big_content_id, "11")
package.loaded["ui/network/manager"] = network
local progress_cancelled, toc_cancelled = 0, 0
local live_client = package.loaded["moonsource_netease.client"]
live_client.putProgressAsync = function(book_id, chapters, idx, within, cb)
Assert.eq(book_id, "book_4")
Assert.eq(chapters, toc)
Assert.eq(idx, 3)
Assert.eq(within, 0.25)
cb(true)
return { cancel = function() progress_cancelled = progress_cancelled + 1 end }
end
source.loadTocAsync = function(_self, _identity, cb)
cb(toc)
return { cancel = function() toc_cancelled = toc_cancelled + 1 end }
end
local handle = source:putProgressAsync(identity, { chapter_idx = 3, chapter_fraction = 0.25 },
function(value, reason) result, err = value, reason end)
Assert.is_true(result)
Assert.is_nil(err)
handle:cancel()
Assert.eq(progress_cancelled, 1, "同步目录回调不能覆盖进度请求的取消句柄")
Assert.eq(toc_cancelled, 0)
source:putProgressAsync(identity, { chapter_idx = 99 }, function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, "缺少网易云阅读章节位置")
+39
View File
@@ -0,0 +1,39 @@
--[[--
电脑阅读器的 Base64、XOR、AES 及组合顺序,失败不能缓存密文。
@module tests.moonsource_netease.content_spec
--]]
local Assert = require("support.assert")
local JSON = require("support.json_stub")
package.loaded["json"] = JSON
local Text = require("utils.text")
local Aes = require("crypto.aes")
local Mapper = require("moonsource_netease.mapper")
local key = "1234567890abcdef"
local plain = "<p>甲乙</p>"
local function decode(body, steps)
return Mapper.content({
content = Text.base64Encode(body),
x = steps and Text.base64Encode(JSON.encode(steps)),
})
end
Assert.eq(decode(plain), plain)
local ascii = "<p>hello</p>"
local encrypted = ascii:gsub(".", function(ch) return string.char(require("bit").bxor(ch:byte(), 7)) end)
Assert.eq(decode(encrypted, { { m = 1, k = "7" } }), ascii)
Assert.eq(decode("<p>电乙</p>", { { m = 1, k = "0" } }), "<p>电乙</p>")
Assert.eq(decode(Aes.to_hex(Aes.ecb_encrypt(plain, key)), { { m = 2, k = key } }), plain)
local hex = Aes.to_hex(Aes.ecb_encrypt(plain, key))
local hidden = hex:gsub(".", function(ch) return string.char(require("bit").bxor(ch:byte(), 7)) end)
Assert.eq(decode(hidden, { { m = 1, k = "7" }, { m = 2, k = key } }), plain)
Assert.eq(decode(Aes.to_hex(Aes.ecb_encrypt(encrypted, key)),
{ { m = 2, k = key }, { m = 1, k = "7" } }), ascii)
for _idx, steps in ipairs({ { { m = 3, k = key } }, { { m = 2, k = "short" } }, { false }, {} }) do
local html, err = decode(hex, steps)
Assert.is_nil(html)
Assert.eq(err, "正文解析失败")
end
local html, err = Mapper.content({ content = "eA==", x = "eA==" })
Assert.is_nil(html)
Assert.eq(err, "正文解析失败")
+92
View File
@@ -0,0 +1,92 @@
--[[--
微信扫码等待、确认、拒绝、过期、网络失败与取消。
@module tests.moonsource_netease.qrlogin_spec
--]]
---@diagnostic disable: undefined-field
local Assert = require("support.assert")
local Themed = require("support.theme_stubs")
Themed.install()
local pending
package.loaded["ui/uimanager"] = {
scheduleIn = function(_self, _seconds, fn) pending = fn end,
unschedule = function(_self, fn) if pending == fn then pending = nil end end,
}
local polls, cancelled, queue, create_callback, exchange_callback = 0, 0, {}, nil, nil
local defer_create, defer_exchange = false, false
package.loaded["moonsource_netease.auth"] = {
new = function()
return {
cancel = function() cancelled = cancelled + 1 end,
qrCreateAsync = function(_self, cb)
if defer_create then create_callback = cb else cb("uuid") end
end,
qrPollAsync = function(_self, uuid, last, cb)
Assert.eq(uuid, "uuid")
polls = polls + 1
local result = table.remove(queue, 1)
cb(result.status, result.code, result.err)
end,
exchangeAsync = function(_self, code, cb)
Assert.eq(code, "wx-code")
if defer_exchange then exchange_callback = cb else cb(true) end
end,
}
end,
}
local QRLogin = require("moonsource_netease.qrlogin")
local function start(results)
polls, pending, queue = 0, nil, results
local done = false
local qr = QRLogin:new(function() done = true end)
qr:start()
return qr, function() return done end
end
local qr, done = start({ { status = 408 }, { status = 404 }, { status = 404 }, { status = 405, code = "wx-code" } })
Assert.eq(Themed.last("qr").text, "https://open.weixin.qq.com/connect/confirm?uuid=uuid")
Assert.is_false(done())
pending()
Assert.eq(Themed.last("toast").text, "已扫码,请在手机上确认")
local before = #Themed.all("toast")
pending()
Assert.len(Themed.all("toast"), before)
pending()
Assert.is_true(done())
Assert.is_true(Themed.last("qr").closed)
Assert.is_true(Themed.last("progress_dialog").closed)
qr, done = start({ { status = 408 } })
local late = pending
Themed.last("qr"):close()
Assert.is_nil(pending)
late()
Assert.eq(polls, 1)
Assert.is_false(done())
for _idx, result in ipairs({
{ status = 403, message = "已在微信中拒绝登录" },
{ status = 402, message = "二维码已过期" },
{ err = "network down", message = "network down" },
}) do
qr, done = start({ result })
Assert.eq(Themed.last("confirm").text, result.message)
Assert.is_false(done())
end
qr, done = start({ { status = 408 } })
qr.deadline = 0
pending()
Assert.eq(Themed.last("confirm").text, "二维码已过期")
Assert.eq(polls, 1)
defer_create = true
qr, done = start({})
Themed.last("progress_dialog").on_cancel()
before = #Themed.all("qr")
create_callback("late")
Assert.len(Themed.all("qr"), before)
Assert.is_false(done())
defer_create, defer_exchange = false, true
qr, done = start({ { status = 405, code = "wx-code" } })
qr:cancel()
exchange_callback(true)
Assert.is_false(done(), "关窗后不能接受迟到的授权")
Assert.is_true(cancelled > 0)
+116
View File
@@ -0,0 +1,116 @@
--[[--
两种设备登录和电脑端 Cookie 入口;离线不留等待窗,密码不修剪。
@module tests.moonsource_netease.setting_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Themed = require("support.theme_stubs")
Themed.install()
local cfg, reloads, connected = {}, 0, true
package.loaded["utils.settings"] = {
getSource = function() return cfg end, saveSource = function() end,
}
package.loaded["source.registry"] = { reload = function() reloads = reloads + 1 end }
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end }
local valid_cookie = true
package.loaded["moonsource_netease.client"] = {
loggedIn = function() return cfg.logged_in == true end,
loginCheckAsync = function(cookie, cb)
Assert.eq(cookie, "NTES=browser")
cb(valid_cookie, not valid_cookie and "expired" or nil)
end,
}
local passwords, cancelled, qr_started = {}, 0, 0
package.loaded["moonsource_netease.auth"] = {
new = function()
return {
cancel = function() cancelled = cancelled + 1 end,
passwordAsync = function(_self, phone, password, code, cb)
passwords[#passwords + 1] = { phone = phone, password = password, code = code, cb = cb }
end,
}
end,
}
package.loaded["moonsource_netease.qrlogin"] = {
new = function(_self, cb)
return { start = function() qr_started = qr_started + 1; cb() end }
end,
}
local verification_callback
package.loaded["moonsource_netease.verify"] = {
new = function(_session, cb)
verification_callback = cb
return { cancel = function() end }
end,
}
local Setting = require("moonsource_netease.setting")
Setting.login()
local input = Themed.last("input")
Assert.len(input.fields, 2, "不再混用手机版短信协议")
input.callback("invalid", "secret")
Assert.len(passwords, 0)
input.callback("13800138000", "")
Assert.len(passwords, 0)
connected = false
input.callback("13800138000", "secret")
Assert.len(passwords, 0)
Assert.is_nil(Themed.last("progress_dialog"), "离线立即结束,不能等永不触发的联网回调")
connected = true
input.callback(" 13800138000 ", " secret ")
Assert.eq(passwords[1].phone, "13800138000")
Assert.eq(passwords[1].password, " secret ")
input.callback("13800138000", "duplicate")
Assert.len(passwords, 1, "重复点击不能覆盖在途请求")
passwords[1].cb(nil, "验证码错误", true)
verification_callback("ab12")
Assert.eq(passwords[2].code, "ab12")
passwords[2].cb(true)
Assert.is_true(input.closed)
Assert.eq(reloads, 1)
Assert.eq(cancelled, 1)
Setting.login()
input = Themed.last("input")
input.callback("13800138000", "secret")
Themed.last("progress_dialog").on_cancel()
Assert.is_true(Themed.last("progress_dialog").closed)
input.callback("13800138000", "retry")
Assert.len(passwords, 4)
input:close()
Assert.eq(cancelled, 3)
local rows = Setting.rows()
rows[2](400).callback()
Assert.eq(qr_started, 1)
local opened
package.loaded["utils.extension"] = {
call = function(name, path, title)
opened = { name = name, path = path, title = title }
return { close = function() end }
end,
}
Assert.eq(rows[3](400).title, "浏览器登录")
rows[3](400).callback()
Assert.eq(opened.path, "/cookie.html")
package.loaded["utils.extension"] = nil
rows[4](400).callback()
Assert.eq(Themed.last("input").title, "网易云阅读登录 Cookie")
Assert.eq(Setting.browser.domain, "yuedu.163.com")
Assert.eq(Setting.browser.check, "https://yuedu.163.com/myinfor.do")
local accepted
Setting.browser.apply({ cookies = {
{ domain = ".yuedu.163.com", name = "NTES", value = "browser" },
{ domain = ".weibo.com", name = "OTHER", value = "excluded" },
} }, function(ok) accepted = ok end)
Assert.is_true(accepted)
Assert.eq(cfg.cookie, "NTES=browser")
Assert.is_nil(cfg.csrf)
Assert.is_true(Setting.browser.isAuthorized())
valid_cookie = false
Setting.browser.apply({ cookies = {
{ domain = ".yuedu.163.com", name = "NTES", value = "browser" },
} }, function(ok) accepted = ok end)
Assert.is_false(accepted)
Assert.eq(cfg.cookie, "NTES=browser")
+176
View File
@@ -0,0 +1,176 @@
--[[--
网易官网 HTML 书架:身份、分页、整批失败与取消,以及本地增删上行。
@module tests.moonsource_netease.shelf_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local CookieOf = require("support.cookie")
local JSON = require("support.json_stub")
package.loaded["json"] = JSON
local Text = require("utils.text")
local Mapper = require("moonsource_netease.mapper")
local function row(id, title, extra)
return '<li><div class="m-bookshow" prog="0"><div class="m-infos"><h4>书</h4><p>作者甲</p></div>'
.. '<a data-contentinfo="' .. Text.xmlEscape(JSON.encode({
sourceUuid = id, sourceTitle = title, imageUrl = "//img/cover.jpg",
imageDescription = "简介", origin = { "bookshelf", 0 },
})) .. '"></a>' .. (extra or "") .. '</div></li>'
end
local function page(content, next_page)
return "<html><title>我的书架--网易云阅读</title>" .. content
.. (next_page and '<a href="/shelf.do?operation=query_current&amp;style=grid&amp;page='
.. next_page .. '">下一页</a>' or "") .. "</html>"
end
local books, next_page, err = Mapper.shelfPage(page(row("first_4", "甲 & 乙"), 2), 1)
Assert.eq(books[1].source_id, "ext.netease")
Assert.eq(books[1].stable_id, "first_4")
Assert.eq(books[1].title, "甲 & 乙")
Assert.eq(books[1].authors, "作者甲")
Assert.eq(books[1].cover, "https://img/cover.jpg")
Assert.eq(next_page, 2)
Assert.is_nil(err)
books = Mapper.shelfPage(page(row("first_4", "甲") .. row("first_4", "重复")
.. row("local_4", "本地上传", '<input data-local="true">')), 1)
Assert.len(books, 1)
books, next_page = Mapper.shelfPage(page("", 1), 1)
Assert.len(books, 0)
Assert.is_nil(next_page, "当前页链接不能造成循环")
books, next_page, err = Mapper.shelfPage("<html><title>登录</title></html>", 1)
Assert.is_nil(books)
Assert.is_true(err ~= nil)
books, next_page, err = Mapper.shelfPage(page('<li><div class="m-bookshow"><a data-contentinfo="broken"></a></div></li>'), 1)
Assert.is_nil(books, "坏行不能被跳过后当作完整快照")
Assert.eq(err, "响应无效")
local cfg = { logged_in = true, cookie = "NTES=fixture", csrf = "csrf" }
package.loaded["utils.settings"] = { getSource = function() return cfg end }
local pending, cancelled = {}, 0
package.loaded["http.request"] = {
get = function(url, opts, cb)
pending[#pending + 1] = { url = url, opts = opts, cb = cb }
return { cancel = function() cancelled = cancelled + 1 end }
end,
}
local Client = require("moonsource_netease.client")
local result, failure, calls = nil, nil, 0
local function done(value, reason) result, failure, calls = value, reason, calls + 1 end
Client:shelfSyncAsync(done)
Assert.matches(pending[1].url, "https://guofeng%.yuedu%.163%.com/shelf%.do")
Assert.eq(CookieOf(pending[1]), "NTES=fixture")
Assert.eq(pending[1].opts.cache_ttl, 0, "增删后必须拉新鲜书架,不能拿旧缓存对账")
pending[1].cb(page(row("first_4", "第一本"), 2))
Assert.len(pending, 2)
Assert.eq(calls, 0, "没拉完所有页不能对账")
pending[2].cb(page(row("first_4", "重复") .. row("second_4", "第二本")))
Assert.len(result, 2)
Assert.is_nil(failure)
Assert.eq(calls, 1)
Client:shelfSyncAsync(done)
pending[#pending].cb(page(row("first_4", "第一本"), 2))
pending[#pending].cb(nil, "network down")
Assert.is_nil(result, "后一页失败不能把第一页当完整书架")
Assert.eq(failure, "network down")
local handle = Client:shelfSyncAsync(done)
local before = calls
handle:cancel()
pending[#pending].cb(page(row("first_4", "第一本"), 2))
Assert.eq(calls, before)
Assert.eq(cancelled, 1)
local reconciled, deleted, added, marked = {}, { "deleted_4" }, { "added_4" }, {}
package.loaded["book.books_db"] = {
pendingDeleteIds = function() return deleted end,
pendingShelfAddIds = function() return added end,
remove = function(id, stable_id)
Assert.eq(id, "ext.netease")
Assert.eq(stable_id, "deleted_4")
deleted = {}
return true
end,
markSynced = function(_id, stable_id)
marked[#marked + 1] = stable_id
added = {}
return true
end,
reconcile = function(id, values, options)
reconciled = { id = id, books = values, force = options.force }
return true, 0
end,
}
package.loaded["source.shelf"] = nil
local posts = {}
package.loaded["http.request"].post = function(url, body, options, cb)
posts[#posts + 1] = { url = url, body = body, opts = options, cb = cb }
return { cancel = function() cancelled = cancelled + 1 end }
end
local source = require("moonsource_netease.source").new()
before = #pending
source:syncBooksAsync({ force = true }, done)
Assert.eq(#pending, before, "先推删除,再拉书架")
Assert.len(deleted, 1, "远端确认前不能撕墓碑")
posts[1].cb(JSON.encode({ resultCode = 0 }))
Assert.len(deleted, 0)
pending[#pending].cb(page(row("first_4", "第一本")))
Assert.len(posts, 2, "拉完书架后推本地独有成员")
Assert.matches(posts[2].body, "id=added_4")
posts[2].cb(JSON.encode({ resultCode = 0 }))
pending[#pending].cb(page(row("first_4", "第一本") .. row("added_4", "新增")))
Assert.eq(reconciled.id, "ext.netease")
Assert.is_true(reconciled.force)
Assert.eq(result.pulled, 2)
Assert.eq(result.pushed, 2)
Assert.eq(marked[1], "added_4")
Assert.is_true(source:capabilities().shelf_push)
before = #pending
added = { "retry_4" }
source:syncBooksAsync({ dirty_only = true }, done)
require("support.stubs").flush()
posts[#posts].cb(JSON.encode({ resultCode = 0 }))
Assert.eq(marked[2], "retry_4")
Assert.eq(result.pushed, 1)
Assert.len(pending, before, "推脏行只上传增删,不拉书架")
deleted, added = { "deleted_4" }, { "added_4" }
before = #marked
source:syncBooksAsync({ dirty_only = true }, done)
posts[#posts].cb(JSON.encode({ resultCode = -1 }))
posts[#posts].cb("")
Assert.len(deleted, 1, "移出失败保留墓碑")
Assert.len(added, 1, "加入失败保留脏行")
Assert.len(marked, before)
Assert.eq(result.pushed, 0)
source:syncBooksAsync({ dirty_only = true }, done)
posts[#posts].cb(JSON.encode({ resultCode = 0 }))
posts[#posts].cb(JSON.encode({ resultCode = 0 }))
Assert.len(deleted, 0)
Assert.len(added, 0)
Assert.eq(result.pushed, 2, "失败后下轮重试增删")
added = { "cancel_4" }
before = cancelled
handle = source:syncBooksAsync({ dirty_only = true }, done)
require("support.stubs").flush()
handle:cancel()
Assert.eq(cancelled, before + 1, "取消同步应取消正在加入书架的请求")
Assert.len(added, 1)
package.loaded["ui/network/manager"] = { isConnected = function() return false end }
package.loaded["book.store"] = {
markDeleted = function(id, stable_id)
Assert.eq(id, "ext.netease")
Assert.eq(stable_id, "deleted_4")
deleted = { stable_id }
return true
end,
}
before = #posts
source:deleteBookAsync({ source_id = "ext.netease", stable_id = "deleted_4" }, done)
require("support.stubs").flush()
Assert.is_true(result)
Assert.len(deleted, 1, "离线删除立即隐藏,墓碑等联网后再推")
Assert.len(posts, before, "删除入口不直接发网络请求")
+62
View File
@@ -0,0 +1,62 @@
--[[--
密码图形验证码:同一会话取图、刷新、取消与迟到回调。
@module tests.moonsource_netease.verify_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Themed = require("support.theme_stubs")
Themed.install()
local loads, cancelled, results = {}, 0, {}
local decode_fails = false
package.loaded["ui.themes"] = { px = function(n) return n end }
package.loaded["ui/widget/imagewidget"] = { new = function(_class, opts) return opts end }
package.loaded["ui/renderimage"] = {
renderImageData = function(_self, raw, size, frames)
Assert.eq(raw, "picture")
Assert.eq(size, 7)
Assert.is_false(frames)
if not decode_fails then return { bitmap = true } end
end,
}
local session = {
captchaAsync = function(_self, cb) loads[#loads + 1] = cb end,
cancel = function() cancelled = cancelled + 1 end,
}
local Verification = require("moonsource_netease.verify")
local function done(code) results[#results + 1] = code or false end
local verification = Verification.new(session, done)
Assert.is_true(Themed.last("progress_dialog").shown)
loads[#loads]("picture")
local input = Themed.last("input")
Assert.is_true(input.header_widget.image.bitmap)
Assert.eq(input.ok_text, "登录")
Assert.is_false(input.validate(" "))
Assert.eq(Themed.last("toast").text, "请输入图形码")
input.actions[1].callback()
Assert.is_true(input.closed)
Assert.len(loads, 2)
loads[#loads]("picture")
input = Themed.last("input")
input.callback(" ab12 ")
Assert.eq(results[1], "ab12")
Assert.is_true(verification.done)
Assert.eq(cancelled, 1)
verification = Verification.new(session, done)
local before = #Themed.all("input")
Themed.last("progress_dialog").on_cancel()
loads[#loads]("picture")
Assert.len(Themed.all("input"), before)
Assert.eq(results[2], false)
Assert.eq(cancelled, 2)
verification = Verification.new(session, done)
loads[#loads](nil, "network down")
Assert.eq(Themed.last("toast").text, "network down")
Assert.is_true(verification.done)
decode_fails = true
verification = Verification.new(session, done)
loads[#loads]("picture")
Assert.eq(Themed.last("toast").text, "图形验证码加载失败")
Assert.is_true(verification.done)