|
|
@@ -5,8 +5,6 @@ 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.*
|
|
|
|
|
|
/**
|
|
|
* 自动获取文件的编码
|
|
|
@@ -14,9 +12,21 @@ 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) {
|
|
|
@@ -24,16 +34,14 @@ object EncodingDetect {
|
|
|
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 (!TextUtils.isEmpty(charsetStr)) {
|
|
|
return charsetStr
|