2 changed files with 46 additions and 1 deletions
@ -0,0 +1,43 @@ |
|||||||
|
package com.utun.chat.data |
||||||
|
|
||||||
|
import org.json.JSONArray |
||||||
|
import org.json.JSONObject |
||||||
|
|
||||||
|
data class ReactionState(val id: Int, val emoji: String, val count: Int = 0, val mine: Boolean = false) |
||||||
|
data class PollOption(val id: Int, val text: String, val count: Int, val percent: Double) |
||||||
|
data class PollResponse(val nodeId: Long, val choices: List<Int>, val custom: String) |
||||||
|
data class PollState(val question: String, val multiple: Boolean, val allowCustom: Boolean, |
||||||
|
val options: List<PollOption>, val voters: Int, val ver: Long, |
||||||
|
val myChoices: List<Int>, val myCustom: String, val answers: List<PollResponse>) |
||||||
|
data class FeedbackState(val messageId: String, val pending: Boolean, val reactions: List<ReactionState>, val poll: PollState?) |
||||||
|
|
||||||
|
private fun JSONArray?.choices(): List<Int> = if (this == null) emptyList() else (0 until length()).map { getInt(it) } |
||||||
|
|
||||||
|
/** Формат и правила задаёт ядро; интерфейс разбирает готовый снимок. */ |
||||||
|
fun parseFeedback(json: JSONObject): FeedbackState { |
||||||
|
val id = json.getString("message_id") |
||||||
|
require(id.length == 64) { "Invalid message ID" } |
||||||
|
val reactions = json.getJSONArray("reactions").let { values -> |
||||||
|
(0 until values.length()).map { i -> values.getJSONObject(i).let { |
||||||
|
ReactionState(it.getInt("id"), it.getString("emoji"), it.getInt("count"), it.getBoolean("mine")) |
||||||
|
} } |
||||||
|
} |
||||||
|
val poll = json.optJSONObject("poll")?.let { value -> |
||||||
|
val options = value.getJSONArray("options").let { values -> |
||||||
|
(0 until values.length()).map { i -> values.getJSONObject(i).let { |
||||||
|
PollOption(it.getInt("id"), it.getString("text"), it.getInt("count"), it.getDouble("percent")) |
||||||
|
} } |
||||||
|
} |
||||||
|
val mine = value.getJSONObject("mine") |
||||||
|
val answers = value.getJSONArray("answers").let { values -> |
||||||
|
(0 until values.length()).map { i -> values.getJSONObject(i).let { row -> |
||||||
|
val answer = row.getJSONObject("answer") |
||||||
|
PollResponse(row.getString("node_id").removePrefix("0x").toLong(16), |
||||||
|
answer.optJSONArray("choices").choices(), answer.optString("custom")) |
||||||
|
} } |
||||||
|
} |
||||||
|
PollState(value.getString("question"), value.getString("mode") == "multiple", value.getBoolean("allow_custom_answer"), |
||||||
|
options, value.getInt("voters"), value.getLong("ver"), mine.optJSONArray("choices").choices(), mine.optString("custom"), answers) |
||||||
|
} |
||||||
|
return FeedbackState(id, json.optBoolean("pending"), reactions, poll) |
||||||
|
} |
||||||
Loading…
Reference in new issue