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

FullChatIdentifierSerializer

This commit is contained in:
InsanusMokrassar 2022-11-11 21:44:37 +06:00
parent e8991f8f89
commit c72993017f
2 changed files with 40 additions and 0 deletions

View File

@ -4,6 +4,7 @@
* `Core`:
* Add opportunity to create `IdChatIdentifier` with optional `threadId`
* New serializer `FullChatIdentifierSerializer` with serialization of `ChatIdWithThreadId`
## 4.1.0

View File

@ -97,6 +97,7 @@ object ChatIdentifierSerializer : KSerializer<ChatIdentifier> {
override val descriptor: SerialDescriptor = internalSerializer.descriptor
override fun deserialize(decoder: Decoder): ChatIdentifier {
val id = internalSerializer.deserialize(decoder)
return id.longOrNull ?.let {
ChatId(it)
} ?: id.content.let {
@ -115,3 +116,41 @@ object ChatIdentifierSerializer : KSerializer<ChatIdentifier> {
}
}
}
@RiskFeature
object FullChatIdentifierSerializer : KSerializer<ChatIdentifier> {
private val internalSerializer = JsonPrimitive.serializer()
override val descriptor: SerialDescriptor = internalSerializer.descriptor
override fun deserialize(decoder: Decoder): ChatIdentifier {
val id = internalSerializer.deserialize(decoder)
return id.longOrNull ?.let {
ChatId(it)
} ?:let {
val splitted = id.content.split("/")
if (splitted.size == 2) {
val (chatId, threadId) = splitted
ChatIdWithThreadId(
chatId.toLongOrNull() ?: return@let null,
threadId.toLongOrNull() ?: return@let null
)
} else {
null
}
} ?: id.content.let {
if (!it.startsWith("@")) {
Username("@$it")
} else {
Username(it)
}
}
}
override fun serialize(encoder: Encoder, value: ChatIdentifier) {
when (value) {
is ChatId -> encoder.encodeLong(value.chatId)
is ChatIdWithThreadId -> encoder.encodeString("${value.chatId}/${value.threadId}")
is Username -> encoder.encodeString(value.username)
}
}
}