package eu.friedcutlet.yokan.services.files private val containerRootfilePath = Regex("full-path=\"([^\"]+)\"") private val manifestItem = Regex("]+)/?>") private val itemId = Regex("id=\"([^\"]+)\"") private val itemHref = Regex("href=\"([^\"]+)\"") private val spineItemRef = Regex("]*?idref=\"([^\"]+)\"") private val titleElement = Regex("]*>(.*?)", RegexOption.DOT_MATCHES_ALL) private val markupTag = Regex("<[^>]+>") /** * Reads an EPUB's chapters in spine order (`META-INF/container.xml` → OPF → spine → manifest). * Manifest hrefs resolve against the OPF directory and are normalised with [normalizeArchivePath]. * [readEntry] returns the bytes of an archive entry at a normalised path, or null when it is missing. * Chapters without a `` are named "Chapter N" after their spine position. */ internal fun readEpubManifest(readEntry: (String) -> ByteArray?): List<LocalEpubChapter> { val opfPath = epubPackagePath(readEntry("META-INF/container.xml")) ?: return emptyList() val opfXml = readEntry(opfPath)?.decodeToString() ?: return emptyList() return epubSpine(opfPath, opfXml).mapNotNull { (index, href) -> readEntry(href)?.let { epubChapter(index, href, it) } } } /** Same manifest interpretation for asynchronous file backends, without buffering a whole book. */ internal suspend fun readEpubManifestAsync(readEntry: suspend (String) -> ByteArray?): List<LocalEpubChapter> { val opfPath = epubPackagePath(readEntry("META-INF/container.xml")) ?: return emptyList() val opfXml = readEntry(opfPath)?.decodeToString() ?: return emptyList() return epubSpine(opfPath, opfXml).mapNotNull { (index, href) -> readEntry(href)?.let { epubChapter(index, href, it) } } } private fun epubPackagePath(container: ByteArray?): String? = container?.decodeToString()?.let { xml -> containerRootfilePath.find(xml)?.groupValues?.get(1)?.let(::normalizeArchivePath)?.takeIf(String::isNotEmpty) } private fun epubSpine(opfPath: String, opfXml: String): List<Pair<Int, String>> { val opfDir = opfPath.substringBeforeLast('/', "").let { if (it.isEmpty()) "" else "$it/" } val manifest = manifestItem.findAll(opfXml).associate { match -> val attributes = match.groupValues[1] itemId.find(attributes)?.groupValues?.get(1).orEmpty() to itemHref.find(attributes)?.groupValues?.get(1).orEmpty() }.filterValues(String::isNotBlank) return spineItemRef.findAll(opfXml).mapIndexedNotNull { index, match -> val href = manifest[match.groupValues[1]] ?: return@mapIndexedNotNull null normalizeArchivePath(if (href.startsWith('/')) href else opfDir + href) .takeIf(String::isNotEmpty) ?.let { index to it } }.toList() } private fun epubChapter(index: Int, href: String, bytes: ByteArray): LocalEpubChapter { val title = titleElement.find(bytes.decodeToString())?.groupValues?.get(1) ?.replace(markupTag, "")?.trim()?.takeIf(String::isNotBlank) return LocalEpubChapter(title ?: "Chapter ${index + 1}", href) } /** Archive-relative path; EPUB hrefs decode `%20`, but literal ZIP entry names must not. */ internal fun normalizeArchivePath(path: String, decodePercentSpaces: Boolean = true): String { val output = ArrayDeque<String>() path.replace('\\', '/').split('/').forEach { part -> when (part) { "", "." -> Unit ".." -> output.removeLastOrNull() else -> output.addLast(if (decodePercentSpaces) part.replace("%20", " ") else part) } } return output.joinToString("/") }