@poolse/native 3.4.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +69 -7
- package/android/build.gradle +3 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +1 -1
- package/android/src/main/java/dev/poolse/callcore/android/MessageActionWorker.kt +215 -0
- package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +123 -59
- package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +10 -1
- package/dist/index.cjs +24 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +48 -1
- package/dist/index.d.ts +48 -1
- package/dist/index.js +22 -1
- package/dist/index.js.map +1 -1
- package/ios/Module/PoolseCallsModule.swift +14 -1
- package/ios/Platform/CallCore.swift +7 -0
- package/ios/Platform/MessageNotifications.swift +276 -53
- package/package.json +1 -1
- package/plugin/index.js +7 -0
- package/plugin/withMessageReplyUnlock.js +33 -0
- package/src/index.ts +77 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
Formerly `@poolse/react-native-calls` (0.x).
|
|
4
4
|
|
|
5
|
+
## 3.5.0 — 2026-11-21
|
|
6
|
+
|
|
7
|
+
- Reply and Mark as read from a chat notification now use
|
|
8
|
+
`POST /v1/notification-actions/{reply,read}` (grant as bearer and `token`,
|
|
9
|
+
reply text as `text`) instead of the first `/v1/notifications/*` paths.
|
|
10
|
+
- iOS: a reply is retried with the same id on a network error, 5xx or 429
|
|
11
|
+
while iOS keeps the app alive; success clears the conversation's
|
|
12
|
+
notifications and lowers the badge; a failed reply posts a "Couldn't send
|
|
13
|
+
your reply" notification with Reply on it. The background task now starts
|
|
14
|
+
before expo-notifications completes the response.
|
|
15
|
+
- Android: Reply shows your line at once ("Sending…") and is sent by
|
|
16
|
+
WorkManager (new dependency `androidx.work:work-runtime-ktx`), which waits
|
|
17
|
+
for a network, survives the process being killed and retries with the
|
|
18
|
+
same id; a failed reply reads "Not sent: …" with the reason and alerts.
|
|
19
|
+
The read-sync push still clears the conversation.
|
|
20
|
+
- New `onNotificationAction(cb)`, `onNotificationReply(cb)` and
|
|
21
|
+
`takeNotificationActions()` with `NotificationActionResult`: what a Reply
|
|
22
|
+
or Mark as read from a notification did, live or queued while the app
|
|
23
|
+
was closed.
|
|
24
|
+
- Config plugin: `messageReplyRequiresUnlock` (default `false`) makes Reply
|
|
25
|
+
ask for the passcode / biometrics first on both platforms.
|
|
26
|
+
|
|
5
27
|
## 3.4.0 — 2026-11-21
|
|
6
28
|
|
|
7
29
|
- No changes; released with the other `@poolse/*` packages at 3.4.0.
|
package/README.md
CHANGED
|
@@ -37,12 +37,13 @@ In `app.json`, after `expo-notifications`:
|
|
|
37
37
|
]
|
|
38
38
|
```
|
|
39
39
|
|
|
40
|
-
| Option
|
|
41
|
-
|
|
|
42
|
-
| `ringback`
|
|
43
|
-
| `pictureInPicture`
|
|
44
|
-
| `lockscreen`
|
|
45
|
-
| `
|
|
40
|
+
| Option | Default | What it does |
|
|
41
|
+
| ---------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
42
|
+
| `ringback` | none | Ships this sound in both apps; pass its base name to `configure({ ringback })`. Lowercase letters, digits and underscores only. |
|
|
43
|
+
| `pictureInPicture` | `true` | Android: the activity may float as a picture-in-picture window. |
|
|
44
|
+
| `lockscreen` | `true` | Android: the app shows over the lock screen when opened for a call. |
|
|
45
|
+
| `messageReplyRequiresUnlock` | `false` | Both: a chat notification's Reply asks for the passcode / Face ID / fingerprint before it sends. Off, Reply works straight from the lock screen (as in WhatsApp). Mark as read never asks. |
|
|
46
|
+
| `screenShare` | `false` | iOS: adds the broadcast upload extension that sharing the screen needs, and the app group `group.<bundle id>` it shares with the app (`{ "appGroup": "…" }` for your own). Register that group in the Apple Developer portal and assign it to the app's and `<bundle id>.broadcast`'s App IDs. |
|
|
46
47
|
|
|
47
48
|
Always applied on Android: the LiveKit media adapter, and `expo-notifications`
|
|
48
49
|
as the receiver for pushes that aren't calls. On iOS, add `UIBackgroundModes`
|
|
@@ -101,7 +102,8 @@ The full API:
|
|
|
101
102
|
`poolse.devices.register({ token, platform: 'ios', kind: 'voip', environment })`
|
|
102
103
|
from `@poolse/sdk`, and the regular APNs token with `kind: 'alert'`.
|
|
103
104
|
- Chat notifications: `setActiveConversation`, `shouldPresentMessage`,
|
|
104
|
-
`conversationOfNotification
|
|
105
|
+
`conversationOfNotification`, `onNotificationAction`,
|
|
106
|
+
`onNotificationReply`, `takeNotificationActions` (see below).
|
|
105
107
|
- Socket forwarding (optional): `onCallFinished`, `onRingEnded`. Feed them
|
|
106
108
|
from `@poolse/sdk` 3.1's user channel:
|
|
107
109
|
|
|
@@ -111,6 +113,66 @@ The full API:
|
|
|
111
113
|
userChannel.onCallFinished((e) => calls.onCallFinished(e.call_id, e.reason));
|
|
112
114
|
```
|
|
113
115
|
|
|
116
|
+
## Reply and Mark as read from a notification
|
|
117
|
+
|
|
118
|
+
poolse's chat pushes carry a reply grant (24 h, bound to the device and
|
|
119
|
+
conversation) and `actions: "reply,mark_read"`. The native core turns them
|
|
120
|
+
into a Reply button with a text field and a Mark as read button, and sends
|
|
121
|
+
them itself — from the lock screen, with the app closed, with no session
|
|
122
|
+
and no JS — to `POST /v1/notification-actions/reply` and `/read` on the API
|
|
123
|
+
origin you passed to `configure` (persisted, so call it once on every app
|
|
124
|
+
start as usual).
|
|
125
|
+
|
|
126
|
+
- **iOS**: the core registers the `poolse_message` category (actions `reply`
|
|
127
|
+
and `mark_read`) beside the app's own categories at launch, and handles the
|
|
128
|
+
taps through expo-notifications' delegate. A tap launches the app in the
|
|
129
|
+
background; a background task keeps it alive for the request, retried
|
|
130
|
+
(same reply id) on a network error, 5xx or 429 while iOS allows. On
|
|
131
|
+
success the conversation's notifications go and the badge drops by them
|
|
132
|
+
(the server's read-sync push then sets the exact count). A failed reply
|
|
133
|
+
posts a "Couldn't send your reply" notification in the same thread, with
|
|
134
|
+
Reply on it to try again. No Notification Service Extension is needed:
|
|
135
|
+
the grant rides in the delivered notification itself.
|
|
136
|
+
- **Android**: one MessagingStyle notification per conversation. Reply shows
|
|
137
|
+
your line at once ("Sending…"), then WorkManager sends it — waiting for a
|
|
138
|
+
network, surviving the process being killed, retrying with the same id —
|
|
139
|
+
and the line stays (sent) or turns "Not sent: …" with the reason and an
|
|
140
|
+
alert. Mark as read cancels the notification at once. Launcher badges follow
|
|
141
|
+
the notifications' counts.
|
|
142
|
+
|
|
143
|
+
Your app learns what happened:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
import * as calls from '@poolse/native';
|
|
147
|
+
|
|
148
|
+
useEffect(() => {
|
|
149
|
+
// Finished while the app was closed: oldest first, each once.
|
|
150
|
+
for (const r of calls.takeNotificationActions()) apply(r);
|
|
151
|
+
return calls.onNotificationAction(apply);
|
|
152
|
+
}, []);
|
|
153
|
+
|
|
154
|
+
function apply(r: calls.NotificationActionResult) {
|
|
155
|
+
if (r.action === 'reply' && r.ok) refreshConversation(r.conversationId); // r.messageId
|
|
156
|
+
if (r.action === 'mark_read' && r.ok) markReadLocally(r.conversationId);
|
|
157
|
+
// !r.ok: r.error is the server code (device_signed_out, forbidden,
|
|
158
|
+
// rate_limited, …) or network / no_grant / not_configured.
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
`onNotificationReply(cb)` is the same, replies only. Results that finish
|
|
163
|
+
with no `onNotificationAction` listener are queued (the last 50) for
|
|
164
|
+
`takeNotificationActions`.
|
|
165
|
+
|
|
166
|
+
Requirements: `configure` has run at least once on the device; the regular
|
|
167
|
+
APNs token is registered with `kind: 'alert'` (iOS) and the FCM token
|
|
168
|
+
(Android); `remote-notification` in `UIBackgroundModes` for the iOS
|
|
169
|
+
read-sync push. If your app calls expo-notifications'
|
|
170
|
+
`setNotificationCategoryAsync`, that keeps `poolse_message`; don't replace
|
|
171
|
+
the whole category set natively without it.
|
|
172
|
+
expo-notifications also hands these responses to its own JS listeners: in
|
|
173
|
+
`addNotificationResponseReceivedListener`, ignore an `actionIdentifier` of
|
|
174
|
+
`reply` or `mark_read` (only the default tap should open the chat).
|
|
175
|
+
|
|
114
176
|
## Links
|
|
115
177
|
|
|
116
178
|
- Docs: <https://poolse.dev/docs/sdk/native>
|
package/android/build.gradle
CHANGED
|
@@ -46,6 +46,9 @@ dependencies {
|
|
|
46
46
|
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
|
|
47
47
|
implementation 'com.google.firebase:firebase-messaging:24.0.3'
|
|
48
48
|
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1'
|
|
49
|
+
// Notification Reply / Mark as read: sent with retries that survive
|
|
50
|
+
// the process being killed and wait for a network.
|
|
51
|
+
implementation 'androidx.work:work-runtime-ktx:2.9.1'
|
|
49
52
|
|
|
50
53
|
if (useLiveKit) {
|
|
51
54
|
implementation 'io.livekit:livekit-android:2.11.0'
|
|
@@ -42,7 +42,7 @@ class CallMessagingService : FirebaseMessagingService() {
|
|
|
42
42
|
val conversationId = data["conversation_id"] ?: return
|
|
43
43
|
when (data["event"]) {
|
|
44
44
|
"new" -> MessageNotifications.onNew(this, data, CallCore.smallIcon(this))
|
|
45
|
-
"read" -> MessageNotifications.
|
|
45
|
+
"read" -> MessageNotifications.onRead(this, data)
|
|
46
46
|
}
|
|
47
47
|
return
|
|
48
48
|
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
package dev.poolse.callcore.android
|
|
2
|
+
|
|
3
|
+
import android.content.BroadcastReceiver
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.content.Intent
|
|
6
|
+
import android.util.Log
|
|
7
|
+
import androidx.core.app.NotificationCompat
|
|
8
|
+
import androidx.core.app.RemoteInput
|
|
9
|
+
import androidx.work.BackoffPolicy
|
|
10
|
+
import androidx.work.Constraints
|
|
11
|
+
import androidx.work.CoroutineWorker
|
|
12
|
+
import androidx.work.Data
|
|
13
|
+
import androidx.work.ExistingWorkPolicy
|
|
14
|
+
import androidx.work.ForegroundInfo
|
|
15
|
+
import androidx.work.NetworkType
|
|
16
|
+
import androidx.work.OneTimeWorkRequestBuilder
|
|
17
|
+
import androidx.work.OutOfQuotaPolicy
|
|
18
|
+
import androidx.work.WorkManager
|
|
19
|
+
import androidx.work.WorkerParameters
|
|
20
|
+
import kotlinx.coroutines.Dispatchers
|
|
21
|
+
import kotlinx.coroutines.withContext
|
|
22
|
+
import okhttp3.MediaType.Companion.toMediaType
|
|
23
|
+
import okhttp3.OkHttpClient
|
|
24
|
+
import okhttp3.Request
|
|
25
|
+
import okhttp3.RequestBody.Companion.toRequestBody
|
|
26
|
+
import org.json.JSONObject
|
|
27
|
+
import java.util.UUID
|
|
28
|
+
import java.util.concurrent.TimeUnit
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Reply / Mark as read, tapped on a message notification (CALL_CONTRACT.md
|
|
32
|
+
* §5.5). The receiver only does what must be instant — show the reply
|
|
33
|
+
* line (Android spins the reply field until the notification changes),
|
|
34
|
+
* or drop the notification for Mark as read — and hands the request to
|
|
35
|
+
* [MessageActionWorker].
|
|
36
|
+
*/
|
|
37
|
+
class MessageActionReceiver : BroadcastReceiver() {
|
|
38
|
+
override fun onReceive(context: Context, intent: Intent) {
|
|
39
|
+
val conversationId = intent.getStringExtra(MessageNotifications.EXTRA_CONVERSATION) ?: return
|
|
40
|
+
val app = context.applicationContext
|
|
41
|
+
|
|
42
|
+
when (intent.action) {
|
|
43
|
+
MessageNotifications.ACTION_REPLY -> {
|
|
44
|
+
val text = RemoteInput.getResultsFromIntent(intent)
|
|
45
|
+
?.getCharSequence(MessageNotifications.KEY_REPLY)?.toString()?.trim().orEmpty()
|
|
46
|
+
if (text.isEmpty()) {
|
|
47
|
+
// Nothing typed; still repost so the field stops spinning.
|
|
48
|
+
MessageNotifications.refresh(app, conversationId)
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
// One id per reply, reused by every retry of it: the server
|
|
52
|
+
// answers a repeat with the original message, never a second one.
|
|
53
|
+
val clientId = UUID.randomUUID().toString()
|
|
54
|
+
MessageNotifications.onReplying(app, conversationId, clientId, text)
|
|
55
|
+
MessageActionWorker.enqueue(app, MessageActionWorker.REPLY, conversationId, text, clientId)
|
|
56
|
+
}
|
|
57
|
+
MessageNotifications.ACTION_READ -> {
|
|
58
|
+
// Optimistic: the notification goes now; the server catches up.
|
|
59
|
+
MessageNotifications.clear(app, conversationId)
|
|
60
|
+
MessageActionWorker.enqueue(app, MessageActionWorker.READ, conversationId, null, null)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The HTTP side of a notification action: `POST /v1/notification-actions/
|
|
68
|
+
* {reply,read}` with the conversation's reply grant (bearer and `token`),
|
|
69
|
+
* against the API origin `configure` persisted — no app, no session, no JS.
|
|
70
|
+
*
|
|
71
|
+
* WorkManager, expedited: it runs at once when there is a network, waits
|
|
72
|
+
* for one when there is not, survives the process being killed, and
|
|
73
|
+
* retries a network error / 5xx / 429 with backoff — always with the
|
|
74
|
+
* reply's same `id`, so a retry after a lost response cannot post twice.
|
|
75
|
+
* Gives up after [MAX_ATTEMPTS] or the grant's lifetime.
|
|
76
|
+
*/
|
|
77
|
+
class MessageActionWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
|
|
78
|
+
|
|
79
|
+
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
|
|
80
|
+
val app = applicationContext
|
|
81
|
+
val action = inputData.getString(KEY_ACTION) ?: return@withContext Result.failure()
|
|
82
|
+
val conversationId = inputData.getString(KEY_CONVERSATION) ?: return@withContext Result.failure()
|
|
83
|
+
val text = inputData.getString(KEY_TEXT).orEmpty()
|
|
84
|
+
val clientId = inputData.getString(KEY_CLIENT_ID).orEmpty()
|
|
85
|
+
// The newest grant this conversation got, else the one at tap time.
|
|
86
|
+
val grant = MessageNotifications.grantFor(app, conversationId) ?: inputData.getString(KEY_GRANT)
|
|
87
|
+
val base = CallCore.apiBaseUrl(app)
|
|
88
|
+
|
|
89
|
+
val outcome = when {
|
|
90
|
+
base == null -> Outcome(0, "not_configured", null)
|
|
91
|
+
grant == null -> Outcome(0, "no_grant", null)
|
|
92
|
+
action == REPLY -> post("$base/v1/notification-actions/reply", grant, JSONObject().put("text", text).put("id", clientId))
|
|
93
|
+
else -> post("$base/v1/notification-actions/read", grant, JSONObject())
|
|
94
|
+
}
|
|
95
|
+
val ok = outcome.status in 200..299
|
|
96
|
+
val retryable = !ok && base != null && grant != null &&
|
|
97
|
+
(outcome.status == 0 || outcome.status == 429 || outcome.status >= 500)
|
|
98
|
+
val expired = System.currentTimeMillis() - inputData.getLong(KEY_AT, 0L) > GIVE_UP_MS
|
|
99
|
+
// The line keeps reading "Sending…" meanwhile.
|
|
100
|
+
if (retryable && runAttemptCount + 1 < MAX_ATTEMPTS && !expired) return@withContext Result.retry()
|
|
101
|
+
|
|
102
|
+
val event = mutableMapOf<String, Any?>(
|
|
103
|
+
"action" to if (action == REPLY) "reply" else "mark_read",
|
|
104
|
+
"conversationId" to conversationId,
|
|
105
|
+
"ok" to ok,
|
|
106
|
+
)
|
|
107
|
+
if (!ok) {
|
|
108
|
+
event["error"] = outcome.code ?: if (outcome.status == 0) "network" else "http_${outcome.status}"
|
|
109
|
+
if (outcome.status != 0) event["status"] = outcome.status
|
|
110
|
+
}
|
|
111
|
+
if (action == REPLY) {
|
|
112
|
+
event["text"] = text
|
|
113
|
+
event["clientId"] = clientId
|
|
114
|
+
if (ok) event["messageId"] = outcome.json?.optString("id")?.ifBlank { null } ?: clientId
|
|
115
|
+
MessageNotifications.onReplied(app, conversationId, clientId, text, ok, if (ok) null else reason(outcome), grant)
|
|
116
|
+
} else if (!ok) {
|
|
117
|
+
// A failed read is only logged: the message stays unread, nothing is lost.
|
|
118
|
+
Log.w(TAG, "mark read failed status=${outcome.status} code=${outcome.code}")
|
|
119
|
+
}
|
|
120
|
+
MessageNotifications.report(app, event)
|
|
121
|
+
if (ok) Result.success() else Result.failure()
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Expedited work runs as a foreground service before Android 12: it needs a notification. */
|
|
125
|
+
override suspend fun getForegroundInfo(): ForegroundInfo {
|
|
126
|
+
val sending = inputData.getString(KEY_ACTION) == REPLY
|
|
127
|
+
val notification = NotificationCompat.Builder(applicationContext, MessageNotifications.CHANNEL_ID)
|
|
128
|
+
.setSmallIcon(CallCore.smallIcon(applicationContext))
|
|
129
|
+
.setContentTitle(if (sending) "Sending reply…" else "Marking as read…")
|
|
130
|
+
.setPriority(NotificationCompat.PRIORITY_LOW)
|
|
131
|
+
.setSilent(true)
|
|
132
|
+
.setOngoing(true)
|
|
133
|
+
.build()
|
|
134
|
+
return ForegroundInfo(FOREGROUND_ID, notification)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private class Outcome(val status: Int, val code: String?, val json: JSONObject?)
|
|
138
|
+
|
|
139
|
+
private fun post(url: String, grant: String, body: JSONObject): Outcome = runCatching {
|
|
140
|
+
val request = Request.Builder()
|
|
141
|
+
.url(url)
|
|
142
|
+
.header("Authorization", "Bearer $grant")
|
|
143
|
+
.header("Accept", "application/json")
|
|
144
|
+
.post(body.put("token", grant).toString().toRequestBody("application/json".toMediaType()))
|
|
145
|
+
.build()
|
|
146
|
+
client.newCall(request).execute().use { res ->
|
|
147
|
+
val json = runCatching { JSONObject(res.body?.string().orEmpty()) }.getOrNull()
|
|
148
|
+
val code = json?.optJSONObject("error")?.optString("code")?.ifBlank { null }
|
|
149
|
+
if (!res.isSuccessful) Log.w(TAG, "notification action ${res.code} ${code ?: ""}")
|
|
150
|
+
Outcome(res.code, code, json)
|
|
151
|
+
}
|
|
152
|
+
}.getOrElse {
|
|
153
|
+
Log.w(TAG, "notification action failed", it)
|
|
154
|
+
Outcome(0, null, null)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
private fun reason(o: Outcome): String = when {
|
|
158
|
+
o.code == "not_configured" || o.code == "no_grant" -> "Open the app to reply"
|
|
159
|
+
o.status == 0 -> "No connection"
|
|
160
|
+
o.status == 401 && o.code == "device_signed_out" -> "Signed out — open the app"
|
|
161
|
+
o.status == 401 && o.code == "user_blocked" -> "Your account is blocked"
|
|
162
|
+
o.status == 401 -> "Expired — open the app to reply"
|
|
163
|
+
o.status == 402 -> "Your workspace is full this month"
|
|
164
|
+
o.status == 403 -> "You're no longer in this chat"
|
|
165
|
+
o.status == 404 -> "This chat is gone"
|
|
166
|
+
o.status == 429 -> "Too many replies — try again soon"
|
|
167
|
+
else -> "Couldn't send"
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
companion object {
|
|
171
|
+
internal const val REPLY = "reply"
|
|
172
|
+
internal const val READ = "read"
|
|
173
|
+
private const val KEY_ACTION = "action"
|
|
174
|
+
private const val KEY_CONVERSATION = "conversation_id"
|
|
175
|
+
private const val KEY_TEXT = "text"
|
|
176
|
+
private const val KEY_CLIENT_ID = "client_id"
|
|
177
|
+
private const val KEY_GRANT = "grant"
|
|
178
|
+
private const val KEY_AT = "at"
|
|
179
|
+
private const val MAX_ATTEMPTS = 6
|
|
180
|
+
// The grant lives 24 h; well before that a stale reply is worse than none.
|
|
181
|
+
private const val GIVE_UP_MS = 30 * 60 * 1000L
|
|
182
|
+
private const val FOREGROUND_ID = 0x504F4F52
|
|
183
|
+
private const val TAG = "PoolseMessages"
|
|
184
|
+
|
|
185
|
+
private val client: OkHttpClient by lazy {
|
|
186
|
+
OkHttpClient.Builder()
|
|
187
|
+
.connectTimeout(10, TimeUnit.SECONDS)
|
|
188
|
+
.readTimeout(15, TimeUnit.SECONDS)
|
|
189
|
+
.callTimeout(20, TimeUnit.SECONDS)
|
|
190
|
+
.build()
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
internal fun enqueue(context: Context, action: String, conversationId: String, text: String?, clientId: String?) {
|
|
194
|
+
val data = Data.Builder()
|
|
195
|
+
.putString(KEY_ACTION, action)
|
|
196
|
+
.putString(KEY_CONVERSATION, conversationId)
|
|
197
|
+
.putString(KEY_TEXT, text)
|
|
198
|
+
.putString(KEY_CLIENT_ID, clientId)
|
|
199
|
+
.putString(KEY_GRANT, MessageNotifications.grantFor(context, conversationId))
|
|
200
|
+
.putLong(KEY_AT, System.currentTimeMillis())
|
|
201
|
+
.build()
|
|
202
|
+
val request = OneTimeWorkRequestBuilder<MessageActionWorker>()
|
|
203
|
+
.setInputData(data)
|
|
204
|
+
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
|
|
205
|
+
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
|
|
206
|
+
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)
|
|
207
|
+
.addTag("poolse-notification-action")
|
|
208
|
+
.build()
|
|
209
|
+
val name = "poolse-$action-" + (clientId ?: conversationId)
|
|
210
|
+
runCatching {
|
|
211
|
+
WorkManager.getInstance(context).enqueueUniqueWork(name, ExistingWorkPolicy.KEEP, request)
|
|
212
|
+
}.onFailure { Log.e(TAG, "could not queue the notification action", it) }
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
@@ -3,7 +3,6 @@ package dev.poolse.callcore.android
|
|
|
3
3
|
import android.app.NotificationChannel
|
|
4
4
|
import android.app.NotificationManager
|
|
5
5
|
import android.app.PendingIntent
|
|
6
|
-
import android.content.BroadcastReceiver
|
|
7
6
|
import android.content.Context
|
|
8
7
|
import android.content.Intent
|
|
9
8
|
import android.os.Build
|
|
@@ -12,12 +11,8 @@ import androidx.core.app.NotificationCompat
|
|
|
12
11
|
import androidx.core.app.NotificationManagerCompat
|
|
13
12
|
import androidx.core.app.Person
|
|
14
13
|
import androidx.core.app.RemoteInput
|
|
15
|
-
import okhttp3.MediaType.Companion.toMediaType
|
|
16
|
-
import okhttp3.Request
|
|
17
|
-
import okhttp3.RequestBody.Companion.toRequestBody
|
|
18
14
|
import org.json.JSONArray
|
|
19
15
|
import org.json.JSONObject
|
|
20
|
-
import java.util.UUID
|
|
21
16
|
|
|
22
17
|
/**
|
|
23
18
|
* Chat notifications on Android (CALL_CONTRACT.md §5.5), WhatsApp-style.
|
|
@@ -28,6 +23,10 @@ import java.util.UUID
|
|
|
28
23
|
* read run natively, authorized by the reply grant the push carried, so
|
|
29
24
|
* they work with the app killed and the phone locked.
|
|
30
25
|
*
|
|
26
|
+
* The HTTP side ([MessageActionWorker]) runs in WorkManager, so a reply
|
|
27
|
+
* typed with no signal, or into a process Android kills a second later,
|
|
28
|
+
* still goes out — with the same idempotency id on every retry.
|
|
29
|
+
*
|
|
31
30
|
* Android cannot read back the lines of a posted notification, so the
|
|
32
31
|
* last few lines per conversation are kept in a small preferences file
|
|
33
32
|
* and the notification is rebuilt from them on every message. They are
|
|
@@ -44,6 +43,9 @@ object MessageNotifications {
|
|
|
44
43
|
internal const val ACTION_READ = "dev.poolse.callcore.message.READ"
|
|
45
44
|
internal const val EXTRA_CONVERSATION = "poolse_message_conversation"
|
|
46
45
|
private const val TAG = "PoolseMessages"
|
|
46
|
+
private const val ACTIONS_PREFS = "dev.poolse.messages.actions"
|
|
47
|
+
private const val MAX_PENDING_ACTIONS = 50
|
|
48
|
+
private const val META_REPLY_UNLOCK = "dev.poolse.messages.reply_requires_unlock"
|
|
47
49
|
|
|
48
50
|
// A message notification that waited this long for the phone to come
|
|
49
51
|
// online is history.
|
|
@@ -55,6 +57,15 @@ object MessageNotifications {
|
|
|
55
57
|
*/
|
|
56
58
|
@Volatile var activeConversationId: String? = null
|
|
57
59
|
|
|
60
|
+
/** The bridge's subscriber for finished Reply / Mark as read actions. */
|
|
61
|
+
@Volatile var actionListener: ((Map<String, Any?>) -> Unit)? = null
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* True while JS has an `onNotificationAction` subscriber; until then
|
|
65
|
+
* results queue, even with the bridge observing other events.
|
|
66
|
+
*/
|
|
67
|
+
@Volatile var actionsObserved = false
|
|
68
|
+
|
|
58
69
|
/** A `type: "message", event: "new"` push. */
|
|
59
70
|
fun onNew(context: Context, data: Map<String, String>, smallIcon: Int) {
|
|
60
71
|
val conversationId = data["conversation_id"] ?: return
|
|
@@ -83,6 +94,17 @@ object MessageNotifications {
|
|
|
83
94
|
post(context, state, smallIcon, alert = true)
|
|
84
95
|
}
|
|
85
96
|
|
|
97
|
+
/**
|
|
98
|
+
* A `type: "message", event: "read"` push: read on some device (maybe
|
|
99
|
+
* this one, after a Reply or Mark as read). Launcher badges follow the
|
|
100
|
+
* notifications' numbers, so dropping the conversation's is the badge
|
|
101
|
+
* update; `unread_total` has no Android API to go to.
|
|
102
|
+
*/
|
|
103
|
+
fun onRead(context: Context, data: Map<String, String>) {
|
|
104
|
+
val conversationId = data["conversation_id"] ?: return
|
|
105
|
+
clear(context, conversationId)
|
|
106
|
+
}
|
|
107
|
+
|
|
86
108
|
/** The conversation was read (here, or on another device): clear it. */
|
|
87
109
|
fun clear(context: Context, conversationId: String) {
|
|
88
110
|
prefs(context).edit().remove(key(conversationId)).apply()
|
|
@@ -90,22 +112,98 @@ object MessageNotifications {
|
|
|
90
112
|
refreshSummary(context, CallCore.smallIcon(context))
|
|
91
113
|
}
|
|
92
114
|
|
|
93
|
-
/**
|
|
94
|
-
internal fun
|
|
115
|
+
/** Repost a conversation's notification as it is, silently. */
|
|
116
|
+
internal fun refresh(context: Context, conversationId: String) {
|
|
95
117
|
val state = load(context, conversationId) ?: return
|
|
118
|
+
post(context, state, CallCore.smallIcon(context), alert = false)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Reply tapped: show the user's line at once ("Sending…") — Android
|
|
123
|
+
* keeps the reply field spinning until the notification is updated.
|
|
124
|
+
*/
|
|
125
|
+
internal fun onReplying(context: Context, conversationId: String, clientId: String, text: String) {
|
|
126
|
+
val state = load(context, conversationId) ?: Conversation(conversationId)
|
|
127
|
+
state.lines.removeAll { it.self && it.id == clientId }
|
|
96
128
|
state.lines += Line(
|
|
97
|
-
id =
|
|
129
|
+
id = clientId,
|
|
98
130
|
sender = "You",
|
|
99
131
|
senderKey = null,
|
|
100
|
-
text =
|
|
132
|
+
text = text,
|
|
101
133
|
at = System.currentTimeMillis(),
|
|
102
134
|
self = true,
|
|
135
|
+
status = STATUS_SENDING,
|
|
103
136
|
)
|
|
104
137
|
while (state.lines.size > MAX_LINES) state.lines.removeAt(0)
|
|
105
138
|
save(context, state)
|
|
106
139
|
post(context, state, CallCore.smallIcon(context), alert = false)
|
|
107
140
|
}
|
|
108
141
|
|
|
142
|
+
/**
|
|
143
|
+
* The reply's outcome. Sent: the line stays (the server's read-sync
|
|
144
|
+
* push then clears the conversation — replying is reading). Failed:
|
|
145
|
+
* the line reads "Not sent", with why underneath, and the
|
|
146
|
+
* notification alerts again; Reply stays on it to try again.
|
|
147
|
+
*/
|
|
148
|
+
internal fun onReplied(context: Context, conversationId: String, clientId: String, text: String, ok: Boolean, reason: String?, grant: String?) {
|
|
149
|
+
val state = load(context, conversationId) ?: if (ok) return else Conversation(conversationId, grant = grant)
|
|
150
|
+
val index = state.lines.indexOfFirst { it.self && it.id == clientId }
|
|
151
|
+
val line = Line(
|
|
152
|
+
id = clientId,
|
|
153
|
+
sender = "You",
|
|
154
|
+
senderKey = null,
|
|
155
|
+
text = text,
|
|
156
|
+
at = if (index >= 0) state.lines[index].at else System.currentTimeMillis(),
|
|
157
|
+
self = true,
|
|
158
|
+
status = if (ok) STATUS_SENT else STATUS_FAILED,
|
|
159
|
+
)
|
|
160
|
+
if (index >= 0) state.lines[index] = line else state.lines += line
|
|
161
|
+
while (state.lines.size > MAX_LINES) state.lines.removeAt(0)
|
|
162
|
+
state.failure = if (ok) null else reason
|
|
163
|
+
save(context, state)
|
|
164
|
+
post(context, state, CallCore.smallIcon(context), alert = !ok)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
internal const val STATUS_SENDING = "sending"
|
|
168
|
+
internal const val STATUS_SENT = "sent"
|
|
169
|
+
internal const val STATUS_FAILED = "failed"
|
|
170
|
+
|
|
171
|
+
// ── JS events ───────────────────────────────────────────────────────
|
|
172
|
+
|
|
173
|
+
/** A finished action, to JS: live when the bridge listens, else queued on disk. */
|
|
174
|
+
internal fun report(context: Context, event: Map<String, Any?>) {
|
|
175
|
+
val full = event + ("at" to System.currentTimeMillis())
|
|
176
|
+
val listener = actionListener.takeIf { actionsObserved }
|
|
177
|
+
if (listener != null && runCatching { listener(full) }.isSuccess) return
|
|
178
|
+
val p = context.applicationContext.getSharedPreferences(ACTIONS_PREFS, Context.MODE_PRIVATE)
|
|
179
|
+
synchronized(this) {
|
|
180
|
+
val queue = runCatching { JSONArray(p.getString("queue", "[]")) }.getOrDefault(JSONArray())
|
|
181
|
+
queue.put(JSONObject(full.filterValues { it != null }))
|
|
182
|
+
val trimmed = JSONArray()
|
|
183
|
+
for (i in maxOf(0, queue.length() - MAX_PENDING_ACTIONS) until queue.length()) trimmed.put(queue.get(i))
|
|
184
|
+
p.edit().putString("queue", trimmed.toString()).apply()
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** The queued actions, oldest first, removed. */
|
|
189
|
+
fun takePendingActions(context: Context): List<Map<String, Any?>> {
|
|
190
|
+
val p = context.applicationContext.getSharedPreferences(ACTIONS_PREFS, Context.MODE_PRIVATE)
|
|
191
|
+
val raw = synchronized(this) {
|
|
192
|
+
p.getString("queue", null).also { p.edit().remove("queue").apply() }
|
|
193
|
+
} ?: return emptyList()
|
|
194
|
+
val queue = runCatching { JSONArray(raw) }.getOrNull() ?: return emptyList()
|
|
195
|
+
return List(queue.length()) { i ->
|
|
196
|
+
val o = queue.getJSONObject(i)
|
|
197
|
+
o.keys().asSequence().associateWith { k -> o.get(k).takeUnless { it == JSONObject.NULL } }
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private fun replyRequiresUnlock(context: Context): Boolean = runCatching {
|
|
202
|
+
context.packageManager
|
|
203
|
+
.getApplicationInfo(context.packageName, android.content.pm.PackageManager.GET_META_DATA)
|
|
204
|
+
.metaData?.getBoolean(META_REPLY_UNLOCK, false) ?: false
|
|
205
|
+
}.getOrDefault(false)
|
|
206
|
+
|
|
109
207
|
internal fun grantFor(context: Context, conversationId: String): String? =
|
|
110
208
|
load(context, conversationId)?.grant
|
|
111
209
|
|
|
@@ -119,7 +217,8 @@ object MessageNotifications {
|
|
|
119
217
|
if (state.group) style.conversationTitle = state.title
|
|
120
218
|
for (line in state.lines) {
|
|
121
219
|
val person = if (line.self) null else Person.Builder().setName(line.sender).setKey(line.senderKey).build()
|
|
122
|
-
|
|
220
|
+
val text = if (line.self && line.status == STATUS_FAILED) "Not sent: ${line.text}" else line.text
|
|
221
|
+
style.addMessage(NotificationCompat.MessagingStyle.Message(text, line.at, person))
|
|
123
222
|
}
|
|
124
223
|
|
|
125
224
|
val id = notificationId(state.id)
|
|
@@ -142,6 +241,10 @@ object MessageNotifications {
|
|
|
142
241
|
} else {
|
|
143
242
|
builder.setStyle(style)
|
|
144
243
|
}
|
|
244
|
+
when {
|
|
245
|
+
state.failure != null -> builder.setSubText(state.failure)
|
|
246
|
+
state.lines.lastOrNull()?.let { it.self && it.status == STATUS_SENDING } == true -> builder.setSubText("Sending…")
|
|
247
|
+
}
|
|
145
248
|
openIntent(context, state.id, id)?.let(builder::setContentIntent)
|
|
146
249
|
|
|
147
250
|
if (state.grant != null) {
|
|
@@ -151,6 +254,7 @@ object MessageNotifications {
|
|
|
151
254
|
.setAllowGeneratedReplies(true)
|
|
152
255
|
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
|
|
153
256
|
.setShowsUserInterface(false)
|
|
257
|
+
.setAuthenticationRequired(replyRequiresUnlock(context))
|
|
154
258
|
.build()
|
|
155
259
|
val read = NotificationCompat.Action.Builder(0, "Mark as read", actionIntent(context, ACTION_READ, state.id, id + 2, mutable = false))
|
|
156
260
|
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
|
|
@@ -239,6 +343,8 @@ object MessageNotifications {
|
|
|
239
343
|
val text: String,
|
|
240
344
|
val at: Long,
|
|
241
345
|
val self: Boolean,
|
|
346
|
+
/** The user's own replies: sending | sent | failed (`id` is the reply's client id). */
|
|
347
|
+
val status: String? = null,
|
|
242
348
|
)
|
|
243
349
|
|
|
244
350
|
internal class Conversation(
|
|
@@ -248,6 +354,8 @@ object MessageNotifications {
|
|
|
248
354
|
var grant: String? = null,
|
|
249
355
|
val lines: MutableList<Line> = mutableListOf(),
|
|
250
356
|
var hidden: Boolean = false,
|
|
357
|
+
/** Why the last reply was not sent, shown under the conversation. */
|
|
358
|
+
var failure: String? = null,
|
|
251
359
|
)
|
|
252
360
|
|
|
253
361
|
private fun prefs(context: Context) =
|
|
@@ -266,6 +374,7 @@ object MessageNotifications {
|
|
|
266
374
|
group = o.optBoolean("group"),
|
|
267
375
|
grant = o.optString("grant").ifBlank { null },
|
|
268
376
|
hidden = o.optBoolean("hidden"),
|
|
377
|
+
failure = o.optString("failure").ifBlank { null },
|
|
269
378
|
lines = MutableList(lines.length()) { i ->
|
|
270
379
|
val l = lines.getJSONObject(i)
|
|
271
380
|
Line(
|
|
@@ -275,6 +384,7 @@ object MessageNotifications {
|
|
|
275
384
|
text = l.optString("text"),
|
|
276
385
|
at = l.optLong("at"),
|
|
277
386
|
self = l.optBoolean("self"),
|
|
387
|
+
status = l.optString("status").ifBlank { null },
|
|
278
388
|
)
|
|
279
389
|
},
|
|
280
390
|
)
|
|
@@ -291,7 +401,8 @@ object MessageNotifications {
|
|
|
291
401
|
.put("key", l.senderKey ?: "")
|
|
292
402
|
.put("text", l.text)
|
|
293
403
|
.put("at", l.at)
|
|
294
|
-
.put("self", l.self)
|
|
404
|
+
.put("self", l.self)
|
|
405
|
+
.put("status", l.status ?: ""),
|
|
295
406
|
)
|
|
296
407
|
}
|
|
297
408
|
val o = JSONObject()
|
|
@@ -299,55 +410,8 @@ object MessageNotifications {
|
|
|
299
410
|
.put("group", c.group)
|
|
300
411
|
.put("grant", c.grant ?: "")
|
|
301
412
|
.put("hidden", c.hidden)
|
|
413
|
+
.put("failure", c.failure ?: "")
|
|
302
414
|
.put("lines", lines)
|
|
303
415
|
prefs(context).edit().putString(key(c.id), o.toString()).apply()
|
|
304
416
|
}
|
|
305
417
|
}
|
|
306
|
-
|
|
307
|
-
/**
|
|
308
|
-
* Reply / Mark as read, tapped on a message notification. Posts to the
|
|
309
|
-
* notification-action endpoints with the conversation's reply grant —
|
|
310
|
-
* no app, no session — on a background thread kept alive by goAsync().
|
|
311
|
-
*/
|
|
312
|
-
class MessageActionReceiver : BroadcastReceiver() {
|
|
313
|
-
override fun onReceive(context: Context, intent: Intent) {
|
|
314
|
-
val conversationId = intent.getStringExtra(MessageNotifications.EXTRA_CONVERSATION) ?: return
|
|
315
|
-
val app = context.applicationContext
|
|
316
|
-
val grant = MessageNotifications.grantFor(app, conversationId)
|
|
317
|
-
val base = CallCore.apiBaseUrl(app)
|
|
318
|
-
|
|
319
|
-
when (intent.action) {
|
|
320
|
-
MessageNotifications.ACTION_REPLY -> {
|
|
321
|
-
val text = RemoteInput.getResultsFromIntent(intent)
|
|
322
|
-
?.getCharSequence(MessageNotifications.KEY_REPLY)?.toString()?.trim().orEmpty()
|
|
323
|
-
if (text.isEmpty() || grant == null || base == null) return
|
|
324
|
-
val pending = goAsync()
|
|
325
|
-
Thread {
|
|
326
|
-
val body = JSONObject().put("body", text).put("id", UUID.randomUUID().toString())
|
|
327
|
-
val ok = post("$base/v1/notifications/reply", grant, body)
|
|
328
|
-
MessageNotifications.onReplied(app, conversationId, text, ok)
|
|
329
|
-
pending.finish()
|
|
330
|
-
}.start()
|
|
331
|
-
}
|
|
332
|
-
MessageNotifications.ACTION_READ -> {
|
|
333
|
-
// Optimistic: the notification goes now; the server catches up.
|
|
334
|
-
MessageNotifications.clear(app, conversationId)
|
|
335
|
-
if (grant == null || base == null) return
|
|
336
|
-
val pending = goAsync()
|
|
337
|
-
Thread {
|
|
338
|
-
post("$base/v1/notifications/read", grant, JSONObject())
|
|
339
|
-
pending.finish()
|
|
340
|
-
}.start()
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
private fun post(url: String, grant: String, body: JSONObject): Boolean = runCatching {
|
|
346
|
-
val request = Request.Builder()
|
|
347
|
-
.url(url)
|
|
348
|
-
.header("Authorization", "Bearer $grant")
|
|
349
|
-
.post(body.toString().toRequestBody("application/json".toMediaType()))
|
|
350
|
-
.build()
|
|
351
|
-
CallHttpClient.defaultClient().newCall(request).execute().use { it.isSuccessful }
|
|
352
|
-
}.onFailure { Log.w("PoolseMessages", "notification action failed", it) }.getOrDefault(false)
|
|
353
|
-
}
|