Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsUpExtras.kt

RcsUpExtras.kt132 lines · 5.8 KiBRaw
1package com.vayunmathur.communicate.data.rcs
2
3/**
4 * Universal Profile extras beyond 1:1 chat sessions.
5 *
6 * - Geolocation Push (RCC.07 Annex: `application/vnd.gsma.rcs.geopush+xml`,
7 * iari tag `...ims.iari.rcs.geosms` — already requested in
8 * [RcsSipTransport.CPM_FEATURE_TAGS]): RCC.07 §2.6 Geolocation Push format.
9 * - Large Message (pager-mode `cpm.largemsg`): CPIM split across multiple SIP
10 * MESSAGEs with `Message-ID` correlation; reassembly on receipt.
11 * - Message Revoke / Edit over pager-mode: `message/cpim` wrapping an IMDN
12 * `revoke` extension (UP 2.x) / replacement text with `Message-ID` match.
13 * - Delivery-report correlation: outgoing CPIM carries `imdn.Message-ID`;
14 * inbound IMDN `positive-delivery`/`display` map back to our cached
15 * message rows for status ticks.
16 *
17 * All bodies are plain strings over the existing pager-mode path — no new
18 * transport needed.
19 */
20
21/** Geolocation Push body (RCC.07 Geolocation Push schema, minimal subset). */
22fun buildGeopushBody(latitude: Double, longitude: Double, label: String? = null): String =
23 buildString {
24 append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
25 append("<rcsenvelope xmlns=\"urn:gsma:params:xml:ns:rcs:rcsenvelope\">\n")
26 append(" <rcspushlocation>\n")
27 append(" <latitude>$latitude</latitude>\n")
28 append(" <longitude>$longitude</longitude>\n")
29 if (!label.isNullOrBlank()) append(" <label>${label.xmlEscape()}</label>\n")
30 append(" <radius>0</radius>\n")
31 append(" </rcspushlocation>\n")
32 append("</rcsenvelope>")
33 }
34
35/** Parse a Geolocation Push body into (lat, lon, label?), or null. */
36fun parseGeopushBody(body: String): Triple<Double, Double, String?>? {
37 if (!body.contains("rcspushlocation", ignoreCase = true)) return null
38 val lat = Regex("<latitude>([^<]+)</latitude>", RegexOption.IGNORE_CASE).find(body)
39 ?.groupValues?.getOrNull(1)?.trim()?.toDoubleOrNull() ?: return null
40 val lon = Regex("<longitude>([^<]+)</longitude>", RegexOption.IGNORE_CASE).find(body)
41 ?.groupValues?.getOrNull(1)?.trim()?.toDoubleOrNull() ?: return null
42 val label = Regex("<label>([^<]*)</label>", RegexOption.IGNORE_CASE).find(body)
43 ?.groupValues?.getOrNull(1)?.trim()?.takeIf { it.isNotEmpty() }
44 return Triple(lat, lon, label)
45}
46
47private fun String.xmlEscape(): String = this
48 .replace("&", "&amp;")
49 .replace("<", "&lt;")
50 .replace(">", "&gt;")
51 .replace("\"", "&quot;")
52
53/** Maximum single pager-mode payload before Large Message chunking. */
54const val RCS_LARGE_MESSAGE_CHUNK = 8192
55
56/**
57 * Split [text] into Large Message chunks, each tagged with the shared
58 * `imdn.Message-ID` ([messageId]) + `part/total` envelope headers so the far
59 * end reassembles. Returns single-element list when under the limit.
60 */
61fun chunkLargeMessage(messageId: String, text: String): List<String> {
62 val bytes = text.toByteArray(Charsets.UTF_8)
63 if (bytes.size <= RCS_LARGE_MESSAGE_CHUNK) return listOf(text)
64 val parts = bytes.toList().chunked(RCS_LARGE_MESSAGE_CHUNK).map {
65 it.toByteArray().toString(Charsets.UTF_8)
66 }
67 return parts.mapIndexed { index, part ->
68 "Message-ID: $messageId\r\nPart: ${index + 1}/${parts.size}\r\n\r\n$part"
69 }
70}
71
72/**
73 * Reassemble Large Message chunks. [chunks] maps part number → text for one
74 * `Message-ID`; returns the joined text when all [total] parts are present.
75 */
76fun reassembleLargeMessage(chunks: Map<Int, String>, total: Int): String? {
77 if (chunks.size != total) return null
78 return (1..total).map { chunks[it] ?: return null }.joinToString("")
79}
80
81/** Parse a chunk envelope header into (messageId, part, total). */
82fun parseChunkHeader(body: String): Triple<String, Int, Int>? {
83 val id = Regex("Message-ID:\\s*(\\S+)", RegexOption.IGNORE_CASE).find(body)
84 ?.groupValues?.getOrNull(1)?.trim() ?: return null
85 val part = Regex("Part:\\s*(\\d+)/(\\d+)", RegexOption.IGNORE_CASE).find(body)
86 ?: return null
87 val (num, total) = part.destructured
88 return Triple(id, num.toIntOrNull() ?: return null, total.toIntOrNull() ?: return null)
89}
90
91/**
92 * Build a pager-mode revoke for [originalMessageId]: CPIM wrapping an IMDN
93 * revoke extension body. The far end blanks the message row.
94 */
95fun buildRevokeBody(originalMessageId: String): String = buildString {
96 append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
97 append("<imdn xmlns=\"urn:ietf:params:xml:ns:imdn\">\n")
98 append(" <message-id>$originalMessageId</message-id>\n")
99 append(" <datetime>${java.time.Instant.now()}</datetime>\n")
100 append(" <status><revoked xmlns=\"urn:gsma:params:xml:ns:rcs:revoke\"/></status>\n")
101 append("</imdn>")
102}
103
104/** True when [body] is a revoke report for some message; returns its id. */
105fun parseRevokeBody(body: String): String? {
106 if (!body.contains("revoked", ignoreCase = true)) return null
107 return Regex("<message-id>([^<]+)</message-id>").find(body)
108 ?.groupValues?.getOrNull(1)?.trim()
109}
110
111/**
112 * Build a pager-mode edit: replacement [newText] with the original
113 * `imdn.Message-ID` so the far end swaps the row body.
114 */
115fun buildEditBody(originalMessageId: String, newText: String): String = buildString {
116 append("imdn.Message-ID: $originalMessageId\r\n")
117 append("Edit-Type: replace\r\n")
118 append("\r\n")
119 append(newText)
120}
121
122/** Parse an edit body into (originalId, newText). */
123fun parseEditBody(body: String): Pair<String, String>? {
124 if (!body.contains("Edit-Type: replace", ignoreCase = true)) return null
125 val id = Regex("imdn\\.Message-ID:\\s*(\\S+)", RegexOption.IGNORE_CASE).find(body)
126 ?.groupValues?.getOrNull(1)?.trim() ?: return null
127 val text = body.substringAfter("\r\n\r\n", "").ifBlank {
128 body.substringAfter("\n\n", "")
129 }.trim()
130 if (text.isEmpty()) return null
131 return id to text
132}