1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2024-06-26 11:38:09 +00:00
tgbotapi/src/main/kotlin/com/github/insanusmokrassar/TelegramBotAPI/types/ChatIdentifier.kt

55 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()
typealias UserId = ChatId
fun Identifier.toChatId(): ChatId = ChatId(this)
@Serializable(ChatIdentifierSerializer::class)
data class Username(
2019-02-17 13:12:56 +00:00
private val baseUsername: String
2018-12-26 08:07:24 +00:00
) : ChatIdentifier() {
2019-02-17 13:12:56 +00:00
@Transient
val username: String = if (!baseUsername.startsWith("@")) {
"@$baseUsername"
} else {
baseUsername
}
override fun equals(other: Any?): Boolean {
return super.equals(other) || other ?.let {
super.equals("@$it")
} ?: false
2018-12-26 08:07:24 +00:00
}
}
fun String.asUsername(): Username = Username(this)
@Serializer(ChatIdentifier::class)
internal class ChatIdentifierSerializer: KSerializer<ChatIdentifier> {
override fun deserialize(input: Decoder): ChatIdentifier {
val id = input.decodeString()
return id.toLongOrNull() ?.let {
ChatId(it)
} ?: Username(id)
}
override fun serialize(output: Encoder, obj: ChatIdentifier) {
when (obj) {
is ChatId -> output.encodeString(obj.chatId.toString())
is Username -> output.encodeString(obj.username)
}
}
}