Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalDeviceMismatch.kt
SignalDeviceMismatch.kt57 lines · 2.4 KiBRaw
| 1 | package com.vayunmathur.communicate.data.signal |
| 2 | |
| 3 | import kotlinx.serialization.json.Json |
| 4 | import kotlinx.serialization.json.int |
| 5 | import kotlinx.serialization.json.jsonArray |
| 6 | import kotlinx.serialization.json.jsonObject |
| 7 | import kotlinx.serialization.json.jsonPrimitive |
| 8 | |
| 9 | /** |
| 10 | * The device-set disagreements a send can come back with. |
| 11 | * |
| 12 | * `409` carries `MismatchedDevices{missingDevices, extraDevices}` — we are missing sessions for some |
| 13 | * of the recipient's devices and holding sessions for devices that no longer exist. `410` carries |
| 14 | * `StaleDevices{staleDevices}` — our sessions for those devices are out of date. |
| 15 | */ |
| 16 | data class SignalDeviceMismatch( |
| 17 | /** Devices needing a fresh session built from a pre-key bundle. */ |
| 18 | val fetch: Set<Int>, |
| 19 | /** Devices whose session should be archived. */ |
| 20 | val archive: Set<Int>, |
| 21 | ) { |
| 22 | /** Factories and the 409-mismatch parser for [SignalDeviceMismatch]. */ |
| 23 | companion object { |
| 24 | private val json = Json { ignoreUnknownKeys = true } |
| 25 | private const val HTTP_MISMATCH = 409 |
| 26 | private const val HTTP_STALE = 410 |
| 27 | |
| 28 | /** Returns null when the body does not parse or names no devices at all. */ |
| 29 | fun parse(status: Int, body: String): SignalDeviceMismatch? { |
| 30 | val root = try { |
| 31 | json.parseToJsonElement(body).jsonObject |
| 32 | } catch (_: Exception) { |
| 33 | return null |
| 34 | } |
| 35 | val result = when (status) { |
| 36 | HTTP_MISMATCH -> SignalDeviceMismatch( |
| 37 | fetch = root.ints("missingDevices"), |
| 38 | archive = root.ints("extraDevices"), |
| 39 | ) |
| 40 | // Stale sessions are archived to keep the old chain readable, then rebuilt from fresh |
| 41 | // pre-keys. Archiving alone would leave the device unsendable until the server came |
| 42 | // back with a 409 naming it. |
| 43 | HTTP_STALE -> root.ints("staleDevices").let { stale -> |
| 44 | SignalDeviceMismatch(fetch = stale, archive = stale) |
| 45 | } |
| 46 | else -> return null |
| 47 | } |
| 48 | return if (result.fetch.isEmpty() && result.archive.isEmpty()) null else result |
| 49 | } |
| 50 | |
| 51 | private fun kotlinx.serialization.json.JsonObject.ints(key: String): Set<Int> = try { |
| 52 | this[key]?.jsonArray?.mapNotNull { it.jsonPrimitive.int }?.toSet() ?: emptySet() |
| 53 | } catch (_: Exception) { |
| 54 | emptySet() |
| 55 | } |
| 56 | } |
| 57 | } |