commit 2bc5c24ea70e62fcac14aa3b3bbfd277f0d62824 Author: Garfield Date: Mon Nov 16 12:07:59 2026 +0800 ✨ 初始提交:月读第三方书源插件集合 每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> diff --git a/moonsource-jjwxc.koplugin/README.md b/moonsource-jjwxc.koplugin/README.md new file mode 100644 index 0000000..dc8f397 --- /dev/null +++ b/moonsource-jjwxc.koplugin/README.md @@ -0,0 +1,23 @@ +# 晋江文学城 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| App 账号密码登录 | 已实现,未实测 | 支持手机/邮箱设备验证;密码不保存,不靠密码自动重登 | +| 浏览器登录与 Cookie 导入 | 已实现,未实测 | 手机 Web Cookie,支持手动粘贴及扩展回传 | +| 扫码登录 | 不支持 | 未接入 | +| 书架拉取 | 支持 | Web 收藏全量分页或 App 收藏快照 | +| 加入远端收藏 | 不支持 | 尚未接入官网设备校验流程 | +| 移出远端收藏 | 部分支持 | Web 删除后回读确认;App 删除未实现,真实写入未实测 | +| 搜索 | 部分支持 | 匿名 App 搜索,仅第一页 | +| 分类书城与榜单 | 支持 | 动态频道、分类、时代、类型、资费、状态和排序;保留旧榜单 | +| 详情与目录 | 支持 | 保留章节顺序,卷标题和锁章不当作可读章节 | +| 免费正文 | 支持 | 匿名读取 | +| 已购 VIP 正文 | 已实现,未实测 | 按所选 Web 或 App 协议读取,不解锁未购章节 | +| 章节与全本缓存 | 支持 | 已缓存目录和正文可离线续读、重开 | +| 阅读进度同步 | 不支持 | 仅本地保存,未接入可验证的远端写回 | +| 笔记与统计同步 | 不支持 | 仅本地保存 | +| 整书书评 | 不支持 | 未找到可验证的独立整书接入接口 | +| 章评与段评 | 支持 | 按章/段归属,支持分页、定位和离线缓存 | +| 评论表情 | 支持 | 官网表情原位显示;离线缺图保留文字标记 | +| 评论回复与写操作 | 不支持 | 未接入回复分页、发评、点赞或删评 | +| 账号切换 | 部分支持 | 不允许直接换凭据;须先退出清理旧本地数据,未同步记录会丢失 | diff --git a/moonsource-jjwxc.koplugin/_meta.lua b/moonsource-jjwxc.koplugin/_meta.lua new file mode 100644 index 0000000..a50333f --- /dev/null +++ b/moonsource-jjwxc.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:晋江文学城"), + description = _("给月读增加「晋江文学城」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-jjwxc.koplugin/main.lua b/moonsource-jjwxc.koplugin/main.lua new file mode 100644 index 0000000..e03f711 --- /dev/null +++ b/moonsource-jjwxc.koplugin/main.lua @@ -0,0 +1,9 @@ +--[[-- +KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。 +--]] +local WidgetContainer = require("ui/widget/container/widgetcontainer") + +return WidgetContainer:extend{ + name = "moonsource_jjwxc", + is_doc_only = false, +} diff --git a/moonsource-jjwxc.koplugin/moon_source.lua b/moonsource-jjwxc.koplugin/moon_source.lua new file mode 100644 index 0000000..3cdefa8 --- /dev/null +++ b/moonsource-jjwxc.koplugin/moon_source.lua @@ -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_jjwxc.source").meta() end, + new = function() return require("moonsource_jjwxc.source").new() end, + setting = lazy("moonsource_jjwxc.setting"), +} diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/_meta.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/_meta.lua new file mode 100644 index 0000000..f991467 --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/_meta.lua @@ -0,0 +1,15 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +@module moonsource_jjwxc._meta +--]] + +local _ = require("l10n").get("moonsource_jjwxc") + +return { + id = "ext.jjwxc", + name = _("晋江文学城"), + type = "chapter", + description = _("晋江文学城书架与在线阅读"), + abilities = { _("搜索与发现"), _("分类书库"), _("书架同步"), _("VIP 章节"), _("他人段评"), _("章节评论") }, +} diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/browse.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/browse.lua new file mode 100644 index 0000000..38f937b --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/browse.lua @@ -0,0 +1,94 @@ +--[[-- +晋江官网分类库:动态表单筛选、顺序分页;榜单旧节点仍由源入口处理。 + +@module moonsource_jjwxc.browse +--]] + +local Browse = require("source.browse") +local Client = require("moonsource_jjwxc.client") +local SourceBase = require("source.base") +local _ = require("l10n").get("moonsource_jjwxc") + +local Library = {} +local FILTERS = { + { "xx", _("频道") }, { "yc", _("原创") }, { "sd", _("时代") }, { "lx", _("分类") }, + { "fw", _("价格") }, { "isfinish", _("状态") }, { "sortType", _("排序") }, +} + +local function node(params) + local parts = {} + for index, filter in ipairs(FILTERS) do parts[index] = tostring(params[filter[1]]) end + return "cate:" .. table.concat(parts, ":") +end + +---@param opts { node?: string, limit?: integer } +---@param cb fun(res: table|nil, err: string|nil) +---@return { cancel: fun() } +function Library.run(opts, cb) + local limit = opts.limit or 60 + local value = opts.node or "cate:0:0:0:0:0:0:2" + local parts = {} + for part in value:sub(6):gmatch("[^:]+") do parts[#parts + 1] = part end + if #parts ~= #FILTERS or value ~= "cate:" .. table.concat(parts, ":") then + return SourceBase.defer(cb, nil, _("晋江分类条件无效")) + end + local params = { page = 1 } + for index, filter in ipairs(FILTERS) do + if not parts[index]:match("^%d+$") then return SourceBase.defer(cb, nil, _("晋江分类条件无效")) end + params[filter[1]] = parts[index] + end + local cancelled, job, pending = false, nil, true + local initial = Client.categoryAsync(params, function(first, err) + pending = false + if cancelled then return end + if not first then cb(nil, err); return end + local groups = {} + for _index, filter in ipairs(FILTERS) do + local key, title = filter[1], filter[2] + local options = first.filters[key] + if not options or #options == 0 then cb(nil, _("晋江分类响应无效")); return end + local valid = false + for _idx, option in ipairs(options) do + if option.id == params[key] then valid = true end + end + if not valid then cb(nil, _("晋江分类条件无效")); return end + local chips = {} + for _idx, option in ipairs(options) do + local copy = {} + for name, current in pairs(params) do copy[name] = current end + copy[key] = option.id + if key == "xx" or key == "yc" then copy.lx, copy.sd = "0", "0" end + chips[#chips + 1] = { id = node(copy), title = _(option.title) } + end + local group = Browse.group(chips, node(params)) + group.title = title + groups[#groups + 1] = group + end + groups[#groups + 1] = { title = _("排行榜"), chips = { { id = "1:1", title = _("排行榜") } } } + job = Browse.pages(function(page, done) + local function loaded(data, reason) + if not data then done(nil, reason); return end + if data.page ~= page or (#data.books == 0 and page < data.pages) then + done(nil, _("晋江分类响应无效")); return + end + done(data.books, nil, page < data.pages) + end + if page == 1 then loaded(first); return end + params.page = page + return Client.categoryAsync(params, loaded) + end, limit, groups, function(result, reason) + if cancelled then return end + if not result then cb(nil, reason); return end + local more = #result.data > limit or params.page < first.pages + while #result.data > limit do table.remove(result.data) end + cb({ data = result.data, groups = result.groups, more = more }, reason) + end) + end) + if pending then job = initial end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +return Library diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/client.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/client.lua new file mode 100644 index 0000000..469c1a4 --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/client.lua @@ -0,0 +1,158 @@ +--[[-- +晋江文学城 HTTP 客户端(仅异步):匿名 App JSON(app-cdn.jjwxc.net/androidapi)和书城榜单(/bookstore/getFullPage)。 + +书的元数据、目录、免费章正文都不要登录。VIP 章正文需要登录态,交给 protocols/ 里用户选定的协议 +(web 网页 Cookie / app 账号 token,二选一,见 protocols/init.lua)。 + +@module koplugin.book.moonsource_jjwxc.client +--]] + +local JSON = require("json") +local Charset = require("utils.charset") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_jjwxc") + +local Client = {} + +local APP = "https://app-cdn.jjwxc.net/androidapi" +local STORE = "https://app-cdn.jjwxc.net/bookstore" +-- 榜单分页接口一页 25 本;首页 chip 缓存 10 分钟,翻页不缓存。 +Client.RANK_PAGE = 25 +local STORE_HOME_TTL = 600 +local APP_HEADERS = { + ["User-Agent"] = "Mozilla/5.0 (Linux; Android 5.1; Lenovo) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 " + .. "Chrome/39.0.0.0 Mobile Safari/537.36/JINJIANG-Android/206(Lenovo;android 5.1;Scale/2.0)", + ["Referer"] = "http://android.jjwxc.net?v=206", +} +-- 接口回包里「该章是 VIP 章」的 code。 +local VIP_CODE = 1004 + +---@param path string +---@param params table +---@param cb fun(wire: table|nil, err: string|nil) +---@param ratio number|nil 超时倍率,缺省 0.5 +---@return HttpJob +local function appGet(path, params, cb, ratio, cache_ttl) + local query = {} + for key, value in pairs(params) do query[#query + 1] = key .. "=" .. tostring(value) end + table.sort(query) + return Request.get(APP .. path .. "?" .. table.concat(query, "&"), { + accept = "application/json", + headers = APP_HEADERS, + timeout = require("http.timeout").net(ratio or 0.5), + cache_ttl = cache_ttl, + }, function(raw, err) + if 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 + +local function storeGet(url, cb, cache_ttl) + return Request.get(url, { + accept = "application/json", + headers = APP_HEADERS, + timeout = require("http.timeout").net(0.5), + cache_ttl = cache_ttl, + }, function(raw, err) + if 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 + +--- 书城首页。channel=yq 的六排行里已经带纯爱 / 原创 / 衍生频道。 +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client.storeHomeAsync(cb) + return storeGet(STORE .. "/getFullPage?channel=yq&version=4", cb, STORE_HOME_TTL) +end + +--- 某一个频道的一页。offset 从 0 起,每页 Client.RANK_PAGE 本。 +---@param channel_id string natural_592 这种频道号 +---@param offset integer +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client.rankPageAsync(channel_id, offset, cb) + local body = Text.urlEncode(string.format('{"%s":{"offset":"%d","limit":"%d"}}', + channel_id, offset, Client.RANK_PAGE)) + return storeGet(STORE .. "/getFullPage?versionCode=185&channelMore=1&channelBody=" .. body, cb) +end + +--- 官网高级分类库;匿名请求,筛选编码由页面表单提供。 +---@param params table +---@param cb fun(page: table|nil, err: string|nil) +---@return HttpJob +function Client.categoryAsync(params, cb) + return Request.get("https://m.jjwxc.com/assort?" .. Text.formEncode(params), { + headers = { ["User-Agent"] = APP_HEADERS["User-Agent"] }, + timeout = require("http.timeout").net(1), + cache_ttl = 600, + }, function(raw, err, res) + if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end + local html, reason = Charset.toUtf8(raw, Request.header(res, "Content-Type")) + if not html then cb(nil, reason); return end + cb(require("moonsource_jjwxc.mapper").category(html)) + end) +end + +---@param keyword string +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +function Client.searchAsync(keyword, cb) + return appGet("/search", { keyword = Text.urlEncode(keyword), type = 1, page = 1, versionCode = 206 }, cb, 1) +end + +---@param novel_id string +---@param cb fun(info: table|nil, err: string|nil) +---@return HttpJob +function Client.detailAsync(novel_id, cb) + return appGet("/novelbasicinfo", { novelId = novel_id }, function(wire, err) + if not wire then cb(nil, err); return end + if not wire.novelName then cb(nil, wire.message or _("晋江书籍信息为空")); return end + cb(wire) + end) +end + +---@param novel_id string +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +function Client.chaptersAsync(novel_id, cb) + return appGet("/chapterList", { novelId = novel_id, more = 0, whole = 1 }, cb) +end + +--- 一章正文(纯文本,段落以换行分隔)。匿名接口只给免费章;VIP 章在已登录时交给选定协议。 +---@param novel_id string +---@param chapter_id string +---@param cb fun(text: string|nil, err: string|nil, kind: "unpaid"|nil) kind = "unpaid":登录态有效但这章没买 +---@return { cancel: fun() } +function Client.contentAsync(novel_id, chapter_id, cb) + local cancelled, job = false, nil + local pending = true + local initial = appGet("/chapterContent", { novelId = novel_id, chapterId = chapter_id }, function(wire, err) + pending = false + if cancelled then return end + if wire and type(wire.content) == "string" and wire.content ~= "" then + cb(wire.content) + return + end + local protocol = require("moonsource_jjwxc.protocols").current() + if not (wire and tonumber(wire.code) == VIP_CODE and protocol) then + cb(nil, err or (wire and wire.message) or _("晋江章节内容为空")) + return + end + job = protocol.contentAsync(novel_id, chapter_id, function(text, why, kind) + if not cancelled then cb(text, why, kind) end + end) + end) + if pending then job = initial end + return { cancel = function() + cancelled = true + if job then job:cancel() end + end } +end + +return Client diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/emoticons.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/emoticons.lua new file mode 100644 index 0000000..16da5d9 --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/emoticons.lua @@ -0,0 +1,105 @@ +--[[-- +晋江官方表情标记与图片地址;只下载评论实际用到的图片。 +来源:https://www.jjwxc.net/app.jjwxc/Pc/Emoji/getList(2026-11-08)。 +磕糖接口中的橘糖、紫糖同样包含在此目录中。 + +@module moonsource_jjwxc.emoticons +--]] + +return { + ["[狗头]"] = "https://i9-static.jjwxc.net/tmp/emoji/dog.png", + ["[星星眼]"] = "https://i9-static.jjwxc.net/tmp/emoji/star.png", + ["[亲亲]"] = "https://i9-static.jjwxc.net/tmp/emoji/kiss.png", + ["[害羞]"] = "https://i9-static.jjwxc.net/tmp/emoji/shy.png", + ["[坏笑]"] = "https://i9-static.jjwxc.net/tmp/emoji/bad_smile.png", + ["[爱心眼]"] = "https://i9-static.jjwxc.net/tmp/emoji/love_heart.png", + ["[让我康康]"] = "https://i9-static.jjwxc.net/tmp/emoji/look.png", + ["[加油]"] = "https://i9-static.jjwxc.net/tmp/emoji/go.png", + ["[撒花]"] = "https://i9-static.jjwxc.net/tmp/emoji/flower.png", + ["[奶茶]"] = "https://i9-static.jjwxc.net/tmp/emoji/milk.png", + ["[彩虹屁]"] = "https://i9-static.jjwxc.net/tmp/emoji/rainbow.png", + ["[笑哭]"] = "https://i9-static.jjwxc.net/tmp/emoji/laugh.png", + ["[爆哭]"] = "https://i9-static.jjwxc.net/tmp/emoji/cry.png", + ["[托腮]"] = "https://i9-static.jjwxc.net/tmp/emoji/sigh.png", + ["[问号]"] = "https://i9-static.jjwxc.net/tmp/emoji/question.png", + ["[闭嘴]"] = "https://i9-static.jjwxc.net/tmp/emoji/shut.png", + ["[白眼]"] = "https://i9-static.jjwxc.net/tmp/emoji/eyes.png", + ["[裂开]"] = "https://i9-static.jjwxc.net/tmp/emoji/break.png", + ["[墨镜]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240809171403_66b5dddb9b4a9_201.png", + ["[吃瓜]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813133503_66baf08792cb4_971.png", + ["[可怜]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813133538_66baf0aa48da0_272.png", + ["[摊手]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813133559_66baf0bfe94a8_123.png", + ["[化了]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813133734_66baf11eca900_736.png", + ["[捂脸偷看]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813133808_66baf140db042_203.png", + ["[哈哈大笑]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250327162728_67e50bf002312_926.png", + ["[摸头]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250327162816_67e50c2004946_460.png", + ["[抱抱]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250327162653_67e50bcdc4107_345.png", + ["[哦哦哦]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250327162901_67e50c4d70e05_616.png", + ["[无奈]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250327163425_67e50d916f9f7_934.png", + ["[捂脸笑哭]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250327162314_67e50af266b86_726.png", + ["[眼镜]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142108_6822e4d4908c7_855.png", + ["[好的]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142306_6822e54a95fec_363.png", + ["[求你了]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142345_6822e5719d933_198.png", + ["[求求你了]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142416_6822e59075a3b_751.png", + ["[小丑]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813134155_66baf223161c9_172.png", + ["[猫头]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813134245_66baf2554d0c0_482.png", + ["[三花猫头]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813134304_66baf2688507d_882.png", + ["[垂耳兔头]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813134345_66baf29111f22_694.png", + ["[竖耳兔头]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813134441_66baf2c986c2b_931.png", + ["[熊猫头]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813134502_66baf2deb9a59_203.png", + ["[害怕]"] = "https://i9-static.jjwxc.net/tmp/emoji/fear.png", + ["[愤怒]"] = "https://i9-static.jjwxc.net/tmp/emoji/anger.png", + ["[菜狗]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813134018_66baf1c223617_332.png", + ["[狗头叼玫瑰]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142003_6822e493665f5_485.png", + ["[抱大腿]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204135809_6982dff14e77e_333.png", + ["[加载ing]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204140413_6982e15d2793a_774.png", + ["[抠脑壳]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204140336_6982e138332f7_280.png", + ["[吐血]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204140451_6982e1831a3eb_940.png", + ["[躺平]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204140510_6982e1966d57c_902.png", + ["[咬手绢]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204140825_6982e259def03_162.png", + ["[接]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204140844_6982e26c6b04d_710.png", + ["[咦~]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204140948_6982e2ace7d2d_985.png", + ["[鸽子]"] = "https://i9-static.jjwxc.net/tmp/emoji/dove.png", + ["[发财]"] = "https://i9-static.jjwxc.net/tmp/emoji/rich.png", + ["[好运莲莲]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813132511_66baee37a0048_173.png", + ["[玫瑰]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813132550_66baee5e5f847_433.png", + ["[橘糖]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813132714_66baeeb282db3_126.png", + ["[紫糖]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813132746_66baeed24ae82_531.png", + ["[猫爪]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813132824_66baeef888f6a_514.png", + ["[药丸]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813132902_66baef1e7590e_674.png", + ["[柠檬]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813133018_66baef6a49f76_858.png", + ["[烟花]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142645_6822e6257d8f0_243.png", + ["[元宝]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142558_6822e5f6c2986_398.png", + ["[饭饭]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142708_6822e63c630d3_583.png", + ["[空碗]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142731_6822e653b7bac_594.png", + ["[鸡腿]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204143139_6982e7cba82a6_247.png", + ["[蛋糕]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204143253_6982e815d10ed_365.png", + ["[裤子]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142753_6822e669080b5_216.png", + ["[橙裤]"] = "https://i9-static.jjwxc.net/tmp/emoji/20251222112949_6948bb2d0c1a0_312.png", + ["[黄裤]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204142815_6982e6ffb9231_878.png", + ["[绿裤]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204150217_6982eef91613d_152.png", + ["[青裤]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204153134_6982f5d665d98_318.png", + ["[蓝裤]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204150249_6982ef1911a40_263.png", + ["[紫裤]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204150315_6982ef3399d82_820.png", + ["[加一]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142841_6822e699f2124_862.png", + ["[减一]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250513142916_6822e6bc011ee_516.png", + ["[敲木鱼]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204142929_6982e7493d944_145.png", + ["[耳朵]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813133118_66baefa6c51c9_627.png", + ["[沙发]"] = "https://i9-static.jjwxc.net/tmp/emoji/20260204143209_6982e7e9ea976_665.png", + ["[比心]"] = "https://i9-static.jjwxc.net/tmp/emoji/hand_heart.png", + ["[点赞]"] = "https://i9-static.jjwxc.net/tmp/emoji/like.png", + ["[鼓掌]"] = "https://i9-static.jjwxc.net/tmp/emoji/clap.png", + ["[666]"] = "https://i9-static.jjwxc.net/tmp/emoji/666.png", + ["[摆手]"] = "https://i9-static.jjwxc.net/tmp/emoji/wave.png", + ["[合十]"] = "https://i9-static.jjwxc.net/tmp/emoji/20240813132056_66baed38130c1_545.png", + ["[抱拳]"] = "https://i9-static.jjwxc.net/tmp/emoji/20250327163246_67e50d2e50aa5_351.png", + ["[心碎]"] = "https://i9-static.jjwxc.net/tmp/emoji/broken_heart.png", + ["[红心]"] = "https://i9-static.jjwxc.net/tmp/emoji/red_heart.png", + ["[橙心]"] = "https://i9-static.jjwxc.net/tmp/emoji/orange_heart.png", + ["[黄心]"] = "https://i9-static.jjwxc.net/tmp/emoji/yellow_heart.png", + ["[绿心]"] = "https://i9-static.jjwxc.net/tmp/emoji/green_heart.png", + ["[青心]"] = "https://i9-static.jjwxc.net/tmp/emoji/cyan_heart.png", + ["[蓝心]"] = "https://i9-static.jjwxc.net/tmp/emoji/blue_heart.png", + ["[紫心]"] = "https://i9-static.jjwxc.net/tmp/emoji/purple_heart.png", + ["[粉心]"] = "https://i9-static.jjwxc.net/tmp/emoji/pink_heart.png", +} diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/font.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/font.lua new file mode 100644 index 0000000..d3b4054 --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/font.lua @@ -0,0 +1,151 @@ +--[[-- +晋江 VIP 章反爬字体解码。正文里的常用字被换成私有区码点,页面附带一份 TTF(jjwxcfont_<串>), +每章随机洗牌,但同一个字的字形轮廓固定:按轮廓哈希查 `font_table`(tools/build_jjwxc_font.py 生成)即可还原。 + +@module koplugin.book.moonsource_jjwxc.font +--]] + +local Table = require("moonsource_jjwxc.font_table") + +local Font = {} + +local M1, M2 = 2147483647, 1000000007 + +local function u16(s, pos) local a, b = s:byte(pos, pos + 1); return a * 256 + b end +local function i16(s, pos) local v = u16(s, pos); return v >= 32768 and v - 65536 or v end +local function u32(s, pos) return u16(s, pos) * 65536 + u16(s, pos + 2) end + +--- sfnt 表目录 → { tag = 偏移 }(偏移从 1 起)。 +local function tables(ttf) + local dir = {} + for i = 0, u16(ttf, 5) - 1 do + local rec = 13 + i * 16 + dir[ttf:sub(rec, rec + 3)] = u32(ttf, rec + 8) + 1 + end + return dir +end + +--- cmap 里 BMP 的 format 4 子表 → { [码点] = 字形号 }。 +local function cmap(ttf, base) + local sub + for i = 0, u16(ttf, base + 2) - 1 do + local rec = base + 4 + i * 8 + local pos = base + u32(ttf, rec + 4) + if u16(ttf, pos) == 4 then sub = pos end + end + if not sub then return nil end + local segs = math.floor(u16(ttf, sub + 6) / 2) + local ends, starts, deltas, offsets = sub + 14, sub + 16 + segs * 2, sub + 16 + segs * 4, sub + 16 + segs * 6 + local map = {} + for i = 0, segs - 1 do + local last, first = u16(ttf, ends + i * 2), u16(ttf, starts + i * 2) + local delta, off = i16(ttf, deltas + i * 2), u16(ttf, offsets + i * 2) + for code = first, math.min(last, 0xFFFE) do + local gid + if off == 0 then + gid = (code + delta) % 65536 + else + local pos = offsets + i * 2 + off + (code - first) * 2 + gid = u16(ttf, pos) + if gid ~= 0 then gid = (gid + delta) % 65536 end + end + if gid ~= 0 then map[code] = gid end + end + end + return map +end + +--- 简单字形的轮廓哈希;算法与 tools/build_jjwxc_font.py 的 key 一致。复合字形与空字形返回 nil。 +local function key(ttf, glyf, start, stop, upm) + if stop <= start then return nil end + local pos = glyf + start + local contours = i16(ttf, pos) + if contours <= 0 then return nil end + local h1, h2 = 7, 7 + local function feed(v) + v = v + 100000 + h1 = (h1 * 131 + v) % M1 + h2 = (h2 * 137 + v) % M2 + end + feed(contours) + pos = pos + 10 + local count = 0 + for i = 0, contours - 1 do + count = u16(ttf, pos + i * 2) + 1 + feed(count - 1) + end + pos = pos + contours * 2 + pos = pos + 2 + u16(ttf, pos) + local flags = {} + while #flags < count do + local f = ttf:byte(pos) + pos = pos + 1 + flags[#flags + 1] = f + if f % 16 >= 8 then + for _rep = 1, ttf:byte(pos) do flags[#flags + 1] = f end + pos = pos + 1 + end + end + local function axis(short_bit, same_bit) + local out, cur = {}, 0 + for i = 1, count do + local f = flags[i] + if math.floor(f / short_bit) % 2 == 1 then + local d = ttf:byte(pos) + pos = pos + 1 + cur = cur + (math.floor(f / same_bit) % 2 == 1 and d or -d) + elseif math.floor(f / same_bit) % 2 == 0 then + cur = cur + i16(ttf, pos) + pos = pos + 2 + end + out[i] = cur + end + return out + end + local xs = axis(2, 16) + local ys = axis(4, 32) + for i = 1, count do + feed(flags[i] % 2) + feed(math.floor(xs[i] * 1000 / upm + 0.5)) + feed(math.floor(ys[i] * 1000 / upm + 0.5)) + end + return string.format("%08x%08x", h1, h2) +end + +--- 字体里每个码点对应的真字:{ [码点] = 字 }。字体解析不了或没有哈希命中的字形不入表。 +---@param ttf string +---@return table|nil +function Font.mapping(ttf) + local ok, result = pcall(function() + local dir = tables(ttf) + local upm = u16(ttf, dir.head + 18) + local long_loca = i16(ttf, dir.head + 50) == 1 + local codes = cmap(ttf, dir.cmap) + local map = {} + for code, gid in pairs(codes) do + local at = dir.loca + gid * (long_loca and 4 or 2) + local from, to + if long_loca then from, to = u32(ttf, at), u32(ttf, at + 4) else from, to = u16(ttf, at) * 2, u16(ttf, at + 2) * 2 end + local char = Table[key(ttf, dir.glyf, from, to, upm) or ""] + if char then map[code] = char end + end + return map + end) + return ok and result or nil +end + +--- 把正文里的私有区字符还原成真字,并去掉零宽字符(反爬字体后面跟的占位)。 +---@param text string UTF-8 +---@param map table +---@return string +function Font.decode(text, map) + local out = text:gsub("[\238\239][\128-\191][\128-\191]", function(ch) + local b1, b2, b3 = ch:byte(1, 3) + local code = (b1 % 16) * 4096 + (b2 % 64) * 64 + (b3 % 64) + if code >= 0xE000 and code <= 0xF8FF then return map[code] end + if code == 0xFEFF then return "" end + end) + return (out:gsub("\226\128[\139-\141]", "")) +end + +return Font diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/font_table.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/font_table.lua new file mode 100644 index 0000000..fd70efc --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/font_table.lua @@ -0,0 +1,208 @@ +--[[-- +晋江 VIP 章反爬字体:字形哈希 → 真字。由 tools/build_jjwxc_font.py 生成,勿手改。 + +@module koplugin.book.moonsource_jjwxc.font_table +--]] + +return { + ["00154a6b1c8b56f4"] = "看", + ["003603c812ca6cb9"] = "因", + ["0039923416a29944"] = "着", + ["00a7c7bf32aedbde"] = "他", + ["00e5e1da165ae20f"] = "公", + ["00ef0dd6285d8477"] = "之", + ["01088d012b098b75"] = "你", + ["0137f41423653d65"] = "会", + ["015a34d533889fbf"] = "二", + ["015fff502c321d00"] = "笑", + ["040233342f1b60df"] = "行", + ["0457599a21d8ecb0"] = "年", + ["048352b4338068c4"] = "四", + ["05c743e3058300cd"] = "现", + ["062a240d16193a5a"] = "不", + ["06b0bf881f9f2226"] = "多", + ["088e49fa39b6f880"] = "国", + ["09ff029326e86634"] = "几", + ["0abbfee029445859"] = "话", + ["0c7c16ac379a368b"] = "想", + ["0c8c788935eb4c6d"] = "法", + ["0cd499d21adc4075"] = "三", + ["0ce7553e341df099"] = "力", + ["0d59d79c255b26ae"] = "起", + ["0eb03ab13b8fecf8"] = "物", + ["0ecd20cb29d92a68"] = "对", + ["0edb5eb83058c70a"] = "自", + ["1087c1a13035f6e7"] = "但", + ["113677b02151cc54"] = "下", + ["115449b02bd79de0"] = "特", + ["1172c22d18119f8b"] = "从", + ["12356bd2071cd673"] = "何", + ["124e303120efe23f"] = "也", + ["133043da262891ee"] = "天", + ["13ef79062ac3d1d1"] = "论", + ["149e6780017ee49b"] = "给", + ["15d4b90832525c96"] = "并", + ["169fb4d632f94e0a"] = "书", + ["173ff1f031dd13db"] = "果", + ["184115df390833fc"] = "去", + ["188e591e180f8e96"] = "在", + ["19b1a58d103eb0c7"] = "同", + ["1aa2074a056ddbb5"] = "身", + ["1afb25c12fe803a9"] = "向", + ["1c12c0221b14b585"] = "使", + ["1dbd22af181d6e54"] = "打", + ["1e7064da2c43a480"] = "将", + ["1ec9379119027626"] = "新", + ["20c73d791f151327"] = "还", + ["20e5649a2017aa2a"] = "而", + ["2168c86e22945710"] = "它", + ["2226e8a417b8e642"] = "美", + ["222c52fb3869ab22"] = "口", + ["22336dd905e33be0"] = "子", + ["2235475211e9176e"] = "手", + ["2364bc1d28592888"] = "们", + ["25ca49ae0160dfa2"] = "然", + ["26cf0f301be32614"] = "理", + ["26e04e9a1cb6bddc"] = "西", + ["26f65f171d11692e"] = "只", + ["27e0e43d1fdbe3fc"] = "人", + ["27eda58f10ea029e"] = "听", + ["29198b84150e2a02"] = "种", + ["2a9a63a208db52cf"] = "过", + ["2b2043860a42f996"] = "这", + ["2b61971b073b5842"] = "代", + ["2bd90a330732c715"] = "里", + ["2c50307e157d6b0e"] = "没", + ["2cf2f6d221290a6a"] = "无", + ["2d6eed0a2cae9869"] = "头", + ["2d9945ea2664a9ab"] = "主", + ["2e927429335c13b5"] = "写", + ["2f1b92e306866f21"] = "到", + ["2f9553b9314fe40d"] = "开", + ["2fa93dcc26d6e2e8"] = "了", + ["307aeb5e186d90a6"] = "把", + ["31126af32d98854f"] = "等", + ["3147482a1e7c2787"] = "知", + ["3215d98f2c387b93"] = "最", + ["326e4ba02d62949e"] = "家", + ["3345985812325ce3"] = "经", + ["33c74c1218f9ddc3"] = "出", + ["33c8c79306682dd7"] = "于", + ["340bc8003b70efe1"] = "先", + ["3657a8c62c1383bb"] = "面", + ["36865d7e11f46b78"] = "为", + ["36e397e41c9062fb"] = "分", + ["380350671201b015"] = "气", + ["3861b2e329696837"] = "中", + ["3a97948e1de6c5f4"] = "女", + ["3bf7baa0372f6f00"] = "便", + ["3c465aa6245f67f4"] = "情", + ["3f32aca22ee80a90"] = "体", + ["3f428c7b267a61b8"] = "化", + ["3f4de79c333d43e7"] = "由", + ["4043a2e000c27bf1"] = "以", + ["4215aa5d2dfe3341"] = "此", + ["427dcf4e2b4c0dac"] = "好", + ["435b44cb3a093136"] = "明", + ["45da937f3a4e04f7"] = "作", + ["46769d630a62cf6a"] = "感", + ["47941d4e008bfb51"] = "儿", + ["47d3037514209c17"] = "社", + ["486f0fb3116323da"] = "道", + ["48b7ebab3a7ecdcb"] = "要", + ["48f21ae23593414c"] = "可", + ["491c37fd21375960"] = "上", + ["4a69b7772c51271f"] = "心", + ["4ace7a71004fcb43"] = "我", + ["4bafd6742e9d28c5"] = "老", + ["4bde746b27d2f440"] = "却", + ["4c19e7c931a5393a"] = "实", + ["4c826b1b0add86da"] = "来", + ["4c9cddcc0edaa3bf"] = "是", + ["4d2ef4e001dac785"] = "回", + ["4dc52058297c6c6e"] = "才", + ["4dfe3f8121f151f5"] = "前", + ["4e150e77022d1731"] = "关", + ["4efece4528ac825c"] = "点", + ["4f0d414f3a26189c"] = "本", + ["50b74008151f8779"] = "全", + ["512158f705f1102a"] = "有", + ["51dac53805488378"] = "第", + ["523e43b61eb81625"] = "再", + ["524908dd0c504da7"] = "动", + ["525b224b2a3c5e69"] = "史", + ["53b91871313c87e1"] = "就", + ["53e80c372daf792e"] = "教", + ["54036c4225c63550"] = "外", + ["54e5d3e3210f2947"] = "十", + ["55d667553b8b0db3"] = "她", + ["570f11d93b5fd870"] = "问", + ["587ee7c900891797"] = "很", + ["589d00c32229f925"] = "者", + ["58f1d0741752f362"] = "重", + ["59953abf2074ea93"] = "定", + ["59fff24c062dd782"] = "长", + ["5a3fd71d01325a3b"] = "部", + ["5b8b98991621a6df"] = "时", + ["5c86bc9512db5989"] = "高", + ["5cf629802f52c1f5"] = "个", + ["5de9b25d05bc443b"] = "己", + ["5e1dfe0b227c69fd"] = "方", + ["5e6b7a602017121a"] = "什", + ["5ee6421a0baf6b20"] = "名", + ["613c7379144fe701"] = "被", + ["619ce4cd35bc2fc2"] = "民", + ["6216c2a915612b9f"] = "间", + ["62954e2c04a4d150"] = "见", + ["62b118e130dcf3dc"] = "太", + ["636c1f752941d91f"] = "都", + ["64062c9918cfa2ca"] = "生", + ["6431c0db0ad501ed"] = "用", + ["64377b5e39f49e3b"] = "文", + ["64cced2918ddb31d"] = "性", + ["658ae6f72b4148e4"] = "成", + ["65bb8b7929460bf7"] = "后", + ["65c3321c336aaaef"] = "少", + ["6697e0633447ae33"] = "能", + ["6702b2d62ffb33a8"] = "别", + ["6745daf7157df3dc"] = "日", + ["6818cbd437787b67"] = "与", + ["6929e5aa35ba6c65"] = "神", + ["6b647f3025ad6d8c"] = "那", + ["6bb372693661ed92"] = "声", + ["6d1b497b0fd9f084"] = "相", + ["6d62ebca25d4273c"] = "其", + ["6d8e39fc07cba1dc"] = "意", + ["6ee59f3022d4e801"] = "走", + ["7051be711e796a0a"] = "更", + ["716b00b914b4238d"] = "两", + ["7212492d07c7dd75"] = "正", + ["7320c02800fa0624"] = "些", + ["7343928136b90bde"] = "的", + ["7381bd5e1c5c65ff"] = "已", + ["73cb101a00871bb6"] = "说", + ["73ddd1652fe5784b"] = "和", + ["74078d122ceebd69"] = "门", + ["742de861183233e2"] = "如", + ["750e9cb21d272023"] = "真", + ["75903fbb1fe83156"] = "眼", + ["765295db254176ca"] = "所", + ["785ade33150e9065"] = "白", + ["78aeb52e1d87f596"] = "样", + ["7909ea5514a95263"] = "义", + ["7a0fd8a116a67df3"] = "学", + ["7a175d2128e8e5a2"] = "世", + ["7a9596e00300969e"] = "进", + ["7ae8534201b24360"] = "地", + ["7b64232013109594"] = "又", + ["7c1c5ee00c1772a7"] = "发", + ["7d5d5dc904dee8cf"] = "得", + ["7db4216c2727791d"] = "一", + ["7dfe8d472d0c0519"] = "么", + ["7e5289903b3da004"] = "小", + ["7eabd922010f6142"] = "事", + ["7f1f75bc15a2138e"] = "大", + ["7f28bafd08237204"] = "思", + ["7fe2038424c0128e"] = "当", + ["7fe8dc93015ef26a"] = "死", +} diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/l10n/en.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/l10n/en.lua new file mode 100644 index 0000000..39cee2f --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/l10n/en.lua @@ -0,0 +1,85 @@ +return { + ["未登录 · 点此用账号密码"] = "Not signed in · Tap to use your account and password", + ["未联网"] = "Offline", + ["晋江分类响应无效"] = "Invalid Jinjiang category response", + ["晋江分类条件无效"] = "Invalid Jinjiang category filters", + ["晋江没有确认取消收藏"] = "Jinjiang did not confirm removal from favorites", + ["时代"] = "Era", + ["排行榜"] = "Rankings", + ["分类书库"] = "Category library", + ["无法确认旧账号,请先退出旧账号再登录"] = "Cannot identify the previous account. Sign out before signing in again.", + ["本章讨论"] = "Chapter discussion", + ["原创"] = "Original", + ["频道"] = "Channel", + ["章节评论"] = "Chapter comments", + ["价格"] = "Price", + ["正在登录…"] = "Signing in…", + ["章节目录保存失败"] = "Failed to save chapter list", + ["缺少晋江章节位置"] = "Missing Jinjiang chapter position", + ["晋江段评请求失败"] = "Jinjiang paragraph comments request failed", + ["晋江段评响应缺少评论列表"] = "Jinjiang paragraph comments response has no comment list", + ["发到手机"] = "Send to phone", + ["发到邮箱"] = "Send to email", + ["晋江书架无法解析"] = "Jinjiang shelf could not be parsed", + ["晋江收藏页过多,没有同步完"] = "Jinjiang favorites have too many pages; the shelf was not fully synced", + ["App 账号"] = "Jinjiang App account", + ["网页 Cookie"] = "Web cookie", + ["登录协议"] = "Login protocol", + ["(未登录)"] = " (not signed in)", + ["App 协议暂不支持取消收藏,请在设置里改用网页协议"] = "The App protocol can't remove favorites; switch to the web protocol in settings", + ["晋江已购章节解密失败"] = "Failed to decrypt purchased Jinjiang chapter", + ["晋江没有确认验证码已发送"] = "Jinjiang did not confirm the code was sent", + ["晋江登录失败"] = "Jinjiang login failed", + ["晋江要求设备验证"] = "Jinjiang requires device verification", + ["晋江设备验证"] = "Jinjiang device verification", + ["晋江账号登录"] = "Jinjiang account login", + ["笔名 / 邮箱 / 手机号"] = "Pen name / email / phone", + ["请先填写验证码"] = "Enter the verification code first", + ["账号或密码不能为空"] = "Account and password are required", + ["验证并登录"] = "Verify and sign in", + ["晋江账号"] = "Jinjiang account", + ["晋江登录 Cookie"] = "Jinjiang login cookie", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header", + ["确定退出晋江账号?"] = "Sign out of Jinjiang?", + ["未登录晋江"] = "Not signed in to Jinjiang", + ["你在晋江用的是哪种登录,就做哪种。"] = "Use whichever Jinjiang sign-in you already use.", + ["晋江收藏页无法解析"] = "Cannot parse the Jinjiang favorites page", + ["晋江书籍信息为空"] = "Jinjiang book info is empty", + ["晋江章节内容为空"] = "Jinjiang chapter is empty", + ["晋江 VIP 章节未购买"] = "This Jinjiang VIP chapter is not purchased", + ["晋江 VIP 章节解密失败"] = "Failed to decrypt this Jinjiang VIP chapter", + ["晋江 VIP 章节字体无法解析"] = "Cannot parse the anti-scraping font of this Jinjiang VIP chapter", + ["晋江目录为空"] = "Jinjiang table of contents is empty", + ["晋江暂不支持从月读加入收藏"] = "Adding to Jinjiang favorites from Moon is not supported yet", + ["账号和密码:点这个提示上的「重新登录」。没有这个按钮的话,打开「设置 → 书库 → 账号 → 晋江文学城 → 晋江账号」。填笔名、邮箱或手机号,再填密码,点「登录」。要验证码就点「发到手机」或「发到邮箱」,把验证码填进去,再点「验证并登录」。"] = "Username and password: tap Sign in again on this message. If there is no button, open Settings → Library → Account → Jinjiang Literature City → Jinjiang account. Enter your pen name, email, or phone number, then the password, and tap Sign in. If it asks for a code, tap Send to phone or Send to email, enter the code, and tap Verify and sign in.", + ["不想装扩展、平时用的是网页 Cookie:打开「设置 → 书库 → 账号 → 晋江文学城 → 晋江账号」,点「用 Cookie 登录」。Cookie 这样复制:电脑登录后按 F12,点「网络」,刷新,点任意一条请求,复制「请求标头」里的整段 Cookie,贴进去点「登录」。"] = "If you use a web cookie and do not want the extension: open Settings → Library → Account → Jinjiang Literature City → Jinjiang account, and tap Sign in with Cookie. To copy the cookie, sign in on a computer, press F12, open Network, refresh, click any request, copy the entire Cookie request header, paste it, and tap Sign in.", + ["晋江榜单无法解析"] = "Cannot parse Jinjiang ranking", + ["VIP 章节"] = "VIP chapters", + ["书架同步"] = "Shelf sync", + ["搜索与发现"] = "Search and discover", + ["晋江文学城书架与在线阅读"] = "Jinjiang shelf and online reading", + ["无限制"] = "Any", + ["积分"] = "Score", + ["最近更新"] = "Recently updated", + ["最新发表"] = "Newest", + ["收藏数"] = "Favorites", + ["完结高分"] = "Top-rated completed", + ["随机排序"] = "Random", + ["完结半价"] = "Half-price completed", + ["VIP库"] = "VIP library", + ["短篇包月"] = "Monthly short-story subscription", + ["阅文衍生"] = "Yuewen fan fiction", + ["纯爱"] = "Boys' love", + ["无CP"] = "No pairing", + ["多元"] = "Diverse", + ["近代现代"] = "Modern", + ["古色古香"] = "Historical", + ["架空历史"] = "Alternate history", + ["幻想未来"] = "Future fantasy", + ["爱情"] = "Love", + ["传奇"] = "Legend", + ["古典衍生"] = "Classical fan fiction", + ["东方衍生"] = "Eastern fan fiction", + ["西方衍生"] = "Western fan fiction", + ["其他衍生"] = "Other fan fiction", +} diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/l10n/zh_TW.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/l10n/zh_TW.lua new file mode 100644 index 0000000..f143e1e --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/l10n/zh_TW.lua @@ -0,0 +1,85 @@ +return { + ["未登录 · 点此用账号密码"] = "未登入 · 點此用帳號密碼", + ["未联网"] = "未連網", + ["晋江分类响应无效"] = "晉江分類回應無效", + ["晋江分类条件无效"] = "晉江分類條件無效", + ["晋江没有确认取消收藏"] = "晉江未確認取消收藏", + ["时代"] = "時代", + ["排行榜"] = "排行榜", + ["分类书库"] = "分類書庫", + ["无法确认旧账号,请先退出旧账号再登录"] = "無法確認舊帳號,請先登出舊帳號再登入", + ["本章讨论"] = "本章討論", + ["原创"] = "原創", + ["频道"] = "頻道", + ["章节评论"] = "章節評論", + ["价格"] = "價格", + ["正在登录…"] = "正在登入…", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["缺少晋江章节位置"] = "缺少晉江章節位置", + ["晋江段评请求失败"] = "晉江段評請求失敗", + ["晋江段评响应缺少评论列表"] = "晉江段評回應缺少評論列表", + ["发到手机"] = "發到手機", + ["发到邮箱"] = "發到信箱", + ["晋江书架无法解析"] = "晉江書架無法解析", + ["晋江收藏页过多,没有同步完"] = "晉江收藏頁過多,沒有同步完", + ["App 账号"] = "App 帳號", + ["网页 Cookie"] = "網頁 Cookie", + ["登录协议"] = "登入協議", + ["(未登录)"] = "(未登入)", + ["App 协议暂不支持取消收藏,请在设置里改用网页协议"] = "App 協議暫不支援取消收藏,請在設定裡改用網頁協議", + ["晋江已购章节解密失败"] = "晉江已購章節解密失敗", + ["晋江没有确认验证码已发送"] = "晉江沒有確認驗證碼已發送", + ["晋江登录失败"] = "晉江登入失敗", + ["晋江要求设备验证"] = "晉江要求裝置驗證", + ["晋江设备验证"] = "晉江裝置驗證", + ["晋江账号登录"] = "晉江帳號登入", + ["笔名 / 邮箱 / 手机号"] = "筆名 / 信箱 / 手機號", + ["请先填写验证码"] = "請先填寫驗證碼", + ["账号或密码不能为空"] = "帳號或密碼不能為空", + ["验证并登录"] = "驗證並登入", + ["晋江账号"] = "晉江帳號", + ["晋江登录 Cookie"] = "晉江登入 Cookie", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie", + ["确定退出晋江账号?"] = "確定登出晉江帳號?", + ["未登录晋江"] = "未登入晉江", + ["你在晋江用的是哪种登录,就做哪种。"] = "你在晉江用的是哪種登入,就做哪種。", + ["晋江收藏页无法解析"] = "無法解析晉江收藏頁", + ["晋江书籍信息为空"] = "晉江書籍資訊為空", + ["晋江章节内容为空"] = "晉江章節內容為空", + ["晋江 VIP 章节未购买"] = "此晉江 VIP 章節尚未購買", + ["晋江 VIP 章节解密失败"] = "此晉江 VIP 章節解密失敗", + ["晋江 VIP 章节字体无法解析"] = "無法解析此晉江 VIP 章節的反爬字體", + ["晋江目录为空"] = "晉江目錄為空", + ["晋江暂不支持从月读加入收藏"] = "暫不支援從月讀加入晉江收藏", + ["账号和密码:点这个提示上的「重新登录」。没有这个按钮的话,打开「设置 → 书库 → 账号 → 晋江文学城 → 晋江账号」。填笔名、邮箱或手机号,再填密码,点「登录」。要验证码就点「发到手机」或「发到邮箱」,把验证码填进去,再点「验证并登录」。"] = "帳號和密碼:點這個提示上的「重新登入」。沒有這個按鈕的話,打開「設定 → 書庫 → 帳號 → 晉江文學城 → 晉江帳號」。填筆名、郵箱或手機號,再填密碼,點「登入」。要驗證碼就點「發到手機」或「發到郵箱」,把驗證碼填進去,再點「驗證並登入」。", + ["不想装扩展、平时用的是网页 Cookie:打开「设置 → 书库 → 账号 → 晋江文学城 → 晋江账号」,点「用 Cookie 登录」。Cookie 这样复制:电脑登录后按 F12,点「网络」,刷新,点任意一条请求,复制「请求标头」里的整段 Cookie,贴进去点「登录」。"] = "不想裝擴充功能、平時用的是網頁 Cookie:打開「設定 → 書庫 → 帳號 → 晉江文學城 → 晉江帳號」,點「用 Cookie 登入」。Cookie 這樣複製:電腦登入後按 F12,點「網路」,重新整理,點任意一條請求,複製「請求標頭」裡的整段 Cookie,貼進去點「登入」。", + ["晋江榜单无法解析"] = "晉江榜單無法解析", + ["VIP 章节"] = "VIP 章節", + ["书架同步"] = "書架同步", + ["搜索与发现"] = "搜尋與發現", + ["晋江文学城书架与在线阅读"] = "晉江文學城書架與線上閱讀", + ["无限制"] = "無限制", + ["积分"] = "積分", + ["最近更新"] = "最近更新", + ["最新发表"] = "最新發表", + ["收藏数"] = "收藏數", + ["完结高分"] = "完結高分", + ["随机排序"] = "隨機排序", + ["完结半价"] = "完結半價", + ["VIP库"] = "VIP 書庫", + ["短篇包月"] = "短篇包月", + ["阅文衍生"] = "閱文衍生", + ["纯爱"] = "純愛", + ["无CP"] = "無 CP", + ["多元"] = "多元", + ["近代现代"] = "近代現代", + ["古色古香"] = "古色古香", + ["架空历史"] = "架空歷史", + ["幻想未来"] = "幻想未來", + ["爱情"] = "愛情", + ["传奇"] = "傳奇", + ["古典衍生"] = "古典衍生", + ["东方衍生"] = "東方衍生", + ["西方衍生"] = "西方衍生", + ["其他衍生"] = "其他衍生", +} diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/loadmeta.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/loadmeta.lua new file mode 100644 index 0000000..93b0265 --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_jjwxc._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/mapper.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/mapper.lua new file mode 100644 index 0000000..00c407e --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/mapper.lua @@ -0,0 +1,353 @@ +--[[-- +晋江文学城数据映射(纯函数):App JSON 与手机网页 HTML → 领域对象。 + +@module koplugin.book.moonsource_jjwxc.mapper +--]] + +local Text = require("utils.text") +local Vip = require("moonsource_jjwxc.vip") + +local Mapper = {} + +local SOURCE_ID = "ext.jjwxc" + +--- 带 ver 参数的封面链接服务端强制 gzip(Content-Encoding 与图片下载器不兼容,落盘变成无法识别的文件); +--- 去掉 ver 就是同一张图的原始 PNG。 +---@param url string|nil +---@return string|nil +local function cover(url) + if type(url) ~= "string" or url == "" then return nil end + return (url:gsub("&ver=[^&]*", "")) +end + +--- novelbasicinfo → Book。简介是实体转义过的 HTML。 +---@param info table +---@return Book +function Mapper.book(info) + local words = tonumber((tostring(info.novelSize or ""):gsub(",", ""))) + local status = type(info.novelStep) == "string" and Text.trim(info.novelStep) or "" + local tags = type(info.novelTags) == "string" and Text.trim(info.novelTags) + or type(info.novelTag) == "string" and Text.trim(info.novelTag) or "" + if tags ~= "" then tags = (tags:gsub("[,%s;;]+", " · ")) end + return { + source_id = SOURCE_ID, + stable_id = tostring(info.novelId), + title = info.novelName, + authors = info.authorName, + category = info.novelClass, + intro = info.novelIntro and Text.stripHtml(info.novelIntro), + cover = cover(info.novelCover), + meta = { + words = words, + status = status ~= "" and status or nil, + tags = tags ~= "" and tags or nil, + source = { + [SOURCE_ID] = { + protagonist = type(info.protagonist) == "string" and info.protagonist or nil, + perspective = type(info.mainview) == "string" and info.mainview or nil, + }, + }, + }, + } +end + +--- 搜索 wire → Book[](按 novelid / novelname 取,只留有书号的)。 +---@param wire table +---@return Book[] +function Mapper.search(wire) + local out = {} + for _idx, item in ipairs(type(wire.items) == "table" and wire.items or {}) do + if item.novelid then + out[#out + 1] = { + source_id = SOURCE_ID, + stable_id = tostring(item.novelid), + title = item.novelname, + authors = item.authorname, + intro = item.novelintroshort and Text.stripHtml(item.novelintroshort), + cover = cover(item.ebookurl), + } + end + end + return out +end + +--- 手机榜单页 HTML → { title, books }[]:按「【xx排行】」分节,每节只有书名和书号(作者、封面等详情补)。 +---@param html string +---@return { title: string, books: Book[] }[] +function Mapper.rankSections(html) + local sections = {} + for title, body in html:gmatch("【(.-)】(.-)") do + local books = {} + for id, name in body:gmatch(']*>([^<]*)') do + books[#books + 1] = { source_id = SOURCE_ID, stable_id = id, title = Text.xmlDecode(name) } + end + if #books > 0 then sections[#sections + 1] = { title = title, books = books } end + end + return sections +end + +--- 书城首页 getFullPage(channel=yq)里 type=rankings 的「六排行」。 +--- 没有频道列表的项(页面中间那条空位)丢掉。 +---@param home table +---@return { title: string, channels: { id: string, title: string }[] }[] +function Mapper.storeRanks(home) + local ranks = {} + for _idx, section in ipairs(type(home) == "table" and home or {}) do + if section.type == "rankings" then + for _i, item in ipairs(type(section.data) == "table" and section.data or {}) do + local more = item.more + local list = type(more) == "table" and more.channellist + if type(list) == "table" and more.rankName then + local channels = {} + for _j, ch in ipairs(list) do + if type(ch.channelid) == "string" and ch.channelid:find("^[%w_]+$") and ch.channel then + channels[#channels + 1] = { id = ch.channelid, title = ch.channel } + end + end + if #channels > 0 then + ranks[#ranks + 1] = { title = more.rankName, channels = channels } + end + end + end + end + end + return ranks +end + +--- 榜单分页(channelMore)里的书。封面、简介有就带上,没有书号的丢掉。 +---@param wire table|nil +---@return Book[] +function Mapper.rankBooks(wire) + local data = type(wire) == "table" and wire.data + local rows = type(data) == "table" and data.data or {} + local books = {} + for _idx, item in ipairs(type(rows) == "table" and rows or {}) do + local id = item.novelId or item.novelid + if id then + books[#books + 1] = { + source_id = SOURCE_ID, + stable_id = tostring(id), + title = item.novelName or item.novelname, + authors = item.authorName or item.authorname, + category = item.novelClass, + intro = item.novelIntroShort and Text.stripHtml(item.novelIntroShort), + cover = cover(item.cover or item.ebookurl), + } + end + end + return books +end + +--- 分类页表单与结果;缺分页信息不是空书库,而是响应格式错误。 +---@param html string +---@return table|nil, string|nil +function Mapper.category(html) + local filters = {} + for label in html:gmatch("]*>(.-)") do + local name = label:match("name%s*=%s*['\"]([%w_]+)['\"]") + local key, value + if name then key, value = name:match("^(%a+)(%d+)$") end + if key and value then + filters[key] = filters[key] or {} + filters[key][#filters[key] + 1] = { id = value, title = Text.stripHtml(label) } + end + end + for tag, body in html:gmatch("(]*>)(.-)") do + local key = tag:match("name%s*=%s*['\"]([%w_]+)['\"]") + if key then + local options = {} + for value, text in body:gmatch("]-value%s*=%s*['\"](%d+)['\"][^>]*>([^<]*)") do + options[#options + 1] = { id = value, title = Text.stripHtml(text) } + end + filters[key] = options + end + end + local pages, page = html:match("共(%d+)页,当前第(%d+)页") + local body = html:match(']-width="100%%"[^>]*>(.-)') + if not pages or not page or not body then return nil, require("l10n").get("moonsource_jjwxc")("晋江分类响应无效") end + local books, seen = {}, {} + for row in body:gmatch("]*>(.-)") do + local id, title = row:match(']-href="/book2/(%d+)"[^>]*>(.-)') + if id and not seen[id] then + seen[id] = true + books[#books + 1] = { source_id = SOURCE_ID, stable_id = id, title = Text.stripHtml(title), + cover = "https://i9-static.jjwxc.net/novelimage.php?novelid=" .. id, + authors = Text.stripHtml(row:match(']-href="/wapauthor/%d+"[^>]*>(.-)') or "") } + end + end + return { filters = filters, books = books, pages = tonumber(pages), page = tonumber(page) } +end + +--- 收藏页 HTML → { id, title, author }[];找不到收藏列表(页面改版 / 不是收藏页)返回 nil。 +--- 页面上的书名被截断,只作详情拉不到时的兜底。 +---@param html string +---@return { id: string, title: string, author: string|nil }[]|nil +function Mapper.favRows(html) + local list = html:match('
    (.-)
