1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2024-11-22 16:23:48 +00:00

fix in chat member deserializing

This commit is contained in:
InsanusMokrassar 2023-09-24 21:33:26 +06:00
parent 1a1fd926dd
commit 6273990b00

View File

@ -4,6 +4,7 @@ import dev.inmo.tgbotapi.abstracts.WithUser
import dev.inmo.tgbotapi.types.statusField
import dev.inmo.tgbotapi.utils.RiskFeature
import dev.inmo.tgbotapi.utils.nonstrictJsonFormat
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.SerialDescriptor
@ -15,13 +16,13 @@ import kotlinx.serialization.json.jsonPrimitive
@Serializable(ChatMemberSerializer::class)
sealed interface ChatMember : WithUser {
@Serializable
enum class Status(val status: String) {
Creator("creator"),
Administrator("administrator"),
Member("member"),
Restricted("restricted"),
Left("left"),
Kicked("kicked")
enum class Status(val status: String, val deserializationStrategy: DeserializationStrategy<ChatMember>) {
Creator("creator", OwnerChatMember.serializer()),
Administrator("administrator", AdministratorChatMemberImpl.serializer()),
Member("member", MemberChatMemberImpl.serializer()),
Restricted("restricted", RestrictedChatMember.serializer()),
Left("left", LeftChatMemberImpl.serializer()),
Kicked("kicked", KickedChatMember.serializer())
}
val status: Status
}
@ -32,17 +33,14 @@ object ChatMemberSerializer : KSerializer<ChatMember> {
override fun deserialize(decoder: Decoder): ChatMember {
val json = JsonObject.serializer().deserialize(decoder)
val status = ChatMember.Status.valueOf(
json[statusField] ?.jsonPrimitive ?.content ?: error("Status field of chat member must be specified, but incoming json contains next: $json")
)
return when (status) {
ChatMember.Status.Creator -> nonstrictJsonFormat.decodeFromJsonElement(OwnerChatMember.serializer(), json)
ChatMember.Status.Administrator -> nonstrictJsonFormat.decodeFromJsonElement(AdministratorChatMemberImpl.serializer(), json)
ChatMember.Status.Member -> nonstrictJsonFormat.decodeFromJsonElement(MemberChatMemberImpl.serializer(), json)
ChatMember.Status.Restricted -> nonstrictJsonFormat.decodeFromJsonElement(RestrictedChatMember.serializer(), json)
ChatMember.Status.Left -> nonstrictJsonFormat.decodeFromJsonElement(LeftChatMemberImpl.serializer(), json)
ChatMember.Status.Kicked -> nonstrictJsonFormat.decodeFromJsonElement(KickedChatMember.serializer(), json)
val status = json[statusField] ?.jsonPrimitive ?.content ?: error("Status field of chat member must be specified, but incoming json contains next: $json")
return ChatMember.Status.values().firstNotNullOfOrNull {
if (it.status == status) {
nonstrictJsonFormat.decodeFromJsonElement(it.deserializationStrategy, json)
} else {
null
}
} ?: error("Unknown type of chat member in json: $json")
}
override fun serialize(encoder: Encoder, value: ChatMember) {