✨ (shidian): 接入识典古籍,按分类分章阅读
Release / release (push) Successful in 12s

This commit is contained in:
Garfield committed 2026-11-28 13:44:23 +08:00
commit eb118c6b39
21 files changed
+2126

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
local _ = require("gettext")
return {
fullname = _("月读书源:识典古籍"),
description = _("给月读增加「识典古籍」书源。需要同时安装月读,与平台官方无关。"),
}
+9
View File
@@ -0,0 +1,9 @@
--[[--
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
--]]
local WidgetContainer = require("ui/widget/container/widgetcontainer")
return WidgetContainer:extend{
name = "moonsource_shidian",
is_doc_only = false,
}
@@ -0,0 +1,12 @@
--[[--
月读第三方书源描述:识典古籍。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。
--]]
return {
api = 1,
provides = {
source = true,
},
meta = function() return require("moonsource_shidian.source").meta() end,
new = function() return require("moonsource_shidian.source").new() end,
}
@@ -0,0 +1,15 @@
# 识典古籍
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| 登录 | 不支持 | 公开阅读不需要账号,插件不保存 Cookie |
| 书架拉取、新增、删除 | 不支持 | 书架接口要站点签名,插件不接 |
| 搜索 | 部分支持 | 只读搜索页首屏:书名推荐,加上这一页正文命中的书 |
| 分类书库 | 部分支持 | 分类树来自书库页;每个分类只读首屏 20 本,后续页要签名。封面地址会过期 |
| 详情、目录、正文 | 部分支持 | 章节页带全书目录和该章整理本。书目上没有章节号、书号_1 打不开、分类首屏和书名搜索也碰不到这本书时,打不开 |
| 白话译文 | 部分支持 | 这一章的页面里带了译文就附在段落后面 |
| 已购内容 | 不支持 | 站点是公开阅读,没有购买接口 |
| 书评、章评、段评、回复 | 不支持 | 评论接口要站点签名,公开页面里没有评论列表 |
| 进度、笔记、统计同步 | 不支持 | 只留在本机 |
| 离线与整本缓存 | 部分支持 | 打开过的章节留在本机。整本缓存按章请求;断网后接着读下一章没有实测 |
| 账号切换 | 不支持 | 没有账号 |
@@ -0,0 +1,15 @@
--[[--
识典古籍元信息。
@module moonsource_shidian._meta
--]]
local _ = require("l10n").get("moonsource_shidian")
return {
id = "shidian",
name = _("识典古籍"),
type = "chapter",
description = _("识典古籍,按章阅读公开整理本"),
abilities = { _("搜索"), _("分类书库"), _("在线阅读"), _("整本缓存") },
}
@@ -0,0 +1,221 @@
--[[--
识典古籍 HTTP。只请求官网直接返回的 loader JSON。
/api/ancientlib 要 a_bogus,不签、不绕。书库和搜索只有首屏;
打开一本书时用公开页上能找到的章节号,换到带全书目录的章节页。
@module moonsource_shidian.client
--]]
local Mapper = require("moonsource_shidian.mapper")
local Request = require("http.request")
local _ = require("l10n").get("moonsource_shidian")
local BASE = "https://www.shidianguji.com"
local UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
local HEADERS = {
["User-Agent"] = UA,
Accept = "application/json",
Referer = BASE .. "/",
}
local LIBRARY_QUERY = "__loader=__session%2F%28lang%24%29%2Flibrary.%28cateId%24%29%2Fpage&__ssrDirect=true"
local SEARCH_QUERY = "__loader=__session%2F%28lang%24%29%2Fsearch.%28query%24%29%2Fpage&__ssrDirect=true"
local BOOK_QUERY = "__loader=__session%2F%28lang%24%29%2Fbook%2F%24&__ssrDirect=true"
---@class ShidianClient
---@field page table|nil
local Client = {}
Client.__index = Client
Client.UA = UA
---@return ShidianClient
function Client.new()
return setmetatable({}, Client)
end
---@param s string
---@return string
local function encode(s)
return (s:gsub("[^%w%-_%.~]", function(c)
return string.format("%%%02X", string.byte(c))
end))
end
---@param id string|nil
---@return boolean
local function idOk(id)
return type(id) == "string" and id:match("^[%w_]+$") ~= nil
end
---@param url string
---@param cb fun(data: table|nil, err: string|nil)
---@return { cancel: fun() }|nil
function Client:getJson(url, cb)
local pending = true
local inner = Request.get(url, {
headers = HEADERS, timeout = require("http.timeout").net(1),
}, function(body, err)
pending = false
if not body then cb(nil, err or _("网络请求失败")); return end
if body:sub(1, 1) ~= "{" then cb(nil, _("响应无效")); return end
local ok, data = pcall(require("json").decode, body)
if not ok or type(data) ~= "table" then cb(nil, _("响应无效")); return end
cb(data)
end)
if pending then return inner end
end
---@param data table
---@return boolean
local function spider(data)
return data.isSpider == true and type(data.bookInfo) ~= "table"
end
---@param cate string
---@param cb fun(data: table|nil, err: string|nil)
---@return { cancel: fun() }|nil
function Client:libraryAsync(cate, cb)
if not idOk(cate) then return require("source.base").defer(cb, nil, _("响应无效")) end
return self:getJson(BASE .. "/library/" .. cate .. "?" .. LIBRARY_QUERY, cb)
end
---@param keyword string
---@param cb fun(data: table|nil, err: string|nil)
---@return { cancel: fun() }|nil
function Client:searchAsync(keyword, cb)
if keyword == "" then return require("source.base").defer(cb, nil, _("响应无效")) end
return self:getJson(BASE .. "/search/" .. encode(keyword) .. "?" .. SEARCH_QUERY, cb)
end
--- 章节页。没有这本书时 cb(nil);网络、坏 JSON、被当成爬虫时带错误。
---@param book_id string
---@param chapter_id string
---@param cb fun(page: table|nil, err: string|nil)
---@return { cancel: fun() }|nil
function Client:chapterAsync(book_id, chapter_id, cb)
if not idOk(book_id) or not idOk(chapter_id) then
return require("source.base").defer(cb, nil, _("响应无效"))
end
local url = BASE .. "/book/" .. book_id .. "/chapter/" .. chapter_id .. "?" .. BOOK_QUERY
return self:getJson(url, function(data, err)
if not data then cb(nil, err); return end
if spider(data) then cb(nil, _("识典古籍把这次请求当成了爬虫,没有返回正文")); return end
local info = data.bookInfo
if type(info) ~= "table" or info.bookId ~= book_id then cb(nil); return end
self.page = data
cb(data)
end)
end
---@param book_id string
---@param chapter_id string
---@param cb fun(page: table|nil, err: string|nil)
---@return { cancel: fun() }|nil
function Client:contentAsync(book_id, chapter_id, cb)
local page = self.page
if type(page) == "table" and page.ssrChapterId == chapter_id
and type(page.bookInfo) == "table" and page.bookInfo.bookId == book_id then
return require("source.base").defer(cb, page)
end
return self:chapterAsync(book_id, chapter_id, cb)
end
--- 用公开页能找到的任意一章换出带目录的章节页。
--- 顺序:书目上的章节号、书号_1、该书分类首屏、书名搜索。都没有就失败,不猜签名接口。
---@param hint { id: string, title: string|nil, seed: string|nil, cate: string|nil }
---@param cb fun(page: table|nil, err: string|nil)
---@return { cancel: fun() }
function Client:resolveAsync(hint, cb)
local handle = {}
local function stopped() return handle.cancelled end
local function fail(err)
if not stopped() then cb(nil, err or _("这本书的公开页面没有给出可打开的章节")) end
end
local function ok(page)
if not stopped() then cb(page) end
end
-- 回调可能当场发生。当场发生时不要把已经结束的请求写回 inner,盖掉下一步。
local function spawn(make)
local done = false
local inner = make(function(next_cb)
return function(...)
done = true
return next_cb(...)
end
end)
if not done then handle.inner = inner end
end
local function trySearch()
if type(hint.title) ~= "string" or hint.title == "" then
return fail()
end
spawn(function(wrap)
return self:searchAsync(hint.title, wrap(function(data, err)
if stopped() then return end
if not data then return fail(err) end
local seed = Mapper.searchSeed(data, hint.id)
if not seed then return fail() end
spawn(function(wrap_chapter)
return self:chapterAsync(hint.id, seed, wrap_chapter(function(page, chapter_err)
if stopped() then return end
if page then return ok(page) end
fail(chapter_err)
end))
end)
end))
end)
end
local function tryCate()
if not idOk(hint.cate) or hint.cate == "all" then return trySearch() end
spawn(function(wrap)
return self:libraryAsync(hint.cate, wrap(function(data, err)
if stopped() then return end
if not data then return fail(err) end
local seed = Mapper.librarySeed(data, hint.id)
if not seed then return trySearch() end
spawn(function(wrap_chapter)
return self:chapterAsync(hint.id, seed, wrap_chapter(function(page, chapter_err)
if stopped() then return end
if page then return ok(page) end
if chapter_err then return fail(chapter_err) end
trySearch()
end))
end)
end))
end)
end
local function tryPlain()
spawn(function(wrap)
return self:chapterAsync(hint.id, hint.id .. "_1", wrap(function(page, err)
if stopped() then return end
if page then return ok(page) end
if err then return fail(err) end
tryCate()
end))
end)
end
if not idOk(hint.id) then return require("source.base").defer(cb, nil, _("响应无效")) end
if idOk(hint.seed) then
spawn(function(wrap)
return self:chapterAsync(hint.id, hint.seed, wrap(function(page, err)
if stopped() then return end
if page then return ok(page) end
if err then return fail(err) end
tryPlain()
end))
end)
else
tryPlain()
end
function handle.cancel()
handle.cancelled = true
if handle.inner then handle.inner.cancel() end
end
return handle
end
return Client
@@ -0,0 +1,17 @@
return {
["这本书的公开页面没有给出可打开的章节"] = "This book's public page does not include a chapter that can be opened",
["分类"] = "Category",
["分类书库"] = "Categories",
["响应无效"] = "Invalid response",
["在线阅读"] = "Read online",
["整本缓存"] = "Cache the book",
["搜索"] = "Search",
["章节目录保存失败"] = "Failed to save the chapter list",
["网络请求失败"] = "Network request failed",
["译文"] = "Translation",
["识典古籍"] = "Shidian Ancient Books",
["识典古籍,按章阅读公开整理本"] = "Shidian Ancient Books, read the public edited text chapter by chapter",
["识典古籍把这次请求当成了爬虫,没有返回正文"] = "Shidian Ancient Books treated this request as a crawler and returned no text",
["这一章没有正文"] = "This chapter has no text",
["部类"] = "Division",
}
@@ -0,0 +1,17 @@
return {
["这本书的公开页面没有给出可打开的章节"] = "這本書的公開頁面沒有給出可打開的章節",
["分类"] = "分類",
["分类书库"] = "分類書庫",
["响应无效"] = "回應無效",
["在线阅读"] = "線上閱讀",
["整本缓存"] = "整本快取",
["搜索"] = "搜尋",
["章节目录保存失败"] = "章節目錄儲存失敗",
["网络请求失败"] = "網路請求失敗",
["译文"] = "譯文",
["识典古籍"] = "識典古籍",
["识典古籍,按章阅读公开整理本"] = "識典古籍,按章閱讀公開整理本",
["识典古籍把这次请求当成了爬虫,没有返回正文"] = "識典古籍把這次請求當成了爬蟲,沒有返回正文",
["这一章没有正文"] = "這一章沒有正文",
["部类"] = "部類",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_shidian._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,422 @@
--[[--
识典古籍页面数据映射:纯函数,无网络。
书库、搜索、章节都是官网直接吐出的 JSON(Modern.js loader),不走要签名的 /api。
书库每个分类只有这一屏;章节页自带全书目录和这一章的段落。
@module moonsource_shidian.mapper
--]]
local JSON = require("json")
local _ = require("l10n").get("moonsource_shidian")
local SOURCE_ID = "shidian"
local Mapper = {}
Mapper.CONTENT_MARK = "moon:shidian:1"
Mapper.SOURCE_ID = SOURCE_ID
---@param s string
---@return string
local function esc(s)
return (s:gsub("&", "&amp;"):gsub("<", "&lt;"):gsub(">", "&gt;"))
end
---@param raw string|table|nil
---@return table|nil
local function object(raw)
if type(raw) == "table" then return raw end
if type(raw) ~= "string" or raw == "" then return nil end
local ok, data = pcall(JSON.decode, raw)
if ok and type(data) == "table" then return data end
end
---@param name table|string|nil
---@return string
local function chapterTitle(name)
if type(name) == "string" then return name end
if type(name) ~= "table" then return "" end
local parts = {}
for _i, item in ipairs(name) do
local text = type(item) == "table" and item.content or item
if type(text) == "string" and text ~= "" then parts[#parts + 1] = text end
end
return table.concat(parts)
end
---@param authors table|nil
---@return string
local function authorLine(authors)
local names = {}
for _i, author in ipairs(authors or {}) do
local name = type(author) == "table" and author.persName or nil
if type(name) == "string" and name ~= "" then
local role = author.responsibleTypeStr
names[#names + 1] = type(role) == "string" and role ~= "" and (name .. " " .. role) or name
end
end
return table.concat(names, "、")
end
---@param info table
---@return string
local function coverOf(info)
local pretty = info.beautifulCover
if type(pretty) == "string" and pretty ~= "" then return pretty end
if type(pretty) == "table" and type(pretty.pngUrl) == "string" then return pretty.pngUrl end
local cover = info.coverUrl
if type(cover) == "string" then return cover end
if type(cover) == "table" and type(cover.pngUrl) == "string" then return cover.pngUrl end
return ""
end
--- 书库卡片的封面埋在 content.fileDesc 里,和章节页不是同一层。
---@param item table
---@return string
local function libraryCover(item)
local content = item.content
local stmt = type(content) == "table" and content.fileDesc and content.fileDesc.titleStmt
if type(stmt) ~= "table" then return "" end
return coverOf({ beautifulCover = stmt.beautifulCover, coverUrl = stmt.cover })
end
---@param item table
---@return string
local function libraryAuthors(item)
local content = item.content
local monogr = type(content) == "table" and content.fileDesc and content.fileDesc.sourceDesc
and content.fileDesc.sourceDesc.biblStruct and content.fileDesc.sourceDesc.biblStruct.monogr
return authorLine(type(monogr) == "table" and monogr.authorList or nil)
end
---@param cats table|nil
---@return string
local function cateLabel(cats)
local names = {}
for _i, cate in ipairs(cats or {}) do
if type(cate) == "table" and type(cate.cateName) == "string" and cate.cateName ~= "" then
names[#names + 1] = cate.cateName
end
end
return table.concat(names, " · ")
end
---@param cats table|nil
---@return string|nil
local function leafCate(cats)
local id
for _i, cate in ipairs(cats or {}) do
if type(cate) == "table" and type(cate.cateId) == "string" and cate.cateId ~= "" then id = cate.cateId end
end
return id
end
---@param extra table|nil
---@return string|nil
local function firstSeed(extra)
local ids = type(extra) == "table" and extra.hasEntityRelationChapterIds
local seed = type(ids) == "table" and ids[1]
if type(seed) == "string" and seed ~= "" then return seed end
end
---@param item table
---@param category string
---@return Book|nil
local function bookFromCard(item, category)
if type(item.bookId) ~= "string" or item.bookId == "" then return nil end
if type(item.bookName) ~= "string" or item.bookName == "" then return nil end
local extra = type(item.extra) == "table" and item.extra or {}
local intro = type(extra.introduction) == "string" and extra.introduction or ""
return {
source_id = SOURCE_ID,
stable_id = item.bookId,
title = item.bookName,
authors = libraryAuthors(item),
category = category ~= "" and category or (item.dynastyCategoryName or ""),
intro = intro,
cover = libraryCover(item),
meta = { source = { shidian = { seed = firstSeed(extra) } } },
}
end
---@param nodes table
---@param id string
---@param trail table
---@return table|nil
local function findPath(nodes, id, trail)
for _i, node in ipairs(nodes) do
trail[#trail + 1] = node
local key = node.value or node.key
if key == id then return trail end
if type(node.children) == "table" and findPath(node.children, id, trail) then return trail end
trail[#trail] = nil
end
end
---@param nodes table
---@return { id: string, title: string }[]
local function chips(nodes)
local out = {}
for _i, node in ipairs(nodes) do
local id = node.value or node.key
if type(id) == "string" and id ~= "" and id ~= "all" and type(node.label) == "string" then
out[#out + 1] = { id = id, title = node.label }
end
end
return out
end
--- 两行筛选:部类,以及当前这一支的下一级。全部没有对应书库页,不放进芯片。
---@param tree table
---@param node string
---@return StoreChipGroup[]
local function groups(tree, node)
local top = chips(tree)
local path = {}
findPath(tree, node, path)
local top_active = path[1] and (path[1].value or path[1].key) or nil
if top_active == "all" then top_active = nil end
local here = path[#path]
-- 部类自己的下一级仍叫「分类」。再往下钻时,这一行就是当前类,标题用它的名字,
-- 否则类名从两行芯片里消失,只剩一排没有选中项的子类。
local branch = #path > 1 and type(here.children) == "table" and here.children[1] ~= nil
local section = branch and here or (#path > 1 and path[#path - 1] or path[1])
local child_nodes = section and section.children or {}
local child_chips = chips(child_nodes)
local child_active
for _i, chip in ipairs(child_chips) do
if chip.id == node then child_active = node end
end
local child_title = branch and type(here.label) == "string" and here.label or _("分类")
local out = { { title = _("部类"), chips = top, active = top_active } }
if child_chips[1] then
out[#out + 1] = { title = child_title, chips = child_chips, active = child_active }
end
return out
end
---@param root table|nil
---@param node string
---@return Book[]|nil
---@return StoreChipGroup[]|nil
---@return string|nil
function Mapper.library(root, node)
local lib = type(root) == "table" and root.library or nil
local data = type(lib) == "table" and lib.data or nil
if type(lib) ~= "table" or lib.status == 404 or type(data) ~= "table" or type(data.bookList) ~= "table"
or type(lib.treeData) ~= "table" then
return nil, nil, _("响应无效")
end
local label = ""
local path = {}
findPath(lib.treeData, node, path)
local here = path[#path]
if here and type(here.label) == "string" then label = here.label end
local books = {}
for _i, item in ipairs(data.bookList) do
local book = type(item) == "table" and bookFromCard(item, label) or nil
if book then
book.meta.source.shidian.cate = node
if type(item.dynastyCategoryName) == "string" and item.dynastyCategoryName ~= "" and label ~= "" then
book.category = label .. " · " .. item.dynastyCategoryName
end
books[#books + 1] = book
end
end
return books, groups(lib.treeData, node)
end
---@param item table
---@param seed string|nil
---@return Book|nil
local function bookFromSearch(item, seed)
if type(item.bookId) ~= "string" or item.bookId == "" then return nil end
if type(item.bookName) ~= "string" or item.bookName == "" then return nil end
return {
source_id = SOURCE_ID,
stable_id = item.bookId,
title = item.bookName,
authors = authorLine(item.authors),
category = cateLabel(item.traditionalCategory),
intro = "",
cover = coverOf(item),
meta = { source = { shidian = { seed = seed, cate = leafCate(item.traditionalCategory) } } },
}
end
---@param root table|nil
---@return Book[]|nil
---@return string|nil
function Mapper.search(root)
local data = type(root) == "table" and root.data or nil
if type(data) ~= "table" then return nil, _("响应无效") end
local recommended = type(data.recommendBooks) == "table" and data.recommendBooks.books or nil
local paragraphs = data.paragraphs
if recommended == nil and paragraphs == nil then return nil, _("响应无效") end
if recommended ~= nil and type(recommended) ~= "table" then return nil, _("响应无效") end
if paragraphs ~= nil and type(paragraphs) ~= "table" then return nil, _("响应无效") end
local seeds = {}
for _i, para in ipairs(paragraphs or {}) do
local info = type(para) == "table" and para.bookInfo or nil
if type(info) == "table" and type(info.bookId) == "string" and type(para.chapterId) == "string" then
if not seeds[info.bookId] then seeds[info.bookId] = { chapter = para.chapterId, info = info } end
end
end
local books, seen = {}, {}
for _i, item in ipairs(recommended or {}) do
local hit = type(item) == "table" and seeds[item.bookId] or nil
local book = type(item) == "table" and bookFromSearch(item, hit and hit.chapter or nil) or nil
if book and not seen[book.stable_id] then
seen[book.stable_id] = true
books[#books + 1] = book
end
end
for _i, para in ipairs(paragraphs or {}) do
local info = type(para) == "table" and para.bookInfo or nil
local book = type(info) == "table" and bookFromSearch(info, para.chapterId) or nil
if book and not seen[book.stable_id] then
seen[book.stable_id] = true
books[#books + 1] = book
end
end
return books
end
---@param root table|nil
---@param book_id string
---@return string|nil
function Mapper.librarySeed(root, book_id)
local list = type(root) == "table" and root.library and root.library.data and root.library.data.bookList or {}
for _i, item in ipairs(list) do
if type(item) == "table" and item.bookId == book_id then return firstSeed(item.extra) end
end
end
---@param root table|nil
---@param book_id string
---@return string|nil
function Mapper.searchSeed(root, book_id)
local books = Mapper.search(root)
if not books then return nil end
for _i, book in ipairs(books) do
local own = book.meta and book.meta.source and book.meta.source.shidian
if book.stable_id == book_id and type(own) == "table" then return own.seed end
end
end
---@param page table
---@return Book|nil
function Mapper.book(page)
local info = type(page) == "table" and page.bookInfo or nil
if type(info) ~= "table" or type(info.bookId) ~= "string" or type(info.bookName) ~= "string" then return nil end
local extra = type(info.extra) == "table" and info.extra or {}
local intro = type(extra.introduction) == "string" and extra.introduction or ""
return {
source_id = SOURCE_ID,
stable_id = info.bookId,
title = info.bookName,
authors = authorLine(info.authors),
category = cateLabel(info.traditionalCategory),
intro = intro,
cover = coverOf(info),
meta = { source = { shidian = {
seed = page.ssrChapterId or firstSeed(extra),
cate = leafCate(info.traditionalCategory),
} } },
}
end
---@param nodes table
---@param out BookChapter[]
local function flatten(nodes, out)
for _i, node in ipairs(nodes) do
if type(node) == "table" and type(node.chapterId) == "string" and node.chapterId ~= "" then
local title = chapterTitle(node.chapterName)
out[#out + 1] = {
idx = #out + 1,
uid = node.chapterId,
title = title ~= "" and title or node.chapterId,
}
end
if type(node) == "table" and type(node.subChapters) == "table" then flatten(node.subChapters, out) end
end
end
---@param page table|nil
---@return BookChapter[]|nil
---@return string|nil
function Mapper.toc(page)
local info = type(page) == "table" and page.bookInfo or nil
local chapters = type(info) == "table" and type(info.catalog) == "table" and info.catalog.chapters or nil
if type(chapters) ~= "table" then return nil, _("响应无效") end
local toc = {}
flatten(chapters, toc)
if not toc[1] then return nil, _("这本书的公开页面没有给出可打开的章节") end
return toc
end
---@param lines table
---@param blocks string[]
local function appendLines(lines, blocks)
local para = {}
local function flush()
if para[1] then
blocks[#blocks + 1] = "<p>" .. table.concat(para) .. "</p>"
para = {}
end
end
for _i, line in ipairs(lines) do
local text = type(line) == "table" and line.content or nil
if type(text) == "string" and text ~= "" then
local kind = line.lineType
if kind == 4 or kind == 8 or kind == 9 then
flush()
blocks[#blocks + 1] = "<h3>" .. esc(text) .. "</h3>"
elseif kind == 3 then
-- 页标,没有可读正文。
elseif kind == 2 then
para[#para + 1] = "<small>" .. esc(text) .. "</small>"
else
para[#para + 1] = esc(text)
end
end
end
flush()
end
---@param raw string|table|nil
---@return string
local function translation(raw)
local doc = object(raw)
local sentences = type(doc) == "table" and doc.sentences or nil
if type(sentences) ~= "table" then return "" end
local parts = {}
for _i, sentence in ipairs(sentences) do
local text = type(sentence) == "table" and sentence.content or nil
if type(text) == "string" and text ~= "" then parts[#parts + 1] = esc(text) end
end
if not parts[1] then return "" end
return "<p><small>" .. _("译文") .. ":" .. table.concat(parts) .. "</small></p>"
end
---@param page table|nil
---@return string|nil
---@return string|nil
function Mapper.chapterHtml(page)
local list = type(page) == "table" and page.paragraphList or nil
if type(list) ~= "table" then return nil, _("响应无效") end
local blocks = {}
for _i, para in ipairs(list) do
if type(para) == "table" then
local content = object(para.content)
appendLines(type(content) == "table" and content.lines or {}, blocks)
local translated = translation(para.translateContent)
if translated ~= "" then blocks[#blocks + 1] = translated end
end
end
if not blocks[1] then return nil, _("这一章没有正文") end
return table.concat(blocks)
end
return Mapper
@@ -0,0 +1,215 @@
--[[--
识典古籍书源。
阅读公开整理本,不登录。书架、进度、评论走要签名的接口,这里不接。
分类和搜索只有官网首屏。
@module moonsource_shidian.source
--]]
local Browse = require("source.browse")
local Client = require("moonsource_shidian.client")
local Mapper = require("moonsource_shidian.mapper")
local SourceBase = require("source.base")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_shidian")
-- 书库页「经部」。其余分类从这一页的树来,不在本地造一份分类表。
local DEFAULT_CATE = "10000"
local FETCH_INTERVAL = 1
local Shidian = {}
---@return BookSourceMeta
function Shidian.meta()
return require("moonsource_shidian.loadmeta")()
end
---@class ShidianSource : SourceBase
---@field client ShidianClient
local Source = setmetatable({}, { __index = SourceBase })
Source.__index = Source
---@return ShidianSource
function Shidian.new()
local meta = Shidian.meta()
return setmetatable({
id = meta.id, name = meta.name, type = meta.type, client = Client.new(),
}, Source)
end
function Source:configured()
return true
end
function Source:capabilities()
return { scrape = false, edit = false, stats_pull = false, shelf_cache = false, shelf_push = false }
end
function Source:syncBooksAsync(_opts, cb)
return SourceBase.skipped(cb, "shidian has no shelf")
end
---@param identity BookIdentity
---@return { id: string, title: string|nil, seed: string|nil, cate: string|nil }
local function hint(identity)
local book = identity.book or {}
local meta = book.meta or {}
local own = type(meta.source) == "table" and meta.source.shidian or nil
own = type(own) == "table" and own or {}
return { id = identity.stable_id, title = book.title, seed = own.seed, cate = own.cate }
end
---@param keyword string
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
---@return { cancel: fun() }|nil
function Source:searchAsync(keyword, cb)
return self.client:searchAsync(keyword, function(data, err)
if not data then cb(nil, err); return end
local books, map_err = Mapper.search(data)
if not books then cb(nil, map_err); return end
cb({ data = books })
end)
end
---@param opts { node?: string, limit?: integer }|nil
---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil)
---@return { cancel: fun() }
function Source:browseAsync(opts, cb)
opts = opts or {}
local node = opts.node
if type(node) ~= "string" or node == "" or node == "all" then node = DEFAULT_CATE end
local groups
return Browse.pages(function(_page, done)
return self.client:libraryAsync(node, function(data, err)
if not data then done(nil, err); return end
local books, filters, map_err = Mapper.library(data, node)
if not books then done(nil, map_err); return end
groups = filters
done(books, nil, false)
end)
end, opts.limit or 60, {}, function(result, err)
if result then result.groups = groups end
cb(result, err)
end)
end
---@param identity BookIdentity
---@param cb fun(book: Book|nil, err: string|nil)
---@return { cancel: fun() }
function Source:getDetailAsync(identity, cb)
return self.client:resolveAsync(hint(identity), function(page, err)
if not page then cb(nil, err); return end
local book = Mapper.book(page)
if not book then cb(nil, _("响应无效")); return end
local existing = require("book.books_db").get(self.id, identity.stable_id)
if existing then book.deleted = existing.deleted end
cb(require("book.store").rememberDetail(book))
end)
end
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
---@return { cancel: fun() }
function Source:refreshTocAsync(identity, cb)
local handle = {}
local pending = true
local inner = self.client:resolveAsync(hint(identity), function(page, err)
pending = false
if handle.cancelled then return end
if not page then cb(nil, err); return end
local toc, toc_err = Mapper.toc(page)
if not toc then cb(nil, toc_err); return end
if not Toc.put(self.id, identity.stable_id, toc) then
cb(nil, _("章节目录保存失败"))
return
end
cb(toc)
end)
if pending then handle.inner = inner end
function handle.cancel()
handle.cancelled = true
if handle.inner then handle.inner.cancel() end
end
return handle
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 force then return self:refreshTocAsync(identity, cb) end
local cancelled, active = false, nil
active = Toc.readAsync(self.id, identity.stable_id, function(cached, err)
if cancelled then return end
if cached and cached[1] then cb(cached); return end
if err then cb(nil, err); return end
active = self:refreshTocAsync(identity, cb)
end)
return { cancel = function()
cancelled = true
if active then active.cancel() end
end }
end
---@return ChapterFetchContent
local function contentFetcher(self)
return function(ref, chapter, done)
return self.client:contentAsync(ref.stable_id, chapter.uid, function(page, err)
if not page then done(nil, err or _("这一章没有正文")); return end
local html, html_err = Mapper.chapterHtml(page)
if not html then done(nil, html_err); return end
done({
title = chapter.title,
book_title = ref.book and ref.book.title or nil,
html = html,
mark = Mapper.CONTENT_MARK,
})
end)
end
end
---@param path string
---@return boolean
local function reuse(path)
if not require("ui/network/manager"):isConnected() then return true end
local file = assert(io.open(path, "rb"))
local head, err = file:read(64)
file:close()
assert(head, err)
return head:find(Mapper.CONTENT_MARK, 1, true) ~= nil
end
function Source:openBookAsync(identity, opts, cb)
local Chapter = require("source.chapter")
local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi
return open(self, identity, identity.book, opts, {
loadToc = function(ref, done) return self:loadTocAsync(ref, done) end,
fetchContent = contentFetcher(self),
reuse = reuse,
}, cb)
end
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
return require("source.chapter").prefetchAsync(identity, identity.book, toc, from_idx, count, {
fetchContent = contentFetcher(self),
interval_seconds = FETCH_INTERVAL,
reuse = reuse,
}, cb)
end
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
return require("source.chapter").cacheAllAsync(self, identity, contentFetcher(self), on_progress, cb,
FETCH_INTERVAL, range, reuse)
end
---@param identity BookIdentity
---@return BookCoverRequest|nil
function Source:coverRequest(identity)
local url = identity.book and identity.book.cover
if type(url) ~= "string" or url == "" then return nil end
return { url = url, headers = { ["User-Agent"] = Client.UA, Referer = "https://www.shidianguji.com/" } }
end
return Shidian
@@ -0,0 +1,4 @@
-- 版本号由 tools/package.sh 打包时把占位符换成发布版本;源码运行显示 0.0.0-dev。
local VERSION = "@VERSION@"
if VERSION:find("^@") then return "0.0.0-dev" end
return VERSION