1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2024-06-03 00:15:27 +00:00
tgbotapi/tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/types/buttons/KeyboardButtonPollType.kt

60 lines
1.9 KiB
Kotlin
Raw Normal View History

2020-10-04 11:06:30 +00:00
package dev.inmo.tgbotapi.types.buttons
2020-01-23 12:06:22 +00:00
2020-10-04 11:06:30 +00:00
import dev.inmo.tgbotapi.types.*
2020-01-23 12:06:22 +00:00
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.SerialDescriptor
2020-08-18 06:50:11 +00:00
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
2020-01-23 12:06:22 +00:00
import kotlinx.serialization.json.*
@Serializable(KeyboardButtonPollTypeSerializer::class)
sealed interface KeyboardButtonPollType {
val type: String
2020-01-23 12:06:22 +00:00
}
@Serializable
class UnknownKeyboardButtonPollType internal constructor(override val type: String): KeyboardButtonPollType
2020-01-23 12:06:22 +00:00
@Serializable
object RegularKeyboardButtonPollType : KeyboardButtonPollType {
2020-01-23 12:06:22 +00:00
override val type: String = regularPollType
}
@Serializable
object QuizKeyboardButtonPollType : KeyboardButtonPollType {
2020-01-23 12:06:22 +00:00
override val type: String = quizPollType
}
@Serializer(KeyboardButtonPollType::class)
internal object KeyboardButtonPollTypeSerializer : KSerializer<KeyboardButtonPollType> {
private val internalSerializer = JsonElement.serializer()
override val descriptor: SerialDescriptor = internalSerializer.descriptor
2020-01-23 12:06:22 +00:00
override fun deserialize(decoder: Decoder): KeyboardButtonPollType {
val type = when (val asJson = internalSerializer.deserialize(decoder)) {
2020-01-23 12:06:22 +00:00
is JsonPrimitive -> asJson.content
2020-08-18 06:50:11 +00:00
else -> asJson.jsonObject[typeField] ?.jsonPrimitive ?.content ?: "absent"
2020-01-23 12:06:22 +00:00
}
return when (type) {
regularPollType -> RegularKeyboardButtonPollType
quizPollType -> QuizKeyboardButtonPollType
else -> UnknownKeyboardButtonPollType(type)
}
}
/**
* Crutch due to the fact that direct serialization of objects currently does not work perfectly
*/
2020-03-22 07:37:01 +00:00
override fun serialize(encoder: Encoder, value: KeyboardButtonPollType) {
internalSerializer.serialize(
encoder,
JsonObject(
mapOf(
2020-03-22 07:37:01 +00:00
typeField to JsonPrimitive(value.type)
)
)
)
2020-01-23 12:06:22 +00:00
}
}