[core] Encode html entities for forward message; fix #2241

This commit is contained in:
Karlatemp 2022-12-11 22:26:06 +08:00
parent c52e99dd87
commit c77ed79b12
No known key found for this signature in database
GPG Key ID: BA173CA2B9956C59
3 changed files with 31 additions and 3 deletions

View File

@ -31,6 +31,23 @@ public fun String.decodeHtmlEscape(): String = replace(STR_TO_CHAR_PATTERN) { ma
match.value match.value
} }
public fun String.encodeHtmlEscape(): String = buildString(length) {
this@encodeHtmlEscape.forEach { c ->
if (needDoHtmlEscape(c)) {
append("&#").append(c.code).append(';')
} else {
append(c)
}
}
}
private fun needDoHtmlEscape(c: Char): Boolean {
if (c.code < 32) return true // Ascii control codes
if (c in "#@!~$%^&*()<>/\\\"'") return true
return false
}
private val STR_TO_CHAR_MAPPINGS: Map<String, String> by lazy { private val STR_TO_CHAR_MAPPINGS: Map<String, String> by lazy {
//<editor-fold defaultstate="collapsed" desc="Generated Code"> //<editor-fold defaultstate="collapsed" desc="Generated Code">

View File

@ -22,4 +22,16 @@ internal class HtmlEscapeTest {
ALL.decodeHtmlEscape() ALL.decodeHtmlEscape()
) )
} }
@Test
fun testEncode() {
val str = buildString {
for (i in 1 until 2048) {
append(i.toChar())
}
}
val escaped = str.encodeHtmlEscape()
// println(escaped)
assertEquals(escaped.decodeHtmlEscape(), str)
}
} }

View File

@ -21,6 +21,7 @@ import net.mamoe.mirai.internal.network.protocol.data.proto.MsgTransmit
import net.mamoe.mirai.message.MessageReceipt import net.mamoe.mirai.message.MessageReceipt
import net.mamoe.mirai.message.data.* import net.mamoe.mirai.message.data.*
import net.mamoe.mirai.message.data.visitor.MessageVisitor import net.mamoe.mirai.message.data.visitor.MessageVisitor
import net.mamoe.mirai.utils.encodeHtmlEscape
import net.mamoe.mirai.utils.safeCast import net.mamoe.mirai.utils.safeCast
// internal runtime value, not serializable // internal runtime value, not serializable
@ -152,9 +153,7 @@ internal data class ForwardMessageInternal(
} }
} }
private fun String.xmlEnc(): String { private fun String.xmlEnc(): String = encodeHtmlEscape()
return this.replace("&", "&amp;")
}
internal fun RichMessage.Key.forwardMessage( internal fun RichMessage.Key.forwardMessage(
resId: String, resId: String,