1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2024-06-03 00:15:27 +00:00
tgbotapi/src/main/kotlin/com/github/insanusmokrassar/TelegramBotAPI/types/ChatIdentifier.kt

58 lines
1.5 KiB
Kotlin
Raw Normal View History

2018-12-26 08:07:24 +00:00
package com.github.insanusmokrassar.TelegramBotAPI.types
import kotlinx.serialization.*
@Serializable(ChatIdentifierSerializer::class)
sealed class ChatIdentifier
/**
* Also used as User Identifier
*/
@Serializable(ChatIdentifierSerializer::class)
data class ChatId(
2018-12-26 08:07:24 +00:00
val chatId: Identifier
) : ChatIdentifier()
2019-03-31 03:11:32 +00:00
val ChatId.link: String
get() = "tg://user?id=$chatId"
2018-12-26 08:07:24 +00:00
typealias UserId = ChatId
fun Identifier.toChatId(): ChatId = ChatId(this)
2019-06-02 14:59:24 +00:00
fun Int.toChatId(): ChatId = toLong().toChatId()
fun Byte.toChatId(): ChatId = toLong().toChatId()
2018-12-26 08:07:24 +00:00
@Serializable(ChatIdentifierSerializer::class)
data class Username(
2019-02-18 06:35:58 +00:00
val username: String
2018-12-26 08:07:24 +00:00
) : ChatIdentifier() {
2019-02-18 06:35:58 +00:00
init {
if (!username.startsWith("@")) {
throw IllegalArgumentException("Username must starts with `@`")
2019-02-18 04:53:01 +00:00
}
2018-12-26 08:07:24 +00:00
}
}
2019-06-02 14:57:52 +00:00
fun String.toUsername(): Username = Username(this)
2018-12-26 08:07:24 +00:00
@Serializer(ChatIdentifier::class)
internal class ChatIdentifierSerializer: KSerializer<ChatIdentifier> {
2019-02-21 06:21:33 +00:00
override fun deserialize(decoder: Decoder): ChatIdentifier {
val id = decoder.decodeString()
2018-12-26 08:07:24 +00:00
return id.toLongOrNull() ?.let {
ChatId(it)
2019-02-18 06:35:58 +00:00
} ?: if (!id.startsWith("@")) {
Username("@$id")
} else {
Username(id)
}
2018-12-26 08:07:24 +00:00
}
2019-02-21 06:21:33 +00:00
override fun serialize(encoder: Encoder, obj: ChatIdentifier) {
2018-12-26 08:07:24 +00:00
when (obj) {
2019-02-21 06:21:33 +00:00
is ChatId -> encoder.encodeString(obj.chatId.toString())
is Username -> encoder.encodeString(obj.username)
2018-12-26 08:07:24 +00:00
}
}
}