--[[--
Kmoe 回包解析:书单 JSON、详情页 HTML、卷列表 JSON、书架页 HTML。纯函数,不发请求。
@module moonsource_kmoe.mapper
--]]
local JSON = require("json")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_kmoe")
local SOURCE_ID = "kmoe"
local Mapper = {}
---@param s string|nil
---@return string
local function plain(s)
return Text.stripHtml(s or "")
end
---@param body string|nil
---@return table|nil
local function decode(body)
if type(body) ~= "string" or body == "" then return nil end
local ok, wire = pcall(JSON.decode, body)
return ok and type(wire) == "table" and wire or nil
end
--- 书页链接里的书 key(`/c/.htm`),即本源的 stable_id。
---@param url string|nil
---@return string|nil
function Mapper.key(url)
return type(url) == "string" and url:match("/c/(%w+)%.htm") or nil
end
--- `data_list.php` 回包 → 书列表。搜索结果的书名带 `` 高亮,一并剥掉。
---@param body string|nil
---@return Book[]|nil books
---@return string|nil err
---@return boolean|nil more 还有下一页
function Mapper.list(body)
local wire = decode(body)
if not wire or type(wire.data) ~= "table" then return nil, _("Kmoe 书单响应无效") end
local books = {}
for _idx, row in ipairs(wire.data) do
local key = type(row) == "table" and Mapper.key(row.url_book)
if key then
books[#books + 1] = {
source_id = SOURCE_ID,
stable_id = key,
title = plain((tostring(row.name or ""):gsub("?[bB]>", ""))),
authors = plain(row.author),
cover = row.url_cover,
}
end
end
return books, nil, (tonumber(wire.nowpage) or 0) < (tonumber(wire.totalpage) or 0)
end
--- 详情页里一段 `…` 中可见的文字;隐藏的占位不算。第二个起的作者前面垫了全角空格。
---@param block string|nil
---@return string[]
local function visible(block)
local out = {}
for display, inner in (block or ""):gmatch('(.-)') do
local text = Text.trim((plain(inner):gsub("\227\128\128", " ")))
if display == "" and text ~= "" then out[#out + 1] = text end
end
return out
end
---@class KmoeDetail
---@field book Book
---@field bookid string 数字书号;收藏、下载接口用它
---@field hash string|nil 卷列表 `data_book.php?h=` 的参数
---@field logged_in boolean 页面按登录态渲染(`var uin` 非空)
--- 手机版详情页 `/m/c/.htm` → 书信息。认不出书号或书名返回 nil。
---@param key string
---@param html string|nil
---@return KmoeDetail|nil
function Mapper.detail(key, html)
html = html or ""
local bookid = html:match('var%s+bookid%s*=%s*"(%d+)"')
local title = html:match("]*>(.-)")
if not bookid or not title then return nil end
local intro = html:match('getElementById%("div_desc_content"%)%.innerHTML%s*=%s*"(.-)";')
return {
book = {
source_id = SOURCE_ID,
stable_id = key,
title = plain(title),
authors = table.concat(visible(html:match("作者:(.-)
(.-)') do
local key, title, author = tr:match("href='[^']*/c/(%w+)%.htm'[^>]*>(.-)%s*]*>(.-) | ")
local bookid = tr:match("sel_pushtype_(%d+)")
local fav = tr:match('icon%-tick%-fav%.png"[^>]-display:(%a*)"')
if key and bookid and fav == "" then
rows[#rows + 1] = {
book = { source_id = SOURCE_ID, stable_id = key, title = plain(title), authors = plain(author) },
bookid = bookid,
}
end
end
return rows, nil, html:find("myfollow%.php%?[^\"']*p=%d") ~= nil
end
return Mapper