@poolse/native 3.7.1 → 3.9.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +94 -1
  3. package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +8 -0
  4. package/android/src/main/java/dev/poolse/callcore/CallServers.kt +72 -0
  5. package/android/src/main/java/dev/poolse/callcore/Ports.kt +34 -0
  6. package/android/src/main/java/dev/poolse/callcore/RoutedHttpPort.kt +74 -0
  7. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +3 -3
  8. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +131 -14
  9. package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +3 -0
  10. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +4 -0
  11. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +1 -1
  12. package/android/src/main/java/dev/poolse/callcore/android/MessageActionWorker.kt +35 -12
  13. package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +142 -48
  14. package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +8 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/PoolseIncomingCall.kt +16 -0
  16. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +6 -0
  17. package/android/src/main/java/dev/poolse/callcore/android/ServerRegistry.kt +107 -0
  18. package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +23 -0
  19. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +58 -7
  20. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +96 -9
  21. package/dist/index.cjs +83 -24
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +156 -9
  24. package/dist/index.d.ts +156 -9
  25. package/dist/index.js +77 -25
  26. package/dist/index.js.map +1 -1
  27. package/ios/Core/CallCoreRuntime.swift +8 -0
  28. package/ios/Core/CallHttpClient.swift +11 -1
  29. package/ios/Core/CallServers.swift +89 -0
  30. package/ios/Core/Ports.swift +35 -2
  31. package/ios/Core/RoutedHttpPort.swift +83 -0
  32. package/ios/Core/SnapshotEncoding.swift +17 -1
  33. package/ios/Module/PoolseCallsModule.swift +50 -8
  34. package/ios/Platform/CallCore.swift +132 -12
  35. package/ios/Platform/CallKitController.swift +4 -1
  36. package/ios/Platform/LiveKitMediaPort.swift +103 -14
  37. package/ios/Platform/MessageNotifications.swift +76 -23
  38. package/ios/Platform/ServerRegistry.swift +90 -0
  39. package/ios/Platform/VoipPush.swift +5 -1
  40. package/package.json +1 -1
  41. package/src/index.ts +265 -31
@@ -174,6 +174,7 @@ internal class CallHttpClient(
174
174
  livekitToken = livekit.getString("token"),
175
175
  controlToken = root.optStringOrNull("control_token") ?: current.controlToken,
176
176
  ringing = 0,
177
+ // recording / transcription: the current bundle's stand.
177
178
  )
178
179
  }
179
180
  return CallSessionBundle(
@@ -190,6 +191,8 @@ internal class CallHttpClient(
190
191
  ringing = call.optJSONObject("ring_states")?.let { states ->
191
192
  states.keys().asSequence().count { states.optString(it) == "ringing" }
192
193
  } ?: 0,
194
+ recording = call.optJSONObject("recording")?.toString() ?: current?.recording,
195
+ transcription = call.optJSONObject("transcription")?.toString() ?: current?.transcription,
193
196
  )
194
197
  }
195
198
 
@@ -99,6 +99,10 @@ class CallMessagingService : FirebaseMessagingService() {
99
99
  externalId = this["caller_external_id"],
100
100
  userId = this["caller_user_id"],
101
101
  ),
102
+ // Signed in to several workspaces: the ring is answered (and
103
+ // declined) on the server of its tenant.
104
+ serverId = ServerRegistry.resolve(this@CallMessagingService, this["tenant_id"])?.id,
105
+ workspaceName = this["workspace_name"]?.ifEmpty { null },
102
106
  )
103
107
  }
104
108
 
@@ -121,7 +121,7 @@ class IncomingCallActivity : Activity() {
121
121
  ring = next
122
122
  awaitingForward = false
123
123
  pulse?.cancel()
124
- val title = next.conversationName ?: next.callerName ?: "Incoming call"
124
+ val title = ServerRegistry.ringTitle(this, next, next.conversationName ?: next.callerName) ?: "Incoming call"
125
125
  val body = if (next.media == "video") "Incoming video call" else "Incoming call"
126
126
  setContentView(buildScene(title, body, next))
127
127
  }
