From fd1cd66cd69d49adad4425439701b56e96413e28 Mon Sep 17 00:00:00 2001 From: Garfield Date: Tue, 1 Dec 2026 11:34:05 +0800 Subject: [PATCH] =?UTF-8?q?:sparkles:=20(kmoe):=20=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E7=9A=84=20EPUB=20=E6=8C=89=E9=A1=B5=E5=BA=8F=E8=BD=AC?= =?UTF-8?q?=E6=88=90=20CBZ?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 转不了时仍打开原来的 EPUB,已下载的卷不再重新扣额度。 --- .../moonsource_kmoe/README.md | 4 +- .../moonsource_kmoe/_meta.lua | 2 +- .../moonsource_kmoe/chapter.lua | 301 ++++++++++++++++-- .../moonsource_kmoe/l10n/en.lua | 3 +- .../moonsource_kmoe/l10n/zh_TW.lua | 3 +- .../moonsource_kmoe/source.lua | 58 ++-- tests/kmoe/source_spec.lua | 181 ++++++++++- 7 files changed, 497 insertions(+), 55 deletions(-) diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/README.md b/moonsource-kmoe.koplugin/moonsource_kmoe/README.md index 83e1276..dc15907 100644 --- a/moonsource-kmoe.koplugin/moonsource_kmoe/README.md +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/README.md @@ -9,8 +9,8 @@ | 搜索与书城 | 支持 | 排序、连载状态、语言、分类筛选,每页 21 部,默认聚合约 60 部;无需登录 | | 详情 | 支持 | 作者、分类、简介、封面;无需登录 | | 卷列表 | 支持 | 需要登录;一卷是一章,单行本、话、番外按网站顺序排列 | -| 漫画阅读 | 支持 | 整卷下载 EPUB(普通线路);网站要求账号先验证手机号,并消耗账号下载额度;下载要求 UA 与登录时完全一致 | -| 卷缓存与离线阅读 | 支持 | 只在打开或手动缓存时下载,不做阅读期预取;已下载的卷离线可读;批量缓存未实测 | +| 漫画阅读 | 支持 | 整卷下载 EPUB 后按目录页序转成 CBZ;转不了时仍打开原来的 EPUB。已有 EPUB 的卷内页码不沿用。网站要求账号先验证手机号,并消耗账号下载额度;下载要求 UA 与登录时完全一致 | +| 卷缓存与离线阅读 | 支持 | 只在打开或手动缓存时下载,不做阅读期预取;缓存的是 CBZ,已下载的 EPUB 离线打开时再转;批量缓存未实测 | | 书架拉取 | 支持 | 网站「收藏」即书架,只订阅不收藏的书不算;收藏页出现分页时不按缺席下架 | | 书架新增与移出 | 支持 | 改网站收藏,之后重新拉取书架确认 | | 阅读进度同步 | 不支持 | 网站没有阅读进度接口,只保存本地进度 | diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/_meta.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/_meta.lua index d6bb9b7..1be7e05 100644 --- a/moonsource-kmoe.koplugin/moonsource_kmoe/_meta.lua +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/_meta.lua @@ -10,6 +10,6 @@ return { id = "kmoe", name = _("Kmoe"), type = "chapter", - description = _("Kmoe 漫画,按卷下载 EPUB 阅读"), + description = _("Kmoe 漫画,按卷下载后转成 CBZ 阅读"), abilities = { _("搜索与发现"), _("书架同步") }, } diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/chapter.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/chapter.lua index ef87296..226fdef 100644 --- a/moonsource-kmoe.koplugin/moonsource_kmoe/chapter.lua +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/chapter.lua @@ -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("]*>") + 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 卷;单卷失败不阻断后面。 diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/en.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/en.lua index 6600b4f..32338f9 100644 --- a/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/en.lua +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/en.lua @@ -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", diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/zh_TW.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/zh_TW.lua index ddf0c03..e57d691 100644 --- a/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/zh_TW.lua +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/zh_TW.lua @@ -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 { ["未登录 · 点此登录"] = "未登入 · 點此登入", ["正在下载这一卷…"] = "正在下載這一卷…", ["正在准备漫画…"] = "正在準備漫畫…", + ["正在整理这一卷…"] = "正在整理這一卷…", ["正在登录…"] = "正在登入…", ["漫画目录保存失败"] = "漫畫目錄儲存失敗", ["热门"] = "熱門", diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/source.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/source.lua index cd66dbb..e85397e 100644 --- a/moonsource-kmoe.koplugin/moonsource_kmoe/source.lua +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/source.lua @@ -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) diff --git a/tests/kmoe/source_spec.lua b/tests/kmoe/source_spec.lua index 432f698..f99c0e6 100644 --- a/tests/kmoe/source_spec.lua +++ b/tests/kmoe/source_spec.lua @@ -1,5 +1,5 @@ --[[-- -moonsource_kmoe.source / chapter 离线用例:书城节点与筛选组、搜索聚合、卷下载(制作中、已有文件、非 EPUB)、缓存统计。 +moonsource_kmoe.source / chapter 离线用例:书城节点与筛选组、搜索聚合、卷下载(制作中、EPUB 转 CBZ、坏文件、转不了时留 EPUB)、缓存统计。 @module tests.moonsource_kmoe.source_spec --]] @@ -52,6 +52,122 @@ function fake.downUrlAsync(_self, origin, cb) return { cancel = function() end } end +local archives = {} +local function u16(n) return string.char(n % 256, math.floor(n / 256) % 256) end +local function u32(n) + return string.char(n % 256, math.floor(n / 256) % 256, math.floor(n / 65536) % 256, math.floor(n / 16777216) % 256) +end +--- 测试用的 store zip。桩阅读器只认这种头,不跑 libarchive。 +local function zipStore(files) + local parts, central, offset = {}, {}, 0 + for _, file in ipairs(files) do + local name, data = file[1], file[2] + local local_hdr = "PK\3\4" .. u16(20) .. u16(0) .. u16(0) .. u16(0) .. u16(0) + .. u32(0) .. u32(#data) .. u32(#data) .. u16(#name) .. u16(0) .. name + parts[#parts + 1] = local_hdr .. data + central[#central + 1] = "PK\1\2" .. u16(20) .. u16(20) .. u16(0) .. u16(0) .. u16(0) .. u16(0) + .. u32(0) .. u32(#data) .. u32(#data) .. u16(#name) .. u16(0) .. u16(0) .. u16(0) .. u16(0) + .. u32(0) .. u32(offset) .. name + offset = offset + #local_hdr + #data + end + local central_blob = table.concat(central) + return table.concat(parts) .. central_blob .. "PK\5\6" .. u16(0) .. u16(0) .. u16(#files) .. u16(#files) + .. u32(#central_blob) .. u32(offset) .. u16(0) +end +local function readZip(blob) + if #blob < 22 then return nil end + local entries, i = {}, 1 + while i + 3 <= #blob do + local sig = blob:sub(i, i + 3) + if sig == "PK\1\2" or sig == "PK\5\6" then return entries end + if sig ~= "PK\3\4" or i + 29 > #blob then return nil end + local name_len = blob:byte(i + 26) + blob:byte(i + 27) * 256 + local extra_len = blob:byte(i + 28) + blob:byte(i + 29) * 256 + local size = blob:byte(i + 18) + blob:byte(i + 19) * 256 + blob:byte(i + 20) * 65536 + blob:byte(i + 21) * 16777216 + local start = i + 30 + name_len + extra_len + if start - 1 + size > #blob then return nil end + local name = blob:sub(i + 30, i + 29 + name_len) + entries[#entries + 1] = { + path = name, mode = "file", size = size, index = #entries + 1, + data = blob:sub(start, start + size - 1), + } + i = start + size + end + return nil +end +package.preload["ffi/archiver"] = function() + local Reader = {} + Reader.__index = Reader + function Reader:new() return setmetatable({ index = 0, entries = {} }, Reader) end + function Reader:open(path) + local f = io.open(path, "rb") + if not f then self.err = "open"; return nil end + local blob = f:read("*a") + f:close() + local list = readZip(blob) + if not list then self.err = "bad"; return nil end + self._list, self.entries, self.index = list, {}, 0 + for _, entry in ipairs(list) do + self.entries[entry.path] = entry + self.entries[entry.index] = entry + end + return true + end + function Reader:next() + self.index = self.index + 1 + return self._list[self.index] + end + function Reader:iterate() + self.index = 0 + return self.next, self + end + function Reader:extractToMemory(key) + local entry = self.entries[key] + return entry and entry.data or nil + end + function Reader:close() end + local Writer = {} + Writer.__index = Writer + function Writer:new() return setmetatable({ files = {} }, Writer) end + function Writer:open(path) self.path = path; self.files = {}; return true end + function Writer:setZipCompression(method) + self.method = method + return method == "store" + end + function Writer:addFileFromMemory(name, data) + self.files[#self.files + 1] = { name = name, data = data } + return true + end + function Writer:close() + if not self.path then return end + archives[self.path] = { method = self.method, files = self.files } + local f = io.open(self.path, "wb") + if f then f:write("PK\3\4stub"); f:close() end + end + return { Reader = Reader, Writer = Writer } +end + +local JPG, PNG = "jpeg-page-one", "png-page-two" +local function comic(rotate) + local mark = rotate and ' kmoetag="rotate:' .. rotate .. '"' or ' kmoetag="rotate:0"' + local opf = [[ + + + + + + + +]] + return zipStore({ + { "image/zzz.png", PNG }, + { "html/b.html", '' }, + { "image/aaa.jpg", JPG }, + { "html/a.html", '" }, + { "vol.opf", opf }, + }) +end + local Kmoe = require("moonsource_kmoe.source") local Chapter = require("moonsource_kmoe.chapter") local src = Kmoe.new() @@ -111,7 +227,7 @@ do Assert.len(downloads, 0) end --- 下到的不是 zip 就删掉报错;是 EPUB 就交出路径,下次直接复用不再下载。 +-- 下到的不是 zip 就删掉报错。能打开但不是漫画的 zip 留下 EPUB。 do down_body = "額度不足" local path, err @@ -122,18 +238,69 @@ do down_body = "PK\3\4epub" Chapter.materializeAsync(fake, identity, { uid = "3086", origin = "o" }, nil, function(p, e) path, err = p, e end) - Assert.eq(path, WORK .. "/de34d9/3086.epub") - Assert.eq(downloads[#downloads].url, "https://dl.example/o") + Assert.is_nil(path) + Assert.matches(err, "EPUB") + Assert.is_nil(io.open(WORK .. "/de34d9/3086.epub", "rb"), "截断的 zip 不留") + + down_body = zipStore({ { "readme.txt", "x" } }) + Chapter.materializeAsync(fake, identity, { uid = "plain", origin = "o" }, nil, function(p, e) path, err = p, e end) + Assert.eq(path, WORK .. "/de34d9/plain.epub", "没有页序就继续用 EPUB") + Assert.is_nil(io.open(WORK .. "/de34d9/plain.cbz", "rb")) +end + +-- 页序跟 spine,不跟压缩包里的文件名。转完删 EPUB,已有 CBZ 不再下载。 +do + down_body = comic(0) + local path, err + local phases = {} + Chapter.materializeAsync(fake, identity, { uid = "3086", origin = "o" }, function() + phases[#phases + 1] = "convert" + end, function(p, e) path, err = p, e end) + Assert.is_nil(err) + Assert.eq(path, WORK .. "/de34d9/3086.cbz") + Assert.eq(phases[1], "convert") + Assert.is_nil(io.open(WORK .. "/de34d9/3086.epub", "rb"), "转完不留 EPUB") + local packed = archives[WORK .. "/de34d9/3086.cbz.part"] + Assert.eq(packed.method, "store") + Assert.eq(packed.files[1].name, "0001.jpg") + Assert.eq(packed.files[1].data, JPG) + Assert.eq(packed.files[2].name, "0002.png") + Assert.eq(packed.files[2].data, PNG) local n = #downloads Chapter.materializeAsync(fake, identity, { uid = "3086", origin = "o" }, nil, function(p) path = p end) Stubs.flush() - Assert.eq(path, WORK .. "/de34d9/3086.epub") - Assert.eq(#downloads, n, "已有文件不再下载") + Assert.eq(path, WORK .. "/de34d9/3086.cbz") + Assert.eq(#downloads, n, "已有 CBZ 不再下载") +end + +-- 磁盘上的旧 EPUB 离线转换,不请求下载地址。非 0 旋转转不了,EPUB 还在。 +do + local n = #downloads + local legacy = WORK .. "/de34d9/old.epub" + local f = assert(io.open(legacy, "wb")) + f:write(comic(0)) + f:close() + local path + Chapter.materializeAsync(fake, identity, { uid = "old", origin = "o" }, nil, function(p) path = p end) + Stubs.flush() + Assert.eq(path, WORK .. "/de34d9/old.cbz") + Assert.eq(#downloads, n, "旧 EPUB 不重新下载") + Assert.is_nil(io.open(legacy, "rb")) + + local turned = WORK .. "/de34d9/turn.epub" + f = assert(io.open(turned, "wb")) + f:write(comic(90)) + f:close() + Chapter.materializeAsync(fake, identity, { uid = "turn", origin = "o" }, nil, function(p) path = p end) + Stubs.flush() + Assert.eq(path, turned, "旋转页仍打开 EPUB") + Assert.not_nil(io.open(turned, "rb")) + Assert.is_nil(io.open(WORK .. "/de34d9/turn.cbz", "rb")) end -- 缓存一段:单卷失败不阻断,统计已缓存 / 失败。 do - down_body = "PK\3\4epub" + down_body = comic(0) local toc = { { uid = "a", origin = "o" }, { uid = "b", origin = "o", building = true }, { uid = "c", origin = "o" }, }