Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / mex / MexModels.kt
MexModels.kt64 lines · 2.6 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp.mex |
| 2 | |
| 3 | import org.json.JSONObject |
| 4 | |
| 5 | /** |
| 6 | * A single GraphQL error entry from a MEX/WWW response `{"errors":[{message, code, …}]}`. |
| 7 | */ |
| 8 | data class MexError( |
| 9 | val message: String?, |
| 10 | val code: Int?, |
| 11 | ) |
| 12 | |
| 13 | /** |
| 14 | * Result of a MEX (`w:mex` XMPP IQ) or WWW GraphQL call. |
| 15 | * |
| 16 | * - [data]: the `data` object of the GraphQL envelope `{"data":…,"errors":…}` (null on failure). |
| 17 | * - [errors]: GraphQL-level errors returned by the server (may be non-empty even with partial data). |
| 18 | * - [transportError]: a client/transport-side failure that never reached the GraphQL layer, e.g. |
| 19 | * `no_persisted_id:<op>` (the operation's doc_id isn't in the bundled JSON), `timeout`, `iq_error`, |
| 20 | * or `http:<status>`. Null when the request completed at the GraphQL layer. |
| 21 | * |
| 22 | * [isSuccess] is true only when there was no transport error and no GraphQL errors. |
| 23 | */ |
| 24 | data class MexResult( |
| 25 | val data: JSONObject?, |
| 26 | val errors: List<MexError> = emptyList(), |
| 27 | val transportError: String? = null, |
| 28 | ) { |
| 29 | val isSuccess: Boolean get() = transportError == null && errors.isEmpty() |
| 30 | |
| 31 | /** Factories for [MexResult] (transport failures). */ |
| 32 | companion object { |
| 33 | /** Build a transport-level failure result (no GraphQL round-trip completed). */ |
| 34 | fun transport(reason: String): MexResult = MexResult(null, emptyList(), reason) |
| 35 | |
| 36 | /** |
| 37 | * Parse a GraphQL envelope string `{"data":…,"errors":[…]}` into a [MexResult]. |
| 38 | * Runtime-only (Android `org.json`); envelope *building* is done JVM-pure in [MexEnvelope]. |
| 39 | */ |
| 40 | fun fromEnvelope(envelopeJson: String): MexResult { |
| 41 | return try { |
| 42 | val root = JSONObject(envelopeJson) |
| 43 | val data = root.optJSONObject("data") |
| 44 | val errorsArr = root.optJSONArray("errors") |
| 45 | val errors = buildList { |
| 46 | if (errorsArr != null) { |
| 47 | for (i in 0 until errorsArr.length()) { |
| 48 | val e = errorsArr.optJSONObject(i) ?: continue |
| 49 | add( |
| 50 | MexError( |
| 51 | message = e.optString("message").ifEmpty { null }, |
| 52 | code = if (e.has("code") && !e.isNull("code")) e.optInt("code") else null, |
| 53 | ), |
| 54 | ) |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | MexResult(data = data, errors = errors, transportError = null) |
| 59 | } catch (expected: Throwable) { |
| 60 | transport("parse_error:${expected.message}") |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | } |