Files
moonsource-weread/moonsource-weread.koplugin/moonsource_weread/package.lua
T
GarfieldandCopilot ed44254f1c ✨ 初始提交:月读第三方书源插件集合
每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。

Co-authored-by: Copilot <[email protected]>
2026-11-16 12:08:03 +08:00

330 lines
13 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
--[[--
微信读书 App 章节下载包(GET /book/chapterdownload)解包。
响应头 encryptKey 是 base64 的 AES-128-CBC(PKCS7) 密文,明文即 zip 的 ZipCrypto 口令。
解密用的 key/iv 来自 vid:十进制字符串循环铺满 32 字节,逐字节过 REMAP 表,前 16 字节为 key、后 16 字节为 iv
(移植自官方 App libencrypt.so 的 nativeDecryptHeaderKey,抓包样本验证)。
@module koplugin.book.moonsource_weread.package
--]]
local bit = require("bit")
local ffi = require("ffi")
local JSON = require("json")
local Aes = require("crypto.aes")
local Inflate = require("utils.inflate")
local Text = require("utils.text")
local Package = {}
local REMAP = Aes.from_hex(
"34ca55401db693c63130293532a7b811c2b516fa8bb124a4109004e908f83b8a"
.. "9c8c44f9bc5c69e2a1dad2d37589f71e2d5056d77253bf22fb200f012e45876e"
.. "6648f2e0cdfe67a943f49451cea54aee13268eccaa33145d0e39bbcf912b814d"
.. "ea99ec1a2c85c5d936744b18e1f13d9d419fb4170dd64cbedcaf972877f062ff"
.. "71c1c8278f6c68a89be6591c1b1209984e3f063700ba1f0a192fc9d5d057496f"
.. "fd25e4610c42cb96645fdbad60238d9a6dc3c45e3eb9926abd5b077f7695ed4f"
.. "ab847a80e778c7e5eb73836bfc38467d4765b352633a05d1efa3a6de9e3c02ae"
.. "b27ba0f6f32ac0ac86035a540bf582d47ee3dfb0d8dd21e87c88a2795870b715")
--- 由 vid 与响应头 encryptKey 算出 zip 口令。
---@param vid string
---@param encrypt_key string base64
---@return string|nil password
---@return string|nil err
function Package.password(vid, encrypt_key)
if not vid:match("^%d+$") then return nil, "bad vid" end
local raw = vid:rep(math.ceil(32 / #vid)):sub(1, 32)
local kiv = raw:gsub(".", function(c) return string.char(REMAP:byte(c:byte() + 1)) end)
local ok, plain = pcall(Aes.cbc_decrypt, Text.base64Decode(encrypt_key), kiv:sub(1, 16), kiv:sub(17, 32))
if not ok then return nil, "encryptKey decrypt failed" end
return plain
end
local CRC = {}
for i = 0, 255 do
local c = i
for _bit = 1, 8 do
c = bit.band(c, 1) == 1 and bit.bxor(0xEDB88320, bit.rshift(c, 1)) or bit.rshift(c, 1)
end
CRC[i] = c
end
local function crcUpdate(crc, byte)
return bit.bxor(CRC[bit.band(bit.bxor(crc, byte), 0xff)], bit.rshift(crc, 8))
end
--- 32 位乘法取低 32 位(LuaJIT 的 double 装不下 32×27 位乘积)。
local function mul32(a, b)
local lo, hi = b % 65536, math.floor(b / 65536)
return (a * lo + (a * hi % 65536) * 65536) % 4294967296
end
--- 传统 ZipCrypto 解密:data 含开头 12 字节随机头。
---@param data string
---@param password string
---@return string
local function zipDecrypt(data, password)
local k0, k1, k2 = 0x12345678, 0x23456789, 0x34567890
local function update(c)
k0 = crcUpdate(k0, c) % 4294967296
k1 = (mul32((k1 + bit.band(k0, 0xff)) % 4294967296, 134775813) + 1) % 4294967296
k2 = crcUpdate(k2, bit.rshift(k1, 24)) % 4294967296
end
for i = 1, #password do update(password:byte(i)) end
local size = math.max(0, #data - 12)
local out = ffi.new("uint8_t[?]", size)
for i = 1, #data do
local t = bit.bor(k2, 2) % 65536
local c = bit.bxor(data:byte(i), bit.band(bit.rshift(t * bit.bxor(t, 1), 8), 0xff))
update(c)
if i > 12 then out[i - 13] = c end
end
return ffi.string(out, size)
end
local function u16(s, p) local a, b = s:byte(p, p + 1) return a + b * 256 end
local function u32(s, p) local a, b, c, d = s:byte(p, p + 3) return a + b * 256 + c * 65536 + d * 16777216 end
--- 解压峰值增量(字节):正文分块与拼接各一份;密文切片、解密缓冲与解密字符串各一份最大压缩块。
--- `data` 已在内存里,MemAvailable 已包含它;预检只问额外还要多少。
--- 另留 64KB 给 inflate 输出缓冲;解析失败时沿用 3× 包长估计。
---@param data string
---@return number
function Package.unzipNeed(data)
data = data or ""
local fallback = 3 * #data
local eocd
for p = #data - 21, math.max(1, #data - 65557), -1 do
if u32(data, p) == 0x06054b50 then eocd = p break end
end
if not eocd then return fallback end
local sum_un, max_c, p = 0, 0, u32(data, eocd + 16) + 1
for _entry = 1, u16(data, eocd + 10) do
if u32(data, p) ~= 0x02014b50 then return fallback end
local csize, usize = u32(data, p + 20), u32(data, p + 24)
local nlen, elen, clen = u16(data, p + 28), u16(data, p + 30), u16(data, p + 32)
sum_un = sum_un + usize
if csize > max_c then max_c = csize end
p = p + 46 + nlen + elen + clen
end
return 2 * sum_un + 3 * max_c + 65536
end
--- 解开整个 zip(走中央目录,数据描述符模式也能用)。
---@param data string
---@param password string|nil
---@return table<string, string>|nil files 文件名 → 内容
---@return string|nil err
function Package.unzip(data, password)
local eocd
for p = #data - 21, math.max(1, #data - 65557), -1 do
if u32(data, p) == 0x06054b50 then eocd = p break end
end
if not eocd then return nil, "zip: no end record" end
local files, p = {}, u32(data, eocd + 16) + 1
for _entry = 1, u16(data, eocd + 10) do
if u32(data, p) ~= 0x02014b50 then return nil, "zip: bad central directory" end
local flags, method, csize = u16(data, p + 8), u16(data, p + 10), u32(data, p + 20)
local nlen, elen, clen, lho = u16(data, p + 28), u16(data, p + 30), u16(data, p + 32), u32(data, p + 42) + 1
local name = data:sub(p + 46, p + 45 + nlen)
p = p + 46 + nlen + elen + clen
if u32(data, lho) ~= 0x04034b50 then return nil, "zip: bad local header" end
local start = lho + 30 + u16(data, lho + 26) + u16(data, lho + 28)
local body = data:sub(start, start + csize - 1)
if bit.band(flags, 1) == 1 then
if not password then return nil, "zip: password required" end
body = zipDecrypt(body, password)
end
if method == 8 then
local out, err = Inflate.raw(body)
if not out then return nil, "zip: " .. name .. " " .. tostring(err) end
body = out
elseif method ~= 0 then
return nil, "zip: unsupported method " .. method
end
files[name] = body
end
return files
end
--- 整书 / 章包里的样式表。常见 ``Styles/stylesheets.css``,也有书只用 ``stylesheet.css``。
---@param files table<string, string> Package.unzip 的结果
---@return string|nil css
function Package.pickStyle(files)
local css = files["Styles/stylesheets.css"] or files["Styles/stylesheet.css"]
if css then return css end
local names = {}
for name in pairs(files) do
if name:match("^Styles/[^/]+%.css$") then
names[#names + 1] = name
end
end
table.sort(names)
return names[1] and files[names[1]] or nil
end
--- 官方 /book/chapterdownload 的 chapters 参数。
--- 连续 uid 写成 a-b;缓存/批量时带上 0(整书样式)。第一批若从 1 起连续,合并成 0-n(如 0-5);
--- 其后是 0,a-b(如 0,6-10)。非数字 uid 退回 0,u1,u2,…。
---@param uids (string|number)[] 本章批次的 chapterUid(不含 0)
---@return string
function Package.formatChaptersParam(uids)
uids = uids or {}
if #uids == 0 then return "0" end
local nums = {}
for i, u in ipairs(uids) do
local n = tonumber(u)
if not n then
local parts = { "0" }
for _idx, x in ipairs(uids) do parts[#parts + 1] = tostring(x) end
return table.concat(parts, ",")
end
nums[i] = n
end
local contiguous = true
for i = 2, #nums do
if nums[i] ~= nums[i - 1] + 1 then contiguous = false; break end
end
if contiguous then
local a, b = nums[1], nums[#nums]
if a == 1 then return "0-" .. tostring(b) end
if a == b then return "0," .. tostring(a) end
return "0," .. tostring(a) .. "-" .. tostring(b)
end
local parts = { "0" }
for _idx, n in ipairs(nums) do parts[#parts + 1] = tostring(n) end
return table.concat(parts, ",")
end
--- 从已解包的 zip 按 uid 列表抽出各章正文(及可选样式)。
---@param files table<string, string>
---@param book_id string
---@param uids (string|number)[]
---@param book_type '"epub"'|'"txt"'
---@return table<string, { text: string|nil, err: string|nil, format: string }>
---@return string|nil style
function Package.extractChapters(files, book_id, uids, book_type)
local out = {}
for _idx, uid in ipairs(uids) do
local key = tostring(uid)
if book_type == "txt" then
local text = Package.chapterZipText(files, book_id, uid)
if text then
out[key] = { text = text, format = "txt" }
else
out[key] = { err = "zip: chapter " .. key .. " not in package", format = "txt" }
end
else
local html, err = Package.chapterHtml(files, uid)
if html then
out[key] = { text = html, format = "html" }
else
out[key] = { err = err or ("package: chapter " .. key .. " not in package"), format = "html" }
end
end
end
return out, Package.pickStyle(files)
end
--- 取某章的 xhtml:章节由主文件(标题 / 插图)加若干 _000N 续篇组成,续篇 body 依次并入主文件 body 末尾。
---@param files table<string, string> Package.unzip 的结果
---@param uid string|number
---@return string|nil xhtml
---@return string|nil err
function Package.chapterHtml(files, uid)
local info = files["info.txt"] and JSON.decode(files["info.txt"])
for _idx, chapter in ipairs(info and info.chapters or {}) do
if tostring(chapter.chapterUid) == tostring(uid) then
if type(chapter.files) ~= "table" or type(chapter.files[1]) ~= "string" then
return nil, "package: no HTML files for chapter " .. tostring(uid)
end
local html = files[chapter.files[1]]
if not html then return nil, "package: missing " .. tostring(chapter.files[1]) end
for i = 2, #chapter.files do
local part = files[chapter.files[i]]
local inner = part and part:match("<body[^>]*>(.*)</body>")
if not inner then return nil, "package: bad part " .. tostring(chapter.files[i]) end
local last = html:match(".*()</body>")
if not last then return nil, "package: no body" end
html = html:sub(1, last - 1) .. inner .. html:sub(last)
end
return html
end
end
return nil, "package: chapter " .. tostring(uid) .. " not in package"
end
--- 解开 ustar。只取普通文件。
---@param data string
---@return { name: string, data: string }[]|nil
---@return string|nil err
local function untar(data)
if data:sub(258, 262) ~= "ustar" then return nil, "tar: not ustar" end
local entries, offset = {}, 1
while offset + 511 <= #data do
local header = data:sub(offset, offset + 511)
if header:match("^%z+$") then break end
local name = (header:sub(1, 100):gsub("%z.*$", ""))
local size = tonumber((header:sub(125, 136):gsub("%z.*$", ""):gsub("%s", "")), 8) or 0
local typeflag = header:sub(157, 157)
local body_start = offset + 512
if name ~= "" and (typeflag == "0" or typeflag == "" or typeflag == "\0") and size > 0 then
entries[#entries + 1] = { name = name, data = data:sub(body_start, body_start + size - 1) }
end
offset = body_start + math.ceil(size / 512) * 512
end
return entries
end
--- TXT 章节包:条目名是 ``bookId_uid``,续篇是 ``bookId_uid_...``。info.txt 是目录,不是正文。
---@param entries { name: string, data: string }[]
---@param book_id string
---@param uid string|number
---@return string|nil text
local function readTextEntries(entries, book_id, uid)
local prefix = book_id .. "_" .. tostring(uid)
local parts = {}
for _idx, entry in ipairs(entries) do
local name = entry.name:match("([^/]+)$")
if name ~= "info.txt" and (name == prefix or name:sub(1, #prefix + 1) == prefix .. "_") then
parts[#parts + 1] = entry
end
end
-- TAR 主文件是 bookId_uid;ZIP 主文件常见 bookId_uid_o。二者都排在 _000N 续篇前。
local function rank(entry)
local name = entry.name:match("([^/]+)$")
if name == prefix or name == prefix .. "_o" then return "" end
return name:sub(#prefix + 2)
end
table.sort(parts, function(a, b)
local ra, rb = rank(a), rank(b)
if ra ~= rb then return ra < rb end
return a.name < b.name
end)
if #parts == 0 then return nil end
local chunks = {}
for i, entry in ipairs(parts) do
chunks[i] = Text.stripBom(entry.data)
end
return table.concat(chunks)
end
function Package.chapterText(data, book_id, uid)
local entries, err = untar(data)
if not entries then return nil, err end
local text = readTextEntries(entries, book_id, uid)
if text then return text end
return nil, "tar: chapter " .. tostring(uid) .. " not in package"
end
function Package.chapterZipText(files, book_id, uid)
local entries = {}
for name, data in pairs(files) do
entries[#entries + 1] = { name = name, data = data }
end
return readTextEntries(entries, book_id, uid)
end
return Package