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

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

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

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# 掌阅
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| App 扫码登录 | 已实现,未实测 | 校验候选会话后保存 |
| 浏览器登录与 Cookie 导入 | 支持 | 从电脑站 Cookie 解析必要会话并校验 |
| 设备密码与短信登录 | 不支持 | 其他方式可在官网完成后导入 Cookie |
| 书架拉取 | 支持 | 过滤文件夹和本机上传书 |
| 加入远端书架 | 已实现,未实测 | 本地先生效,后续同步上传 |
| 移出远端书架 | 不支持 | 没有已接入的删除接口;本地清缓存并保留墓碑 |
| 搜索与分类书城 | 支持 | 男生、女生、出版;动态分类、排序与筛选,支持后续页 |
| 目录与正文 | 支持 | 分页目录、按章阅读、特殊字码还原及插图本地化 |
| 已购正文 | 已实现,未实测 | 以服务端权限为准;未购提示不计入正文缓存 |
| 章节与全本缓存 | 支持 | 支持预取;插图下载失败不算正文缓存成功 |
| 离线阅读 | 支持 | 已缓存正文和本地插图可读;旧远程插图需先联网补齐 |
| 阅读进度同步 | 部分支持 | 仅章节位置,无精确章内进度;真实写后回读未实测 |
| 笔记与统计同步 | 不支持 | 仅本地保存 |
| 整书书评 | 部分支持 | 仅手机 Web 首屏;本地翻阅已加载条目,不续拉 AJAX 页 |
| 章评、段评与回复 | 不支持 | 当前 Web 协议未找到可验证接口 |
| 评论写操作 | 不支持 | 不发评、不点赞、不删评 |
| 账号切换 | 部分支持 | 同账号可续期;换号须先退出清理旧数据,未同步记录会丢失 |
+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_ireader",
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_ireader.source").meta() end,
new = function() return require("moonsource_ireader.source").new() end,
setting = lazy("moonsource_ireader.setting"),
}
@@ -0,0 +1,17 @@
--[[--
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
掌阅 PC(pc.ireader.com)扫码登录后同步 App 书架;书城搜索与频道来自手机站 m.zhangyue.com。
@module moonsource_ireader._meta
--]]
local _ = require("l10n").get("moonsource_ireader")
return {
id = "ext.ireader",
name = _("掌阅书城"),
type = "chapter",
description = _("掌阅书架与在线阅读"),
abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("VIP 章节"), _("书评"), _("扫码登录"), _("浏览器登录") },
}
@@ -0,0 +1,508 @@
--[[--
掌阅网页接口。
登录、书架、目录、进度、正文走 PC 站(api-pc.zhangyue.com,正文在 pc.ireader.com/nsr)。
设备参数 p29/p2/p3/p4/p33 来自 PC 站运行时配置,每次请求都带,和网页 axios 拦截器一致。
书城搜索与频道是手机站 m.zhangyue.com 的页面,不走这套 JSON。
插件保存扫码回包里的 usr(账号名)和 zysid(session_id),不依赖浏览器 Cookie。
@module moonsource_ireader.client
--]]
local JSON = require("json")
local Mapper = require("moonsource_ireader.mapper")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_ireader")
local Client = {}
local SOURCE_ID = "ext.ireader"
local API = "https://api-pc.zhangyue.com"
local WEB = "https://pc.ireader.com"
local STORE = "https://m.zhangyue.com"
local SUCCESS = 0
local LOGIN_EXPIRED = 600001
local HAS_IN_SHELF = 100011
local FEE_WHOLE = 10
local DEVICE = {
p29 = "zye5b814",
p2 = "104583",
p3 = "101010010",
p4 = "501603",
p33 = "com.chaozh.iReaderFree",
}
---@type table<string, number>
local fee_unit = {}
---@return { usr: string, zysid: string, name: string|nil, avatar: string|nil }|nil
function Client.session()
local cfg = require("utils.settings").getSource(SOURCE_ID)
local usr = type(cfg.usr) == "string" and cfg.usr or ""
local zysid = type(cfg.zysid) == "string" and cfg.zysid or ""
if usr == "" or zysid == "" then return nil end
return { usr = usr, zysid = zysid, name = cfg.name, avatar = cfg.avatar }
end
---@param session table|nil
---@param params table|nil
---@return string
local function query(session, params)
local form = {
usr = session and session.usr or "",
zysid = session and session.zysid or "",
}
for key, value in pairs(DEVICE) do form[key] = value end
for key, value in pairs(params or {}) do form[key] = value end
return Text.formEncode(form)
end
---@param path string
---@param session table|nil
---@param params table|nil
---@return string
local function url(path, session, params)
local base = path
if path:sub(1, 5) == "/nsr/" then
base = WEB .. path
elseif not path:find("^https?://") then
base = API .. path
end
return base .. "?" .. query(session, params)
end
--- 解 PC 站统一封套。code 0 的 body 可能再套一层 JSON 字符串。
---@param wire table
---@param session table|nil
---@return any|nil
---@return string|nil
local function bodyOf(wire, session)
local current = Client.session()
local active = session and current and current.usr == session.usr and current.zysid == session.zysid
local code = tonumber(wire.code)
if code == SUCCESS or (code == nil and type(wire.bookContent) == "string") then
if type(wire.bookContent) == "string" then return wire end
local body = wire.body
if type(body) == "string" then
local ok, inner = pcall(JSON.decode, body)
if ok and inner ~= nil then body = inner end
end
if active then require("source.auth").ok(SOURCE_ID) end
if body == nil then return true end
return body
end
if code == LOGIN_EXPIRED then
local message = _("掌阅登录已失效,请点「重新登录」,用掌阅 App 扫码。")
return nil, active and require("source.auth").expire(SOURCE_ID, message) or message
end
if code == 100001 and not session then return nil, _("未登录掌阅") end
return nil, type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("请求失败")
end
---@param raw string|nil
---@param err any
---@return table|nil
---@return string|nil
local function envelope(raw, err)
if not raw then return nil, err and tostring(err) or _("请求失败") end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then return nil, _("响应无效") end
return wire
end
---@param path string
---@param params table|nil
---@param session table|nil
---@param cb fun(body: any, err: string|nil)
---@return HttpJob
local function get(path, params, session, cb)
return Request.get(url(path, session, params), {
accept = "application/json",
cache_ttl = 0,
timeout = require("http.timeout").net(0.5),
}, function(raw, err)
local wire, reason = envelope(raw, err)
if not wire then cb(nil, reason); return end
local body, message = bodyOf(wire, session)
cb(body, message)
end)
end
function Client.get(path, params, cb)
return get(path, params, Client.session(), cb)
end
---@param path string
---@param params table|nil
---@param payload string
---@param content_type string
---@param cb fun(body: any, err: string|nil)
---@return HttpJob
local function post(path, params, payload, content_type, cb)
local session = Client.session()
return Request.post(url(path, session, params), payload, {
accept = "application/json",
content_type = content_type,
timeout = require("http.timeout").net(0.5),
}, function(raw, err)
local wire, reason = envelope(raw, err)
if not wire then cb(nil, reason); return end
local body, message = bodyOf(wire, session)
cb(body, message)
end)
end
---@param fields { name: string, value: string }[]
---@return string body
---@return string content_type
local function multipart(fields)
local boundary = "----moonireader"
local parts = {}
for _idx, field in ipairs(fields) do
parts[#parts + 1] = "--" .. boundary
.. '\r\nContent-Disposition: form-data; name="' .. field.name .. '"\r\n\r\n' .. field.value
end
parts[#parts + 1] = "--" .. boundary .. "--\r\n"
return table.concat(parts, "\r\n"), "multipart/form-data; boundary=" .. boundary
end
---@param cb fun(code: string|nil, err: string|nil)
---@return HttpJob
function Client.qrCreateAsync(cb)
return get("/bookstore/open/user/qrcode/get", nil, nil, function(body, err)
local code = Mapper.qrCode(body)
if not code then cb(nil, err or _("获取二维码失败")); return end
cb(code)
end)
end
--- 轮询不把「还没扫」当成失败。回包原样交给调用方。
---@param code string
---@param cb fun(wire: table|nil, err: string|nil)
---@return HttpJob
function Client.qrPollAsync(code, cb)
return Request.get(url("/bookstore/open/user/qrcode/result", nil, { code = code }), {
accept = "application/json",
cache_ttl = 0,
timeout = require("http.timeout").net(0.5),
}, function(raw, err)
local wire, reason = envelope(raw, err)
cb(wire, reason)
end)
end
---@param cb fun(body: table|nil, err: string|nil)
---@return HttpJob
function Client.shelfAsync(cb)
return Client.get("/bookstore/open/cloud/bookshelf/list", nil, function(body, err)
if type(body) ~= "table" or type(body.data) ~= "table" then cb(nil, err or _("响应无效")); return end
cb(body)
end)
end
---@param session table
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return HttpJob
function Client.checkSessionAsync(session, cb)
return get("/bookstore/open/cloud/bookshelf/list", nil, session, function(body, err)
if type(body) ~= "table" or type(body.data) ~= "table" then cb(nil, err or _("响应无效")); return end
cb(true)
end)
end
--- 新书插到未置顶书的最前:order 取当前最小再减一,和网页 insert 一致。
---@param rows table[]|nil
---@return integer order
---@return integer version
local function shelfCursor(rows, version)
local order = nil
for _idx, row in ipairs(type(rows) == "table" and rows or {}) do
local value = tonumber(row.order)
if row.top ~= 1 and value and (not order or value < order) then order = value end
end
return (order or 999999) - 1, tonumber(version) or 0
end
Client.shelfCursor = shelfCursor
---@param stable_id string
---@param title string
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return { cancel: fun() }
function Client.addAsync(stable_id, title, cb)
local session = Client.session()
if not session then return require("source.base").defer(cb, nil, _("未登录掌阅")) end
local handle, pending = {}, true
local initial = Client.shelfAsync(function(shelf, err)
pending = false
if handle.cancelled then return end
if not shelf then cb(nil, err); return end
local current = Client.session()
if not current or current.usr ~= session.usr or current.zysid ~= session.zysid then
cb(nil, _("登录状态已变化,请重试"))
return
end
local order, version = shelfCursor(shelf.data, shelf.current_version)
local data = JSON.encode({ {
dtype = 0,
order = order,
folder = "",
md5 = "",
top = 0,
top_sort = 0,
book_id = tostring(stable_id),
book_name = title,
book_type = 24,
cover_name = "",
is_local_book = false,
book_file_id = "",
book_file_size = 0,
cover_file_id = "",
cover_file_size = 0,
folder_hierarchy = "[]",
} })
local payload, content_type = multipart({
{ name = "usr", value = session.usr },
{ name = "current_version", value = tostring(version) },
{ name = "type", value = "1" },
{ name = "data", value = data },
})
handle.job = Request.post(url("/bookstore/open/cloud/bookshelf/upsert", session), payload, {
accept = "application/json",
content_type = content_type,
timeout = require("http.timeout").net(0.5),
}, function(raw, post_err)
if handle.cancelled then return end
local wire, reason = envelope(raw, post_err)
if not wire then cb(nil, reason); return end
local code = tonumber(wire.code)
if code == SUCCESS or code == HAS_IN_SHELF then
local active = Client.session()
if active and active.usr == session.usr and active.zysid == session.zysid then
require("source.auth").ok(SOURCE_ID)
end
cb(true)
return
end
local _ignored, message = bodyOf(wire, session)
cb(nil, message)
end)
end)
if pending then handle.job = initial end
return { cancel = function()
handle.cancelled = true
if handle.job and handle.job.cancel then handle.job.cancel() end
end }
end
---@param book_id string
---@param cb fun(body: table|nil, err: string|nil)
---@return HttpJob
function Client.detailAsync(book_id, cb)
return Client.get("/bookstore/open/book/detail", { book_id = book_id }, function(body, err)
if type(body) == "table" and body.fee_unit ~= nil then
fee_unit[tostring(book_id)] = tonumber(body.fee_unit)
end
cb(body, err)
end)
end
---@param book_id string
---@param cb fun(rows: table[]|nil, err: string|nil)
---@return { cancel: fun() }
function Client.chaptersAsync(book_id, cb)
local handle, rows = {}, {}
local function nextPage(page)
local pending = true
local initial = Client.get("/bookstore/open/book/chapter/web/list", {
book_id = book_id, page = page, size = 50,
}, function(body, err)
pending = false
if handle.cancelled then return end
if type(body) ~= "table" or type(body.list) ~= "table" then cb(nil, err or _("响应无效")); return end
local list = body.list
local total = type(body.page) == "table" and tonumber(body.page.totalPage)
if not total or total < page or total % 1 ~= 0 or (#list == 0 and page < total) then
cb(nil, _("响应无效"))
return
end
for _idx, row in ipairs(list) do
if type(row) ~= "table" or (row.id == nil and row.chapter_id == nil) then
cb(nil, _("响应无效"))
return
end
rows[#rows + 1] = row
end
if page < total and #list > 0 then
nextPage(page + 1)
return
end
cb(rows)
end)
if pending then handle.job = initial end
end
nextPage(1)
return { cancel = function()
handle.cancelled = true
if handle.job and handle.job.cancel then handle.job.cancel() end
end }
end
---@param book_id string
---@param chapter_id string
---@param cb fun(html: string|nil, err: string|nil, kind: "unpaid"|nil)
---@return HttpJob
function Client.contentAsync(book_id, chapter_id, cb)
local whole = fee_unit[tostring(book_id)] == FEE_WHOLE
return Client.get("/nsr/chapter-content", {
book_id = book_id,
chapter_id = chapter_id,
is_whole_book = whole and "true" or "false",
}, function(body, err)
if type(body) ~= "table" then cb(nil, err or _("响应无效")); return end
-- 免费章的 charging_info 是 JSON null,LuaJSON 解成函数,不能当成未购买。
-- 未购买才是计费表,而且 is_buy 不为真。已购章也带这张表,正文仍在 bookContent。
local info = body.charging_info
local bought = type(info) == "table" and (info.is_buy == true or tonumber(info.is_buy) == 1)
if type(info) == "table" and not bought then cb(nil, _("本章未购买"), "unpaid"); return end
if type(body.bookContent) ~= "string" or body.bookContent == "" then
cb(nil, _("响应无效"))
return
end
local html = Mapper.content(body.bookContent)
cb(html, not html and _("掌阅正文含未知字码,请更新插件后重试") or nil)
end)
end
---@param book_id string
---@param cb fun(item: table|nil, err: string|nil)
---@return HttpJob
function Client.progressAsync(book_id, cb)
return Client.get("/bookstore/open/cloud/book/getProgress", { bookIds = book_id }, function(body, err)
if type(body) ~= "table" then cb(nil, err or _("响应无效")); return end
local key = tostring(book_id)
cb(body[key] or body[tonumber(key)])
end)
end
---@param book_id string
---@param chapter_uid string
---@param total integer
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return HttpJob
function Client.putProgressAsync(book_id, chapter_uid, total, cb)
local session = Client.session()
if not session then return require("source.base").defer(cb, nil, _("未登录掌阅")) end
local stored = math.max(0, (tonumber(chapter_uid) or 1) - 1)
local now = os.time() * 1000
local payload = JSON.encode({
bookId = tostring(book_id),
deviceName = "掌阅网页",
updateTime = now,
usr = session.usr,
readProcess = {
bookOverStatus = 0,
totalCount = total,
lastReadDate = now,
readingSource = "web",
chapterId = tostring(stored),
},
})
return post("/bookstore/open/cloud/book/progress", nil, payload, "application/json", function(body, err)
cb(body and true or nil, err)
end)
end
local STORE_HEADERS = {
["User-Agent"] = "Mozilla/5.0 (Linux; Android 12) AppleWebKit/537.36 Chrome/120.0.0.0 Mobile Safari/537.36",
}
---@param book_id string
---@param cb fun(result: IReaderReviewPage|nil, err: string|nil)
---@return HttpJob
function Client.reviewsAsync(book_id, cb)
local target = STORE .. "/comment/" .. Text.urlEncode(book_id)
local cancelled = false
local job = Request.get(target, {
accept = "text/html",
headers = STORE_HEADERS,
timeout = require("http.timeout").net(0.5),
}, function(raw, err)
if cancelled then return end
if err or not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
local result = Mapper.reviews(raw)
if not result then cb(nil, _("响应无效")); return end
cb(result)
end)
return { cancel = function()
cancelled = true
if job and job.cancel then job.cancel() end
end }
end
---@param keyword string
---@param cb fun(html: string|nil, err: string|nil)
---@return HttpJob
function Client.searchAsync(keyword, cb)
return Request.get(STORE .. "/search?" .. Text.formEncode({ keyWord = keyword }), {
accept = "text/html",
headers = STORE_HEADERS,
timeout = require("http.timeout").net(0.5),
}, function(raw, err) cb(raw, err and tostring(err) or nil) end)
end
---@param channel_id string
---@param cb fun(html: string|nil, err: string|nil)
---@return HttpJob
function Client.channelAsync(channel_id, cb)
return Request.get(STORE .. "/channel/" .. channel_id, {
accept = "text/html",
headers = STORE_HEADERS,
timeout = require("http.timeout").net(0.5),
}, function(raw, err) cb(raw, err and tostring(err) or nil) end)
end
---@param parent string
---@param category string
---@param cb fun(page: table|nil, err: string|nil)
---@return HttpJob
function Client.categoriesAsync(parent, category, cb)
return Request.get(STORE .. "/category/" .. parent .. "/" .. category .. "?currentPage=1", {
accept = "text/html", headers = STORE_HEADERS,
timeout = require("http.timeout").net(0.5),
}, function(raw, err)
local page = raw and Mapper.categories(raw)
if not page then cb(nil, err and tostring(err) or _("响应无效")); return end
cb(page)
end)
end
---@param opts table
---@param page integer
---@param cb fun(books: Book[]|nil, err: string|nil, more: boolean|nil)
---@return HttpJob
function Client.catalogAsync(opts, page, cb)
return Request.get(STORE .. "/category/" .. opts.parent .. "/" .. opts.category .. "?" .. Text.formEncode({
isAjax = 1, currentPage = page, pageSize = 20, order = opts.order, status = opts.status,
}), {
accept = "application/json", headers = STORE_HEADERS,
timeout = require("http.timeout").net(0.5),
}, function(raw, err)
local wire, reason = envelope(raw, err)
if not wire then cb(nil, reason); return end
if tonumber(wire.code) ~= SUCCESS then cb(nil, wire.msg or _("请求失败")); return end
local body = wire.body
if type(wire.html) ~= "string" or type(body) ~= "table"
or tonumber(body.current_page) ~= page or not tonumber(body.page_total) then
cb(nil, _("响应无效"))
return
end
local books = Mapper.catalog(wire.html)
if #books == 0 and Text.trim(wire.html) ~= "" then cb(nil, _("响应无效")); return end
cb(books, nil, page < tonumber(body.page_total))
end)
end
return Client
@@ -0,0 +1,85 @@
return {
["掌阅登录 Cookie"] = "iReader login Cookie",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie(须含 _zypps)"] = "Press F12, open Network, refresh the page and copy the complete Cookie request header (including _zypps).",
["没有读到 _zypps(usr/zysid)"] = "Could not find _zypps (usr/zysid)",
["登录状态已变化,请重试"] = "The login session changed. Please retry.",
["扫码登录"] = "Sign in with QR code",
["请先退出当前账号,再登录其他账号"] = "Sign out of the current account before signing in to another account",
["掌阅"] = "iReader",
["掌阅书城"] = "iReader Store",
["掌阅书架与在线阅读"] = "iReader shelf and online reading",
["掌阅扫码登录"] = "iReader QR sign-in",
["用掌阅 App 扫一扫"] = "Scan with the iReader app",
["在掌阅 App「我的」页右上角使用扫一扫"] = "Use the scanner at the top right of Me in the iReader app",
["未登录掌阅"] = "Not signed in to iReader",
["掌阅目录为空"] = "iReader chapter list is empty",
["掌阅正文含未知字码,请更新插件后重试"] = "iReader content contains unknown character codes. Update the plugin and try again.",
["掌阅插图下载失败,请重试"] = "Failed to download iReader illustrations. Please try again.",
["掌阅登录已失效,请点「重新登录」,用掌阅 App 扫码。"] = "iReader sign-in has expired. Tap Sign in again and scan with the iReader app.",
["确定退出掌阅账号?"] = "Sign out of iReader?",
["掌阅网页不能把书移出书架"] = "The iReader website cannot remove a book from the shelf",
["掌阅账号"] = "iReader account",
["本章未购买"] = "This chapter has not been purchased",
["缺少掌阅章节位置"] = "Missing iReader chapter position",
["男生"] = "Male",
["女生"] = "Female",
["出版"] = "Published",
["未登录 · 点此扫码"] = "Not signed in · tap to scan",
["章节目录保存失败"] = "Failed to save chapter list",
["VIP 章节"] = "VIP chapters",
["书架同步"] = "Shelf sync",
["搜索与发现"] = "Search and discover",
["进度同步"] = "Progress sync",
["100-200万字"] = "1–2 million words",
["15天内"] = "Within 15 days",
["20-50万字"] = "200,000–500,000 words",
["200万字以上"] = "Over 2 million words",
["20万字以下"] = "Under 200,000 words",
["30天内"] = "Within 30 days",
["3天内"] = "Within 3 days",
["50-100万字"] = "500,000–1 million words",
["7天内"] = "Within 7 days",
["两性"] = "Relationships",
["亲子"] = "Parenting",
["休闲"] = "Leisure",
["会员免费"] = "Free for members",
["传记"] = "Biography",
["公版"] = "Public domain",
["养生"] = "Wellness",
["农林"] = "Agriculture and forestry",
["医学"] = "Medicine",
["古籍"] = "Classics",
["哲学"] = "Philosophy",
["外语"] = "Foreign languages",
["宗教"] = "Religion",
["家居"] = "Home",
["小说"] = "Fiction",
["工业"] = "Industry",
["工具"] = "Reference",
["幻情"] = "Fantasy romance",
["建筑"] = "Architecture",
["心理"] = "Psychology",
["手工"] = "Crafts",
["投资"] = "Investing",
["政治"] = "Politics",
["教材教辅"] = "Textbooks and study guides",
["文化"] = "Culture",
["文学"] = "Literature",
["旅游"] = "Travel",
["时尚"] = "Fashion",
["杂志"] = "Magazines",
["法律"] = "Law",
["漫画书"] = "Comics",
["畅销"] = "Best-selling",
["社科"] = "Social sciences",
["科普"] = "Popular science",
["童书"] = "Children's books",
["管理"] = "Management",
["经济"] = "Economics",
["考试"] = "Exams",
["自然"] = "Nature",
["艺术"] = "Art",
["英文图书"] = "English books",
["计算机"] = "Computing",
["青春"] = "Youth",
}
@@ -0,0 +1,85 @@
return {
["掌阅登录 Cookie"] = "掌閱登入 Cookie",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie(须含 _zypps)"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie(須含 _zypps)",
["没有读到 _zypps(usr/zysid)"] = "沒有讀到 _zypps(usr/zysid)",
["登录状态已变化,请重试"] = "登入狀態已改變,請重試",
["扫码登录"] = "掃碼登入",
["请先退出当前账号,再登录其他账号"] = "請先退出目前帳號,再登入其他帳號",
["掌阅"] = "掌閱",
["掌阅书城"] = "掌閱書城",
["掌阅书架与在线阅读"] = "掌閱書架與線上閱讀",
["掌阅扫码登录"] = "掌閱掃碼登入",
["用掌阅 App 扫一扫"] = "用掌閱 App 掃一掃",
["在掌阅 App「我的」页右上角使用扫一扫"] = "在掌閱 App「我的」頁右上角使用掃一掃",
["未登录掌阅"] = "未登入掌閱",
["掌阅目录为空"] = "掌閱目錄為空",
["掌阅正文含未知字码,请更新插件后重试"] = "掌閱正文含未知字碼,請更新外掛後重試",
["掌阅插图下载失败,请重试"] = "掌閱插圖下載失敗,請重試",
["掌阅登录已失效,请点「重新登录」,用掌阅 App 扫码。"] = "掌閱登入已失效,請點「重新登入」,用掌閱 App 掃碼。",
["确定退出掌阅账号?"] = "確定退出掌閱帳號?",
["掌阅网页不能把书移出书架"] = "掌閱網頁不能把書移出書架",
["掌阅账号"] = "掌閱帳號",
["本章未购买"] = "本章未購買",
["缺少掌阅章节位置"] = "缺少掌閱章節位置",
["男生"] = "男生",
["女生"] = "女生",
["出版"] = "出版",
["未登录 · 点此扫码"] = "未登入 · 點此掃碼",
["章节目录保存失败"] = "章節目錄儲存失敗",
["VIP 章节"] = "VIP 章節",
["书架同步"] = "書架同步",
["搜索与发现"] = "搜尋與發現",
["进度同步"] = "進度同步",
["100-200万字"] = "100–200萬字",
["15天内"] = "15天內",
["20-50万字"] = "20–50萬字",
["200万字以上"] = "200萬字以上",
["20万字以下"] = "20萬字以下",
["30天内"] = "30天內",
["3天内"] = "3天內",
["50-100万字"] = "50–100萬字",
["7天内"] = "7天內",
["两性"] = "兩性",
["亲子"] = "親子",
["休闲"] = "休閒",
["会员免费"] = "會員免費",
["传记"] = "傳記",
["公版"] = "公版",
["养生"] = "養生",
["农林"] = "農林",
["医学"] = "醫學",
["古籍"] = "古籍",
["哲学"] = "哲學",
["外语"] = "外語",
["宗教"] = "宗教",
["家居"] = "家居",
["小说"] = "小說",
["工业"] = "工業",
["工具"] = "工具",
["幻情"] = "幻情",
["建筑"] = "建築",
["心理"] = "心理",
["手工"] = "手工",
["投资"] = "投資",
["政治"] = "政治",
["教材教辅"] = "教材教輔",
["文化"] = "文化",
["文学"] = "文學",
["旅游"] = "旅遊",
["时尚"] = "時尚",
["杂志"] = "雜誌",
["法律"] = "法律",
["漫画书"] = "漫畫書",
["畅销"] = "暢銷",
["社科"] = "社科",
["科普"] = "科普",
["童书"] = "童書",
["管理"] = "管理",
["经济"] = "經濟",
["考试"] = "考試",
["自然"] = "自然",
["艺术"] = "藝術",
["英文图书"] = "英文圖書",
["计算机"] = "電腦",
["青春"] = "青春",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_ireader._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,271 @@
--[[--
掌阅网页响应 → 领域对象。纯函数,不发请求。
@module moonsource_ireader.mapper
--]]
local Text = require("utils.text")
local Mapper = {}
local SOURCE_ID = "ext.ireader"
-- 官网 FZYouH_509R_V1.10.ttf 的二十个私用字形;两个连续区间,中间 A–F 没有字形。
local CONTENT_CHARS = {}
for first, chars in pairs({
[0xF0000] = "的一是了在有他我这们",
[0xF0010] = "来去说就事你对也还但",
}) do
for idx, ch in ipairs(Text.chars(chars)) do
CONTENT_CHARS[Text.utf8char(first + idx - 1)] = ch
end
end
--- 官网用补充私用区 A 代替常用字;还原为普通 Unicode,不要求用户安装官网字体。
---@param html string
---@return string|nil 未知私用字码不能当作有效正文缓存
function Mapper.content(html)
local unknown = false
local decoded = html:gsub("\243[\176-\191][\128-\191][\128-\191]", function(ch)
local plain = CONTENT_CHARS[ch]
if not plain then unknown = true end
return plain
end)
return not unknown and decoded or nil
end
--- 只读取官网书评首屏。
---@class IReaderReviewPage
---@field items { author: string, text: string, time: string, grade: number|nil }[]
---@param html string
---@return IReaderReviewPage|nil
function Mapper.reviews(html)
local list = html:match('<ul[^>]*class="sns_commentlist"[^>]*>(.-)</ul>')
if not list then return nil end
local items = {}
for card in list:gmatch("<li[^>]*>(.-)</li>") do
local author = card:match('<i[^>]*class="vm"[^>]*>(.-)</i>')
local body = card:match('<p[^>]*class="con_dec"[^>]*>(.-)</p>')
local time = card:match('<span[^>]*class="sns_time"[^>]*>(.-)</span>')
if not author or not body or not time then return nil end
items[#items + 1] = {
author = Text.stripHtml(author),
text = Text.stripHtml(body),
time = Text.stripHtml(time),
grade = tonumber(card:match('class="cur r(%d+)"')),
}
end
if #items == 0 and Text.trim(list) ~= "" then return nil end
return { items = items }
end
--- 目录缓存格式。首章携带,变了就当缓存失效。
Mapper.TOC_VERSION = 1
--- 扫码回包 body 是带引号的 JSON 字符串,网页用 replace 去掉引号。两种都认。
---@param body any
---@return string|nil
function Mapper.qrCode(body)
if type(body) ~= "string" or body == "" then return nil end
local ok, inner = pcall(require("json").decode, body)
if ok and type(inner) == "string" and inner ~= "" then return inner end
local stripped = body:gsub('"', "")
if stripped == "" then return nil end
return stripped
end
--- 轮询回包。等待是 30059(网页常量 WAIT_LOGIN),成功 body 里 name 是账号、session_id 是 zysid。
---@param wire table|nil
---@return table|nil user
---@return "wait"|"fail"|nil kind
function Mapper.login(wire)
if type(wire) ~= "table" then return nil, "fail" end
local code = tonumber(wire.code)
if code == 30059 then return nil, "wait" end
local body = wire.body
if code == 0 and type(body) == "table" and type(body.name) == "string" and body.name ~= ""
and type(body.session_id) == "string" and body.session_id ~= "" then
local nick = type(body.nick) == "string" and body.nick ~= "" and body.nick or body.name
return {
usr = body.name,
zysid = body.session_id,
name = nick,
avatar = type(body.avatar) == "string" and body.avatar or nil,
}
end
return nil, "fail"
end
---@param id string|number
---@param title string|nil
---@param author string|nil
---@param intro string|nil
---@param cover string|nil
---@return Book
local function book(id, title, author, intro, cover)
local function clean(value)
if type(value) ~= "string" then return "" end
return Text.trim(Text.xmlDecode(value))
end
local picture = type(cover) == "string" and cover ~= "" and Text.xmlDecode(cover) or nil
return {
source_id = SOURCE_ID,
stable_id = tostring(id),
title = clean(title),
authors = clean(author),
intro = clean(intro),
cover = picture,
}
end
--- 书架行。文件夹和本机上传的书网页读不了,不进月读书架。
---@param wire table|nil
---@return Book[]
function Mapper.shelf(wire)
local out = {}
local rows = type(wire) == "table" and wire.data or nil
if type(rows) ~= "table" then return out end
for _idx, row in ipairs(rows) do
if type(row) == "table" and row.book_id and row.dtype ~= 1 and row.is_local_book ~= true then
local item = book(row.book_id, row.book_name, row.author, nil, row.icon or row.cover)
if item.title ~= "" then out[#out + 1] = item end
end
end
return out
end
--- 搜索结果页。卡片是 data-id + data-src + name / author / brief。
---@param html string|nil
---@return Book[]
function Mapper.search(html)
local out, seen = {}, {}
if type(html) ~= "string" then return out end
local pos = 1
while true do
local _start, stop, id = html:find('data%-id="(%d+)"', pos)
if not _start then break end
if not seen[id] then
seen[id] = true
local window = html:sub(stop, math.min(#html, stop + 1500))
local cover = window:match('data%-src="([^"]+)"')
local title = window:match('class="name[^"]*"[^>]*>([^<]*)')
local author = window:match('class="author[^"]*"[^>]*>([^<]*)')
local intro = window:match('class="brief"[^>]*>([^<]*)')
if title and Text.trim(title) ~= "" then
out[#out + 1] = book(id, title, author, intro, cover)
end
end
pos = stop
end
return out
end
--- 频道页 data-point 里的 cli_res_id / cli_res_name。同一本书滑块里会重复,只留第一次。
---@param html string|nil
---@return Book[]
function Mapper.channel(html)
local out, seen = {}, {}
if type(html) ~= "string" then return out end
local pattern = '"cli_res_id"%s*:%s*(%d+)%s*,%s*"cli_res_name"%s*:%s*"([^"]*)"'
local pos = 1
while true do
local _start, stop, id, title = html:find(pattern, pos)
if not _start then break end
if not seen[id] then
seen[id] = true
local cover = html:sub(stop, math.min(#html, stop + 500)):match('src="(https://[^"]+)"')
out[#out + 1] = book(id, title, nil, nil, cover)
end
pos = stop
end
return out
end
---@param html string
---@return Book[]
function Mapper.catalog(html)
local out, seen = {}, {}
for id, card in html:gmatch('<li[^>]-data%-type="book"[^>]-data%-id="(%d+)"[^>]*>(.-)</li>') do
local title = card:match("<dt[^>]*>(.-)</dt>")
if title and not seen[id] then
seen[id] = true
out[#out + 1] = book(id, title, card:match('class="author[^"]*"[^>]*>([^<]*)'),
card:match('class="content[^"]*"[^>]*>([^<]*)'), card:match('data%-src="([^"]+)"'))
end
end
return out
end
---@param html string
---@return table|nil
function Mapper.categories(html)
local parent, category = html:match("var parentId%s*=%s*'(%d+)'%s*,%s*categoryId%s*=%s*'(%d+)'")
if not parent then return nil end
local result = { parent = parent, category = category, channels = {}, categories = {}, orders = {}, statuses = {} }
local seen = {}
for p, id, title in html:gmatch('<a[^>]-href="[^"]-/category/(%d+)/(%d+)[^"]*"[^>]*>([^<]+)</a>') do
local key = p .. ":" .. id
if not seen[key] then
seen[key] = true
if p == id then
result.channels[#result.channels + 1] = { id = p, title = Text.xmlDecode(title) }
elseif p == parent then
result.categories[#result.categories + 1] = { id = id, title = Text.xmlDecode(title) }
end
end
end
for field, list in pairs({ order = result.orders, status = result.statuses }) do
for id, title in html:gmatch('<span[^>]-data%-' .. field .. '="([%w]+)"[^>]*>([^<]+)</span>') do
list[#list + 1] = { id = id, title = Text.xmlDecode(title) }
end
end
if #result.channels == 0 or #result.categories == 0 or #result.orders == 0 or #result.statuses == 0 then return nil end
return result
end
---@param body table|nil
---@param stable_id string
---@return Book|nil
function Mapper.detail(body, stable_id)
if type(body) ~= "table" then return nil end
local id = body.book_id or body.id or stable_id
if not id then return nil end
return book(id, body.name or body.book_name, body.author, body.description or body.brief, body.icon or body.cover or body.pic)
end
--- 章节目录。网页列表项是 id + name,本地书才有 children。
---@param rows table[]|nil
---@return BookChapter[]
function Mapper.chapters(rows)
local out = {}
local function walk(list, depth)
for _idx, row in ipairs(type(list) == "table" and list or {}) do
local id = row.id or row.chapter_id
if id ~= nil then
out[#out + 1] = {
uid = tostring(id),
title = Text.trim(tostring(row.name or row.title or "")),
depth = depth,
}
end
if type(row.children) == "table" then walk(row.children, depth + 1) end
end
end
walk(rows, 1)
for idx, chapter in ipairs(out) do chapter.idx = idx end
if out[1] then out[1].toc_version = Mapper.TOC_VERSION end
return out
end
--- 进度接口把章节 id 存成「列表 id - 1」,读回来要加回去才能对上目录 uid。
---@param chapter_id number|string|nil
---@return string|nil
function Mapper.progressUid(chapter_id)
local stored = tonumber(chapter_id)
if not stored then return nil end
return tostring(stored + 1)
end
return Mapper
@@ -0,0 +1,147 @@
--[[--
掌阅扫码登录。
GET /bookstore/open/user/qrcode/get 的 body 是登录码,二维码内容是 web_login:<码>。
每 1.5 秒轮询 /bookstore/open/user/qrcode/result,和 PC 站一样最多 160 次。
30059 继续等;code 0 时 body.name 是账号、body.session_id 是后续请求的 zysid。
@module moonsource_ireader.qrlogin
--]]
local Client = require("moonsource_ireader.client")
local Mapper = require("moonsource_ireader.mapper")
local _ = require("l10n").get("moonsource_ireader")
local QRLogin = {}
QRLogin.__index = QRLogin
local POLL_INTERVAL = 1.5
local POLL_LIMIT = 160
---@param on_user fun(user: table)
---@return table
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.job and self.job.cancel then self.job.cancel() end
self.job = nil
end
---@param text string
function QRLogin:toast(text)
require("ui.themes.widgets.toast"):new{ text = text, timeout = 3 }:show()
end
---@param text string
function QRLogin:_retry(text)
self:cancel()
if self.dialog then
local previous = self.dialog
self.dialog = nil
previous:close()
end
require("ui.themes.widgets.confirm"):new{
text = text,
ok_text = _("重新获取"),
ok_callback = function() self:start() end,
}:show()
end
---@param gen integer
---@param code string
---@param polls integer
function QRLogin:_poll(gen, code, polls)
if gen ~= self.generation then return end
if not require("ui/network/manager"):isConnected() then
self:_retry(_("网络不可用,请先连接 Wi-Fi"))
return
end
if polls > POLL_LIMIT or os.time() >= self.deadline then
self:_retry(_("二维码已过期"))
return
end
local pending = true
local job = Client.qrPollAsync(code, function(wire, err)
pending = false
if gen ~= self.generation then return end
self.job = nil
if not wire then
self:_retry(err or _("请求失败"))
return
end
local user, kind = Mapper.login(wire)
if user then
local checking = true
local check = Client.checkSessionAsync(user, function(ok, reason)
checking = false
if gen ~= self.generation then return end
if not ok then self:_retry(reason or _("登录失败")); return end
self:cancel()
if self.dialog then
local previous = self.dialog
self.dialog = nil
previous:close()
end
self.on_user(user)
end)
if checking then self.job = check end
return
end
if kind ~= "wait" then
self:_retry(type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("登录失败"))
return
end
require("ui/uimanager"):scheduleIn(POLL_INTERVAL, function()
if gen == self.generation then self:_poll(gen, code, polls + 1) end
end)
end)
if pending then self.job = job end
end
function QRLogin:start()
self:cancel()
if self.dialog then
local previous = self.dialog
self.dialog = nil
previous:close()
end
if not require("ui/network/manager"):isConnected() then
self:toast(_("网络不可用,请先连接 Wi-Fi"))
return
end
local gen = self.generation
self.deadline = os.time() + POLL_INTERVAL * POLL_LIMIT
local pending = true
local job = Client.qrCreateAsync(function(code, err)
pending = false
if gen ~= self.generation then return end
self.job = nil
if not code then
self:toast(err or _("获取二维码失败"))
return
end
local dialog
dialog = require("ui.themes.widgets.qr"):new{
title = _("掌阅扫码登录"),
text = "web_login:" .. code,
caption = _("用掌阅 App 扫一扫"),
actions = { { text = _("重新获取"), callback = function() self:start() end } },
close_callback = function()
if self.dialog == dialog then
self.dialog = nil
self:cancel()
self:toast(_("已取消登录"))
end
end,
}
self.dialog = dialog
dialog:show()
self:_poll(gen, code, 1)
end)
if pending then self.job = job end
end
return QRLogin
@@ -0,0 +1,166 @@
--[[--
掌阅账号:App 扫码、官网浏览器登录及 Cookie 导入(`_zypps` → usr/zysid)。
@module moonsource_ireader.setting
--]]
local _ = require("l10n").get("moonsource_ireader")
local CookieLogin = require("source.cookie_login")
local SOURCE_ID = "ext.ireader"
local Setting = {}
local LOGIN_URL = "https://pc.ireader.com/login"
---@return boolean
local function loggedIn()
return require("moonsource_ireader.client").session() ~= nil
end
--- Cookie 请求头里的 `_zypps`(官网 qs 串)→ usr/zysid。
---@param header string
---@return { usr: string, zysid: string, name: string|nil, avatar: string|nil }|nil
local function userFromCookie(header)
local Text = require("utils.text")
local raw
for part in tostring(header):gmatch("[^;]+") do
local name, value = part:match("^%s*([^=%s]+)%s*=%s*(.-)%s*$")
if name == "_zypps" and value and value ~= "" then
raw = value
break
end
end
if not raw then return nil end
raw = Text.urlDecode(raw) or raw
local fields = {}
for pair in raw:gmatch("[^&]+") do
local key, value = pair:match("^([^=]+)=(.*)$")
if key then
fields[Text.urlDecode(key) or key] = Text.urlDecode(value) or value
end
end
local usr, zysid = fields.usr, fields.zysid
if type(usr) ~= "string" or usr == "" or type(zysid) ~= "string" or zysid == "" then
return nil
end
return { usr = usr, zysid = zysid, name = fields.name, avatar = fields.avatar }
end
---@param user table
---@return boolean ok
---@return string|nil err
local function commitUser(user)
local settings = require("utils.settings")
local cfg = settings.getSource(SOURCE_ID)
if cfg.usr and cfg.usr ~= "" and cfg.usr ~= user.usr then
local cleared = require("source.logout").clear(SOURCE_ID, function()
cfg.usr, cfg.zysid, cfg.name, cfg.avatar = nil, nil, nil, nil
settings.saveSource(SOURCE_ID)
end)
if not cleared then return false, _("准备本地同步失败") end
end
cfg.usr = user.usr
cfg.zysid = user.zysid
cfg.name = user.name
cfg.avatar = user.avatar
settings.saveSource(SOURCE_ID)
require("source.auth").ok(SOURCE_ID)
require("source.registry").reload()
return true
end
---@param user table
local function save(user)
local ok, err = commitUser(user)
if not ok then
require("ui.themes.widgets.toast"):new{ text = err, timeout = 3 }:show()
return
end
require("ui.themes.widgets.toast"):new{ text = _("登录成功"), timeout = 2 }:show()
end
---@return string, boolean
function Setting.rowStatus()
local on = loggedIn()
return on and _("已登录") or _("未登录 · 点此扫码"), on
end
function Setting.open()
require("moonsource_ireader.qrlogin"):new(save):start()
end
local SPEC = {
id = SOURCE_ID, title = _("掌阅账号"), cookie_title = _("掌阅登录 Cookie"),
cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie(须含 _zypps)"),
logout_text = _("确定退出掌阅账号?"),
loggedIn = loggedIn,
checkAsync = function(cookie, cb)
local user = userFromCookie(cookie)
if not user then return cb(false, _("没有读到 _zypps(usr/zysid)")) end
return require("moonsource_ireader.client").checkSessionAsync(user, function(ok, err)
if not ok then return cb(false, err or _("登录失败")) end
cb(true, nil, user)
end)
end,
commit = function(_cookie, account, cb)
local ok, err = commitUser(account)
cb(ok, err)
end,
clear = function(cfg)
cfg.usr, cfg.zysid, cfg.name, cfg.avatar = nil, nil, nil, nil
end,
}
--- 扩展 payload 里取 `_zypps`(pc.ireader.com / .zhangyue.com 任一即可)。
---@param payload table
---@return string
local function cookieFromPayload(payload)
for _idx, cookie in ipairs(type(payload.cookies) == "table" and payload.cookies or {}) do
local host = type(cookie) == "table" and type(cookie.domain) == "string"
and cookie.domain:gsub("^%.", ""):lower()
if host and cookie.name == "_zypps" and type(cookie.value) == "string" and cookie.value ~= "" then
if host == "ireader.com" or host:match("%.ireader%.com$")
or host == "zhangyue.com" or host:match("%.zhangyue%.com$") then
return "_zypps=" .. cookie.value
end
end
end
return ""
end
Setting.browser = {
domain = "pc.ireader.com", scope = "cookie", login = LOGIN_URL,
check = "https://pc.ireader.com/",
icon = "https://static-efe-front-h.zhangyuecdn.com/sfm-production/logos/bf7fe8aa-35e2-4961-9e1a-e2a095950ff2.png",
isAuthorized = function() return CookieLogin.authorized(SPEC) end,
apply = function(payload, cb)
return CookieLogin.save(SPEC, cookieFromPayload(payload), cb)
end,
}
---@return table[]
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 = _("在掌阅 App「我的」页右上角使用扫一扫"),
status = status, status_on = status_on,
callback = function() Setting.open() end,
})
end,
CookieLogin.browserRow(),
CookieLogin.pasteRow(SPEC),
}
if loggedIn() then
rows[#rows + 1] = CookieLogin.logoutRow(SPEC)
end
return rows
end
Setting.login = Setting.open
Setting.userFromCookie = userFromCookie
return Setting
@@ -0,0 +1,335 @@
--[[--
掌阅数据源。
扫码登录(掌阅 App)后,书架、目录、正文、进度走 PC 站 JSON。
书城搜索、分类和分页走手机站。本地删除留墓碑,不伪造远端删除成功。
@module moonsource_ireader
--]]
local Assets = require("source.assets")
local Browse = require("source.browse")
local Client = require("moonsource_ireader.client")
local Mapper = require("moonsource_ireader.mapper")
local Paths = require("utils.paths")
local Shelf = require("source.shelf")
local SourceBase = require("source.base")
local Toc = require("source.toc")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_ireader")
local IReader = {}
local FETCH_INTERVAL = 0.5
local LEGACY_CHANNELS = { h5_ch_male = "10", h5_ch_female = "68", h5_ch_publish = "92" }
local CHANNEL_TITLES = { ["10"] = _("男生"), ["68"] = _("女生"), ["92"] = _("出版") }
---@return BookSourceMeta
function IReader.meta()
return require("moonsource_ireader.loadmeta")()
end
---@class IReaderSource : SourceBase
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
Source.__index = Source
---@return IReaderSource
function IReader.new()
local meta = IReader.meta()
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source)
end
---@return boolean
function Source:configured()
return Client.session() ~= nil
end
local Remote = {}
function Remote:shelfSyncAsync(cb) return Client.shelfAsync(cb) end
---@param stable_id string
---@param cb fun(ok: boolean|nil, err: string|nil)
function Remote:addToShelfAsync(stable_id, cb)
local row = require("book.books_db").get("ext.ireader", stable_id)
return Client.addAsync(stable_id, row and row.title or stable_id, cb)
end
--- 未接入可验证的远端移架请求。返回失败,墓碑留着,下次拉书架也不会把这本书加回来。
function Remote:removeFromShelfAsync(_stable_id, cb)
return SourceBase.defer(cb, nil, _("掌阅网页不能把书移出书架"))
end
function Source:syncBooksAsync(opts, cb)
if not self:configured() then return SourceBase.skipped(cb, "ireader not logged in") end
return Shelf.syncAsync(self.id, Remote, Mapper.shelf, 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(html, err)
if not html then cb(nil, err or _("请求失败")); return end
cb({ data = Mapper.search(html) })
end)
end
---@param identity BookIdentity
---@param cb fun(page: IReaderReviewPage|nil, err: string|nil)
---@return HttpJob
function Source:bookReviewsAsync(identity, cb)
return Client.reviewsAsync(identity.stable_id, cb)
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 parent, category, order, status = node:match("^(%d+):(%d+):(%w+):(%d+)$")
parent = parent or LEGACY_CHANNELS[node] or "10"
category, order, status = category or parent, order or "download", status or "0"
local limit = opts and opts.limit or 60
local handle, pending = {}, true
local initial = Client.categoriesAsync(parent, category, function(page, err)
pending = false
if handle.cancelled then return end
if not page then cb(nil, err); return end
parent, category = page.parent, page.category
local function valid(rows, value, fallback)
for _idx, row in ipairs(rows) do if row.id == value then return value end end
return fallback
end
order = valid(page.orders, order, page.orders[1].id)
status = valid(page.statuses, status, page.statuses[1].id)
local values = { parent, category, order, status }
local function group(title, rows, position)
local chips, active = {}, nil
for _idx, row in ipairs(rows) do
local next_node = { unpack(values) }
next_node[position] = row.id
if position == 1 then
next_node[2] = row.id
if row.id == "92" and status == "3" then next_node[4] = "0" end
end
local id = table.concat(next_node, ":")
chips[#chips + 1] = { id = id, title = position == 1 and CHANNEL_TITLES[row.id] or row.title }
if row.id == values[position] then active = id end
end
return { title = title, chips = chips, active = active }
end
local groups = {
group(nil, page.channels, 1), group(_("分类"), page.categories, 2),
group(_("排序"), page.orders, 3), group(_("状态"), page.statuses, 4),
}
handle.job = Browse.pages(function(index, done)
return Client.catalogAsync({ parent = parent, category = category, order = order, status = status }, index, done)
end, limit, groups, function(result, reason)
if handle.cancelled then return end
if result then
for index = #result.data, limit + 1, -1 do result.data[index] = nil end
end
cb(result, reason)
end)
end)
if pending then handle.job = initial end
function handle.cancel()
handle.cancelled = true
if handle.job then handle.job.cancel() end
end
return handle
end
function Source:getDetailAsync(identity, cb)
return Client.detailAsync(identity.stable_id, function(body, err)
local detail = Mapper.detail(body, identity.stable_id)
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 IReaderSource
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
local function fetchTocAsync(self, identity, cb)
return Client.chaptersAsync(identity.stable_id, function(rows, err)
if not rows then cb(nil, err); return end
local toc = Mapper.chapters(rows)
if #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
--- 已缓存正文离线原地还原字码,保留路径、节点和 sidecar;失败不覆盖旧文件。
---@param path string
---@return boolean
local function reuse(path)
local file = assert(io.open(path, "rb"))
local raw, read_err = file:read("*a")
file:close()
assert(raw, read_err)
local html = assert(Mapper.content(raw), _("掌阅正文含未知字码,请更新插件后重试"))
if html == raw then return true end
local temp = path .. ".part"
file = assert(io.open(temp, "wb"))
local written, write_err = file:write(html)
local closed, close_err = file:close()
if not written or not closed then
os.remove(temp)
error(write_err or close_err)
end
local renamed, rename_err = os.rename(temp, path)
if not renamed then
os.remove(temp)
error(rename_err)
end
return true
end
---@param open boolean
---@return ChapterFetchContent
local function fetcher(open)
return function(identity, chapter, done)
local cancelled, active, image_err = false, nil, nil
local pending = true
local initial = Client.contentAsync(identity.stable_id, chapter.uid, function(html, err, kind)
pending = false
if cancelled then return end
if html then
active = Assets.localizeAsync(html,
Paths.bookWorkDir(identity.stable_id, "ext.ireader") .. "/images",
function(url, cb)
return require("http.request").get(url, {
accept = "image/*",
headers = { Referer = "https://pc.ireader.com/" },
cache_ttl = 0,
allow_redirects = true,
timeout = require("http.timeout").net(0.5),
}, function(raw, reason)
if reason then image_err = tostring(reason) end
cb(raw, reason)
end)
end,
function(localized)
if cancelled then return end
if Text.hasRemoteImageSrc(localized) then
done(nil, image_err or _("掌阅插图下载失败,请重试"))
return
end
done({ title = chapter.title, html = localized })
end)
elseif open and kind == "unpaid" then
local notice = string.format(_("这是 VIP 章节,你还没有购买。\n请先在%s购买本章,再回来阅读。"), _("掌阅"))
done({
title = chapter.title,
html = Text.chapterHtml(chapter.title, notice),
temporary = true,
})
else
done(nil, err)
end
end)
if pending then active = initial end
return { cancel = function()
cancelled = true
if active and active.cancel then active.cancel() end
end }
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),
reuse = reuse,
}, 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),
interval_seconds = FETCH_INTERVAL,
reuse = reuse,
}, 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, FETCH_INTERVAL, range, reuse)
end
function Source:getProgressAsync(identity, cb)
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录掌阅")) end
local cancelled, job = false, nil
local pending = true
local initial = Client.progressAsync(identity.stable_id, function(item, err)
pending = false
if cancelled then return end
if err then cb(nil, err); return end
---@type { chapterId: string|number|nil, readPercent: string|number|nil }|nil
local process = type(item) == "table" and item.readProcess or nil
local uid = type(process) == "table" and Mapper.progressUid(process.chapterId) or nil
if not uid then cb(nil, nil, { empty = true }); return end
job = self:loadTocAsync(identity, function(toc, reason)
if cancelled then return end
if not toc or #toc == 0 then cb(nil, reason or _("掌阅目录为空")); return end
local idx = Toc.index(self.id, identity.stable_id, uid)
if not idx then cb(nil, nil, { empty = true }); return end
cb({
chapter_idx = idx,
chapter_title = toc[idx].title,
fraction = (idx - 1) / #toc,
extra = { chapter_uid = uid, chapter_idx = idx },
})
end)
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job and job.cancel then job.cancel() end
end }
end
function Source:putProgressAsync(identity, pos, cb)
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录掌阅")) end
local cancelled, job = false, nil
local pending = 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)
local chapter = idx and toc[idx]
if not chapter then cb(nil, _("缺少掌阅章节位置")); return end
job = Client.putProgressAsync(identity.stable_id, chapter.uid, #toc, function(ok, perr)
if cancelled then return end
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 IReader