✨ (kmoe): 下载的 EPUB 按页序转成 CBZ

转不了时仍打开原来的 EPUB,已下载的卷不再重新扣额度。
This commit is contained in:
Garfield committed 2026-12-01 11:34:05 +08:00
1 parent 6fddb67ab3
commit fd1cd66cd6
7 files changed
+497 -55

No files matched your search

@@ -9,8 +9,8 @@
| 搜索与书城 | 支持 | 排序、连载状态、语言、分类筛选,每页 21 部,默认聚合约 60 部;无需登录 |
| 详情 | 支持 | 作者、分类、简介、封面;无需登录 |
| 卷列表 | 支持 | 需要登录;一卷是一章,单行本、话、番外按网站顺序排列 |
| 漫画阅读 | 支持 | 整卷下载 EPUB(普通线路);网站要求账号先验证手机号,并消耗账号下载额度;下载要求 UA 与登录时完全一致 |
| 卷缓存与离线阅读 | 支持 | 只在打开或手动缓存时下载,不做阅读期预取;已下载的卷离线可读;批量缓存未实测 |
| 漫画阅读 | 支持 | 整卷下载 EPUB 后按目录页序转成 CBZ;转不了时仍打开原来的 EPUB。已有 EPUB 的卷内页码不沿用。网站要求账号先验证手机号,并消耗账号下载额度;下载要求 UA 与登录时完全一致 |
| 卷缓存与离线阅读 | 支持 | 只在打开或手动缓存时下载,不做阅读期预取;缓存的是 CBZ,已下载的 EPUB 离线打开时再转;批量缓存未实测 |
| 书架拉取 | 支持 | 网站「收藏」即书架,只订阅不收藏的书不算;收藏页出现分页时不按缺席下架 |
| 书架新增与移出 | 支持 | 改网站收藏,之后重新拉取书架确认 |
| 阅读进度同步 | 不支持 | 网站没有阅读进度接口,只保存本地进度 |
@@ -10,6 +10,6 @@ return {
id = "kmoe",
name = _("Kmoe"),
type = "chapter",
description = _("Kmoe 漫画,按卷下载 EPUB 阅读"),
description = _("Kmoe 漫画,按卷下载后转成 CBZ 阅读"),
abilities = { _("搜索与发现"), _("书架同步") },
}
@@ -1,6 +1,7 @@
--[[--
Kmoe 一卷 = 一章:取下载地址,把整卷 EPUB 下到书目录,按卷号命名。
Kmoe 一卷 = 一章。站点只给 EPUB,按 vol.opf 的 spine 抽出每页那一张图,打成不压缩的 CBZ。
图片文件名是乱的,页序只在 spine 里。转不成时留下 EPUB,阅读器仍打开它。
一卷几十 MB,而且占用账号的下载额度,所以只在打开或用户点缓存时下载,不做阅读期预取。
@module moonsource_kmoe.chapter
@@ -13,15 +14,23 @@ local Chapter = {}
---@param identity BookIdentity
---@param chapter BookChapter
---@param ext string
---@return string
local function volumePath(identity, chapter, ext)
return Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/" .. chapter.uid .. ext
end
--- 交给阅读器的漫画路径。
---@param identity BookIdentity
---@param chapter BookChapter
---@return string
function Chapter.path(identity, chapter)
return Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/" .. chapter.uid .. ".epub"
return volumePath(identity, chapter, ".cbz")
end
--- 文件是完整的 EPUB(zip 头)。
---@param path string
---@return boolean
local function isEpub(path)
local function isZip(path)
local f = io.open(path, "rb")
if not f then return false end
local head = f:read(4)
@@ -29,32 +38,286 @@ local function isEpub(path)
return head == "PK\3\4"
end
--- 已下载好的卷;没有则 nil。
--- 已转好的 CBZ;没有则 nil。
---@param identity BookIdentity
---@param chapter BookChapter
---@return string|nil
function Chapter.existing(identity, chapter)
local path = Chapter.path(identity, chapter)
return isEpub(path) and path or nil
return isZip(path) and path or nil
end
--- 下载一卷;已有文件直接复用。
--- 还没转成 CBZ 的 EPUB。离线打开靠它,不重新下载。
---@param identity BookIdentity
---@param chapter BookChapter
---@return string|nil
function Chapter.epubOnDisk(identity, chapter)
local path = volumePath(identity, chapter, ".epub")
return isZip(path) and path or nil
end
---@param path string
---@return string
local function shellQuote(path)
return "'" .. path:gsub("'", "'\\''") .. "'"
end
---@param path string
---@return string
local function normalize(path)
local parts = {}
for seg in path:gmatch("[^/]+") do
if seg == ".." then
parts[#parts] = nil
elseif seg ~= "." then
parts[#parts + 1] = seg
end
end
return table.concat(parts, "/")
end
---@param dir string
---@param rel string
---@return string
local function under(dir, rel)
rel = rel:gsub("\\", "/")
if rel:sub(1, 1) == "/" then return normalize(rel:sub(2)) end
if dir == "" then return normalize(rel) end
return normalize(dir .. "/" .. rel)
end
---@param tag string
---@param name string
---@return string|nil
local function attr(tag, name)
return tag:match(name .. '%s*=%s*"([^"]*)"') or tag:match(name .. "%s*=%s*'([^']*)'")
end
--- spine 的 href,顺序就是阅读顺序。缺一页则整卷不能转。
---@param opf string
---@return string[]|nil
local function spineHrefs(opf)
local id_href = {}
for tag in opf:gmatch("<[^>]*item%s[^>]*>") do
local id, href = attr(tag, "id"), attr(tag, "href")
if id and href then id_href[id] = href end
end
local hrefs = {}
for tag in opf:gmatch("<[^>]*itemref%s[^>]*>") do
local href = id_href[attr(tag, "idref") or ""]
if not href then return nil end
hrefs[#hrefs + 1] = href
end
if #hrefs == 0 then return nil end
return hrefs
end
--- 一页 HTML 里的那一张图。多图、缺图、非 0 旋转都转不了。
---@param html string|nil
---@return string|nil src
---@return string|nil ext_or_err
local function pageImage(html)
if type(html) ~= "string" then return nil, "pages" end
local _, count = html:gsub("<img%s", "")
if count ~= 1 then return nil, "pages" end
local tag = html:match("<img%s[^>]*>")
local src = attr(tag, "src")
if not src or src == "" then return nil, "pages" end
local rot = tonumber(tag:match('kmoetag%s*=%s*"rotate:(%-?%d+)"')
or tag:match("kmoetag%s*=%s*'rotate:(%-?%d+)'")) or 0
rot = rot % 360
if rot ~= 0 then return nil, "rotate" end
local ext = src:lower():match("%.([a-z0-9]+)$")
if ext == "jpeg" then ext = "jpg" end
if ext ~= "jpg" and ext ~= "png" and ext ~= "gif" and ext ~= "webp" then return nil, "pages" end
return src, ext
end
---@param path string
---@return string|nil
local function readAll(path)
local f = io.open(path, "rb")
if not f then return nil end
local data = f:read("*a")
f:close()
return data
end
---@param path string
---@param data string
---@return boolean
local function writeAll(path, data)
local f = io.open(path, "wb")
if not f then return false end
local ok = f:write(data)
f:close()
return ok ~= nil
end
--- EPUB → CBZ。成功 true;打不开是 "bad"(调用方删掉文件);其余错误留下 EPUB。
---@param epub string
---@param cbz string
---@param handle { cancelled: boolean|nil }
---@return boolean|nil ok
---@return string|nil err
local function toCbz(epub, cbz, handle)
local function aborted()
return handle.cancelled
end
local reader = require("ffi/archiver").Reader:new()
if not reader:open(epub) then
reader:close()
return nil, "bad"
end
local files, by_norm = {}, {}
for entry in reader:iterate() do
if entry.mode == "file" then
if not entry.index then entry.index = #files + 1 end
files[#files + 1] = entry
by_norm[normalize(entry.path:gsub("\\", "/"))] = entry
end
end
local opf_entry
for _, entry in ipairs(files) do
if entry.path:lower():match("%.opf$") then opf_entry = entry; break end
end
local opf = opf_entry and reader:extractToMemory(opf_entry.path)
local hrefs = opf and spineHrefs(opf)
if not hrefs then reader:close(); return nil, "pages" end
local opf_dir = opf_entry.path:gsub("\\", "/"):match("(.+)/[^/]+$") or ""
local pages = {}
for i, href in ipairs(hrefs) do
local html_entry = by_norm[under(opf_dir, href)]
if not html_entry then reader:close(); return nil, "pages" end
pages[i] = { html = html_entry, spine = i }
end
local html_order = {}
for i, page in ipairs(pages) do html_order[i] = page end
table.sort(html_order, function(a, b) return a.html.index < b.html.index end)
for _, page in ipairs(html_order) do
if aborted() then reader:close(); return nil, "cancel" end
local html = reader:extractToMemory(page.html.path)
local src, ext = pageImage(html)
if not src then reader:close(); return nil, ext end
local html_dir = page.html.path:gsub("\\", "/"):match("(.+)/[^/]+$") or ""
local image = by_norm[under(html_dir, src)]
if not image then reader:close(); return nil, "pages" end
page.image, page.ext = image, ext
end
local dir = cbz .. ".src"
local part = cbz .. ".part"
os.execute("mkdir -p " .. shellQuote(dir))
local function removeSrc()
os.execute("rm -rf " .. shellQuote(dir))
end
local function fail(err)
reader:close()
os.remove(part)
removeSrc()
return nil, err
end
local image_order = {}
for i, page in ipairs(pages) do image_order[i] = page end
table.sort(image_order, function(a, b) return a.image.index < b.image.index end)
for _, page in ipairs(image_order) do
if aborted() then return fail("cancel") end
local data = reader:extractToMemory(page.image.path)
local temp = string.format("%s/%04d.%s", dir, page.spine, page.ext)
if not data or data == "" or not writeAll(temp, data) then return fail("pages") end
page.temp = temp
end
reader:close()
collectgarbage("collect")
if aborted() then os.remove(part); removeSrc(); return nil, "cancel" end
local writer = require("ffi/archiver").Writer:new()
if not writer:open(part, "zip") or not writer:setZipCompression("store") then
writer:close()
os.remove(part)
removeSrc()
return nil, "write"
end
local mtime = os.time()
for i, page in ipairs(pages) do
if aborted() then writer:close(); os.remove(part); removeSrc(); return nil, "cancel" end
local data = readAll(page.temp)
if not data or not writer:addFileFromMemory(string.format("%04d.%s", i, page.ext), data, mtime) then
writer:close()
os.remove(part)
removeSrc()
return nil, "write"
end
end
writer:close()
removeSrc()
os.remove(cbz)
if not os.rename(part, cbz) then return nil, "write" end
return true
end
---@param handle { cancelled: boolean|nil, inner: { cancel: fun() }|nil }
---@param epub string
---@param cbz string
---@param on_progress fun(bytes: number|nil, total: number|nil)|nil
---@param cb fun(path: string|nil, err: string|nil)
local function finishConvert(handle, epub, cbz, on_progress, cb)
if handle.cancelled then return end
if on_progress then on_progress() end
local ok, err = toCbz(epub, cbz, handle)
if handle.cancelled then return end
if ok then
os.remove(epub)
cb(cbz)
return
end
if err == "bad" then
os.remove(epub)
cb(nil, _("Kmoe 返回的不是 EPUB 文件"))
return
end
require("utils.log").warn("kmoe volume to cbz failed", err)
cb(epub)
end
---@param handle { cancelled: boolean|nil, inner: { cancel: fun() }|nil }
---@return { cancel: fun() }
local function cancellable(handle)
function handle.cancel()
handle.cancelled = true
if handle.inner and handle.inner.cancel then handle.inner.cancel() end
end
return handle
end
--- 下载一卷并转成 CBZ。已有 CBZ 直接复用;只有 EPUB 时离线转换,不再下载。
---@param client KmoeClient
---@param identity BookIdentity
---@param chapter KmoeChapter
---@param on_progress fun(bytes: number, total: number|nil)|nil
---@param on_progress fun(bytes: number|nil, total: number|nil)|nil 无参数表示开始从 EPUB 抽页
---@param cb fun(path: string|nil, err: string|nil)
---@return { cancel: fun() }
function Chapter.materializeAsync(client, identity, chapter, on_progress, cb)
local SourceBase = require("source.base")
local path = Chapter.existing(identity, chapter)
if path then return SourceBase.defer(cb, path) end
local cbz = Chapter.path(identity, chapter)
local epub = volumePath(identity, chapter, ".epub")
local handle = {}
if isZip(cbz) then
handle.inner = SourceBase.defer(function()
if handle.cancelled then return end
os.remove(epub)
cb(cbz)
end)
return cancellable(handle)
end
if isZip(epub) then
handle.inner = SourceBase.defer(function()
finishConvert(handle, epub, cbz, on_progress, cb)
end)
return cancellable(handle)
end
if chapter.building then
return SourceBase.defer(cb, nil, _("这一卷的 EPUB 还在制作中,过一阵再试"))
end
Paths.ensureBookWork(identity.stable_id, identity.source_id)
path = Chapter.path(identity, chapter)
local handle = {}
handle.inner = client:downUrlAsync(chapter.origin, function(url, err)
if handle.cancelled then return end
if not url then cb(nil, err); return end
@@ -65,22 +328,18 @@ function Chapter.materializeAsync(client, identity, chapter, on_progress, cb)
max_bytes = 1024 * 1024 * 1024,
resume = true,
on_progress = on_progress,
}, path, function(ok, download_err)
}, epub, function(ok, download_err)
if handle.cancelled then return end
if not ok then cb(nil, download_err or _("下载失败")); return end
if not isEpub(path) then
os.remove(path)
if not isZip(epub) then
os.remove(epub)
cb(nil, _("Kmoe 返回的不是 EPUB 文件"))
return
end
cb(path)
finishConvert(handle, epub, cbz, on_progress, cb)
end)
end)
function handle.cancel()
handle.cancelled = true
if handle.inner then handle.inner.cancel() end
end
return handle
return cancellable(handle)
end
--- 顺序下载 from_idx+1 起的 count 卷;单卷失败不阻断后面。
@@ -8,7 +8,7 @@ return {
["Kmoe 没有返回下载地址"] = "Kmoe returned no download link",
["Kmoe 没有返回这部漫画的卷列表"] = "Kmoe returned no volume list for this comic",
["Kmoe 漫画详情解析失败"] = "Failed to parse Kmoe comic details",
["Kmoe 漫画,按卷下载 EPUB 阅读"] = "Kmoe comics, read by downloading each volume as EPUB",
["Kmoe 漫画,按卷下载后转成 CBZ 阅读"] = "Kmoe comics, downloaded by volume and read as CBZ",
["Kmoe 登录响应无效"] = "Invalid sign-in response from Kmoe",
["Kmoe 登录已失效。打开「设置 → 书库 → 账号 → Kmoe」,重新登录。"] = "Your Kmoe sign-in has expired. Open Settings → Library → Account → Kmoe and sign in again.",
["Kmoe 登录成功但没有返回 Cookie"] = "Kmoe sign-in succeeded but returned no cookie",
@@ -35,6 +35,7 @@ return {
["未登录 · 点此登录"] = "Not signed in · Tap to sign in",
["正在下载这一卷…"] = "Downloading this volume…",
["正在准备漫画…"] = "Preparing comic…",
["正在整理这一卷…"] = "Building this volume…",
["正在登录…"] = "Signing in…",
["漫画目录保存失败"] = "Failed to save comic chapter list",
["热门"] = "Popular",
@@ -8,7 +8,7 @@ return {
["Kmoe 没有返回下载地址"] = "Kmoe 沒有返回下載地址",
["Kmoe 没有返回这部漫画的卷列表"] = "Kmoe 沒有返回這部漫畫的卷列表",
["Kmoe 漫画详情解析失败"] = "Kmoe 漫畫詳情解析失敗",
["Kmoe 漫画,按卷下载 EPUB 阅读"] = "Kmoe 漫畫,按卷下載 EPUB 閱讀",
["Kmoe 漫画,按卷下载后转成 CBZ 阅读"] = "Kmoe 漫畫,按卷下載後轉成 CBZ 閱讀",
["Kmoe 登录响应无效"] = "Kmoe 登入回應無效",
["Kmoe 登录已失效。打开「设置 → 书库 → 账号 → Kmoe」,重新登录。"] = "Kmoe 登入已失效。打開「設定 → 書庫 → 帳號 → Kmoe」,重新登入。",
["Kmoe 登录成功但没有返回 Cookie"] = "Kmoe 登入成功但沒有返回 Cookie",
@@ -35,6 +35,7 @@ return {
["未登录 · 点此登录"] = "未登入 · 點此登入",
["正在下载这一卷…"] = "正在下載這一卷…",
["正在准备漫画…"] = "正在準備漫畫…",
["正在整理这一卷…"] = "正在整理這一卷…",
["正在登录…"] = "正在登入…",
["漫画目录保存失败"] = "漫畫目錄儲存失敗",
["热门"] = "熱門",
@@ -1,7 +1,7 @@
--[[--
Kmoe 数据源门面。
书城与搜索匿名可用;卷列表、下载、书架要登录。一卷是一章,下载整卷 EPUB 阅读。
书城与搜索匿名可用;卷列表、下载、书架要登录。一卷是一章,下载 EPUB 后转成 CBZ 阅读。
书架是网站的「收藏」,经 Shelf 双向同步。网站没有阅读进度接口,进度只在本机。
@module moonsource_kmoe.source
@@ -213,14 +213,21 @@ function Source:openBookAsync(identity, opts, cb)
cb(ok and path or nil, err)
end
-- 已下载的卷直接交给阅读器,不经过联网门控。
-- 已转好的 CBZ 直接开。只有 EPUB 时离线转换,不重新下载。
local toc = Toc.read(identity.source_id, identity.stable_id)
local local_chapter, local_idx
if toc then
local idx = startIndex(identity, opts, toc)
local path = Chapter.existing(identity, toc[idx])
if path then return SourceBase.defer(finish, path, idx) end
local_idx = startIndex(identity, opts, toc)
local_chapter = toc[local_idx]
local ready = Chapter.existing(identity, local_chapter)
if ready then
local leftover = Chapter.epubOnDisk(identity, local_chapter)
if leftover then os.remove(leftover) end
return SourceBase.defer(finish, ready, local_idx)
end
end
if not require("ui/network/manager"):isConnected() then
local local_epub = local_chapter and Chapter.epubOnDisk(identity, local_chapter)
if not local_epub and not require("ui/network/manager"):isConnected() then
return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi"))
end
@@ -228,6 +235,27 @@ function Source:openBookAsync(identity, opts, cb)
local function closeDialog()
if dialog then dialog:close(); dialog = nil end
end
---@param fresh KmoeChapter[]
local function materialize(fresh)
local idx = startIndex(identity, opts, fresh)
local mb = 1024 * 1024
active = Chapter.materializeAsync(self._client, identity, fresh[idx],
function(bytes, total)
if not dialog then return end
if not bytes then dialog:set(_("正在整理这一卷…")); return end
if total and total > 0 then
dialog:update(_("正在下载这一卷…"), math.floor(bytes / mb), math.ceil(total / mb))
end
end,
function(path, materialize_err)
active = nil
closeDialog()
if cancelled then return end
if not path then cb(nil, materialize_err); return end
finish(path, idx)
end
)
end
require("ui/uimanager"):nextTick(function()
if cancelled then return end
dialog = require("ui.themes.widgets.progress_dialog"):new{
@@ -236,26 +264,12 @@ function Source:openBookAsync(identity, opts, cb)
}
dialog:show()
dialog:set(_("正在准备漫画…"))
if local_epub then materialize(toc); return end
active = self:loadTocAsync(identity, function(fresh, err)
active = nil
if cancelled then return end
if not fresh then closeDialog(); cb(nil, err); return end
local idx = startIndex(identity, opts, fresh)
local mb = 1024 * 1024
active = Chapter.materializeAsync(self._client, identity, fresh[idx],
function(bytes, total)
if dialog and total and total > 0 then
dialog:update(_("正在下载这一卷…"), math.floor(bytes / mb), math.ceil(total / mb))
end
end,
function(path, materialize_err)
active = nil
closeDialog()
if cancelled then return end
if not path then cb(nil, materialize_err); return end
finish(path, idx)
end
)
materialize(fresh)
end)
end)