379 lines
13 KiB
Lua
379 lines
13 KiB
Lua
--[[--
|
|
Kmoe 一卷 = 一章。站点只给 EPUB,按 vol.opf 的 spine 抽出每页那一张图,打成不压缩的 CBZ。
|
|
|
|
图片文件名是乱的,页序只在 spine 里。转不成时留下 EPUB,阅读器仍打开它。
|
|
一卷几十 MB,而且占用账号的下载额度,所以只在打开或用户点缓存时下载,不做阅读期预取。
|
|
|
|
@module moonsource_kmoe.chapter
|
|
--]]
|
|
|
|
local Paths = require("utils.paths")
|
|
local _ = require("l10n").get("moonsource_kmoe")
|
|
|
|
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 volumePath(identity, chapter, ".cbz")
|
|
end
|
|
|
|
---@param path string
|
|
---@return boolean
|
|
local function isZip(path)
|
|
local f = io.open(path, "rb")
|
|
if not f then return false end
|
|
local head = f:read(4)
|
|
f:close()
|
|
return head == "PK\3\4"
|
|
end
|
|
|
|
--- 已转好的 CBZ;没有则 nil。
|
|
---@param identity BookIdentity
|
|
---@param chapter BookChapter
|
|
---@return string|nil
|
|
function Chapter.existing(identity, chapter)
|
|
local path = Chapter.path(identity, chapter)
|
|
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|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 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)
|
|
handle.inner = client:downUrlAsync(chapter.origin, function(url, err)
|
|
if handle.cancelled then return end
|
|
if not url then cb(nil, err); return end
|
|
handle.inner = require("http.request").download({
|
|
url = url,
|
|
headers = { ["User-Agent"] = client.ua, ["Referer"] = client.BASE .. "/" },
|
|
timeout = require("http.timeout").net(20),
|
|
max_bytes = 1024 * 1024 * 1024,
|
|
resume = true,
|
|
on_progress = on_progress,
|
|
}, epub, function(ok, download_err)
|
|
if handle.cancelled then return end
|
|
if not ok then cb(nil, download_err or _("下载失败")); return end
|
|
if not isZip(epub) then
|
|
os.remove(epub)
|
|
cb(nil, _("Kmoe 返回的不是 EPUB 文件"))
|
|
return
|
|
end
|
|
finishConvert(handle, epub, cbz, on_progress, cb)
|
|
end)
|
|
end)
|
|
return cancellable(handle)
|
|
end
|
|
|
|
--- 顺序下载 from_idx+1 起的 count 卷;单卷失败不阻断后面。
|
|
---@param client KmoeClient
|
|
---@param identity BookIdentity
|
|
---@param toc KmoeChapter[]
|
|
---@param from_idx integer
|
|
---@param count integer
|
|
---@param progress fun(done: integer, total: integer)|nil
|
|
---@param cb fun(cached: integer, total: integer, failed: integer, err: string|nil)
|
|
---@return { cancel: fun() }
|
|
function Chapter.cacheAsync(client, identity, toc, from_idx, count, progress, cb)
|
|
local handle, cached, failed, last_err = {}, 0, 0, nil
|
|
local last = math.min(#toc, from_idx + count)
|
|
local total = math.max(0, last - from_idx)
|
|
local idx = from_idx
|
|
local function step()
|
|
if handle.cancelled then return end
|
|
idx = idx + 1
|
|
if idx > last then cb(cached, total, failed, last_err); return end
|
|
handle.inner = Chapter.materializeAsync(client, identity, toc[idx], nil, function(path, err)
|
|
if handle.cancelled then return end
|
|
if path then cached = cached + 1 else failed, last_err = failed + 1, err end
|
|
if progress then progress(cached + failed, total) end
|
|
step()
|
|
end)
|
|
end
|
|
step()
|
|
function handle.cancel()
|
|
handle.cancelled = true
|
|
if handle.inner then handle.inner.cancel() end
|
|
end
|
|
return handle
|
|
end
|
|
|
|
return Chapter
|