Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

epub-parser: Fix line break issue in some cases #154

Merged
merged 1 commit into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/src/main/java/com/starry/myne/epub/EpubParser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ class EpubParser {
files: Map<String, EpubFile>,
): List<EpubChapter> {
var chapterIndex = 0
val chapterExtensions = listOf("xhtml", "xml", "html").map { ".$it" }
val chapterExtensions = listOf("xhtml", "xml", "html", "htm").map { ".$it" }
return spine
.selectChildTag("itemref")
.mapNotNull { manifestItems[it.getAttribute("idref")] }
Expand Down
33 changes: 19 additions & 14 deletions app/src/main/java/com/starry/myne/epub/EpubXMLFileParser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class EpubXMLFileParser(
fragmentElement?.selectFirst("h1, h2, h3, h4, h5, h6")?.remove()

while (currentNode != null && currentNode != nextFragmentIdElement) {
bodyBuilder.append(getNodeStructuredText(currentNode) + "\n\n")
bodyBuilder.append(getNodeStructuredText(currentNode, true) + "\n\n")
currentNode = getNextSibling(currentNode)
}
bodyContent = bodyBuilder.toString()
Expand Down Expand Up @@ -215,21 +215,26 @@ class EpubXMLFileParser(
}
}

private fun getNodeStructuredText(node: Node): String {
val children = node.childNodes()
if (children.isEmpty())
return ""
private fun getNodeStructuredText(node: Node, singleNode: Boolean = false): String {
val nodeActions = mapOf(
"p" to { n: Node -> getPTraverse(n) },
"br" to { "\n" },
"hr" to { "\n\n" },
"img" to ::declareImgEntry,
"image" to ::declareImgEntry
)

return children.joinToString("") { child ->
when {
child.nodeName() == "p" -> getPTraverse(child)
child.nodeName() == "br" -> "\n"
child.nodeName() == "hr" -> "\n\n"
child.nodeName() == "img" -> declareImgEntry(child)
child.nodeName() == "image" -> declareImgEntry(child)
child is TextNode -> child.text().trim()
else -> getNodeTextTraverse(child)
val action: (Node) -> String = { n: Node ->
if (n is TextNode) {
n.text().trim()
} else {
getNodeTextTraverse(n)
}
}

val children = if (singleNode) listOf(node) else node.childNodes()
return children.joinToString("") { child ->
nodeActions[child.nodeName()]?.invoke(child) ?: action(child)
}
}
}
Loading