@@ -37,6 +37,8 @@ import java.util.concurrent.TimeUnit
37
37
  class MessageActionReceiver : BroadcastReceiver() {
38
38
  override fun onReceive(context: Context, intent: Intent) {
39
39
  val conversationId = intent.getStringExtra(MessageNotifications.EXTRA_CONVERSATION) ?: return
40
+ // Null on a notification posted before servers (the default one).
41
+ val serverId = intent.getStringExtra(MessageNotifications.EXTRA_SERVER)
40
42
  val app = context.applicationContext
41
43
 
42
44
  when (intent.action) {
@@ -45,19 +47,21 @@ class MessageActionReceiver : BroadcastReceiver() {
45
47
  ?.getCharSequence(MessageNotifications.KEY_REPLY)?.toString()?.trim().orEmpty()
46
48
  if (text.isEmpty()) {
47
49
  // Nothing typed; still repost so the field stops spinning.
48
- MessageNotifications.refresh(app, conversationId)
50
+ MessageNotifications.refresh(app, serverId, conversationId)
49
51
  return
50
52
  }
51
53
  // One id per reply, reused by every retry of it: the server
52
54
  // answers a repeat with the original message, never a second one.
53
55
  val clientId = UUID.randomUUID().toString()
54
- MessageNotifications.onReplying(app, conversationId, clientId, text)
55
- MessageActionWorker.enqueue(app, MessageActionWorker.REPLY, conversationId, text, clientId)
56
+ MessageNotifications.onReplying(app, serverId, conversationId, clientId, text)
57
+ MessageActionWorker.enqueue(app, MessageActionWorker.REPLY, serverId, conversationId, text, clientId)
56
58
  }
57
59
  MessageNotifications.ACTION_READ -> {
58
60
  // Optimistic: the notification goes now; the server catches up.
59
- MessageNotifications.clear(app, conversationId)
60
- MessageActionWorker.enqueue(app, MessageActionWorker.READ, conversationId, null, null)
61
+ // Grant first: clearing drops it with the conversation.
62
+ val grant = MessageNotifications.grantFor(app, serverId, conversationId)
63
+ MessageNotifications.clear(app, conversationId, serverId ?: dev.poolse.callcore.CallServers.DEFAULT_ID)
64
+ MessageActionWorker.enqueue(app, MessageActionWorker.READ, serverId, conversationId, null, null, grant)
61
65
  }
62
66
  }
63
67
  }
@@ -66,7 +70,8 @@ class MessageActionReceiver : BroadcastReceiver() {
66
70
  /**
67
71
  * The HTTP side of a notification action: `POST /v1/notification-actions/
68
72
  * {reply,read}` with the conversation's reply grant (bearer and `token`),
69
- * against the API origin `configure` persisted — no app, no session, no JS.
73
+ * against its server's API origin (persisted by `configure` / `addServer`)
74
+ * — no app, no session, no JS.
70
75
  *
71
76
  * WorkManager, expedited: it runs at once when there is a network, waits
72
77
  * for one when there is not, survives the process being killed, and
@@ -82,9 +87,16 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
82
87
  val conversationId = inputData.getString(KEY_CONVERSATION) ?: return@withContext Result.failure()
83
88
  val text = inputData.getString(KEY_TEXT).orEmpty()
84
89
  val clientId = inputData.getString(KEY_CLIENT_ID).orEmpty()
90
+ val serverId = inputData.getString(KEY_SERVER)
85
91
  // 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)
92
+ val grant = MessageNotifications.grantFor(app, serverId, conversationId) ?: inputData.getString(KEY_GRANT)
93
+ // Its own server; one signed out since has no address (never another
94
+ // server's: the grant is for this one).
95
+ val base = if (serverId != null) {
96
+ ServerRegistry.baseUrl(app, serverId).ifEmpty { null }
97
+ } else {
98
+ ServerRegistry.baseUrl(app, null).ifEmpty { null } ?: CallCore.apiBaseUrl(app)
99
+ }
88
100
 
89
101
  val outcome = when {
90
102
  base == null -> Outcome(0, "not_configured", null)
@@ -103,6 +115,7 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
103
115
  "action" to if (action == REPLY) "reply" else "mark_read",
104
116
  "conversationId" to conversationId,
105
117
  "ok" to ok,
118
+ "serverId" to (serverId ?: ServerRegistry.servers(app).get(null)?.id),
106
119
  )
107
120
  if (!ok) {
108
121
  event["error"] = outcome.code ?: if (outcome.status == 0) "network" else "http_${outcome.status}"
@@ -112,7 +125,7 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
112
125
  event["text"] = text
113
126
  event["clientId"] = clientId
114
127
  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)
128
+ MessageNotifications.onReplied(app, serverId, conversationId, clientId, text, ok, if (ok) null else reason(outcome), grant)
116
129
  } else if (!ok) {
117
130
  // A failed read is only logged: the message stays unread, nothing is lost.
118
131
  Log.w(TAG, "mark read failed status=${outcome.status} code=${outcome.code}")
@@ -172,6 +185,7 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
172
185
  internal const val READ = "read"
173
186
  private const val KEY_ACTION = "action"
174
187
  private const val KEY_CONVERSATION = "conversation_id"
188
+ private const val KEY_SERVER = "server_id"
175
189
  private const val KEY_TEXT = "text"
176
190
  private const val KEY_CLIENT_ID = "client_id"
177
191
  private const val KEY_GRANT = "grant"
@@ -190,13 +204,22 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
190
204
  .build()
191
205
  }
192
206
 
193
- internal fun enqueue(context: Context, action: String, conversationId: String, text: String?, clientId: String?) {
207
+ internal fun enqueue(
208
+ context: Context,
209
+ action: String,
210
+ serverId: String?,
211
+ conversationId: String,
212
+ text: String?,
213
+ clientId: String?,
214
+ grant: String? = MessageNotifications.grantFor(context, serverId, conversationId),
215
+ ) {
194
216
  val data = Data.Builder()
195
217
  .putString(KEY_ACTION, action)
196
218
  .putString(KEY_CONVERSATION, conversationId)
219
+ .putString(KEY_SERVER, serverId)
197
220
  .putString(KEY_TEXT, text)
198
221
  .putString(KEY_CLIENT_ID, clientId)
199
- .putString(KEY_GRANT, MessageNotifications.grantFor(context, conversationId))
222
+ .putString(KEY_GRANT, grant)
200
223
  .putLong(KEY_AT, System.currentTimeMillis())
201
224
  .build()
202
225
  val request = OneTimeWorkRequestBuilder<MessageActionWorker>()
@@ -206,7 +229,7 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
206
229
  .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)
207
230
  .addTag("poolse-notification-action")
208
231
  .build()
209
- val name = "poolse-$action-" + (clientId ?: conversationId)
232
+ val name = "poolse-$action-" + (clientId ?: listOfNotNull(serverId, conversationId).joinToString("/"))
210
233
  runCatching {
211
234
  WorkManager.getInstance(context).enqueueUniqueWork(name, ExistingWorkPolicy.KEEP, request)
212
235
  }.onFailure { Log.e(TAG, "could not queue the notification action", it) }
@@ -11,6 +11,7 @@ import androidx.core.app.NotificationCompat
11
11
  import androidx.core.app.NotificationManagerCompat
12
12
  import androidx.core.app.Person
13
13
  import androidx.core.app.RemoteInput
14
+ import dev.poolse.callcore.CallServers
14
15
  import org.json.JSONArray
15
16
  import org.json.JSONObject
16
17
 
@@ -31,6 +32,15 @@ import org.json.JSONObject
31
32
  * last few lines per conversation are kept in a small preferences file
32
33
  * and the notification is rebuilt from them on every message. They are
33
34
  * dropped the moment the conversation is read, here or elsewhere.
35
+ *
36
+ * Several workspaces: a push's `tenant_id` picks its server
37
+ * ([ServerRegistry]). Each server other than `default` gets its own
38
+ * notification group, summary and channel (in a channel group named
39
+ * after the workspace, so it can be muted on its own); with more than
40
+ * one signed in every chat names its workspace. Reply and Mark as read
41
+ * go to the conversation's own server, and their results say which
42
+ * (`serverId`). The `default` server keeps the original channel, group
43
+ * and storage, so a single-server app looks and behaves as before.
34
44
  */
35
45
  object MessageNotifications {
36
46
  const val CHANNEL_ID = "poolse_messages"
@@ -42,6 +52,7 @@ object MessageNotifications {
42
52
  internal const val ACTION_REPLY = "dev.poolse.callcore.message.REPLY"
43
53
  internal const val ACTION_READ = "dev.poolse.callcore.message.READ"
44
54
  internal const val EXTRA_CONVERSATION = "poolse_message_conversation"
55
+ internal const val EXTRA_SERVER = "poolse_message_server"
45
56
  private const val TAG = "PoolseMessages"
46
57
  private const val ACTIONS_PREFS = "dev.poolse.messages.actions"
47
58
  private const val MAX_PENDING_ACTIONS = 50
@@ -57,6 +68,9 @@ object MessageNotifications {
57
68
  */
58
69
  @Volatile var activeConversationId: String? = null
59
70
 
71
+ /** The server of [activeConversationId]; null = whichever has it. */
72
+ @Volatile var activeServerId: String? = null
73
+
60
74
  /** The bridge's subscriber for finished Reply / Mark as read actions. */
61
75
  @Volatile var actionListener: ((Map<String, Any?>) -> Unit)? = null
62
76
 
@@ -69,12 +83,16 @@ object MessageNotifications {
69
83
  /** A `type: "message", event: "new"` push. */
70
84
  fun onNew(context: Context, data: Map<String, String>, smallIcon: Int) {
71
85
  val conversationId = data["conversation_id"] ?: return
72
- if (conversationId == activeConversationId) return
86
+ val serverId = bucket(ServerRegistry.resolve(context, data["tenant_id"])?.id)
87
+ if (conversationId == activeConversationId &&
88
+ (activeServerId == null || bucket(activeServerId) == serverId)
89
+ ) return
73
90
  val sentAt = data["sent_at"]?.toLongOrNull() ?: System.currentTimeMillis()
74
91
  if (System.currentTimeMillis() - sentAt > STALE_MS) return
75
92
 
76
- val state = load(context, conversationId) ?: Conversation(conversationId)
93
+ val state = load(context, serverId, conversationId) ?: Conversation(conversationId, serverId)
77
94
  state.title = data["conversation_name"]?.ifBlank { null } ?: state.title
95
+ state.workspace = data["workspace_name"]?.ifBlank { null } ?: state.workspace
78
96
  state.group = data["group"] == "1"
79
97
  state.hidden = data["private"] == "1"
80
98
  data["reply_grant"]?.ifBlank { null }?.let { state.grant = it }
@@ -102,19 +120,39 @@ object MessageNotifications {
102
120
  */
103
121
  fun onRead(context: Context, data: Map<String, String>) {
104
122
  val conversationId = data["conversation_id"] ?: return
105
- clear(context, conversationId)
123
+ clear(context, conversationId, ServerRegistry.resolve(context, data["tenant_id"])?.id ?: CallServers.DEFAULT_ID)
124
+ }
125
+
126
+ /**
127
+ * The conversation was read (here, or on another device): clear it —
128
+ * on [serverId], or on every server that has it when null.
129
+ */
130
+ fun clear(context: Context, conversationId: String, serverId: String? = null) {
131
+ val servers = if (serverId != null) listOf(bucket(serverId)) else storedKeys(context)
132
+ .filter { it.second == conversationId }.map { it.first }.ifEmpty { listOf(null) }
133
+ val edit = prefs(context).edit()
134
+ for (server in servers) {
135
+ edit.remove(key(server, conversationId))
136
+ runCatching { NotificationManagerCompat.from(context).cancel(notificationId(server, conversationId)) }
137
+ }
138
+ edit.apply()
139
+ for (server in servers.distinct()) refreshSummary(context, server, CallCore.smallIcon(context))
106
140
  }
107
141
 
108
- /** The conversation was read (here, or on another device): clear it. */
109
- fun clear(context: Context, conversationId: String) {
110
- prefs(context).edit().remove(key(conversationId)).apply()
111
- runCatching { NotificationManagerCompat.from(context).cancel(notificationId(conversationId)) }
112
- refreshSummary(context, CallCore.smallIcon(context))
142
+ /** Signed out of a workspace: every chat of it goes, with its channel group. */
143
+ fun removeServer(context: Context, serverId: String) {
144
+ val server = bucket(serverId)
145
+ for ((s, conversationId) in storedKeys(context)) if (s == server) clear(context, conversationId, serverId)
146
+ if (server != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
147
+ runCatching {
148
+ context.getSystemService(NotificationManager::class.java).deleteNotificationChannelGroup(channelGroupId(server))
149
+ }
150
+ }
113
151
  }
114
152
 
115
153
  /** Repost a conversation's notification as it is, silently. */
116
- internal fun refresh(context: Context, conversationId: String) {
117
- val state = load(context, conversationId) ?: return
154
+ internal fun refresh(context: Context, serverId: String?, conversationId: String) {
155
+ val state = load(context, bucket(serverId), conversationId) ?: return
118
156
  post(context, state, CallCore.smallIcon(context), alert = false)
119
157
  }
120
158
 
@@ -122,8 +160,8 @@ object MessageNotifications {
122
160
  * Reply tapped: show the user's line at once ("Sending…") — Android
123
161
  * keeps the reply field spinning until the notification is updated.
124
162
  */
125
- internal fun onReplying(context: Context, conversationId: String, clientId: String, text: String) {
126
- val state = load(context, conversationId) ?: Conversation(conversationId)
163
+ internal fun onReplying(context: Context, serverId: String?, conversationId: String, clientId: String, text: String) {
164
+ val state = load(context, bucket(serverId), conversationId) ?: Conversation(conversationId, bucket(serverId))
127
165
  state.lines.removeAll { it.self && it.id == clientId }
128
166
  state.lines += Line(
129
167
  id = clientId,
@@ -145,8 +183,9 @@ object MessageNotifications {
145
183
  * the line reads "Not sent", with why underneath, and the
146
184
  * notification alerts again; Reply stays on it to try again.
147
185
  */
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)
186
+ internal fun onReplied(context: Context, serverId: String?, conversationId: String, clientId: String, text: String, ok: Boolean, reason: String?, grant: String?) {
187
+ val server = bucket(serverId)
188
+ val state = load(context, server, conversationId) ?: if (ok) return else Conversation(conversationId, server, grant = grant)
150
189
  val index = state.lines.indexOfFirst { it.self && it.id == clientId }
151
190
  val line = Line(
152
191
  id = clientId,
@@ -204,13 +243,15 @@ object MessageNotifications {
204
243
  .metaData?.getBoolean(META_REPLY_UNLOCK, false) ?: false
205
244
  }.getOrDefault(false)
206
245
 
207
- internal fun grantFor(context: Context, conversationId: String): String? =
208
- load(context, conversationId)?.grant
246
+ internal fun grantFor(context: Context, serverId: String?, conversationId: String): String? =
247
+ load(context, bucket(serverId), conversationId)?.grant
209
248
 
210
249
  // ── building ────────────────────────────────────────────────────────
211
250
 
212
251
  private fun post(context: Context, state: Conversation, smallIcon: Int, alert: Boolean) {
213
- ensureChannel(context)
252
+ val channel = ensureChannel(context, state.server, state.workspace)
253
+ // Several workspaces signed in: every chat says which it is.
254
+ val workspace = ServerRegistry.servers(context).workspaceLabel(state.server ?: CallServers.DEFAULT_ID, state.workspace)
214
255
  val me = Person.Builder().setName("You").build()
215
256
  val style = NotificationCompat.MessagingStyle(me)
216
257
  .setGroupConversation(state.group)
@@ -221,12 +262,12 @@ object MessageNotifications {
221
262
  style.addMessage(NotificationCompat.MessagingStyle.Message(text, line.at, person))
222
263
  }
223
264
 
224
- val id = notificationId(state.id)
225
- val builder = NotificationCompat.Builder(context, CHANNEL_ID)
265
+ val id = notificationId(state.server, state.id)
266
+ val builder = NotificationCompat.Builder(context, channel)
226
267
  .setSmallIcon(smallIcon)
227
268
  .setCategory(NotificationCompat.CATEGORY_MESSAGE)
228
269
  .setPriority(NotificationCompat.PRIORITY_HIGH)
229
- .setGroup(GROUP_KEY)
270
+ .setGroup(groupKey(state.server))
230
271
  .setAutoCancel(true)
231
272
  .setOnlyAlertOnce(!alert)
232
273
  .setWhen(state.lines.lastOrNull()?.at ?: System.currentTimeMillis())
@@ -244,19 +285,20 @@ object MessageNotifications {
244
285
  when {
245
286
  state.failure != null -> builder.setSubText(state.failure)
246
287
  state.lines.lastOrNull()?.let { it.self && it.status == STATUS_SENDING } == true -> builder.setSubText("Sending…")
288
+ workspace != null -> builder.setSubText(workspace)
247
289
  }
248
- openIntent(context, state.id, id)?.let(builder::setContentIntent)
290
+ openIntent(context, state.server, state.id, id)?.let(builder::setContentIntent)
249
291
 
250
292
  if (state.grant != null) {
251
293
  val remoteInput = RemoteInput.Builder(KEY_REPLY).setLabel("Message").build()
252
- val reply = NotificationCompat.Action.Builder(0, "Reply", actionIntent(context, ACTION_REPLY, state.id, id + 1, mutable = true))
294
+ val reply = NotificationCompat.Action.Builder(0, "Reply", actionIntent(context, ACTION_REPLY, state.server, state.id, id + 1, mutable = true))
253
295
  .addRemoteInput(remoteInput)
254
296
  .setAllowGeneratedReplies(true)
255
297
  .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
256
298
  .setShowsUserInterface(false)
257
299
  .setAuthenticationRequired(replyRequiresUnlock(context))
258
300
  .build()
259
- val read = NotificationCompat.Action.Builder(0, "Mark as read", actionIntent(context, ACTION_READ, state.id, id + 2, mutable = false))
301
+ val read = NotificationCompat.Action.Builder(0, "Mark as read", actionIntent(context, ACTION_READ, state.server, state.id, id + 2, mutable = false))
260
302
  .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
261
303
  .setShowsUserInterface(false)
262
304
  .build()
@@ -269,37 +311,43 @@ object MessageNotifications {
269
311
  Log.w(TAG, "message notification refused (POST_NOTIFICATIONS?)", e)
270
312
  return
271
313
  }
272
- refreshSummary(context, smallIcon)
314
+ refreshSummary(context, state.server, smallIcon)
273
315
  }
274
316
 
275
- /** The group's summary: "5 messages from 2 chats". Gone with the last chat. */
276
- private fun refreshSummary(context: Context, smallIcon: Int) {
277
- val all = prefs(context).all.keys.filter { it.startsWith("conv:") }
278
- .mapNotNull { load(context, it.removePrefix("conv:")) }
317
+ /**
318
+ * A server's group summary: "5 messages from 2 chats" (with the
319
+ * workspace's name while several are signed in). Gone with its last chat.
320
+ */
321
+ private fun refreshSummary(context: Context, server: String?, smallIcon: Int) {
322
+ val all = storedKeys(context).filter { it.first == server }.mapNotNull { load(context, server, it.second) }
279
323
  val manager = NotificationManagerCompat.from(context)
280
324
  if (all.isEmpty()) {
281
- runCatching { manager.cancel(SUMMARY_ID) }
325
+ runCatching { manager.cancel(summaryId(server)) }
282
326
  return
283
327
  }
284
328
  val messages = all.sumOf { c -> c.lines.count { !it.self } }
285
329
  val text = if (all.size == 1) "$messages new messages" else "$messages messages from ${all.size} chats"
286
- val summary = NotificationCompat.Builder(context, CHANNEL_ID)
330
+ val workspace = ServerRegistry.servers(context)
331
+ .workspaceLabel(server ?: CallServers.DEFAULT_ID, all.firstNotNullOfOrNull { it.workspace })
332
+ val summary = NotificationCompat.Builder(context, ensureChannel(context, server, all.firstNotNullOfOrNull { it.workspace }))
287
333
  .setSmallIcon(smallIcon)
288
334
  .setContentTitle(text)
289
- .setStyle(NotificationCompat.InboxStyle().setSummaryText(text))
290
- .setGroup(GROUP_KEY)
335
+ .setStyle(NotificationCompat.InboxStyle().setSummaryText(workspace ?: text))
336
+ .apply { if (workspace != null) setSubText(workspace) }
337
+ .setGroup(groupKey(server))
291
338
  .setGroupSummary(true)
292
339
  .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN)
293
340
  .setAutoCancel(true)
294
341
  .build()
295
- runCatching { manager.notify(SUMMARY_ID, summary) }
342
+ runCatching { manager.notify(summaryId(server), summary) }
296
343
  }
297
344
 
298
- private fun openIntent(context: Context, conversationId: String, requestCode: Int): PendingIntent? {
345
+ private fun openIntent(context: Context, server: String?, conversationId: String, requestCode: Int): PendingIntent? {
299
346
  val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null
300
347
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
301
348
  .putExtra(MissedCallNotification.EXTRA_ACTION, MissedCallNotification.ACTION_OPEN)
302
349
  .putExtra(MissedCallNotification.EXTRA_CONVERSATION_ID, conversationId)
350
+ .putExtra(MissedCallNotification.EXTRA_SERVER_ID, server ?: CallServers.DEFAULT_ID)
303
351
  return PendingIntent.getActivity(
304
352
  context,
305
353
  requestCode,
@@ -308,10 +356,11 @@ object MessageNotifications {
308
356
  )
309
357
  }
310
358
 
311
- private fun actionIntent(context: Context, action: String, conversationId: String, requestCode: Int, mutable: Boolean): PendingIntent {
359
+ private fun actionIntent(context: Context, action: String, server: String?, conversationId: String, requestCode: Int, mutable: Boolean): PendingIntent {
312
360
  val intent = Intent(context, MessageActionReceiver::class.java)
313
361
  .setAction(action)
314
362
  .putExtra(EXTRA_CONVERSATION, conversationId)
363
+ .putExtra(EXTRA_SERVER, server)
315
364
  // RemoteInput writes the typed text into the intent: it must be mutable.
316
365
  val mutability = if (mutable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
317
366
  PendingIntent.FLAG_MUTABLE
@@ -321,18 +370,43 @@ object MessageNotifications {
321
370
  return PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT or mutability)
322
371
  }
323
372
 
324
- private fun ensureChannel(context: Context) {
325
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
373
+ /**
374
+ * The channel a server's chats post on (returned): the original one for
375
+ * the default server; for any other its own "Messages" channel inside
376
+ * a channel group named after the workspace — never its raw id.
377
+ */
378
+ private fun ensureChannel(context: Context, server: String?, workspaceName: String?): String {
379
+ val id = if (server == null) CHANNEL_ID else "$CHANNEL_ID.$server"
380
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return id
326
381
  val manager = context.getSystemService(NotificationManager::class.java)
327
- if (manager.getNotificationChannel(CHANNEL_ID) != null) return
328
- manager.createNotificationChannel(
329
- NotificationChannel(CHANNEL_ID, "Messages", NotificationManager.IMPORTANCE_HIGH).apply {
330
- lockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE
331
- },
332
- )
382
+ if (manager.getNotificationChannel(id) != null) return id
383
+ val channel = NotificationChannel(id, "Messages", NotificationManager.IMPORTANCE_HIGH).apply {
384
+ lockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE
385
+ }
386
+ if (server != null) {
387
+ val label = workspaceName ?: ServerRegistry.servers(context).get(server)?.let { s ->
388
+ s.name ?: runCatching { android.net.Uri.parse(s.apiBaseUrl).host }.getOrNull()
389
+ } ?: "Workspace"
390
+ runCatching {
391
+ manager.createNotificationChannelGroup(android.app.NotificationChannelGroup(channelGroupId(server), label))
392
+ channel.group = channelGroupId(server)
393
+ }
394
+ }
395
+ manager.createNotificationChannel(channel)
396
+ return id
333
397
  }
334
398
 
335
- private fun notificationId(conversationId: String) = ("msg:$conversationId").hashCode()
399
+ /** Server ids as stored: null is the default server (the original keys, ids and channel). */
400
+ private fun bucket(serverId: String?): String? = serverId?.takeIf { it != CallServers.DEFAULT_ID }
401
+
402
+ private fun channelGroupId(server: String) = "poolse.workspace.$server"
403
+
404
+ private fun groupKey(server: String?) = if (server == null) GROUP_KEY else "$GROUP_KEY.$server"
405
+
406
+ private fun summaryId(server: String?) = if (server == null) SUMMARY_ID else ("summary:$server").hashCode()
407
+
408
+ private fun notificationId(server: String?, conversationId: String) =
409
+ (if (server == null) "msg:$conversationId" else "msg:$server/$conversationId").hashCode()
336
410
 
337
411
  // ── storage ─────────────────────────────────────────────────────────
338
412
 
@@ -349,7 +423,11 @@ object MessageNotifications {
349
423
 
350
424
  internal class Conversation(
351
425
  val id: String,
426
+ /** Its server, as stored ([bucket]): null = the default. */
427
+ val server: String? = null,
352
428
  var title: String? = null,
429
+ /** The push's `workspace_name`. */
430
+ var workspace: String? = null,
353
431
  var group: Boolean = false,
354
432
  var grant: String? = null,
355
433
  val lines: MutableList<Line> = mutableListOf(),
@@ -361,16 +439,31 @@ object MessageNotifications {
361
439
  private fun prefs(context: Context) =
362
440
  context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
363
441
 
364
- private fun key(conversationId: String) = "conv:$conversationId"
442
+ /** `conv:<conversation>` for the default server (as before servers), `conv:@<server>/<conversation>` otherwise. */
443
+ private fun key(server: String?, conversationId: String) =
444
+ if (server == null) "conv:$conversationId" else "conv:@$server/$conversationId"
445
+
446
+ /** Every stored conversation as (server, conversation). */
447
+ private fun storedKeys(context: Context): List<Pair<String?, String>> =
448
+ prefs(context).all.keys.filter { it.startsWith("conv:") }.map { k ->
449
+ val rest = k.removePrefix("conv:")
450
+ if (rest.startsWith("@") && rest.contains('/')) {
451
+ rest.substring(1, rest.indexOf('/')) to rest.substring(rest.indexOf('/') + 1)
452
+ } else {
453
+ null to rest
454
+ }
455
+ }
365
456
 
366
- private fun load(context: Context, conversationId: String): Conversation? {
367
- val raw = prefs(context).getString(key(conversationId), null) ?: return null
457
+ private fun load(context: Context, server: String?, conversationId: String): Conversation? {
458
+ val raw = prefs(context).getString(key(server, conversationId), null) ?: return null
368
459
  return runCatching {
369
460
  val o = JSONObject(raw)
370
461
  val lines = o.optJSONArray("lines") ?: JSONArray()
371
462
  Conversation(
372
463
  id = conversationId,
464
+ server = server,
373
465
  title = o.optString("title").ifBlank { null },
466
+ workspace = o.optString("workspace").ifBlank { null },
374
467
  group = o.optBoolean("group"),
375
468
  grant = o.optString("grant").ifBlank { null },
376
469
  hidden = o.optBoolean("hidden"),
@@ -407,11 +500,12 @@ object MessageNotifications {
407
500
  }
408
501
  val o = JSONObject()
409
502
  .put("title", c.title ?: "")
503
+ .put("workspace", c.workspace ?: "")
410
504
  .put("group", c.group)
411
505
  .put("grant", c.grant ?: "")
412
506
  .put("hidden", c.hidden)
413
507
  .put("failure", c.failure ?: "")
414
508
  .put("lines", lines)
415
- prefs(context).edit().putString(key(c.id), o.toString()).apply()
509
+ prefs(context).edit().putString(key(c.server, c.id), o.toString()).apply()
416
510
  }
417
511
  }
@@ -27,6 +27,8 @@ object MissedCallNotification {
27
27
  const val EXTRA_CONVERSATION_ID = "poolse_call_action_conversation"
28
28
  const val EXTRA_CALL_ID = "poolse_call_action_call"
29
29
  const val EXTRA_MEDIA = "poolse_call_action_media"
30
+ /** The host's id of the server (workspace) the notification belongs to. */
31
+ const val EXTRA_SERVER_ID = "poolse_call_action_server"
30
32
  const val ACTION_OPEN = "open"
31
33
  const val ACTION_CALL_BACK = "call_back"
32
34
  private const val TAG = "PoolseMissedCall"
@@ -45,6 +47,10 @@ object MissedCallNotification {
45
47
  ?: "Missed call"
46
48
  val body = data["body"]?.ifBlank { null }
47
49
  ?: if (media == "video") "Missed video call" else "Missed voice call"
50
+ val servers = ServerRegistry.servers(context)
51
+ val server = servers.resolve(data["tenant_id"]?.ifBlank { null })
52
+ // Several workspaces signed in: say which one called.
53
+ val workspace = servers.workspaceLabel(server?.id, data["workspace_name"])
48
54
 
49
55
  ensureChannel(context)
50
56
  val id = notificationId(callId)
@@ -56,6 +62,7 @@ object MissedCallNotification {
56
62
  .putExtra(EXTRA_CONVERSATION_ID, conversationId)
57
63
  .putExtra(EXTRA_CALL_ID, callId)
58
64
  .putExtra(EXTRA_MEDIA, media)
65
+ .putExtra(EXTRA_SERVER_ID, server?.id)
59
66
  return PendingIntent.getActivity(
60
67
  context,
61
68
  id + requestOffset,
@@ -73,6 +80,7 @@ object MissedCallNotification {
73
80
  .setAutoCancel(true)
74
81
  .setWhen(sentAt ?: System.currentTimeMillis())
75
82
  .setShowWhen(true)
83
+ .apply { if (workspace != null) setSubText(workspace) }
76
84
  launch(ACTION_OPEN, 0)?.let(builder::setContentIntent)
77
85
  launch(ACTION_CALL_BACK, 1)?.let { builder.addAction(0, "Call back", it) }
78
86
 
@@ -45,6 +45,14 @@ object PoolseIncomingCall {
45
45
  /** The conversation's name (a group's title), when it has one. */
46
46
  const val EXTRA_CONVERSATION_NAME = "poolse_conversation_name"
47
47
  const val EXTRA_CALLER_NAME = "poolse_caller_name"
48
+ /**
49
+ * The workspace the ring came from (the push's `workspace_name`, else
50
+ * the server's name), present only while several servers are signed in
51
+ * — show "Ana · Acme" with it.
52
+ */
53
+ const val EXTRA_WORKSPACE_NAME = "poolse_workspace_name"
54
+ /** The host's id of the server the ring came from (`addServer({ id })`). */
55
+ const val EXTRA_SERVER_ID = "poolse_server_id"
48
56
  /** The caller's picture: the push's `caller_avatar_url`, else `incomingCall.avatarUrl` filled in. */
49
57
  const val EXTRA_CALLER_AVATAR_URL = "poolse_caller_avatar_url"
50
58
  /** `audio` | `video`. */
@@ -95,4 +103,12 @@ object PoolseIncomingCall {
95
103
  .putExtra(EXTRA_CALLER_AVATAR_URL, ring.callerAvatarUrl)
96
104
  .putExtra(EXTRA_MEDIA, ring.media)
97
105
  .putExtra(EXTRA_RING_DEADLINE, ring.ringDeadlineEpochMs)
106
+ .putExtra(EXTRA_SERVER_ID, ring.serverId)
107
+
108
+ /** [fill] plus the workspace label, which needs the server list. */
109
+ internal fun fill(context: Context, intent: Intent, ring: RingContext): Intent = fill(intent, ring)
110
+ .putExtra(
111
+ EXTRA_WORKSPACE_NAME,
112
+ ServerRegistry.servers(context).workspaceLabel(ring.serverId, ring.workspaceName),
113
+ )
98
114
  }
@@ -17,6 +17,8 @@ internal fun RingContext.toBundle(): Bundle = Bundle().apply {
17
17
  putString(K_GRANT, grant)
18
18
  putLong(K_DEADLINE, ringDeadlineEpochMs)
19
19
  putString(K_AVATAR, callerAvatarUrl)
20
+ putString(K_SERVER, serverId)
21
+ putString(K_WORKSPACE, workspaceName)
20
22
  }
21
23
 
22
24
  internal fun Bundle.toRingContext(): RingContext? {
@@ -32,6 +34,8 @@ internal fun Bundle.toRingContext(): RingContext? {
32
34
  grant = grant,
33
35
  ringDeadlineEpochMs = getLong(K_DEADLINE),
34
36
  callerAvatarUrl = getString(K_AVATAR),
37
+ serverId = getString(K_SERVER),
38
+ workspaceName = getString(K_WORKSPACE),
35
39
  )
36
40
  }
37
41
 
@@ -43,3 +47,5 @@ private const val K_MEDIA = "media"
43
47
  private const val K_GRANT = "grant"
44
48
  private const val K_DEADLINE = "ringDeadline"
45
49
  private const val K_AVATAR = "callerAvatarUrl"
50
+ private const val K_SERVER = "serverId"
51
+ private const val K_WORKSPACE = "workspaceName"