Rename module name and add dm-codec module to serialization/deserialization dm message

This commit is contained in:
2026-08-30 22:09:27 +08:00
parent 9ce6fc32a0
commit 539a300946
42 files changed
+886 -55

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
kotlin("multiplatform")
kotlin("plugin.serialization")
}
kotlin {
explicitApi()
linuxX64()
linuxArm64()
macosArm64()
mingwX64()
jvm { compilerOptions.jvmTarget = JvmTarget.JVM_11 }
sourceSets {
commonMain.dependencies {
api("org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0")
api("org.kotlincrypto.hash:md:0.8.0")
api("org.jetbrains.kotlinx:kotlinx-io-core:0.9.1")
}
commonTest.dependencies {
implementation(kotlin("test"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0")
}
}
}
@@ -0,0 +1,13 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.annotations
@RequiresOptIn(level = RequiresOptIn.Level.ERROR)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY)
public annotation class InternalBldmApi
@@ -0,0 +1,14 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/29
*/
package cn.rtast.bldm.codec
public object BLDMConstants {
public const val REAL_ROOM_ID_URL: String = "https://api.live.bilibili.com/room/v1/Room/room_init?id="
public const val USER_NAV_URL: String = "https://api.bilibili.com/x/web-interface/nav"
public const val DM_SERVER_CONF_URL: String =
"https://api.live.bilibili.com/xlive/web-room/v1/index/getDanmuInfo"
}
@@ -0,0 +1,37 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/29
*/
package cn.rtast.bldm.codec.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
@Serializable
public data class DMServerConf(
val data: ServerConf,
) {
@Serializable
public data class ServerConf(
val token: String,
@SerialName("host_list")
val hostList: List<ServerHost>,
)
@Serializable
public data class ServerHost(
val host: String,
val port: Int,
@SerialName("wss_port")
val wssPort: Int,
@SerialName("ws_port")
val wsPort: Int,
)
@Transient
public val defaultServerHost: ServerHost = ServerHost("broadcastlv.chat.bilibili.com", 2243, 2245, 2244)
}
@@ -0,0 +1,22 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/29
*/
package cn.rtast.bldm.codec.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
public data class RealRoomId(
val data: RoomId
) {
@Serializable
public data class RoomId(
@SerialName("room_id")
val roomId: Long
)
}
@@ -0,0 +1,93 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
@file:OptIn(ExperimentalUnsignedTypes::class)
package cn.rtast.bldm.codec.data
import cn.rtast.bldm.codec.util.digest
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlin.time.Clock
@Serializable
public data class UserNavData(
val data: NavData,
) {
@Serializable
public data class NavData(
@SerialName("wbi_img")
val wbiImg: WbiImg,
)
@Serializable
public data class WbiImg(
@SerialName("img_url")
val imgUrl: String,
@SerialName("sub_url")
val subUrl: String,
)
private companion object {
val MIXIN_KEY_ENC_TAB = intArrayOf(
46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49,
33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40,
61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11,
36, 20, 34, 44, 52
)
fun String.encodeURIComponent(): String {
val bytes = this.encodeToByteArray()
val sb = StringBuilder()
for (b in bytes) {
val c = b.toInt().and(0xFF).toChar()
if (c in 'A'..'Z' || c in 'a'..'z' || c in '0'..'9' || c == '-' || c == '_' || c == '.' || c == '~') {
sb.append(c)
} else {
val hex = (b.toInt() and 0xFF).toString(16).uppercase()
sb.append('%')
if (hex.length == 1) sb.append('0')
sb.append(hex)
}
}
return sb.toString()
}
fun Map<String, Any?>.toQueryString(): String {
return this.mapNotNull { (key, value) ->
if (value != null) {
"${key.encodeURIComponent()}=${value.toString().encodeURIComponent()}"
} else {
null
}
}.joinToString("&")
}
}
/**
* get resorted mixin key
*/
private fun getMixinKey(): String =
(data.wbiImg.imgUrl.substringAfterLast('/').removeSuffix(".png") +
data.wbiImg.subUrl.substringAfterLast('/').removeSuffix(".png")).let { s ->
buildString { repeat(32) { append(s[MIXIN_KEY_ENC_TAB[it]]) } }
}
public fun signWbi(room: Long): String {
// val payload = _wbi_sign_payload(room, 0, Clock.System.now().epochSeconds) // ref
val wts = Clock.System.now().epochSeconds
val params = mapOf("id" to room, "type" to 0)
.entries.sortedBy { it.key }.associate { it.key to it.value }.toMutableMap()
return buildString {
append(params.toQueryString())
params["wts"] = wts
append("&wts=$wts")
append("&w_rid=${(params.toQueryString() + getMixinKey()).digest()}")
}
}
}
@@ -0,0 +1,43 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.data.protocol
import kotlinx.serialization.Serializable
@Serializable
internal data class AuthPayload(
/**
* user id
*/
val uid: Long,
/**
* room id
*/
val roomid: Long,
/**
* protocol version
* always be 2
*/
val protover: Int,
/**
* device id
*/
val buvid: String,
/**
* platform always be "web"
*/
val platform: String,
/**
* always be 2
*/
val type: Int,
/**
* token
*/
val key: String
)
@@ -0,0 +1,17 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.data.protocol
import kotlinx.serialization.Serializable
@Serializable
public data class PacketMetadata(
val packetLength: Int,
val protocolType: Int,
val opCode: Int
)
@@ -0,0 +1,13 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.data.protocol
import kotlinx.serialization.Serializable
@Serializable
public data class RawDanmuMessage(val content: String)
@@ -0,0 +1,83 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.protocol
import kotlinx.io.Buffer
import kotlinx.io.readByteArray
/**
* packet header 16 bytes length + body (variant length)
*/
public data class Packet(
/**
* total packet length
* 4 bytes
*/
val packetLength: Int = -1,
/**
* always 16
* 2 bytes
*/
val headerLength: Short = 16,
/**
* protocol = 1
* 2 bytes
*/
val protocolVersion: Short = 1,
/**
* packet type
* 4 bytes
*/
val packetType: Int,
/**
* packet sequence
* value is usually 1
* 4 bytes
*/
val sequence: Int = 1,
/**
* packet body
* variant length
*/
val body: ByteArray,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as Packet
if (packetLength != other.packetLength) return false
if (headerLength != other.headerLength) return false
if (protocolVersion != other.protocolVersion) return false
if (packetType != other.packetType) return false
if (sequence != other.sequence) return false
if (!body.contentEquals(other.body)) return false
return true
}
override fun hashCode(): Int {
var result = packetLength
result = 31 * result + headerLength
result = 31 * result + protocolVersion
result = 31 * result + packetType
result = 31 * result + sequence
result = 31 * result + body.contentHashCode()
return result
}
public fun toByteArray(): ByteArray = Buffer().apply {
writeInt(16 + body.size)
writeShort(headerLength)
writeShort(protocolVersion)
writeInt(packetType)
writeInt(sequence)
write(body, 0, body.size)
}.readByteArray()
}
@@ -0,0 +1,21 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.protocol
public enum class PacketType(public val pkCode: Int) {
AUTH(7),
AUTH_REPLY(8),
HEARTBEAT(2),
HEARTBEAT_REPLY(3),
Message(5);
public companion object {
private val map = PacketType.entries.associateBy { it.pkCode }
public fun fromCode(code: Int): PacketType? = map[code]
}
}
@@ -0,0 +1,17 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.protocol
internal enum class ProtocolVersion(val proto: Short) {
Raw(0), Zlib(2);
companion object {
private val map = entries.associateBy { it.proto }
fun fromCode(code: Short): ProtocolVersion? = map[code]
}
}
@@ -0,0 +1,68 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.protocol.codec
import cn.rtast.bldm.codec.data.protocol.RawDanmuMessage
import cn.rtast.bldm.codec.protocol.PacketType
import cn.rtast.bldm.codec.protocol.ProtocolVersion
import cn.rtast.bldm.codec.protocol.ProtocolVersion.Raw
import cn.rtast.bldm.codec.protocol.ProtocolVersion.Zlib
import cn.rtast.bldm.codec.protocol.event.PacketEvents
import cn.rtast.bldm.codec.util.zlibDecompress
import kotlinx.io.Buffer
import kotlinx.io.readByteArray
public class PacketDecoder(eventsBuilder: PacketEvents.() -> Unit) {
private val events = PacketEvents().apply(eventsBuilder)
private val persistentBuffer = Buffer()
public fun decode(bytes: ByteArray) {
persistentBuffer.write(bytes)
this.decodeBuffer(persistentBuffer)
}
private fun decodeBuffer(buffer: Buffer) {
while (buffer.size >= 16) {
val pk = buffer.peek()
val packetLength = pk.readInt()
val headerLength = pk.readShort()
val protocolVersion = pk.readShort()
val opCode = pk.readInt()
if (buffer.size < packetLength) break
val currentPacket = buffer.readByteArray(packetLength)
val bodySize = packetLength - headerLength
if (bodySize <= 0) continue
val body = currentPacket.copyOfRange(headerLength.toInt(), packetLength)
when (ProtocolVersion.fromCode(protocolVersion)) {
Raw -> handlePayload(opCode, body)
Zlib -> {
val decompressed = body.zlibDecompress()
val decompressedBuffer = Buffer().apply { write(decompressed) }
decodeBuffer(decompressedBuffer)
}
null -> {}
}
}
}
private fun handlePayload(opCode: Int, body: ByteArray) {
when (PacketType.fromCode(opCode)) {
PacketType.AUTH_REPLY -> events.authReplyHandler?.invoke()
PacketType.HEARTBEAT_REPLY -> events.heartbeatHandler?.invoke()
PacketType.Message -> events.messageHandler?.invoke(decodeDanmuMessage(body))
else -> {}
}
}
private fun decodeDanmuMessage(bytes: ByteArray): RawDanmuMessage {
return RawDanmuMessage(bytes.decodeToString())
}
}
@@ -0,0 +1,33 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
@file:OptIn(InternalBldmApi::class)
package cn.rtast.bldm.codec.protocol.codec
import cn.rtast.bldm.codec.annotations.InternalBldmApi
import cn.rtast.bldm.codec.data.protocol.AuthPayload
import cn.rtast.bldm.codec.protocol.Packet
import cn.rtast.bldm.codec.protocol.PacketType
import cn.rtast.bldm.codec.util.AutoIncrementInt
import cn.rtast.bldm.codec.util._encodeJson
public class PacketEncoder {
public companion object {
private val HEARTBEAT_BODY: ByteArray = "[Object object]".encodeToByteArray()
}
private val _sequence by AutoIncrementInt()
public fun authPacket(uid: Long, roomId: Long, buvid: String, token: String): Packet {
val payload = AuthPayload(uid, roomId, 2, buvid, "web", 2, token)
._encodeJson().encodeToByteArray()
return Packet(packetType = PacketType.AUTH.pkCode, sequence = _sequence, body = payload)
}
public fun heartbeatPacket(): Packet = Packet(packetType = 2, sequence = _sequence, body = HEARTBEAT_BODY)
}
@@ -0,0 +1,28 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.protocol.event
import cn.rtast.bldm.codec.data.protocol.RawDanmuMessage
public class PacketEvents {
internal var messageHandler: ((RawDanmuMessage) -> Unit)? = null
internal var heartbeatHandler: (() -> Unit)? = null
internal var authReplyHandler: (() -> Unit)? = null
public fun onMessage(block: (RawDanmuMessage) -> Unit) {
messageHandler = block
}
public fun onHeartbeat(block: () -> Unit) {
heartbeatHandler = block
}
public fun onAuthReply(block: () -> Unit) {
authReplyHandler = block
}
}
@@ -0,0 +1,18 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.util
import kotlin.reflect.KProperty
internal class AutoIncrementInt(initialValue: Int = 1) {
private var count = initialValue
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
return ++count
}
}
@@ -0,0 +1,29 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.util
/**
* get buvid and uid from a cookie
* first -> buvid
* second -> uid
*/
public fun parseBuvidAndUid(cookie: String): Pair<String?, Long?> {
if (cookie.isBlank()) return Pair(null, null)
var buvid: String? = null
var uid: Long? = null
cookie.split(';').forEach { entry ->
val parts = entry.split('=', limit = 2)
if (parts.size == 2) {
when (parts[0].trim()) {
"buvid3" -> buvid = parts[1].trim()
"DedeUserID" -> uid = parts[1].trim().toLongOrNull()
}
}
}
return buvid to uid
}
@@ -0,0 +1,14 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.util
import org.kotlincrypto.hash.md.MD5
internal val md5Instance = MD5()
internal fun String.digest(): String = md5Instance.digest(this.encodeToByteArray()).toHexString()
@@ -0,0 +1,30 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
@file:Suppress("FunctionName")
package cn.rtast.bldm.codec.util
import cn.rtast.bldm.codec.annotations.InternalBldmApi
import kotlinx.serialization.json.Json
internal val dmMessageParser = Json {
ignoreUnknownKeys = true
classDiscriminator = "cmd"
}
@InternalBldmApi
@Suppress("ObjectPropertyName")
public val _json: Json = Json {
ignoreUnknownKeys = true
isLenient = true
}
@InternalBldmApi
public inline fun <reified T> String._fromJson(): T = _json.decodeFromString(this)
@InternalBldmApi
public inline fun <reified T> T._encodeJson(): String = _json.encodeToString(this)
@@ -0,0 +1,10 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.util
internal expect fun ByteArray.zlibDecompress(): ByteArray
@@ -0,0 +1,24 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package test
import org.kotlincrypto.hash.md.MD5
import kotlin.test.Test
import kotlin.test.assertEquals
class TestMd5 {
@Test
fun `test md5`() {
val target = "e10adc3949ba59abbe56e057f20f883e" // 123456
val res = MD5().digest("123456".encodeToByteArray()).toHexString()
assertEquals(target, res)
}
}
@@ -0,0 +1,22 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package test
import cn.rtast.bldm.codec.data.UserNavData
import kotlin.test.Test
class TestWbiSign {
@Test
fun `test wbi sign`() {
val imgUrl = "https://i0.hdslb.com/bfs/wbi/7cd084941338484aae1ad9425b84077c.png"
val subUrl = "https://i0.hdslb.com/bfs/wbi/4932caff0ff746eab6f01bf08b70ac45.png"
val signWbi = UserNavData(UserNavData.NavData(UserNavData.WbiImg(imgUrl, subUrl))).signWbi(27245513)
println(signWbi)
}
}
@@ -0,0 +1,24 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
package cn.rtast.bldm.codec.util
import java.io.ByteArrayOutputStream
import java.util.zip.Inflater
public actual fun ByteArray.zlibDecompress(): ByteArray {
val inflater = Inflater(false)
val outputStream = ByteArrayOutputStream(this.size)
val buffer = ByteArray(1024)
inflater.setInput(this)
while (!inflater.finished()) {
val length = inflater.inflate(buffer)
if (length > 0) outputStream.write(buffer, 0, length)
}
inflater.end()
return outputStream.toByteArray()
}
@@ -0,0 +1,68 @@
/*
* Copyright © 2026 RTAkland
* Author: RTAkland
* Date: 2026/8/30
*/
@file:OptIn(ExperimentalForeignApi::class)
package cn.rtast.bldm.codec.util
import kotlinx.cinterop.*
import platform.zlib.*
private const val ENABLE_ZLIB_GZIP_HEADER = 15 + 32
public actual fun ByteArray.zlibDecompress(): ByteArray {
if (isEmpty()) return ByteArray(0)
return memScoped {
val stream = alloc<z_stream>()
stream.zalloc = null
stream.zfree = null
stream.opaque = null
val initResult = inflateInit2_(
stream.ptr,
ENABLE_ZLIB_GZIP_HEADER,
ZLIB_VERSION,
sizeOf<z_stream>().toInt()
)
check(initResult == Z_OK) { "inflateInit2_ failed with code: $initResult" }
val inputPinned = this@zlibDecompress.pin()
try {
stream.next_in = inputPinned.addressOf(0).reinterpret()
stream.avail_in = this@zlibDecompress.size.toUInt()
val bufferSize = 4096
val tempBuffer = ByteArray(bufferSize)
val tempPinned = tempBuffer.pin()
val output = ArrayList<Byte>(this@zlibDecompress.size * 3)
try {
var result: Int
do {
stream.next_out = tempPinned.addressOf(0).reinterpret()
stream.avail_out = bufferSize.toUInt()
result = inflate(stream.ptr, Z_NO_FLUSH)
check(result == Z_OK || result == Z_STREAM_END) { "inflate error: $result" }
val bytesDecompressed = bufferSize - stream.avail_out.toInt()
for (i in 0 until bytesDecompressed) {
output.add(tempBuffer[i])
}
if (result == Z_STREAM_END) break
} while (stream.avail_in > 0u || stream.avail_out == 0u)
} finally {
tempPinned.unpin()
}
inflateEnd(stream.ptr)
return@memScoped output.toByteArray()
} finally {
inputPinned.unpin()
}
}
}