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

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

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

+19
View File
@@ -0,0 +1,19 @@
# 网易云阅读
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| 手机号密码登录 | 支持 | 支持同一会话的图形验证码 |
| 微信扫码登录 | 支持 | 官方扫码确认后兑换网易会话 |
| 浏览器登录与 Cookie 导入 | 支持 | 电脑站登录后导入或粘贴 |
| 书架拉取 | 支持 | 读取官网书架 |
| 书架新增与移出 | 支持 | 本地先生效,远端确认后清脏/撕墓碑;失败重试 |
| 搜索与分类书城 | 支持 | 男频、女频、出版;动态分类、排序、资费及原创连载状态 |
| 详情与分卷目录 | 支持 | 保留章节顺序 |
| 免费与已购正文 | 支持 | 未购明确拒绝,不绕过权限 |
| 章节与全本缓存 | 支持 | 已缓存内容可断网续章和关书重开 |
| 阅读进度同步 | 支持 | 章节及章内比例;上传后回读确认 |
| 笔记与统计同步 | 不支持 | 仅本地保存 |
| 整书书评 | 支持 | 阅读器和章末评论入口均按整本书归属 |
| 章评与段评 | 不支持 | 当前电脑/移动 Web 未找到可验证接口,不代表 App 不支持 |
| 评论回复与写操作 | 不支持 | 未接入 |
| 账号切换 | 不支持直接隔离 | 须先关书、退出并清理旧本地数据;未同步记录会丢失 |
+5
View File
@@ -0,0 +1,5 @@
local _ = require("gettext")
return {
fullname = _("月读书源:网易云阅读"),
description = _("给月读增加「网易云阅读」书源。需要同时安装月读,与平台官方无关。"),
}
+9
View File
@@ -0,0 +1,9 @@
--[[--
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
--]]
local WidgetContainer = require("ui/widget/container/widgetcontainer")
return WidgetContainer:extend{
name = "moonsource_netease",
is_doc_only = false,
}
@@ -0,0 +1,15 @@
--[[--
月读第三方书源描述:网易云阅读。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。
--]]
local function lazy(module)
return setmetatable({}, { __index = function(_, key) return require(module)[key] end })
end
return {
api = 1,
provides = { source = true },
meta = function() return require("moonsource_netease.source").meta() end,
new = function() return require("moonsource_netease.source").new() end,
setting = lazy("moonsource_netease.setting"),
}
@@ -0,0 +1,19 @@
--[[--
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
网易云阅读网页搜索、分类书库和免费章节不需要登录。
电脑端支持手机号密码、微信扫码以及电脑浏览器 Cookie 登录。
登录后同步官网书架,本地增删联网后上行。
@module moonsource_netease._meta
--]]
local _ = require("l10n").get("moonsource_netease")
return {
id = "ext.netease",
name = _("网易云阅读"),
type = "chapter",
description = _("网易云阅读在线阅读"),
abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("书评"), _("VIP 章节") },
}
@@ -0,0 +1,187 @@
--[[--
电脑端登录会话。Cookie 归本次登录窗口所有,校验成功才替换持久会话。
密码响应是 HTML 中的 mobileCallback,不是手机版 JSON。
@module moonsource_netease.auth
--]]
local Request = require("http.request")
local Text = require("utils.text")
local Mapper = require("moonsource_netease.mapper")
local _ = require("l10n").get("moonsource_netease")
local ORIGIN = "https://yuedu.163.com"
local CALLBACK = ORIGIN .. "/weiboCallback.do?site=7&from=login&fromHttps=true"
---@class NeteaseLogin
---@field cookies table<string, string>
---@field job HttpJob|nil
---@field serial integer
---@field prepared boolean|nil
local Login = {}
Login.__index = Login
function Login.new()
return setmetatable({ cookies = {}, serial = 0 }, Login)
end
function Login:cancel()
self.serial = self.serial + 1
if self.job then self.job:cancel(); self.job = nil end
end
function Login:cookie()
local names, parts = {}, {}
for name in pairs(self.cookies) do names[#names + 1] = name end
table.sort(names)
for _idx, name in ipairs(names) do parts[#parts + 1] = name .. "=" .. self.cookies[name] end
return table.concat(parts, "; ")
end
--- 同步回调不能把后续请求的取消句柄覆盖掉;微信请求不携带网易 Cookie。
function Login:request(method, url, fields, cb)
self.serial = self.serial + 1
local serial, pending = self.serial, true
local options = { timeout = require("http.timeout").net(1.5) }
if url:sub(1, #ORIGIN + 1) == ORIGIN .. "/" then
options.headers = { Cookie = self:cookie(), Referer = ORIGIN .. "/loginForm.do" }
end
local function done(raw, err, res)
pending = false
if serial ~= self.serial then return end
self.job = nil
if options.headers then
for _idx, line in ipairs(Request.headerAll(res, "Set-Cookie")) do
local name, value = line:match("^%s*([^=;%s]+)=([^;]*)")
if name then
self.cookies[name] = value ~= "" and value ~= '""' and value or nil
end
end
end
cb(raw, err, res)
end
local job
if method == "POST" then
job = Request.post(url, Text.formEncode(fields), options, done)
else
job = Request.get(url, options, done)
end
if pending and serial == self.serial then self.job = job end
end
function Login:confirm(cb)
self:request("GET", ORIGIN .. "/myinfor.do", nil, function(raw, err)
if not Mapper.authorized(raw) then
cb(nil, err and tostring(err) or _("网易云阅读登录校验失败,请在浏览器重新登录"))
return
end
local settings = require("utils.settings")
local cfg = settings.getSource("ext.netease")
cfg.cookie, cfg.logged_in, cfg.csrf = self:cookie(), true, nil
settings.saveSource("ext.netease")
require("source.auth").ok("ext.netease")
cb(true)
end)
end
function Login:prepare(cb)
if self.prepared then cb(true); return end
self:request("GET", ORIGIN .. "/loginForm.do?targetUrl=" .. Text.urlEncode(ORIGIN .. "/myinfor.do"),
nil, function(raw, err)
if not raw or not raw:find("login%-container") then
cb(nil, err and tostring(err) or _("登录失败"))
return
end
self.prepared = true
cb(true)
end)
end
function Login:passwordAsync(phone, password, code, cb)
self:prepare(function(ok, err)
if not ok then cb(nil, err); return end
self:request("POST", ORIGIN .. "/cellPhoneLogin.do", {
operation = "login", cellPhone = phone, password = password,
remember_me = "on", checkCode = code or "",
}, function(raw, reason)
if not raw then cb(nil, reason and tostring(reason) or _("登录失败")); return end
local result = raw:match("mobileCallback%s*%(%s*['\"]([%w]+)['\"]%s*%)")
if result == "success" then self:confirm(cb); return end
local messages = {
notRegistered = _("网易云阅读手机号未注册"),
notRegisteredNeedCode = _("网易云阅读手机号未注册"),
authenticationFailed = _("网易云阅读密码错误"),
authFailNeedCode = _("网易云阅读密码错误"),
errorCaptcha = _("图形验证码错误"),
}
cb(nil, messages[result] or _("登录失败"),
result == "notRegisteredNeedCode" or result == "authFailNeedCode" or result == "errorCaptcha")
end)
end)
end
function Login:captchaAsync(cb)
self:prepare(function(ok, err)
if not ok then cb(nil, err); return end
self:request("GET", ORIGIN .. "/captcha.do?d=" .. os.time() * 1000, nil, function(raw, reason)
if not raw then cb(nil, reason and tostring(reason) or _("图形验证码加载失败")); return end
local _ext, mime = require("utils.image").ext(raw)
if not mime then cb(nil, _("图形验证码加载失败")); return end
cb(raw)
end)
end)
end
function Login:qrCreateAsync(cb)
self:request("GET", "https://open.weixin.qq.com/connect/qrconnect?" .. Text.formEncode({
appid = "wxc662b4239bb6644e", redirect_uri = CALLBACK, response_type = "code",
scope = "snsapi_login", state = "",
}), nil, function(raw, err)
local uuid = raw and raw:match("/connect/qrcode/([%w_%-]+)")
if not uuid then cb(nil, err and tostring(err) or _("获取二维码失败")); return end
cb(uuid)
end)
end
function Login:qrPollAsync(uuid, last, cb)
self:request("GET", "https://long.open.weixin.qq.com/connect/l/qrconnect?"
.. Text.formEncode({ uuid = uuid, last = last, f = "json" }), nil, function(raw, err)
if not raw then cb(nil, nil, err and tostring(err) or _("请求失败")); return end
local ok, wire = pcall(require("json").decode, raw)
local status = ok and type(wire) == "table" and tonumber(wire.wx_errcode)
or tonumber(raw:match("wx_errcode%s*=%s*(%d+)"))
local code = ok and type(wire) == "table" and wire.wx_code
or raw:match("wx_code%s*=%s*['\"]([^'\"]+)['\"]")
if not status or (status == 405 and (type(code) ~= "string" or code == "")) then
cb(nil, nil, _("响应无效"))
return
end
cb(status, code)
end)
end
function Login:exchangeAsync(code, cb)
local function follow(url, remaining)
self:request("GET", url, nil, function(raw, err, res)
local status = res and tonumber(res.code)
if status and status >= 300 and status < 400 then
local location = Request.header(res, "Location")
if location and location:sub(1, 1) == "/" and location:sub(1, 2) ~= "//" then
location = ORIGIN .. location
end
if remaining == 0 or type(location) ~= "string"
or location:sub(1, #ORIGIN + 1) ~= ORIGIN .. "/" then
cb(nil, _("网易云阅读登录校验失败,请在浏览器重新登录"))
return
end
follow(location, remaining - 1)
return
end
if not raw then cb(nil, err and tostring(err) or _("登录失败")); return end
self:confirm(cb)
end)
end
follow(CALLBACK .. "&code=" .. Text.urlEncode(code) .. "&state=", 5)
end
return Login
@@ -0,0 +1,230 @@
--[[--
网易云阅读 Web 接口。账号、书架、目录、正文和进度共用电脑端 Cookie。
公开搜索和分类使用官方移动网页 JSON,不向该域名发送电脑端 Cookie。
@module moonsource_netease.client
--]]
local JSON = require("json")
local Mapper = require("moonsource_netease.mapper")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_netease")
local Client = {}
local ORIGIN = "https://yuedu.163.com"
local SHELF_ORIGIN = "https://guofeng.yuedu.163.com"
local PUBLIC = "https://yuedu.3g.163.com"
local SOURCE_ID = "ext.netease"
function Client.loggedIn()
local cfg = require("utils.settings").getSource(SOURCE_ID)
return cfg.logged_in == true and type(cfg.cookie) == "string" and cfg.cookie ~= ""
and not require("source.auth").expired(SOURCE_ID)
end
--- account 是发请求时的已保存 Cookie,回包后与当前保存值比对判断是否换号。
local function opts(origin)
local cookie = require("utils.settings").getSource(SOURCE_ID).cookie
return {
timeout = require("http.timeout").net(1),
account = cookie,
jar = require("http.cookie_jar").session(SOURCE_ID, cookie),
headers = { Referer = (origin or ORIGIN) .. "/" },
}
end
local function getJson(url, options, cb)
return Request.get(url, options, function(raw, err)
if err or not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then cb(nil, _("响应无效")); return end
cb(wire)
end)
end
--- 只校验,不改当前会话;匿名账号页会重定向至 loginForm.do。
function Client.loginCheckAsync(cookie, cb)
return Request.get(ORIGIN .. "/myinfor.do", {
headers = { Cookie = cookie }, timeout = require("http.timeout").net(1),
}, function(raw, err, res)
if err or not Mapper.authorized(raw) then
local location = res and Request.header(res, "Location")
local status = res and tonumber(res.code)
local expired = (status and status >= 300 and status < 400
and location and location:find("/loginForm.do", 1, true) ~= nil)
or (not err and raw and raw:find("login%-container") ~= nil)
cb(false, not expired and err and tostring(err)
or _("网易云阅读登录校验失败,请在浏览器重新登录"), expired == true)
return
end
cb(true)
end)
end
function Client:shelfSyncAsync(cb)
if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录网易云阅读")) end
local cancelled, job = false, nil
local books, seen = {}, {}
local options = opts(SHELF_ORIGIN)
options.cache_ttl = 0
local function nextPage(page)
local pending = true
local current = Request.get(SHELF_ORIGIN .. "/shelf.do?operation=query_current&style=grid&page=" .. page,
options, function(raw, err)
pending = false
if cancelled then return end
if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
local rows, next_page, reason = Mapper.shelfPage(raw, page)
if not rows then cb(nil, reason); return end
for _idx, item in ipairs(rows) do
if not seen[item.stable_id] then
seen[item.stable_id] = true
books[#books + 1] = item
end
end
if next_page then nextPage(next_page); return end
cb(books)
end)
if pending then job = current end
end
nextPage(1)
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
local function changeShelf(url, fields, cb)
if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录网易云阅读")) end
local options = opts(SHELF_ORIGIN)
options.cache_ttl = 0
return Request.post(SHELF_ORIGIN .. url, fields and Text.formEncode(fields) or "", options, function(raw, err)
if err then cb(nil, tostring(err)); return end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then cb(nil, _("响应无效")); return end
local code = tonumber(wire.resultCode)
if code == -999 then
local reason = _("网易云阅读登录已失效")
if options.account == require("utils.settings").getSource(SOURCE_ID).cookie then
reason = require("source.auth").expire(SOURCE_ID, reason)
end
cb(nil, reason)
return
end
if code ~= 0 then
require("utils.log").warn("book netease shelf mutation failed", code)
cb(nil, code == nil and _("响应无效") or _("同步失败"))
return
end
cb(wire)
end)
end
function Client:addToShelfAsync(stable_id, cb)
return changeShelf("/subscribe.do", { operation = "addSub", id = stable_id }, cb)
end
function Client:removeFromShelfAsync(stable_id, cb)
return changeShelf("/shelf.do?operation=unsub&source_uuids=" .. Text.urlEncode(stable_id), nil, cb)
end
function Client.searchAsync(keyword, cb)
return getJson(PUBLIC .. "/search/book/data.json?key=" .. Text.urlEncode(keyword), {}, function(wire, err)
if not wire then cb(nil, err); return end
cb(Mapper.searchBooks(wire))
end)
end
function Client.categoriesAsync(cb)
return Request.get(PUBLIC .. "/category", { cache_ttl = 3600 }, function(raw, err)
if err or not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
cb(Mapper.categories(raw))
end)
end
---@param options { channel: string, category: string, sort: string, pay: string, state: string }
---@param page integer
function Client.catalogAsync(options, page, cb)
local publish = options.channel == "publish"
local fields = {
id = options.category == "all" and "" or options.category,
sort = options.sort == "hot" and (publish and 1 or 2) or (publish and 2 or 1),
pay = options.pay, page = page,
}
if not publish then fields.gender, fields.state = options.channel, options.state end
local url = PUBLIC .. (publish and "/category/publish/data.json?" or "/category/original/data.json?")
.. Text.formEncode(fields)
return getJson(url, {}, function(wire, err)
if not wire then cb(nil, err); return end
cb(Mapper.catalog(wire))
end)
end
function Client.infoAsync(stable_id, cb)
return getJson(ORIGIN .. "/getBook.do?id=" .. Text.urlEncode(stable_id), opts(), function(wire, err)
if not wire then cb(nil, err); return end
if not Mapper.detail(wire) then cb(nil, _("响应无效")); return end
cb(wire)
end)
end
---@param chapter { uid?: string, leaf?: boolean, big_content_id?: string }
function Client.contentAsync(stable_id, chapter, cb)
local url = ORIGIN .. (chapter.leaf == false and "/getChapterContent.do?" or "/getArticleContent.do?")
.. Text.formEncode({
sourceUuid = stable_id, articleUuid = chapter.uid, bigContentId = chapter.big_content_id,
})
return getJson(url, opts(), function(wire, err)
if not wire then cb(nil, err); return end
if tonumber(wire.resultCode) == 1 then cb(nil, _("本章未购买")); return end
if tonumber(wire.resultCode) ~= 0 then cb(nil, _("请求失败")); return end
cb(Mapper.content(wire))
end)
end
function Client.commentsAsync(stable_id, cb)
local url = ORIGIN .. "/snsComment.do?operation=get&type=2&page=1&id=" .. Text.urlEncode(stable_id)
return getJson(url, opts(), function(wire, err)
if not wire then cb(nil, err); return end
local items, pages = Mapper.comments(wire)
if not items then cb(nil, _("网易云阅读书评加载失败")); return end
cb(items, nil, pages)
end)
end
function Client.putProgressAsync(stable_id, toc, idx, fraction, cb)
if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录网易云阅读")) end
local fields = Mapper.readlog(stable_id, toc, idx, fraction, os.time() * 1000)
if not fields then return require("source.base").defer(cb, nil, _("缺少网易云阅读章节位置")) end
-- 官网匿名写进度也返回 1;先确认会话,避免把未同步的本地进度标成成功。
local cancelled, job, pending = false, nil, true
local options = opts()
local initial = Client.loginCheckAsync(options.account, function(valid, reason, expired)
pending = false
if cancelled then return end
if not valid then
if expired and options.account == require("utils.settings").getSource(SOURCE_ID).cookie then
reason = require("source.auth").expire(SOURCE_ID, _("网易云阅读登录已失效"))
end
cb(nil, reason)
return
end
job = Request.post(ORIGIN .. "/addUserReadLog.do", Text.formEncode(fields), options, function(raw, err)
if cancelled then return end
if err or tonumber(raw) ~= 1 then
cb(nil, err and tostring(err) or _("网易云阅读进度保存失败"))
return
end
require("source.auth").ok(SOURCE_ID)
cb(true)
end)
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
return Client
@@ -0,0 +1,48 @@
return {
["网易云阅读"] = "NetEase Cloud Reading",
["网易云阅读在线阅读"] = "NetEase Cloud Reading online books",
["网易云阅读目录为空"] = "NetEase Cloud Reading chapter list is empty",
["网易云阅读书评加载失败"] = "Could not load NetEase Cloud Reading reviews",
["未登录网易云阅读"] = "Not signed in to NetEase Cloud Reading",
["网易云阅读书架读取失败,请在官网确认登录"] = "Could not read the NetEase bookshelf. Check your sign-in on the official website",
["网易云阅读登录已失效"] = "NetEase Cloud Reading sign-in has expired",
["缺少网易云阅读章节位置"] = "Missing the NetEase Cloud Reading chapter position",
["网易云阅读进度保存失败"] = "Could not save the NetEase Cloud Reading position",
["网易云阅读账号"] = "NetEase Cloud Reading account",
["网易云阅读手机号未注册"] = "This phone number is not registered with NetEase Cloud Reading",
["网易云阅读密码错误"] = "Wrong NetEase Cloud Reading password",
["图形验证码错误"] = "Wrong image code",
["请输入图形码"] = "Enter the characters in the image",
["图形验证码加载失败"] = "Could not load the image code",
["确定退出网易云阅读账号?"] = "Sign out of NetEase Cloud Reading?",
["网易云阅读图形验证码"] = "NetEase Cloud Reading image code",
["正文为空"] = "Chapter text is empty",
["用微信扫一扫"] = "Scan with WeChat",
["打开微信,扫屏幕上的二维码"] = "Open WeChat and scan the QR code",
["本章未购买"] = "This chapter has not been purchased",
["出版"] = "Published",
["价格"] = "Price",
["免费"] = "Free",
["付费"] = "Paid",
["连载中"] = "Ongoing",
["已完结"] = "Completed",
["微信扫码登录"] = "WeChat QR login",
["正在登录…"] = "Signing in…",
["正在获取二维码…"] = "Fetching QR code…",
["章节目录保存失败"] = "Failed to save chapter list",
["已在微信中拒绝登录"] = "Login declined in WeChat",
["手机号"] = "Phone number",
["请填写正确的手机号"] = "Enter a valid phone number",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header",
["女频"] = "Female",
["男频"] = "Male",
["网易云阅读登录 Cookie"] = "NetEase Cloud Reading sign-in cookie",
["网易云阅读登录校验失败,请在浏览器重新登录"] = "NetEase Cloud Reading sign-in verification failed. Please sign in again in your browser",
["VIP 章节"] = "VIP chapters",
["书架同步"] = "Shelf sync",
["搜索与发现"] = "Search and discover",
["进度同步"] = "Progress sync",
["手机号密码登录"] = "Sign in with phone and password",
["请填写密码"] = "Enter your password",
["刷新"] = "Refresh",
}
@@ -0,0 +1,48 @@
return {
["网易云阅读"] = "網易雲閱讀",
["网易云阅读在线阅读"] = "網易雲閱讀線上閱讀",
["网易云阅读目录为空"] = "網易雲閱讀目錄為空",
["网易云阅读书评加载失败"] = "網易雲閱讀書評載入失敗",
["未登录网易云阅读"] = "未登入網易雲閱讀",
["网易云阅读书架读取失败,请在官网确认登录"] = "無法讀取網易雲閱讀書架,請在官網確認登入狀態",
["网易云阅读登录已失效"] = "網易雲閱讀登入已失效",
["缺少网易云阅读章节位置"] = "缺少網易雲閱讀章節位置",
["网易云阅读进度保存失败"] = "網易雲閱讀進度保存失敗",
["网易云阅读账号"] = "網易雲閱讀帳號",
["网易云阅读手机号未注册"] = "這個手機號還沒註冊網易雲閱讀",
["网易云阅读密码错误"] = "網易雲閱讀密碼錯誤",
["图形验证码错误"] = "圖形驗證碼錯誤",
["请输入图形码"] = "請輸入圖形碼",
["图形验证码加载失败"] = "圖形驗證碼載入失敗",
["确定退出网易云阅读账号?"] = "確定退出網易雲閱讀帳號?",
["网易云阅读图形验证码"] = "網易雲閱讀圖形驗證碼",
["正文为空"] = "正文為空",
["用微信扫一扫"] = "用微信掃一掃",
["打开微信,扫屏幕上的二维码"] = "打開微信,掃螢幕上的二維碼",
["本章未购买"] = "本章未購買",
["出版"] = "出版",
["价格"] = "價格",
["免费"] = "免費",
["付费"] = "付費",
["连载中"] = "連載中",
["已完结"] = "已完結",
["微信扫码登录"] = "微信掃碼登入",
["正在登录…"] = "正在登入…",
["正在获取二维码…"] = "正在取得二維碼…",
["章节目录保存失败"] = "章節目錄儲存失敗",
["已在微信中拒绝登录"] = "已在微信中拒絕登入",
["手机号"] = "手機號碼",
["请填写正确的手机号"] = "請填寫正確的手機號碼",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie",
["女频"] = "女頻",
["男频"] = "男頻",
["网易云阅读登录 Cookie"] = "網易雲閱讀登入 Cookie",
["网易云阅读登录校验失败,请在浏览器重新登录"] = "網易雲閱讀登入驗證失敗,請在瀏覽器重新登入",
["VIP 章节"] = "VIP 章節",
["书架同步"] = "書架同步",
["搜索与发现"] = "搜尋與發現",
["进度同步"] = "進度同步",
["手机号密码登录"] = "手機號碼密碼登入",
["请填写密码"] = "請填寫密碼",
["刷新"] = "重新整理",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_netease._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,305 @@
--[[--
网易云阅读响应到书籍、目录和正文。
电脑端目录来自 getBook.do,分卷也保留为章节,避免改变已有章节序号。
正文的 x 字段指定 XOR / AES 解密顺序;没有 x 时为标准 Base64。
@module moonsource_netease.mapper
--]]
local Text = require("utils.text")
local JSON = require("json")
local _ = require("l10n").get("moonsource_netease")
---@class NeteaseChapter : BookChapter
---@field big_content_id string|nil
---@field leaf boolean|nil
local Mapper = {}
Mapper.TOC_VERSION = 2
local SOURCE_ID = "ext.netease"
function Mapper.authorized(html)
return type(html) == "string" and html:find("<title[^>]*>个人资料[^<]*</title>") ~= nil
and html:find('id=["\']editNickName["\']') ~= nil
end
---@param value any
---@return string
local function clean(value)
if type(value) ~= "string" then return "" end
return Text.trim(value)
end
---@param value any
---@return string|nil
local function picture(value)
if type(value) ~= "string" or value == "" then return nil end
if value:sub(1, 2) == "//" then return "https:" .. value end
return value
end
---@param row table
---@return string|nil
local function stableId(row)
if row.sourceUuid ~= nil and tostring(row.sourceUuid) ~= "" then return tostring(row.sourceUuid) end
if type(row.sourceUrl) == "string" then
local id = row.sourceUrl:match("/source/([^/?#]+)")
if id and id ~= "" then return id end
end
return nil
end
---@param row table
---@return Book|nil
local function book(row)
local id = stableId(row)
local title = clean(row.title or row.bookName)
if not id or title == "" then return nil end
return {
source_id = SOURCE_ID,
stable_id = id,
title = title,
authors = clean(row.author or row.authorName),
intro = clean(row.description or row.intro),
cover = picture(row.iconUrl or row.coverImage or row.cover),
}
end
---@param rows table|nil
---@return Book[]
function Mapper.books(rows)
local out = {}
if type(rows) ~= "table" then return out end
for _idx, row in ipairs(rows) do
if type(row) == "table" then
local item = book(row)
if item then out[#out + 1] = item end
end
end
return out
end
---@param wire table|nil
---@return Book[]|nil
---@return string|nil
function Mapper.searchBooks(wire)
if type(wire) ~= "table" or tonumber(wire.code) ~= 0 or type(wire.data) ~= "table" then
return nil, type(wire) == "table" and wire.error or nil
end
return Mapper.books(wire.data.books)
end
--- 分类取官网实际目录,不在客户端另存一份容易过时的分类编码。
function Mapper.categories(html)
local categories = { male = {}, female = {}, publish = {} }
local seen = {}
for href, label in html:gmatch('<a[^>]-href=["\']([^"\']+)["\'][^>]*>(.-)</a>') do
href = Text.xmlDecode(href)
local id = href:match("[?&]id=(%d+)")
local channel = href:match("/category/original%.do%?gender=(%a+)")
if href:find("/category/publish.do?", 1, true) then channel = "publish" end
if id and categories[channel] and not seen[channel .. ":" .. id] then
seen[channel .. ":" .. id] = true
local rows = categories[channel]
rows[#rows + 1] = { id = id, title = Text.stripHtml(label) }
end
end
for _channel, rows in pairs(categories) do
if #rows == 0 then return nil, _("响应无效") end
end
return categories
end
function Mapper.catalog(wire)
local data = type(wire) == "table" and wire.data
if type(wire) ~= "table" or tonumber(wire.code) ~= 0 or type(data) ~= "table" or type(data.books) ~= "table"
or type(data.pageQuery) ~= "table" or type(data.pageQuery.more) ~= "boolean" then
return nil, _("响应无效")
end
local books = Mapper.books(data.books)
if #books ~= #data.books then return nil, _("响应无效") end
return books, nil, data.pageQuery.more
end
--- 官网书架是服务端 HTML;每行的分享数据携带结构化书籍身份,不能当搜索 JSON 解析。
---@param html string
---@param page integer
---@return Book[]|nil
---@return integer|nil next_page
---@return string|nil err
function Mapper.shelfPage(html, page)
if not html:find("<title[^>]*>[^<]*我的书架") then
return nil, nil, _("网易云阅读书架读取失败,请在官网确认登录")
end
local books, seen = {}, {}
for row in html:gmatch('<div[^>]-class=["\']m%-bookshow["\'][^>]*>(.-)</li>') do
if not row:find('data%-local=["\']true["\']') then
local encoded = row:match('data%-contentinfo="([^"]*)"') or row:match("data%-contentinfo='([^']*)'")
local ok, info = pcall(JSON.decode, Text.xmlDecode(encoded or ""))
if not ok or type(info) ~= "table" then return nil, nil, _("响应无效") end
local item = book({
sourceUuid = info.sourceUuid, title = info.sourceTitle,
iconUrl = info.imageUrl, description = info.imageDescription,
author = Text.stripHtml(row:match("<p[^>]*>(.-)</p>") or ""),
})
if not item then return nil, nil, _("响应无效") end
if not seen[item.stable_id] then
seen[item.stable_id] = true
books[#books + 1] = item
end
end
end
local next_page
for encoded in html:gmatch('href=["\']([^"\']+)["\']') do
local link = Text.xmlDecode(encoded)
local target = tonumber(link:match("[?&]page=(%d+)"))
if link:find("/shelf.do?", 1, true) and link:find("operation=query_current", 1, true)
and target and target > page and (not next_page or target < next_page) then
next_page = target
end
end
return books, next_page
end
---@param wire table|nil
---@return Book|nil
function Mapper.detail(wire)
if type(wire) ~= "table" or type(wire.portions) ~= "table" then return nil end
return book({
sourceUuid = wire.id, title = wire.title, author = wire.author,
description = wire.shareDescription, coverImage = wire.coverImg,
})
end
---@param wire table|nil
---@return NeteaseChapter[]|nil
function Mapper.chapters(wire)
local rows = type(wire) == "table" and wire.portions or nil
if type(rows) ~= "table" then return nil end
local out = {}
for _idx, row in ipairs(rows) do
if type(row) == "table" and row.id ~= nil and tostring(row.id) ~= "" then
out[#out + 1] = {
idx = #out + 1,
uid = tostring(row.id),
title = clean(row.title),
sec_id = tostring(row.id),
big_content_id = row.bigContentId,
leaf = row.leafNode,
word_count = tonumber(row.charSize),
vip = tonumber(row.needPay) == 1 and row.isPaid ~= true,
}
end
end
if out[1] then out[1].toc_version = Mapper.TOC_VERSION end
return out
end
--- 电脑端以章节 UUID 定位;匿名响应带默认章节,但没有阅读时间。
---@param wire table|nil
---@return integer|nil
function Mapper.progressIndex(wire)
if type(wire) ~= "table" or (tonumber(wire.curDate) or 0) <= 0 then return nil end
for idx, row in ipairs(wire.portions or {}) do
if row.id == wire.curArticleUuid then return idx end
end
end
--- 电脑端章内百分比是 0..100,不是比例 0..1。
---@param stable_id string
---@param toc BookChapter[]|nil
---@param idx number|nil
---@param fraction number|nil
---@param now_ms number
---@return table|nil
function Mapper.readlog(stable_id, toc, idx, fraction, now_ms)
if type(toc) ~= "table" or type(idx) ~= "number" then return nil end
idx = math.floor(idx)
local chapter = toc[idx]
if type(chapter) ~= "table" or type(chapter.uid) ~= "string" or chapter.uid == "" then
return nil
end
local page = tonumber(fraction) or 0
if page < 0 then page = 0 end
if page > 1 then page = 1 end
return {
sourceUuid = stable_id,
articleUuid = chapter.uid,
curPagePercent = page * 100,
date = now_ms,
}
end
--- 书评。网页模板用的字段:username、text、posttime、grade、likes、replied.username。
--- 第二返回值是总页数,没有分页信息就是 nil。
---@param wire table|nil
---@return { author: string, text: string, time: string|nil, grade: number|nil, likes: number|nil, reply_to: string|nil }[]|nil
---@return integer|nil
function Mapper.comments(wire)
if type(wire) ~= "table" or tonumber(wire.resultCode) ~= 0 or type(wire.data) ~= "table" then
return nil
end
local out = {}
for _idx, row in ipairs(wire.data) do
if type(row) == "table" and type(row.text) == "string" then
local item = {
author = type(row.username) == "string" and row.username or "",
text = row.text,
time = type(row.posttime) == "string" and row.posttime or nil,
grade = tonumber(row.stars),
likes = tonumber(row.likes),
}
if type(row.replied) == "table" and type(row.replied.username) == "string" then
item.reply_to = row.replied.username
end
out[#out + 1] = item
end
end
return out, tonumber(wire.totalPage)
end
--- XOR 作用于 JavaScript UTF-16 码元,而不是 UTF-8 字节。
local function xor(text, key)
local bxor = require("bit").bxor
local Glyph = require("utils.glyph")
return (text:gsub(Text.UTF8_CHAR, function(ch)
local cp = Glyph.codepoint(ch)
if cp <= 0xFFFF then return Text.utf8char(bxor(cp, key)) end
cp = cp - 0x10000
local high = bxor(0xD800 + math.floor(cp / 0x400), key)
local low = bxor(0xDC00 + cp % 0x400, key)
return Text.utf8char(0x10000 + (high - 0xD800) * 0x400 + low - 0xDC00)
end))
end
--- 正文解码失败必须报错,不得把密文写进章节缓存。
---@param wire table|nil
---@return string|nil
function Mapper.content(wire)
local cipher = type(wire) == "table" and wire.content or nil
if type(cipher) ~= "string" or cipher == "" then return nil, _("正文为空") end
local html = Text.base64Decode(cipher)
if type(wire.x) == "string" and wire.x ~= "" then
local ok, steps = pcall(JSON.decode, Text.base64Decode(wire.x))
if not ok or type(steps) ~= "table" or #steps < 1 or #steps > 2 then
return nil, _("正文解析失败")
end
for _idx, step in ipairs(steps) do
if type(step) ~= "table" then return nil, _("正文解析失败") end
local decoded, value
if step.m == 1 and tonumber(step.k) then
decoded, value = pcall(xor, html, tonumber(step.k))
elseif step.m == 2 and type(step.k) == "string" and html:match("^%x+$") and #html % 32 == 0 then
local Aes = require("crypto.aes")
decoded, value = pcall(Aes.ecb_decrypt, Aes.from_hex(html), step.k)
end
if not decoded then return nil, _("正文解析失败") end
html = value
end
end
if html == "" then return nil, _("正文为空") end
return html
end
return Mapper
@@ -0,0 +1,92 @@
--[[--
网易云阅读微信开放平台扫码,确认后由网易回调换取电脑端 Cookie。
@module moonsource_netease.qrlogin
--]]
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_netease")
local QRLogin = {}
QRLogin.__index = QRLogin
function QRLogin:new(on_user)
return setmetatable({ on_user = on_user, generation = 0 }, QRLogin)
end
function QRLogin:cancel()
self.generation = self.generation + 1
if self.session then self.session:cancel() end
if self.poll then require("ui/uimanager"):unschedule(self.poll); self.poll = nil end
if self.waiting then self.waiting:close(); self.waiting = nil end
if self.dialog then
local dialog = self.dialog
self.dialog = nil
dialog:close()
end
end
function QRLogin:retry(text)
self:cancel()
require("ui.themes.widgets.confirm"):new{
text = text, ok_text = _("重新获取"), ok_callback = function() self:start() end,
}:show()
end
function QRLogin:pollAsync(gen, uuid, last)
if gen ~= self.generation then return end
if os.time() >= self.deadline then self:retry(_("二维码已过期")); return end
self.session:qrPollAsync(uuid, last, function(status, code, err)
if gen ~= self.generation then return end
if status == 405 then
self.session:exchangeAsync(code, function(ok, reason)
if gen ~= self.generation then return end
if not ok then self:retry(reason or _("登录失败")); return end
self:cancel()
self.on_user()
end)
return
end
if status ~= 404 and status ~= 408 then
self:retry(err or (status == 403 and _("已在微信中拒绝登录") or _("二维码已过期")))
return
end
if status == 404 and last ~= 404 then
require("ui.themes.widgets.toast"):new{ text = _("已扫码,请在手机上确认") }:show()
end
self.poll = function()
self.poll = nil
self:pollAsync(gen, uuid, status)
end
require("ui/uimanager"):scheduleIn(1, self.poll)
end)
end
function QRLogin:start()
self:cancel()
local gen = self.generation
self.session = require("moonsource_netease.auth").new()
self.deadline = os.time() + 300
self.waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("微信扫码登录"), text = _("正在获取二维码…"),
on_cancel = function() self:cancel() end,
}
self.waiting:show()
self.session:qrCreateAsync(function(uuid, err)
if gen ~= self.generation then return end
self.waiting:close()
self.waiting = nil
if not uuid then self:retry(err or _("获取二维码失败")); return end
self.dialog = require("ui.themes.widgets.qr"):new{
title = _("微信扫码登录"), caption = _("用微信扫一扫"),
text = "https://open.weixin.qq.com/connect/confirm?uuid=" .. Text.urlEncode(uuid),
close_callback = function()
if gen == self.generation then self:cancel() end
end,
}
self.dialog:show()
self:pollAsync(gen, uuid)
end)
end
return QRLogin
@@ -0,0 +1,156 @@
--[[--
网易云阅读电脑端账号:手机号密码、微信扫码、电脑浏览器 Cookie。
@module moonsource_netease.setting
--]]
local _ = require("l10n").get("moonsource_netease")
local CookieLogin = require("source.cookie_login")
local SOURCE_ID = "ext.netease"
local Setting = {}
local LOGIN_URL = "https://yuedu.163.com/loginForm.do?targetUrl=https%3A%2F%2Fyuedu.163.com%2Fmyinfor.do"
local function loggedIn()
return require("moonsource_netease.client").loggedIn()
end
local SPEC = {
id = SOURCE_ID,
title = _("网易云阅读账号"),
cookie_title = _("网易云阅读登录 Cookie"),
cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"),
logout_text = _("确定退出网易云阅读账号?"),
loggedIn = loggedIn,
checkAsync = function(cookie, cb)
return require("moonsource_netease.client").loginCheckAsync(cookie, cb)
end,
store = function(cfg, cookie)
cfg.cookie, cfg.logged_in, cfg.csrf = cookie, true, nil
end,
clear = function(cfg)
cfg.cookie, cfg.csrf, cfg.logged_in = nil, nil, nil
end,
}
Setting.browser = {
domain = "yuedu.163.com",
scope = "cookie",
login = LOGIN_URL,
check = "https://yuedu.163.com/myinfor.do",
icon = "https://yuedust.yuedu.126.net/favicon.ico",
isAuthorized = function() return CookieLogin.authorized(SPEC) end,
apply = function(payload, cb)
CookieLogin.save(SPEC, CookieLogin.fromPayload(payload, "163.com"), cb)
end,
}
local function connected()
if require("ui/network/manager"):isConnected() then return true end
require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show()
return false
end
local function onLogin()
require("source.registry").reload()
require("ui.themes.widgets.toast"):new{ text = _("登录成功"), timeout = 2 }:show()
end
local function showLogin()
local Toast = require("ui.themes.widgets.toast")
local session = require("moonsource_netease.auth").new()
local closed, busy, verification, waiting = false, false, nil, nil
local dialog
local function submit(phone, password, code)
if closed or busy or not connected() then return end
busy = true
waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("网易云阅读账号"), text = _("正在登录…"),
on_cancel = function()
session:cancel()
busy = false
waiting:close()
waiting = nil
end,
}
waiting:show()
session:passwordAsync(phone, password, code, function(ok, err, needs_code)
busy = false
waiting:close()
waiting = nil
if closed then return end
if ok then dialog:close(); onLogin(); return end
Toast:new{ text = err or _("登录失败"), timeout = 3 }:show()
if needs_code then
verification = require("moonsource_netease.verify").new(session, function(value)
verification = nil
if value then submit(phone, password, value) end
end)
end
end)
end
dialog = require("ui.themes.widgets.input"):new{
title = _("网易云阅读账号"),
keep_open = true,
fields = {
{ label = _("手机号"), text = "", input_type = "number" },
{ label = _("密码"), text = "", text_type = "password" },
},
ok_text = _("登录"),
close_callback = function()
closed = true
if verification then verification:cancel() end
session:cancel()
if waiting then waiting:close(); waiting = nil end
end,
callback = function(phone, password)
phone = require("utils.text").trim(phone)
if #phone ~= 11 or not phone:match("^%d+$") then
Toast:new{ text = _("请填写正确的手机号"), timeout = 3 }:show()
return
end
if password == "" then
Toast:new{ text = _("请填写密码"), timeout = 3 }:show()
return
end
submit(phone, password)
end,
}
dialog:show()
end
function Setting.rowStatus()
local on = loggedIn()
return on and _("已登录") or _("未登录 · 点此登录"), on
end
function Setting.rows()
local Row = require("ui.themes.widgets.row")
local rows = {
function(iw)
local status, status_on = Setting.rowStatus()
return Row.widget({
width = iw, chevron = true, kind = "nav", icon = "account_circle",
title = _("网易云阅读账号"), subtitle = _("手机号密码登录"),
status = status, status_on = status_on, callback = showLogin,
})
end,
function(iw)
return Row.widget({
width = iw, chevron = true, kind = "nav", icon = "qr_code",
title = _("微信扫码登录"), subtitle = _("打开微信,扫屏幕上的二维码"),
callback = function()
if connected() then require("moonsource_netease.qrlogin"):new(onLogin):start() end
end,
})
end,
CookieLogin.browserRow(),
CookieLogin.pasteRow(SPEC),
}
if loggedIn() then rows[#rows + 1] = CookieLogin.logoutRow(SPEC) end
return rows
end
Setting.login = showLogin
return Setting
@@ -0,0 +1,257 @@
--[[--
网易云阅读数据源。
搜索、榜单和免费章节不需要登录。未购买章节给一页提示。
手机号密码或微信扫码登录后,电脑端 Cookie 用于书架与阅读。
书架本地优先增删,联网后经公共书架同步推到官网。
@module moonsource_netease
--]]
local Browse = require("source.browse")
local Client = require("moonsource_netease.client")
local Mapper = require("moonsource_netease.mapper")
local SourceBase = require("source.base")
local Text = require("utils.text")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_netease")
local Netease = {}
---@return BookSourceMeta
function Netease.meta()
return require("moonsource_netease.loadmeta")()
end
---@class NeteaseSource : SourceBase
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
Source.__index = Source
---@return NeteaseSource
function Netease.new()
local meta = Netease.meta()
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source)
end
--- 未登录仍可搜索和读免费章节。进度上行只在登录后发生,避免每次唤醒都重试。
---@return boolean
function Source:configured()
return Client.loggedIn()
end
function Source:syncBooksAsync(opts, cb)
if not self:configured() then return SourceBase.skipped(cb, "netease not logged in") end
return require("source.shelf").syncAsync(self.id, Client, nil, opts, cb)
end
---@param keyword string
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
function Source:searchAsync(keyword, cb)
return Client.searchAsync(keyword, function(books, err)
if not books then cb(nil, err or _("请求失败")); return end
cb({ data = books })
end)
end
---@param opts { node?: string, limit?: integer }|nil
---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil)
function Source:browseAsync(opts, cb)
local node = opts and opts.node or ""
local channel, category, sort, pay, state = node:match(
"^(%a+):(%w+):(%a+):([012]):([012])$")
channel = channel or node
if channel ~= "male" and channel ~= "female" and channel ~= "publish" then channel = "male" end
if sort ~= "new" then sort = "hot" end
category, pay, state = category or "all", pay or "0", state or "0"
if channel == "publish" then state = "0" end
local cancelled, job, pending = false, nil, true
local initial = Client.categoriesAsync(function(categories, err)
pending = false
if cancelled then return end
if not categories then cb(nil, err); return end
local valid = category == "all"
for _idx, row in ipairs(categories[channel]) do
if row.id == category then valid = true end
end
if not valid then category = "all" end
local values = { channel, category, sort, pay, state }
local function chips(title, rows, position)
local list = {}
for _idx, row in ipairs(rows) do
local node = { unpack(values) }
node[position] = row.id
if position == 1 then node[2], node[5] = "all", "0" end
list[#list + 1] = { id = table.concat(node, ":"), title = row.title }
end
local active = { unpack(values) }
if position == 1 then active[2], active[5] = "all", "0" end
local group = Browse.group(list, table.concat(active, ":"))
group.title = title
return group
end
local cats = { { id = "all", title = _("全部") } }
for _idx, row in ipairs(categories[channel]) do cats[#cats + 1] = row end
local groups = {
chips(nil, {
{ id = "male", title = _("男频") }, { id = "female", title = _("女频") },
{ id = "publish", title = _("出版") },
}, 1),
chips(_("分类"), cats, 2),
chips(_("排序"), { { id = "hot", title = _("热门") }, { id = "new", title = _("最新") } }, 3),
chips(_("价格"), {
{ id = "0", title = _("全部") }, { id = "1", title = _("免费") }, { id = "2", title = _("付费") },
}, 4),
}
if channel ~= "publish" then
groups[#groups + 1] = chips(_("状态"), {
{ id = "0", title = _("全部") }, { id = "1", title = _("连载中") }, { id = "2", title = _("已完结") },
}, 5)
end
job = Browse.pages(function(page, done)
return Client.catalogAsync({
channel = channel, category = category, sort = sort, pay = pay, state = state,
}, page, done)
end, opts and opts.limit or 60, groups, function(result, reason)
if not cancelled then cb(result, reason) end
end)
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
function Source:getDetailAsync(identity, cb)
return Client.infoAsync(identity.stable_id, function(wire, err)
local detail = wire and Mapper.detail(wire)
if detail then cb(require("book.store").rememberDetail(detail)); return end
local row = identity.book or require("book.books_db").get(self.id, identity.stable_id)
if row then cb(row); return end
cb(nil, err or _("请求失败"))
end)
end
---@param self NeteaseSource
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
local function fetchTocAsync(self, identity, cb)
return Client.infoAsync(identity.stable_id, function(wire, err)
if not wire then cb(nil, err); return end
local toc = Mapper.chapters(wire)
if not toc or #toc == 0 then cb(nil, _("网易云阅读目录为空")); return end
if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end
cb(toc)
end)
end
function Source:loadTocAsync(identity, cb, force)
if not force then
local cached = Toc.read(self.id, identity.stable_id)
if cached and #cached > 0 and (cached[1].toc_version == Mapper.TOC_VERSION
or not require("ui/network/manager"):isConnected()) then
return SourceBase.defer(cb, cached)
end
end
return fetchTocAsync(self, identity, cb)
end
Source.refreshTocAsync = fetchTocAsync
---@param open boolean
---@return ChapterFetchContent
local function fetcher(open)
return function(identity, chapter, done)
local function finish(html, err)
if html then
if chapter.vip then Toc.markPaid("ext.netease", identity.stable_id, chapter.uid, true) end
done({ title = chapter.title, html = html })
return
end
if not open or err ~= _("本章未购买") then done(nil, err); return end
local notice = string.format(_("这是 VIP 章节,你还没有购买。\n请先在%s购买本章,再回来阅读。"), _("网易云阅读"))
done({ title = chapter.title, html = Text.chapterHtml(chapter.title, notice), temporary = true })
end
if chapter.vip and not Client.loggedIn() then return finish(nil, _("本章未购买")) end
return Client.contentAsync(identity.stable_id, chapter, finish)
end
end
function Source:openBookAsync(identity, opts, cb)
local Chapter = require("source.chapter")
local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi
return open(self, identity, identity.book, opts, {
loadToc = function(ref, done) return self:loadTocAsync(ref, done) end,
fetchContent = fetcher(true),
}, cb)
end
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
local Chapter = require("source.chapter")
return Chapter.prefetchAsync(identity, identity.book, toc, from_idx, count, {
fetchContent = fetcher(false),
}, cb)
end
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
local Chapter = require("source.chapter")
return Chapter.cacheAllAsync(self, identity, fetcher(false), on_progress, cb, nil, range, nil)
end
function Source:getProgressAsync(identity, cb)
local cancelled, job = false, nil
job = Client.infoAsync(identity.stable_id, function(wire, err)
if cancelled then return end
if not wire then cb(nil, err); return end
local toc = Mapper.chapters(wire)
local idx = Mapper.progressIndex(wire)
if not toc or not idx or not toc[idx] then cb(nil, nil, { empty = true }); return end
if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end
local chapter_fraction = math.max(0, math.min(1, (tonumber(wire.curPagePercent) or 0) / 100))
cb({
chapter_idx = idx,
chapter_title = toc[idx].title,
chapter_fraction = chapter_fraction,
fraction = (idx - 1 + chapter_fraction) / #toc,
extra = { chapter_uid = toc[idx].uid, chapter_idx = idx, chapter_fraction = chapter_fraction },
})
end)
return { cancel = function()
cancelled = true
if job and job.cancel then job.cancel() end
end }
end
function Source:bookReviewsAsync(identity, cb)
return Client.commentsAsync(identity.stable_id, function(items, err, pages)
if not items then cb(nil, err); return end
cb({ items = items, pages = pages })
end)
end
function Source:putProgressAsync(identity, pos, cb)
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录网易云阅读")) end
local cancelled, job, pending = false, nil, true
local initial = self:loadTocAsync(identity, function(toc, err)
pending = false
if cancelled then return end
if not toc then cb(nil, err); return end
local idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx)
if idx then idx = math.floor(idx) end
local chapter = idx and toc[idx]
if not chapter then
cb(nil, _("缺少网易云阅读章节位置"))
return
end
job = Client.putProgressAsync(identity.stable_id, toc, idx, pos.chapter_fraction, function(ok, perr)
cb(ok and true or nil, perr)
end)
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job and job.cancel then job.cancel() end
end }
end
return Netease
@@ -0,0 +1,72 @@
--[[--
电脑端密码登录的图形验证码,与登录窗口共用匿名会话。
@module moonsource_netease.verify
--]]
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_netease")
local Verification = {}
Verification.__index = Verification
function Verification:cancel()
if self.done then return end
self.done = true
self.session:cancel()
if self.waiting then self.waiting:close(); self.waiting = nil end
if self.dialog then self.dialog:close(); self.dialog = nil end
end
function Verification:finish(code)
if self.done then return end
self:cancel()
self.callback(code)
end
function Verification:load()
if self.done then return end
if self.dialog then self.dialog:close(); self.dialog = nil end
self.waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("网易云阅读图形验证码"), text = _("正在加载…"),
on_cancel = function() self:finish() end,
}
self.waiting:show()
self.session:captchaAsync(function(raw, err)
if self.done then return end
self.waiting:close()
self.waiting = nil
local bitmap = raw and require("ui/renderimage"):renderImageData(raw, #raw, false)
if not bitmap then
require("ui.themes.widgets.toast"):new{ text = err or _("图形验证码加载失败") }:show()
self:finish()
return
end
local Theme = require("ui.themes")
self.dialog = require("ui.themes.widgets.input"):new{
title = _("网易云阅读图形验证码"),
header_widget = require("ui/widget/imagewidget"):new{
image = bitmap, width = Theme.px(180), height = Theme.px(90), scale_factor = 0, alpha = true,
},
fields = { { label = _("请输入图形码"), text = "" } },
ok_text = _("登录"),
cancel_callback = function() self:finish() end,
actions = { { text = _("刷新"), callback = function() self:load() end } },
validate = function(code)
if Text.trim(code) ~= "" then return not self.done end
require("ui.themes.widgets.toast"):new{ text = _("请输入图形码") }:show()
return false
end,
callback = function(code) self:finish(Text.trim(code)) end,
}
self.dialog:show()
end)
end
function Verification.new(session, cb)
local self = setmetatable({ session = session, callback = cb }, Verification)
self:load()
return self
end
return Verification
+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)