') + if not list then return nil end + local rows = {} + for item in list:gmatch("]*>(.-)") do + local id, title = item:match(']*>(.-)') + if id then + rows[#rows + 1] = { + id = id, + title = Text.stripHtml(title), + author = item:match('(.-)'), + } + end + end + return rows +end + +--- App 书架 addData → 与网页收藏同形的 {id,title,author};没有书号的丢弃。 +---@param list table[] +---@return table[] +function Mapper.tokenFavRows(list) + local rows = {} + for _idx, item in ipairs(list) do + local id = item.novelId or item.novelid + if id then + rows[#rows + 1] = { + id = tostring(id), + title = item.novelName or item.novelname, + author = item.authorName or item.authorname, + } + end + end + return rows +end + +--- 收藏行 → Book。本地已有同一本(local_book)沿用其完整元数据,没有就用刚拉到的详情,都没有才退回页面上截断的书名。 +---@param rows table[] { id, title, author, info?: table, local_book?: Book } +---@return Book[] +function Mapper.shelfList(rows) + local books = {} + for _idx, row in ipairs(rows) do + if row.info then + books[#books + 1] = Mapper.book(row.info) + elseif row.local_book then + row.local_book.cover = cover(row.local_book.cover) + books[#books + 1] = row.local_book + else + books[#books + 1] = { source_id = SOURCE_ID, stable_id = row.id, title = row.title, authors = row.author } + end + end + return books +end + +--- 目录缓存格式版本:2 起章节带 vip 标记。 +Mapper.TOC_VERSION = 2 + +--- chapterList → 目录。卷标题(chaptertype 1)与审核中被锁的章不进目录;章号(uid)是接口里的 chapterid。 +---@param wire table|nil +---@return BookChapter[] +function Mapper.toc(wire) + local rows = wire and wire.chapterlist + local toc = {} + for _idx, row in ipairs(type(rows) == "table" and rows or {}) do + if row.chaptertype ~= "1" and row.islock == "0" then + toc[#toc + 1] = { + idx = #toc + 1, + uid = tostring(row.chapterid), + title = row.chaptername, + words = tonumber(row.chaptersize), + vip = (tonumber(row.isvip) or 0) > 0 or nil, + } + end + end + if toc[1] then toc[1].toc_version = Mapper.TOC_VERSION end + return toc +end + +--- 取一条 CSS 规则里的 content 字符串(解 \' \" \\ 与 \XXXXXX 十六进制转义);没有返回 nil。 +---@param rule string +---@return string|nil +local function cssContent(rule) + local _from, stop = rule:find("content%s*:%s*") + if not stop then return nil end + local quote = rule:sub(stop + 1, stop + 1) + if quote ~= "'" and quote ~= '"' then return nil end + local out, i = {}, stop + 2 + while i <= #rule do + local c = rule:sub(i, i) + if c == quote then return table.concat(out) end + if c == "\\" then + local hex, next_i = rule:match("^\\(%x%x?%x?%x?%x?%x?)%s?()", i) + if hex then + out[#out + 1] = Text.utf8char(tonumber(hex, 16) or 0) + i = next_i + else + out[#out + 1] = rule:sub(i + 1, i + 1) + i = i + 2 + end + else + out[#out + 1] = c + i = i + 1 + end + end + return nil +end + +--- VIP 页正文被切成 ,段缝里的字不在解密片段里,挂在同页 ") do + for selectors, rule in style:gmatch("([^{}]+)%{([^{}]*)}") do + local text = cssContent(rule) + if text then + for cls, kind in selectors:gmatch("%.(c_%w+)%s*::?%s*(%a+)") do + if kind == "before" or kind == "after" then + local seam = seams[cls] or {} + seam[kind] = text + seams[cls] = seam + end + end + end + end + end + return seams +end + +--- 把段缝拼回片段:span 开标签换成该类的 before、配对的 换成 after,之后再走原有剥标签。 +--- 片段里 span 不嵌套,按出现顺序配对。 +---@param body string +---@param seams table +---@return string +local function spliceSeams(body, seams) + local opens, closed = {}, 0 + body = body:gsub("<[Ss][Pp][Aa][Nn][^>]*>", function(tag) + local cls = tag:match("class%s*=%s*['\"](c_%w+)['\"]") + opens[#opens + 1] = cls + local seam = cls and seams[cls] + return seam and seam.before or "" + end) + return (body:gsub("", function() + closed = closed + 1 + local seam = opens[closed] and seams[opens[closed]] + return seam and seam.after or "" + end)) +end + +--- 章节网页 HTML → 正文纯文本;不是正文页(未购买的提示页等)返回 nil。 +---@param html string +---@return string|nil +---@return string|nil 加密页解不开时的失败阶段 +function Mapper.webContent(html) + local body, why + if html:find('id="contentvars"', 1, true) then + body, why = Vip.content(html) + else + body = html:match('
    %s*]*>(.-)') + end + if not body then return nil, why end + local seams = seamTexts(html) + if next(seams) then body = spliceSeams(body, seams) end + body = body:gsub("", ""):gsub("‌", ""):gsub("&#([xX]%x+);?", "&#%1;") + local text = Text.xmlDecode((body:gsub("<[Bb][Rr]%s*/?>", "\n"):gsub("<[^>]*>", ""))) + return Text.trim(text) ~= "" and text or nil +end + +return Mapper diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/protocols.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/protocols.lua new file mode 100644 index 0000000..6f8fe44 --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/protocols.lua @@ -0,0 +1,36 @@ +--[[-- +晋江登录协议选择:网页(web)与 App(app)两套登录态各自独立,用户只用其中一个。 + +选择存在源设置 `protocol`;没设置(或所选协议没有登录态)时,哪个协议有登录态就用哪个,两个都有时先 web(沿用旧行为)。 + +@module koplugin.book.moonsource_jjwxc.protocols +--]] + +local Protocols = {} + +local SOURCE_ID = "ext.jjwxc" + +---@type table[] +Protocols.list = { require("moonsource_jjwxc.protocols.web"), require("moonsource_jjwxc.protocols.app") } + +---@return table|nil +function Protocols.current() + local chosen = require("utils.settings").getSource(SOURCE_ID).protocol + local fallback + for _idx, protocol in ipairs(Protocols.list) do + if protocol.available() then + if protocol.id == chosen then return protocol end + fallback = fallback or protocol + end + end + return fallback +end + +---@param id "web"|"app" +function Protocols.select(id) + local Settings = require("utils.settings") + Settings.getSource(SOURCE_ID).protocol = id + Settings.saveSource(SOURCE_ID) +end + +return Protocols diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/protocols/app.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/protocols/app.lua new file mode 100644 index 0000000..fd2dcc7 --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/protocols/app.lua @@ -0,0 +1,354 @@ +--[[-- +晋江「App」协议:账号密码登录拿 token(android API)。 + +只保存账号与 token,不保存密码;token 失效时交给 Auth 提示重新登录。和网页 Cookie 协议(web.lua)互不相干; +token 的请求头各接口不同,响应既可能是明文 JSON,也可能整包加密(密钥由响应头 accesskey / keystring 派生,见 decryptBody)。 + +协议接口(protocols/init.lua 按设置选一个协议调用):`available` / `shelfAsync` / `contentAsync`。 + +@module koplugin.book.moonsource_jjwxc.protocols.app +--]] + +local Job = require("workers.job") +local JSON = require("json") +local Mapper = require("moonsource_jjwxc.mapper") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_jjwxc") + +local Token = {} + +Token.id = "app" + +local SOURCE_ID = "ext.jjwxc" +local APP = "https://app-cdn.jjwxc.net/androidapi" +-- 接口回包 code:1004 = 要登录(token 无效),1025 = 登录态有效但这章没买。 +local LOGIN_CODE = 1004 +local UNPAID_CODE = 1025 +-- 登录接口的版本号与 App 内置的 DES 密钥(密钥写在 App 里,不是用户机密)。 +local LOGIN_VERSION = 402 +local DES_KEY, DES_IV = "KW8Dvm2N", "1ae2c94b" +local ACCOUNT_HEADERS = { + ["User-Agent"] = "Mobile", + ["Accept-Encoding"] = "identity", + ["Referer"] = "http://android.jjwxc.net?v=" .. LOGIN_VERSION, +} +-- 带 token 取正文必须带 App 的 UA,UA 是 "Mobile" 时服务端回 2016「浏览器标识异常」。 +local CONTENT_HEADERS = { + ["User-Agent"] = "JINJIANG-Android/381", + ["Referer"] = "http://android.jjwxc.net?v=381", + ["Accept-Encoding"] = "identity", +} +-- 要求设备验证(手机 / 邮箱验证码)的 code。 +local DEVICE_VERIFY_CODE = 221003 + +---@return string +function Token.label() return _("App 账号") end + +---@return string|nil +function Token.get() + local Settings = require("utils.settings") + local cfg = Settings.getSource(SOURCE_ID) + if cfg.password ~= nil then + cfg.password = nil + Settings.saveSource(SOURCE_ID) + end + local token = cfg.token + return type(token) == "string" and token ~= "" and token or nil +end + +---@return boolean +function Token.available() return Token.get() ~= nil end + +--- 段评接口(Pc/comment)的登录态:VIP 章节要求,App 协议把 token 放查询参数(放请求头 / Cookie 都被拒)。 +---@return string query +---@return table headers +function Token.commentAuth() + local token = Token.get() + return token and "&token=" .. Text.urlEncode(token) or "", {} +end + +--- 登录成功后保存账号与 token。 +---@param account string +---@param _password string 仅为旧调用签名保留,不落盘 +---@param token string +function Token.save(account, _password, token) + local Settings = require("utils.settings") + local cfg = Settings.getSource(SOURCE_ID) + cfg.account, cfg.password, cfg.token = account, nil, token + Settings.saveSource(SOURCE_ID) +end + +--- 整包加密响应的解密:accesskey / keystring 两个响应头派生 DES 密钥,12 字符的盐在正文头或尾(看 accesskey 末字符奇偶)。 +---@param body string +---@param accesskey string +---@param keystring string +---@return string|nil +function Token.decryptBody(body, accesskey, keystring) + local sum = 0 + for i = 1, #accesskey do sum = sum + accesskey:byte(i) end + local start, count = sum % #keystring, math.floor(sum / 65) + local part = start + count > #keystring and keystring:sub(start + 1) or keystring:sub(start + 1, start + count) + local salt, cipher + if accesskey:byte(-1) % 2 == 1 then + salt, cipher = body:sub(-12), body:sub(1, -13) + else + salt, cipher = body:sub(1, 12), body:sub(13) + end + local md5, Des = require("ffi/sha2").md5, require("crypto.des") + local key, iv = md5(part .. salt):sub(1, 8), md5(salt):sub(1, 8) + if cipher:find("^%x+$") then + local raw = require("crypto.hex").from_hex(cipher) + return raw and Des.decrypt(raw, key, iv) + end + return Des.decryptBase64(cipher, key, iv) +end + +---@param path string +---@param params table +---@param headers table +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +local function get(path, params, headers, cb) + local query = {} + for key, value in pairs(params) do query[#query + 1] = key .. "=" .. tostring(value) end + table.sort(query) + local cancelled, job, pending = false, nil, true + local initial = Request.get(APP .. path .. "?" .. table.concat(query, "&"), { + accept = "application/json", + headers = headers, + timeout = require("http.timeout").net(1), + cache_ttl = 0, + }, function(raw, err, res) + pending = false + if cancelled then return end + if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end + local ok, wire = pcall(JSON.decode, raw) + if ok and type(wire) == "table" then cb(wire); return end + local accesskey, keystring = Request.header(res, "accesskey"), Request.header(res, "keystring") + if not (accesskey and keystring and keystring ~= "") then + require("utils.log").warn("jjwxc invalid response", path, #raw) + cb(nil, _("响应无效")) + return + end + -- DES 是纯 Lua 重活,放子进程 + job = Job.run(function() return { plain = Token.decryptBody(raw, accesskey, keystring) } end, { + name = "jjwxc_body", + kind = "light", + timeout = 60, + on_done = function(r) + if cancelled then return end + local ok2, wire2 = pcall(JSON.decode, r.plain or "") + if ok2 and type(wire2) == "table" then cb(wire2); return end + require("utils.log").warn("jjwxc decrypt body failed", path, #raw) + cb(nil, _("响应无效")) + end, + on_failed = function(e) if not cancelled then cb(nil, tostring(e)) end end, + on_cancelled = function() end, + }) + end) + if pending then job = initial end + return { cancel = function() + cancelled = true + if job then job:cancel() end + end } +end + +---@param value any +---@return string|nil +local function nonEmpty(value) + return type(value) == "string" and value ~= "" and value or nil +end + +---@param n integer +---@param alphabet string +---@return string +local function randomString(n, alphabet) + local out = {} + for i = 1, n do + local k = math.random(#alphabet) + out[i] = alphabet:sub(k, k) + end + return table.concat(out) +end + +--- 账号密码登录,拿 App token。 +--- 回调 (token) / (nil, err) / (nil, message, "verify"):后者表示要先做设备验证再带 checktype + code 重试。 +---@param account string +---@param password string +---@param verify { checktype: "phone"|"email", code: string }|nil +---@param cb fun(token: string|nil, err: string|nil, kind: "verify"|nil) +---@return HttpJob +function Token.loginAsync(account, password, verify, cb) + local Des = require("crypto.des") + local identifiers = randomString(20, "0123456789") .. ":" .. randomString(16, "0123456789abcdef") .. "d4:" + local params = { + loginName = Text.urlEncode(account), + encode = 1, + loginPassword = Text.urlEncode(Des.encryptBase64(password, DES_KEY, DES_IV)), + sign = Text.urlEncode(Des.encryptBase64(os.time() * 1000 .. "_" .. identifiers .. "_", DES_KEY, DES_IV)), + identifiers = Text.urlEncode(identifiers), + autologin = 1, + versionCode = LOGIN_VERSION, + } + if verify then + params.checktype = verify.checktype + params.checkdevicecode = Text.urlEncode(verify.code) + end + return get("/login", params, ACCOUNT_HEADERS, function(wire, err) + if not wire then cb(nil, err); return end + if type(wire.token) == "string" and wire.token ~= "" then cb(wire.token); return end + if tonumber(wire.code) == DEVICE_VERIFY_CODE and not verify then + cb(nil, nonEmpty(wire.message) or _("晋江要求设备验证"), "verify") + return + end + cb(nil, nonEmpty(wire.message) or _("晋江登录失败")) + end) +end + +--- 让晋江给账号绑定的手机 / 邮箱发设备验证码。 +---@param account string +---@param checktype "phone"|"email" +---@param cb fun(message: string|nil, err: string|nil) +---@return HttpJob +function Token.sendCodeAsync(account, checktype, cb) + local headers = { ["User-Agent"] = "Mobile", ["Accept-Encoding"] = "identity" } + return Request.post("https://app.jjwxc.org/appDevicesecurityAndroid/getDeviceSecurityCode", + Text.formEncode({ versionCode = 401, username = account, checktype = checktype }), { + accept = "application/json", + headers = headers, + content_type = "application/x-www-form-urlencoded", + timeout = require("http.timeout").net(1), + }, function(raw, err) + if 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 + -- 发送成功时提示语在 data.message;失败(如 2021 缺少前置步骤、1004)只有顶层 message + local sent = type(wire.data) == "table" and wire.data.message + if type(sent) == "string" and sent ~= "" and tonumber(wire.code) ~= 1004 then cb(sent); return end + cb(nil, nonEmpty(wire.message) or _("晋江没有确认验证码已发送")) + end) +end + +--- 带 token 的书架;旧请求不能让新登录态过期。 +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Token.shelfAsync(cb) + ---@type boolean, CancelHandle|nil + local cancelled, job = false, nil + local function fetch(token, retry) + local pending = true + local initial = get("/incrementFavorite", { versionCode = 185, token = Text.urlEncode(token), backupTime = 1041350400, order = 1 }, + ACCOUNT_HEADERS, function(wire, err) + pending = false + if cancelled then return end + if not wire then cb(nil, err); return end + if tonumber(wire.code) == LOGIN_CODE and retry then + local fresh = Token.get() + if fresh and fresh ~= token then fetch(fresh, false) + else cb(nil, require("source.auth").expire(SOURCE_ID, require("moonsource_jjwxc.setting").expired())) end + return + end + local list = wire.addData + if type(list) ~= "table" then cb(nil, wire.message or _("晋江书架无法解析")); return end + require("source.auth").ok(SOURCE_ID) + cb(Mapper.tokenFavRows(list)) + end) + if pending then job = initial end + end + fetch(Token.get(), true) + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 已购正文。encryptType 为 jj 时一定是 DES;漏标时不像章节的内容才解,解开后像章节才采用。 +---@param content string +---@param encrypt_type string|nil +---@return string|nil +function Token.chapterText(content, encrypt_type) + local function readable(text) + return type(text) == "string" and (text:find("/<章>,已购才有正文,反爬字体见 font.lua)、 +VIP 章购买状态。Cookie 失效时网页 302 到登录页。 + +协议接口(protocols/init.lua 按设置选一个协议调用):`available` / `shelfAsync` / `contentAsync`。 + +@module koplugin.book.moonsource_jjwxc.protocols.web +--]] + +local Charset = require("utils.charset") +local Font = require("moonsource_jjwxc.font") +local Job = require("workers.job") +local Mapper = require("moonsource_jjwxc.mapper") +local Request = require("http.request") +local _ = require("l10n").get("moonsource_jjwxc") + +local Web = {} + +Web.id = "web" + +local SOURCE_ID = "ext.jjwxc" +local HOST = "https://m.jjwxc.com" +local FONT_URL = "https://static.jjwxc.net/tmp/fonts/%s.ttf" +local UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) " + .. "Version/16.0 Mobile/15E148 Safari/604.1" + +---@return string +function Web.label() return _("网页 Cookie") end + +---@return string|nil +function Web.cookie() + local cookie = require("utils.settings").getSource(SOURCE_ID).cookie + return type(cookie) == "string" and cookie ~= "" and cookie or nil +end + +---@return boolean +function Web.available() return Web.cookie() ~= nil end + +--- 段评接口(Pc/comment)的登录态:VIP 章节要求,网页协议走 Cookie。 +---@return string query +---@return table headers +function Web.commentAuth() return "", { Cookie = Web.cookie() } end + +--- 带登录态取网页,回调 UTF-8 的 HTML。302 到登录页 = Cookie 失效。 +---@param path string +---@param cookie string|nil +---@param cb fun(html: string|nil, err: string|nil, kind: "unpaid"|nil) +---@return HttpJob +local function get(path, cookie, cb) + return Request.get(HOST .. path, { + headers = { ["User-Agent"] = UA }, + jar = require("http.cookie_jar").session(SOURCE_ID, cookie), + timeout = require("http.timeout").net(0.5), + cache_ttl = 0, + }, function(raw, err, res) + if not raw then + local location = res and tonumber(res.code) == 302 and Request.header(res, "Location") + if location and not location:find("login", 1, true) then + -- 跳到非登录页(如未购买章节的订阅页)说明 Cookie 有效 + cb(nil, _("晋江 VIP 章节未购买"), "unpaid") + elseif location then + -- 校验新 Cookie 时不能污染已保存的登录态。 + local msg = require("moonsource_jjwxc.setting").expired() + cb(nil, cookie == Web.cookie() and require("source.auth").expire(SOURCE_ID, msg) or msg) + else + cb(nil, err and tostring(err) or _("请求失败")) + end + return + end + local html, charset = Charset.toUtf8(raw, Request.header(res, "Content-Type")) + if not html then cb(nil, charset); return end + cb(html) + end) +end + +--- 拉个人收藏(一页列全)。cookie 显式传入:登录入口要先校验再保存。 +---@param cookie string +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return HttpJob +function Web.favAsync(cookie, cb) + return get("/my/fav", cookie, function(html, err) + if not html then cb(nil, err); return end + local rows = Mapper.favRows(html) + if not rows then cb(nil, _("晋江收藏页无法解析")); return end + if cookie == Web.cookie() then require("source.auth").ok(SOURCE_ID) end + cb(rows) + end) +end + +--- 收藏按页拉。页面上没有下一页链接,一页 30 本,空页才是尽头。 +--- 登录校验仍走 favAsync(只要第一页能解析)。 +--- 后面某页失败、或翻到上限这一页还有新书,整次失败:半截列表交给书架对账会把没拉到的书藏掉。 +local MAX_FAV_PAGES = 50 + +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Web.shelfAsync(cb) + local cookie = Web.cookie() + local rows, seen, handle = {}, {}, {} + local function page(n) + local pending = true + local initial = get("/my/fav?p=" .. n, cookie, function(html, err) + pending = false + if handle.cancelled then return end + if cookie ~= Web.cookie() then cb(nil, _("账号已变化,请重新登录")); return end + if not html then cb(nil, err); return end + local batch = Mapper.favRows(html) + if not batch then cb(nil, _("晋江收藏页无法解析")); return end + if n == 1 and cookie == Web.cookie() then require("source.auth").ok(SOURCE_ID) end + local added = 0 + for _idx, row in ipairs(batch) do + if not seen[row.id] then + seen[row.id] = true + rows[#rows + 1] = row + added = added + 1 + end + end + if #batch == 0 then cb(rows); return end + if added == 0 then cb(nil, _("晋江收藏页无法解析")); return end + if n >= MAX_FAV_PAGES then cb(nil, _("晋江收藏页过多,没有同步完")); return end + page(n + 1) + end) + if pending then handle.inner = initial end + end + page(1) + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner:cancel() end + end + return handle +end + +--- 取消收藏。网页是「确认页 → /my/delBookSure」两步,这里直接走第二步。 +---@param novel_id string +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return { cancel: fun() } +function Web.favRemoveAsync(novel_id, cb) + local cookie = Web.cookie() + if not cookie then return require("source.base").defer(cb, nil, _("未登录晋江")) end + local cancelled, job, pending = false, nil, true + local initial = get("/my/delBookSure?novelid=" .. novel_id, cookie, function(html, err) + pending = false + if cancelled then return end + if not html then cb(nil, err); return end + if cookie ~= Web.cookie() then cb(nil, _("账号已变化,请重新登录")); return end + job = Web.shelfAsync(function(rows, reason) + if cancelled then return end + if not rows then cb(nil, reason); return end + for _idx, row in ipairs(rows) do + if row.id == novel_id then cb(nil, _("晋江没有确认取消收藏")); return end + end + cb(true) + end) + end) + if pending then job = initial end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 这章 VIP 买了没有:true 已购、false 未购、nil 没问出来(未登录 / 网络 / Cookie 失效)。 +---@param novel_id string +---@param chapter_id string +---@param cb fun(paid: boolean|nil) +---@return HttpJob|nil +function Web.paidAsync(novel_id, chapter_id, cb) + local cookie = Web.cookie() + if not cookie then cb(nil); return nil end + return get("/vip/" .. novel_id .. "/" .. chapter_id, cookie, function(html, _err, kind) + if kind == "unpaid" then cb(false) + elseif html and html:find('id="contentvars"', 1, true) then cb(true) + else cb(nil) end + end) +end + +--- 反爬字体的私有区字符映射回真字:下字体、解析映射都放子进程。 +---@param text string +---@param font string +---@param cancelled fun(): boolean +---@param cb fun(text: string|nil, err: string|nil) +---@return { cancel: fun() } +local function decodeFont(text, font, cancelled, cb) + local job + local pending = true + local initial = Request.get(FONT_URL:format(font), { + timeout = require("http.timeout").net(0.5), + }, function(ttf, font_err) + pending = false + if cancelled() then return end + if not ttf then cb(nil, font_err and tostring(font_err) or _("晋江 VIP 章节字体无法解析")); return end + job = Job.run(function() + local map = Font.mapping(ttf) + return { text = map and Font.decode(text, map) } + end, { + name = "jjwxc_font", + kind = "light", + timeout = 60, + on_done = function(res) + if cancelled() then return end + if res.text then cb(res.text) else cb(nil, _("晋江 VIP 章节字体无法解析")) end + end, + on_failed = function(err) if not cancelled() then cb(nil, tostring(err)) end end, + on_cancelled = function() end, + }) + end) + if pending then job = initial end + return { cancel = function() if job then job:cancel() end end } +end + +--- VIP 章正文(纯文本,段落以换行分隔):网页只有已购章节才有正文。 +---@param novel_id string +---@param chapter_id string +---@param cb fun(text: string|nil, err: string|nil, kind: "unpaid"|nil) +---@return { cancel: fun() } +function Web.contentAsync(novel_id, chapter_id, cb) + local cancelled, job = false, nil + local function isCancelled() return cancelled end + local pending = true + local initial = get("/vip/" .. novel_id .. "/" .. chapter_id, Web.cookie(), function(html, web_err, kind) + pending = false + if cancelled then return end + if not html then + cb(nil, web_err or _("晋江 VIP 章节未购买"), kind and "unpaid" or nil) + return + end + -- AES 解密与字体解析都是纯 Lua 重活,放子进程,免得卡 UI + local decoding = true + local decoder = Job.run(function() local text, why = Mapper.webContent(html); return { text = text, why = why } end, { + name = "jjwxc_vip", + kind = "light", + timeout = 60, + on_done = function(res) + decoding = false + if cancelled then return end + local text = res.text + if not text then + if html:find('id="contentvars"', 1, true) then + require("utils.log").warn("jjwxc vip decrypt failed", novel_id, chapter_id, res.why) + cb(nil, _("晋江 VIP 章节解密失败")) + else + cb(nil, _("晋江 VIP 章节未购买"), "unpaid") + end + return + end + local font = html:match("jjwxcfont_%w+") + if not (font and text:find("[\238\239][\128-\191][\128-\191]")) then cb(text); return end + job = decodeFont(text, font, isCancelled, cb) + end, + on_failed = function(err) if not cancelled then cb(nil, tostring(err)) end end, + on_cancelled = function() end, + }) + if decoding then job = decoder end + end) + if pending then job = initial end + return { cancel = function() + cancelled = true + if job then job:cancel() end + end } +end + +return Web diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/reviews.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/reviews.lua new file mode 100644 index 0000000..1a3b2d5 --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/reviews.lua @@ -0,0 +1,162 @@ +--[[-- +晋江段评:本章各段评论数、某段的评论页、把段落定位到章节 HTML。 + +走晋江网页版的段评接口(www.jjwxc.net/app.jjwxc/Pc/comment/…),免费章节匿名可读,VIP 章节要登录态(当前协议的 commentAuth:web 带 Cookie,app 带 token 查询参数): +- getNovelParagraphCommentNum:本章每段的评论数;paragraph_id 是「第几个非空段」(从 1 数),-2 是章末总评。 +- getCommentList:某段的评论,offset / limit 翻页,新的在前。 +章节 HTML 的段落就是非空行逐个包成

    (Text.textToBody),所以第 n 个

    就是 paragraph_id = n。 + +@module koplugin.book.moonsource_jjwxc.reviews +--]] + +local JSON = require("json") +local Request = require("http.request") +local ReviewLocate = require("book.review_locate") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_jjwxc") + +local Reviews = {} + +local BASE = "https://www.jjwxc.net/app.jjwxc/Pc/comment/" +local VERSION = "489" +local PAGE_SIZE = 20 + +---@class JjwxcReviewHotspot +---@field range string 段落序号(第几个非空段) +---@field text string +---@field total integer 本段评论数 + +---@param name string +---@param query string +---@param novel_id string +---@param chapter_id string +---@param cb fun(data: table|nil, err: string|nil) +---@return HttpJob +local function get(name, query, novel_id, chapter_id, cb) + local referer = "https://www.jjwxc.net/onebook.php?novelid=" .. novel_id .. "&chapterid=" .. chapter_id + local headers = { ["User-Agent"] = "Mozilla/5.0", Referer = referer, versionCode = VERSION } + -- 免费章节匿名可读,VIP 章节要登录态;没有任何登录态就匿名发。 + local protocol = require("moonsource_jjwxc.protocols").current() + local auth_query, auth_headers = "", {} + if protocol then auth_query, auth_headers = protocol.commentAuth() end + for key, value in pairs(auth_headers) do headers[key] = value end + return Request.get(BASE .. name .. "?versionCode=" .. VERSION .. query .. auth_query, { + accept = "application/json", + headers = headers, + timeout = require("http.timeout").net(0.5), + }, function(raw, err) + if 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 + if tostring(wire.code) ~= "200" or type(wire.data) ~= "table" then + cb(nil, tostring(wire.message or _("晋江段评请求失败"))) + return + end + cb(wire.data) + end) +end + +--- 统计回包 → 有评论的段落与章末(-2);源入口按粒度分开。 +---@param data table +---@return JjwxcReviewHotspot[]|nil, string|nil +function Reviews.hotspots(data) + if next(data) and data[1] == nil then return nil, _("响应无效") end + local out = {} + for _idx, row in ipairs(data) do + if type(row) ~= "table" then return nil, _("响应无效") end + local pid, total = tonumber(row.paragraph_id), tonumber(row.comment_total) + if not pid or not total or total < 0 then return nil, _("响应无效") end + if (pid > 0 or pid == -2) and total > 0 then + out[#out + 1] = { range = tostring(pid), text = "", total = total } + end + end + table.sort(out, function(a, b) return tonumber(a.range) < tonumber(b.range) end) + return out +end + +--- 表情标记交给主题行内图片渲染;保留原文供离线缺图时显示。 +---@param content string +---@return table }>|nil +function Reviews.inlineImages(content) + local emoticons = require("moonsource_jjwxc.emoticons") + local images = {} + for placeholder in content:gmatch("%b[]") do + local url = emoticons[placeholder] + if url then images[placeholder] = { url = url, headers = { Referer = "https://www.jjwxc.net/" } } end + end + return next(images) and images or nil +end + +--- 正文里偶有 HTML 实体 / 换行标签。 +---@param row table +---@return WechatReview +function Reviews.item(row) + local body = Text.stripHtml(row.commentBody) + return { + id = tostring(row.commentId or ""), + author = tostring(row.commentAuthor or ""), + content = body, + inline_images = Reviews.inlineImages(body), + likes = tonumber(row.agreenum) or 0, + images = {}, + time = tonumber(row.comment_date_time) or 0, + } +end + +--- 评论回包 → 一页;offset 即游标(首页 0)。 +---@param data table +---@param offset integer +---@return WechatReviewPage|nil, string|nil +function Reviews.page(data, offset) + local list = data.commentList + if type(list) ~= "table" then return nil, _("晋江段评响应缺少评论列表") end + if next(list) and list[1] == nil then return nil, _("晋江段评响应缺少评论列表") end + local total = tonumber(data.commentTotal) + if not total or total < 0 then return nil, _("晋江段评响应缺少评论列表") end + local items = {} + for _idx, row in ipairs(list) do + if type(row) ~= "table" or not row.commentId then return nil, _("晋江段评响应缺少评论列表") end + items[#items + 1] = Reviews.item(row) + end + local next_offset = offset + #items + return { items = items, total = total, max_idx = next_offset, more = #items > 0 and next_offset < total } +end + +--- 本章有评论的段落。 +---@param novel_id string +---@param chapter_id string +---@param cb fun(hotspots: JjwxcReviewHotspot[]|nil, err: string|nil) +---@return HttpJob +function Reviews.hotspotsAsync(novel_id, chapter_id, cb) + return get("getNovelParagraphCommentNum", "&novelid=" .. novel_id .. "&chapterid=" .. chapter_id, + novel_id, chapter_id, function(data, err) + if not data then cb(nil, err); return end + cb(Reviews.hotspots(data)) + end) +end + +--- 某段的一页评论。 +---@param novel_id string +---@param chapter_id string +---@param para_index integer +---@param offset integer +---@param cb fun(page: WechatReviewPage|nil, err: string|nil) +---@return HttpJob +function Reviews.pageAsync(novel_id, chapter_id, para_index, offset, cb) + local query = string.format("&novelId=%s&chapterId=%s¶graph_id=%d&offset=%d&limit=%d", + novel_id, chapter_id, para_index, offset, PAGE_SIZE) + return get("getCommentList", query, novel_id, chapter_id, function(data, err) + if not data then cb(nil, err); return end + cb(Reviews.page(data, offset)) + end) +end + +--- 把有评论的段落定位到章节 HTML。 +---@param hotspots JjwxcReviewHotspot[] +---@param html string +---@return table[] +function Reviews.locate(hotspots, html) + return ReviewLocate.locate(ReviewLocate.paragraphs(html), hotspots, html) +end + +return Reviews diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/setting.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/setting.lua new file mode 100644 index 0000000..0467a9d --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/setting.lua @@ -0,0 +1,242 @@ +--[[-- +晋江源设置:登录。 + +晋江手机网页的登录要过数美验证,墨水屏上做不了;登录协议有两套(protocols/web.lua、protocols/app.lua),只用其中一个: +1. 网页 Cookie:远程管理里的「浏览器登录」(浏览器扩展交 Cookie),或在电脑浏览器登录后把 Cookie 请求头粘贴进来, + 先拉一次收藏页校验,通过才保存。能同步收藏、取消收藏、读已购 VIP 章。 +2. App 账号:设备上直接输账号密码(新设备要手机 / 邮箱验证码),只保存账号与 token,token 失效后重新登录。 + 能同步书架、读已购 VIP 章。 +登录成功即切到该协议;两套都登录过时可在设置里改用哪一个。 + +@module koplugin.book.moonsource_jjwxc.setting +--]] + +local _ = require("l10n").get("moonsource_jjwxc") +local CookieLogin = require("source.cookie_login") + +local SOURCE_ID = "ext.jjwxc" +local Setting = {} + +---@return boolean +local function loggedIn() + return require("moonsource_jjwxc.protocols").current() ~= nil +end + +---@return string, boolean +function Setting.rowStatus() + local on = loggedIn() + return on and _("已登录") or _("未登录 · 点此登录"), on +end + +---@type CookieLoginSpec +local SPEC = { + id = SOURCE_ID, + title = _("晋江账号"), + cookie_title = _("晋江登录 Cookie"), + cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"), + logout_text = _("确定退出晋江账号?"), + loggedIn = loggedIn, + -- 拉一次收藏页校验 Cookie;通过即切到网页协议。 + checkAsync = function(cookie, cb) + return require("moonsource_jjwxc.protocols.web").favAsync(cookie, function(rows, err) cb(rows ~= nil, err) end) + end, + commit = function(cookie, _account, cb) + local Settings = require("utils.settings") + local cfg = Settings.getSource(SOURCE_ID) + if (cfg.cookie or cfg.token) and cfg.cookie ~= cookie then + local cleared = require("source.logout").clear(SOURCE_ID, function() + cfg.cookie, cfg.token, cfg.account, cfg.password, cfg.protocol = nil, nil, nil, nil, nil + Settings.saveSource(SOURCE_ID) + end) + if not cleared then return cb(false, _("准备本地同步失败")) end + end + cfg.cookie, cfg.protocol = cookie, "web" + Settings.saveSource(SOURCE_ID) + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() + cb(true) + end, + clear = function(cfg) cfg.cookie, cfg.token, cfg.account, cfg.password, cfg.protocol = nil, nil, nil, nil, nil end, +} + +Setting.parseCookie = CookieLogin.parse + +--- 浏览器扩展交来的 payload.cookies → Cookie 请求头;只收晋江站点的 Cookie。 +---@param payload table +---@return string +function Setting.fromPayload(payload) + return CookieLogin.fromPayload(payload, "jjwxc.com") +end + +--- 浏览器扩展登录(features/cookie)。 +Setting.browser = { + domain = "m.jjwxc.com", + scope = "cookie", + login = "https://m.jjwxc.com/my/login", + check = "https://m.jjwxc.com/my/fav", + icon = "https://m-static.jjwxc.net/images/wap/logo2.png", + isAuthorized = function() return CookieLogin.authorized(SPEC) end, + apply = function(payload, cb) return CookieLogin.save(SPEC, Setting.fromPayload(payload), cb) end, +} + +local showAccountLogin + +---@param plugin table|nil +---@return table[] +function Setting.rows(plugin) + local Row = require("ui.themes.widgets.row") + local rows = { + CookieLogin.accountRow(SPEC, { callback = function() showAccountLogin() end, + off_text = _("未登录 · 点此用账号密码") }), + CookieLogin.browserRow(), + CookieLogin.pasteRow(SPEC), + require("source.review_setting").row(SOURCE_ID, plugin), + } + if not loggedIn() then return rows end + local Protocols = require("moonsource_jjwxc.protocols") + rows[#rows + 1] = function(iw) + local current = Protocols.current() + return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "swap_horiz", title = _("登录协议"), + status = current.label(), status_on = true, + callback = function() + local items = {} + for _idx, protocol in ipairs(Protocols.list) do + items[#items + 1] = { + text = protocol.label() .. (protocol.available() and "" or _("(未登录)")), + variant = protocol == current and "primary" or "normal", + enabled = protocol.available(), + callback = function() + Protocols.select(protocol.id) + require("source.registry").reload() + end, + } + end + require("ui.themes.widgets.sheet"):new{ title = _("登录协议"), items = items }:show() + end }) + end + rows[#rows + 1] = CookieLogin.logoutRow(SPEC) + return rows +end + +---@param account string +---@param password string +---@param token string +local function saveToken(account, password, token) + require("moonsource_jjwxc.protocols.app").save(account, password, token) + require("moonsource_jjwxc.protocols").select("app") + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() +end + +local showLogin + +--- 设备验证:选手机或邮箱收验证码,填了再登录一次。 +---@param account string +---@param password string +---@param message string +local function showVerify(account, password, message) + local Toast = require("ui.themes.widgets.toast") + local Token = require("moonsource_jjwxc.protocols.app") + local checktype = "phone" + local function send(kind) + checktype = kind + Token.sendCodeAsync(account, kind, function(msg, err) + Toast:new{ text = msg or err, timeout = 3 }:show() + end) + end + require("ui.themes.widgets.input"):new{ + title = _("晋江设备验证"), + fields = { { label = message, text = "", hint = _("验证码"), input_type = "number" } }, + ok_text = _("验证并登录"), + actions = { + { text = _("发到手机"), callback = function() send("phone") end }, + { text = _("发到邮箱"), callback = function() send("email") end }, + }, + callback = function(code) + code = (code or ""):gsub("%s", "") + if code == "" then + Toast:new{ text = _("请先填写验证码"), timeout = 3 }:show() + return + end + showLogin(account, password, { checktype = checktype, code = code }) + end, + }:show() +end + +--- 账号密码登录;verify 非空表示带设备验证码重试。 +---@param account string +---@param password string +---@param verify { checktype: string, code: string }|nil +function showLogin(account, password, verify) + local Toast = require("ui.themes.widgets.toast") + if not require("ui/network/manager"):isConnected() then + Toast:new{ text = _("未联网"), timeout = 3 }:show() + return + end + local cfg = require("utils.settings").getSource(SOURCE_ID) + local previous_cookie, previous_token = cfg.cookie, cfg.token + local current = require("source.auth").beginLogin(SOURCE_ID) + local cancelled, job = false, nil + local waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("晋江账号"), text = _("正在登录…"), dismissable = false, + on_cancel = function() + cancelled = true + if job then job.cancel() end + end, + } + waiting:show() + job = require("moonsource_jjwxc.protocols.app").loginAsync(account, password, verify, function(token, err, kind) + if cancelled then return end + waiting:close() + if not current() or cfg.cookie ~= previous_cookie or cfg.token ~= previous_token then + Toast:new{ text = _("账号已变化,请重新登录"), timeout = 3 }:show() + elseif token then + if cfg.cookie or (cfg.token and cfg.account ~= account) then + local cleared = require("source.logout").clear(SOURCE_ID, function() + cfg.cookie, cfg.token, cfg.account, cfg.password, cfg.protocol = nil, nil, nil, nil, nil + require("utils.settings").saveSource(SOURCE_ID) + end) + if not cleared then Toast:new{ text = _("准备本地同步失败"), timeout = 3 }:show(); return end + end + saveToken(account, password, token) + Toast:new{ text = _("登录成功"), timeout = 2 }:show() + elseif kind == "verify" then + showVerify(account, password, err) + else + Toast:new{ text = err, timeout = 3 }:show() + end + end) +end + +function showAccountLogin() + require("ui.themes.widgets.input"):new{ + title = _("晋江账号登录"), + fields = { + { label = _("账号"), text = "", hint = _("笔名 / 邮箱 / 手机号") }, + { label = _("密码"), text = "", text_type = "password" }, + }, + ok_text = _("登录"), + callback = function(account, password) + account = (account or ""):gsub("^%s+", ""):gsub("%s+$", "") + if account == "" or (password or "") == "" then + require("ui.themes.widgets.toast"):new{ text = _("账号或密码不能为空"), timeout = 3 }:show() + return + end + showLogin(account, password) + end, + }:show() +end + +--- 登录失效时的操作说明:账号密码和浏览器 Cookie 两条都写清。 +---@return string +function Setting.expired() + return _("你在晋江用的是哪种登录,就做哪种。") .. "\n\n" + .. _("账号和密码:点这个提示上的「重新登录」。没有这个按钮的话,打开「设置 → 书库 → 账号 → 晋江文学城 → 晋江账号」。填笔名、邮箱或手机号,再填密码,点「登录」。要验证码就点「发到手机」或「发到邮箱」,把验证码填进去,再点「验证并登录」。") + .. "\n\n" .. require("source.cookie_login").relogin(_("晋江文学城"), "https://m.jjwxc.com/my/login") + .. "\n\n" .. _("不想装扩展、平时用的是网页 Cookie:打开「设置 → 书库 → 账号 → 晋江文学城 → 晋江账号」,点「用 Cookie 登录」。Cookie 这样复制:电脑登录后按 F12,点「网络」,刷新,点任意一条请求,复制「请求标头」里的整段 Cookie,贴进去点「登录」。") +end + +--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。 +Setting.login = showAccountLogin + +return Setting diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/source.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/source.lua new file mode 100644 index 0000000..d91670d --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/source.lua @@ -0,0 +1,394 @@ +--[[-- +晋江文学城数据源。 + +书的元数据 / 目录 / 免费章正文走匿名 App 接口,VIP 章与个人收藏走手机网页 Cookie(client.lua)。 +登录是浏览器登录态的 Cookie(setting.lua);登录后收藏双向同步(source.shelf):拉取、本地删除上行。 +段评走网页版匿名接口(reviews.lua),设置里开关。 +最近阅读页能读到章,但没有确认能写回的接口,进度不接,避免只拉不推。笔记和统计没有接口。 + +@module moonsource_jjwxc +--]] + +local Browse = require("source.browse") +local Client = require("moonsource_jjwxc.client") +local Mapper = require("moonsource_jjwxc.mapper") +local Protocols = require("moonsource_jjwxc.protocols") +local ReviewCache = require("book.review_cache") +local Shelf = require("source.shelf") +local SourceBase = require("source.base") +local Toc = require("source.toc") +local Web = require("moonsource_jjwxc.protocols.web") +local _ = require("l10n").get("moonsource_jjwxc") + +local Jjwxc = {} + +-- 接口按 IP 限流,预取与整本缓存逐章间隔请求。 +local FETCH_INTERVAL = 1 + +---@return BookSourceMeta +function Jjwxc.meta() + return require("moonsource_jjwxc.loadmeta")() +end + +---@class JjwxcSource : SourceBase +---@field probe { stable_id: string, cancel: fun() }|nil 在飞的 VIP 章购买状态探测 +local Source = setmetatable({}, { __index = SourceBase }) +Source.__index = Source + +---@return JjwxcSource +function Jjwxc.new() + local meta = Jjwxc.meta() + return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source) +end + +---@return boolean +function Source:configured() + return Protocols.current() ~= nil +end + +--- 收藏页的书名是截断的:本地没有完整元数据(封面是标志)的书逐本补拉详情,拉不到就退回页面上的书名。 +---@param rows table[] +---@param cb fun(rows: table[]) +---@return { cancel: fun() } +local function fillDetails(rows, cb) + local BookDB = require("book.books_db") + local cancelled, job, index = false, nil, 0 + local function nextRow() + if cancelled then return end + index = index + 1 + local row = rows[index] + if not row then cb(rows); return end + row.local_book = BookDB.get(Jjwxc.meta().id, row.id) + local cover = row.local_book and row.local_book.cover + if cover and cover ~= "" then nextRow(); return end + row.local_book = nil + local pending = true + local initial = Client.detailAsync(row.id, function(info, err) + pending = false + if cancelled then return end + if info then + row.info = info + else + require("utils.log").warn("book jjwxc detail failed", row.id, err) + end + nextRow() + end) + if pending then job = initial end + end + nextRow() + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 书架远端:Shelf.syncAsync 要的三个冒号方法。 +local Remote = {} + +function Remote:shelfSyncAsync(cb) + local cancelled, job, fill = false, nil, nil + job = Protocols.current().shelfAsync(function(rows, err) + if cancelled then return end + if not rows then cb(nil, err); return end + fill = fillDetails(rows, cb) + end) + return { cancel = function() + cancelled = true + job.cancel() + if fill then fill.cancel() end + end } +end + +--- 网页收藏要过数美设备校验,月读暂时加不进去。 +function Remote:addToShelfAsync(_stable_id, cb) + return SourceBase.defer(cb, nil, _("晋江暂不支持从月读加入收藏")) +end + +function Remote:removeFromShelfAsync(stable_id, cb) + if Protocols.current() ~= Web then + return SourceBase.defer(cb, nil, _("App 协议暂不支持取消收藏,请在设置里改用网页协议")) + end + return Web.favRemoveAsync(stable_id, cb) +end + +function Source:syncBooksAsync(opts, cb) + if not self:configured() then return SourceBase.skipped(cb, "jjwxc not logged in") end + return Shelf.syncAsync(self.id, Remote, Mapper.shelfList, opts, cb) +end + +--- 进度 / 笔记 / 统计没有远端接口:不定义 put/push 方法,基类按能力回 skipped,脏行不入推送队列。 + +--- 书城搜索:匿名 App 接口,只取第一页。 +---@param keyword string +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Source:searchAsync(keyword, cb) + return Client.searchAsync(keyword, function(wire, err) + if not wire then + cb(nil, err) + return + end + cb({ data = Mapper.search(wire) }) + end) +end + +--- 书城浏览:默认官网分类库;兼容「榜单序号:频道序号」旧节点。 +--- 榜单名和频道来自书城首页;书按页拉到 opts.limit。 +---@param opts { node?: string, limit?: integer } +---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil) +---@return { cancel: fun() } +function Source:browseAsync(opts, cb) + opts = opts or {} + if not opts.node or opts.node:sub(1, 5) == "cate:" then + return require("moonsource_jjwxc.browse").run(opts, cb) + end + local handle = {} + -- 首页缓存命中时回调是下一拍,不会在赋值前跑完;这里仍按同步回调记步,避免把已换上的翻页句柄盖掉。 + local step = 0 + local function load(ranks) + if handle.cancelled then return end + step = step + 1 + if #ranks == 0 then cb(nil, _("晋江榜单无法解析")); return end + local rank_s, ch_s = (opts.node or "1:1"):match("^(%d+):(%d+)$") + local rank_i = tonumber(rank_s) or 1 + if not ranks[rank_i] then rank_i = 1 end + local channels = ranks[rank_i].channels + local ch_i = tonumber(ch_s) or 1 + if not channels[ch_i] then ch_i = 1 end + local node = rank_i .. ":" .. ch_i + local rank_chips, channel_chips = {}, {} + for i, rank in ipairs(ranks) do + local ci = rank.channels[ch_i] and ch_i or 1 + rank_chips[#rank_chips + 1] = { id = i .. ":" .. ci, title = rank.title } + end + for i, ch in ipairs(channels) do + channel_chips[#channel_chips + 1] = { id = rank_i .. ":" .. i, title = ch.title } + end + local page_size = Client.RANK_PAGE + handle.inner = Browse.pages(function(page, done) + return Client.rankPageAsync(channels[ch_i].id, (page - 1) * page_size, function(wire, err) + if not wire then done(nil, err); return end + local books = Mapper.rankBooks(wire) + done(books, nil, #books >= page_size) + end) + end, opts.limit or 60, { Browse.group(rank_chips, node), Browse.group(channel_chips, node), + { title = _("分类书库"), chips = { { id = "cate:0:0:0:0:0:0:2", title = _("分类书库") } } } }, cb) + end + local first = Client.storeHomeAsync(function(wire, err) + if handle.cancelled then return end + if not wire then cb(nil, err); return end + load(Mapper.storeRanks(wire)) + end) + if step == 0 then handle.inner = first end + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner:cancel() end + end + return handle +end + +function Source:getDetailAsync(identity, cb) + return SourceBase.defer(cb, identity.book or require("book.books_db").get(self.id, identity.stable_id)) +end + +--- 目录里还没问过的 VIP 章逐章问一遍购买状态(只在已登录时),问完落库一次;失败(断网 / Cookie 失效)就停。 +--- 一个源实例同时只有一条探测(`self.probe`):同一本书在飞就不重开;换书则取消旧的。 +--- 探测拿着自己那份目录表,结束时整表写回,所以目录重拉前必须先取消它,否则旧表把新目录盖回去。 +---@param self JjwxcSource +---@param identity BookIdentity +---@param toc BookChapter[] +local function probePaid(self, identity, toc) + if Protocols.current() ~= Web then return end + local todo = {} + for _idx, chapter in ipairs(toc) do + if chapter.vip and chapter.paid == nil then todo[#todo + 1] = chapter end + end + if #todo == 0 then return end + if self.probe then + if self.probe.stable_id == identity.stable_id then return end + self.probe.cancel() + end + local pos, changed, cancelled, job = 0, false, false, nil + local probe = { stable_id = identity.stable_id } + probe.cancel = function() + cancelled = true + if job then job.cancel() end + if self.probe == probe then self.probe = nil end + end + local function nextChapter() + pos = pos + 1 + local chapter = todo[pos] + if not chapter then + self.probe = nil + if changed then Toc.put(self.id, identity.stable_id, toc) end + return + end + local pending = true + local initial = Web.paidAsync(identity.stable_id, chapter.uid, function(paid) + pending = false + if cancelled then return end + if paid == nil then + pos = #todo + else + chapter.paid, changed = paid, true + end + nextChapter() + end) + if pending then job = initial end + end + self.probe = probe + nextChapter() +end + +function Source:close() + if self.probe then self.probe.cancel() end +end + +--- 强制拉目录并写回;失败由调用方继续用旧缓存。 +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +---@return { cancel: fun() } +local function fetchTocAsync(self, identity, cb) + local cancelled, job = false, nil + job = Client.chaptersAsync(identity.stable_id, function(wire, err) + if cancelled then return end + local toc = wire and Mapper.toc(wire) + if not toc then cb(nil, err); return end + if #toc == 0 then cb(nil, _("晋江目录为空")); return end + if self.probe and self.probe.stable_id == identity.stable_id then self.probe.cancel() end + if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end + cb(toc) + probePaid(self, identity, toc) + end) + return { cancel = function() + cancelled = true + job.cancel() + end } +end + +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +---@param force boolean|nil 真=跳过缓存强制拉 +---@return { cancel: fun() } +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 then + probePaid(self, identity, cached) + return SourceBase.defer(cb, cached) + end + end + return fetchTocAsync(self, identity, cb) +end + +Source.refreshTocAsync = fetchTocAsync + +function Source:openBookAsync(identity, opts, cb) + local Chapter = require("source.chapter") + local locate = require("book.review_locate") + local reviews = self:paragraphReviewsEnabled() + 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 = Chapter.vipFetcher(self, Client.contentAsync, true, reviews and locate.prepareChapterEnd or nil), + reuse = reviews and locate.reuseChapterEnd or nil, + }, cb) +end + +function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb) + local Chapter = require("source.chapter") + local locate = require("book.review_locate") + local reviews = self:paragraphReviewsEnabled() + return Chapter.prefetchAsync(identity, identity.book, toc, from_idx, count, { + fetchContent = Chapter.vipFetcher(self, Client.contentAsync, false, reviews and locate.prepareChapterEnd or nil), + reuse = reviews and locate.reuseChapterEnd or nil, + interval_seconds = FETCH_INTERVAL, + }, cb) +end + +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + local Chapter = require("source.chapter") + local prepare = self:paragraphReviewsEnabled() and require("book.review_locate").prepareChapterEnd or nil + return Chapter.cacheAllAsync(self, identity, Chapter.vipFetcher(self, Client.contentAsync, false, prepare), on_progress, cb, + FETCH_INTERVAL, range) +end + +--- 阅读页是否显示他人段评(设置页开关,默认关)。 +---@return boolean +function Source:paragraphReviewsEnabled() + return require("source.review_setting").enabled(self.id) +end + +--- 本章有评论的段落(未定位)。 +---@param identity BookIdentity +---@param cb fun(hotspots: JjwxcReviewHotspot[]|nil, err: string|nil) +---@return { cancel: fun() } +local function hotspotsAsync(self, identity, cb) + local withUid = require("source.with_chapter_uid") + return ReviewCache.hotspotsAsync(identity, function(done) + return withUid.run(self, identity, _("缺少晋江章节位置"), function(uid, finish) + return require("moonsource_jjwxc.reviews").hotspotsAsync(identity.stable_id, uid, finish) + end, done) + end, cb) +end + +function Source:paragraphHotspotsAsync(identity, cb) + return hotspotsAsync(self, identity, function(list, err) + if not list then cb(nil, err); return end + local paragraphs = {} + for _idx, spot in ipairs(list) do + if tonumber(spot.range) > 0 then paragraphs[#paragraphs + 1] = spot end + end + cb(paragraphs) + end) +end + +function Source:chapterReviewHotspotsAsync(identity, cb) + return hotspotsAsync(self, identity, function(list, err) + if not list then cb(nil, err); return end + local ending = {} + for _idx, spot in ipairs(list) do + if spot.range == "-2" then + ending[#ending + 1] = { range = spot.range, text = _("本章讨论"), total = spot.total, + badge = tostring(spot.total), heading = _("章节评论"), + anchor = require("book.review_locate").CHAPTER_ANCHOR } + end + end + cb(ending) + end) +end + +--- 段落按段末文字定位到章节 HTML(子进程里跑,不碰实例状态)。 +---@param hotspots JjwxcReviewHotspot[] +---@param html string +---@return table[] +function Source:locateHotspots(hotspots, html) + return require("moonsource_jjwxc.reviews").locate(hotspots, html) +end + +--- 某段的一页评论;range 是段落序号,max_idx 是翻页偏移(首页 0)。 +---@param identity BookIdentity +---@param range string +---@param max_idx integer +---@param cb fun(page: WechatReviewPage|nil, err: string|nil) +---@return { cancel: fun() } +function Source:paragraphReviewPageAsync(identity, range, max_idx, cb) + local withUid = require("source.with_chapter_uid") + local Reviews = require("moonsource_jjwxc.reviews") + local Text = require("utils.text") + return ReviewCache.pageAsync(identity, range, max_idx, function(done) + return withUid.run(self, identity, _("缺少晋江章节位置"), function(uid, finish) + return Reviews.pageAsync(identity.stable_id, uid, tonumber(range), max_idx, finish) + end, done) + end, function(page, err) + if page then + for _idx, item in ipairs(page.items) do + item.content = Text.stripHtml(item.content) + if not item.inline_images then item.inline_images = Reviews.inlineImages(item.content) end + end + end + cb(page, err) + end) +end + +return Jjwxc diff --git a/moonsource-jjwxc.koplugin/moonsource_jjwxc/vip.lua b/moonsource-jjwxc.koplugin/moonsource_jjwxc/vip.lua new file mode 100644 index 0000000..6f4ab4e --- /dev/null +++ b/moonsource-jjwxc.koplugin/moonsource_jjwxc/vip.lua @@ -0,0 +1,144 @@ +--[[-- +晋江 VIP 章网页(m.jjwxc.com/vip/<书>/<章>)正文解密。页面里正文是 #contentvars 的隐藏域, +由官方 jjcontent.js 在浏览器里解开。现行脚本(jsver 不是 20220527 就自己报错): + +1. s1 = md5("...") 的十六进制。按 accessKey 码点和 + 对 32 取余左旋,前 16 / 后 16 字符对调后各取 8 字节,DES-CBC 解 cryptInfo 得 JSON{time,key}; +2. s2 = md5(key .. time .. readerid),同样左旋(仍用 accessKey 的码点和),前 16 / 后 16 直接做 + AES-128-CBC 解 content,这次不对调。 + +这套解不开再退回旧页面:偶数章 AES 穷举窗口;奇数章(书号 + 章号)用 +md5("---") 左旋 33。正文仍是 AES。 +结果是 HTML 片段,多数经 encodeURIComponent,也有直接 UTF-8:`
    ` 分段。 + +@module koplugin.book.moonsource_jjwxc.vip +--]] + +local Aes = require("crypto.aes") +local Des = require("crypto.des") +local Text = require("utils.text") +local md5 = require("ffi/sha2").md5 + +local Vip = {} + +local function field(html, name) + return html:match('name="' .. name .. '"[^>]-value="([^"]*)"') + or html:match('value="([^"]*)"[^>]-name="' .. name .. '"') +end + +--- 明文形状:encodeURIComponent 串,或含中文的合法 UTF-8 文本(有的页面不再编码;纯 ASCII 非 URL 串多半是错 iv 解出来的)。 +--- @param text string +--- @param inner boolean|nil 为真时首尾可能切在多字节字符中间 +local function looksText(text, inner) + if text:find("^[%w%%%-_.!~*'()]+$") then return true end + if not text:find("[\128-\255]") then return false end + local i, n = 1, #text + if inner then + while i <= n and text:byte(i) >= 0x80 and text:byte(i) < 0xC0 do i = i + 1 end + end + while i <= n do + local c = text:byte(i) + local len = c < 0x80 and 1 or (c >= 0xC2 and c < 0xE0) and 2 or (c >= 0xE0 and c < 0xF0) and 3 + or (c >= 0xF0 and c < 0xF5) and 4 or 0 + if len == 0 or (c < 0x20 and c ~= 9 and c ~= 10 and c ~= 13) or c == 0x7F then return false end + if i + len - 1 > n then return inner or false end + for j = i + 1, i + len - 1 do + local b = text:byte(j) + if b < 0x80 or b >= 0xC0 then return false end + end + i = i + len + end + return true +end + +--- @param html string +--- @return string|nil 解出的 HTML 片段;不是加密正文页或解不开返回 nil +--- @return string|nil 失败阶段(写日志用,不含密钥) +function Vip.content(html) + local vars = html:match('id="contentvars"(.-)') + if not vars then return nil, "no contentvars" end + local novel, chapter, reader = field(vars, "novelid"), field(vars, "chapterid"), field(vars, "readerid") + local access, info, content = field(vars, "accessKey"), field(vars, "cryptInfo"), field(vars, "content") + if not (novel and chapter and reader and access and info and content) then + return nil, ("missing fields novel=%s chapter=%s reader=%s access=%s info=%s content=%s"):format( + tostring(novel ~= nil), tostring(chapter ~= nil), tostring(reader ~= nil), tostring(access ~= nil), + tostring(info ~= nil), tostring(content ~= nil)) + end + + local function charSum(text) + local n = 0 + for i = 1, #text do n = n + text:byte(i) end + return n + end + local function finish(text) + if text:find("^[%w%%%-_.!~*'()]+$") then return Text.urlDecode(text) end + return text + end + + --- 现行脚本。cryptInfo 是 DES 解出的 JSON,不是旧页面那种再套一层 base64。 + local function decryptCurrent() + local function turn(source) + local hex = md5(source) + local off = charSum(access) % #hex + if off ~= 0 then hex = hex:sub(off + 1) .. hex:sub(1, off) end + return hex + end + local spun = turn(novel .. "." .. chapter .. "." .. reader .. "." .. access) + local meta = Des.decryptBase64(info, spun:sub(-16, -9), spun:sub(1, 8)) + local key, time = meta and meta:match('"key":"([^"]*)"'), meta and meta:match('"time":(%d+)') + if not (key and time) then return nil end + spun = turn(key .. time .. reader) + local ok, text = pcall(Aes.cbc_decrypt, Text.base64Decode(content), spun:sub(1, 16), spun:sub(-16)) + if ok and looksText(text) then return finish(text) end + end + local current = decryptCurrent() + if current then return current end + + --- 奇数章(书号 + 章号)的旧 cryptInfo 密钥。对不上时再走偶数那套搜索。 + local function decryptOdd(data, access_key) + local digest = md5(access_key .. "-" .. novel .. "-" .. chapter .. "-" .. reader) + local shift = charSum(access_key) % 33 + if shift ~= 0 then digest = digest:sub(shift + 1) .. digest:sub(1, shift) end + local ok, plain = pcall(Aes.cbc_decrypt, data, digest:sub(-16), digest:sub(1, 16)) + if ok and plain:find("^[%w+/=]+$") then return plain end + end + + --- 在摘要的 32 个偏移里找出让密文解成 `shape` 的 key 和 iv,返回去填充后的明文。 + local function decrypt(data, source, shape) + local digest = md5(source) + digest = digest .. digest + local function window(from) return digest:sub(from + 1, from + 16) end + local probe_len = math.min(#data - 16, 48) + for key_off = 0, 31 do + local key = window(key_off) + local probe = Aes.cbc_decrypt(data:sub(17, 16 + probe_len), key, data:sub(1, 16), false) + if shape(probe, true) then + for iv_off = 0, 31 do + if shape(Aes.cbc_decrypt(data:sub(1, 16), key, window(iv_off), false), true) then + local ok, plain = pcall(Aes.cbc_decrypt, data, key, window(iv_off)) + if ok then return plain end + end + end + end + end + end + + local info_raw = Text.base64Decode(info) + local novel_n, chapter_n = tonumber(novel), tonumber(chapter) + local meta = novel_n and chapter_n and (novel_n + chapter_n) % 2 == 1 + and decryptOdd(info_raw, access) or nil + if not meta then + meta = decrypt(info_raw, novel .. "." .. chapter .. "." .. reader .. "." .. access, + function(text) return text:find("^[%w+/=]+$") end) + end + if not meta then return nil, "cryptInfo undecryptable, info_len=" .. #info end + local params = Text.base64Decode(meta) + local key, time = params:match('"key":"([^"]*)"'), params:match('"time":(%d+)') + local ver = params:match('"ver":"([^"]*)"') + if not (key and time) then return nil, "meta without key/time, ver=" .. tostring(ver) end + local text = decrypt(Text.base64Decode(content), key .. time .. reader, looksText) + if not text then return nil, "content undecryptable, ver=" .. tostring(ver) .. " content_len=" .. #content end + return finish(text) +end + +return Vip diff --git a/tests/jjwxc/async_spec.lua b/tests/jjwxc/async_spec.lua new file mode 100644 index 0000000..d0722e9 --- /dev/null +++ b/tests/jjwxc/async_spec.lua @@ -0,0 +1,113 @@ +--[[-- +晋江多阶段请求取消、收藏读回、登录竞态与密码不落盘。 + +@module tests.moonsource_jjwxc.async_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +local cfg, requests, synchronous, saved = { cookie = "sid=test", token = "old" }, {}, nil, 0 +package.loaded["json"] = JSON +package.loaded["utils.settings"] = { + getSource = function() return cfg end, + saveSource = function() saved = saved + 1 end, +} +local expired = 0 +package.loaded["source.auth"] = { ok = function() end, expire = function(_id, msg) expired = expired + 1; return msg end } +local Request = { + get = function(url, opts, cb) + local request = { url = url, cb = cb, opts = opts } + request.cancel = function() request.cancelled = true end + requests[#requests + 1] = request + if synchronous then synchronous(request, #requests) end + return request + end, + header = function(res, key) return res and res.headers and res.headers[key] end, +} +package.loaded["http.request"] = Request +package.loaded["utils.charset"] = { toUtf8 = function(raw) return raw end } +package.loaded["moonsource_jjwxc.protocols.web"] = nil +local Web = require("moonsource_jjwxc.protocols.web") +local fav = '

    ' + +local called +synchronous = function(request, index) if index == 1 then request.cb(fav) end end +local handle = Web.shelfAsync(function() called = true end) +Assert.len(requests, 2) +handle.cancel() +Assert.is_true(requests[2].cancelled) +requests[2].cb('
      ') +Assert.is_nil(called) + +requests, synchronous = {}, nil +local result, reason +Web.shelfAsync(function(value, err) result, reason = value, err end) +requests[1].cb(fav) +requests[2].cb(fav) +Assert.is_nil(result) +Assert.eq(reason, "晋江收藏页无法解析", "重复页不能伪装完整书架") + +requests = {} +Web.favRemoveAsync("1", function(value, err) result, reason = value, err end) +requests[1].cb("HTTP 200 但未删除") +requests[2].cb(fav) +requests[3].cb('
        ') +Assert.is_nil(result) +Assert.eq(reason, "晋江没有确认取消收藏") +requests = {} +Web.favRemoveAsync("1", function(value, err) result, reason = value, err end) +requests[1].cb("已执行") +requests[2].cb('
          ') +Assert.is_true(result) +Assert.eq(requests[1].opts.cache_ttl, 0) + +requests = {} +Web.favAsync(cfg.cookie, function() end) +cfg.cookie = "sid=new" +requests[1].cb(nil, "HTTP 302", { code = 302, headers = { Location = "/my/login" } }) +Assert.eq(expired, 0, "旧 Cookie 迟到不能使新登录过期") +Web.favAsync(cfg.cookie, function() end) +requests[2].cb(nil, "网络故障") +Assert.eq(expired, 0, "网络错误不能使登录过期") + +requests, synchronous = {}, function(request, index) + if index == 1 then request.cb(JSON.encode({ code = 1004 })) end +end +package.loaded["moonsource_jjwxc.protocols"] = { current = function() return { + contentAsync = function(_novel, _chapter, cb) + local request = { cb = cb, cancel = function() called = "cancelled" end } + requests[#requests + 1] = request + return request + end, +} end } +package.loaded["moonsource_jjwxc.client"] = nil +called = nil +local Client = require("moonsource_jjwxc.client") +handle = Client.contentAsync("1", "2", function() called = "late" end) +handle.cancel() +Assert.eq(called, "cancelled") +requests[2].cb("测试正文") +Assert.eq(called, "cancelled") + +requests, synchronous = {}, nil +package.loaded["moonsource_jjwxc.protocols.app"] = nil +local App = require("moonsource_jjwxc.protocols.app") +App.save("test", "do-not-store", "old") +Assert.is_nil(cfg.password) +cfg.password = "legacy" +Assert.eq(App.get(), "old") +Assert.is_nil(cfg.password) +Assert.eq(saved, 2) +App.shelfAsync(function(value, err) result, reason = value, err end) +cfg.token = "new" +requests[1].cb(JSON.encode({ code = 1004 })) +Assert.matches(requests[2].url, "token=new") +requests[2].cb(JSON.encode({ addData = {} })) +Assert.len(result, 0) +Assert.eq(expired, 0) +requests = {} +App.shelfAsync(function(value, err) result, reason = value, err end) +requests[1].cb(nil, "网络故障") +Assert.eq(reason, "网络故障") +Assert.eq(expired, 0) diff --git a/tests/jjwxc/browse_spec.lua b/tests/jjwxc/browse_spec.lua new file mode 100644 index 0000000..29366f3 --- /dev/null +++ b/tests/jjwxc/browse_spec.lua @@ -0,0 +1,106 @@ +--[[-- +晋江动态分类:真实 HTML 形状、筛选、分页、旧榜单、错误与取消。 + +@module tests.moonsource_jjwxc.browse_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Mapper = require("moonsource_jjwxc.mapper") +local html = [[
          + + + + + + +
          + +
          《甲&乙》 --- +测试作者
          +
          共3页,当前第1页
          ]] +local parsed = Mapper.category(html) +Assert.eq(parsed.filters.xx[2].id, "2") +Assert.eq(parsed.filters.isfinish[1].title, "无限制") +Assert.eq(parsed.books[1].title, "甲&乙") +Assert.eq(parsed.books[1].authors, "测试作者") +Assert.eq(parsed.pages, 3) +Assert.matches(parsed.books[1].cover, "novelid=101$") +Assert.is_nil(Mapper.category("错误")) +Assert.len(Mapper.category(html:gsub(".-", "")).books, 0) + +local requests, reply, mode = {}, nil, "pending" +package.loaded["moonsource_jjwxc.client"] = { + categoryAsync = function(params, cb) + local saved = {} + for key, value in pairs(params) do saved[key] = value end + local request = { params = saved, cb = cb, cancelled = false } + request.cancel = function() request.cancelled = true end + requests[#requests + 1] = request + if #requests == 1 then cb(Mapper.category(html)) + elseif mode == "oversized" then + cb({ page = params.page, pages = 3, books = { + { source_id = "ext.jjwxc", stable_id = "201" }, + { source_id = "ext.jjwxc", stable_id = "202" }, + { source_id = "ext.jjwxc", stable_id = "203" }, + } }) + elseif mode == "sync" then + cb({ page = params.page, pages = 3, books = { { source_id = "ext.jjwxc", stable_id = tostring(params.page) } } }) + end + return request + end, + storeHomeAsync = function(cb) cb({}); return { cancel = function() end } end, +} +package.loaded["moonsource_jjwxc.browse"] = nil +local Library = require("moonsource_jjwxc.browse") +local handle = Library.run({}, function(value) reply = value end) +Assert.eq(requests[2].params.page, 2) +handle.cancel() +Assert.is_true(requests[2].cancelled) +requests[2].cb({ page = 2, pages = 3, books = {} }) +Assert.is_nil(reply) + +requests, mode = {}, "sync" +Library.run({ limit = 2 }, function(value) reply = value end) +Assert.len(reply.data, 2) +Assert.eq(reply.groups[1].title, "频道") +Assert.eq(reply.groups[1].chips[2].id, "cate:2:0:0:0:0:0:2") +Assert.eq(reply.groups[5].chips[2].id, "cate:0:0:0:0:6:0:2") +Assert.is_true(reply.more) + +requests = {} +Library.run({ limit = 1 }, function(value) reply = value end) +Assert.len(reply.data, 1) +Assert.is_true(reply.more) + +requests, mode = {}, "oversized" +Library.run({ limit = 2 }, function(value) reply = value end) +Assert.len(reply.data, 2, "聚合整页超过 limit 时只交付要求数量") +Assert.eq(reply.data[2].stable_id, "201") +Assert.is_true(reply.more) +Assert.len(requests, 2) + +requests, mode = {}, "pending" +local reason +Library.run({}, function(value, err) reply, reason = value, err end) +requests[2].cb(nil, "网络故障") +Assert.is_nil(reply) +Assert.eq(reason, "网络故障") + +requests = {} +Library.run({}, function(value, err) reply, reason = value, err end) +requests[2].cb({ page = 1, pages = 3, books = {} }) +Assert.is_nil(reply) +Assert.eq(reason, "晋江分类响应无效") + +requests = {} +Library.run({ node = "cate:99:0:0:0:0:0:2" }, function(value, err) reply, reason = value, err end) +Assert.is_nil(reply) +Assert.eq(reason, "晋江分类条件无效") + +package.loaded["moonsource_jjwxc.source"] = nil +local source = require("moonsource_jjwxc.source").new() +source:browseAsync({ node = "1:1" }, function(value, err) reply, reason = value, err end) +Assert.is_nil(reply) +Assert.eq(reason, "晋江榜单无法解析", "旧榜单节点仍走榜单") diff --git a/tests/jjwxc/jjwxc_probe_spec.lua b/tests/jjwxc/jjwxc_probe_spec.lua new file mode 100644 index 0000000..1eff398 --- /dev/null +++ b/tests/jjwxc/jjwxc_probe_spec.lua @@ -0,0 +1,139 @@ +--[[-- +晋江 VIP 章购买状态探测:句柄挂在源实例上,目录重拉前取消在飞探测,旧目录表不能盖回新目录。 + +@module tests.source.jjwxc_probe_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +Stubs.install() +Stubs.reset() + +package.preload["utils.settings"] = function() + return { getSource = function() return {} end, saveSource = function() end } +end + +-- 内存目录表:put 记每次写入的表 +local stored, puts = {}, {} +package.preload["source.toc"] = function() + return { + read = function(_source_id, stable_id) return stored[stable_id] end, + put = function(_source_id, stable_id, list) + stored[stable_id] = list + puts[#puts + 1] = list + return true + end, + } +end + +-- Web 协议:paidAsync 挂起,由用例手动回 +local pending = {} +local Web = { + id = "web", + paidAsync = function(_novel, uid, cb) + local req = { uid = uid, cb = cb, cancelled = false } + req.cancel = function() req.cancelled = true end + pending[#pending + 1] = req + return req + end, +} +package.preload["moonsource_jjwxc.protocols.web"] = function() return Web end +package.preload["moonsource_jjwxc.protocols"] = function() + return { list = { Web }, current = function() return Web end } +end + +local chapter_cbs = {} +package.preload["moonsource_jjwxc.client"] = function() + return { + chaptersAsync = function(_id, cb) + chapter_cbs[#chapter_cbs + 1] = cb + return { cancel = function() end } + end, + } +end +package.preload["moonsource_jjwxc.mapper"] = function() + return { + TOC_VERSION = 7, + toc = function(wire) return wire end, + } +end + +for _idx, name in ipairs({ "moonsource_jjwxc.source", "moonsource_jjwxc.init", "source.toc", "moonsource_jjwxc.protocols", + "moonsource_jjwxc.protocols.web", "moonsource_jjwxc.client", "moonsource_jjwxc.mapper", "utils.settings" }) do + package.loaded[name] = nil +end +local Jjwxc = require("moonsource_jjwxc.source") + +local function vipToc() + return { + { uid = "1", idx = 1, title = "一", vip = true, toc_version = 7 }, + { uid = "2", idx = 2, title = "二", vip = true, toc_version = 7 }, + } +end +local identity = { source_id = "ext.jjwxc", stable_id = "9" } + +-- 缓存命中:开探测;同一本书再问不重开;问完一次性写回 +do + stored["9"] = vipToc() + local src = Jjwxc.new() + src:loadTocAsync(identity, function() end) + Stubs.flush() + Assert.len(pending, 1) + Assert.eq(src.probe.stable_id, "9") + src:loadTocAsync(identity, function() end) + Stubs.flush() + Assert.len(pending, 1, "同一本书在飞不重开") + pending[1].cb(true) + Assert.len(pending, 2) + pending[2].cb(false) + Assert.is_nil(src.probe) + Assert.len(puts, 1) + Assert.eq(puts[1][1].paid, true) + Assert.eq(puts[1][2].paid, false) + pending, puts, stored = {}, {}, {} +end + +-- 目录重拉:在飞的探测先取消,旧目录表不能在新目录之后写回 +do + stored["9"] = vipToc() + local src = Jjwxc.new() + src:loadTocAsync(identity, function() end) + Stubs.flush() + Assert.len(pending, 1) + local old_probe_req = pending[1] + stored["9"] = nil -- 缓存失效,下一次走网络 + local got + src:loadTocAsync(identity, function(toc) got = toc end) + local fresh = vipToc() + fresh[1].title = "新一" + chapter_cbs[1](fresh) + Assert.eq(got[1].title, "新一") + Assert.is_true(old_probe_req.cancelled, "重拉前取消旧探测") + old_probe_req.cb(true) -- 迟到的回包 + Assert.eq(stored["9"][1].title, "新一", "旧表不能盖回新目录") + Assert.is_nil(stored["9"][1].paid) + -- 新目录自己的探测在跑 + Assert.eq(src.probe.stable_id, "9") + Assert.len(pending, 2) + pending, puts, stored, chapter_cbs = {}, {}, {}, {} +end + +-- 换书:旧书探测取消;close 取消在飞探测 +do + stored["9"] = vipToc() + stored["10"] = vipToc() + local src = Jjwxc.new() + src:loadTocAsync(identity, function() end) + Stubs.flush() + src:loadTocAsync({ source_id = "ext.jjwxc", stable_id = "10" }, function() end) + Stubs.flush() + Assert.is_true(pending[1].cancelled) + Assert.eq(src.probe.stable_id, "10") + src:close() + Assert.is_true(pending[2].cancelled) + Assert.is_nil(src.probe) + pending[2].cb(true) + Assert.len(puts, 0, "取消后不落库") + pending, puts, stored = {}, {}, {} +end diff --git a/tests/jjwxc/jjwxc_spec.lua b/tests/jjwxc/jjwxc_spec.lua new file mode 100644 index 0000000..5af549b --- /dev/null +++ b/tests/jjwxc/jjwxc_spec.lua @@ -0,0 +1,309 @@ +--[[-- +晋江收藏页 / 目录 / 网页正文映射与 Cookie 解析离线用例。 + +@module tests.source.jjwxc_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") + +local source_cfg = {} +package.preload["utils.settings"] = function() + return { getSource = function() return source_cfg end, saveSource = function() end } +end +package.loaded["moonsource_jjwxc.mapper"] = nil +package.loaded["moonsource_jjwxc.setting"] = nil +local Mapper = require("moonsource_jjwxc.mapper") +local Setting = require("moonsource_jjwxc.setting") + +do + local html = '' + local rows = Mapper.favRows(html) + Assert.len(rows, 2) + Assert.eq(rows[1].id, "123") + Assert.eq(rows[1].author, "某作者") + Assert.is_nil(Mapper.favRows("请登录")) +end + +do + local html = ' 【言情排行】 ' + .. '【纯爱排行】' + local sections = Mapper.rankSections(html) + Assert.len(sections, 2) + Assert.eq(sections[1].title, "言情排行") + Assert.eq(sections[1].books[1].stable_id, "1") + Assert.eq(sections[1].books[1].title, "甲&乙") + Assert.len(sections[2].books, 2) + Assert.len(Mapper.rankSections(""), 0) + local ranks = Mapper.storeRanks({ + { type = "img" }, + { type = "rankings", data = { + { more = { rankName = "月榜", channellist = { + { channel = "言情", channelid = "natural_592" }, + { channel = "纯爱", channelid = "natural_604" }, + { channel = "坏", channelid = "a/b" }, + } } }, + { more = {} }, + } }, + }) + Assert.len(ranks, 1) + Assert.eq(ranks[1].title, "月榜") + Assert.len(ranks[1].channels, 2) + Assert.eq(ranks[1].channels[2].id, "natural_604") + local books = Mapper.rankBooks({ data = { data = { + { novelId = "1", novelName = "甲", authorName = "乙", novelIntroShort = "

          简介

          " }, + { novelname = "无号" }, + } } }) + Assert.len(books, 1) + Assert.eq(books[1].title, "甲") + Assert.eq(books[1].intro, "简介") + Assert.eq(books[1].authors, "乙") +end + +do + local books = Mapper.shelfList({ + { id = "1", title = "短…", info = { novelId = 1, novelName = "全名", authorName = "甲", novelSize = "271,300", novelCover = "" } }, + { id = "2", title = "截断", local_book = { stable_id = "2", title = "本地全名" } }, + { id = "3", title = "兜底", author = "乙" }, + }) + Assert.eq(books[1].title, "全名") + Assert.eq(books[1].meta.words, 271300) + Assert.is_nil(books[1].cover) + Assert.eq(books[2].title, "本地全名") + Assert.eq(books[3].title, "兜底") +end + +do + local toc = Mapper.toc({ chapterlist = { + { chapterid = "0", chaptertype = "1", chaptername = "卷一", islock = "0" }, + { chapterid = "1", chaptertype = "0", chaptername = "第一章", islock = "0", chaptersize = "100" }, + { chapterid = "2", chaptertype = "0", chaptername = "锁定", islock = "1" }, + { chapterid = "3", chaptertype = "0", chaptername = "第三章", islock = "0", isvip = 2 }, + } }) + Assert.len(toc, 2) + Assert.eq(toc[2].uid, "3") + Assert.eq(toc[2].idx, 2) + Assert.is_true(toc[2].vip) + Assert.is_nil(toc[1].vip) + Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION) +end + +do + Assert.eq(Mapper.webContent('
          • 甲
            乙&丙
          '), "甲\n乙&丙") + Assert.is_nil(Mapper.webContent("

          提示

          ")) + Assert.eq(Mapper.webContent('
          • 甲乙
          '), "甲乙") + local vip = '
          • vip内容加载中...
            ' + .. '' + .. '' + .. '' + .. '
          ' + Assert.eq(Mapper.webContent(vip), "  甲&乙\n\n  丙\238\129\132丁") + Assert.is_nil(Mapper.webContent(vip:gsub("PxowDj", "xxxxxx"))) +end + +do + -- key / iv 取摘要里任意偏移的窗口,正文也可能是未编码的 UTF-8。 + local Aes, md5, Text = require("crypto.aes"), require("ffi/sha2").md5, require("utils.text") + local function enc(plain, source, key_off, iv_off) + local d = md5(source) + d = d .. d + return Text.base64Encode(Aes.cbc_encrypt(plain, d:sub(key_off + 1, key_off + 16), d:sub(iv_off + 1, iv_off + 16))) + end + local meta = Text.base64Encode('{"time":1792544104,"key":"HqgOwYk","ver":"20250926"}') + local body = "  沈玄宁讪讪一笑,道:“我是路过的。”

            他转身走了,留下一句话:好自为之。" + local page = '
          ' + .. '' + .. '' + .. '
          ' + Assert.eq(require("moonsource_jjwxc.vip").content(page), body) + -- 书号 + 章号为奇数时官方脚本换密钥(issue #78)。密文由 Node crypto 按脚本规则生成, + -- 不跟 Lua 实现共用派生,派生错了这里对不上。奇数章若仍是旧的点号密钥,也要能解开。 + local odd = '
          ' + .. '' + .. '' + .. '
          ' + Assert.eq(require("moonsource_jjwxc.vip").content(odd), body) + local odd_old = '
          ' + .. '' + .. '' + .. '
          ' + Assert.eq(require("moonsource_jjwxc.vip").content(odd_old), body) + -- 现行 jjcontent.js:cryptInfo 是 DES,正文是固定窗口 AES。密文在这里用 Des/Aes 现算,不走 Vip 内部。 + local Des = require("crypto.des") + local function turn(source, access) + local hex = md5(source) + local sum = 0 + for i = 1, #access do sum = sum + access:byte(i) end + local off = sum % #hex + if off ~= 0 then hex = hex:sub(off + 1) .. hex:sub(1, off) end + return hex + end + local access, novel, chapter, reader = "Ab12Cd", "8718162", "19", "7" + local spun = turn(novel .. "." .. chapter .. "." .. reader .. "." .. access, access) + local info = Des.encryptBase64('{"key":"K1","time":1700000000}', spun:sub(-16, -9), spun:sub(1, 8)) + spun = turn("K117000000007", access) + local content = Text.base64Encode(Aes.cbc_encrypt(body, spun:sub(1, 16), spun:sub(-16))) + local current = '
          ' + .. '' + .. '' + .. '
          ' + Assert.eq(require("moonsource_jjwxc.vip").content(current), body) + -- 段缝:正文切成 c_ span,缝里的字挂在同页 ]] + .. [[
          • 甲乙丙丁
          ]]), + "甲缝1乙丙缝2丁") +end + +do + package.loaded["moonsource_jjwxc.font"] = nil + local Font = require("moonsource_jjwxc.font") + local fh = assert(io.open("tests/fixtures/jjwxcfont_9eo8b.ttf", "rb")) + local ttf = fh:read("*a") + fh:close() + local map = Font.mapping(ttf) + local n = 0 + for _code in pairs(map) do n = n + 1 end + Assert.eq(n, 200) + Assert.eq(map[0xE044], "他") + Assert.eq(map[0xE9BE], "已") + -- 私有区字 → 真字;字后的零宽占位去掉;未命中的私有区字原样保留。 + Assert.eq(Font.decode("\u{E044}\u{200B}说\u{E9BE}\u{FEFF}\u{F8F0}", map), "他说已\u{F8F0}") + Assert.is_nil(Font.mapping("not a font")) +end + +do + Assert.eq(Setting.parseCookie("b=2; a=1;bad name=3; c="), "a=1; b=2") + Assert.eq(Setting.fromPayload({ cookies = { + { domain = ".jjwxc.com", name = "sid", value = "v" }, + { domain = "m.jjwxc.com", name = "JJSESS", value = "w" }, + { domain = "evil.com", name = "x", value = "y" }, + } }), "JJSESS=w; sid=v") +end + +do + local html = require("utils.text").chapterHtml("第一章", "  甲\n\n  乙〇\n") + Assert.eq(html, "

          第一章

          \n

          甲

          \n

          乙〇

          ") +end + +do + local book = Mapper.book({ novelId = 1, novelName = "x", novelCover = "https://i9-static.jjwxc.net/novelimage.php?novelid=1&coverid=2&ver=abc" }) + Assert.eq(book.cover, "https://i9-static.jjwxc.net/novelimage.php?novelid=1&coverid=2") +end + +do + local books = Mapper.search({ items = { + { novelid = 5, novelname = "甲", authorname = "乙", novelintroshort = "简介" }, + } }) + Assert.len(books, 1) + Assert.eq(books[1].stable_id, "5") + Assert.eq(books[1].title, "甲") + Assert.eq(books[1].authors, "乙") +end + +-- 段评:统计只留有评论的真实段(-2 是章末总评),评论页的游标是累计偏移。 +do + package.loaded["moonsource_jjwxc.reviews"] = nil + local Reviews = require("moonsource_jjwxc.reviews") + local hot = Reviews.hotspots({ + { paragraph_id = "-2", comment_total = "130" }, + { paragraph_id = "3", comment_total = "7" }, + { paragraph_id = "1", comment_total = "24148" }, + { paragraph_id = "2", comment_total = "0" }, + }) + Assert.len(hot, 3) + Assert.eq(hot[1].range, "-2") + Assert.eq(hot[2].range, "1") + Assert.eq(hot[3].range, "3") + Assert.eq(hot[3].total, 7) + + local page = Reviews.page({ commentTotal = "45", commentList = { + { commentId = "9", commentAuthor = "甲", commentBody = "好&看
          真的", agreenum = "6", comment_date_time = "1792324141" }, + } }, 20) + Assert.eq(page.total, 45) + Assert.eq(page.max_idx, 21) + Assert.is_true(page.more) + Assert.eq(page.items[1].content, "好&看\n真的") + Assert.eq(page.items[1].likes, 6) + Assert.eq(page.items[1].time, 1792324141) + Assert.is_false(Reviews.page({ commentTotal = "1", commentList = { { commentId = "1" } } }, 0).more) + Assert.is_nil((Reviews.page({}, 0))) +end + +-- App 登录用的 DES-CBC:向量来自 openssl(des-cbc,key KW8Dvm2N,iv 1ae2c94b)。 +do + local Des = require("crypto.des") + local cipher = Des.encrypt("hello-世界 password 123", "KW8Dvm2N", "1ae2c94b") + local hex = cipher:gsub(".", function(c) return string.format("%02x", c:byte()) end) + Assert.eq(hex, "6c85a3005530ad3b2e41bb2f25eb77bb5fc29c01b2df52790e15fb89ec87c576") + Assert.eq(Des.decrypt(cipher, "KW8Dvm2N", "1ae2c94b"), "hello-世界 password 123") + Assert.is_nil(Des.decrypt(cipher:sub(1, 15), "KW8Dvm2N", "1ae2c94b")) + Assert.is_nil(Des.decrypt(cipher, "WRONGKEY", "1ae2c94b")) + + local rows = Mapper.tokenFavRows({ { novelId = 7, novelName = "甲", authorName = "乙" }, { novelname = "无号" } }) + Assert.len(rows, 1) + Assert.eq(rows[1].id, "7") + Assert.eq(rows[1].author, "乙") +end + +do + local Des = require("crypto.des") + local md5, Hex = require("ffi/sha2").md5, require("crypto.hex") + package.loaded["moonsource_jjwxc.protocols.app"] = nil + local Client = require("moonsource_jjwxc.protocols.app") + local keystring = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" + local plain = '{"content":"正文","code":"1004"}' + -- accesskey 字节和 = 97+98+99 = 294,末字符 c(99) 为奇:盐在尾;偏移 294%62=46,长度 floor(294/65)=4 + local salt, part = "0123456789ab", keystring:sub(47, 50) + local cipher = Hex.to_hex(Des.encrypt(plain, md5(part .. salt):sub(1, 8), md5(salt):sub(1, 8))) + Assert.eq(Client.decryptBody(cipher .. salt, "abc", keystring), plain) + -- 末字符为偶:盐在头 + local even_sum = 97 + 98 + 100 + local start2, count2 = even_sum % #keystring, math.floor(even_sum / 65) + local part2 = keystring:sub(start2 + 1, start2 + count2) + local cipher2 = Hex.to_hex(Des.encrypt(plain, md5(part2 .. salt):sub(1, 8), md5(salt):sub(1, 8))) + Assert.eq(Client.decryptBody(salt .. cipher2, "abd", keystring), plain) + local chapter = "甲
          乙" + local chapter_cipher = Des.encryptBase64(chapter, "KW8Dvm2N", "1ae2c94b") + Assert.eq(Client.chapterText(chapter_cipher, nil), chapter) + Assert.eq(Client.chapterText(chapter_cipher, "jj"), chapter) + Assert.eq(Client.chapterText(chapter, nil), chapter) + Assert.is_nil(Client.chapterText("@@@@", "jj")) +end + +do + local Settings = require("utils.settings") + local Protocols = require("moonsource_jjwxc.protocols") + local cfg = Settings.getSource("ext.jjwxc") + cfg.cookie, cfg.token, cfg.protocol = nil, nil, nil + Assert.is_nil(Protocols.current()) + cfg.token = "t" + Assert.eq(Protocols.current().id, "app") + cfg.cookie = "c=1" + Assert.eq(Protocols.current().id, "web") + Protocols.select("app") + Assert.eq(Protocols.current().id, "app") + cfg.protocol = "web" + cfg.cookie = nil + Assert.eq(Protocols.current().id, "app") + cfg.token, cfg.protocol = nil, nil +end + +-- 段评接口:VIP 章节要登录态,web 带 Cookie、app 带 token 查询参数,都没有就匿名。 +do + local Settings = require("utils.settings") + local Protocols = require("moonsource_jjwxc.protocols") + local cfg = Settings.getSource("ext.jjwxc") + cfg.cookie, cfg.token, cfg.protocol = nil, nil, nil + Assert.eq(select(1, Protocols.list[1].commentAuth()), "") + Assert.is_nil(select(2, Protocols.list[1].commentAuth()).Cookie) + cfg.cookie, cfg.token = "c=1", "t k" + local query, headers = Protocols.list[1].commentAuth() + Assert.eq(query, "") + Assert.eq(headers.Cookie, "c=1") + query, headers = Protocols.list[2].commentAuth() + Assert.eq(query, "&token=t%20k") + Assert.is_nil(headers.Cookie) + cfg.cookie, cfg.token = nil, nil +end diff --git a/tests/jjwxc/reviews_spec.lua b/tests/jjwxc/reviews_spec.lua new file mode 100644 index 0000000..67e07b8 --- /dev/null +++ b/tests/jjwxc/reviews_spec.lua @@ -0,0 +1,102 @@ +--[[-- +晋江章评与段评分流、分页、坏响应、章节归属及取消。 + +@module tests.moonsource_jjwxc.reviews_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +local pending, request, called +package.loaded["json"] = JSON +package.loaded["moonsource_jjwxc.protocols"] = { current = function() end } +package.loaded["http.request"] = { get = function(url, _opts, cb) + pending = cb + request = { url = url, cancel = function() request.cancelled = true end } + return request +end } +package.loaded["moonsource_jjwxc.reviews"] = nil +local Reviews = require("moonsource_jjwxc.reviews") +Assert.eq(Reviews.item({ commentBody = "第一行<br>第二行<BR />第三行" }).content, + "第一行\n第二行\n第三行", "转义换行标签不能直接显示") +local formatted = Reviews.item({ commentBody = "

          第一行

          第二行 [紫糖]

          " }) +Assert.eq(formatted.content, "第一行\n第二行 [紫糖]") +Assert.is_true(formatted.inline_images["[紫糖]"] ~= nil, "清理标签后保留表情") +local emoji_body = " [紫糖][狗头][紫糖][红心]
          😀[未知表情] " +local emoji_item = Reviews.item({ commentId = "emoji", commentBody = emoji_body }) +Assert.eq(emoji_item.content, "[紫糖][狗头][紫糖][红心]\n😀[未知表情]") +Assert.matches(emoji_item.inline_images["[紫糖]"].url, "66baeed24ae82_531%.png$") +Assert.eq(emoji_item.inline_images["[狗头]"].url, "https://i9-static.jjwxc.net/tmp/emoji/dog.png") +Assert.eq(emoji_item.inline_images["[红心]"].headers.Referer, "https://www.jjwxc.net/") +Assert.is_nil(emoji_item.inline_images["[未知表情]"]) +Assert.len(emoji_item.images, 0, "表情不能变成卡片配图") +Assert.is_nil(Reviews.item({ commentBody = "普通评论 😀[未知表情]" }).inline_images) +Assert.len(Reviews.hotspots({}), 0) +Assert.is_nil(Reviews.hotspots({ message = "错误对象" })) +Assert.is_nil(Reviews.hotspots({ { paragraph_id = 1 } })) +Reviews.hotspotsAsync("9", "23", function(value, err) called = { value, err } end) +pending(JSON.encode({ code = 200, data = { { paragraph_id = 1, comment_total = "bad" } } })) +Assert.is_nil(called[1]) +Assert.eq(called[2], "响应无效") +Reviews.pageAsync("9", "23", -2, 20, function(value, err) called = { value, err } end) +Assert.matches(request.url, "novelId=9&chapterId=23¶graph_id=%-2&offset=20") +pending(JSON.encode({ code = 200, data = { commentTotal = "21", commentList = { { commentId = "7", commentBody = "测试评论" } } } })) +Assert.eq(called[1].max_idx, 21) +Assert.is_false(called[1].more) +Reviews.pageAsync("9", "23", 1, 0, function(value, err) called = { value, err } end) +pending(JSON.encode({ code = 200, data = { commentTotal = 0, commentList = {} } })) +Assert.len(called[1].items, 0) +Assert.is_nil(Reviews.page({ commentTotal = 2, commentList = { "bad" } }, 0)) +Assert.is_nil(Reviews.page({ commentList = {} }, 0)) +Assert.is_nil(Reviews.page({ commentTotal = 0, commentList = { error = "bad" } }, 0)) +Reviews.pageAsync("9", "23", 1, 0, function(value, err) called = { value, err } end) +pending(nil, "网络故障") +Assert.eq(called[2], "网络故障") + +local hotspots = { { range = "-2", total = 37 }, { range = "6", total = 205 } } +package.loaded["book.review_cache"] = { + hotspotsAsync = function(_identity, fetch, cb) return fetch(cb) end, + pageAsync = function(_identity, _range, _offset, fetch, cb) return fetch(cb) end, +} +package.loaded["moonsource_jjwxc.reviews"] = { + inlineImages = Reviews.inlineImages, + hotspotsAsync = function(_novel, uid, cb) + Assert.eq(uid, "23") + cb(hotspots) + return { cancel = function() end } + end, + pageAsync = function(_novel, uid, range, offset, cb) + Assert.eq(uid, "23"); Assert.eq(range, -2); Assert.eq(offset, 0) + pending = cb + request = { cancel = function() request.cancelled = true end } + return request + end, +} +package.loaded["moonsource_jjwxc.source"] = nil +local source = require("moonsource_jjwxc.source").new() +source.loadTocAsync = function(_self, _identity, cb) + cb({ { uid = "23" } }) + return { cancel = function() error("不应取消已完成目录请求") end } +end +local identity = { source_id = "ext.jjwxc", stable_id = "9", chapter_idx = 1 } +source:paragraphHotspotsAsync(identity, function(value) called = value end) +Assert.len(called, 1) +Assert.eq(called[1].range, "6") +source:chapterReviewHotspotsAsync(identity, function(value) called = value end) +Assert.len(called, 1) +Assert.eq(called[1].range, "-2") +Assert.eq(called[1].anchor, "moon-chapter-reviews") +called = nil +local handle = source:paragraphReviewPageAsync(identity, "-2", 0, function() called = true end) +handle.cancel() +Assert.is_true(request.cancelled) +pending({}) +Assert.is_nil(called, "换章取消后不得展示旧评论") + +package.loaded["book.review_cache"].pageAsync = function(_identity, _range, _offset, _fetch, cb) + cb({ items = { { content = "旧缓存
          [紫糖]" } } }) + return { cancel = function() end } +end +source:paragraphReviewPageAsync(identity, "-2", 0, function(value) called = value end) +Assert.matches(called.items[1].inline_images["[紫糖]"].url, "66baeed24ae82_531%.png$") +Assert.eq(called.items[1].content, "旧缓存\n[紫糖]", "修正旧缓存中的标签,不丢弃离线评论") diff --git a/tests/jjwxc/setting_spec.lua b/tests/jjwxc/setting_spec.lua new file mode 100644 index 0000000..0e62616 --- /dev/null +++ b/tests/jjwxc/setting_spec.lua @@ -0,0 +1,83 @@ +--[[-- +晋江登录:不静默覆盖旧账号、取消迟到回包、离线立即失败。 + +@module tests.moonsource_jjwxc.setting_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local beginLogin = require("source.auth").beginLogin +local Themed = require("support.theme_stubs") +Themed.install() +local cfg, online, pending, cancelled, stored = {}, true, nil, false, 0 +local cleared = 0 +package.loaded["source.logout"] = { clear = function(_id, clear) + clear(); cleared = cleared + 1; return true +end } +local cookie_pending, cookie_cancelled, cookie_async +package.loaded["utils.settings"] = { getSource = function() return cfg end, saveSource = function() end } +package.loaded["source.registry"] = { reload = function() end } +package.loaded["source.auth"] = { beginLogin = beginLogin, ok = function() end } +package.loaded["ui/network/manager"] = { isConnected = function() return online end } +local App = { + loginAsync = function(_account, password, _verify, cb) + Assert.eq(password, " password ", "密码按原值提交") + pending = cb + return { cancel = function() cancelled = true end } + end, + save = function(_account, _password, token) stored = stored + 1; cfg.token = token end, +} +package.loaded["moonsource_jjwxc.protocols.app"] = App +package.loaded["moonsource_jjwxc.protocols"] = { current = function() end, select = function() end } +package.loaded["moonsource_jjwxc.protocols.web"] = { + favAsync = function(_cookie, cb) + if cookie_async then cookie_pending = cb else cb({}) end + return { cancel = function() cookie_cancelled = true end } + end, +} +package.loaded["moonsource_jjwxc.setting"] = nil +local Setting = require("moonsource_jjwxc.setting") + +Setting.login() +Themed.last("input").callback("test", " password ") +Themed.last("progress_dialog").on_cancel() +Assert.is_true(cancelled) +pending("late") +Assert.eq(stored, 0) + +Setting.login() +Themed.last("input").callback("test", " password ") +cfg.token = "newer" +pending("older") +Assert.eq(stored, 0) +Assert.eq(cfg.token, "newer") +Assert.eq(Themed.last("toast").text, "账号已变化,请重新登录") + +local result, reason +cfg.cookie = "sid=old" +Setting.browser.apply({ cookies = { { domain = ".jjwxc.com", name = "sid", value = "new" } } }, + function(ok, err) result, reason = ok, err end) +Assert.is_true(result) +Assert.is_nil(reason) +Assert.eq(cfg.cookie, "sid=new") +Assert.eq(cleared, 1) +Assert.is_nil(Themed.last("confirm")) +cfg.token = nil +Setting.browser.apply({ cookies = { { domain = ".jjwxc.com", name = "sid", value = "new" } } }, + function(ok) result = ok end) +Assert.is_true(result, "同一 Cookie 重新校验不清库") + +cfg, cookie_async, result = {}, true, nil +local cookie_job = Setting.browser.apply({ cookies = { { domain = ".jjwxc.com", name = "sid", value = "new" } } }, + function(ok) result = ok end) +cookie_job.cancel() +Assert.is_true(cookie_cancelled, "关闭登录必须取消校验请求") +cookie_pending({}) +Assert.is_nil(cfg.cookie) +Assert.is_nil(result) + +cfg, online, pending = {}, false, nil +Setting.login() +Themed.last("input").callback("test", " password ") +Assert.is_nil(pending) +Assert.eq(Themed.last("toast").text, "未联网")