← Back to Pull requests

Redesign MultiMsg #1667

Merged
Karlatemp merged 14 files (1093 lines) on Nov 16, 2021 04:38 UTC
View on GitHub
Karlatemp Karlatemp commented on Nov 12, 2021 15:49 UTC
Author

Changes

See commit message

Issues:

  • Fix #1636

  • Fix #1652

  • Fix #1507

  • Fix #1620

  • Close #1198
  • New Features

  • #1198
  • Superseded PRs

  • #1640

  • #1598
  • ------

    For mamoe: Don't use Squash and merge for this pr

    Diff: 1093 lines (+945 / -148) across 14 files Reviewer: Him188 Review duration: 5088m
    All Vouch review confidence checks passed
    Residual risk 0.18 = Change Risk (0.62) × (1 − Review Confidence (0.71)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.62 · 1093 lines diff across 14 files
    0.62
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.50 · 5 substantive comment(s)
    0.50
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    70%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    35 items
    Him188 Him188 commented on code on Nov 13, 2021 23:56 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/contact/GroupImpl.kt:1
    @@ -181,6 +182,12 @@ internal class GroupImpl constructor(
             if (BeforeImageUploadEvent(this, resource).broadcast().isCancelled) {
                 throw EventCancelledException("cancelled by BeforeImageUploadEvent.ToGroup")
             }
    +
    +        fun OfflineGroupImage.putIntoCache() {
    +            // We can't understand wny Image(group.uploadImage().imageId)

    What does this mean?

    Him188 Him188 commented on code on Nov 14, 2021 00:00 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/message/MultiMsgUploader.kt:1
    @@ -0,0 +1,239 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.message
    +
    +import io.ktor.utils.io.core.*
    +import net.mamoe.mirai.internal.contact.SendMessageHandler
    +import net.mamoe.mirai.internal.contact.takeSingleContent
    +import net.mamoe.mirai.internal.network.QQAndroidClient
    +import net.mamoe.mirai.internal.network.highway.Highway
    +import net.mamoe.mirai.internal.network.highway.ResourceKind
    +import net.mamoe.mirai.internal.network.protocol.data.proto.ImMsgBody
    +import net.mamoe.mirai.internal.network.protocol.data.proto.LongMsg
    +import net.mamoe.mirai.internal.network.protocol.data.proto.MsgComm
    +import net.mamoe.mirai.internal.network.protocol.data.proto.MsgTransmit
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.MessageValidationData
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.MultiMsg
    +import net.mamoe.mirai.internal.utils.io.serialization.toByteArray
    +import net.mamoe.mirai.message.data.*
    +import net.mamoe.mirai.utils.ExternalResource.Companion.toExternalResource
    +import net.mamoe.mirai.utils.bitPlusAsLong
    +import net.mamoe.mirai.utils.currentTimeMillis
    +import net.mamoe.mirai.utils.gzip
    +import net.mamoe.mirai.utils.toLongUnsigned
    +import kotlin.math.absoluteValue
    +import kotlin.random.Random
    +
    +internal open class MultiMsgUploader(
    +    val client: QQAndroidClient,
    +    val isLong: Boolean,
    +    val handler: SendMessageHandler<*>,
    +    val tmpRand: Random = Random(Random.nextLong() xor currentTimeMillis()),

    我觉得没有必要, 用 Random.Default 就可以了

    Him188 Him188 commented on code on Nov 14, 2021 00:04 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/message/MultiMsgUploader.kt:1
    @@ -0,0 +1,239 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.message
    +
    +import io.ktor.utils.io.core.*
    +import net.mamoe.mirai.internal.contact.SendMessageHandler
    +import net.mamoe.mirai.internal.contact.takeSingleContent
    +import net.mamoe.mirai.internal.network.QQAndroidClient
    +import net.mamoe.mirai.internal.network.highway.Highway
    +import net.mamoe.mirai.internal.network.highway.ResourceKind
    +import net.mamoe.mirai.internal.network.protocol.data.proto.ImMsgBody
    +import net.mamoe.mirai.internal.network.protocol.data.proto.LongMsg
    +import net.mamoe.mirai.internal.network.protocol.data.proto.MsgComm
    +import net.mamoe.mirai.internal.network.protocol.data.proto.MsgTransmit
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.MessageValidationData
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.MultiMsg
    +import net.mamoe.mirai.internal.utils.io.serialization.toByteArray
    +import net.mamoe.mirai.message.data.*
    +import net.mamoe.mirai.utils.ExternalResource.Companion.toExternalResource
    +import net.mamoe.mirai.utils.bitPlusAsLong
    +import net.mamoe.mirai.utils.currentTimeMillis
    +import net.mamoe.mirai.utils.gzip
    +import net.mamoe.mirai.utils.toLongUnsigned
    +import kotlin.math.absoluteValue
    +import kotlin.random.Random
    +
    +internal open class MultiMsgUploader(
    +    val client: QQAndroidClient,
    +    val isLong: Boolean,
    +    val handler: SendMessageHandler<*>,
    +    val tmpRand: Random = Random(Random.nextLong() xor currentTimeMillis()),
    +) {
    +
    +    protected open fun newUploader(): MultiMsgUploader = MultiMsgUploader(
    +        isLong = isLong,
    +        handler = handler,
    +        client = client,
    +        tmpRand = tmpRand,
    +    )
    +
    +    val mainMsg = mutableListOf<MsgComm.Msg>()
    +    val nestedMsgs = mutableMapOf<String, MutableList<MsgComm.Msg>>()
    +
    +    init {
    +        nestedMsgs["MultiMsg"] = mainMsg
    +    }
    +
    +    protected open fun newNid(): String {
    +        var nid: String
    +        do {
    +            nid = "${tmpRand.nextInt().absoluteValue}"
    +        } while (nestedMsgs.containsKey(nid))
    +        return nid
    +    }
    +
    +    open suspend fun emitMain(
    +        nodes: Collection<ForwardMessage.INode>,
    +    ) {
    +        emit("MultiMsg", nodes)
    +    }
    +
    +    open suspend fun emit(id: String, msgs: Collection<ForwardMessage.INode>) {

    方法体比较复杂, 有没有可能抽几个小函数 (如果更好)?

    Him188 Him188 commented on code on Nov 14, 2021 00:08 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/network/protocol/data/richstatus/RichStatus.kt:1
    @@ -0,0 +1,185 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.network.protocol.data.richstatus
    +
    +import net.mamoe.mirai.utils.toIntUnsigned
    +import java.nio.ByteBuffer
    +import java.nio.ByteOrder
    +
    +internal class RichStatus(
    +    @JvmField var actId: Int = 0,
    +    @JvmField var actionId: Int = 0,
    +    @JvmField var actionText: String? = null,
    +
    +    @JvmField var dataId: Int = 0,
    +    @JvmField var dataText: String? = null,
    +
    +    @JvmField var feedsId: String? = null,
    +
    +    @JvmField var fontId: Int = 0,
    +    @JvmField var fontType: Int = 0,
    +
    +
    +    @JvmField var key: ByteArray? = null,
    +
    +    @JvmField var latitude: Int = 0,
    +    @JvmField var locationPosition: Int = 0,
    +    @JvmField var locationText: String? = null,
    +    @JvmField var lontitude: Int = 0,
    +
    +    // @JvmField var mStickerInfos: MutableList<StickerInfo>? = null,
    +    // @JvmField var mUins: MutableList<String>? = null,
    +    @JvmField var plainText: MutableList<String>? = null,
    +
    +    // public HashMap<Integer, /**/> sigZanInfo,
    +    @JvmField var signType: Int = 0,
    +    @JvmField var time: Long = 0,
    +
    +    // var topics: MutableList<Pair<Integer, String>> = mutableListOf(),
    +    // var topicsPos: MutableList<Pair<Integer, Integer>> = mutableListOf(),
    +    @JvmField var tplId: Int = 0,
    +    @JvmField var tplType: Int = 0,
    +) {
    +
    +    fun addPlainText(var1: String) {
    +        var pts = this.plainText
    +        if (pts == null) {
    +            pts = mutableListOf()
    +            this.plainText = pts
    +        }
    +        pts.add(var1)
    +    }
    +
    +    companion object {
    +        @Suppress("ConvertTwoComparisonsToRangeCheck", "UsePropertyAccessSyntax")
    +        fun parseStatus(rawData: ByteArray?): RichStatus {
    +            val rsp = RichStatus()
    +
    +            if (rawData == null || rawData.size <= 2) return rsp
    +
    +            val byteBuffer = ByteBuffer.wrap(rawData).order(ByteOrder.BIG_ENDIAN)
    +
    +            var lastPosition = 0
    +            var var7: String? = null
    +
    +            while (byteBuffer.remaining() >= 2) {
    +                val dataType = byteBuffer.get().toIntUnsigned()
    +                val dataLength = byteBuffer.get().toIntUnsigned()
    +
    +                if (byteBuffer.remaining() < dataLength) break
    +
    +                val dataStartPosition = lastPosition + 2
    +
    +                if (dataType > 0 && dataType < 128) {
    +                    val var19 = String(rawData, dataStartPosition, dataLength)
    +                    lastPosition = dataStartPosition + dataLength
    +                    byteBuffer.position(lastPosition)
    +
    +                    println("DT: $dataType, v7: $var7, 19:$var19")
    +                    when (dataType) {
    +                        1 -> rsp.actionText = var19
    +                        2 -> rsp.dataText = var19
    +                        4 -> {
    +                            if (var7 != null) {
    +                                rsp.addPlainText(var7)
    +                                var7 = null
    +                            }
    +                            if (rsp.plainText != null) {
    +                                rsp.locationPosition = rsp.plainText!!.size
    +                            } else {
    +                                rsp.locationPosition = 0
    +                            }
    +                            rsp.locationText = var19
    +                        }
    +                        else -> {
    +                            if (var7 == null) {
    +                                var7 = var19
    +                            } else {
    +                                var7 += var19
    +                            }
    +                        }
    +                    }
    +                } else {
    +                    println("WDT: $dataType")

    println

    Him188 Him188 commented on code on Nov 14, 2021 00:08 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/network/protocol/data/richstatus/RichStatus.kt:1
    @@ -0,0 +1,185 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.network.protocol.data.richstatus
    +
    +import net.mamoe.mirai.utils.toIntUnsigned
    +import java.nio.ByteBuffer
    +import java.nio.ByteOrder
    +
    +internal class RichStatus(
    +    @JvmField var actId: Int = 0,
    +    @JvmField var actionId: Int = 0,
    +    @JvmField var actionText: String? = null,
    +
    +    @JvmField var dataId: Int = 0,
    +    @JvmField var dataText: String? = null,
    +
    +    @JvmField var feedsId: String? = null,
    +
    +    @JvmField var fontId: Int = 0,
    +    @JvmField var fontType: Int = 0,
    +
    +
    +    @JvmField var key: ByteArray? = null,
    +
    +    @JvmField var latitude: Int = 0,
    +    @JvmField var locationPosition: Int = 0,
    +    @JvmField var locationText: String? = null,
    +    @JvmField var lontitude: Int = 0,
    +
    +    // @JvmField var mStickerInfos: MutableList<StickerInfo>? = null,
    +    // @JvmField var mUins: MutableList<String>? = null,
    +    @JvmField var plainText: MutableList<String>? = null,
    +
    +    // public HashMap<Integer, /**/> sigZanInfo,
    +    @JvmField var signType: Int = 0,
    +    @JvmField var time: Long = 0,
    +
    +    // var topics: MutableList<Pair<Integer, String>> = mutableListOf(),
    +    // var topicsPos: MutableList<Pair<Integer, Integer>> = mutableListOf(),
    +    @JvmField var tplId: Int = 0,
    +    @JvmField var tplType: Int = 0,
    +) {
    +
    +    fun addPlainText(var1: String) {
    +        var pts = this.plainText
    +        if (pts == null) {
    +            pts = mutableListOf()
    +            this.plainText = pts
    +        }
    +        pts.add(var1)
    +    }
    +
    +    companion object {
    +        @Suppress("ConvertTwoComparisonsToRangeCheck", "UsePropertyAccessSyntax")
    +        fun parseStatus(rawData: ByteArray?): RichStatus {
    +            val rsp = RichStatus()
    +
    +            if (rawData == null || rawData.size <= 2) return rsp
    +
    +            val byteBuffer = ByteBuffer.wrap(rawData).order(ByteOrder.BIG_ENDIAN)
    +
    +            var lastPosition = 0
    +            var var7: String? = null
    +
    +            while (byteBuffer.remaining() >= 2) {
    +                val dataType = byteBuffer.get().toIntUnsigned()
    +                val dataLength = byteBuffer.get().toIntUnsigned()
    +
    +                if (byteBuffer.remaining() < dataLength) break
    +
    +                val dataStartPosition = lastPosition + 2
    +
    +                if (dataType > 0 && dataType < 128) {
    +                    val var19 = String(rawData, dataStartPosition, dataLength)
    +                    lastPosition = dataStartPosition + dataLength
    +                    byteBuffer.position(lastPosition)
    +
    +                    println("DT: $dataType, v7: $var7, 19:$var19")

    println

    Him188 Him188 commented on code on Nov 14, 2021 00:12 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/utils/ImagePatcher.kt:1
    @@ -0,0 +1,188 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.utils
    +
    +import net.mamoe.mirai.internal.contact.GroupImpl
    +import net.mamoe.mirai.internal.message.OfflineGroupImage
    +import net.mamoe.mirai.internal.network.component.ComponentKey
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.image.ImgStore
    +import net.mamoe.mirai.internal.network.protocol.packet.sendAndExpect
    +import net.mamoe.mirai.message.data.FriendImage
    +import net.mamoe.mirai.message.data.md5
    +import net.mamoe.mirai.utils.ResourceAccessLock
    +import net.mamoe.mirai.utils.UnsafeMutableNonNullProperty
    +import net.mamoe.mirai.utils.currentTimeMillis
    +import net.mamoe.mirai.utils.unsafeMutableNonNullPropertyOf
    +
    +internal open class ImagePatcher {
    +    companion object : ComponentKey<ImagePatcher>
    +
    +    data class ImageCache(
    +        var updateTime: Long = 0,
    +        val imgId: UnsafeMutableNonNullProperty<String> = unsafeMutableNonNullPropertyOf(),
    +        val cacheOGI: UnsafeMutableNonNullProperty<OfflineGroupImage> = unsafeMutableNonNullPropertyOf(),
    +        val access: ResourceAccessLock = ResourceAccessLock(),
    +    )
    +
    +    val caches: Array<ImageCache> = Array(20) { ImageCache() }
    +
    +    fun findCache(id: String): ImageCache? {
    +        return caches.firstOrNull { it.imgId.value0 == id && it.access.tryToUse() }
    +    }
    +
    +    fun findCacheByImageId(id: String): ImageCache? = findCache(iid(id))
    +
    +    fun putCache(id: String): ImageCache {
    +        fun ImageCache.postReturn(): ImageCache = also { cache ->
    +            cache.updateTime = currentTimeMillis()
    +            cache.imgId.value0 = id
    +        }
    +
    +        caches.forEach { exists ->
    +            if (exists.imgId.value0 == id && exists.access.tryToInit()) {
    +                return exists.postReturn()

    逻辑比较复杂, mark一下明天再看

    Him188 Him188 commented on code on Nov 14, 2021 00:13 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/utils/ImagePatcher.kt:1
    @@ -0,0 +1,188 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.utils
    +
    +import net.mamoe.mirai.internal.contact.GroupImpl
    +import net.mamoe.mirai.internal.message.OfflineGroupImage
    +import net.mamoe.mirai.internal.network.component.ComponentKey
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.image.ImgStore
    +import net.mamoe.mirai.internal.network.protocol.packet.sendAndExpect
    +import net.mamoe.mirai.message.data.FriendImage
    +import net.mamoe.mirai.message.data.md5
    +import net.mamoe.mirai.utils.ResourceAccessLock
    +import net.mamoe.mirai.utils.UnsafeMutableNonNullProperty
    +import net.mamoe.mirai.utils.currentTimeMillis
    +import net.mamoe.mirai.utils.unsafeMutableNonNullPropertyOf
    +
    +internal open class ImagePatcher {
    +    companion object : ComponentKey<ImagePatcher>
    +
    +    data class ImageCache(
    +        var updateTime: Long = 0,
    +        val imgId: UnsafeMutableNonNullProperty<String> = unsafeMutableNonNullPropertyOf(),
    +        val cacheOGI: UnsafeMutableNonNullProperty<OfflineGroupImage> = unsafeMutableNonNullPropertyOf(),
    +        val access: ResourceAccessLock = ResourceAccessLock(),
    +    )
    +
    +    val caches: Array<ImageCache> = Array(20) { ImageCache() }
    +
    +    fun findCache(id: String): ImageCache? {
    +        return caches.firstOrNull { it.imgId.value0 == id && it.access.tryToUse() }
    +    }
    +
    +    fun findCacheByImageId(id: String): ImageCache? = findCache(iid(id))
    +
    +    fun putCache(id: String): ImageCache {
    +        fun ImageCache.postReturn(): ImageCache = also { cache ->
    +            cache.updateTime = currentTimeMillis()
    +            cache.imgId.value0 = id
    +        }
    +
    +        caches.forEach { exists ->
    +            if (exists.imgId.value0 == id && exists.access.tryToInit()) {
    +                return exists.postReturn()
    +            }
    +        }
    +
    +        // Try to use existing slot
    +        caches.forEach { exists ->
    +            if (exists.access.tryToInit()) {
    +                return exists.postReturn()
    +            }
    +        }
    +
    +        val availableCaches = caches.filter { it.access.lockIfNotUsing() }
    +        if (availableCaches.isNotEmpty()) {
    +            val target = availableCaches.minByOrNull { it.updateTime }!!
    +            availableCaches.forEach { if (it !== target) it.access.unlock() }
    +
    +            target.access.setToInit()
    +            return target.postReturn()
    +        }
    +
    +        // No available sort. Force to override the last one
    +        val newCache = ImageCache()
    +        newCache.access.setToInit()
    +        newCache.postReturn()
    +
    +        var idx = 0
    +        var lupd = Long.MAX_VALUE
    +        caches.forEachIndexed { index, imageCache ->
    +            val upd0 = imageCache.updateTime
    +            if (upd0 < lupd) {
    +                lupd = upd0
    +                idx = index
    +            }
    +        }
    +        caches[idx] = newCache
    +
    +        return newCache
    +    }
    +
    +    private fun iid(imageId: String): String {
    +        return imageId.substring(1, imageId.indexOf('}'))
    +    }
    +
    +    suspend fun patchOfflineGroupImage(
    +        group: GroupImpl,
    +        image: OfflineGroupImage,
    +    ) {
    +        if (image.fileId != null) return
    +        val iid = iid(image.imageId)
    +        findCache(iid)?.let { cache ->
    +            cache.cacheOGI.value0?.let { cachedOGI ->
    +                image.fileId = cachedOGI.fileId
    +            }
    +            cache.access.release()
    +
    +            if (image.fileId != null) return
    +        }
    +
    +        val bot = group.bot
    +
    +        val response: ImgStore.GroupPicUp.Response = ImgStore.GroupPicUp(
    +            bot.client,
    +            uin = bot.id,
    +            groupCode = group.id,
    +            md5 = image.md5,
    +            size = 1,
    +        ).sendAndExpect(bot)
    +
    +        when (response) {
    +            is ImgStore.GroupPicUp.Response.Failed -> {
    +                image.fileId = 0 // Failed
    +            }
    +            is ImgStore.GroupPicUp.Response.FileExists -> {
    +                image.fileId = response.fileId.toInt()
    +            }
    +            is ImgStore.GroupPicUp.Response.RequireUpload -> {
    +                image.fileId = response.fileId.toInt()
    +            }
    +        }
    +
    +        putCache(iid).cacheOGI.value0 = image
    +    }
    +
    +    /**
    +     * Ensures server holds the cache
    +     */
    +    suspend fun patchFriendImageToGroupImage(
    +        group: GroupImpl,
    +        image: FriendImage,
    +    ): OfflineGroupImage {
    +        val iid = iid(image.imageId)
    +        findCache(iid)?.let { cache ->
    +            val fig = cache.cacheOGI.value0
    +            cache.access.release()
    +            if (fig != null) return fig
    +        }
    +
    +        val bot = group.bot
    +
    +        bot.network.run {

    顺便去除 run, 减少一层缩进

    Him188 Him188 commented on code on Nov 14, 2021 00:14 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/utils/ImagePatcher.kt:1
    @@ -0,0 +1,188 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.utils
    +
    +import net.mamoe.mirai.internal.contact.GroupImpl
    +import net.mamoe.mirai.internal.message.OfflineGroupImage
    +import net.mamoe.mirai.internal.network.component.ComponentKey
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.image.ImgStore
    +import net.mamoe.mirai.internal.network.protocol.packet.sendAndExpect
    +import net.mamoe.mirai.message.data.FriendImage
    +import net.mamoe.mirai.message.data.md5
    +import net.mamoe.mirai.utils.ResourceAccessLock
    +import net.mamoe.mirai.utils.UnsafeMutableNonNullProperty
    +import net.mamoe.mirai.utils.currentTimeMillis
    +import net.mamoe.mirai.utils.unsafeMutableNonNullPropertyOf
    +
    +internal open class ImagePatcher {
    +    companion object : ComponentKey<ImagePatcher>
    +
    +    data class ImageCache(
    +        var updateTime: Long = 0,
    +        val imgId: UnsafeMutableNonNullProperty<String> = unsafeMutableNonNullPropertyOf(),
    +        val cacheOGI: UnsafeMutableNonNullProperty<OfflineGroupImage> = unsafeMutableNonNullPropertyOf(),
    +        val access: ResourceAccessLock = ResourceAccessLock(),
    +    )
    +
    +    val caches: Array<ImageCache> = Array(20) { ImageCache() }
    +
    +    fun findCache(id: String): ImageCache? {
    +        return caches.firstOrNull { it.imgId.value0 == id && it.access.tryToUse() }
    +    }
    +
    +    fun findCacheByImageId(id: String): ImageCache? = findCache(iid(id))
    +
    +    fun putCache(id: String): ImageCache {
    +        fun ImageCache.postReturn(): ImageCache = also { cache ->
    +            cache.updateTime = currentTimeMillis()
    +            cache.imgId.value0 = id
    +        }
    +
    +        caches.forEach { exists ->
    +            if (exists.imgId.value0 == id && exists.access.tryToInit()) {
    +                return exists.postReturn()
    +            }
    +        }
    +
    +        // Try to use existing slot
    +        caches.forEach { exists ->
    +            if (exists.access.tryToInit()) {
    +                return exists.postReturn()
    +            }
    +        }
    +
    +        val availableCaches = caches.filter { it.access.lockIfNotUsing() }
    +        if (availableCaches.isNotEmpty()) {
    +            val target = availableCaches.minByOrNull { it.updateTime }!!
    +            availableCaches.forEach { if (it !== target) it.access.unlock() }
    +
    +            target.access.setToInit()
    +            return target.postReturn()
    +        }
    +
    +        // No available sort. Force to override the last one
    +        val newCache = ImageCache()
    +        newCache.access.setToInit()
    +        newCache.postReturn()
    +
    +        var idx = 0
    +        var lupd = Long.MAX_VALUE
    +        caches.forEachIndexed { index, imageCache ->
    +            val upd0 = imageCache.updateTime
    +            if (upd0 < lupd) {
    +                lupd = upd0
    +                idx = index
    +            }
    +        }
    +        caches[idx] = newCache
    +
    +        return newCache
    +    }
    +
    +    private fun iid(imageId: String): String {
    +        return imageId.substring(1, imageId.indexOf('}'))
    +    }
    +
    +    suspend fun patchOfflineGroupImage(
    +        group: GroupImpl,
    +        image: OfflineGroupImage,
    +    ) {
    +        if (image.fileId != null) return
    +        val iid = iid(image.imageId)
    +        findCache(iid)?.let { cache ->
    +            cache.cacheOGI.value0?.let { cachedOGI ->
    +                image.fileId = cachedOGI.fileId
    +            }
    +            cache.access.release()
    +
    +            if (image.fileId != null) return
    +        }
    +
    +        val bot = group.bot
    +
    +        val response: ImgStore.GroupPicUp.Response = ImgStore.GroupPicUp(
    +            bot.client,
    +            uin = bot.id,
    +            groupCode = group.id,
    +            md5 = image.md5,
    +            size = 1,
    +        ).sendAndExpect(bot)
    +
    +        when (response) {
    +            is ImgStore.GroupPicUp.Response.Failed -> {
    +                image.fileId = 0 // Failed
    +            }
    +            is ImgStore.GroupPicUp.Response.FileExists -> {
    +                image.fileId = response.fileId.toInt()
    +            }
    +            is ImgStore.GroupPicUp.Response.RequireUpload -> {
    +                image.fileId = response.fileId.toInt()
    +            }
    +        }
    +
    +        putCache(iid).cacheOGI.value0 = image
    +    }
    +
    +    /**
    +     * Ensures server holds the cache
    +     */
    +    suspend fun patchFriendImageToGroupImage(
    +        group: GroupImpl,
    +        image: FriendImage,
    +    ): OfflineGroupImage {
    +        val iid = iid(image.imageId)
    +        findCache(iid)?.let { cache ->
    +            val fig = cache.cacheOGI.value0
    +            cache.access.release()
    +            if (fig != null) return fig
    +        }
    +
    +        val bot = group.bot
    +
    +        bot.network.run {
    +            val response = ImgStore.GroupPicUp(
    +                bot.client,
    +                uin = bot.id,
    +                groupCode = group.id,
    +                md5 = image.md5,
    +                size = image.size
    +            ).sendAndExpect()
    +            return OfflineGroupImage(
    +                imageId = image.imageId,
    +                width = image.width,
    +                height = image.height,
    +                size = if (response is ImgStore.GroupPicUp.Response.FileExists) {
    +                    response.fileInfo.fileSize
    +                } else {
    +                    image.size
    +                },
    +                imageType = image.imageType
    +            ).also { img ->
    +                when (response) {
    +                    is ImgStore.GroupPicUp.Response.FileExists -> {
    +                        img.fileId = response.fileId.toInt()
    +                    }
    +                    is ImgStore.GroupPicUp.Response.RequireUpload -> {
    +                        img.fileId = response.fileId.toInt()
    +                    }
    +                    is ImgStore.GroupPicUp.Response.Failed -> {
    +                        img.fileId = 0
    +                    }
    +                }
    +            }.also { img ->
    +                putCache(iid).cacheOGI.value0 = img
    +            }
    +        }
    +    }
    +
    +    fun putCache(image: OfflineGroupImage) {

    把重载放到一起方便阅读

    Him188 Him188 commented on code on Nov 14, 2021 00:16 UTC
    Code Review
    mirai-core-utils/src/commonMain/kotlin/Numbers.kt:1
    @@ -15,3 +15,4 @@ package net.mamoe.mirai.utils
     public fun Int.toLongUnsigned(): Long = this.toLong().and(0xFFFF_FFFF)
     public fun Short.toIntUnsigned(): Int = this.toUShort().toInt()
     public fun Byte.toIntUnsigned(): Int = toInt() and 0xFF
    +public fun Int.bitPlusAsLong(i2: Int): Long = this.toLongUnsigned().shl(Long.SIZE_BITS) or i2.toLongUnsigned()

    我觉得叫 concat 可能更好

    Him188 Him188 commented on code on Nov 14, 2021 00:17 UTC
    Code Review
    mirai-core-utils/src/commonMain/kotlin/Resources.kt:1
    @@ -9,8 +9,93 @@
     
     package net.mamoe.mirai.utils
     
    +import java.util.concurrent.atomic.AtomicInteger
    +
     
     @TestOnly
     public fun readResource(url: String): String =
         Thread.currentThread().contextClassLoader.getResourceAsStream(url)?.readBytes()?.decodeToString()
             ?: error("Could not find resource '$url'")
    +
    +public class ResourceAccessLock {
    +    // -2: Locked
    +    // -1: Uninitialized
    +    // 0: Initialized
    +    // >0: Using
    +    private val count = AtomicInteger(-1)
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToDispose()) {
    +     *  res.internal.close()
    +     * }
    +     * ```
    +     */
    +    public fun tryToDispose(): Boolean {

    tryDispose would be neater

    Him188 Him188 commented on code on Nov 14, 2021 00:18 UTC
    Code Review
    mirai-core-utils/src/commonMain/kotlin/Resources.kt:1
    @@ -9,8 +9,93 @@
     
     package net.mamoe.mirai.utils
     
    +import java.util.concurrent.atomic.AtomicInteger
    +
     
     @TestOnly
     public fun readResource(url: String): String =
         Thread.currentThread().contextClassLoader.getResourceAsStream(url)?.readBytes()?.decodeToString()
             ?: error("Could not find resource '$url'")
    +
    +public class ResourceAccessLock {
    +    // -2: Locked
    +    // -1: Uninitialized
    +    // 0: Initialized
    +    // >0: Using
    +    private val count = AtomicInteger(-1)

    使用 const val 代替 magics -1 和 -2, if appropriate.

    Him188 Him188 commented on code on Nov 14, 2021 00:19 UTC
    Code Review
    mirai-core-utils/src/commonMain/kotlin/Resources.kt:1
    @@ -9,8 +9,93 @@
     
     package net.mamoe.mirai.utils
     
    +import java.util.concurrent.atomic.AtomicInteger
    +
     
     @TestOnly
     public fun readResource(url: String): String =
         Thread.currentThread().contextClassLoader.getResourceAsStream(url)?.readBytes()?.decodeToString()
             ?: error("Could not find resource '$url'")
    +
    +public class ResourceAccessLock {
    +    // -2: Locked
    +    // -1: Uninitialized
    +    // 0: Initialized
    +    // >0: Using
    +    private val count = AtomicInteger(-1)
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToDispose()) {
    +     *  res.internal.close()
    +     * }
    +     * ```
    +     */
    +    public fun tryToDispose(): Boolean {
    +        return count.compareAndSet(0, -1)
    +    }
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToInit()) {
    +     *  res.internalRes = download()
    +     * }
    +     * ```
    +     */
    +    public fun tryToInit(): Boolean {
    +        return count.compareAndSet(-1, 0)
    +    }
    +
    +    public fun tryToUse(): Boolean {
    +        val c = count
    +        while (true) {
    +            val v = c.get()
    +            if (v < 0) return false
    +            if (c.compareAndSet(v, v + 1)) return true
    +        }
    +    }
    +
    +    public fun lockIfNotUsing(): Boolean {
    +        val count = this.count
    +        while (true) {
    +            val value = count.get()
    +            if (value != 0) return false
    +            if (count.compareAndSet(0, -2)) return true
    +        }
    +    }
    +
    +    public fun release() {
    +        count.getAndDecrement()
    +    }
    +
    +    public fun unlock() {
    +        count.compareAndSet(-2, 0)
    +    }
    +
    +    public fun setToInit() {
    +        count.set(0)
    +    }
    +
    +    public fun setToLocked() {
    +        count.set(-2)
    +    }
    +
    +    public fun setToDisposed() {
    +        count.set(-1)
    +    }
    +
    +    public fun setToUninitialized() {
    +        setToDisposed()
    +    }
    +
    +    public fun currentStatus(): Int = count.get()

    I'd prefer

        public fun currentCound(): Int = count.get()
    

    for not introducing a new concept 'status'

    Him188 Him188 commented on code on Nov 14, 2021 00:20 UTC
    Code Review
    mirai-core-utils/src/commonMain/kotlin/Resources.kt:1
    @@ -9,8 +9,93 @@
     
     package net.mamoe.mirai.utils
     
    +import java.util.concurrent.atomic.AtomicInteger
    +
     
     @TestOnly
     public fun readResource(url: String): String =
         Thread.currentThread().contextClassLoader.getResourceAsStream(url)?.readBytes()?.decodeToString()
             ?: error("Could not find resource '$url'")
    +
    +public class ResourceAccessLock {

    这个用在哪里了?

    Him188 Him188 commented on code on Nov 14, 2021 00:23 UTC
    Code Review
    mirai-core-utils/src/commonMain/kotlin/Resources.kt:1
    @@ -9,8 +9,93 @@
     
     package net.mamoe.mirai.utils
     
    +import java.util.concurrent.atomic.AtomicInteger
    +
     
     @TestOnly
     public fun readResource(url: String): String =
         Thread.currentThread().contextClassLoader.getResourceAsStream(url)?.readBytes()?.decodeToString()
             ?: error("Could not find resource '$url'")
    +
    +public class ResourceAccessLock {
    +    // -2: Locked
    +    // -1: Uninitialized
    +    // 0: Initialized
    +    // >0: Using
    +    private val count = AtomicInteger(-1)
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToDispose()) {
    +     *  res.internal.close()
    +     * }
    +     * ```
    +     */
    +    public fun tryToDispose(): Boolean {
    +        return count.compareAndSet(0, -1)
    +    }
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToInit()) {
    +     *  res.internalRes = download()
    +     * }
    +     * ```
    +     */
    +    public fun tryToInit(): Boolean {
    +        return count.compareAndSet(-1, 0)
    +    }
    +
    +    public fun tryToUse(): Boolean {
    +        val c = count
    +        while (true) {
    +            val v = c.get()
    +            if (v < 0) return false
    +            if (c.compareAndSet(v, v + 1)) return true
    +        }
    +    }
    +
    +    public fun lockIfNotUsing(): Boolean {
    +        val count = this.count
    +        while (true) {
    +            val value = count.get()
    +            if (value != 0) return false
    +            if (count.compareAndSet(0, -2)) return true
    +        }
    +    }
    +
    +    public fun release() {

    release 多次 (导致 count < -2) 会怎么办?

    Him188 Him188 commented on code on Nov 14, 2021 00:24 UTC
    Code Review
    mirai-core-utils/src/commonMain/kotlin/Resources.kt:1
    @@ -9,8 +9,93 @@
     
     package net.mamoe.mirai.utils
     
    +import java.util.concurrent.atomic.AtomicInteger
    +
     
     @TestOnly
     public fun readResource(url: String): String =
         Thread.currentThread().contextClassLoader.getResourceAsStream(url)?.readBytes()?.decodeToString()
             ?: error("Could not find resource '$url'")
    +
    +public class ResourceAccessLock {
    +    // -2: Locked
    +    // -1: Uninitialized
    +    // 0: Initialized
    +    // >0: Using
    +    private val count = AtomicInteger(-1)
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToDispose()) {
    +     *  res.internal.close()
    +     * }
    +     * ```
    +     */
    +    public fun tryToDispose(): Boolean {
    +        return count.compareAndSet(0, -1)
    +    }
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToInit()) {
    +     *  res.internalRes = download()
    +     * }
    +     * ```
    +     */
    +    public fun tryToInit(): Boolean {
    +        return count.compareAndSet(-1, 0)
    +    }
    +
    +    public fun tryToUse(): Boolean {
    +        val c = count
    +        while (true) {
    +            val v = c.get()
    +            if (v < 0) return false
    +            if (c.compareAndSet(v, v + 1)) return true
    +        }
    +    }
    +
    +    public fun lockIfNotUsing(): Boolean {
    +        val count = this.count
    +        while (true) {
    +            val value = count.get()
    +            if (value != 0) return false
    +            if (count.compareAndSet(0, -2)) return true
    +        }
    +    }
    +
    +    public fun release() {
    +        count.getAndDecrement()
    +    }
    +
    +    public fun unlock() {
    +        count.compareAndSet(-2, 0)
    +    }
    +
    +    public fun setToInit() {

        public fun setInitialized() {
    

    If you useuninitialized, you'd also use initialized over init.

    Him188 Him188 commented on code on Nov 14, 2021 00:25 UTC
    Code Review
    mirai-core-utils/src/commonMain/kotlin/Resources.kt:1
    @@ -9,8 +9,93 @@
     
     package net.mamoe.mirai.utils
     
    +import java.util.concurrent.atomic.AtomicInteger
    +
     
     @TestOnly
     public fun readResource(url: String): String =
         Thread.currentThread().contextClassLoader.getResourceAsStream(url)?.readBytes()?.decodeToString()
             ?: error("Could not find resource '$url'")
    +
    +public class ResourceAccessLock {
    +    // -2: Locked
    +    // -1: Uninitialized
    +    // 0: Initialized
    +    // >0: Using
    +    private val count = AtomicInteger(-1)
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToDispose()) {
    +     *  res.internal.close()
    +     * }
    +     * ```
    +     */
    +    public fun tryToDispose(): Boolean {
    +        return count.compareAndSet(0, -1)
    +    }
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToInit()) {
    +     *  res.internalRes = download()
    +     * }
    +     * ```
    +     */
    +    public fun tryToInit(): Boolean {
    +        return count.compareAndSet(-1, 0)
    +    }
    +
    +    public fun tryToUse(): Boolean {
    +        val c = count
    +        while (true) {
    +            val v = c.get()
    +            if (v < 0) return false
    +            if (c.compareAndSet(v, v + 1)) return true
    +        }
    +    }
    +
    +    public fun lockIfNotUsing(): Boolean {
    +        val count = this.count
    +        while (true) {
    +            val value = count.get()
    +            if (value != 0) return false
    +            if (count.compareAndSet(0, -2)) return true
    +        }
    +    }
    +
    +    public fun release() {
    +        count.getAndDecrement()
    +    }
    +
    +    public fun unlock() {
    +        count.compareAndSet(-2, 0)
    +    }
    +
    +    public fun setToInit() {
    +        count.set(0)
    +    }
    +
    +    public fun setToLocked() {

        public fun setLocked() {
    

    'To' is redundant. Removing for clarity. Same for the other 3 'To's.

    Him188 Him188 commented on code on Nov 14, 2021 00:28 UTC
    Code Review
    mirai-core-utils/src/commonMain/kotlin/Resources.kt:1
    @@ -9,8 +9,93 @@
     
     package net.mamoe.mirai.utils
     
    +import java.util.concurrent.atomic.AtomicInteger
    +
     
     @TestOnly
     public fun readResource(url: String): String =
         Thread.currentThread().contextClassLoader.getResourceAsStream(url)?.readBytes()?.decodeToString()
             ?: error("Could not find resource '$url'")
    +
    +public class ResourceAccessLock {
    +    // -2: Locked
    +    // -1: Uninitialized
    +    // 0: Initialized
    +    // >0: Using
    +    private val count = AtomicInteger(-1)
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToDispose()) {
    +     *  res.internal.close()
    +     * }
    +     * ```
    +     */
    +    public fun tryToDispose(): Boolean {
    +        return count.compareAndSet(0, -1)
    +    }
    +
    +    /**
    +     * ```
    +     * if (res.lock.tryToInit()) {
    +     *  res.internalRes = download()
    +     * }
    +     * ```
    +     */
    +    public fun tryToInit(): Boolean {
    +        return count.compareAndSet(-1, 0)
    +    }
    +
    +    public fun tryToUse(): Boolean {
    +        val c = count
    +        while (true) {
    +            val v = c.get()
    +            if (v < 0) return false
    +            if (c.compareAndSet(v, v + 1)) return true
    +        }
    +    }
    +
    +    public fun lockIfNotUsing(): Boolean {
    +        val count = this.count
    +        while (true) {
    +            val value = count.get()
    +            if (value != 0) return false
    +            if (count.compareAndSet(0, -2)) return true
    +        }
    +    }
    +
    +    public fun release() {

    Test 缺少 release 测试

    Karlatemp Karlatemp commented on code on Nov 14, 2021 00:40 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/contact/GroupImpl.kt:1
    @@ -181,6 +182,12 @@ internal class GroupImpl constructor(
             if (BeforeImageUploadEvent(this, resource).broadcast().isCancelled) {
                 throw EventCancelledException("cancelled by BeforeImageUploadEvent.ToGroup")
             }
    +
    +        fun OfflineGroupImage.putIntoCache() {
    +            // We can't understand wny Image(group.uploadImage().imageId)

    user's code

    Karlatemp Karlatemp commented on code on Nov 14, 2021 00:42 UTC
    Code Review
    mirai-core-utils/src/commonMain/kotlin/Resources.kt:1
    @@ -9,8 +9,93 @@
     
     package net.mamoe.mirai.utils
     
    +import java.util.concurrent.atomic.AtomicInteger
    +
     
     @TestOnly
     public fun readResource(url: String): String =
         Thread.currentThread().contextClassLoader.getResourceAsStream(url)?.readBytes()?.decodeToString()
             ?: error("Could not find resource '$url'")
    +
    +public class ResourceAccessLock {

    ImagePatcher

    sandtechnology sandtechnology commented on code on Nov 14, 2021 14:43 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/network/protocol/data/richstatus/RichStatus.kt:1
    @@ -0,0 +1,183 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.network.protocol.data.richstatus
    +
    +import net.mamoe.mirai.utils.toIntUnsigned
    +import java.nio.ByteBuffer
    +import java.nio.ByteOrder
    +
    +internal class RichStatus(
    +    @JvmField var actId: Int = 0,
    +    @JvmField var actionId: Int = 0,
    +    @JvmField var actionText: String? = null,
    +
    +    @JvmField var dataId: Int = 0,
    +    @JvmField var dataText: String? = null,
    +
    +    @JvmField var feedsId: String? = null,
    +
    +    @JvmField var fontId: Int = 0,
    +    @JvmField var fontType: Int = 0,
    +
    +
    +    @JvmField var key: ByteArray? = null,
    +
    +    @JvmField var latitude: Int = 0,
    +    @JvmField var locationPosition: Int = 0,
    +    @JvmField var locationText: String? = null,
    +    @JvmField var lontitude: Int = 0,
    +
    +    // @JvmField var mStickerInfos: MutableList<StickerInfo>? = null,
    +    // @JvmField var mUins: MutableList<String>? = null,
    +    @JvmField var plainText: MutableList<String>? = null,
    +
    +    // public HashMap<Integer, /**/> sigZanInfo,
    +    @JvmField var signType: Int = 0,
    +    @JvmField var time: Long = 0,
    +
    +    // var topics: MutableList<Pair<Integer, String>> = mutableListOf(),
    +    // var topicsPos: MutableList<Pair<Integer, Integer>> = mutableListOf(),
    +    @JvmField var tplId: Int = 0,
    +    @JvmField var tplType: Int = 0,
    +) {
    +
    +    fun addPlainText(var1: String) {
    +        var pts = this.plainText
    +        if (pts == null) {
    +            pts = mutableListOf()
    +            this.plainText = pts
    +        }
    +        pts.add(var1)
    +    }
    +
    +    companion object {
    +        @Suppress("ConvertTwoComparisonsToRangeCheck", "UsePropertyAccessSyntax")
    +        fun parseStatus(rawData: ByteArray?): RichStatus {
    +            val rsp = RichStatus()
    +
    +            if (rawData == null || rawData.size <= 2) return rsp
    +
    +            val byteBuffer = ByteBuffer.wrap(rawData).order(ByteOrder.BIG_ENDIAN)
    +
    +            var lastPosition = 0
    +            var var7: String? = null
    +
    +            while (byteBuffer.remaining() >= 2) {
    +                val dataType = byteBuffer.get().toIntUnsigned()
    +                val dataLength = byteBuffer.get().toIntUnsigned()
    +
    +                if (byteBuffer.remaining() < dataLength) break
    +
    +                val dataStartPosition = lastPosition + 2
    +
    +                if (dataType > 0 && dataType < 128) {

    dataType in 1...127?

    sandtechnology sandtechnology commented on code on Nov 14, 2021 14:43 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/network/protocol/data/richstatus/RichStatus.kt:1
    @@ -0,0 +1,183 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.network.protocol.data.richstatus
    +
    +import net.mamoe.mirai.utils.toIntUnsigned
    +import java.nio.ByteBuffer
    +import java.nio.ByteOrder
    +
    +internal class RichStatus(
    +    @JvmField var actId: Int = 0,
    +    @JvmField var actionId: Int = 0,
    +    @JvmField var actionText: String? = null,
    +
    +    @JvmField var dataId: Int = 0,
    +    @JvmField var dataText: String? = null,
    +
    +    @JvmField var feedsId: String? = null,
    +
    +    @JvmField var fontId: Int = 0,
    +    @JvmField var fontType: Int = 0,
    +
    +
    +    @JvmField var key: ByteArray? = null,
    +
    +    @JvmField var latitude: Int = 0,
    +    @JvmField var locationPosition: Int = 0,
    +    @JvmField var locationText: String? = null,
    +    @JvmField var lontitude: Int = 0,
    +
    +    // @JvmField var mStickerInfos: MutableList<StickerInfo>? = null,
    +    // @JvmField var mUins: MutableList<String>? = null,
    +    @JvmField var plainText: MutableList<String>? = null,
    +
    +    // public HashMap<Integer, /**/> sigZanInfo,
    +    @JvmField var signType: Int = 0,
    +    @JvmField var time: Long = 0,
    +
    +    // var topics: MutableList<Pair<Integer, String>> = mutableListOf(),
    +    // var topicsPos: MutableList<Pair<Integer, Integer>> = mutableListOf(),
    +    @JvmField var tplId: Int = 0,
    +    @JvmField var tplType: Int = 0,
    +) {
    +
    +    fun addPlainText(var1: String) {
    +        var pts = this.plainText
    +        if (pts == null) {
    +            pts = mutableListOf()
    +            this.plainText = pts
    +        }
    +        pts.add(var1)
    +    }
    +
    +    companion object {
    +        @Suppress("ConvertTwoComparisonsToRangeCheck", "UsePropertyAccessSyntax")
    +        fun parseStatus(rawData: ByteArray?): RichStatus {
    +            val rsp = RichStatus()
    +
    +            if (rawData == null || rawData.size <= 2) return rsp
    +
    +            val byteBuffer = ByteBuffer.wrap(rawData).order(ByteOrder.BIG_ENDIAN)
    +
    +            var lastPosition = 0
    +            var var7: String? = null
    +
    +            while (byteBuffer.remaining() >= 2) {
    +                val dataType = byteBuffer.get().toIntUnsigned()
    +                val dataLength = byteBuffer.get().toIntUnsigned()
    +
    +                if (byteBuffer.remaining() < dataLength) break
    +
    +                val dataStartPosition = lastPosition + 2
    +
    +                if (dataType > 0 && dataType < 128) {
    +                    val var19 = String(rawData, dataStartPosition, dataLength)

    var19->dataStr?

    sandtechnology sandtechnology commented on code on Nov 14, 2021 14:44 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/network/protocol/data/richstatus/RichStatus.kt:1
    @@ -0,0 +1,183 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.network.protocol.data.richstatus
    +
    +import net.mamoe.mirai.utils.toIntUnsigned
    +import java.nio.ByteBuffer
    +import java.nio.ByteOrder
    +
    +internal class RichStatus(
    +    @JvmField var actId: Int = 0,
    +    @JvmField var actionId: Int = 0,
    +    @JvmField var actionText: String? = null,
    +
    +    @JvmField var dataId: Int = 0,
    +    @JvmField var dataText: String? = null,
    +
    +    @JvmField var feedsId: String? = null,
    +
    +    @JvmField var fontId: Int = 0,
    +    @JvmField var fontType: Int = 0,
    +
    +
    +    @JvmField var key: ByteArray? = null,
    +
    +    @JvmField var latitude: Int = 0,
    +    @JvmField var locationPosition: Int = 0,
    +    @JvmField var locationText: String? = null,
    +    @JvmField var lontitude: Int = 0,
    +
    +    // @JvmField var mStickerInfos: MutableList<StickerInfo>? = null,
    +    // @JvmField var mUins: MutableList<String>? = null,
    +    @JvmField var plainText: MutableList<String>? = null,
    +
    +    // public HashMap<Integer, /**/> sigZanInfo,
    +    @JvmField var signType: Int = 0,
    +    @JvmField var time: Long = 0,
    +
    +    // var topics: MutableList<Pair<Integer, String>> = mutableListOf(),
    +    // var topicsPos: MutableList<Pair<Integer, Integer>> = mutableListOf(),
    +    @JvmField var tplId: Int = 0,
    +    @JvmField var tplType: Int = 0,
    +) {
    +
    +    fun addPlainText(var1: String) {
    +        var pts = this.plainText
    +        if (pts == null) {
    +            pts = mutableListOf()
    +            this.plainText = pts
    +        }
    +        pts.add(var1)
    +    }
    +
    +    companion object {
    +        @Suppress("ConvertTwoComparisonsToRangeCheck", "UsePropertyAccessSyntax")
    +        fun parseStatus(rawData: ByteArray?): RichStatus {
    +            val rsp = RichStatus()
    +
    +            if (rawData == null || rawData.size <= 2) return rsp
    +
    +            val byteBuffer = ByteBuffer.wrap(rawData).order(ByteOrder.BIG_ENDIAN)
    +
    +            var lastPosition = 0
    +            var var7: String? = null

    var7->pendingDataStr?

    sandtechnology sandtechnology commented on code on Nov 14, 2021 14:47 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/network/protocol/data/richstatus/RichStatus.kt:1
    @@ -0,0 +1,183 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.network.protocol.data.richstatus
    +
    +import net.mamoe.mirai.utils.toIntUnsigned
    +import java.nio.ByteBuffer
    +import java.nio.ByteOrder
    +
    +internal class RichStatus(
    +    @JvmField var actId: Int = 0,
    +    @JvmField var actionId: Int = 0,
    +    @JvmField var actionText: String? = null,
    +
    +    @JvmField var dataId: Int = 0,
    +    @JvmField var dataText: String? = null,
    +
    +    @JvmField var feedsId: String? = null,
    +
    +    @JvmField var fontId: Int = 0,
    +    @JvmField var fontType: Int = 0,
    +
    +
    +    @JvmField var key: ByteArray? = null,
    +
    +    @JvmField var latitude: Int = 0,
    +    @JvmField var locationPosition: Int = 0,
    +    @JvmField var locationText: String? = null,
    +    @JvmField var lontitude: Int = 0,
    +
    +    // @JvmField var mStickerInfos: MutableList<StickerInfo>? = null,
    +    // @JvmField var mUins: MutableList<String>? = null,
    +    @JvmField var plainText: MutableList<String>? = null,
    +
    +    // public HashMap<Integer, /**/> sigZanInfo,
    +    @JvmField var signType: Int = 0,
    +    @JvmField var time: Long = 0,
    +
    +    // var topics: MutableList<Pair<Integer, String>> = mutableListOf(),
    +    // var topicsPos: MutableList<Pair<Integer, Integer>> = mutableListOf(),
    +    @JvmField var tplId: Int = 0,
    +    @JvmField var tplType: Int = 0,
    +) {
    +
    +    fun addPlainText(var1: String) {
    +        var pts = this.plainText
    +        if (pts == null) {
    +            pts = mutableListOf()
    +            this.plainText = pts
    +        }
    +        pts.add(var1)
    +    }
    +
    +    companion object {
    +        @Suppress("ConvertTwoComparisonsToRangeCheck", "UsePropertyAccessSyntax")
    +        fun parseStatus(rawData: ByteArray?): RichStatus {
    +            val rsp = RichStatus()
    +
    +            if (rawData == null || rawData.size <= 2) return rsp
    +
    +            val byteBuffer = ByteBuffer.wrap(rawData).order(ByteOrder.BIG_ENDIAN)
    +
    +            var lastPosition = 0
    +            var var7: String? = null
    +
    +            while (byteBuffer.remaining() >= 2) {
    +                val dataType = byteBuffer.get().toIntUnsigned()
    +                val dataLength = byteBuffer.get().toIntUnsigned()
    +
    +                if (byteBuffer.remaining() < dataLength) break
    +
    +                val dataStartPosition = lastPosition + 2
    +
    +                if (dataType > 0 && dataType < 128) {
    +                    val var19 = String(rawData, dataStartPosition, dataLength)
    +                    lastPosition = dataStartPosition + dataLength
    +                    byteBuffer.position(lastPosition)
    +
    +                    when (dataType) {
    +                        1 -> rsp.actionText = var19
    +                        2 -> rsp.dataText = var19
    +                        4 -> {
    +                            if (var7 != null) {
    +                                rsp.addPlainText(var7)
    +                                var7 = null
    +                            }
    +                            if (rsp.plainText != null) {
    +                                rsp.locationPosition = rsp.plainText!!.size
    +                            } else {
    +                                rsp.locationPosition = 0
    +                            }
    +                            rsp.locationText = var19
    +                        }
    +                        else -> {
    +                            if (var7 == null) {
    +                                var7 = var19
    +                            } else {
    +                                var7 += var19
    +                            }
    +                        }
    +                    }
    +                } else {
    +                    kotlin.run theSwitch@{
    +                        when (dataType) {
    +                            129 -> {
    +                                if (byteBuffer.remaining() >= 8) {
    +                                    rsp.actionId = byteBuffer.getInt()
    +                                    rsp.dataId = byteBuffer.getInt()
    +                                }
    +                            }
    +                            130 -> {
    +                                if (byteBuffer.remaining() >= 8) {
    +                                    rsp.lontitude = byteBuffer.getInt()
    +                                    rsp.latitude = byteBuffer.getInt()
    +                                }
    +                            }
    +                            144 -> rsp.feedsId = String(rawData, dataStartPosition, dataLength)
    +                            145 -> rsp.tplId = byteBuffer.getInt()
    +                            146 -> rsp.tplType = byteBuffer.getInt()
    +                            147 -> rsp.actId = byteBuffer.getInt()
    +                            148 -> {
    +                                if (byteBuffer.remaining() >= 4) {
    +                                    lastPosition = byteBuffer.getInt()
    +                                    /*
    +                                    if (var1 > 4) {
    +                                        var19 = String(var0, var5+4, var1-4)
    +                                        if (var19.isNotEmpty()) {
    +                                            var9.topics.add(Pair(var2, var19))
    +                                        }
    +                                    }
    +                                    */
    +                                }
    +                            }
    +                            149 -> {
    +                                if (byteBuffer.remaining() >= 5) {
    +                                    lastPosition = dataLength
    +                                    while (true) {
    +                                        if (lastPosition < 5) return@theSwitch
    +
    +                                        val var6 = byteBuffer.getInt()
    +                                        var var4 = byteBuffer.get().toIntUnsigned()

    var6->topicsIndex
    var4->topicsId?

    sandtechnology sandtechnology commented on code on Nov 14, 2021 14:48 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/utils/ImagePatcher.kt:1
    @@ -0,0 +1,188 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.utils
    +
    +import net.mamoe.mirai.internal.contact.GroupImpl
    +import net.mamoe.mirai.internal.message.OfflineGroupImage
    +import net.mamoe.mirai.internal.network.component.ComponentKey
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.image.ImgStore
    +import net.mamoe.mirai.internal.network.protocol.packet.sendAndExpect
    +import net.mamoe.mirai.message.data.FriendImage
    +import net.mamoe.mirai.message.data.md5
    +import net.mamoe.mirai.utils.ResourceAccessLock
    +import net.mamoe.mirai.utils.UnsafeMutableNonNullProperty
    +import net.mamoe.mirai.utils.currentTimeMillis
    +import net.mamoe.mirai.utils.unsafeMutableNonNullPropertyOf
    +
    +internal open class ImagePatcher {
    +    companion object : ComponentKey<ImagePatcher>
    +
    +    data class ImageCache(
    +        var updateTime: Long = 0,
    +        val imgId: UnsafeMutableNonNullProperty<String> = unsafeMutableNonNullPropertyOf(),
    +        val cacheOGI: UnsafeMutableNonNullProperty<OfflineGroupImage> = unsafeMutableNonNullPropertyOf(),
    +        val access: ResourceAccessLock = ResourceAccessLock(),
    +    )
    +
    +    val caches: Array<ImageCache> = Array(20) { ImageCache() }
    +
    +    fun findCache(id: String): ImageCache? {
    +        return caches.firstOrNull { it.imgId.value0 == id && it.access.tryUse() }
    +    }
    +
    +    fun findCacheByImageId(id: String): ImageCache? = findCache(iid(id))
    +
    +    fun putCache(image: OfflineGroupImage) {
    +        putCache(iid(image.imageId)).cacheOGI.value0 = image
    +    }
    +
    +    fun putCache(id: String): ImageCache {
    +        fun ImageCache.postReturn(): ImageCache = also { cache ->
    +            cache.updateTime = currentTimeMillis()
    +            cache.imgId.value0 = id
    +        }
    +
    +        caches.forEach { exists ->
    +            if (exists.imgId.value0 == id && exists.access.tryInitialize()) {
    +                return exists.postReturn()
    +            }
    +        }
    +
    +        // Try to use existing slot
    +        caches.forEach { exists ->
    +            if (exists.access.tryInitialize()) {
    +                return exists.postReturn()
    +            }
    +        }
    +
    +        val availableCaches = caches.filter { it.access.lockIfNotUsing() }
    +        if (availableCaches.isNotEmpty()) {
    +            val target = availableCaches.minByOrNull { it.updateTime }!!
    +            availableCaches.forEach { if (it !== target) it.access.unlock() }
    +
    +            target.access.setInitialized()
    +            return target.postReturn()
    +        }
    +
    +        // No available sort. Force to override the last one
    +        val newCache = ImageCache()
    +        newCache.access.setInitialized()
    +        newCache.postReturn()
    +
    +        var idx = 0
    +        var lupd = Long.MAX_VALUE
    +        caches.forEachIndexed { index, imageCache ->
    +            val upd0 = imageCache.updateTime
    +            if (upd0 < lupd) {
    +                lupd = upd0
    +                idx = index
    +            }
    +        }
    +        caches[idx] = newCache
    +
    +        return newCache
    +    }
    +
    +    private fun iid(imageId: String): String {

    getImageIdFromStr?

    sandtechnology sandtechnology commented on code on Nov 14, 2021 14:48 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/utils/ImagePatcher.kt:1
    @@ -0,0 +1,188 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.utils
    +
    +import net.mamoe.mirai.internal.contact.GroupImpl
    +import net.mamoe.mirai.internal.message.OfflineGroupImage
    +import net.mamoe.mirai.internal.network.component.ComponentKey
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.image.ImgStore
    +import net.mamoe.mirai.internal.network.protocol.packet.sendAndExpect
    +import net.mamoe.mirai.message.data.FriendImage
    +import net.mamoe.mirai.message.data.md5
    +import net.mamoe.mirai.utils.ResourceAccessLock
    +import net.mamoe.mirai.utils.UnsafeMutableNonNullProperty
    +import net.mamoe.mirai.utils.currentTimeMillis
    +import net.mamoe.mirai.utils.unsafeMutableNonNullPropertyOf
    +
    +internal open class ImagePatcher {
    +    companion object : ComponentKey<ImagePatcher>
    +
    +    data class ImageCache(
    +        var updateTime: Long = 0,
    +        val imgId: UnsafeMutableNonNullProperty<String> = unsafeMutableNonNullPropertyOf(),
    +        val cacheOGI: UnsafeMutableNonNullProperty<OfflineGroupImage> = unsafeMutableNonNullPropertyOf(),
    +        val access: ResourceAccessLock = ResourceAccessLock(),
    +    )
    +
    +    val caches: Array<ImageCache> = Array(20) { ImageCache() }
    +
    +    fun findCache(id: String): ImageCache? {
    +        return caches.firstOrNull { it.imgId.value0 == id && it.access.tryUse() }
    +    }
    +
    +    fun findCacheByImageId(id: String): ImageCache? = findCache(iid(id))
    +
    +    fun putCache(image: OfflineGroupImage) {
    +        putCache(iid(image.imageId)).cacheOGI.value0 = image
    +    }
    +
    +    fun putCache(id: String): ImageCache {
    +        fun ImageCache.postReturn(): ImageCache = also { cache ->
    +            cache.updateTime = currentTimeMillis()
    +            cache.imgId.value0 = id
    +        }
    +
    +        caches.forEach { exists ->
    +            if (exists.imgId.value0 == id && exists.access.tryInitialize()) {
    +                return exists.postReturn()
    +            }
    +        }
    +
    +        // Try to use existing slot
    +        caches.forEach { exists ->
    +            if (exists.access.tryInitialize()) {
    +                return exists.postReturn()
    +            }
    +        }
    +
    +        val availableCaches = caches.filter { it.access.lockIfNotUsing() }
    +        if (availableCaches.isNotEmpty()) {
    +            val target = availableCaches.minByOrNull { it.updateTime }!!
    +            availableCaches.forEach { if (it !== target) it.access.unlock() }
    +
    +            target.access.setInitialized()
    +            return target.postReturn()
    +        }
    +
    +        // No available sort. Force to override the last one
    +        val newCache = ImageCache()
    +        newCache.access.setInitialized()
    +        newCache.postReturn()
    +
    +        var idx = 0
    +        var lupd = Long.MAX_VALUE
    +        caches.forEachIndexed { index, imageCache ->
    +            val upd0 = imageCache.updateTime
    +            if (upd0 < lupd) {
    +                lupd = upd0
    +                idx = index
    +            }
    +        }
    +        caches[idx] = newCache
    +
    +        return newCache
    +    }
    +
    +    private fun iid(imageId: String): String {
    +        return imageId.substring(1, imageId.indexOf('}'))
    +    }
    +
    +    suspend fun patchOfflineGroupImage(
    +        group: GroupImpl,
    +        image: OfflineGroupImage,
    +    ) {
    +        if (image.fileId != null) return
    +        val iid = iid(image.imageId)

    imageId?

    sandtechnology sandtechnology commented on code on Nov 14, 2021 14:49 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/utils/ImagePatcher.kt:1
    @@ -0,0 +1,188 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.utils
    +
    +import net.mamoe.mirai.internal.contact.GroupImpl
    +import net.mamoe.mirai.internal.message.OfflineGroupImage
    +import net.mamoe.mirai.internal.network.component.ComponentKey
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.image.ImgStore
    +import net.mamoe.mirai.internal.network.protocol.packet.sendAndExpect
    +import net.mamoe.mirai.message.data.FriendImage
    +import net.mamoe.mirai.message.data.md5
    +import net.mamoe.mirai.utils.ResourceAccessLock
    +import net.mamoe.mirai.utils.UnsafeMutableNonNullProperty
    +import net.mamoe.mirai.utils.currentTimeMillis
    +import net.mamoe.mirai.utils.unsafeMutableNonNullPropertyOf
    +
    +internal open class ImagePatcher {
    +    companion object : ComponentKey<ImagePatcher>
    +
    +    data class ImageCache(
    +        var updateTime: Long = 0,
    +        val imgId: UnsafeMutableNonNullProperty<String> = unsafeMutableNonNullPropertyOf(),
    +        val cacheOGI: UnsafeMutableNonNullProperty<OfflineGroupImage> = unsafeMutableNonNullPropertyOf(),

    Add a comment: OGI->OfflineGroupImage

    sandtechnology sandtechnology commented on code on Nov 14, 2021 14:50 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/utils/ImagePatcher.kt:1
    @@ -0,0 +1,188 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.utils
    +
    +import net.mamoe.mirai.internal.contact.GroupImpl
    +import net.mamoe.mirai.internal.message.OfflineGroupImage
    +import net.mamoe.mirai.internal.network.component.ComponentKey
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.image.ImgStore
    +import net.mamoe.mirai.internal.network.protocol.packet.sendAndExpect
    +import net.mamoe.mirai.message.data.FriendImage
    +import net.mamoe.mirai.message.data.md5
    +import net.mamoe.mirai.utils.ResourceAccessLock
    +import net.mamoe.mirai.utils.UnsafeMutableNonNullProperty
    +import net.mamoe.mirai.utils.currentTimeMillis
    +import net.mamoe.mirai.utils.unsafeMutableNonNullPropertyOf
    +
    +internal open class ImagePatcher {
    +    companion object : ComponentKey<ImagePatcher>
    +
    +    data class ImageCache(
    +        var updateTime: Long = 0,
    +        val imgId: UnsafeMutableNonNullProperty<String> = unsafeMutableNonNullPropertyOf(),
    +        val cacheOGI: UnsafeMutableNonNullProperty<OfflineGroupImage> = unsafeMutableNonNullPropertyOf(),
    +        val access: ResourceAccessLock = ResourceAccessLock(),

    access->accessLock?

    sandtechnology sandtechnology commented on Nov 14, 2021 14:52 UTC
    Reviewer

    加了点命名建议(

    Karlatemp Karlatemp commented on code on Nov 14, 2021 15:09 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/network/protocol/data/richstatus/RichStatus.kt:1
    @@ -0,0 +1,183 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.network.protocol.data.richstatus
    +
    +import net.mamoe.mirai.utils.toIntUnsigned
    +import java.nio.ByteBuffer
    +import java.nio.ByteOrder
    +
    +internal class RichStatus(
    +    @JvmField var actId: Int = 0,
    +    @JvmField var actionId: Int = 0,
    +    @JvmField var actionText: String? = null,
    +
    +    @JvmField var dataId: Int = 0,
    +    @JvmField var dataText: String? = null,
    +
    +    @JvmField var feedsId: String? = null,
    +
    +    @JvmField var fontId: Int = 0,
    +    @JvmField var fontType: Int = 0,
    +
    +
    +    @JvmField var key: ByteArray? = null,
    +
    +    @JvmField var latitude: Int = 0,
    +    @JvmField var locationPosition: Int = 0,
    +    @JvmField var locationText: String? = null,
    +    @JvmField var lontitude: Int = 0,
    +
    +    // @JvmField var mStickerInfos: MutableList<StickerInfo>? = null,
    +    // @JvmField var mUins: MutableList<String>? = null,
    +    @JvmField var plainText: MutableList<String>? = null,
    +
    +    // public HashMap<Integer, /**/> sigZanInfo,
    +    @JvmField var signType: Int = 0,
    +    @JvmField var time: Long = 0,
    +
    +    // var topics: MutableList<Pair<Integer, String>> = mutableListOf(),
    +    // var topicsPos: MutableList<Pair<Integer, Integer>> = mutableListOf(),
    +    @JvmField var tplId: Int = 0,
    +    @JvmField var tplType: Int = 0,
    +) {
    +
    +    fun addPlainText(var1: String) {
    +        var pts = this.plainText
    +        if (pts == null) {
    +            pts = mutableListOf()
    +            this.plainText = pts
    +        }
    +        pts.add(var1)
    +    }
    +
    +    companion object {
    +        @Suppress("ConvertTwoComparisonsToRangeCheck", "UsePropertyAccessSyntax")
    +        fun parseStatus(rawData: ByteArray?): RichStatus {
    +            val rsp = RichStatus()
    +
    +            if (rawData == null || rawData.size <= 2) return rsp
    +
    +            val byteBuffer = ByteBuffer.wrap(rawData).order(ByteOrder.BIG_ENDIAN)
    +
    +            var lastPosition = 0
    +            var var7: String? = null
    +
    +            while (byteBuffer.remaining() >= 2) {
    +                val dataType = byteBuffer.get().toIntUnsigned()
    +                val dataLength = byteBuffer.get().toIntUnsigned()
    +
    +                if (byteBuffer.remaining() < dataLength) break
    +
    +                val dataStartPosition = lastPosition + 2
    +
    +                if (dataType > 0 && dataType < 128) {
    +                    val var19 = String(rawData, dataStartPosition, dataLength)
    +                    lastPosition = dataStartPosition + dataLength
    +                    byteBuffer.position(lastPosition)
    +
    +                    when (dataType) {
    +                        1 -> rsp.actionText = var19
    +                        2 -> rsp.dataText = var19
    +                        4 -> {
    +                            if (var7 != null) {
    +                                rsp.addPlainText(var7)
    +                                var7 = null
    +                            }
    +                            if (rsp.plainText != null) {
    +                                rsp.locationPosition = rsp.plainText!!.size
    +                            } else {
    +                                rsp.locationPosition = 0
    +                            }
    +                            rsp.locationText = var19
    +                        }
    +                        else -> {
    +                            if (var7 == null) {
    +                                var7 = var19
    +                            } else {
    +                                var7 += var19
    +                            }
    +                        }
    +                    }
    +                } else {
    +                    kotlin.run theSwitch@{
    +                        when (dataType) {
    +                            129 -> {
    +                                if (byteBuffer.remaining() >= 8) {
    +                                    rsp.actionId = byteBuffer.getInt()
    +                                    rsp.dataId = byteBuffer.getInt()
    +                                }
    +                            }
    +                            130 -> {
    +                                if (byteBuffer.remaining() >= 8) {
    +                                    rsp.lontitude = byteBuffer.getInt()
    +                                    rsp.latitude = byteBuffer.getInt()
    +                                }
    +                            }
    +                            144 -> rsp.feedsId = String(rawData, dataStartPosition, dataLength)
    +                            145 -> rsp.tplId = byteBuffer.getInt()
    +                            146 -> rsp.tplType = byteBuffer.getInt()
    +                            147 -> rsp.actId = byteBuffer.getInt()
    +                            148 -> {
    +                                if (byteBuffer.remaining() >= 4) {
    +                                    lastPosition = byteBuffer.getInt()
    +                                    /*
    +                                    if (var1 > 4) {
    +                                        var19 = String(var0, var5+4, var1-4)
    +                                        if (var19.isNotEmpty()) {
    +                                            var9.topics.add(Pair(var2, var19))
    +                                        }
    +                                    }
    +                                    */
    +                                }
    +                            }
    +                            149 -> {
    +                                if (byteBuffer.remaining() >= 5) {
    +                                    lastPosition = dataLength
    +                                    while (true) {
    +                                        if (lastPosition < 5) return@theSwitch
    +
    +                                        val var6 = byteBuffer.getInt()
    +                                        var var4 = byteBuffer.get().toIntUnsigned()

    目前意义未知先不改

    sandtechnology sandtechnology commented on code on Nov 14, 2021 15:11 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/message/MultiMsgUploader.kt:1
    @@ -0,0 +1,250 @@
    +/*
    + * Copyright 2019-2021 Mamoe Technologies and contributors.
    + *
    + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
    + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
    + *
    + * https://github.com/mamoe/mirai/blob/dev/LICENSE
    + */
    +
    +package net.mamoe.mirai.internal.message
    +
    +import io.ktor.utils.io.core.*
    +import net.mamoe.mirai.internal.contact.SendMessageHandler
    +import net.mamoe.mirai.internal.contact.takeSingleContent
    +import net.mamoe.mirai.internal.network.QQAndroidClient
    +import net.mamoe.mirai.internal.network.highway.Highway
    +import net.mamoe.mirai.internal.network.highway.ResourceKind
    +import net.mamoe.mirai.internal.network.protocol.data.proto.ImMsgBody
    +import net.mamoe.mirai.internal.network.protocol.data.proto.LongMsg
    +import net.mamoe.mirai.internal.network.protocol.data.proto.MsgComm
    +import net.mamoe.mirai.internal.network.protocol.data.proto.MsgTransmit
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.MessageValidationData
    +import net.mamoe.mirai.internal.network.protocol.packet.chat.MultiMsg
    +import net.mamoe.mirai.internal.utils.io.serialization.toByteArray
    +import net.mamoe.mirai.message.data.*
    +import net.mamoe.mirai.utils.ExternalResource.Companion.toExternalResource
    +import net.mamoe.mirai.utils.concatAsLong
    +import net.mamoe.mirai.utils.gzip
    +import net.mamoe.mirai.utils.toLongUnsigned
    +import kotlin.math.absoluteValue
    +import kotlin.random.Random
    +
    +internal open class MultiMsgUploader(
    +    val client: QQAndroidClient,
    +    val isLong: Boolean,
    +    val handler: SendMessageHandler<*>,
    +    val tmpRand: Random = Random.Default,
    +) {
    +
    +    protected open fun newUploader(): MultiMsgUploader = MultiMsgUploader(
    +        isLong = isLong,
    +        handler = handler,
    +        client = client,
    +        tmpRand = tmpRand,
    +    )
    +
    +    val mainMsg = mutableListOf<MsgComm.Msg>()
    +    val nestedMsgs = mutableMapOf<String, MutableList<MsgComm.Msg>>()
    +
    +    init {
    +        nestedMsgs["MultiMsg"] = mainMsg
    +    }
    +
    +    protected open fun newNid(): String {
    +        var nid: String
    +        do {
    +            nid = "${tmpRand.nextInt().absoluteValue}"
    +        } while (nestedMsgs.containsKey(nid))
    +        return nid
    +    }
    +
    +    open suspend fun emitMain(
    +        nodes: Collection<ForwardMessage.INode>,
    +    ) {
    +        emit("MultiMsg", nodes)
    +    }
    +
    +    open suspend fun convertNestedForwardMessage(nestedForward: ForwardMessage, msgChain: MessageChain): MessageChain {
    +        suspend fun convertByMessageOrigin(origin: MessageOrigin): MessageChain? {
    +            if (origin.kind != MessageOriginKind.FORWARD) return null
    +            val resId = origin.resourceId
    +            if (resId != null) {
    +                val nid = newNid()
    +                emit(nid, nestedForward.nodeList)
    +                return messageChainOf(
    +                    RichMessage.forwardMessage(
    +                        resId = resId,
    +                        fileName = nid,
    +                        forwardMessage = nestedForward,
    +                    )
    +                )
    +            }
    +            return null
    +        }
    +
    +        suspend fun convertByReUpload(): MessageChain {
    +            // Upload nested and refine to service msg
    +            val nestedMMUploader = newUploader()
    +            nestedMMUploader.emitMain(nestedForward.nodeList)
    +
    +            val resId = nestedMMUploader.uploadAndReturnResId()
    +
    +            val mirror = nestedMMUploader.nestedMsgs
    +            mirror.remove("MultiMsg")
    +            nestedMsgs.putAll(mirror)
    +
    +            val nid = newNid()
    +            nestedMsgs[nid] = nestedMMUploader.mainMsg
    +            return messageChainOf(
    +                RichMessage.forwardMessage(
    +                    resId = resId,
    +                    fileName = nid,
    +                    forwardMessage = nestedForward,
    +                )
    +            )
    +        }
    +
    +        msgChain.firstIsInstanceOrNull<MessageOrigin>()?.let { origin ->
    +            convertByMessageOrigin(origin)?.let { return it }
    +        }
    +
    +        return convertByReUpload()
    +    }
    +
    +    open suspend fun emit(id: String, msgs: Collection<ForwardMessage.INode>) {
    +        val nds = mutableListOf<MsgComm.Msg>().let { tmp ->
    +            nestedMsgs.putIfAbsent(id, tmp) ?: tmp
    +        }
    +
    +        val existsIds = mutableSetOf<Long>()
    +
    +        msgs.forEach { msg ->
    +            var msgChain = msg.messageChain
    +            msgChain.takeSingleContent<ForwardMessage>()?.let { nestedForward ->
    +                msgChain = convertNestedForwardMessage(nestedForward, msgChain)
    +            }
    +
    +            msgChain = handler.conversionMessageChain(msgChain)
    +
    +            var seq: Int = -1
    +            var uid: Int = -1
    +            msg.messageChain.sourceOrNull?.let { source ->
    +                source as MessageSourceInternal
    +
    +                seq = source.sequenceIds.first()
    +                uid = source.internalIds.first()
    +            }
    +            while (true) {
    +                if (seq != -1 && uid != -1) {
    +                    if (existsIds.add(seq.concatAsLong(uid))) break
    +                }
    +                seq = tmpRand.nextInt().absoluteValue
    +                uid = tmpRand.nextInt().absoluteValue
    +            }

    不妨使用先随机 再递增的方式?

    Him188 Him188 commented on code on Nov 14, 2021 23:28 UTC
    Code Review
    mirai-core/src/commonMain/kotlin/MiraiImpl.kt:1
    @@ -813,7 +763,20 @@ internal open class MiraiImpl : IMirai, LowLevelApiAccessor {
     
         override fun createImage(imageId: String): Image {
             return when {
    -            imageId matches IMAGE_ID_REGEX -> OfflineGroupImage(imageId)
    +            imageId matches IMAGE_ID_REGEX -> {
    +                Bot.instancesSequence.forEach { existsBot ->
    +                    runCatching {
    +                        val patcher = existsBot.asQQAndroidBot().components[ImagePatcher]
    +
    +                        patcher.findCacheByImageId(imageId)?.let { cache ->
    +                            val rsp = cache.cacheOGI.value0
    +                            cache.accessLock.release()

    这有可能抛出 ISE. 这将是个 breaking change (createImage 不再线程安全)

    有可能是我理解错了 findCache, 见 https://github.com/mamoe/mirai/pull/1667#discussion_r748933681

    如果 findCache 确实是我说的那样, 那773行这样写的就没问题, 否则可能有问题

    Him188 Him188 commented on Nov 14, 2021 23:41 UTC
    Reviewer

    Any tests for ImagePatcher? It's essential to ensure Image works properly.

    Him188 Him188 approved these changes on Nov 15, 2021 22:06 UTC
    Approved Reviewer

    Approved these changes.

    Him188 Him188 requested changes on Nov 15, 2021 22:12 UTC
    Changes Requested Reviewer

    Optimize commit history and prepare for Rebase and Merge

    Reviewers
    Assignees
    Karlatemp Karlatemp
    Labels
    risk: low confidence: 70.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 62.1% (MEDIUM) · Higher = larger blast radius
    62.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 70.9% · Lower = rushed or shallow review
    70.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 18.1% · Safe to merge
    18.1%
    Repository