tgbotapi/src/main/kotlin/com/github/insanusmokrassar/TelegramBotAPI/types/ChatIdentifier.kt

56 lines
1.4 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)
@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
}
}
fun String.asUsername(): Username = Username(this)
@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
}
}
}