@poolse/native 3.7.1 → 3.8.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 (33) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +61 -1
  3. package/android/src/main/java/dev/poolse/callcore/CallServers.kt +72 -0
  4. package/android/src/main/java/dev/poolse/callcore/Ports.kt +8 -0
  5. package/android/src/main/java/dev/poolse/callcore/RoutedHttpPort.kt +74 -0
  6. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +3 -3
  7. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +110 -14
  8. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +4 -0
  9. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +1 -1
  10. package/android/src/main/java/dev/poolse/callcore/android/MessageActionWorker.kt +35 -12
  11. package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +142 -48
  12. package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +8 -0
  13. package/android/src/main/java/dev/poolse/callcore/android/PoolseIncomingCall.kt +16 -0
  14. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +6 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/ServerRegistry.kt +107 -0
  16. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +56 -7
  17. package/dist/index.cjs +68 -24
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +91 -8
  20. package/dist/index.d.ts +91 -8
  21. package/dist/index.js +64 -25
  22. package/dist/index.js.map +1 -1
  23. package/ios/Core/CallServers.swift +89 -0
  24. package/ios/Core/Ports.swift +10 -1
  25. package/ios/Core/RoutedHttpPort.swift +83 -0
  26. package/ios/Module/PoolseCallsModule.swift +48 -8
  27. package/ios/Platform/CallCore.swift +116 -11
  28. package/ios/Platform/CallKitController.swift +4 -1
  29. package/ios/Platform/MessageNotifications.swift +76 -23
  30. package/ios/Platform/ServerRegistry.swift +90 -0
  31. package/ios/Platform/VoipPush.swift +5 -1
  32. package/package.json +1 -1
  33. package/src/index.ts +187 -30
@@ -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"
@@ -0,0 +1,107 @@
1
+ package dev.poolse.callcore.android
2
+
3
+ import android.content.Context
4
+ import dev.poolse.callcore.CallServer
5
+ import dev.poolse.callcore.CallServers
6
+ import org.json.JSONArray
7
+ import org.json.JSONObject
8
+
9
+ /**
10
+ * The signed-in servers, persisted — so a ring or a notification action
11
+ * that wakes a killed app (no JS) knows where each workspace's API
12
+ * lives. No secrets in it: ids, URLs, tenant ids and names.
13
+ *
14
+ * Upgrading from a single-server build: no list yet, so the server
15
+ * `configure` persisted becomes `default`.
16
+ */
17
+ object ServerRegistry {
18
+ private const val PREFS = "dev.poolse.callcore"
19
+ private const val KEY = "servers"
20
+
21
+ @Volatile private var loaded: CallServers? = null
22
+
23
+ /** The current list. Any thread. */
24
+ fun servers(context: Context): CallServers = loaded ?: synchronized(this) { loaded ?: load(context) }
25
+
26
+ fun upsert(context: Context, server: CallServer) = mutate(context) { it.upsert(server) }
27
+
28
+ fun remove(context: Context, id: String) = mutate(context) { it.remove(id) }
29
+
30
+ /** The base URL of [serverId] (null = the default server); "" when unknown. */
31
+ fun baseUrl(context: Context, serverId: String?): String {
32
+ val s = servers(context)
33
+ s.get(serverId)?.let { return it.apiBaseUrl }
34
+ // A single-server app that never named its server: whatever it has.
35
+ if (serverId == null && s.all.size == 1) return s.all[0].apiBaseUrl
36
+ return ""
37
+ }
38
+
39
+ /** The server a push of [tenantId] belongs to (see [CallServers.resolve]). */
40
+ fun resolve(context: Context, tenantId: String?): CallServer? =
41
+ servers(context).resolve(tenantId?.ifBlank { null })
42
+
43
+ private fun mutate(context: Context, change: (CallServers) -> CallServers) = synchronized(this) {
44
+ val next = change(loaded ?: load(context))
45
+ loaded = next
46
+ val list = JSONArray()
47
+ for (s in next.all) list.put(s.toJson())
48
+ prefs(context).edit().putString(KEY, list.toString()).apply()
49
+ }
50
+
51
+ private fun load(context: Context): CallServers {
52
+ val p = prefs(context)
53
+ val raw = p.getString(KEY, null)
54
+ val s = if (raw != null) {
55
+ val list = runCatching { JSONArray(raw) }.getOrDefault(JSONArray())
56
+ CallServers((0 until list.length()).mapNotNull { list.optJSONObject(it)?.toServer() })
57
+ } else {
58
+ // Migrate: the one server a single-server build configured.
59
+ val legacy = p.getString("apiBaseUrl", null)?.trimEnd('/')?.ifEmpty { null }
60
+ ?: return CallServers() // nothing yet — not cached: configure may be about to run
61
+ CallServers(listOf(CallServer(CallServers.DEFAULT_ID, legacy))).also { migrated ->
62
+ val list = JSONArray().put(migrated.all[0].toJson())
63
+ p.edit().putString(KEY, list.toString()).apply()
64
+ }
65
+ }
66
+ loaded = s
67
+ return s
68
+ }
69
+
70
+ private fun prefs(context: Context) =
71
+ context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
72
+
73
+ private fun CallServer.toJson(): JSONObject = JSONObject()
74
+ .put("id", id)
75
+ .put("apiBaseUrl", apiBaseUrl)
76
+ .apply {
77
+ tenantId?.let { put("tenantId", it) }
78
+ name?.let { put("name", it) }
79
+ }
80
+
81
+ private fun JSONObject.toServer(): CallServer? {
82
+ val id = optString("id").ifBlank { null } ?: return null
83
+ val url = optString("apiBaseUrl").ifBlank { null } ?: return null
84
+ return CallServer(id, url, optString("tenantId").ifBlank { null }, optString("name").ifBlank { null })
85
+ }
86
+
87
+ /**
88
+ * "Ana · Acme" for a ring surface: [base] (the conversation or caller)
89
+ * with the ring's workspace — only while several servers are signed in.
90
+ */
91
+ fun ringTitle(context: Context, ring: dev.poolse.callcore.RingContext, base: String?): String? =
92
+ CallServers.title(base, servers(context).workspaceLabel(ring.serverId, ring.workspaceName))
93
+
94
+ /** A server from the bridge's `addServer` map; null when it lacks an id or URL. */
95
+ fun fromMap(map: Map<String, Any?>): CallServer? {
96
+ val id = (map["id"] as? String)?.ifBlank { null } ?: return null
97
+ val url = (map["apiBaseUrl"] as? String)?.trimEnd('/')?.ifBlank { null } ?: return null
98
+ return CallServer(id, url, (map["tenantId"] as? String)?.ifBlank { null }, (map["name"] as? String)?.ifBlank { null })
99
+ }
100
+
101
+ fun toMap(server: CallServer): Map<String, Any?> = buildMap {
102
+ put("id", server.id)
103
+ put("apiBaseUrl", server.apiBaseUrl)
104
+ server.tenantId?.let { put("tenantId", it) }
105
+ server.name?.let { put("name", it) }
106
+ }
107
+ }