EpubManifest.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/EpubManifest.kt
1package eu.friedcutlet.yokan.services.files23private val containerRootfilePath = Regex("full-path=\"([^\"]+)\"")4private val manifestItem = Regex("<item\\s+([^>]+)/?>")5private val itemId = Regex("id=\"([^\"]+)\"")6private val itemHref = Regex("href=\"([^\"]+)\"")7private val spineItemRef = Regex("<itemref\\s+[^>]*?idref=\"([^\"]+)\"")8private val titleElement = Regex("<title[^>]*>(.*?)</title>", RegexOption.DOT_MATCHES_ALL)9private val markupTag = Regex("<[^>]+>")1011/**12 * Reads an EPUB's chapters in spine order (`META-INF/container.xml` → OPF → spine → manifest).13 * Manifest hrefs resolve against the OPF directory and are normalised with [normalizeArchivePath].14 * [readEntry] returns the bytes of an archive entry at a normalised path, or null when it is missing.15 * Chapters without a `<title>` are named "Chapter N" after their spine position.16 */17internal fun readEpubManifest(readEntry: (String) -> ByteArray?): List<LocalEpubChapter> {18 val opfPath = epubPackagePath(readEntry("META-INF/container.xml")) ?: return emptyList()19 val opfXml = readEntry(opfPath)?.decodeToString() ?: return emptyList()20 return epubSpine(opfPath, opfXml).mapNotNull { (index, href) ->21 readEntry(href)?.let { epubChapter(index, href, it) }22 }23}2425/** Same manifest interpretation for asynchronous file backends, without buffering a whole book. */26internal suspend fun readEpubManifestAsync(readEntry: suspend (String) -> ByteArray?): List<LocalEpubChapter> {27 val opfPath = epubPackagePath(readEntry("META-INF/container.xml")) ?: return emptyList()28 val opfXml = readEntry(opfPath)?.decodeToString() ?: return emptyList()29 return epubSpine(opfPath, opfXml).mapNotNull { (index, href) ->30 readEntry(href)?.let { epubChapter(index, href, it) }31 }32}3334private fun epubPackagePath(container: ByteArray?): String? = container?.decodeToString()?.let { xml ->35 containerRootfilePath.find(xml)?.groupValues?.get(1)?.let(::normalizeArchivePath)?.takeIf(String::isNotEmpty)36}3738private fun epubSpine(opfPath: String, opfXml: String): List<Pair<Int, String>> {39 val opfDir = opfPath.substringBeforeLast('/', "").let { if (it.isEmpty()) "" else "$it/" }40 val manifest = manifestItem.findAll(opfXml).associate { match ->41 val attributes = match.groupValues[1]42 itemId.find(attributes)?.groupValues?.get(1).orEmpty() to43 itemHref.find(attributes)?.groupValues?.get(1).orEmpty()44 }.filterValues(String::isNotBlank)45 return spineItemRef.findAll(opfXml).mapIndexedNotNull { index, match ->46 val href = manifest[match.groupValues[1]] ?: return@mapIndexedNotNull null47 normalizeArchivePath(if (href.startsWith('/')) href else opfDir + href)48 .takeIf(String::isNotEmpty)49 ?.let { index to it }50 }.toList()51}5253private fun epubChapter(index: Int, href: String, bytes: ByteArray): LocalEpubChapter {54 val title = titleElement.find(bytes.decodeToString())?.groupValues?.get(1)55 ?.replace(markupTag, "")?.trim()?.takeIf(String::isNotBlank)56 return LocalEpubChapter(title ?: "Chapter ${index + 1}", href)57}5859/** Archive-relative path; EPUB hrefs decode `%20`, but literal ZIP entry names must not. */60internal fun normalizeArchivePath(path: String, decodePercentSpaces: Boolean = true): String {61 val output = ArrayDeque<String>()62 path.replace('\\', '/').split('/').forEach { part ->63 when (part) {64 "", "." -> Unit65 ".." -> output.removeLastOrNull()66 else -> output.addLast(if (decodePercentSpaces) part.replace("%20", " ") else part)67 }68 }69 return output.joinToString("/")70}71