Rename ByteArray.encodeToString to .decodeToString

This commit is contained in:
Him188 2021-11-09 21:43:10 +00:00
parent e1ca6dd6c9
commit cb4fb495a3
14 changed files with 38 additions and 39 deletions

View File

@ -13,7 +13,6 @@
package net.mamoe.mirai.utils package net.mamoe.mirai.utils
import kotlinx.io.charsets.Charset
import kotlinx.io.core.ByteReadPacket import kotlinx.io.core.ByteReadPacket
import kotlin.contracts.InvocationKind import kotlin.contracts.InvocationKind
import kotlin.contracts.contract import kotlin.contracts.contract
@ -175,9 +174,6 @@ public fun UByteArray.toUHexString(separator: String = " ", offset: Int = 0, len
} }
} }
public inline fun ByteArray.encodeToString(offset: Int = 0, charset: Charset = Charsets.UTF_8): String =
String(this, charset = charset, offset = offset, length = this.size - offset)
public expect fun ByteArray.encodeBase64(): String public expect fun ByteArray.encodeBase64(): String
public expect fun String.decodeBase64(): ByteArray public expect fun String.decodeBase64(): ByteArray

View File

@ -770,7 +770,7 @@ internal open class MiraiImpl : IMirai, LowLevelApiAccessor {
): String { ): String {
bot.asQQAndroidBot().network.run { bot.asQQAndroidBot().network.run {
val response = PttStore.GroupPttDown(bot.client, groupId, dstUin, md5).sendAndExpect() val response = PttStore.GroupPttDown(bot.client, groupId, dstUin, md5).sendAndExpect()
return "http://${response.strDomain}${response.downPara.encodeToString()}" return "http://${response.strDomain}${response.downPara.decodeToString()}"
} }
} }
@ -980,7 +980,7 @@ internal open class MiraiImpl : IMirai, LowLevelApiAccessor {
val down = longResp.msgDownRsp.single() val down = longResp.msgDownRsp.single()
check(down.result == 0) { check(down.result == 0) {
"Message download failed, result=${down.result}, resId=${down.msgResid.encodeToString()}, msgContent=${down.msgContent.toUHexString()}" "Message download failed, result=${down.result}, resId=${down.msgResid.decodeToString()}, msgContent=${down.msgContent.toUHexString()}"
} }
val content = down.msgContent.ungzip() val content = down.msgContent.ungzip()

View File

@ -23,7 +23,10 @@ import net.mamoe.mirai.internal.network.protocol.data.proto.*
import net.mamoe.mirai.internal.utils.io.serialization.loadAs import net.mamoe.mirai.internal.utils.io.serialization.loadAs
import net.mamoe.mirai.internal.utils.io.serialization.readProtoBuf import net.mamoe.mirai.internal.utils.io.serialization.readProtoBuf
import net.mamoe.mirai.message.data.* import net.mamoe.mirai.message.data.*
import net.mamoe.mirai.utils.* import net.mamoe.mirai.utils.read
import net.mamoe.mirai.utils.toLongUnsigned
import net.mamoe.mirai.utils.toUHexString
import net.mamoe.mirai.utils.unzip
/** /**
* 只在手动构造 [OfflineMessageSource] 时调用 * 只在手动构造 [OfflineMessageSource] 时调用
@ -342,8 +345,8 @@ internal object ReceiveMessageTransformer {
val content = runWithBugReport("解析 lightApp", val content = runWithBugReport("解析 lightApp",
{ "resId=" + lightApp.msgResid + "data=" + lightApp.data.toUHexString() }) { { "resId=" + lightApp.msgResid + "data=" + lightApp.data.toUHexString() }) {
when (lightApp.data[0].toInt()) { when (lightApp.data[0].toInt()) {
0 -> lightApp.data.encodeToString(offset = 1) 0 -> lightApp.data.decodeToString(startIndex = 1)
1 -> lightApp.data.unzip(1).encodeToString() 1 -> lightApp.data.unzip(1).decodeToString()
else -> error("unknown compression flag=${lightApp.data[0]}") else -> error("unknown compression flag=${lightApp.data[0]}")
} }
} }
@ -481,8 +484,8 @@ internal object ReceiveMessageTransformer {
) { ) {
val content = runWithBugReport("解析 richMsg", { richMsg.template1.toUHexString() }) { val content = runWithBugReport("解析 richMsg", { richMsg.template1.toUHexString() }) {
when (richMsg.template1[0].toInt()) { when (richMsg.template1[0].toInt()) {
0 -> richMsg.template1.encodeToString(offset = 1) 0 -> richMsg.template1.decodeToString(startIndex = 1)
1 -> richMsg.template1.unzip(1).encodeToString() 1 -> richMsg.template1.unzip(1).decodeToString()
else -> error("unknown compression flag=${richMsg.template1[0]}") else -> error("unknown compression flag=${richMsg.template1[0]}")
} }
} }
@ -542,11 +545,11 @@ internal object ReceiveMessageTransformer {
} }
fun ImMsgBody.Ptt.toAudio() = OnlineAudioImpl( fun ImMsgBody.Ptt.toAudio() = OnlineAudioImpl(
filename = fileName.encodeToString(), filename = fileName.decodeToString(),
fileMd5 = fileMd5, fileMd5 = fileMd5,
fileSize = fileSize.toLongUnsigned(), fileSize = fileSize.toLongUnsigned(),
codec = AudioCodec.fromId(format), codec = AudioCodec.fromId(format),
url = downPara.encodeToString(), url = downPara.decodeToString(),
length = time.toLongUnsigned(), length = time.toLongUnsigned(),
originalPtt = this, originalPtt = this,
) )

View File

@ -70,7 +70,7 @@ private fun <T : ImgExtPbResvAttrCommon> ByteArray.pbImageResv_checkIsEmoji(seri
val data = this val data = this
return kotlin.runCatching { return kotlin.runCatching {
data.takeIf { it.isNotEmpty() }?.loadAs(serializer)?.let { ext -> data.takeIf { it.isNotEmpty() }?.loadAs(serializer)?.let { ext ->
ext.imageBizType == 1 || ext.textSummary.encodeToString() == "[动画表情]" ext.imageBizType == 1 || ext.textSummary.decodeToString() == "[动画表情]"
} }
}.getOrNull() ?: false }.getOrNull() ?: false
} }

View File

@ -31,7 +31,6 @@ import net.mamoe.mirai.message.data.MessageSourceKind
import net.mamoe.mirai.message.data.OnlineMessageSource import net.mamoe.mirai.message.data.OnlineMessageSource
import net.mamoe.mirai.utils.EMPTY_BYTE_ARRAY import net.mamoe.mirai.utils.EMPTY_BYTE_ARRAY
import net.mamoe.mirai.utils.encodeBase64 import net.mamoe.mirai.utils.encodeBase64
import net.mamoe.mirai.utils.encodeToString
import net.mamoe.mirai.utils.mapToIntArray import net.mamoe.mirai.utils.mapToIntArray
import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicBoolean
@ -189,7 +188,7 @@ internal class OnlineMessageSourceFromGroupImpl(
?: error("cannot find member for OnlineMessageSourceFromGroupImpl. msg=${msg._miraiContentToString()}") ?: error("cannot find member for OnlineMessageSourceFromGroupImpl. msg=${msg._miraiContentToString()}")
anonymousInfo.run { anonymousInfo.run {
group.newAnonymous(anonGroupMsg!!.anonNick.encodeToString(), anonGroupMsg.anonId.encodeBase64()) group.newAnonymous(anonGroupMsg!!.anonNick.decodeToString(), anonGroupMsg.anonId.encodeBase64())
} }
} }

View File

@ -149,7 +149,7 @@ internal data class WLoginSigInfo(
} }
fun getPsKey(name: String): String { fun getPsKey(name: String): String {
return psKeyMap[name]?.data?.encodeToString() ?: error("Cannot find PsKey $name") return psKeyMap[name]?.data?.decodeToString() ?: error("Cannot find PsKey $name")
} }
} }
@ -187,7 +187,7 @@ internal open class KeyWithExpiry(
} }
} }
internal val KeyWithExpiry.str get() = data.encodeToString() internal val KeyWithExpiry.str get() = data.decodeToString()
internal val AbstractBot.sKey get() = client.wLoginSigInfo.sKey.str internal val AbstractBot.sKey get() = client.wLoginSigInfo.sKey.str
internal fun AbstractBot.psKey(name: String) = client.wLoginSigInfo.getPsKey(name) internal fun AbstractBot.psKey(name: String) = client.wLoginSigInfo.getPsKey(name)
internal val AbstractBot.client get() = components[BotClientHolder].client internal val AbstractBot.client get() = components[BotClientHolder].client

View File

@ -114,7 +114,7 @@ internal class GroupMessageProcessor(
val nameCard: MemberNick val nameCard: MemberNick
if (anonymous != null) { // anonymous member if (anonymous != null) { // anonymous member
sender = group.newAnonymous(anonymous.anonNick.encodeToString(), anonymous.anonId.encodeBase64()) sender = group.newAnonymous(anonymous.anonNick.decodeToString(), anonymous.anonId.encodeBase64())
nameCard = sender.generateMemberNickFromMember() nameCard = sender.generateMemberNickFromMember()
} else { // normal member chat } else { // normal member chat
sender = group[msgHead.fromUin] ?: kotlin.run { sender = group[msgHead.fromUin] ?: kotlin.run {
@ -200,9 +200,9 @@ internal class GroupMessageProcessor(
if (this[0] == 0x0A.toByte()) { if (this[0] == 0x0A.toByte()) {
val nameBuf = loadAs(Oidb0x8fc.CommCardNameBuf.serializer()) val nameBuf = loadAs(Oidb0x8fc.CommCardNameBuf.serializer())
if (nameBuf.richCardName.isNotEmpty()) { if (nameBuf.richCardName.isNotEmpty()) {
return@runCatching nameBuf.richCardName.joinToString("") { it.text.encodeToString() } return@runCatching nameBuf.richCardName.joinToString("") { it.text.decodeToString() }
} }
} }
return@runCatching null return@runCatching null
}.getOrNull() ?: encodeToString() }.getOrNull() ?: decodeToString()
} }

View File

@ -63,7 +63,7 @@ internal class GroupNotificationProcessor(
when (info.field) { when (info.field) {
1 -> { 1 -> {
// 群名 // 群名
val new = info.value.encodeToString() val new = info.value.decodeToString()
val group = bot.getGroup(modGroupProfile.groupCode) ?: continue val group = bot.getGroup(modGroupProfile.groupCode) ?: continue
group.checkIsGroupImpl() group.checkIsGroupImpl()

View File

@ -26,7 +26,7 @@ private val Char.isHumanReadable get() = this in '0'..'9' || this in 'a'..'z' ||
internal fun TlvMap.smartToString(leadingLineBreak: Boolean = true, sorted: Boolean = true): String { internal fun TlvMap.smartToString(leadingLineBreak: Boolean = true, sorted: Boolean = true): String {
fun ByteArray.valueToString(): String { fun ByteArray.valueToString(): String {
val str = this.encodeToString() val str = this.decodeToString()
return if (str.all { it.isHumanReadable }) str return if (str.all { it.isHumanReadable }) str
else this.toUHexString() else this.toUHexString()
} }

View File

@ -25,7 +25,6 @@ import net.mamoe.mirai.internal.utils.toIpV4AddressString
import net.mamoe.mirai.message.data.AudioCodec import net.mamoe.mirai.message.data.AudioCodec
import net.mamoe.mirai.utils.EMPTY_BYTE_ARRAY import net.mamoe.mirai.utils.EMPTY_BYTE_ARRAY
import net.mamoe.mirai.utils.ExternalResource import net.mamoe.mirai.utils.ExternalResource
import net.mamoe.mirai.utils.encodeToString
import net.mamoe.mirai.utils.toUHexString import net.mamoe.mirai.utils.toUHexString
internal inline val ExternalResource.voiceCodec: Int get() = audioCodec.id internal inline val ExternalResource.voiceCodec: Int get() = audioCodec.id
@ -118,7 +117,7 @@ internal class PttStore {
val resp = val resp =
resp0.msgTryupPttRsp.firstOrNull() ?: error("cannot find `msgTryupPttRsp` from `Cmd0x388.RspBody`") resp0.msgTryupPttRsp.firstOrNull() ?: error("cannot find `msgTryupPttRsp` from `Cmd0x388.RspBody`")
if (resp.failMsg != null) { if (resp.failMsg != null) {
throw IllegalStateException(resp.failMsg.encodeToString()) throw IllegalStateException(resp.failMsg.decodeToString())
} }
return Response.RequireUpload( return Response.RequireUpload(
fileId = resp.fileid, fileId = resp.fileid,
@ -143,7 +142,7 @@ internal class PttStore {
val uint32DownPort: List<Int> val uint32DownPort: List<Int>
) : GroupPttDown.Response() { ) : GroupPttDown.Response() {
override fun toString(): String { override fun toString(): String {
return "GroupPttDown(downPara=${downPara.encodeToString()},strDomain=$strDomain})" return "GroupPttDown(downPara=${downPara.decodeToString()},strDomain=$strDomain})"
} }
} }
@ -183,7 +182,7 @@ internal class PttStore {
val resp = val resp =
resp0.msgGetpttUrlRsp.firstOrNull() ?: error("cannot find `msgGetpttUrlRsp` from `Cmd0x388.RspBody`") resp0.msgGetpttUrlRsp.firstOrNull() ?: error("cannot find `msgGetpttUrlRsp` from `Cmd0x388.RspBody`")
if (!resp.failMsg.contentEquals(EMPTY_BYTE_ARRAY)) { if (!resp.failMsg.contentEquals(EMPTY_BYTE_ARRAY)) {
throw IllegalStateException(resp.failMsg.encodeToString()) throw IllegalStateException(resp.failMsg.decodeToString())
} }
return Response.DownLoadInfo( return Response.DownLoadInfo(
downDomain = resp.downDomain, downDomain = resp.downDomain,

View File

@ -239,9 +239,9 @@ internal class StatSvc {
iOSVersion = client.device.version.sdk.toLong(), iOSVersion = client.device.version.sdk.toLong(),
cNetType = if (client.networkType == NetworkType.WIFI) 1 else 0, cNetType = if (client.networkType == NetworkType.WIFI) 1 else 0,
vecGuid = client.device.guid, vecGuid = client.device.guid,
strDevName = client.device.model.encodeToString(), strDevName = client.device.model.decodeToString(),
strDevType = client.device.model.encodeToString(), strDevType = client.device.model.decodeToString(),
strOSVer = client.device.version.release.encodeToString(), strOSVer = client.device.version.release.decodeToString(),
// register 时还需要 // register 时还需要
/* /*
var44.uNewSSOIp = field_127445; var44.uNewSSOIp = field_127445;

View File

@ -205,7 +205,7 @@ internal class WtLogin {
} }
private fun onUnsafeDeviceLogin(tlvMap: TlvMap, bot: QQAndroidBot): LoginPacketResponse.UnsafeLogin { private fun onUnsafeDeviceLogin(tlvMap: TlvMap, bot: QQAndroidBot): LoginPacketResponse.UnsafeLogin {
return LoginPacketResponse.UnsafeLogin(bot, tlvMap.getOrFail(0x204).encodeToString()) return LoginPacketResponse.UnsafeLogin(bot, tlvMap.getOrFail(0x204).decodeToString())
} }
private fun onSolveLoginCaptcha(tlvMap: TlvMap, bot: QQAndroidBot): LoginPacketResponse.Captcha { private fun onSolveLoginCaptcha(tlvMap: TlvMap, bot: QQAndroidBot): LoginPacketResponse.Captcha {
@ -222,7 +222,7 @@ internal class WtLogin {
// val ret = tlvMap[0x104]?.let { println(it.toUHexString()) } // val ret = tlvMap[0x104]?.let { println(it.toUHexString()) }
bot.client.t104 = tlvMap.getOrFail(0x104) bot.client.t104 = tlvMap.getOrFail(0x104)
tlvMap[0x192]?.let { tlvMap[0x192]?.let {
return LoginPacketResponse.Captcha.Slider(bot, it.encodeToString()) return LoginPacketResponse.Captcha.Slider(bot, it.decodeToString())
} }
tlvMap[0x165]?.let { tlvMap[0x165]?.let {
// if (question[18].toInt() == 0x36) { // if (question[18].toInt() == 0x36) {
@ -275,7 +275,7 @@ internal class WtLogin {
tlvMap119[0x1c]?.read { tlvMap119[0x1c]?.read {
val bytes = readBytes() val bytes = readBytes()
bot.network.logger.debug("onLoginSuccess, tlvMap119[0x1c]: " + bytes.toUHexString()) bot.network.logger.debug("onLoginSuccess, tlvMap119[0x1c]: " + bytes.toUHexString())
bot.network.logger.debug("onLoginSuccess, tlvMap119[0x1c]: " + bytes.encodeToString()) bot.network.logger.debug("onLoginSuccess, tlvMap119[0x1c]: " + bytes.decodeToString())
} }
tlvMap119[0x130]?.let { client.analysisTlv130(it) } tlvMap119[0x130]?.let { client.analysisTlv130(it) }

View File

@ -11,7 +11,10 @@ package net.mamoe.mirai.internal
import kotlinx.io.core.toByteArray import kotlinx.io.core.toByteArray
import net.mamoe.mirai.internal.test.AbstractTest import net.mamoe.mirai.internal.test.AbstractTest
import net.mamoe.mirai.utils.* import net.mamoe.mirai.utils.gzip
import net.mamoe.mirai.utils.ungzip
import net.mamoe.mirai.utils.unzip
import net.mamoe.mirai.utils.zip
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
@ -19,11 +22,11 @@ internal class PlatformUtilsTest : AbstractTest() {
@Test @Test
fun testZip() { fun testZip() {
assertEquals("test", "test".toByteArray().zip().unzip().encodeToString()) assertEquals("test", "test".toByteArray().zip().unzip().decodeToString())
} }
@Test @Test
fun testGZip() { fun testGZip() {
assertEquals("test", "test".toByteArray().gzip().ungzip().encodeToString()) assertEquals("test", "test".toByteArray().gzip().ungzip().decodeToString())
} }
} }

View File

@ -9,7 +9,6 @@
package net.mamoe.mirai.internal.utils.codegen package net.mamoe.mirai.internal.utils.codegen
import net.mamoe.mirai.utils.encodeToString
import net.mamoe.mirai.utils.toUHexString import net.mamoe.mirai.utils.toUHexString
class ValueCodegen( class ValueCodegen(
@ -80,11 +79,11 @@ class ValueCodegen(
context.append("net.mamoe.mirai.utils.EMPTY_BYTE_ARRAY") // let IDE to shorten references. context.append("net.mamoe.mirai.utils.EMPTY_BYTE_ARRAY") // let IDE to shorten references.
return return
} else { } else {
if (array.encodeToString().all { Character.isUnicodeIdentifierPart(it) || it.isWhitespace() }) { if (array.decodeToString().all { Character.isUnicodeIdentifierPart(it) || it.isWhitespace() }) {
// prefers to show readable string // prefers to show readable string
context.append( context.append(
"\"${ "\"${
array.encodeToString().escapeQuotation() array.decodeToString().escapeQuotation()
}\".toByteArray() /* ${array.toUHexString()} */" }\".toByteArray() /* ${array.toUHexString()} */"
) )
} else { } else {