Skip to content
Open
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
39 changes: 24 additions & 15 deletions src/main/java/io/legado/app/utils/EncodingDetect.kt
Original file line number Diff line number Diff line change
@@ -1,40 +1,49 @@
package io.legado.app.utils

import android.text.TextUtils
import io.legado.app.lib.icu4j.CharsetDetector
import org.jsoup.Jsoup
import java.io.File
import java.io.FileInputStream
import java.nio.charset.StandardCharsets
import java.util.*

/**
* 自动获取文件的编码
* */
@Suppress("MemberVisibilityCanBePrivate", "unused")
object EncodingDetect {

fun getHtmlEncode(bytes: ByteArray): String? {
private val headTagRegex = "(?i)<head>[\\s\\S]*?</head>".toRegex()
private val headOpenBytes = "<head>".toByteArray()
private val headCloseBytes = "</head>".toByteArray()

fun getHtmlEncode(bytes: ByteArray): String {
try {
val doc = Jsoup.parse(String(bytes, StandardCharsets.UTF_8))
var head: String? = null
val startIndex = bytes.indexOf(headOpenBytes)
if (startIndex > -1) {
val endIndex = bytes.indexOf(headCloseBytes, startIndex)
if (endIndex > -1) {
head = String(bytes.copyOfRange(startIndex, endIndex + headCloseBytes.size))
}
}
val doc = Jsoup.parseBodyFragment(head ?: headTagRegex.find(String(bytes))!!.value)
val metaTags = doc.getElementsByTag("meta")
var charsetStr: String
for (metaTag in metaTags) {
charsetStr = metaTag.attr("charset")
if (!charsetStr.isEmpty()) {
if (!TextUtils.isEmpty(charsetStr)) {
return charsetStr
}
val content = metaTag.attr("content")
val httpEquiv = metaTag.attr("http-equiv")
if (httpEquiv.lowercase(Locale.getDefault()) == "content-type") {
charsetStr = if (content.lowercase(Locale.getDefault()).contains("charset")) {
content.substring(
content.lowercase(Locale.getDefault())
.indexOf("charset") + "charset=".length
)
if (httpEquiv.equals("content-type", true)) {
val content = metaTag.attr("content")
val idx = content.indexOf("charset=", ignoreCase = true)
charsetStr = if (idx > -1) {
content.substring(idx + "charset=".length)
} else {
content.substring(content.lowercase(Locale.getDefault()).indexOf(";") + 1)
content.substringAfter(";")
}
if (!charsetStr.isEmpty()) {
if (!TextUtils.isEmpty(charsetStr)) {
return charsetStr
}
}
Expand Down Expand Up @@ -75,4 +84,4 @@ object EncodingDetect {
}
return byteArray
}
}
}