--[[--
微信读书公众号(订阅页用):公众号列表、文章分页、文章页 → 正文。
列表走 App ``GET /mp/chapters``(一页 ``count`` 篇),正文走 ``/web/mp/content`` 的文章页 HTML,
普通图文取 ``#js_content``,图片 / 纯文字消息取脚本里的正文。
@module koplugin.book.moonsource_weread.mp
--]]
local Auth = require("moonsource_weread.auth")
local Assets = require("moonsource_weread.assets")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_weread")
local Mp = {}
local WEB = "https://weread.qq.com"
--- 公众号 CDN 的宽度档位(URL 末段),640 够墨水屏看清,原图(0)动辄几 MB。
local IMAGE_WIDTH = "640"
--- 公众号接口回 -2041 时的提示(订阅刷新据此弹窗,网页端作为源的错误显示)。
Mp.AUTH_EXPIRED = "公众号授权已失效,请在微信读书 App 中打开任意公众号重新授权后再试"
--- 每页篇数(服务端实测最多回 20)。
Mp.PAGE = 20
--- 是否公众号 bookId。
---@param book_id string|nil
---@return boolean
function Mp.isMp(book_id)
return tostring(book_id or ""):sub(1, 7) == "MP_WXS_"
end
--- 旧版本把书架上的公众号同步进了书库:撕掉这些 books 行(连同依附记录)。
--- 公众号只属于订阅;书架映射(mapper.shelfList)已不再产出,这里只清历史遗留,幂等。
---@param BookDB table book.books_db
---@return integer removed
function Mp.dropLegacyBooks(BookDB)
local n = 0
for _idx, id in ipairs(BookDB.stableIdsBySource("ext.weread") or {}) do
if Mp.isMp(id) then
BookDB.remove("ext.weread", id)
n = n + 1
end
end
return n
end
--- 文章列表(新到旧)。App ``/mp/chapters`` 是 ``data[] = { reviewId, createTime, mpInfo }``;
--- 旧网页回包是 ``reviews[].subReviews[]``,两种都认。
---@param data table
---@return { guid: string, title: string, time: integer }[]
function Mp.articles(data)
local out, seen = {}, {}
local function add(uid, time, title)
uid = tostring(uid or "")
if uid == "" or seen[uid] then return end
seen[uid] = true
time = tonumber(time) or 0
if type(title) ~= "string" or title == "" then title = os.date("%Y-%m-%d", time) end
out[#out + 1] = { guid = uid, title = title, time = time }
end
local rows = type(data) == "table" and type(data.data) == "table" and data.data or nil
if rows and type(rows[1]) == "table" and rows[1].reviewId ~= nil then
for _idx, ch in ipairs(rows) do
if type(ch) == "table" then
local info = type(ch.mpInfo) == "table" and ch.mpInfo or {}
add(ch.reviewId, ch.createTime, info.title)
end
end
table.sort(out, function(a, b) return a.time > b.time end)
return out
end
for _g, group in ipairs(type(data) == "table" and type(data.reviews) == "table" and data.reviews or {}) do
for _s, sub in ipairs(type(group) == "table" and type(group.subReviews) == "table" and group.subReviews or {}) do
local review = type(sub) == "table" and (type(sub.review) == "table" and sub.review or sub) or {}
local info = type(review.mpInfo) == "table" and review.mpInfo or {}
add(review.reviewId or sub.reviewId, review.createTime or group.createTime, info.title)
end
end
table.sort(out, function(a, b) return a.time > b.time end)
return out
end
--- 书架 wire 里的公众号 → ``{ id, title, group }``;group 取用户自建分组(archive)名。
--- 公众号可能在 books 行里,也可能在 mp / mpBook / officialAccounts(mp 实测是 ``{ book = 单个对象 }``)。
---@param shelf table
---@return { id: string, title: string, group: string }[]
function Mp.accounts(shelf)
shelf = type(shelf) == "table" and shelf or {}
local groups = require("moonsource_weread.mapper").groupByBookId(shelf)
local out, seen = {}, {}
local function add(rows)
if type(rows) ~= "table" then return end
if rows.book ~= nil then rows = rows.book end
if rows.bookId ~= nil then rows = { rows } end
for _idx, row in ipairs(rows) do
local book = type(row) == "table" and (type(row.bookInfo) == "table" and row.bookInfo
or type(row.book) == "table" and row.book or row) or {}
local id = tostring(book.bookId or "")
if Mp.isMp(id) and not seen[id] then
seen[id] = true
out[#out + 1] = { id = id, title = tostring(book.title or id), group = groups[id] or "" }
end
end
end
for _idx, wire in ipairs({ shelf, type(shelf.data) == "table" and shelf.data or {} }) do
for _i, key in ipairs({ "books", "mp", "mpBook", "officialAccounts" }) do add(wire[key]) end
end
return out
end
--- 公众号图片:懒加载地址换成 src,宽度降到 640 档、去掉 webp 转码参数;超出上限的图去掉。
--- 标签重建成只剩 src:原标签的固定宽高 / 内联样式在墨水屏上只会撑破版面。
---@param html string
---@return string
local function rewriteImages(html)
return (html:gsub("]*>", function(tag)
local _q, src = tag:match('data%-src=(["\'])(.-)%1')
if not src then _q, src = tag:match('%ssrc=(["\'])(.-)%1') end
if not src or src == "" then return "" end
-- QQ 表情是透明占位图 + CSS 雪碧背景,下载下来只是空白:去掉,留 alt(如「[微笑]」)
if src:find("pic_blank.gif", 1, true) then
local _qa, alt = tag:match('%salt=(["\'])(.-)%1')
return alt or ""
end
src = src:gsub("&", "&")
if src:find("mmbiz.qpic.cn", 1, true) then
src = src:gsub("/0([%?#])", "/" .. IMAGE_WIDTH .. "%1"):gsub("/0$", "/" .. IMAGE_WIDTH)
:gsub("([%?&])tp=webp&?", "%1"):gsub("[%?&]$", "")
end
return '
'
end))
end
--- 码点 → UTF-8(含 BMP 以外的 emoji)。
---@param code integer
---@return string
local function utf8Char(code)
if code < 0x80 then return string.char(code) end
if code < 0x800 then return string.char(0xC0 + math.floor(code / 64), 0x80 + code % 64) end
if code < 0x10000 then
return string.char(0xE0 + math.floor(code / 4096), 0x80 + math.floor(code / 64) % 64, 0x80 + code % 64)
end
return string.char(0xF0 + math.floor(code / 0x40000), 0x80 + math.floor(code / 4096) % 64,
0x80 + math.floor(code / 64) % 64, 0x80 + code % 64)
end
local ESCAPES = { n = "\n", r = "", t = "\t" }
--- 页面脚本里 ``key: '…'`` 的单引号 JS 字符串,解开 \xHH / \uXXXX / \n 等转义;没有返回 nil。
---@param html string
---@param key string
---@return string|nil
local function jsString(html, key)
local _s, e = html:find(key .. "%s*:%s*'")
if not e then return nil end
local out, i = {}, e + 1
while true do
local j = html:find("[\\']", i)
if not j then return nil end
out[#out + 1] = html:sub(i, j - 1)
if html:sub(j, j) == "'" then break end
local c = html:sub(j + 1, j + 1)
local hex = c == "x" and html:sub(j + 2, j + 3):match("^%x%x$")
local uni = c == "u" and html:sub(j + 2, j + 5):match("^%x%x%x%x$")
if hex then
out[#out + 1], i = string.char(tonumber(hex, 16)), j + 4
elseif uni then
local code = tonumber(uni, 16)
-- emoji 在 JS 里是代理对「\uD83D\uDE00」:两半合成一个码点,分开编码会成非法 UTF-8(显示为空 / 乱码)
local low = code >= 0xD800 and code < 0xDC00 and html:sub(j + 6, j + 7) == "\\u"
and tonumber(html:sub(j + 8, j + 11):match("^%x%x%x%x$") or "", 16)
if low and low >= 0xDC00 and low < 0xE000 then
out[#out + 1], i = utf8Char(0x10000 + (code - 0xD800) * 0x400 + (low - 0xDC00)), j + 12
else
out[#out + 1], i = utf8Char(code), j + 6
end
else
out[#out + 1], i = ESCAPES[c] or c, j + 2
end
end
return table.concat(out)
end
--- 图片 / 纯文字消息(item_show_type 8、10)没有 ``#js_content``:
--- 正文在脚本里的 ``content_noencode``(纯文字或 HTML),图片在 ``picture_page_info_list`` 的 ``cdn_url``。
---@param html string
---@return string|nil
local function scriptBody(html)
local text = jsString(html, "content_noencode")
local parts = {}
if text and not text:match("^%s*$") then
parts[1] = text:find("<", 1, true) and text or Text.textToBody(text)
end
local list = html:find("picture_page_info_list%s*:%s*%[")
if list then
local stop = html:find("}%s*%]", list) or #html
for url in html:sub(list, stop):gmatch("cdn_url%s*:%s*'([^']+)'") do
-- 地址是 JS 字符串:「\x26amp;」解成「&」(属性里正好是转义后的 &)
url = url:gsub("\\x(%x%x)", function(h) return string.char(tonumber(h, 16)) end)
parts[#parts + 1] = '