🚚 (split): 从月读拆出独立仓库,沿用原书源 id
Release / release (push) Successful in 11s

This commit is contained in:
Garfield committed 2026-11-27 08:08:02 +08:00
commit 994167fbe5
50 files changed
+18324

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
local _ = require("gettext")
return {
fullname = _("月读书源:Kavita"),
description = _("给月读增加「Kavita」书源。需要同时安装月读,与平台官方无关。"),
}
+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_kavita",
is_doc_only = false,
}
@@ -0,0 +1,18 @@
--[[--
月读第三方书源描述:Kavita。契约见月读 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,
home_widgets = { require("moonsource_kavita.on_deck") },
},
meta = function() return require("moonsource_kavita.source").meta() end,
new = function() return require("moonsource_kavita.source").new() end,
setting = lazy("moonsource_kavita.setting"),
}
@@ -0,0 +1,17 @@
# Kavita
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| 服务连接 | 支持 | Kavita 0.9 或更新版本;填写地址、API Key 并选择书库 |
| 书架拉取 | 支持 | 分页读取系列;多卷系列打开时选择卷 |
| 加入与移出远端书架 | 不支持 | 书架只读;本地删除不操作服务器藏书 |
| 详情与封面 | 支持 | 读取书库、系列及作者等元数据 |
| 整本下载与阅读 | 支持 | EPUB、PDF、CBZ 等 KOReader 支持的格式 |
| 漫画在线阅读与缓存 | 部分支持 | 依赖兼容的 kamare 增强版;无增强接口时 CBZ 可下载阅读,图片目录不能同样回退 |
| 阅读进度同步 | 支持 | 按卷保存;EPUB 使用 spine/锚点,固定版式使用页码 |
| 划线与备注同步 | 部分支持 | 仅 EPUB;依赖本地内容和坐标定位 |
| 阅读统计同步 | 部分支持 | 拉取历史快照;进度心跳可记入会话时长,不上传本地统计集合 |
| 整书书评 | 已实现,未实测 | 系列级书评,卷共享所属系列缓存;受服务器版本、Kavita+ 及外部评价权限影响 |
| 章评与段评 | 不支持 | 未接入可验证的读取接口;服务器存在章节评价模型,不等于插件已接入 |
| 评论回复与写操作 | 不支持 | 不发评、不改评分 |
| 离线阅读 | 支持 | 已下载文件及目录可用;漫画缓存取决于 kamare |
@@ -0,0 +1,16 @@
--[[--
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
@module moonsource_kavita._meta
--]]
local _ = require("l10n").get("moonsource_kavita")
return {
id = "kavita",
name = _("Kavita"),
type = "book",
description = _("同步 Kavita 书架、电子书与漫画"),
abilities = { _("书架与卷目录同步(只读)"), _("进度同步"), _("EPUB 划线同步"), _("阅读历史拉取"),
_("漫画在线阅读与缓存(需 kamare 增强版)"), _("书评") },
}
@@ -0,0 +1,192 @@
--[[--
Kavita 注解的线上形态与同一性:纯函数、无 IO,pull / push / delete 共用同一条口径。
Kavita 网页端把备注存成 Quill Delta JSON(`comment`)+ Quill HTML(`commentHtml`),
纯文本 `commentPlainText` 是**后端从 HTML 去标签**算出来的(块级标签不插分隔,有损)。
读回、写入、冲突判定三处必须共用这里的归一,否则同一段备注每轮都会被判「改过」→ 无限 update。
@module moonsource_kavita.annotation
--]]
local JSON = require("json")
local Text = require("utils.text")
local Annotation = {}
--- 键分隔符用 US(0x1F):Kavita 的路径与选中文本里不会出现,天然不可撞。
--- 导出是为了让源侧拼「同坐标」判定键时用同一个字符,不各写一份字面量。
Annotation.KEY_SEP = string.char(31)
--- 排版上不可见、但字节上会破坏比较的字符:ZWSP / ZWNJ / ZWJ / BOM / WORD JOINER。
local ZERO_WIDTH = { "\226\128\139", "\226\128\140", "\226\128\141", "\239\187\191", "\226\129\160" }
--- 写入前的归一:`\r\n` → `\n`、去掉尾部换行;纯空白在调用方判空。
---@param note string|nil
---@return string
local function normalizeNote(note)
return (Text.normalizeNewlines(note):gsub("\n+$", ""))
end
--- 比较用归一:trim + 内部连续空白压成单空格 + 剔除零宽字符。
--- 只用于「是不是同一段备注」,不能拿它落库(会把用户的换行/缩进抹平)。
---@param s string|nil
---@return string
local function comparisonText(s)
local text = tostring(s or ""):gsub("\r\n", "\n"):gsub("\r", "\n")
for _idx, zw in ipairs(ZERO_WIDTH) do text = text:gsub(zw, "") end
return (text:gsub("%s+", " "):gsub("^%s+", ""):gsub("%s+$", ""))
end
--- Delta → 纯文本:`ops[*].insert` 里的字符串拼接,embed(图片等)与 `attributes` 一律忽略。
--- 末尾换行是 Delta 文档的收尾,不是内容;拼完剥掉。
---@param data table
---@return string
local function deltaText(data)
local ops = data.ops
if type(ops) ~= "table" then return "" end
local parts = {}
for _idx, op in ipairs(ops) do
if type(op) == "table" and type(op.insert) == "string" then
parts[#parts + 1] = op.insert
end
end
return (table.concat(parts):gsub("\n+$", ""))
end
--- HTML → 纯文本:块级边界(`</p>` / `</div>` / `<br>`)换行,其余标签丢弃,实体解码。
--- 不能直接用 Text.stripHtml:它会丢弃空行,而备注里的空行是内容。
---@param html string
---@return string
local function htmlText(html)
local text = tostring(html or ""):gsub("\r\n", "\n"):gsub("\r", "\n")
-- Quill 的空行是 `<p><br></p>`:先整个折成一个换行,否则 <br> 与 </p> 会各补一行。
text = text:gsub("<p[^>]*>%s*<br%s*/?>%s*</p>", "\n")
text = text:gsub("<br%s*/?>", "\n"):gsub("</p%s*>", "\n"):gsub("</div%s*>", "\n")
text = text:gsub("<[^>]*>", "")
-- Quill 把连续空格写成 &nbsp;,解出来是 NBSP,还原成普通空格才能与本地文本对上。
text = Text.xmlDecode(text):gsub("\194\160", " ")
return (text:gsub("\n+$", ""))
end
--- 读回归一。优先级:commentHtml → commentPlainText → comment 的 Delta → comment 原文(legacy 纯文本)。
--- 空值集合("" / "{}" / {"ops":[]} / {"ops":[{"insert":"\n"}]} / null)一律 ""。
---@param comment string|nil
---@param comment_html string|nil
---@param comment_plain_text string|nil
---@return string
function Annotation.noteText(comment, comment_html, comment_plain_text)
if type(comment_html) == "string" and Text.trim(comment_html) ~= "" then
return htmlText(comment_html)
end
if type(comment_plain_text) == "string" and Text.trim(comment_plain_text) ~= "" then
-- 后端 StripHtml 的产物,块间无分隔;这里只需去首尾空白。
return Text.trim(comment_plain_text)
end
local raw = tostring(comment or "")
if Text.trim(raw) == "" or Text.trim(raw) == "null" then return "" end
local ok, data = pcall(JSON.decode, raw)
-- json.decode 失败 = 存量纯文本备注(网页端 JSON.parse 会崩,但设备侧要能读)。
if not ok then return raw end
if data == nil then return "" end
if type(data) ~= "table" then return tostring(data) end
local text = deltaText(data)
if text:match("^%s*$") then return "" end
return text
end
--- 写回归一(create / update 共用):与 Web 同构,`comment` 为 Quill Delta JSON、`commentHtml` 为对应 HTML。
--- 空备注写 `"{}"` + `""`(Web「新建未输入」的原样),否则网页端 `JSON.parse(comment)` 会崩。
---@param note string|nil
---@return { comment: string, commentHtml: string }
function Annotation.toRemote(note)
local text = normalizeNote(note)
if text:match("^%s*$") then
return { comment = "{}", commentHtml = "" }
end
local lines = {}
for line in (text .. "\n"):gmatch("([^\n]*)\n") do
lines[#lines + 1] = line == "" and "<p><br></p>" or ("<p>" .. Text.xmlEscape(line) .. "</p>")
end
return {
comment = JSON.encode({ ops = { { insert = text .. "\n" } } }),
commentHtml = table.concat(lines),
}
end
--- 幂等键(spec §8.2):`<chapterId>\31<xPath>\31<endingXPath>\31<selectedText>`。
--- `comment` 不进键(备注可改,进键会把「改备注」变成「新建」);`selectedText` 用比较归一,
--- 否则网页端/设备端的换行差异会让同一条划线认不出来(落库仍存原文)。
--- 字段名两套都要认:线上 DTO 用 `xPath` / `endingXPath` / `selectedText`,落库后的 payload
--- (阅读器快照、远端去重的输入)用 `kavita_xpath` / `kavita_ending_xpath` / `text`。
---@param ann { chapterId: integer|nil, xPath: string|nil, endingXPath: string|nil, selectedText: string|nil, kavita_xpath: string|nil, kavita_ending_xpath: string|nil, text: string|nil }
---@return string
function Annotation.key(ann)
local selected = ann.selectedText
if selected == nil then selected = ann.text end
return table.concat({
tostring(ann.chapterId or ""),
tostring(ann.xPath or ann.kavita_xpath or ""),
tostring(ann.endingXPath or ann.kavita_ending_xpath or ""),
comparisonText(selected),
}, Annotation.KEY_SEP)
end
--- 在对账列表里找本地这条注解的远端对应:同键多条取 id 最小(网页端重扫可能留下重复),
--- 没有 id 的条目没法采纳,直接跳过。
---@param remote table[]|nil
---@param ann table
---@return table|nil
function Annotation.match(remote, ann)
if type(remote) ~= "table" then return nil end
local wanted = Annotation.key(ann)
local best, best_id
for _idx, item in ipairs(remote) do
local id = type(item) == "table" and tonumber(item.id)
if id and (not best_id or id < best_id) and Annotation.key(item) == wanted then
best, best_id = item, id
end
end
return best
end
--- 比较两段备注是不是同一段:trim、内部连续空白压成单空格、剔除零宽字符,两边都空判等。
--- push / pull / 冲突裁决共用;不能拿它落库(换行与缩进会被抹平)。
---@param a string|nil
---@param b string|nil
---@return boolean
function Annotation.sameNote(a, b)
return comparisonText(a) == comparisonText(b)
end
--- owner 比较:远端 id 是数字,调用方可能拿到字符串(配置/`/api/Users/me` 解析),两边能对上。
---@param a any
---@param b any
---@return boolean
local function sameOwner(a, b)
local na, nb = tonumber(a), tonumber(b)
if na and nb then return na == nb end
return tostring(a) == tostring(b)
end
--- 该章全部注解(`GET /api/Annotation/all`,无分页)。`owner_id` 非空时只留自己的:
--- 账号开了「查看他人注解」后接口会混入别人的条目,删改别人的会整批 400。
---@param client KavitaClient
---@param chapter_id integer
---@param owner_id integer|string|nil nil / "" = 拿不到当前用户时的降级:不过滤
---@param cb fun(list: table[]|nil, err: string|nil)
---@return HttpJob|nil
function Annotation.listByChapter(client, chapter_id, owner_id, cb)
return client:json("GET", "/api/Annotation/all", { chapterId = chapter_id }, nil, function(data, err)
if not data then return cb(nil, err) end
local filter = owner_id ~= nil and owner_id ~= ""
local out = {}
for _idx, item in ipairs(type(data) == "table" and data or {}) do
if type(item) == "table" and (not filter or sameOwner(item.ownerUserId, owner_id)) then
out[#out + 1] = item
end
end
cb(out)
end)
end
return Annotation
@@ -0,0 +1,33 @@
--[[--
同步阻塞操作期间的忙碌窗:kamare 的缓存操作直接写盘,主线程会停住。
先把窗画出来、强制重绘一次,再动手;返回后关窗。
调用方只给标题与要跑的函数;`fn` 的返回值原样透传(最多四个)。
关闭失败不会发生:窗在建好后才交给 UIManager。
@module moonsource_kavita.busy
--]]
local _ = require("l10n").get("moonsource_kavita")
local Busy = {}
---@param title string 窗标题(一般是动作名,如「清理已读」)
---@param fn fun(): any
---@return any, any, any, any
function Busy.run(title, fn)
local UIManager = require("ui/uimanager")
local dialog = require("ui.themes.widgets.progress_dialog"):new{
title = title,
text = _("正在清理…"),
dismissable = false,
}
local ok, code, message, detail = dialog:showWhile(function()
if UIManager.forceRePaint then UIManager:forceRePaint() end
return fn()
end)
dialog:close()
return ok, code, message, detail
end
return Busy
@@ -0,0 +1,912 @@
--[[--
kamare 漫画缓存适配层:探测、能力门面、配置镜像、错误文案、书架投影、删除保护。
kamare 是缓存的唯一执行者与写入者;moon 只读状态、发下载 / 删除 / 队列请求。
kamare 的模块一律在函数内 `pcall(require, …)`,绝不顶层 require、也不持有它的 table:
插件升级 / 重载后旧 table 会失效。探测成功结果进程内记忆,失败不记忆(require 自带缓存)。
@module moonsource_kavita.cache
--]]
local _ = require("l10n").get("moonsource_kavita")
local T = require("ffi/util").template
local logger = require("utils.log")
local Text = require("utils.text")
local Cache = {}
---@class KamareProbe
---@field ok boolean
---@field state "missing"|"official"|"incompatible"|"enhanced"
---@field reason string|nil
---@field api_version integer|nil
---@field capabilities table|nil
---@field version string|nil
---@field path string|nil
--- 成功探测的记忆(只存元信息,不存模块 table)。
---@type KamareProbe|nil
local memo
--- 当前进程内已镜像过的配置(base_url\0api_key),失败不写。
---@type string|nil
local mirrored
--- 本次会话的镜像是否失败过(设置页第五态)。
local mirror_failed = false
--- 一次性日志的去重键(同一原因只记一行,状态变化才再记)。
local logged = {}
--- 当前打开的章(kamare 保证同一时刻只有一个 viewer)。
---@type { base_url: string|nil, chapter_id: any }|nil
local active
--- 书架投影记忆,按服务器分开;只由成功写操作 / 手动刷新 / Registry.reload 失效。
---@type table<string, ShelfCacheProjection>
local shelves = {}
--- 上次记录过的暂停原因(按服务器),轮询时只在变化时写日志。
---@type table<string, string>
local pause_reason_logged = {}
--- 记一行日志;同一 key 在本进程内只记一次。
---@param key string
---@param text string
local function logOnce(key, text)
if logged[key] then return end
logged[key] = true
logger.info(text)
end
--- 能力名清单(排序后按分隔符拼接),日志与设置页共用一份口径。
---@param capabilities table|nil
---@param separator string|nil 缺省逗号(日志);设置页传「、」
---@return string
function Cache.capabilityNames(capabilities, separator)
local names = {}
for name, on in pairs(type(capabilities) == "table" and capabilities or {}) do
if on == true then names[#names + 1] = tostring(name) end
end
table.sort(names)
if #names == 0 then return "none" end
return table.concat(names, separator or ",")
end
--- 探测结果每进程(每种结果)一行:四态 + 版本 + 能力;不记 API Key。
---@param probe KamareProbe
local function logProbe(probe)
local capabilities = Cache.capabilityNames(probe.capabilities)
local signature = string.format("probe|%s|%s|%s", probe.state, tostring(probe.version), capabilities)
logOnce(signature, string.format("kamare probe ok=%s state=%s version=%s caps=%s",
tostring(probe.ok), probe.state, tostring(probe.version), capabilities))
end
---@param ids any
---@return string
local function joinIds(ids)
if type(ids) ~= "table" then return "-" end
local parts = {}
for _idx, id in ipairs(ids) do parts[#parts + 1] = tostring(id) end
return #parts > 0 and table.concat(parts, ",") or "-"
end
--- 每次缓存写操作一行:<op> + 章 id + code(成功记 ok)。
---@param op string
---@param ids any
---@param code string|nil
local function logWrite(op, ids, code)
logger.info("cache " .. op .. " cid=" .. joinIds(ids) .. " code=" .. tostring(code or "ok"))
end
--- 目录条目 → chapterId 列表(只用于日志)。
---@param entries table|nil
---@return table
local function entryIds(entries)
local ids = {}
for _idx, entry in ipairs(type(entries) == "table" and entries or {}) do
if type(entry) == "table" then
ids[#ids + 1] = entry.chapterId or entry.chapter_id or entry.id or "?"
end
end
return ids
end
--- 函数内 require:拿不到就 nil,不抛错。
---@param name string
---@return table|nil
local function loadModule(name)
local ok, mod = pcall(require, name)
if ok and type(mod) == "table" then return mod end
return nil
end
--- 本地封面文件存在才算数(缓存可能已被 kamare 清理)。
---@param path any
---@return boolean
local function fileExists(path)
if type(path) ~= "string" or path == "" then return false end
local file = io.open(path, "rb")
if not file then return false end
file:close()
return true
end
--- 官方 / 旧版 kamare 的查看器是否可用(legacy 通道的触发条件)。
---@return boolean
local function legacyAvailable()
local viewer = loadModule("kamareimageviewer")
return type(viewer) == "table" and type(viewer.new) == "function"
end
--- `kamareversion` 返回字符串(发布时写入);老写法可能是表。
---@return string|nil
local function kamareVersion()
local ok, value = pcall(require, "kamareversion")
if not ok then return nil end
if type(value) == "string" and value ~= "" then return value end
if type(value) == "table" then
local version = value.version or value.VERSION
if type(version) == "string" and version ~= "" then return version end
end
return nil
end
--- 模块文件路径:借任一公开函数反查,不扫 package.path。
--- 归一重复斜杠:KOReader 的 `extra_plugin_paths` 带尾斜杠,data 目录里的插件会被拼成
--- `plugins//kamare.koplugin`,原样显示会让人以为路径写错了(文件系统本身不介意)。
---@param mod table
---@return string|nil
local function modulePath(mod)
for _idx, name in ipairs({ "status", "summary", "enqueue", "delete", "open" }) do
if type(mod[name]) == "function" then
local ok, info = pcall(debug.getinfo, mod[name], "S")
local source = ok and info and info.source
if type(source) == "string" and source:sub(1, 1) == "@" then
return (source:sub(2):gsub("/+", "/"))
end
end
end
return nil
end
---@param mod table
---@return KamareProbe
local function enhancedProbe(mod)
local api_version = tonumber(mod.api_version)
local capabilities = type(mod.capabilities) == "table" and mod.capabilities or {}
local ok = api_version == 1
return {
ok = ok,
state = ok and "enhanced" or "incompatible",
reason = ok and nil or "major_mismatch",
api_version = api_version,
capabilities = capabilities,
version = kamareVersion(),
path = modulePath(mod),
}
end
---@param official boolean
---@return KamareProbe
local function missingProbe(official)
return {
ok = false,
state = official and "official" or "missing",
reason = "missing",
api_version = nil,
capabilities = nil,
version = kamareVersion(),
path = nil,
}
end
--- 清空进程内记忆(测试缝;Registry.reload 不经过这里,探测态本就与源实例无关)。
function Cache.reset()
memo = nil
mirrored = nil
mirror_failed = false
logged = {}
shelves = {}
active = nil
pause_reason_logged = {}
end
---@return KamareProbe
function Cache.probe()
if memo then return memo end
local mod = loadModule("kamarecache")
if mod then
local result = enhancedProbe(mod)
-- 只有增强版值得记:官方 / 不兼容 / 未安装都要能随安装或升级立刻变化。
if result.ok then memo = result end
logProbe(result)
return result
end
local result = missingProbe(legacyAvailable())
logProbe(result)
return result
end
--- 重新探测(设置页的「重新检测」):清掉成功记忆再探;结果没变则不重复记日志。
---@return KamareProbe
function Cache.reprobe()
memo = nil
return Cache.probe()
end
--- 插件根目录:kamare 已装用它当前所在目录(就地替换),否则用月读自己的。
---@param own_path string|nil book.koplugin 目录
---@return string
function Cache.pluginsDir(own_path)
local path = Cache.probe().path
local installed = type(path) == "string" and path:gsub("/+", "/"):match("^(.*)/[^/]+%.koplugin/")
if installed then return installed end
if type(own_path) == "string" and own_path ~= "" then
local own = own_path:gsub("/+", "/"):gsub("/+$", "")
return own:match("^(.*)/[^/]+$") or own
end
local source = debug.getinfo(1, "S").source
if type(source) == "string" and source:sub(1, 1) == "@" then source = source:sub(2) end
-- 本文件在 <plugins>/moonsource-kavita.koplugin/moonsource_kavita/,往上三级
return source:match("^(.*)/[^/]+%.koplugin/moonsource_kavita/[^/]+$") or "plugins"
end
--- 功能清单:kamare 随包提供的用户可见功能文案(kamarefeatures.lua)。
--- 只用于展示;缺失 / api_version 不符 / 结构不合法都当没有清单,不做能力推断回退。
---@param probe KamareProbe|nil
---@return string|nil
function Cache.featureText(probe)
probe = probe or Cache.probe()
if not probe.ok then return nil end
local ok, manifest = pcall(require, "kamarefeatures")
if not ok or type(manifest) ~= "table" or manifest.api_version ~= 1 then return nil end
local list = manifest.features
if type(list) ~= "table" then return nil end
local parts, seen = {}, {}
for _idx, item in ipairs(list) do
if type(item) == "string" and item ~= "" and not seen[item] then
seen[item] = true
parts[#parts + 1] = item
if #parts == 8 then break end
end
end
if #parts == 0 then return nil end
return table.concat(parts, " · ")
end
--- 能力是否可用。`open` 是唯一允许退回 legacy 通道的能力(02 A4)。
---@param cap string|nil
---@return boolean
function Cache.available(cap)
local probe = Cache.probe()
if not probe.ok then
return cap == "open" and legacyAvailable() or false
end
if cap == nil then return true end
local capabilities = probe.capabilities or {}
if cap == "open" then
return capabilities.open == true or legacyAvailable()
end
return capabilities[cap] == true
end
--- 源配置:只读 base_url / api_key,其它键与缓存无关。
---@return table
local function config()
local value = require("utils.settings").getSource("kavita")
return type(value) == "table" and value or {}
end
--- 与 Client.new 同口径:去尾斜杠、去首尾空白;空串当未给。
---@param url any
---@return string|nil
local function normBase(url)
local text = Text.rtrimSlashes(Text.trim(url))
return text ~= "" and text or nil
end
--- API Key 里的空白一律去掉(粘贴时常带换行 / 空格)。
---@param key any
---@return string|nil
local function normKey(key)
local text = Text.stripWhitespace(key)
return text ~= "" and text or nil
end
--- 当前服务器;未配置返回 nil(调用方按 unknown_server 静默降级)。
---@return string|nil
local function targetBase()
return normBase(config().base_url)
end
--- 能力对应的 kamare 函数名。
local KAMARE = {
status = "status",
summary = "summary",
resume = "resume_page",
queue = "queue_state",
index = "index",
enqueue = "enqueue",
delete = "delete",
estimate = "estimate",
open = "open",
server = "register_server",
chapters = "chapters",
delete_all = "delete_all",
}
--- 取能力对应的函数:缺能力 / 缺函数一律 unsupported(调用点不各写一套)。
--- 队列控制是同一个能力(queue_control)下的三个动作,由 fn_name 指定函数。
---@param name string
---@param fn_name string|nil 缺省为 KAMARE[name]
---@return table|nil mod, string|nil code, function|nil fn
local function capability(name, fn_name)
local probe = Cache.probe()
if not probe.ok then return nil, "unsupported" end
if (probe.capabilities or {})[name] ~= true then return nil, "unsupported" end
local mod = loadModule("kamarecache")
if not mod then return nil, "unsupported" end
local fn = mod[fn_name or KAMARE[name]]
if type(fn) ~= "function" then return nil, "unsupported" end
return mod, nil, fn
end
--- 写:把 moon 的服务器地址 + API Key 镜像给 kamare(幂等、不联网、不传 name)。
---@param base_url string|nil
---@param api_key string|nil
---@return string|nil server_key, string|nil code, string|nil message
function Cache.registerServer(base_url, api_key)
local mod, code, fn = capability("server")
if not mod then return nil, code end
local url = normBase(base_url) or targetBase()
local key = normKey(api_key) or normKey(config().api_key)
if not url then return nil, "base_url_required" end
if not key then return nil, "api_key_required" end
local server_key, err, message = fn({ base_url = url, api_key = key })
if server_key then
mirrored = url .. "\0" .. key
mirror_failed = false
else
mirror_failed = true
logOnce("mirror|" .. tostring(err), "cache mirror failed code=" .. tostring(err))
end
return server_key, err, message
end
--- 本次会话内镜像是否失败过(设置页的第五态)。
---@return boolean
function Cache.mirrorFailed()
return mirror_failed
end
--- 镜像兜底:读路径首次操作前一次;写路径每次幂等重放。
---@param write boolean
---@param base_url string|nil
---@param api_key string|nil
---@return boolean
local function ensureMirror(write, base_url, api_key)
local probe = Cache.probe()
if not probe.ok or (probe.capabilities or {}).server ~= true then return false end
local url = normBase(base_url) or targetBase()
local key = normKey(api_key) or normKey(config().api_key)
if not url or not key then return false end
if not write and mirrored == url .. "\0" .. key then return true end
return Cache.registerServer(url, key) ~= nil
end
---@param list any
---@param value any
---@return boolean
local function includes(list, value)
if type(list) ~= "table" then return false end
for _idx, item in ipairs(list) do
if tostring(item) == tostring(value) then return true end
end
return false
end
--- 这一章是不是正在 kamare 查看器里(删除按钮据此置灰)。
---@param chapter_id any
---@return boolean
function Cache.isChapterOpen(chapter_id)
if not active then return false end
if tostring(active.chapter_id) ~= tostring(chapter_id) then return false end
local base_url = targetBase()
return base_url == nil or active.base_url == base_url
end
--- 关闭回调包一层:先清 active,再交给调用方(source 写双行进度)。
---@param opts table
---@param base_url string|nil
---@param chapter_id any
---@return table
local function wrapClose(opts, base_url, chapter_id)
local user_close = opts.on_close
local wrapped = {}
for key, value in pairs(opts) do wrapped[key] = value end
wrapped.on_close = function(page, total)
if active and tostring(active.chapter_id) == tostring(chapter_id)
and (base_url == nil or active.base_url == base_url) then
active = nil
end
if user_close then return user_close(page, total) end
end
return wrapped
end
--- kamare 的页尺寸接口页号有时从 0 起,查看器只认从 1 起;拿不到就不预热。
---@param client table
---@param chapter_id any
---@return table|nil
local function dimensions(client, chapter_id)
if type(client.getFileDimensions) ~= "function" then return nil end
local dims, code = client:getFileDimensions(chapter_id)
if type(dims) ~= "table" or type(code) ~= "number" or code < 200 or code >= 300 then return nil end
local zero_based = false
for _idx, item in ipairs(dims) do
if item.pageNumber == 0 then zero_based = true end
end
if zero_based then
for _idx, item in ipairs(dims) do
if type(item.pageNumber) == "number" then item.pageNumber = item.pageNumber + 1 end
end
end
return dims
end
--- 官方 / 旧版 kamare 的查看器通道:02 A4 要求官方版(无 kamarecache)与增强版缺 `open` 时
--- 仍保住今天的在线看图,所以这条通道留在适配层;source.lua 里那份重复实现已删(12 号票)。
---@param opts table
---@return table|nil viewer, string|nil code, string|nil message
local function legacyOpen(opts)
local Viewer = loadModule("kamareimageviewer")
if not Viewer or type(Viewer.new) ~= "function" then return nil, "unsupported" end
local entry = opts.entry or {}
if (tonumber(entry.pages) or 0) <= 0 then return nil, "no_pages" end
local client = loadModule("kavitaclient")
if not client then return nil, "open_failed", _("打开漫画阅读器失败") end
local ok, viewer, code, message = pcall(function()
client.base_url, client.api_key, client.auth_method, client.bearer =
opts.base_url, opts.api_key, "apiKey", nil
if not client.device_id or client.device_id == "" then client.device_id = "moon-kavita" end
local images = client:streamChapter(entry.chapterId)
if type(images) ~= "table" then return nil, "open_failed", _("打开漫画阅读器失败") end
local LuaSettings = require("luasettings")
local spec = Viewer:new{
images_list_data = images,
images_list_nb = entry.pages,
title = opts.title,
fullscreen = true,
metadata = {
seriesName = opts.title,
seriesId = entry.seriesId,
libraryId = entry.libraryId,
volumeId = entry.volumeId,
chapterId = entry.chapterId,
chapter = { id = entry.chapterId, volumeId = entry.volumeId, pages = entry.pages },
startPage = opts.start_page,
content_type = "chapter",
},
preloaded_dimensions = dimensions(client, entry.chapterId),
kamare_settings = LuaSettings:open(require("datastorage"):getSettingsDir() .. "/kamare.lua"),
on_close_callback = opts.on_close,
on_next_chapter_callback = opts.on_next and function(next_id)
require("ui/uimanager"):nextTick(function() opts.on_next(next_id) end)
end or nil,
}
if spec._aborted then return nil, "viewer_running", _("漫画阅读器已在运行") end
require("ui/uimanager"):show(spec)
return spec
end)
if not ok then
logger.warn("kavita.cache legacy open failed", viewer)
return nil, "open_failed", _("打开漫画阅读器失败")
end
return viewer, code, message
end
--- 增强版是否接管打开:起始页 / 离线全归 kamare(journal + 缓存)。
--- 官方版或增强版缺 `open` 时退回 legacy 查看器,起始页要 moon 自己给。
---@return boolean
function Cache.enhancedOpen()
local probe = Cache.probe()
if not probe.ok or (probe.capabilities or {}).open ~= true then return false end
local mod = loadModule("kamarecache")
return mod ~= nil and type(mod.open) == "function"
end
--- 打开一卷:enhanced 有 open 交 kamare 判缓存 / 离线 / 起始页;否则退回 legacy 查看器。
---@param opts { base_url: string|nil, api_key: string|nil, entry: table, title: string,
--- start_page: integer|nil, on_close: function|nil, on_next: function|nil }
---@return table|nil viewer, string|nil code, string|nil message
function Cache.open(opts)
opts = type(opts) == "table" and opts or {}
local entry = opts.entry or {}
local base_url = normBase(opts.base_url) or targetBase()
local api_key = normKey(opts.api_key) or normKey(config().api_key)
if not base_url then return nil, "unknown_server" end
local probe = Cache.probe()
local mod = probe.ok and loadModule("kamarecache") or nil
local use_enhanced = Cache.enhancedOpen()
local viewer, code, message
if use_enhanced then
ensureMirror(false, base_url, api_key)
viewer, code, message = mod.open(wrapClose(opts, base_url, entry.chapterId))
else
local next_opts = {}
for key, value in pairs(opts) do next_opts[key] = value end
next_opts.base_url, next_opts.api_key = base_url, api_key
viewer, code, message = legacyOpen(wrapClose(next_opts, base_url, entry.chapterId))
end
if viewer then
active = { base_url = base_url, chapter_id = entry.chapterId }
elseif code then
logOnce("open|" .. tostring(entry.chapterId) .. "|" .. code,
"cache open cid=" .. tostring(entry.chapterId) .. " code=" .. tostring(code))
end
return viewer, code, message
end
--- 让书架投影失效(手动刷新书架 / Registry.reload 都走这里)。
function Cache.resetShelf()
shelves = {}
end
--- 「已缓存」的唯一口径:complete 或 stale(stale 与 complete 等价,03 A3)。
--- 同时接受两种形状:Cache.status 的章状态(state)与书架 index 的系列摘要(complete/stale)。
---@param status table|nil
---@return boolean
function Cache.isCached(status)
if type(status) ~= "table" then return false end
if status.state == "complete" or status.state == "stale" then return true end
if status.state ~= nil then return false end
return status.complete == true or status.stale == true
end
--- 只读:书架投影(series_ids / mark / cover),按服务器记忆;无 TTL。
---@return ShelfCacheProjection|nil
function Cache.shelf()
local base_url = targetBase()
if not base_url then return nil end
if shelves[base_url] then return shelves[base_url] end
local index = Cache.index()
if not index then return nil end
local projection = { series_ids = {}, mark = {}, cover = {} }
local series = type(index.series) == "table" and index.series or {}
for key, info in pairs(series) do
if type(info) == "table" then
local stable_id = tostring(info.seriesId or key)
-- 只有 complete / stale 算「已缓存」;queued / downloading 只有 .part,离线打不开。
if (tonumber(info.chapters) or 0) > 0 and Cache.isCached(info) then
projection.series_ids[stable_id] = true
projection.mark[stable_id] = true
end
local cover = info.coverPath
if type(cover) == "string" and cover ~= "" and fileExists(cover) then
projection.cover[stable_id] = cover
end
end
end
shelves[base_url] = projection
return projection
end
--- 只读:缓存占用(设置页与「缓存占用」展示;确认框一律用 estimate)。
---@return table|nil, string|nil, string|nil
function Cache.summary()
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("summary")
if not mod then return nil, code end
ensureMirror(false)
return fn(base_url)
end
--- 只读:所有服务器(含未关联)的合计占用;未配置服务器时用它算「清理全部」的预览。
---@return table|nil, string|nil, string|nil
function Cache.summaryAll()
local mod, code, fn = capability("summary")
if not mod then return nil, code end
return fn(nil)
end
--- 只读:当前服务器的清理计划(每章 facts)。series_id 可选。
---@param series_id any|nil
---@return table[]|nil, string|nil, string|nil
function Cache.chapters(series_id)
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("chapters")
if not mod then return nil, code end
ensureMirror(false)
return fn(base_url, series_id)
end
--- 只读:已缓存章的状态(complete / stale / partial)。
---@param chapter_id any
---@return table|nil, string|nil, string|nil
function Cache.status(chapter_id)
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("status")
if not mod then return nil, code end
ensureMirror(false)
return fn(base_url, chapter_id)
end
--- 只读:续读页(journal > snapshot > nil)。
---@param chapter_id any
---@param series_id any|nil
---@return table|nil, string|nil, string|nil
function Cache.resumePage(chapter_id, series_id)
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("resume")
if not mod then return nil, code end
ensureMirror(false)
return fn(base_url, chapter_id, series_id)
end
--- 只读:按当前服务器过滤后的队列状态。
---@return table|nil, string|nil, string|nil
function Cache.queueState()
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("queue")
if not mod then return nil, code end
ensureMirror(false)
local state, err, message = fn(base_url)
if type(state) == "table" then
-- 1 秒轮询:只在暂停原因变化时记一行,恢复后清空,下次同原因再记。
if state.pause_reason ~= nil and state.pause_reason ~= "" then
if pause_reason_logged[base_url] ~= state.pause_reason then
pause_reason_logged[base_url] = state.pause_reason
logger.info("queue paused reason=" .. tostring(state.pause_reason))
end
else
pause_reason_logged[base_url] = nil
end
end
return state, err, message
end
--- 批量暂停(全局队列,契约明确作用于所有服务器)。
---@return boolean|nil, string|nil, string|nil
function Cache.queuePause()
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("queue_control", "queue_pause")
if not mod then return nil, code end
ensureMirror(true)
local ok, err, message = fn(base_url)
logWrite("queue_pause", nil, err)
if ok then Cache.resetShelf() end
return ok, err, message
end
--- 批量恢复。
---@return boolean|nil, string|nil, string|nil
function Cache.queueResume()
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("queue_control", "queue_resume")
if not mod then return nil, code end
ensureMirror(true)
local ok, err, message = fn(base_url)
logWrite("queue_resume", nil, err)
if ok then Cache.resetShelf() end
return ok, err, message
end
--- 只重试 queued / failed 的条目。
---@param chapter_ids any[]
---@return boolean|nil, string|nil, string|nil
function Cache.queueRetry(chapter_ids)
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("queue_control", "queue_retry")
if not mod then return nil, code end
ensureMirror(true)
local ok, err, message = fn(base_url, chapter_ids)
logWrite("queue_retry", chapter_ids, err)
if ok then Cache.resetShelf() end
return ok, err, message
end
--- 只读:书架索引投影(一次全量,不分页)。
---@return table|nil, string|nil, string|nil
function Cache.index()
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("index")
if not mod then return nil, code end
ensureMirror(false)
return fn(base_url)
end
--- 写:入队下载。成功时第三个返回值是 { chapters, bytes, available }。
---@param entries table[]
---@return boolean|nil, string|nil, any, table|nil
function Cache.enqueue(entries)
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("enqueue")
if not mod then return nil, code end
ensureMirror(true)
local ok, err, message, detail = fn(base_url, entries)
logWrite("enqueue", entryIds(entries), err)
if ok then Cache.resetShelf() end
return ok, err, message, detail
end
--- 写:删除缓存(不碰 journal)。正在查看器里打开的章本地先拦一次(与 kamare 双层保护)。
---@param chapter_ids any[]
---@return boolean|nil, string|nil, string|nil, integer|nil
function Cache.delete(chapter_ids)
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
if active and active.base_url == base_url and includes(chapter_ids, active.chapter_id) then
return nil, "chapter_open"
end
local mod, code, fn = capability("delete")
if not mod then return nil, code end
ensureMirror(true)
local ok, err, message, deleted = fn(base_url, chapter_ids)
logWrite("delete", chapter_ids, err)
if ok then Cache.resetShelf() end
return ok, err, message, deleted
end
--- 写:清空所有服务器(含未关联)。成功时第四个返回值是 { chapters, bytes } 估算。
---@return boolean|nil, string|nil, string|nil, table|nil
function Cache.deleteAll()
local mod, code, fn = capability("delete_all")
if not mod then return nil, code end
local ok, err, third = fn()
logWrite("delete_all", nil, err)
if ok then
Cache.resetShelf()
return true, nil, nil, type(third) == "table" and third or nil
end
return nil, err, third
end
--- 只读:下载前估算(数量 / 峰值 / 可用 / 裁决),不写盘、不入队、不建 serverKey。
---@param entries table[]
---@return table|nil, string|nil, string|nil, table|nil
function Cache.estimate(entries)
local base_url = targetBase()
if not base_url then return nil, "unknown_server" end
local mod, code, fn = capability("estimate")
if not mod then return nil, code end
ensureMirror(false)
return fn(base_url, entries)
end
--- 错误码 → 用户可见文案(02 A9)。调用点只问这张表,不各写一套。
local SILENT = {
unknown_server = true,
already_cached = true,
already_queued = true,
}
local CODE_TEXT = {
offline_not_cached = _("这一卷还没缓存,联网后可下载"),
viewer_running = _("漫画阅读器已在运行"),
no_pages = _("这一卷没有可显示的页面"),
settings_write_failed = _("无法写入 kamare 配置"),
retry_no_entry = _("没有可重试的任务"),
chapter_open = _("正在阅读这一卷,关闭后可以删除"),
unsupported = _("需要安装带缓存接口的增强版 kamare"),
base_url_required = _("无法同步配置到 kamare"),
api_key_required = _("无法同步配置到 kamare"),
delete_incomplete = _("部分缓存未能删除(权限或存储错误)"),
}
local SPACE_CODES = {
not_enough_space = true,
cache_limit_reached = true,
low_space = true,
}
--- 字节数 → 一行「x.x MB」;不做单位阶梯,容量判断只看数量级。
---@param bytes any
---@return string
function Cache.sizeText(bytes)
local value = tonumber(bytes)
if not value then return _("未知") end
return T(_("%1 MB"), string.format("%.1f", value / (1024 * 1024)))
end
--- 空间错误的 code + detail 文案。detail 由 kamare 给(不在 moon 复制阈值)。
---@param code string
---@param detail table|nil
---@return string
local function spaceText(code, detail)
detail = type(detail) == "table" and detail or {}
if code == "not_enough_space" then
return T(_("空间不足:需要 %1,可用 %2"), Cache.sizeText(detail.needed), Cache.sizeText(detail.available))
elseif code == "cache_limit_reached" then
return T(_("缓存空间已满:需要 %1,上限 %2"), Cache.sizeText(detail.needed), Cache.sizeText(detail.limit))
end
return T(_("可用空间低于 %1,清理后再下载"), Cache.sizeText(detail.low_water))
end
--- code → 文案;静默码返回 nil。
---@param code string|nil
---@param message string|nil kamare 的原话(未知 code 时优先)
---@param detail table|nil 空间错误的 { needed, available, used, limit, low_water }
---@return string|nil
function Cache.message(code, message, detail)
if code == nil or SILENT[code] then return nil end
if SPACE_CODES[code] then return spaceText(code, detail) end
return CODE_TEXT[code] or message or _("缓存操作失败")
end
--- 清理计划 → 汇总。`filter` 为 "read" 时只算已读;`toc_read` 是可选的服务端进度
--- (chapterId → pagesRead),用于补上 kamare 离线拿不到的第三源。
---@param entries table[]|nil
---@param filter "all"|"read"
---@param toc_read table<string, number>|nil
---@return { chapters: integer, bytes: integer, ids: any[], queued: integer, open: boolean }
function Cache.plan(entries, filter, toc_read)
local out = { chapters = 0, bytes = 0, ids = {}, queued = 0, open = false }
for _idx, entry in ipairs(type(entries) == "table" and entries or {}) do
local pages = tonumber(entry.pages) or 0
local server_read = toc_read and (tonumber(toc_read[tostring(entry.chapterId)]) or 0) or 0
local read = entry.read == true or (pages > 0 and server_read >= pages)
if filter ~= "read" or read then
out.chapters = out.chapters + 1
out.bytes = out.bytes + (tonumber(entry.bytes) or 0)
out.ids[#out.ids + 1] = entry.chapterId
if entry.queued then out.queued = out.queued + 1 end
if entry.open then out.open = true end
end
end
return out
end
--- estimate 的裁决 → 确认框 / toast 文案;可下载时 nil。
---@param result table|nil
---@return string|nil
function Cache.estimateMessage(result)
if type(result) ~= "table" or result.ok then return nil end
if result.reason == "nothing_to_do" then return _("全部已缓存或正在下载") end
if result.reason == "space" then
return T(_("空间不足:需要 %1,可用 %2"), Cache.sizeText(result.bytes), Cache.sizeText(result.available))
end
if result.reason == "low_water" then
return T(_("可用空间不足(剩余 %1),清理后再下载"), Cache.sizeText(result.available))
end
return nil
end
--- 逐条 lastError 的特征 → 文案(07 A7)。moon 不加自动重试,只负责解释。
local FAILURE_PATTERNS = {
{ "http 403", _("服务器拒绝下载(403),检查 API Key / 权限") },
{ "not an archive", _("下载内容不完整或不是有效压缩包") },
{ "size ", _("下载内容不完整或不是有效压缩包") },
{ "extracted", _("下载内容不完整或不是有效压缩包") },
{ "sink write failed", _("存储空间不足或写入失败") },
{ "no space", _("存储空间不足或写入失败") },
{ "disk full", _("存储空间不足或写入失败") },
{ "socket", _("网络中断或服务器不可达") },
{ "connect", _("网络中断或服务器不可达") },
{ "closed", _("网络中断或服务器不可达") },
{ "truncated", _("网络中断或服务器不可达") },
{ "timeout", _("网络中断或服务器不可达") },
}
---@param last_error string|nil
---@return string|nil
function Cache.failureText(last_error)
if type(last_error) ~= "string" or last_error == "" then return nil end
local lowered = last_error:lower()
for _idx, pattern in ipairs(FAILURE_PATTERNS) do
if lowered:find(pattern[1], 1, true) then return pattern[2] end
end
return T(_("缓存失败:%1"), last_error)
end
return Cache
@@ -0,0 +1,257 @@
--[[--
漫画缓存的后台任务登记:把「缓存这一批卷」登记成一条 passive 后台任务。
kamare 仍是唯一的执行者与写入者:这里不下载、不取消队列,只按本批 chapterId 轮询
`queue_state` / `status`,把进度报给 `workers.tasks`,让顶栏「后台任务」看得到、缓存期间不自动休眠、
关掉卷列表后仍有完成提示。队列是全局的(按服务器过滤),所以进度只数本批自己那几卷。
local handle = CacheTask.track{ series = series, entries = entries } -- 入队成功后
handle.mute(true) -- 页面自己的进度框负责提示时静音(默认不静音,由任务 toast)
handle.add(more) -- 同一部又有卷入队 / 重试失败项:并进同一条任务,终态清掉重新观察
handle.cancel() -- 只停轮询,不动 kamare 队列(队列控制仍走 Cache.queuePause/Resume/Retry)
@module moonsource_kavita.cache_task
--]]
local _ = require("l10n").get("moonsource_kavita")
local T = require("ffi/util").template
local Cache = require("moonsource_kavita.cache")
local CacheTask = {}
--- 轮询间隔:下载中 1 秒;暂停时 5 秒(用户可能几小时不处理,别每秒读一次索引)。
local POLL_SECONDS = 1
local PAUSED_SECONDS = 5
--- 连续这么多拍都看不到本批的队列项、也没落地:kamare 重启 / 队列被清,按中断收尾。
local MAX_IDLE_TICKS = 5
--- 队列任务 → 本批状态与句柄;同 key 再入队时并进去。弱键:任务出队后随之回收。
---@type table<BookTask, { st: table, handle: table }>
local tracked = setmetatable({}, { __mode = "k" })
---@param text string|nil
local function toast(text)
if not text then return end
require("ui.themes.widgets.toast"):new{ text = text, timeout = 2 }:show()
end
--- 队列条目按 chapterId 归一成字符串键(kamare 的键可能是数字)。
---@param queue table|nil
---@return table
function CacheTask.queueEntries(queue)
local out = {}
for key, entry in pairs(type(queue) == "table" and queue.entries or {}) do
out[tostring(key)] = entry
end
return out
end
---@param queue table|nil
---@return boolean
function CacheTask.queuePaused(queue)
return type(queue) == "table" and (queue.state == "paused" or queue.pause_reason ~= nil)
end
---@param st table
local function stopTimer(st)
if st.timer then
require("ui/uimanager"):unschedule(st.timer)
st.timer = nil
end
end
---@param st table
local function schedule(st)
if st.settled or st.timer then return end
local delay = st.paused and PAUSED_SECONDS or POLL_SECONDS
st.timer = require("ui.guard").wrap("kavita cache task poll", function()
st.timer = nil
st:poll()
end)
require("ui/uimanager"):scheduleIn(delay, st.timer)
end
--- 本批任务的可变状态:track / 轮询 / handle 共用一份。
---@param opts table
---@return table
local function newState(opts)
local series = type(opts.series) == "table" and opts.series or {}
local st = {
title = series.title or series.stable_id,
ids = {}, -- 顺序数组,去重
seen = {}, -- tostring(id) -> true
landed = {}, -- tostring(id) -> 终态(已缓存或失败)
failed = {}, -- tostring(id) -> true
titles = {}, -- tostring(id) -> 卷名
total = 0,
ok_count = 0,
idle = 0,
muted = false,
paused = false,
settled = false,
timer = nil,
report = nil,
call_done = nil,
}
--- 并进一批卷:新 id 追加;已有的清掉终态,重试 / 重新入队后下一拍重新观察。
---@param entries table[]
function st:add(entries)
for _idx, entry in ipairs(type(entries) == "table" and entries or {}) do
local id = entry.chapterId or entry.chapter_id or entry.id
if id ~= nil then
local key = tostring(id)
if not self.seen[key] then
self.seen[key] = true
self.ids[#self.ids + 1] = id
end
self.landed[key] = nil
self.failed[key] = nil
self.titles[key] = entry.title
end
end
self.total = #self.ids
self.idle = 0
end
--- 报表一次;没有 run 之前(还在排队)跳过。
---@param text string|nil
function st:emit(text)
if self.report then self.report(text, self.ok_count, self.total) end
end
--- 收尾:只结算一次;静音时不出提示(页面自己的进度框已经报过)。
---@param interrupted boolean|nil
---@return table
function st:settle(interrupted)
if self.settled then return { ok = false } end
self.settled = true
stopTimer(self)
-- 最后一卷落地的那一拍直接 settle,不会走到 poll 末尾的 emit:补报一次最终计数,
-- 否则任务卡片停在上一拍的「已完成 2/3」。
self:emit(nil)
local failed_count = 0
for key in pairs(self.failed) do
if self.seen[key] then failed_count = failed_count + 1 end
end
if not self.muted then
if interrupted and self.ok_count == 0 then
toast(_("缓存已中断"))
elseif failed_count == 0 then
toast(T(_("已缓存 %1 卷"), self.total))
else
toast(T(_("%1 卷成功,%2 卷失败"), self.ok_count, failed_count))
end
end
local result = {
ok = failed_count == 0 and not interrupted,
cached = self.ok_count,
total = self.total,
failed = failed_count,
interrupted = interrupted or nil,
}
if self.call_done then self.call_done(result) end
return result
end
--- 每一拍:数本批的终态,报进度;全部落地就收尾。
function st:poll()
self.timer = nil
if self.settled then return end
local queue = Cache.queueState()
local entries = CacheTask.queueEntries(queue)
local remaining, queued_any = 0, false
for _idx, id in ipairs(self.ids) do
local key = tostring(id)
if not self.landed[key] then
local queued = entries[key]
if queued and queued.state == "failed" then
self.landed[key] = true
self.failed[key] = true
elseif Cache.isCached(Cache.status(id)) then
self.landed[key] = true
else
remaining = remaining + 1
if queued then queued_any = true end
end
end
end
local ok_count = 0
for _idx, id in ipairs(self.ids) do
local key = tostring(id)
if self.landed[key] and not self.failed[key] then ok_count = ok_count + 1 end
end
self.ok_count = ok_count
self.paused = CacheTask.queuePaused(queue)
if remaining <= 0 then return self:settle() end
if self.paused then
self.idle = 0
self:emit(queue and queue.pause_reason == "low_space" and _("空间不足,已暂停") or _("已暂停"))
else
local current = queue and queue.current_chapter_id
self:emit(current ~= nil and self.titles[tostring(current)] or nil)
if queued_any then
self.idle = 0
else
-- 本批的卷既没在队列里、也没落地:kamare 重启 / 队列被清,不能永远挂着。
self.idle = self.idle + 1
if self.idle >= MAX_IDLE_TICKS then return self:settle(true) end
end
end
schedule(self)
end
return st
end
--- 登记一条 passive 任务;同一部书已有未结束的任务就并进去。
---@param opts { series: table|nil, entries: table[], key: string|nil }
---@return table|nil handle mute(value): …; add(entries): …; cancel(): …
function CacheTask.track(opts)
opts = type(opts) == "table" and opts or {}
local entries = type(opts.entries) == "table" and opts.entries or {}
if #entries == 0 then return nil end
if not Cache.available("queue") then return nil end
local Tasks = require("workers.tasks")
local series = type(opts.series) == "table" and opts.series or {}
local key = "cache\0kavita\0" .. tostring(opts.key or series.stable_id or series.title or "series")
local live = tracked[Tasks.get(key) or false]
if live then
live.st:add(entries)
live.st:emit(nil)
return live.handle
end
local st = newState(opts)
st:add(entries)
local handle = {}
handle.mute = function(value) st.muted = value ~= false end
handle.add = function(more)
st:add(more)
st:emit(nil)
end
handle.cancel = function() stopTimer(st) end
local task = {
key = key,
kind = "cache",
title = st.title,
passive = true,
-- 队列暂停(空间不足 / 等网络)时不再压自动休眠:一停几小时不能把电耗光。
hold = function() return not st.paused end,
run = function(report, done)
st.report, st.call_done = report, done
st:emit(nil)
schedule(st)
return { cancel = function() stopTimer(st) end }
end,
}
local queued = Tasks.enqueue(task)
if not queued then return nil end
tracked[queued] = { st = st, handle = handle }
handle.task = queued
return handle
end
return CacheTask
@@ -0,0 +1,215 @@
--[[--
Kavita HTTP 客户端:x-api-key 认证,只回 wire,不做领域转换。
调用方先看 configured(),这里不再判。
@module moonsource_kavita.client
--]]
local JSON = require("json")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_kavita")
local T = require("ffi/util").template
--- 单次请求默认超时(秒)。全量书架(`all-v2`)在慢设备 / 慢服务器上 30s 拉不完,
--- 一个请求超时就会中断整轮同步、书架永远加载不出来,所以默认给足,并允许在设置里调大。
local DEFAULT_TIMEOUT = 60
--- 设置里的合法区间:太小等于次次超时,太大等于卡住没法恢复。
local MIN_TIMEOUT = 5
local MAX_TIMEOUT = 600
---@class KavitaClient
---@field base_url string
---@field api_key string
---@field timeout integer 单次请求超时秒(含下载)
local Client = {}
Client.__index = Client
Client.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT
Client.MIN_TIMEOUT = MIN_TIMEOUT
Client.MAX_TIMEOUT = MAX_TIMEOUT
---@param cfg { base_url: string|nil, api_key: string|nil, timeout: integer|string|nil }
---@return KavitaClient
function Client.new(cfg)
local timeout = math.floor(tonumber(cfg.timeout) or DEFAULT_TIMEOUT)
if timeout < MIN_TIMEOUT then timeout = MIN_TIMEOUT end
if timeout > MAX_TIMEOUT then timeout = MAX_TIMEOUT end
return setmetatable({
base_url = Text.rtrimSlashes(cfg.base_url),
api_key = Text.stripWhitespace(cfg.api_key),
timeout = timeout,
}, Client)
end
---@return boolean
function Client:configured()
return self.base_url ~= "" and self.api_key ~= ""
end
--- Kavita 按 User-Agent 识别客户端;不带时设备列表里显示 Unknown Client。
---@return table
function Client:headers()
local device = package.loaded["device"]
local platform = type(device) == "table" and device.isAndroid and device:isAndroid() and "Android" or "Linux"
return { ["x-api-key"] = self.api_key, ["User-Agent"] = "KOReader/MoonBook (" .. platform .. ")" }
end
--- 查询串:单值参数与 `Text.formEncode` 同形;值是数组时展开成重复键
--- (Kavita 的 `Libraries` 过滤器要 `&Libraries=8&Libraries=10`,逗号串会被当成一个库、恒返回 0 条)。
---@param query table
---@return string
local function queryString(query)
local keys = {}
for key in pairs(query) do keys[#keys + 1] = key end
table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
local parts = {}
for _idx, key in ipairs(keys) do
local value = query[key]
if type(value) == "table" then
for _i, item in ipairs(value) do
parts[#parts + 1] = Text.urlEncode(key) .. "=" .. Text.urlEncode(item)
end
elseif value ~= nil then
parts[#parts + 1] = Text.urlEncode(key) .. "=" .. Text.urlEncode(value)
end
end
return table.concat(parts, "&")
end
---@param path string
---@param query table|nil
---@return string
function Client:url(path, query)
if query then return self.base_url .. path .. "?" .. queryString(query) end
return self.base_url .. path
end
--- 原始请求:2xx 回 cb(res)(带状态码与响应头,分页接口要读 `Pagination` 头);
--- 401/403 与非 2xx 一律 cb(nil, err, code)。
---@param method string
---@param path string
---@param query table|nil
---@param body table|nil JSON 请求体
---@param cb fun(res: table|nil, err: string|nil, code: integer|nil)
---@return HttpJob
function Client:requestRes(method, path, query, body, cb)
local headers = self:headers()
local payload
if body then
headers["Content-Type"] = "application/json"
payload = JSON.encode(body)
end
return Request.request({
url = self:url(path, query), method = method, headers = headers, body = payload, timeout = self.timeout,
}, function(res, err)
if err or not res then
cb(nil, err and tostring(err) or _("网络请求失败"))
return
end
local code = tonumber(res.code)
if code == 401 or code == 403 then
cb(nil, _("Kavita API Key 无效或无权限"), code)
elseif not Request.ok(code) then
cb(nil, T(_("请求失败 (HTTP %1)"), tostring(code)), code)
else
-- 只规范化 body;响应头原样带着(`Request.header` 认 Turbo 头与普通表两种)。
cb({ code = code, headers = res.headers, body = Text.stripBom(res.body or "") }, nil, code)
end
end)
end
--- 原始请求:2xx 回 cb(body),否则 cb(nil, err, code)。
---@param method string
---@param path string
---@param query table|nil
---@param body table|nil JSON 请求体
---@param cb fun(body: string|nil, err: string|nil, code: integer|nil)
---@return HttpJob
function Client:request(method, path, query, body, cb)
return self:requestRes(method, path, query, body, function(res, err, code)
cb(res and res.body, err, code)
end)
end
--- JSON 解码:写接口成功时回空体,按 {} 交回;服务端或反代可能回 HTML 错误页,
--- 解析失败按请求失败处理,不让异常冒到回调链外。
---@param raw string
---@return table|nil, string|nil
local function decodeJson(raw)
if Text.trim(raw) == "" then return {} end
local ok, data = pcall(JSON.decode, raw)
if ok and type(data) == "table" then return data end
return nil, _("响应不是 JSON")
end
--- JSON 请求。
---@param method string
---@param path string
---@param query table|nil
---@param body table|nil
---@param cb fun(data: table|nil, err: string|nil, code: integer|nil)
---@return HttpJob
function Client:json(method, path, query, body, cb)
return self:request(method, path, query, body, function(raw, err, code)
if not raw then
cb(nil, err, code)
return
end
local data, derr = decodeJson(raw)
cb(data, derr, code)
end)
end
--- 分页接口的 JSON 请求:Kavita 把分页信息放在响应头 `Pagination` 里(不在 body),
--- 回调第四参是本页声明的总页数(缺失 / 不可信时为 nil,调用方自行兜底)。
--- 头的内容只由 client 解释,源不必碰 `http.request`。
---@param method string
---@param path string
---@param query table|nil
---@param body table|nil
---@param cb fun(data: table|nil, err: string|nil, code: integer|nil, pages: integer|nil)
---@return HttpJob
function Client:jsonPaged(method, path, query, body, cb)
return self:requestRes(method, path, query, body, function(res, err, code)
if not res then
cb(nil, err, code)
return
end
local data, derr = decodeJson(res.body)
cb(data, derr, code, Client.totalPages(Request.header(res, "Pagination")))
end)
end
--- `Pagination` 头 → 总页数:`{"currentPage":1,"itemsPerPage":200,"totalItems":316,"totalPages":2}`。
--- 缺失 / 解析不出 / 负数一律回 nil(当分页信息不可信),调用方按「本页拉满就还有下一页」兜底。
---@param raw string|nil
---@return integer|nil
function Client.totalPages(raw)
if type(raw) ~= "string" or raw == "" then return nil end
local ok, data = pcall(JSON.decode, raw)
if not ok or type(data) ~= "table" then return nil end
local pages = tonumber(data.totalPages)
if not pages or pages < 0 then return nil end
return math.floor(pages)
end
--- 下载一卷原文件。Request.download 遇到非 2xx 也会落盘,这里删掉并报错。
---@param chapter_id integer
---@param dest string
---@param on_progress fun(bytes: number, total: number|nil)
---@param cb fun(ok: boolean, err: string|nil)
---@return HttpJob
function Client:download(chapter_id, dest, on_progress, cb)
return Request.download({
url = self:url("/api/Download/chapter", { chapterId = chapter_id }),
headers = self:headers(), timeout = self.timeout, on_progress = on_progress,
}, dest, function(ok, err, res)
if ok and not Request.ok(res and res.code) then
os.remove(dest)
ok, err = false, T(_("请求失败 (HTTP %1)"), tostring(res and res.code))
end
cb(ok, err and tostring(err))
end)
end
return Client
@@ -0,0 +1,144 @@
--[[--
卷列表与系列页共用的「继续阅读」目标。
主线 = 最远碰过的那一卷(有进度);这一卷读完就顺延到下一卷,全读完回到第一卷(重读)。
`updated_at` 只用来标记「上次翻阅」,不参与选卷——回头翻旧卷不会把入口拽回去
(Kavita 的 continue-point 是「最早未读完」,正是会被回顾劫持的那种)。
纯函数:不读网、不读盘,进度与时间由调用方注入。
@module moonsource_kavita.continue_point
--]]
local T = require("ffi/util").template
local _ = require("l10n").get("moonsource_kavita")
local M = {}
--- 卷名:优先 toc 的标题;没有、或退化成系列名时兜底「第 N 卷」。
---@param entry table|nil
---@param series_title string|nil
---@return string
function M.label(entry, series_title)
local title = entry and entry.title
if type(title) ~= "string" or title == "" or title == series_title then
local n = tonumber(entry and (entry.idx or entry.number))
return n and T(_("第 %1 卷"), n) or "?"
end
return title
end
---@param target ContinueTarget
---@param series_title string|nil
---@return string text, string|nil caption
function M.describe(target, series_title)
local label = M.label(target.entry, series_title)
local text, caption
if target.kind == "done" then
text = T(_("重读 · %1"), label)
elseif target.kind == "fresh" then
text = T(_("开始阅读 · %1"), label)
if target.total_pages > 0 then caption = T(_("共 %1 页"), target.total_pages) end
else
text = T(_("继续阅读 · %1"), label)
if target.total_pages > 0 then
caption = T(_("第 %1/%2 页 · %3%"), target.page, target.total_pages,
math.floor(target.fraction * 100 + 0.5))
end
end
return text, caption
end
---@class ContinueTarget
---@field entry table 要打开的卷
---@field kind "fresh"|"continue"|"done"
---@field fraction number 这一卷的进度 0..1
---@field page number 已读页(用于「第 x/y 页」)
---@field total_pages number
---@field browsed table|nil 上次翻阅且不是主线的卷
--- 选主线。
---@param toc table[] 卷目录(toc 顺序即阅读顺序)
---@param opts table { fraction = fun(entry):number|nil, updated_at = fun(entry):number|nil,
--- page = fun(entry):{page:number,total:number}|nil,
--- complete = fun(entry):boolean }
---@return ContinueTarget|nil
function M.pick(toc, opts)
opts = opts or {}
local entries = {}
for _i, e in ipairs(toc or {}) do
local pages = tonumber(e.pages) or 0
if pages > 0 then
local fraction = opts.fraction and tonumber(opts.fraction(e))
if fraction == nil then
fraction = (tonumber(e.pagesRead) or 0) / pages
end
fraction = math.max(0, math.min(1, fraction))
-- 服务端 / 调用方说这卷已经读完:本机重新打开留下的低进度不改变「已读完」,
-- 否则回顾旧卷会把主线拖回去,列表也会出现「已读 · 1/194 页」。
if (tonumber(e.pagesRead) or 0) >= pages
or (opts.complete and opts.complete(e)) then
fraction = 1
end
entries[#entries + 1] = { entry = e, fraction = fraction }
end
end
if #entries == 0 then return nil end
local last
for i, item in ipairs(entries) do
if item.fraction > 0 then last = i end
end
local target, kind
if not last then
target, kind = entries[1], "fresh"
elseif entries[last].fraction < 1 then
target, kind = entries[last], "continue"
else
local next_item
for i = last + 1, #entries do
if entries[i].fraction < 1 then next_item = entries[i] break end
end
if next_item then
target, kind = next_item, "continue"
else
target, kind = entries[1], "done"
end
end
local total = tonumber(target.entry.pages) or 0
local page
if opts.page then
local got = opts.page(target.entry)
if got then
page = tonumber(got.page)
total = tonumber(got.total) or total
end
end
if not page then page = math.floor(target.fraction * total + 0.5) end
if kind == "fresh" then page = 0 end
-- 「上次翻阅」:本机更新时间最新的一卷;和主线同一卷就不标。
local browsed, browsed_at
if opts.updated_at then
for _i, item in ipairs(entries) do
local ts = tonumber(opts.updated_at(item.entry)) or 0
if ts > 0 and (not browsed_at or ts > browsed_at) then
browsed, browsed_at = item, ts
end
end
end
return {
entry = target.entry,
kind = kind,
fraction = target.fraction,
page = page,
total_pages = total,
browsed = browsed and tostring(browsed.entry.chapterId) ~= tostring(target.entry.chapterId)
and browsed.entry or nil,
}
end
return M
@@ -0,0 +1,48 @@
--[[--
kamare 增强版在线更新:流程在 utils.plugin_update,这里只给 kamare 的目标描述。
版本和 digest 先问 api.ankio.net 的 GitHub 转发,挂了回落 api.github.com。
kamare 已装就地替换,没装装进月读同级插件目录。装好立即重启:旧模块还在内存里。
@module moonsource_kavita.kamare_update
--]]
local Cache = require("moonsource_kavita.cache")
local Updater = require("utils.plugin_update")
local _ = require("l10n").get("moonsource_kavita")
local T = require("ffi/util").template
local NAME = "kamare.koplugin"
local Update = Updater.new({
repo = "backtracker/kamare.koplugin",
api_urls = {
"https://api.ankio.net/gh/repos/backtracker/kamare.koplugin/releases/latest",
"https://api.github.com/repos/backtracker/kamare.koplugin/releases/latest",
},
asset = function() return "kamare.koplugin.zip" end,
archive = "kamare-update.zip",
job = "kamare.update",
installed = function()
local probe = Cache.probe()
return probe.ok and probe.version or nil
end,
name = NAME,
parent = function(plugin) return Cache.pluginsDir(plugin and plugin.path) end,
text = {
checking = _("正在检查 kamare 更新…"),
downloading = _("正在下载 kamare 更新…"),
installing = _("正在安装 kamare 更新…"),
failed = _("kamare 更新失败:%1"),
title = _("更新 kamare"),
latest = function(release) return "kamare " .. release.installed end,
header = function(release)
if release.installed then
return T(_("发现 kamare %1(当前 %2)。下载并完整替换插件目录?"), release.version, release.installed)
end
return T(_("当前未安装可用的 kamare 增强版。安装最新版 %1?"), release.version)
end,
},
})
return Update
@@ -0,0 +1,207 @@
return {
["EPUB 划线同步"] = "EPUB highlight sync",
["书架与卷目录同步(只读)"] = "Bookshelf and volume list sync (read-only)",
["同步 Kavita 书架、电子书与漫画"] = "Sync Kavita bookshelves, ebooks and comics",
["漫画在线阅读与缓存(需 kamare 增强版)"] = "Read and cache comics online (requires enhanced kamare)",
["阅读历史拉取"] = "Fetch reading history",
["下载文件校验失败"] = "Downloaded file failed verification",
["确定退出 Kavita 账号?"] = "Sign out of Kavita?",
["正在下载…"] = "Downloading…",
["章节目录保存失败"] = "Failed to save chapter list",
["请求失败 (HTTP %1)"] = "Request failed (HTTP %1)",
["连接失败"] = "Connection failed",
["打开漫画阅读器失败"] = "Could not open the comic viewer",
["漫画阅读器已在运行"] = "A comic viewer is already running",
["这一卷还没缓存,联网后可下载"] = "This volume is not cached yet; connect to download it",
["这一卷没有可显示的页面"] = "This volume has no pages to show",
["下一卷不在目录里"] = "The next volume is not in the table of contents",
["无法写入 kamare 配置"] = "Could not write the kamare settings",
["没有可重试的任务"] = "Nothing to retry",
["正在阅读这一卷,关闭后可以删除"] = "This volume is open; close it before deleting",
["需要安装带缓存接口的增强版 kamare"] = "Install the enhanced kamare build with the cache API",
["无法同步配置到 kamare"] = "Could not sync settings to kamare",
["%1 MB"] = "%1 MB",
["空间不足:需要 %1,可用 %2"] = "Not enough space: %1 needed, %2 available",
["缓存空间已满:需要 %1,上限 %2"] = "Cache limit reached: %1 needed, %2 limit",
["可用空间低于 %1,清理后再下载"] = "Available space is below %1; free some space and try again",
["缓存操作失败"] = "Cache operation failed",
["全部已缓存或正在下载"] = "Everything is already cached or downloading",
["可用空间不足(剩余 %1),清理后再下载"] = "Not enough free space (%1 left); free some space and try again",
["服务器拒绝下载(403),检查 API Key / 权限"] = "Server refused the download (403); check the API key / permissions",
["下载内容不完整或不是有效压缩包"] = "The download is incomplete or not a valid archive",
["存储空间不足或写入失败"] = "Out of storage space or write failed",
["网络中断或服务器不可达"] = "Network interrupted or server unreachable",
["缓存失败:%1"] = "Cache failed: %1",
["配置同步失败"] = "Settings sync failed",
["增强版 v%1"] = "Enhanced v%1",
["增强版"] = "Enhanced",
["版本不兼容"] = "Incompatible version",
["官方版(无缓存接口)"] = "Official build (no cache API)",
["未安装 / 未启用"] = "Not installed / not enabled",
["连接正常"] = "Connected",
["Kavita %1"] = "Kavita %1",
["未加载"] = "Not loaded",
["获取增强版"] = "Get the enhanced build",
["秒"] = "s",
["检查 Kavita 服务器连接与版本"] = "Check the Kavita server connection and version",
["kamare 增强版"] = "kamare enhanced build",
["点按检查 kamare 增强版更新"] = "Tap to check for kamare enhanced-build updates",
["点按安装 kamare 增强版"] = "Tap to install the kamare enhanced build",
["点按安装兼容的 kamare 增强版"] = "Tap to install a compatible kamare enhanced build",
["点按检查并安装 kamare 增强版"] = "Tap to check for and install the kamare enhanced build",
["官方版"] = "Official build",
[" 也可点上方「kamare 增强版」检查并安装最新版。"] = " Or tap “kamare enhanced build” above to check for and install the latest version.",
["正在检查 kamare 更新…"] = "Checking for kamare updates…",
["更新 kamare"] = "Update kamare",
["发现 kamare %1(当前 %2)。下载并完整替换插件目录?"] = "kamare %1 is available (current %2). Download and replace the plugin directory?",
["当前未安装可用的 kamare 增强版。安装最新版 %1?"] = "No usable kamare enhanced build is installed. Install the latest version %1?",
["正在下载 kamare 更新…"] = "Downloading the kamare update…",
["正在安装 kamare 更新…"] = "Installing the kamare update…",
["kamare 更新失败:%1"] = "kamare update failed: %1",
[" 发布页:github.com/backtracker/kamare.koplugin/releases/latest"] = " Releases: github.com/backtracker/kamare.koplugin/releases/latest",
[" 下载 kamare.koplugin.zip,解压后把 kamare.koplugin/ 放进:%1"] = " Download kamare.koplugin.zip, unzip it, and put kamare.koplugin/ into: %1",
[" 重启 KOReader。包里要有 kamarecache.lua(没有就是官方版);"] = " Restart KOReader. The archive must contain kamarecache.lua (otherwise it is the official build);",
[" 增强版与官方版目录同名,不能共存;替换前先删掉旧的 kamare.koplugin/。"] = " Enhanced and official share the same directory name and cannot coexist; delete the old kamare.koplugin/ before replacing it.",
[" 如该目录不可写,可改用:%1"] = " If that directory is not writable, use: %1",
["%1 · 已缓存"] = "%1 · Cached",
["%1 · 待同步"] = "%1 · Pending sync",
["%1 · 离线"] = "%1 · Offline",
["%1 卷成功,%2 卷失败"] = "%1 volumes succeeded, %2 failed",
["%1 等 %2 卷"] = "%1 and %2 volumes",
["下载中 %1%"] = "Downloading %1%",
["全部已缓存"] = "Everything is cached",
["删除「%1」的缓存?将释放 %2。"] = "Delete the cache for %1? This frees %2.",
["删除会取消这一卷的下载。"] = "Deleting also cancels this volume's download.",
["删除后离线不可读。"] = "It will not be readable offline after deletion.",
["删除缓存"] = "Delete cache",
["去清理空间"] = "Free up space",
["另有 %1 卷失败将重试"] = "%1 failed volumes will be retried",
["完成后剩余 %1"] = "%1 left afterwards",
["将缓存:%1"] = "To cache: %1",
["将重试:%1"] = "To retry: %1",
["已排队"] = "Queued",
["已暂停"] = "Paused",
["已暂停整个下载队列"] = "Paused the whole download queue",
["已暂停 %1%"] = "Paused %1%",
["已暂停(仅 Wi-Fi 下载)"] = "Paused (Wi-Fi only)",
["已暂停(启动恢复)"] = "Paused (restored at startup)",
["已暂停(断网)"] = "Paused (offline)",
["已暂停(连续下载失败)"] = "Paused (repeated download failures)",
["已缓存 %1 卷"] = "Cached %1 volumes",
["缓存已中断"] = "Caching was interrupted",
["开始缓存"] = "Start caching",
["当前下载已暂停,开始缓存会恢复整个队列"] = "Downloads are paused; starting will resume the whole queue",
["未缓存"] = "Not cached",
["查看失败原因"] = "View failure reasons",
["正在缓存 %1/%2 卷"] = "Caching volume %1/%2",
["清理后再下载"] = "Free up space before downloading",
["空间不足"] = "Not enough space",
["空间不足,已暂停"] = "Not enough space, paused",
["空间不足,已暂停。清理后再下载"] = "Not enough space, paused. Free up space before downloading.",
["缓存 %1 卷"] = "Cache %1 volumes",
["缓存这一卷"] = "Cache this volume",
["设备可用 %1"] = "%1 available",
["部分失败"] = "Partly failed",
["重试"] = "Retry",
["重试失败项并继续"] = "Retry failures and continue",
["重试缓存"] = "Retry cache",
["预计占用 %1(峰值)"] = "Estimated use %1 (peak)",
["缓存整部"] = "Cache whole series",
["缓存未读"] = "Cache unread",
["没有未读的卷"] = "No unread volumes",
["缓存后 N 卷…"] = "Cache next N volumes…",
["缓存后 N 卷"] = "Cache next N volumes",
["卷数"] = "Volumes",
["增强版 v%1(旧接口)"] = "Enhanced v%1 (legacy API)",
["增强版(旧接口)"] = "Enhanced (legacy API)",
["kamare API v%1 与当前支持的 v1 不兼容;装回支持 v1 的增强版后可管理缓存"] = "kamare API v%1 is not compatible with the supported v1; install an enhanced build that supports v1 to manage the cache",
["版本与获取"] = "Version and getting the enhanced build",
["正在统计…"] = "Measuring…",
["正在清理…"] = "Cleaning up…",
["增强版功能"] = "Enhanced features",
["加载路径"] = "Loaded from",
["缓存占用"] = "Cache usage",
["已用 %1%2,可用 %3"] = "%1 used%2, %3 available",
["(含未关联服务器)"] = " (unlinked servers included)",
["重试同步"] = "Retry sync",
["已重新同步配置"] = "Settings synced again",
["服务器配置没能写入 kamare,缓存操作可能找不到服务器"] = "The server settings could not be written to kamare; cache actions may not find the server",
["未配置服务器"] = "No server configured",
["填写服务器地址与 API Key 后,可按服务器清理已读或全部缓存"] = "Fill in the server address and API key to clean up read or all cache per server",
["清理已读"] = "Clean up read",
["清理本服务器"] = "Clean up this server",
["清理全部"] = "Clean up all",
["清理全部缓存"] = "Clean up all cache",
["清理本系列"] = "Clean up this series",
["清理本系列已读"] = "Clean up read in this series",
["没有可清理的缓存"] = "No cache to clean up",
["没有已读完的缓存"] = "No finished cache to clean up",
["%1 章"] = "%1 chapters",
["%1 卷"] = "%1 volumes",
["%1 章 · 约 %2"] = "%1 chapters · about %2",
["含未关联服务器"] = "Includes unlinked servers",
["含未关联服务器 · %1 章 · 约 %2"] = "Includes unlinked servers · %1 chapters · about %2",
["将删除 %1 章已读完的缓存(约 %2)。"] = "This deletes %1 finished chapters from the cache (about %2).",
["将删除本服务器的 %1 章(约 %2)。"] = "This deletes %1 chapters from this server (about %2).",
["将删除所有服务器(含未关联服务器)共 %1 章(约 %2)。"] = "This deletes %1 chapters from all servers (unlinked servers included; about %2).",
["将删除本系列 %1 卷缓存(约 %2)。"] = "This deletes the cache for %1 volumes in this series (about %2).",
["将删除本系列 %1 卷已读完的缓存(约 %2)。"] = "This deletes the cache for %1 finished volumes in this series (about %2).",
["会中止正在下载的 %1 章,已下载的部分会被删除。"] = "This aborts %1 downloading chapters; what was downloaded will be removed.",
["会中止正在下载的 %1 卷,已下载的部分会被删除。"] = "This aborts %1 downloading volumes; what was downloaded will be removed.",
["此操作不可撤销,之后阅读需要重新下载。"] = "This cannot be undone; reading again requires downloading again.",
["阅读进度与 kamare journal 保留。"] = "Reading progress and the kamare journal are kept.",
["已清理 %1 章,释放约 %2"] = "Cleaned %1 chapters, freeing about %2",
["已清理 %1 章,%2 章未能删除"] = "Cleaned %1 chapters; %2 could not be deleted",
["已清理 %1 卷,释放约 %2"] = "Cleaned %1 volumes, freeing about %2",
["已清理 %1 卷,%2 卷未能删除"] = "Cleaned %1 volumes; %2 could not be deleted",
["已清理全部缓存,释放约 %1"] = "Cleaned all cache, freeing about %1",
["当前 kamare 没有清理接口"] = "This kamare build has no cleanup API",
["升级到带 chapters / delete_all 的版本后才能清理"] = "Upgrade to a build with chapters / delete_all to clean up",
["增强版功能随版本不同,以实际安装的版本为准。"] = "Enhanced-build features vary by version; the installed build is authoritative.",
["漫画缓存"] = "Comic cache",
["清理已读、按系列或全部清理"] = "Clean up read, per series, or all",
["状态与获取增强版"] = "Status and getting the enhanced build",
["批量操作"] = "Batch actions",
["请先打开月读桌面"] = "Open the Moon Reader desktop first",
["无法识别 Kavita 版本"] = "Could not identify the Kavita version",
["Kavita %1 过旧,需要 0.9 及以上"] = "Kavita %1 is too old; 0.9 or later is required",
["部分缓存未能删除(权限或存储错误)"] = "Some cache files could not be deleted (permission or storage error)",
["缓存与同步"] = "Cache & sync",
["诊断"] = "Diagnostics",
["进度心跳间隔"] = "Progress heartbeat interval",
["阅读时补推进度,0 关闭"] = "Push progress while reading; 0 = off",
["请求超时"] = "Request timeout",
["%1 · 已下载"] = "%1 · Downloaded",
["API Key"] = "API Key",
["Kavita"] = "Kavita",
["Kavita API Key 无效或无权限"] = "Kavita API key is invalid or lacks permission",
["Kavita 上没有在读的书"] = "No books in progress on Kavita",
["Kavita 未确认注解已创建"] = "Kavita did not confirm the annotation was created",
["Kavita 注解删除后复核失败"] = "Kavita could not verify the annotation deletion",
["Kavita 注解删除失败"] = "Kavita annotation deletion failed",
["Kavita 用户设置 → API Key"] = "Kavita user settings → API Key",
["Kavita 继续阅读"] = "Continue reading on Kavita",
["划线无法定位,本轮暂不推送:%1"] = "Highlight could not be anchored; not pushed this round: %1",
["响应不是 JSON"] = "Response is not JSON",
["图片目录格式需要安装 kamare 插件在线阅读"] = "Image-directory format requires the kamare plugin to read online",
["正在拉取书架(%1 本)"] = "Fetching shelf (%1 books)",
["正在连接 Kavita…"] = "Connecting to Kavita…",
["联网后显示 Kavita 上在读的书"] = "Books in progress on Kavita appear when online",
["请先在设置里填写 Kavita 服务器并选择书库"] = "Set the Kavita server and select a library in settings first",
["请先填写服务器地址和 API Key"] = "Fill in the server address and API key first",
["这一卷已不在 Kavita 上"] = "This volume is no longer on Kavita",
["这本书在 Kavita 上没有可读的卷"] = "No readable volumes for this book on Kavita",
["选择书库"] = "Select libraries",
["进度同步"] = "Progress sync",
["漫画缓存(需 kamare 增强版)"] = "Comic cache (needs kamare enhanced build)",
["连接 Kavita 服务器的漫画与电子书"] = "Comics and e-books from a Kavita server",
["第 %1 卷"] = "Vol. %1",
["上次翻阅"] = "Last opened",
["已读完 · 共 %1 卷"] = "Finished · %1 volumes",
["开始阅读 · %1"] = "Start reading · %1",
["第 %1/%2 页 · %3%"] = "Page %1/%2 · %3%",
["继续阅读 · %1"] = "Continue reading · %1",
["重读 · %1"] = "Read again · %1",
["共 %1 页"] = "%1 pages total",
["选择卷"] = "Choose a volume",
}
@@ -0,0 +1,207 @@
return {
["EPUB 划线同步"] = "EPUB 畫線同步",
["书架与卷目录同步(只读)"] = "書架與卷目錄同步(唯讀)",
["同步 Kavita 书架、电子书与漫画"] = "同步 Kavita 書架、電子書與漫畫",
["漫画在线阅读与缓存(需 kamare 增强版)"] = "漫畫線上閱讀與快取(需 kamare 增強版)",
["阅读历史拉取"] = "取得閱讀歷史",
["下载文件校验失败"] = "下載檔案校驗失敗",
["确定退出 Kavita 账号?"] = "確定登出 Kavita 帳號?",
["正在下载…"] = "正在下載…",
["章节目录保存失败"] = "章節目錄儲存失敗",
["请求失败 (HTTP %1)"] = "請求失敗 (HTTP %1)",
["连接失败"] = "連接失敗",
["打开漫画阅读器失败"] = "無法開啟漫畫閱讀器",
["漫画阅读器已在运行"] = "漫畫閱讀器已在執行",
["这一卷还没缓存,联网后可下载"] = "這一卷還沒快取,連網後可下載",
["这一卷没有可显示的页面"] = "這一卷沒有可顯示的頁面",
["下一卷不在目录里"] = "下一卷不在目錄裡",
["无法写入 kamare 配置"] = "無法寫入 kamare 設定",
["没有可重试的任务"] = "沒有可重試的任務",
["正在阅读这一卷,关闭后可以删除"] = "正在閱讀這一卷,關閉後可以刪除",
["需要安装带缓存接口的增强版 kamare"] = "需要安裝帶快取介面的增強版 kamare",
["无法同步配置到 kamare"] = "無法同步設定到 kamare",
["%1 MB"] = "%1 MB",
["空间不足:需要 %1,可用 %2"] = "空間不足:需要 %1,可用 %2",
["缓存空间已满:需要 %1,上限 %2"] = "快取空間已滿:需要 %1,上限 %2",
["可用空间低于 %1,清理后再下载"] = "可用空間低於 %1,清理後再下載",
["缓存操作失败"] = "快取操作失敗",
["全部已缓存或正在下载"] = "全部已快取或正在下載",
["可用空间不足(剩余 %1),清理后再下载"] = "可用空間不足(剩餘 %1),清理後再下載",
["服务器拒绝下载(403),检查 API Key / 权限"] = "伺服器拒絕下載(403),檢查 API Key / 權限",
["下载内容不完整或不是有效压缩包"] = "下載內容不完整或不是有效壓縮檔",
["存储空间不足或写入失败"] = "儲存空間不足或寫入失敗",
["网络中断或服务器不可达"] = "網路中斷或伺服器無法連線",
["缓存失败:%1"] = "快取失敗:%1",
["配置同步失败"] = "設定同步失敗",
["增强版 v%1"] = "增強版 v%1",
["增强版"] = "增強版",
["版本不兼容"] = "版本不相容",
["官方版(无缓存接口)"] = "官方版(無快取介面)",
["未安装 / 未启用"] = "未安裝 / 未啟用",
["连接正常"] = "連線正常",
["Kavita %1"] = "Kavita %1",
["未加载"] = "未載入",
["获取增强版"] = "取得增強版",
["秒"] = "秒",
["检查 Kavita 服务器连接与版本"] = "檢查 Kavita 伺服器連線與版本",
["kamare 增强版"] = "kamare 增強版",
["点按检查 kamare 增强版更新"] = "點按檢查 kamare 增強版更新",
["点按安装 kamare 增强版"] = "點按安裝 kamare 增強版",
["点按安装兼容的 kamare 增强版"] = "點按安裝相容的 kamare 增強版",
["点按检查并安装 kamare 增强版"] = "點按檢查並安裝 kamare 增強版",
["官方版"] = "官方版",
[" 也可点上方「kamare 增强版」检查并安装最新版。"] = " 也可點上方「kamare 增強版」檢查並安裝最新版。",
["正在检查 kamare 更新…"] = "正在檢查 kamare 更新…",
["更新 kamare"] = "更新 kamare",
["发现 kamare %1(当前 %2)。下载并完整替换插件目录?"] = "發現 kamare %1(目前 %2)。下載並完整取代外掛目錄?",
["当前未安装可用的 kamare 增强版。安装最新版 %1?"] = "目前未安裝可用的 kamare 增強版。安裝最新版 %1?",
["正在下载 kamare 更新…"] = "正在下載 kamare 更新…",
["正在安装 kamare 更新…"] = "正在安裝 kamare 更新…",
["kamare 更新失败:%1"] = "kamare 更新失敗:%1",
[" 发布页:github.com/backtracker/kamare.koplugin/releases/latest"] = " 發布頁:github.com/backtracker/kamare.koplugin/releases/latest",
[" 下载 kamare.koplugin.zip,解压后把 kamare.koplugin/ 放进:%1"] = " 下載 kamare.koplugin.zip,解壓後把 kamare.koplugin/ 放進:%1",
[" 重启 KOReader。包里要有 kamarecache.lua(没有就是官方版);"] = " 重新啟動 KOReader。壓縮檔裡要有 kamarecache.lua(沒有就是官方版);",
[" 增强版与官方版目录同名,不能共存;替换前先删掉旧的 kamare.koplugin/。"] = " 增強版與官方版目錄同名,不能共存;替換前先刪掉舊的 kamare.koplugin/。",
[" 如该目录不可写,可改用:%1"] = " 如該目錄不可寫,可改用:%1",
["%1 · 已缓存"] = "%1 · 已快取",
["%1 · 待同步"] = "%1 · 待同步",
["%1 · 离线"] = "%1 · 離線",
["%1 卷成功,%2 卷失败"] = "%1 卷成功,%2 卷失敗",
["%1 等 %2 卷"] = "%1 等 %2 卷",
["下载中 %1%"] = "下載中 %1%",
["全部已缓存"] = "全部已快取",
["删除「%1」的缓存?将释放 %2。"] = "刪除「%1」的快取?將釋放 %2。",
["删除会取消这一卷的下载。"] = "刪除會取消這一卷的下載。",
["删除后离线不可读。"] = "刪除後離線不可讀。",
["删除缓存"] = "刪除快取",
["去清理空间"] = "去清理空間",
["另有 %1 卷失败将重试"] = "另有 %1 卷失敗將重試",
["完成后剩余 %1"] = "完成後剩餘 %1",
["将缓存:%1"] = "將快取:%1",
["将重试:%1"] = "將重試:%1",
["已排队"] = "已排隊",
["已暂停"] = "已暫停",
["已暂停整个下载队列"] = "已暫停整個下載佇列",
["已暂停 %1%"] = "已暫停 %1%",
["已暂停(仅 Wi-Fi 下载)"] = "已暫停(僅 Wi-Fi 下載)",
["已暂停(启动恢复)"] = "已暫停(啟動恢復)",
["已暂停(断网)"] = "已暫停(斷網)",
["已暂停(连续下载失败)"] = "已暫停(連續下載失敗)",
["已缓存 %1 卷"] = "已快取 %1 卷",
["缓存已中断"] = "快取已中斷",
["开始缓存"] = "開始快取",
["当前下载已暂停,开始缓存会恢复整个队列"] = "目前下載已暫停,開始快取會恢復整個佇列",
["未缓存"] = "未快取",
["查看失败原因"] = "查看失敗原因",
["正在缓存 %1/%2 卷"] = "正在快取 %1/%2 卷",
["清理后再下载"] = "清理後再下載",
["空间不足"] = "空間不足",
["空间不足,已暂停"] = "空間不足,已暫停",
["空间不足,已暂停。清理后再下载"] = "空間不足,已暫停。清理後再下載",
["缓存 %1 卷"] = "快取 %1 卷",
["缓存这一卷"] = "快取這一卷",
["设备可用 %1"] = "裝置可用 %1",
["部分失败"] = "部分失敗",
["重试"] = "重試",
["重试失败项并继续"] = "重試失敗項並繼續",
["重试缓存"] = "重試快取",
["预计占用 %1(峰值)"] = "預計佔用 %1(峰值)",
["缓存整部"] = "快取整部",
["缓存未读"] = "快取未讀",
["没有未读的卷"] = "沒有未讀的卷",
["缓存后 N 卷…"] = "快取後 N 卷…",
["缓存后 N 卷"] = "快取後 N 卷",
["卷数"] = "卷數",
["增强版 v%1(旧接口)"] = "增強版 v%1(舊介面)",
["增强版(旧接口)"] = "增強版(舊介面)",
["kamare API v%1 与当前支持的 v1 不兼容;装回支持 v1 的增强版后可管理缓存"] = "kamare API v%1 與目前支援的 v1 不相容;裝回支援 v1 的增強版後可管理快取",
["版本与获取"] = "版本與取得",
["正在统计…"] = "正在統計…",
["正在清理…"] = "正在清理…",
["增强版功能"] = "增強版功能",
["加载路径"] = "載入路徑",
["缓存占用"] = "快取佔用",
["已用 %1%2,可用 %3"] = "已用 %1%2,可用 %3",
["(含未关联服务器)"] = "(含未關聯伺服器)",
["重试同步"] = "重試同步",
["已重新同步配置"] = "已重新同步設定",
["服务器配置没能写入 kamare,缓存操作可能找不到服务器"] = "伺服器設定沒能寫入 kamare,快取操作可能找不到伺服器",
["未配置服务器"] = "未設定伺服器",
["填写服务器地址与 API Key 后,可按服务器清理已读或全部缓存"] = "填寫伺服器位址與 API Key 後,可按伺服器清理已讀或全部快取",
["清理已读"] = "清理已讀",
["清理本服务器"] = "清理本伺服器",
["清理全部"] = "清理全部",
["清理全部缓存"] = "清理全部快取",
["清理本系列"] = "清理本系列",
["清理本系列已读"] = "清理本系列已讀",
["没有可清理的缓存"] = "沒有可清理的快取",
["没有已读完的缓存"] = "沒有已讀完的快取",
["%1 章"] = "%1 章",
["%1 卷"] = "%1 卷",
["%1 章 · 约 %2"] = "%1 章 · 約 %2",
["含未关联服务器"] = "含未關聯伺服器",
["含未关联服务器 · %1 章 · 约 %2"] = "含未關聯伺服器 · %1 章 · 約 %2",
["将删除 %1 章已读完的缓存(约 %2)。"] = "將刪除 %1 章已讀完的快取(約 %2)。",
["将删除本服务器的 %1 章(约 %2)。"] = "將刪除本伺服器的 %1 章(約 %2)。",
["将删除所有服务器(含未关联服务器)共 %1 章(约 %2)。"] = "將刪除所有伺服器(含未關聯伺服器)共 %1 章(約 %2)。",
["将删除本系列 %1 卷缓存(约 %2)。"] = "將刪除本系列 %1 卷快取(約 %2)。",
["将删除本系列 %1 卷已读完的缓存(约 %2)。"] = "將刪除本系列 %1 卷已讀完的快取(約 %2)。",
["会中止正在下载的 %1 章,已下载的部分会被删除。"] = "會中止正在下載的 %1 章,已下載的部分會被刪除。",
["会中止正在下载的 %1 卷,已下载的部分会被删除。"] = "會中止正在下載的 %1 卷,已下載的部分會被刪除。",
["此操作不可撤销,之后阅读需要重新下载。"] = "此操作無法復原,之後閱讀需要重新下載。",
["阅读进度与 kamare journal 保留。"] = "閱讀進度與 kamare journal 保留。",
["已清理 %1 章,释放约 %2"] = "已清理 %1 章,釋放約 %2",
["已清理 %1 章,%2 章未能删除"] = "已清理 %1 章,%2 章未能刪除",
["已清理 %1 卷,释放约 %2"] = "已清理 %1 卷,釋放約 %2",
["已清理 %1 卷,%2 卷未能删除"] = "已清理 %1 卷,%2 卷未能刪除",
["已清理全部缓存,释放约 %1"] = "已清理全部快取,釋放約 %1",
["当前 kamare 没有清理接口"] = "目前 kamare 沒有清理介面",
["升级到带 chapters / delete_all 的版本后才能清理"] = "升級到帶 chapters / delete_all 的版本後才能清理",
["增强版功能随版本不同,以实际安装的版本为准。"] = "增強版功能隨版本不同,以實際安裝的版本為準。",
["漫画缓存"] = "漫畫快取",
["清理已读、按系列或全部清理"] = "清理已讀、按系列或全部清理",
["状态与获取增强版"] = "狀態與取得增強版",
["批量操作"] = "批次操作",
["请先打开月读桌面"] = "請先開啟月讀桌面",
["无法识别 Kavita 版本"] = "無法辨識 Kavita 版本",
["Kavita %1 过旧,需要 0.9 及以上"] = "Kavita %1 過舊,需要 0.9 及以上",
["部分缓存未能删除(权限或存储错误)"] = "部分快取未能刪除(權限或儲存錯誤)",
["缓存与同步"] = "快取與同步",
["诊断"] = "診斷",
["进度心跳间隔"] = "進度心跳間隔",
["阅读时补推进度,0 关闭"] = "閱讀時補推進度,0 關閉",
["请求超时"] = "請求逾時",
["%1 · 已下载"] = "%1 · 已下載",
["API Key"] = "API Key",
["Kavita"] = "Kavita",
["Kavita API Key 无效或无权限"] = "Kavita API Key 無效或無權限",
["Kavita 上没有在读的书"] = "Kavita 上沒有在讀的書",
["Kavita 未确认注解已创建"] = "Kavita 未確認註解已建立",
["Kavita 注解删除后复核失败"] = "Kavita 註解刪除後複核失敗",
["Kavita 注解删除失败"] = "Kavita 註解刪除失敗",
["Kavita 用户设置 → API Key"] = "Kavita 使用者設定 → API Key",
["Kavita 继续阅读"] = "Kavita 繼續閱讀",
["划线无法定位,本轮暂不推送:%1"] = "劃線無法定位,本輪暫不推送:%1",
["响应不是 JSON"] = "回應不是 JSON",
["图片目录格式需要安装 kamare 插件在线阅读"] = "圖片目錄格式需要安裝 kamare 外掛線上閱讀",
["正在拉取书架(%1 本)"] = "正在拉取書架(%1 本)",
["正在连接 Kavita…"] = "正在連線 Kavita…",
["联网后显示 Kavita 上在读的书"] = "連網後顯示 Kavita 上在讀的書",
["请先在设置里填写 Kavita 服务器并选择书库"] = "請先在設定裡填寫 Kavita 伺服器並選擇書庫",
["请先填写服务器地址和 API Key"] = "請先填寫伺服器位址和 API Key",
["这一卷已不在 Kavita 上"] = "這一卷已不在 Kavita 上",
["这本书在 Kavita 上没有可读的卷"] = "這本書在 Kavita 上沒有可讀的卷",
["选择书库"] = "選擇書庫",
["进度同步"] = "進度同步",
["漫画缓存(需 kamare 增强版)"] = "漫畫快取(需 kamare 增強版)",
["连接 Kavita 服务器的漫画与电子书"] = "連接 Kavita 伺服器的漫畫與電子書",
["第 %1 卷"] = "第 %1 卷",
["上次翻阅"] = "上次翻閱",
["已读完 · 共 %1 卷"] = "已讀完 · 共 %1 卷",
["开始阅读 · %1"] = "開始閱讀 · %1",
["第 %1/%2 页 · %3%"] = "第 %1/%2 頁 · %3%",
["继续阅读 · %1"] = "繼續閱讀 · %1",
["重读 · %1"] = "重讀 · %1",
["共 %1 页"] = "共 %1 頁",
["选择卷"] = "選擇卷",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_kavita._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,41 @@
--[[--
Kavita 系列书评映射;个人评价列表和章节评价不混入系列书评。
@module moonsource_kavita.mapper
--]]
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_kavita")
local Mapper = {}
---@param wire table
---@param series_id string
---@return table|nil, string|nil
function Mapper.bookReviewPage(wire, series_id)
local rows = type(wire) == "table" and wire.reviews
if type(rows) ~= "table" then return nil, _("响应无效") end
local items = {}
for _idx, row in ipairs(rows) do
if type(row) ~= "table" or type(row.body) ~= "string"
or type(row.chapterId) ~= "number" or type(row.username) ~= "string" then
return nil, _("响应无效")
end
if row.isExternal ~= true and tostring(row.seriesId) ~= series_id then
return nil, _("响应无效")
end
if row.chapterId == 0 then
local body = type(row.bodyJustText) == "string" and row.bodyJustText ~= ""
and row.bodyJustText or Text.stripHtml(row.body)
local title = type(row.tagline) == "string" and Text.trim(row.tagline) or ""
local text = title ~= "" and title .. "\n" .. body or body
if Text.trim(text) ~= "" then
items[#items + 1] = { author = row.username, text = text, time = "",
grade = tonumber(row.rating), likes = tonumber(row.totalVotes) }
end
end
end
return { items = items, total = #items, pages = 1, title = _("书评") }
end
return Mapper
@@ -0,0 +1,188 @@
--[[--
首页组件:Kavita「继续阅读」(On Deck)。在线且已配置时拉一次,5 分钟内复用;
跟首页「最近阅读列表」同一套封面网格(CoverCell.denseCoverMetrics + Book.widget):
每页 4 本,多了分页;点开走月读开书流程(多卷 series 会先选卷)。
@module moonsource_kavita.on_deck
--]]
local Base = require("desktop.pages.home.base")
local Book = require("ui.widgets.book")
local CenterContainer = require("ui/widget/container/centercontainer")
local CoverCell = require("ui.widgets.cover")
local Geom = require("ui/geometry")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local HorizontalSpan = require("ui/widget/horizontalspan")
local VerticalGroup = require("ui/widget/verticalgroup")
local VerticalSpan = require("ui/widget/verticalspan")
local Pager = require("ui.themes.widgets.pager")
local Theme = require("ui.themes")
local Tap = require("ui.themes.widgets.tap")
local Text = require("ui.themes.widgets.text")
local _ = require("l10n").get("moonsource_kavita")
local ID = "kavita"
local MAX_BOOKS = 10
local TTL = 300
-- 跟首页「最近阅读」一页一样:一行 4 本(封面大),多的分页。
local COLS = 4
local ROWS = 1
---@class KavitaOnDeck : BookHomeComponent
---@field job { cancel: fun() }|nil
---@field loaded_at integer|nil
---@field err string|nil
local M = {
id = "kavita.on_deck",
label = _("Kavita 继续阅读"),
icon = "collections_bookmark",
}
setmetatable(M, Base)
M.__index = M
--- 网格尺寸:跟首页「最近阅读列表」共用 CoverCell.denseCoverMetrics,封面与槽位口径一致
---(封面在固定宽的槽里居中,标题按槽宽居中,不会一本书看着变小/错位)。
--- 列数固定 4(一页 4 本,封面才够大);area_h 有值时再收到放得下。
---@param width integer
---@param area_h integer|nil 分配到的可用高度
---@return integer slot_w
---@return integer cw
---@return integer ch
---@return integer gap
---@return integer row_gap
---@return integer cell_h
local function gridMetrics(width, area_h)
local extra = Book.captionExtra(true, false)
local max_h = CoverCell.gridCoverMaxH(area_h)
local slot_w, cw, ch, _cols, gap, row_gap, cell_h = CoverCell.denseCoverMetrics(
math.max(1, math.floor(tonumber(width) or 1)), 0, {
title_extra = extra,
max_h = max_h,
min_cols = COLS,
max_cols = COLS,
})
if ch > max_h then
ch = max_h
cw = math.max(1, math.min(slot_w, math.floor(ch * 2 / 3)))
cell_h = ch + extra
end
area_h = math.floor(tonumber(area_h) or 0)
if area_h > 0 then
local gaps = row_gap * (ROWS - 1)
if cell_h * ROWS + gaps > area_h then
local fit_cell = math.max(1, math.floor((area_h - gaps) / ROWS))
ch = math.max(1, math.min(ch, fit_cell - extra))
cw = math.max(1, math.min(slot_w, math.floor(ch * 2 / 3)))
cell_h = math.min(ch + extra, fit_cell)
end
end
return slot_w, cw, ch, gap, row_gap, cell_h
end
--- 分页条高度:On Deck 最多 10 本 > 一页 4 本,恒有分页。
---@return integer
local function pagerHeight()
return MAX_BOOKS > COLS * ROWS and Theme.px(Theme.current().control.height) or 0
end
function M:heightRange(_ctx, opts)
local _slot_w, _cw, _ch, _gap, row_gap, cell_h = gridMetrics(tonumber(opts and opts.width) or 0)
return { height = cell_h * ROWS + row_gap * (ROWS - 1) + pagerHeight() }
end
function M:onActivate()
if self.job or (self.loaded_at and os.time() - self.loaded_at < TTL) then return end
local source = require("source.registry").resolve(ID) --[[@as KavitaSource|nil]]
if not (source and source:configured() and require("ui/network/manager"):isConnected()) then return end
self.job = source.client:json("POST", "/api/Series/on-deck", { pageNumber = 1, pageSize = MAX_BOOKS }, {},
function(list, err)
self.job = nil
self.loaded_at, self.err = os.time(), err
if list then
local books = {}
for idx, series in ipairs(list) do
local pages = tonumber(series.pages) or 0
books[idx] = {
source_id = ID,
stable_id = tostring(series.id),
title = series.name,
percent = pages > 0 and math.min(100, (tonumber(series.pagesRead) or 0) * 100 / pages) or 0,
}
end
self.data = books
end
self:refresh()
end)
end
function M:onDeactivate()
if self.job then
self.job:cancel()
self.job = nil
end
end
---@param w integer
---@param h integer
---@param text string
---@return table
local function hint(w, h, text)
return CenterContainer:new{
dimen = Geom:new{ w = w, h = h },
Text.line("body", text, { width = w, color = Theme.current().color.muted }),
}
end
function M:createWidget()
local ctx, w, h = self.ctx, self.opts.width, self.opts.height
local books = self.data
if not books then return hint(w, h, self.err or _("联网后显示 Kavita 上在读的书")) end
if #books == 0 then return hint(w, h, _("Kavita 上没有在读的书")) end
local page_size = COLS * ROWS
local pages = math.max(1, math.ceil(#books / page_size))
local pager_h = pages > 1 and Theme.px(Theme.current().control.height) or 0
local grid_h = math.max(1, h - pager_h)
local slot_w, cw, ch, gap, row_gap = gridMetrics(w, grid_h)
local page = math.max(1, math.min(self.page or 1, pages))
self.page = page
local first = (page - 1) * page_size + 1
local last = math.min(#books, first + page_size - 1)
local grid = VerticalGroup:new{ align = "center" }
local row, col = nil, 0
for i = first, last do
if not row or col == COLS then
if row then grid[#grid + 1] = VerticalSpan:new{ width = row_gap } end
row, col = HorizontalGroup:new{ align = "top" }, 0
grid[#grid + 1] = row
end
col = col + 1
if col > 1 then row[#row + 1] = HorizontalSpan:new{ width = gap } end
local book = books[i]
-- 跟最近阅读列表同一条路:Book.widget 居中封面 + 标题,槽宽用 slot_w。
local cell = Book.widget(ctx.plugin, nil, book, cw, ch, {
slot_w = slot_w,
badge = false,
ribbon = false,
download = false,
show_parent = ctx.desktop,
home = true,
})
row[#row + 1] = Tap.wrap(cell, function() Base.openBook(ctx, book) end)
end
local out = VerticalGroup:new{
align = "center",
CenterContainer:new{ dimen = Geom:new{ w = w, h = grid_h }, grid },
}
if pages > 1 then
out[#out + 1] = Pager.widget({
width = w,
page = page,
pages = pages,
on_prev = function() self.page = page - 1; self:refresh() end,
on_next = function() self.page = page + 1; self:refresh() end,
})
end
return out
end
return M
@@ -0,0 +1,259 @@
--[[--
KOReader xpointer ↔ Kavita 书籍进度(pageNum + bookScrollId)。
Kavita 的 epub 进度以 spine 为单位:pageNum 是 0-based spine 序号(KOReader 的
`DocFragment[D]` = spine D-1),pageNum == pages 表示读完;bookScrollId 是章内锚点,
本插件上报 `//body/...` 路径,Kavita 网页端上报 `id("X")`,后者要读本地 epub 才能还原成路径。
@module moonsource_kavita.position
--]]
local Position = {}
local VOID = {
br = true, img = true, hr = true, meta = true, link = true, input = true,
area = true, base = true, col = true, embed = true, source = true, track = true, wbr = true,
}
--- xpointer 所在 spine(0-based)。单 spine 书 crengine 写 `DocFragment/body`(无下标)。
---@param locator string|nil
---@return integer|nil
function Position.spine(locator)
if type(locator) ~= "string" then return nil end
local d = locator:match("DocFragment%[(%d+)%]")
if d then return tonumber(d) - 1 end
if locator:match("/DocFragment/") then return 0 end
return nil
end
--- xpointer → `//body/...`(同名兄弟下标补全为 [1],丢弃文本偏移)。body 内无元素返回 nil。
---@param locator string|nil
---@return string|nil
function Position.toScrollId(locator)
if type(locator) ~= "string" then return nil end
-- crengine 两种写法都有:`/body/DocFragment[N]/body/...` 与归一化的 `/body[1]/DocFragment[N]/body[1]/...`。
local rest = locator:match("^/body%[%d+%]/DocFragment%[?%d*%]?/body%[%d+%](.*)$")
or locator:match("^/body/DocFragment%[?%d*%]?/body(.*)$")
if not rest then return nil end
local parts = {}
for seg in rest:gmatch("[^/]+") do
if not seg:match("^text%(") then
local name, index = seg:match("^([%w:_%-]+)%[(%d+)%]$")
name = name or seg:match("^([%w:_%-]+)")
if name then parts[#parts + 1] = name .. "[" .. (index or "1") .. "]" end
end
end
if #parts == 0 then return nil end
return "//body/" .. table.concat(parts, "/")
end
--- spine + `//body/...` → xpointer。pageNum == pages(读完)落回最后一个 spine。
---@param spine integer
---@param scroll_id string|nil
---@param pages integer spine 总数
---@return string
function Position.toXPointer(spine, scroll_id, pages)
local n = math.max(0, math.min(spine, pages - 1))
local tail = ""
local path = type(scroll_id) == "string" and scroll_id:match("^//body/(.+)$")
if path then
for seg in path:gmatch("[^/]+") do
-- crengine 规范:[1] 省略。
tail = tail .. "/" .. (seg:gsub("%[1%]$", ""))
end
end
local fragment = pages == 1 and "DocFragment" or ("DocFragment[" .. (n + 1) .. "]")
return "/body/" .. fragment .. "/body" .. tail
end
---@param base string
---@param href string
---@return string
local function joinPath(base, href)
local parts = {}
for seg in ((base ~= "" and base .. "/" or "") .. href):gmatch("[^/]+") do
if seg == ".." then
table.remove(parts)
elseif seg ~= "." then
parts[#parts + 1] = seg
end
end
return table.concat(parts, "/")
end
--- 打开 epub 交给 fn({ count, html(spine) })。用户的 epub 什么样都有:
--- 打不开、解析抛错一律返回 nil,调用方降级(只按 spine 定位 / 不带锚点),不能让开书或同步失败。
---@param epub_path string|nil
---@param fn fun(doc: { count: integer, html: fun(spine: integer): string|nil }): any
---@return any
local function withEpub(epub_path, fn)
if not epub_path then return nil end
local arc = require("ffi/archiver").Reader:new()
if not arc:open(epub_path) then return nil end
local ok, result = pcall(function()
-- archiver 要先扫一遍条目,extractToMemory 才找得到文件。
for _entry in arc:iterate() do end
local opf_path = (arc:extractToMemory("META-INF/container.xml") or ""):match('full%-path="([^"]+)"')
local opf = opf_path and arc:extractToMemory(opf_path) or ""
local manifest, hrefs = {}, {}
for tag in opf:gmatch("<item%s[^>]*>") do
local id, href = tag:match('%sid="([^"]*)"'), tag:match('%shref="([^"]*)"')
if id and href then manifest[id] = href end
end
for idref in (opf:match("<spine[^>]*>(.-)</spine>") or ""):gmatch('idref="([^"]*)"') do
hrefs[#hrefs + 1] = manifest[idref]
end
local base = opf_path and opf_path:match("^(.*)/") or ""
return fn({
count = #hrefs,
html = function(spine)
local href = hrefs[spine + 1]
return href and arc:extractToMemory(joinPath(base, href))
end,
})
end)
arc:close()
return ok and result or nil
end
---@class KavitaElement
---@field name string
---@field tag string 开标签原文(不含尖括号)
---@field path string 相对 body 的路径,同名兄弟下标补全:`section[1]/p[3]`
---@field text string[] 元素内(含后代)的文本片段
--- body 内元素按文档顺序展开,路径口径与 Kavita 的 `//body/...` 一致。
---@param html string
---@return KavitaElement[]
local function elements(html)
local body = html:match("<body[^>]*>(.-)</body>") or html
local out, stack = {}, { { path = "", counts = {} } }
local pos = 1
while true do
local lt = body:find("<", pos, true)
local text = body:sub(pos, (lt or 0) - 1)
if text ~= "" then
for i = 2, #stack do stack[i].text[#stack[i].text + 1] = text end
end
if not lt then break end
local gt = body:find(">", lt, true)
if not gt then break end
local tag = body:sub(lt + 1, gt - 1)
pos = gt + 1
local close = tag:match("^/%s*([%w:_%-]+)")
local name = not close and tag:match("^([%w:_%-]+)")
if close then
for i = #stack, 2, -1 do
if stack[i].name == close then
for j = #stack, i, -1 do stack[j] = nil end
break
end
end
elseif name then
local parent = stack[#stack]
local idx = (parent.counts[name] or 0) + 1
parent.counts[name] = idx
local el = {
name = name, tag = tag, text = {}, counts = {},
path = (parent.path == "" and "" or parent.path .. "/") .. name .. "[" .. idx .. "]",
}
out[#out + 1] = el
if not VOID[name] and tag:sub(-1) ~= "/" then stack[#stack + 1] = el end
end
end
return out
end
--- 远端 bookScrollId → `//body/...`。`id("X")` 需读本地 epub 第 spine 个文档定位;
--- 读不到 / 找不到返回 nil,调用方退回只按 spine 定位。
---@param epub_path string|nil
---@param spine integer
---@param scroll_id string|nil
---@return string|nil
function Position.resolveScrollId(epub_path, spine, scroll_id)
if type(scroll_id) ~= "string" then return nil end
if scroll_id:match("^//body/") then return scroll_id end
local id = scroll_id:match('^id%("(.-)"%)$') or scroll_id:match("^id%('(.-)'%)$")
if not id or id == "" then return nil end
return withEpub(epub_path, function(doc)
for _idx, el in ipairs(elements(doc.html(spine) or "")) do
if (el.tag:match("%sid%s*=%s*\"([^\"]*)\"") or el.tag:match("%sid%s*=%s*'([^']*)'")) == id then
return "//body/" .. el.path
end
end
end)
end
--- 段落匹配用:解实体,去脚注标记(上标数字与 [N])和全部空白。
---@param s string|nil
---@return string
local function normalizeText(s)
s = require("utils.text").xmlDecode(s or "")
s = s:gsub("%[%d+%]", ""):gsub("\194[\185\178\179]", ""):gsub("\226\129[\176-\185]", "")
return (s:gsub("%s+", ""))
end
--- 选中文本落在哪几段:首行定起始段(探针由长到短:整行 → 前 32 / 16 字节,容忍段内差异),
--- 末行尾部定结束段。KOReader 跨段选区按段换行,所以首末行各自落在一段里。
---@param paras { path: string, text: string }[]
---@param head string 首行(已规范化)
---@param tail string 末行(已规范化)
---@return integer|nil first, integer|nil last
local function findRange(paras, head, tail)
local probes = { head }
if #head > 32 then probes[#probes + 1] = head:sub(1, 32) end
if #head > 16 then probes[#probes + 1] = head:sub(1, 16) end
tail = tail:sub(-math.min(24, #tail))
for _pidx, probe in ipairs(probes) do
for i, para in ipairs(paras) do
if para.text:find(probe, 1, true) then
for j = i, #paras do
if paras[j].text:find(tail, 1, true) then return i, j end
end
return i, i
end
end
end
return nil
end
--- KOReader 划线 → Kavita 注解锚点 { pageNumber, xPath, endingXPath }。
--- 先在 pos0 所在 spine 找,找不到由近及远搜其它 spine;都找不到返回 nil(调用方只带 spine)。
---@param text string|nil 划线原文
---@param pos0 string|nil 起点 xpointer
---@param epub_path string|nil
---@return { pageNumber: integer, xPath: string, endingXPath: string }|nil
function Position.anchor(text, pos0, epub_path)
local lines = {}
for line in (text or ""):gmatch("[^\n]+") do
local clean = normalizeText(line)
if clean ~= "" then lines[#lines + 1] = clean end
end
if #table.concat(lines) < 2 then return nil end
local primary = Position.spine(pos0) or 0
return withEpub(epub_path, function(doc)
local function try(spine)
local html = doc.html(spine)
if not html then return nil end
local paras = {}
for _idx, el in ipairs(elements(html)) do
if el.name == "p" then
paras[#paras + 1] = { path = el.path, text = normalizeText(table.concat(el.text)) }
end
end
local first, last = findRange(paras, lines[1], lines[#lines])
return first and {
pageNumber = spine,
xPath = "//body/" .. paras[first].path,
endingXPath = "//body/" .. paras[last].path,
}
end
local hit = try(primary)
for distance = 1, doc.count do
hit = hit or try(primary - distance) or try(primary + distance)
end
return hit
end)
end
return Position
@@ -0,0 +1,750 @@
--[[--
Kavita 源设置:服务器地址、API Key、书库选择、测试连接。
配置经月读 utils.settings.getSource / saveSource("kavita") 落盘。
@module moonsource_kavita.setting
--]]
local Text = require("utils.text")
local Cache = require("moonsource_kavita.cache")
local KamareUpdate = require("moonsource_kavita.kamare_update")
local _ = require("l10n").get("moonsource_kavita")
local T = require("ffi/util").template
local ID = "kavita"
local Setting = {}
---@return table
local function config()
return require("utils.settings").getSource(ID)
end
---@param text string
---@param timeout number|nil 秒,缺省 3
local function toast(text, timeout)
require("ui.themes.widgets.toast"):new{ text = text, timeout = timeout or 3 }:show()
end
---@param plugin table|nil
local function repaint(plugin)
local desktop = plugin and plugin.desktop
if desktop and desktop.settings_overlay then desktop.settings_overlay:updateView() end
end
---@param plugin table|nil
local function shelfChanged(plugin)
if plugin and plugin.desktop then plugin.desktop:onEvent("shelf_changed") end
end
--- 服务器身份:地址 + API Key。换了就是另一套书架(seriesId 会撞)。
local function libraryFingerprint(cfg)
return table.concat({
Text.rtrimSlashes(Text.stripWhitespace(cfg.base_url)),
Text.stripWhitespace(cfg.api_key),
}, "\0")
end
--- 落盘并作废源实例,让新地址 / Key / 书库立即生效。
--- 不走 SourceChanged:那会把设置页复位到根目录;这里只重画当前叠层。
--- 保存后把配置镜像给 kamare(02 A5 第二处);kamare 侧失败只提示,不阻断 moon 自己的保存。
--- 换服务器 / Key:整源撕本地书架(replaceLibrary 会 reload),不再只靠下次 reconcile。
---@param cfg table
---@param plugin table|nil
---@param refresh_shelf boolean|nil 连接配置 / 书库变了才让书架作废旧数据
---@param previous_fingerprint string|nil 保存前的库身份;与现在不同则清书架
local function save(cfg, plugin, refresh_shelf, previous_fingerprint)
local function commit()
require("utils.settings").saveSource(ID, cfg)
end
local replaced = previous_fingerprint and previous_fingerprint ~= libraryFingerprint(cfg)
if replaced then
if not require("source.logout").replaceLibrary(ID, commit) then
toast(_("准备本地同步失败"))
return false
end
else
commit()
require("source.registry").invalidate()
end
local configured = (cfg.base_url or "") ~= "" and (cfg.api_key or "") ~= ""
if configured and Cache.probe().ok then
local server_key, code = Cache.registerServer(cfg.base_url, cfg.api_key)
if not server_key or code then toast(_("无法同步配置到 kamare")) end
end
repaint(plugin)
if refresh_shelf and not replaced then shelfChanged(plugin) end
return true
end
--- 未配置 / 断网当场提示;否则带忙碌提示调 fn(client, done),fn 结束时必须调 done()。
---@param fn fun(client: KavitaClient, done: fun())
local function withServer(fn)
local client = require("moonsource_kavita.client").new(config())
if not client:configured() then
toast(_("请先填写服务器地址和 API Key"))
return
end
if not require("ui/network/manager"):isConnected() then
toast(_("网络不可用,请先连接 Wi-Fi"))
return
end
local busy = require("ui.themes.widgets.toast"):new{ text = _("正在连接 Kavita…"), dismissable = false }
busy:show()
fn(client, function() busy:close() end)
end
---@param key string
---@param title string
---@param hint string
---@param password boolean
---@param normalize fun(value: string|nil): string
---@param icon string
---@return fun(iw: number): table
local function field(plugin, key, title, hint, password, normalize, icon)
return function(iw)
local value = config()[key] or ""
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true,
kind = "nav", icon = icon, title = title,
status = value ~= "" and (password and "******" or value) or _("未设置"),
status_on = value ~= "",
callback = function()
local cfg = config()
require("ui.themes.widgets.input"):new{
title = title,
fields = { { text = cfg[key] or "", hint = hint, text_type = password and "password" or nil } },
ok_text = _("保存"),
callback = function(input)
local before = libraryFingerprint(cfg)
local next_cfg = require("util").tableDeepCopy(cfg)
next_cfg[key] = normalize(input)
save(next_cfg, plugin, true, before)
end,
}:show()
end,
})
end
end
--- 多选书库:只同步选中的库,书架分类即库名。
local function pickLibraries(plugin)
withServer(function(client, done)
client:json("GET", "/api/Library/libraries", nil, nil, function(libraries, err)
done()
if not libraries then
toast(err)
return
end
local cfg = config()
local chosen = cfg.libraries or {}
local items = {}
for _idx, lib in ipairs(libraries) do
local id = tostring(lib.id)
items[#items + 1] = { text = lib.name or id, value = id, checked = chosen[id] == true }
end
require("ui.themes.widgets.list"):new{
title = _("选择书库"),
multi = true,
items = items,
close_callback = function()
local picked = {}
for _idx, item in ipairs(items) do
if item.checked then picked[item.value] = true end
end
cfg.libraries = picked
save(cfg, plugin, true)
end,
}:show()
end)
end)
end
--- 请求超时(秒):全量书架(all-v2)在慢设备 / 慢服务器上一次要几十秒,
--- 硬上限会让整轮同步中断、书架永远加载不出来。留个设置行按设备调大。
---@return fun(iw: number): table
local function timeoutRow(plugin)
return function(iw)
local client = require("moonsource_kavita.client")
local value = tonumber(config().timeout) or client.DEFAULT_TIMEOUT
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true,
kind = "nav", icon = "hourglass_top", title = _("请求超时"),
status = T(_("%1 秒"), value),
status_on = value ~= client.DEFAULT_TIMEOUT,
callback = function()
local cfg = config()
require("ui.themes.widgets.spin"):new{
title = _("请求超时"),
fields = { {
value = tonumber(cfg.timeout) or client.DEFAULT_TIMEOUT,
min = 10, max = client.MAX_TIMEOUT, step = 10,
label = _("秒"),
} },
callback = function(seconds)
cfg.timeout = seconds ~= client.DEFAULT_TIMEOUT and math.floor(seconds) or nil
save(cfg, plugin)
end,
}:show()
end,
})
end
end
--- 进度心跳间隔(秒):Kavita 的阅读会话时长 = 相邻两次进度写入的间隔,只在关书推一次会是
--- 0 秒会话;阅读期按这个间隔补推当前位置。0 = 关闭(关书 / 切章 / 休眠的推送不受影响)。
---@return fun(iw: number): table
local function heartbeatRow(plugin)
return function(iw)
local Source = require("moonsource_kavita.source")
local default = Source.DEFAULT_HEARTBEAT_INTERVAL
local value = tonumber(config().heartbeat_interval) or default
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true,
kind = "nav", icon = "favorite", title = _("进度心跳间隔"),
-- 行副标题是单行截断的(TextWidget 带 max_width 不换行),这行还有状态与箭头,
-- 右边留给文字的位置很窄:副标题必须短,长解释放不进来。
subtitle = _("阅读时补推进度,0 关闭"),
status = value > 0 and T(_("%1 秒"), value) or _("已关闭"),
status_on = value > 0,
callback = function()
local cfg = config()
require("ui.themes.widgets.spin"):new{
title = _("进度心跳间隔"),
fields = { {
value = tonumber(cfg.heartbeat_interval) or default,
min = 0, max = 600, step = 10,
label = _("秒"),
} },
callback = function(seconds)
cfg.heartbeat_interval = seconds ~= default and math.floor(seconds) or nil
save(cfg, plugin)
end,
}:show()
end,
})
end
end
--- 探测结果是否带清理接口(03 A):只有能用且具备 chapters + delete 才能按章删除。
--- 缺任一项就是「旧接口」,设置行与详情页都据此降级。
---@param probe table
---@return boolean
local function cleanupReady(probe)
if not probe.ok then return false end
local caps = probe.capabilities or {}
return caps.chapters == true and caps.delete == true
end
--- 五态文案(02 A8):镜像失败优先于「增强版」,其余按探测态。
--- 增强版再分「能力齐 / 旧接口」两态(03 A 七态矩阵);旧接口不高亮。
--- 行副标题只留结论,API 版本 / 能力清单不再展示(用户不需要,也会误导)。
---@param probe table
---@return string, boolean
local function cacheStatus(probe)
if probe.state == "enhanced" then
if Cache.mirrorFailed() then return _("配置同步失败"), false end
local ready = cleanupReady(probe)
if probe.version then
return ready and T(_("增强版 v%1"), probe.version)
or T(_("增强版 v%1(旧接口)"), probe.version), ready
end
return ready and _("增强版") or _("增强版(旧接口)"), ready
elseif probe.state == "incompatible" then
return _("版本不兼容"), false
elseif probe.state == "official" then
return _("官方版(无缓存接口)"), false
end
return _("未安装 / 未启用"), false
end
--- 测试连接结果:结论一行 + 明细一行或多行(Toast 用 TextBoxWidget,换行生效)。
---@param headline string
---@param detail string|nil
---@return string
local function connectResult(headline, detail)
return detail and (headline .. "\n" .. detail) or headline
end
local function testConnection()
withServer(function(client, done)
client:request("GET", "/api/Plugin/version", { apiKey = client.api_key }, nil, function(version, err)
done()
local major, minor = (version or ""):match("^(%d+)%.(%d+)")
if not major then
toast(connectResult(err and _("连接失败") or _("连接正常"),
err or _("无法识别 Kavita 版本")))
elseif tonumber(major) == 0 and tonumber(minor) < 9 then
toast(connectResult(_("连接正常"),
T(_("Kavita %1 过旧,需要 0.9 及以上"), Text.trim(version))))
else
toast(table.concat({
_("连接正常"),
T(_("Kavita %1"), Text.trim(version)),
}, "\n"))
end
end)
end)
end
---@param plugin table|nil
---@return fun(iw: number): table
local function libraryRow(plugin)
return function(iw)
local count = 0
for _id in pairs(config().libraries or {}) do count = count + 1 end
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true,
kind = "nav", icon = "library_books", title = _("书库"),
status = count > 0 and T(_("%1 个"), count) or _("未选择"),
status_on = count > 0,
callback = function() pickLibraries(plugin) end,
})
end
end
---@return fun(iw: number): table
local function testRow()
return function(iw)
return require("ui.themes.widgets.row").widget({
width = iw,
kind = "action", icon = "network_check", title = _("测试连接"),
subtitle = _("检查 Kavita 服务器连接与版本"),
callback = testConnection,
})
end
end
--- 只读占用:当前服务器。
---@return table|nil
local function serverUsage()
if not Cache.available("summary") then return nil end
local usage = Cache.summary()
return type(usage) == "table" and usage or nil
end
--- 只读占用:所有服务器(含未关联)。
---@return table|nil
local function allUsage()
if not Cache.available("summary") then return nil end
local usage = Cache.summaryAll()
return type(usage) == "table" and usage or nil
end
--- 详情页打开时的一次统计(03 E):配置了服务器时「本服务器」与「合计」各一次;
--- 没配置时两者都是合计,只走盘一次。`need_all` 由「清理全部」是否出现决定。
---@param need_all boolean
---@return table|nil usage, table|nil all_usage
local function loadUsage(need_all)
local configured = (config().base_url or "") ~= ""
if not configured then
local all = allUsage()
return all, all
end
return serverUsage(), need_all and allUsage() or nil
end
--- 设置行的构建函数(sections 每次重绘都按新宽度重建)。
local function mk(opts)
return function(iw)
opts.width = iw
return require("ui.themes.widgets.row").widget(opts)
end
end
local function installText(plugin)
local dir = require("utils.paths").userPath(Cache.pluginsDir(plugin and plugin.path))
return table.concat({
_("获取增强版"),
_(" 发布页:github.com/backtracker/kamare.koplugin/releases/latest"),
T(_(" 下载 kamare.koplugin.zip,解压后把 kamare.koplugin/ 放进:%1"), dir),
_(" 也可点上方「kamare 增强版」检查并安装最新版。"),
_(" 重启 KOReader。包里要有 kamarecache.lua(没有就是官方版);"),
_(" 增强版与官方版目录同名,不能共存;替换前先删掉旧的 kamare.koplugin/。"),
T(_(" 如该目录不可写,可改用:%1"),
require("utils.paths").userPath(require("datastorage"):getDataDir() .. "/plugins")),
"",
_("增强版功能随版本不同,以实际安装的版本为准。"),
}, "\n")
end
--- 叠层的占用是打开时算的一份;清理之后只 updateView 会留着删前的数字,
--- 所以写入路径显式标记「占用过期」,下次重建先回「正在统计…」再走盘。
local usage_stale = false
---@param plugin table|nil
---@param reload_usage boolean|nil 写入路径传 true(删除后占用要重算)
local function refreshOverlay(plugin, reload_usage)
if reload_usage then usage_stale = true end
repaint(plugin)
end
--- 删除后复查:请求里属于「删除前已缓存」的章如果还在,就是没删掉。
local function leftoverCount(entries, ids)
local wanted = {}
for __, id in ipairs(ids or {}) do wanted[tostring(id)] = true end
local left = 0
for __, entry in ipairs(type(entries) == "table" and entries or {}) do
if wanted[tostring(entry.chapterId)] then left = left + 1 end
end
return left
end
---@param title string
---@param fn fun(): boolean|nil, string|nil, string|nil, any
---@return boolean|nil, string|nil, string|nil, any
local function runBusy(title, fn)
return require("moonsource_kavita.busy").run(title, fn)
end
local function runCleanup(plugin, filter, title)
local entries, code = Cache.chapters()
if not entries then
toast(Cache.message(code) or _("缓存操作失败"))
return
end
local plan = Cache.plan(entries, filter)
if plan.chapters == 0 then
toast(filter == "read" and _("没有已读完的缓存") or _("没有可清理的缓存"))
return
end
local first = filter == "read"
and T(_("将删除 %1 章已读完的缓存(约 %2)。"), plan.chapters, Cache.sizeText(plan.bytes))
or T(_("将删除本服务器的 %1 章(约 %2)。"), plan.chapters, Cache.sizeText(plan.bytes))
local lines = { first }
if plan.queued > 0 then
lines[#lines + 1] = T(_("会中止正在下载的 %1 章,已下载的部分会被删除。"), plan.queued)
end
lines[#lines + 1] = _("阅读进度与 kamare journal 保留。")
require("ui.themes.widgets.confirm"):new{
title = title,
text = table.concat(lines, "\n"),
ok_text = _("清理"),
cancel_text = _("取消"),
ok_callback = function()
local ok, err, message = runBusy(title, function() return Cache.delete(plan.ids) end)
if not ok then
toast(Cache.message(err, message))
return
end
local left = leftoverCount(Cache.chapters(), plan.ids)
if left > 0 then
toast(T(_("已清理 %1 章,%2 章未能删除"), plan.chapters - left, left), 3)
else
toast(T(_("已清理 %1 章,释放约 %2"), plan.chapters, Cache.sizeText(plan.bytes)), 3)
end
refreshOverlay(plugin, true)
shelfChanged(plugin)
end,
}:show()
end
local function runCleanupAll(plugin)
local usage = allUsage()
local chapters = usage and tonumber(usage.chapters) or 0
local bytes = usage and tonumber(usage.used) or 0
require("ui.themes.widgets.confirm"):new{
title = _("清理全部缓存"),
text = table.concat({
T(_("将删除所有服务器(含未关联服务器)共 %1 章(约 %2)。"),
chapters, Cache.sizeText(bytes)),
_("此操作不可撤销,之后阅读需要重新下载。"),
_("阅读进度与 kamare journal 保留。"),
}, "\n"),
ok_text = _("清理"),
cancel_text = _("取消"),
ok_callback = function()
local ok, err, message, detail = runBusy(_("清理全部缓存"),
function() return Cache.deleteAll() end)
if not ok then
toast(Cache.message(err, message))
return
end
local freed = detail and tonumber(detail.bytes) or bytes
toast(T(_("已清理全部缓存,释放约 %1"), Cache.sizeText(freed)), 3)
refreshOverlay(plugin, true)
shelfChanged(plugin)
end,
}:show()
end
--- 详情页状态:占用走盘,先画「正在统计…」,下一拍算完再整页刷新(03 E)。
---@class KavitaCachePageState
---@field pending boolean 占用还在统计
---@field usage table|nil 当前服务器(未配置时是所有服务器合计)
---@field all table|nil 所有服务器合计(「清理全部」用;拿不到就是 nil)
--- 详情页:状态 → 清理(+ 非增强态的安装说明)。
---@param plugin table|nil
---@param state KavitaCachePageState|nil
---@return BookThemeSection[]
local function cacheSections(plugin, state)
state = state or { pending = false }
local probe = Cache.probe()
local caps = probe.capabilities or {}
local configured = (config().base_url or "") ~= ""
local can_plan = cleanupReady(probe)
local can_all = probe.ok and caps.delete_all == true
local usage = state.usage
local all_usage = state.all
local out = {}
local version_status, version_hint
if probe.ok then
version_status, version_hint = probe.version, _("点按检查 kamare 增强版更新")
elseif probe.state == "official" then
version_status, version_hint = _("官方版"), _("点按安装 kamare 增强版")
elseif probe.state == "incompatible" then
version_status, version_hint = _("版本不兼容"), _("点按安装兼容的 kamare 增强版")
else
version_status, version_hint = _("未安装"), _("点按检查并安装 kamare 增强版")
end
local status = {
mk({ icon = "info", title = _("kamare 增强版"),
subtitle = version_hint,
status = version_status, status_on = probe.ok == true,
chevron = true,
callback = function() KamareUpdate:manualCheck(plugin) end }),
}
if probe.ok then
local features = Cache.featureText(probe)
if features then
status[#status + 1] = mk({ icon = "book", title = _("增强版功能"),
subtitle = features, chevron = false })
end
end
status[#status + 1] = mk({ icon = "info", title = _("加载路径"),
subtitle = probe.path and require("utils.paths").userPath(probe.path) or _("未加载"), chevron = false })
if state.pending and Cache.available("summary") then
status[#status + 1] = mk({
icon = "storage", title = _("缓存占用"),
subtitle = _("正在统计…"), chevron = false,
})
elseif usage then
local scope = configured and "" or _("(含未关联服务器)")
status[#status + 1] = mk({
icon = "storage", title = _("缓存占用"),
subtitle = T(_("已用 %1%2,可用 %3"),
Cache.sizeText(usage.used), scope, Cache.sizeText(usage.available)),
status = T(_("%1 章"), tostring(usage.chapters or 0)),
status_on = true, chevron = false,
})
end
if probe.ok and Cache.mirrorFailed() then
status[#status + 1] = mk({
icon = "warning", title = _("配置同步失败"),
subtitle = _("服务器配置没能写入 kamare,缓存操作可能找不到服务器"),
status = _("重试同步"), chevron = false,
callback = function()
local cfg = config()
local server_key, code = Cache.registerServer(cfg.base_url, cfg.api_key)
toast(server_key and _("已重新同步配置") or Cache.message(code) or _("同步失败"))
refreshOverlay(plugin)
end,
})
end
out[#out + 1] = { title = _("状态"), rows = status }
--- 「清理全部」一行:跨服务器(含未关联),数字来自 summaryAll 而不是本服务器。
--- 统计到 0 章时置灰并写「没有可清理的缓存」(03 待确认 3);还没统计完 /
--- 拿不到统计时不猜,保持可点(删除时以 kamare 的事实为准)。
local function cleanupAllRow()
local count = all_usage and tonumber(all_usage.chapters) or nil
local empty = count ~= nil and count <= 0
local subtitle
if empty then
subtitle = _("没有可清理的缓存")
elseif all_usage then
subtitle = T(_("含未关联服务器 · %1 章 · 约 %2"), tostring(all_usage.chapters or 0),
Cache.sizeText(all_usage.used))
else
subtitle = _("含未关联服务器")
end
return mk({
icon = "delete", title = _("清理全部"),
subtitle = subtitle,
enabled = not empty,
chevron = not empty,
callback = function() runCleanupAll(plugin) end,
})
end
if can_plan and configured then
local entries = Cache.chapters() or {}
local read_plan = Cache.plan(entries, "read")
local all_plan = Cache.plan(entries, "all")
local cleanup = {
mk({
icon = "delete", title = _("清理已读"),
subtitle = read_plan.chapters > 0
and T(_("%1 章 · 约 %2"), read_plan.chapters, Cache.sizeText(read_plan.bytes))
or _("没有可清理的缓存"),
enabled = read_plan.chapters > 0,
chevron = read_plan.chapters > 0,
callback = function() runCleanup(plugin, "read", _("清理已读")) end,
}),
mk({
icon = "delete", title = _("清理本服务器"),
subtitle = all_plan.chapters > 0
and T(_("%1 章 · 约 %2"), all_plan.chapters, Cache.sizeText(all_plan.bytes))
or _("没有可清理的缓存"),
enabled = all_plan.chapters > 0,
chevron = all_plan.chapters > 0,
callback = function() runCleanup(plugin, "all", _("清理本服务器")) end,
}),
}
if can_all then
cleanup[#cleanup + 1] = cleanupAllRow()
end
out[#out + 1] = { title = _("清理"), rows = cleanup }
elseif can_all and not configured then
out[#out + 1] = { title = _("清理"), rows = {
mk({ icon = "info", title = _("未配置服务器"),
subtitle = _("填写服务器地址与 API Key 后,可按服务器清理已读或全部缓存"),
chevron = false }),
cleanupAllRow(),
} }
elseif probe.ok and not can_plan then
out[#out + 1] = { title = _("清理"), rows = {
mk({ icon = "info", title = _("当前 kamare 没有清理接口"),
subtitle = _("升级到带 chapters / delete_all 的版本后才能清理"),
chevron = false }),
} }
end
if not probe.ok then
local rows = {}
if probe.state == "incompatible" and probe.api_version then
rows[#rows + 1] = mk({
icon = "warning", title = _("版本不兼容"),
subtitle = T(_("kamare API v%1 与当前支持的 v1 不兼容;装回支持 v1 的增强版后可管理缓存"),
tostring(probe.api_version)),
chevron = false,
})
end
local text = installText(plugin)
rows[#rows + 1] = function(iw) return require("ui.themes.widgets.row").note(iw, text) end
out[#out + 1] = {
title = probe.state == "incompatible" and _("版本与获取") or _("获取增强版"),
rows = rows,
}
end
return out
end
---@param plugin table|nil
local function showCachePage(plugin)
local desktop = plugin and plugin.desktop
if not desktop then
toast(_("请先打开月读桌面"))
return
end
local state = { pending = true }
local scheduled = false
require("desktop.pages.setting.overlay").push(desktop, {
title = _("漫画缓存"),
sections = function()
-- 占用走盘:先让叠层用「正在统计…」画出来,下一拍算完再刷新(03 E)。
-- 删除后 refreshOverlay(…, true) 把占用标脏,这里重新走一遍同一条路径。
if usage_stale then
usage_stale = false
state.pending = true
state.usage, state.all = nil, nil
end
if state.pending and not scheduled then
scheduled = true
require("ui/uimanager"):nextTick(function()
scheduled = false
local probe = Cache.probe()
local need_all = probe.ok and (probe.capabilities or {}).delete_all == true
state.usage, state.all = loadUsage(need_all)
state.pending = false
refreshOverlay(plugin)
end)
end
return cacheSections(plugin, state)
end,
})
end
---@param plugin table|nil
---@return fun(iw: number): table
local function cacheRow(plugin)
return function(iw)
local probe = Cache.probe()
local status, on = cacheStatus(probe)
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true,
kind = "nav", icon = "download_done", title = _("漫画缓存"),
-- 副标题只承诺真能做到的事:旧接口没有清理入口。
subtitle = cleanupReady(probe)
and _("清理已读、按系列或全部清理")
or _("状态与获取增强版"),
status = status, status_on = on,
callback = function() showCachePage(plugin) end,
})
end
end
---@param value string|nil
---@return string
local function normalizeUrl(value)
return Text.rtrimSlashes(Text.stripWhitespace(value))
end
--- 设置页按 03 原型分三块:连接 / 缓存与同步 / 诊断。
---@param plugin table|nil 月读插件实例(取 plugin.path 定位实际安装目录)
---@return BookThemeSection[]
function Setting.sections(plugin)
local connect = {
field(plugin, "base_url", _("服务器地址"), "https://kavita.example.com", false, normalizeUrl, "dns"),
field(plugin, "api_key", _("API Key"), _("Kavita 用户设置 → API Key"), true, Text.stripWhitespace, "key"),
libraryRow(plugin),
}
if (config().api_key or "") ~= "" then
connect[#connect + 1] = require("source.logout").row(ID, _("确定退出 Kavita 账号?"), function()
local cfg = config()
cfg.api_key = ""
require("utils.settings").saveSource(ID, cfg)
local Cache = require("moonsource_kavita.cache")
Cache.deleteAll()
Cache.reset()
end)
end
return {
{
title = _("连接"),
rows = connect,
},
{
title = _("缓存与同步"),
rows = { cacheRow(plugin), heartbeatRow(plugin), timeoutRow(plugin) },
},
{
title = _("诊断"),
rows = { testRow() },
},
}
end
--- 扁平行列表(兼容只认 rows 的调用方与测试);顺序与分组一致。
---@param plugin table|nil
---@return table[]
function Setting.rows(plugin)
local rows = {}
for _idx, section in ipairs(Setting.sections(plugin)) do
for _row_idx, row in ipairs(section.rows) do rows[#rows + 1] = row end
end
return rows
end
--- 远程管理「连接配置」网页上的表单;书库要连服务器挑,仍在设备上选。
Setting.remote = {
{ key = "base_url", label = _("服务器地址"), type = "url", placeholder = "https://kavita.example.com",
normalize = normalizeUrl },
{ key = "api_key", label = _("API Key"), secret = true, normalize = Text.stripWhitespace },
}
Setting.replace_on_remote = { "base_url", "api_key" }
return Setting
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,417 @@
--[[--
Kavita 阅读统计纯核心:reading-history 条目 + 身份 / 时区上下文 → reading_stats 行与替换指令。
条目是「会话 × 系列」切片。日 / 时归属按服务端给的 UTC 时刻(`startTimeUtc`)在**设备本地时区**
自行分桶:展示端(SQLite `localtime`、`os.date`)用的是同一个进程时区,两边同一真源才对得上账。
服务端 `localDate` 是它按请求的 `TimeZoneId` 预先算的日期,映射不上时回退 UTC 会把整段挪一天,
所以它只当拿不到 `startTimeUtc` 时的兜底。
时长取各章活动段之和(有效阅读时间,不含会话内空档,与本地计时语义一致);
条目级与聚合结果 `<= 0` 一律丢弃 —— Kavita 会把「打开没读」的会话也写一条 0 时长记录。
身份粒度由调用方给(`volumes`:本地目录章数):1 章的单卷系列记 series 行,多卷系列记
`seriesId:chapterId` 卷行。一条会话可以跨章(多卷)——时长 / 页数按章拆到各卷,
否则会把《2001》的时长记到《2010》头上。
账户日桶 `__kv:day:<当天零点>` 的页数按天**先求和再钳制**(`max(0, ·)`):服务端 pagesRead
实测有负数(退页),逐条钳制会让 +1 / -1 相抵的当天凭空多出 1 页。漫画不用 pagesRead 求和,
而是按最远进度算新推进的页数(见下),贡献本身已 >= 0。
账户时段桶 `__kv:hour:<整点>`:每条活动行的时长记在它起始时刻所在的那个本地整点(跨整点的活动行
整体算起始小时,与「跨零点的会话整体算起始日」同一口径),供「阅读时段」图用;云端只有这一层
粒度,再细就要按跨度分摊,而活动行的跨度含空档,分摊反而把空档算到隔壁小时。
阅读会话行(`cloud_session`):每个「会话 × 章」切片的起始时刻与时长单独落一行,
供书详情 / 统计页的「阅读记录」列出真的读了几点几分;时长不计入日 / 时段 / 总量行
(那些桶已经包含它),只在 `sessionRows` 里读。页数(`event_count`)不另写记录类型:
核心从这一行累加单书页数。页数口径分两种:
- 漫画(Image / Archive):`event_count` = **本次新推进的页数**,不是 `pagesRead`。
`pagesRead` 是「这次翻了多少页」,重读会重复计入(实测 194 页的卷求和 284);
按最远进度算,`SUM(event_count)` 才等于读到的最远页码(≤ 总页数),与 Kavita 的百分比一致。
所以漫画还要补 `page = endPage` / `total_pages = 卷级总页数`。
- epub / PDF:`pagesRead` 是唯一页数来源,`event_count` 照旧;页坐标仍为 0。
全量重拉:日桶 / 时段桶 / 总量行按「前缀 + 覆盖到最后观测桶的时间窗」替换;单书行按「上次 ∪ 本次
身份」精确替换,顺带清掉身份漂移(单卷 ↔ 多卷、系列重建)遗留的孤儿行。
纯函数(无文件 / 网络 IO、无全局状态,只经 `logger` 写日志):目录、卷名与「上次身份」由源钩子经 ctx 注入。
@module moonsource_kavita.stats
--]]
local logger = require("utils.log")
local Stats = {}
local DAY_PREFIX = "__kv:day:"
local HOUR_PREFIX = "__kv:hour:"
local TOTAL_ID = "__kv:total"
--- 单条阅读会话(会话 × 章切片)——只给「阅读记录」列表用,不参与任何时长汇总。
local SESSION_RECORD = "cloud_session"
--- features/clock/init.lua 的 Clock.TIMEZONES 的 19 项 POSIX 串 → Kavita 的 TimeZoneId。
--- 只查表:不读 /etc/localtime(KOReader 设备上不保证存在,读到的也未必是用户选的时区),
--- 不按偏移猜地区。映射不上就按 UTC 请求 —— 只影响 `localDate` 这个兜底(正常条目都带
--- `startTimeUtc`,分日 / 分时按设备本地时区自行换算,见 utcEpoch / dayStart)。
local IANA_BY_POSIX = {
["HST10"] = "Pacific/Honolulu",
["AKST9AKDT,M3.2.0,M11.1.0"] = "America/Anchorage",
["PST8PDT,M3.2.0,M11.1.0"] = "America/Los_Angeles",
["MST7MDT,M3.2.0,M11.1.0"] = "America/Denver",
["CST6CDT,M3.2.0,M11.1.0"] = "America/Chicago",
["EST5EDT,M3.2.0,M11.1.0"] = "America/New_York",
["<-03>3"] = "America/Sao_Paulo",
["UTC0"] = "UTC",
["GMT0BST,M3.5.0/1,M10.5.0"] = "Europe/London",
["CET-1CEST,M3.5.0,M10.5.0/3"] = "Europe/Berlin",
["EET-2EEST,M3.5.0/3,M10.5.0/4"] = "Europe/Athens",
["MSK-3"] = "Europe/Moscow",
["<+04>-4"] = "Asia/Dubai",
["IST-5:30"] = "Asia/Kolkata",
["<+07>-7"] = "Asia/Bangkok",
["CST-8"] = "Asia/Shanghai",
["JST-9"] = "Asia/Tokyo",
["AEST-10AEDT,M10.1.0,M4.1.0/3"] = "Australia/Sydney",
["NZST-12NZDT,M9.5.0,M4.1.0/3"] = "Pacific/Auckland",
}
--- 设备时钟的 POSIX 串 → IANA。未知 / 空串(跟随系统)回退 UTC 并记日志。
---@param posix string|nil 进程 TZ 环境变量(时钟功能按设置写入)
---@return string
function Stats.ianaTimezone(posix)
local iana = type(posix) == "string" and IANA_BY_POSIX[posix] or nil
if iana then return iana end
logger.warn("kavita stats timezone unmapped, fallback to UTC", posix)
return "UTC"
end
--- 合成 reading_stats 行;云端默认没有页坐标,page / total_pages 恒为 0。
--- 漫画(Image / Archive)的会话行由调用方在拿到 endPage / totalPages 后补上。
---@param source_id string
---@param stable_id string
---@param record_type string
---@param start_time number
---@param duration number
---@param last_time number
---@return BookStatsRow
local function statsRow(source_id, stable_id, record_type, start_time, duration, last_time)
return {
source_id = source_id,
stable_id = stable_id,
record_type = record_type,
page = 0,
start_time = start_time,
duration = duration,
total_pages = 0,
last_time = last_time,
}
end
--- 服务端 localDate("2026-10-15T00:00:00")→ 当天设备本地零点;解不出返回 nil。
--- 只取日期部分:时刻是被请求时区下的零点,换算成设备本地同一日期即可。
---@param local_date any
---@return number|nil
local function localMidnight(local_date)
local y, m, d = tostring(local_date):match("^(%d%d%d%d)-(%d%d)-(%d%d)")
if not y then return nil end
return os.time({ year = tonumber(y), month = tonumber(m), day = tonumber(d), hour = 0 })
end
--- 服务端 UTC 时间戳("2026-10-15T23:51:47.4527045")→ 设备本地 epoch;解不出返回 nil。
--- os.time 按进程 TZ(POSIX 串,自带夏令时规则)解释墙钟,所以先把 UTC 墙钟当本地算出 E',
--- 再补回一个用 E' 处的本地偏移量的差。偏移的表必须重建:os.date 给的表带 `isdst`,直接回喂
--- os.time 会把夏令时钉成标准时、整整差一小时(跨夏令时切换的时区实测过)。
---@param text any
---@return number|nil
local function utcEpoch(text)
local y, mo, d, h, mi, s = tostring(text):match("^(%d%d%d%d)%-(%d%d)%-(%d%d)T(%d%d):(%d%d):(%d%d)")
if not y then return nil end
local as_local = os.time({ year = tonumber(y), month = tonumber(mo), day = tonumber(d),
hour = tonumber(h), min = tonumber(mi), sec = tonumber(s) })
if not as_local then return nil end
local u = os.date("!*t", as_local)
local back = os.time({ year = u.year, month = u.month, day = u.day, hour = u.hour, min = u.min, sec = u.sec })
return as_local + os.difftime(as_local, back)
end
--- 设备本地时区的当日零点。`isdst` 取自本地分解,跨切换的零点不会被挪一小时。
---@param epoch number
---@return number
local function dayStart(epoch)
local t = os.date("*t", epoch)
return os.time({ year = t.year, month = t.month, day = t.day, hour = 0, isdst = t.isdst })
end
--- 时段桶键:`day` 那天的、`epoch` 所在小时。跨零点的活动行仍记在条目那天(取小时、换日期),
--- 这样「日页面逐格之和 = 当日日桶」,不会出现某天的时段和比标题少一截。
---@param day number 当日零点
---@param epoch number 活动行起始时刻
---@return number
local function hourBucket(day, epoch)
local d = os.date("*t", day)
local a = os.date("*t", epoch)
return os.time({ year = d.year, month = d.month, day = d.day, hour = a.hour, isdst = a.isdst })
end
--- 本地目录章数:1 = 单卷(读在 series 行),>1 = 多卷(读在卷行);拿不到返回 nil。
--- 数字 / 字符串键都收:状态文件里的 seriesId 可能两种写法。
---@param volumes table
---@param series_id string
---@return number|nil
local function volumeCount(volumes, series_id)
local count = volumes[series_id]
if count == nil then count = volumes[tonumber(series_id) or series_id] end
count = tonumber(count)
if not count or count < 1 then return nil end
return count
end
--- 漫画章行:页数贡献要按身份排完序才能算(见 fromHistory 里「漫画最远进度」一段)。
---@class KavitaComicSlice
---@field identity string 卷身份(单卷 = seriesId,多卷 = seriesId:chapterId)
---@field day number 该活动行归属的本地零点(推进的页数记进这一天)
---@field epoch number|nil 会话行 start_time(也是排序键)
---@field order number 回包顺序,仅用于同一时刻的稳定排序
---@field duration number 秒;`> 0` 才发行
---@field page number 原始 endPage(会话行的进度坐标)
---@field end_page number 钳到总页数后的结束页(算推进页数用)
---@field total_pages number 卷级总页数
---@class KavitaStatsContext
---@field source_id string 本源 id(写进每行)
---@field fetched_at number|nil 拉取时刻(缺省 now);写进行 / 桶的 last_time
---@field volumes table<number|string, number>|nil seriesId → 本地目录章数(1 = 单卷)
---@field seen string[]|nil 上次拉取的身份列表(用于清身份漂移遗留的孤儿行)
--- reading-history 条目 → reading_stats 行 + 替换指令 + 本次身份。
---@param entries table[]|nil reading-history 条目(wire 已解码),通常为分页合并后的全量
---@param ctx KavitaStatsContext
---@return { rows: BookStatsRow[], replace: BookStatsPullReplace, identities: string[] }
function Stats.fromHistory(entries, ctx)
ctx = ctx or {}
local source_id = ctx.source_id
local fetched_at = tonumber(ctx.fetched_at) or os.time()
local volumes = ctx.volumes or {}
local rows = {}
local book_days = {} ---@type table<string, table<number, number>> 身份 → 日 → 秒
local book_totals = {} ---@type table<string, number>
local day_durations = {} ---@type table<number, number>
local day_pages = {} ---@type table<number, number>
local hour_durations = {} ---@type table<number, number> 整点 → 秒(账户时段桶)
local last_day = 0 ---@type number 本次回包里最晚的观测日(零点)
local last_hour = 0 ---@type number 本次回包里最晚的观测整点
local comic_slices = {} ---@type KavitaComicSlice[] 漫画章行,算完进度贡献再落行
local identities, known, warned_series = {}, {}, {}
--- 记下本次出现的身份。零时长条目也记:它上次可能有行,靠 replace.books 清掉。
local function noteIdentity(identity)
if identity and not known[identity] then
known[identity] = true
identities[#identities + 1] = identity
end
end
for _idx, entry in ipairs(type(entries) == "table" and entries or {}) do
local series_id = entry.seriesId ~= nil and tostring(entry.seriesId) or nil
local count = series_id and volumeCount(volumes, series_id) or nil
if not count then
-- 判不出单卷 / 多卷的系列整体跳过:身份是错的比缺行更糟(源钩子侧也会记)。
if series_id and not warned_series[series_id] then
warned_series[series_id] = true
logger.warn("kavita stats skip series without volume info", series_id)
end
else
-- 有 UTC 时刻就按设备本地分日 / 分时;没有才退服务端按请求时区算好的 localDate(无小时)。
local anchor = utcEpoch(entry.startTimeUtc)
local day
if anchor then
day = dayStart(anchor)
else
day = localMidnight(entry.localDate)
if day then logger.warn("kavita stats entry without usable startTimeUtc", series_id) end
end
if not day then
logger.warn("kavita stats entry without usable day", series_id)
else
if day > last_day then last_day = day end
local chapters = type(entry.chapters) == "table" and entry.chapters or {}
-- 漫画才有真实页坐标:Kavita 的 seriesFormat 0 = Image、1 = Archive 是图片页;
-- epub(3)的 chapter.pages 是 spine / 阅读单元(6 万字的书 32 个),PDF(4)同理,
-- 都不是渲染页,填进 page / total_pages 会让详情页的「读了多少页」变成假的。
-- seriesFormat 在条目顶层,不在 chapter 上(实测响应见 history-7453-all.json)。
local fmt = tonumber(entry.seriesFormat)
local comic = fmt == 0 or fmt == 1
local entry_duration = 0
for _ci, chapter in ipairs(chapters) do
entry_duration = entry_duration + (tonumber(chapter.durationSeconds) or 0)
end
-- 单卷:没有章行也读在 series 上;多卷:没有 chapterId 就拆不出来,跳过该章。
if count == 1 then noteIdentity(series_id) end
local contributes = entry_duration > 0
for _ci, chapter in ipairs(chapters) do
local identity = series_id
if count > 1 then
identity = chapter.chapterId ~= nil
and (series_id .. ":" .. tostring(chapter.chapterId)) or nil
if not identity then
logger.warn("kavita stats chapter without chapterId", series_id)
end
end
noteIdentity(identity)
if identity then
local duration = tonumber(chapter.durationSeconds) or 0
-- 章活动行自己的起始时刻(时段桶 / 会话行 / 漫画排序共用);拿不到就退回条目起始时刻。
local chapter_epoch = utcEpoch(chapter.startTimeUtc) or anchor
if contributes and duration > 0 then
local days = book_days[identity]
if not days then
days = {}
book_days[identity] = days
end
days[day] = (days[day] or 0) + duration
book_totals[identity] = (book_totals[identity] or 0) + duration
day_durations[day] = (day_durations[day] or 0) + duration
-- 时段桶:按活动行自己的起始小时;拿不到就退回条目起始时刻。
if chapter_epoch then
local bucket = hourBucket(day, chapter_epoch)
hour_durations[bucket] = (hour_durations[bucket] or 0) + duration
if bucket > last_hour then last_hour = bucket end
end
end
if comic then
-- 漫画的页数不能边遍历边累加:`pagesRead` 是「这次翻了多少页」,重读会重复计入。
-- 先收集,按身份(卷)× 起始时刻排序后再算「本次新推进的页数」。
local total_pages = math.max(0, tonumber(chapter.totalPages) or 0)
local page = math.max(0, tonumber(chapter.endPage) or 0)
comic_slices[#comic_slices + 1] = {
identity = identity,
day = day,
epoch = chapter_epoch,
order = #comic_slices + 1,
duration = duration,
page = page,
-- 只有拿到总页数才钳:缺总页数时别凭空假设一个上界。
end_page = total_pages > 0 and math.min(page, total_pages) or page,
total_pages = total_pages,
}
elseif contributes then
if duration > 0 and chapter_epoch then
-- 阅读会话行:详情「阅读记录」按真实起止时间列出这一段。
local session = statsRow(source_id, identity, SESSION_RECORD,
chapter_epoch, duration, fetched_at)
session.event_count = math.max(0, tonumber(chapter.pagesRead) or 0)
rows[#rows + 1] = session
end
day_pages[day] = (day_pages[day] or 0) + (tonumber(chapter.pagesRead) or 0)
end
end
end
end
end
end
-- 漫画:按身份(卷)分别按起始时刻升序走一遍,只留「比此前更远」的页数 —— 这样重读不再重复计入,
-- 跳读也只按推进到哪算,`SUM(event_count)` = 读到的最远页码(天然 ≤ 总页数),与 Kavita 百分比一致。
-- 回包可能是新→旧(服务端按时间倒序),所以必须排序,不能依赖遍历顺序。
table.sort(comic_slices, function(a, b)
if a.identity ~= b.identity then return a.identity < b.identity end
local ae, be = a.epoch or 0, b.epoch or 0
if ae ~= be then return ae < be end
return a.order < b.order
end)
local reached = {} ---@type table<string, number> 身份(卷)→ 此前到达的最远页码
for _idx, slice in ipairs(comic_slices) do
local previous = reached[slice.identity] or 0
local advance = slice.end_page - previous
if advance < 0 then advance = 0 end
if slice.end_page > previous then reached[slice.identity] = slice.end_page end
-- 零时长章行不发行(会话行说的是「这一段读了多久」),但推进照样算进当天页数:
-- 否则这次跳读会从当天页数里消失,而后续会话又因 reached 更高而少算。
day_pages[slice.day] = (day_pages[slice.day] or 0) + advance
-- 零时长章行也要发行:Kavita 的会话是「两次进度写入之间」,只写一次(开书 / 关书各一次)
-- 就是 0 秒,但推进的页数是真的。丢掉它,详情页「已读页数 / 上次阅读」会整段消失
-- (另一台设备刚读的那一卷尤其明显)。既没时长又没推进的(打开没翻)才跳过。
if slice.epoch and (slice.duration > 0 or advance > 0) then
local session = statsRow(source_id, slice.identity, SESSION_RECORD,
slice.epoch, slice.duration, fetched_at)
session.event_count = advance
-- page = endPage(读到哪一页,核心 reading_stats.page 的语义);total_pages 取卷级,
-- 多卷系列汇总处取 MAX。pagesRead = 0 是合法值(打开没翻页),不是缺数据。
session.page = slice.page
session.total_pages = slice.total_pages
rows[#rows + 1] = session
end
end
for identity, days in pairs(book_days) do
for day, duration in pairs(days) do
if duration > 0 then
rows[#rows + 1] = statsRow(source_id, identity, "book_day", day, duration, fetched_at)
end
end
end
for identity, duration in pairs(book_totals) do
if duration > 0 then
rows[#rows + 1] = statsRow(source_id, identity, "book_total", fetched_at, duration, fetched_at)
end
end
local grand_total = 0
for day, duration in pairs(day_durations) do
grand_total = grand_total + duration
if duration > 0 then
local row = statsRow(source_id, DAY_PREFIX .. tostring(day), "day", day, duration, fetched_at)
row.event_count = math.max(0, day_pages[day] or 0)
rows[#rows + 1] = row
end
end
for hour, duration in pairs(hour_durations) do
if duration > 0 then
rows[#rows + 1] = statsRow(source_id, HOUR_PREFIX .. tostring(hour), "hour", hour, duration, fetched_at)
end
end
if grand_total > 0 then
rows[#rows + 1] = statsRow(source_id, TOTAL_ID, "total", 0, grand_total, fetched_at)
end
-- 稳定输出:持久化顺序与对账都别受 pairs 遍历顺序影响。
table.sort(rows, function(a, b)
if a.record_type ~= b.record_type then return a.record_type < b.record_type end
if a.start_time ~= b.start_time then return a.start_time < b.start_time end
return a.stable_id < b.stable_id
end)
table.sort(identities)
local books, book_known = {}, {}
local function addBook(stable_id)
if type(stable_id) == "string" and stable_id ~= "" and not book_known[stable_id] then
book_known[stable_id] = true
books[#books + 1] = stable_id
end
end
for _idx, stable_id in ipairs(type(ctx.seen) == "table" and ctx.seen or {}) do addBook(stable_id) end
for _idx, identity in ipairs(identities) do addBook(identity) end
table.sort(books)
return {
rows = rows,
replace = {
mode = "ranges",
ranges = {
-- 全量重拉:窗口一直连到最后观测日 / 整点的桶止,清掉本次回包里已消失的桶。
-- 上界不能只取拉取时刻:服务端「当天」可能晚于设备本地的拉取时刻(设备为负偏移),
-- 桶零点会落在窗口外、清不掉(残留到下一轮)。
{ stable_prefix = DAY_PREFIX, from_ts = 0, to_ts = math.max(fetched_at, last_day + 86399) },
{ stable_prefix = HOUR_PREFIX, from_ts = 0, to_ts = math.max(fetched_at, last_hour + 3599) },
{ stable_prefix = TOTAL_ID, from_ts = 0, to_ts = 0 },
},
-- 上次 ∪ 本次:身份漂移后旧身份不再出现在回包里,只能按它精确清。
books = books,
},
-- 交回给源持久化:下次拉取当「上次身份」用。
identities = identities,
}
end
return Stats
@@ -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
File diff suppressed because it is too large. Load diff