-
Notifications
You must be signed in to change notification settings - Fork 19
/
MessageNotificationManager.kt
513 lines (428 loc) · 23.3 KB
/
MessageNotificationManager.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
/*
* Wire
* Copyright (C) 2023 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*
*/
package com.wire.android.notification
import android.app.Notification
import android.app.NotificationManager
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.BitmapDrawable
import android.service.notification.StatusBarNotification
import android.text.Spannable
import android.text.style.StyleSpan
import androidx.annotation.StringRes
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.Person
import androidx.core.graphics.drawable.IconCompat
import androidx.core.text.toSpannable
import com.wire.android.R
import com.wire.android.appLogger
import com.wire.android.notification.NotificationConstants.getConversationNotificationId
import com.wire.android.ui.home.appLock.LockCodeTimeManager
import com.wire.android.util.toBitmap
import com.wire.kalium.logic.data.id.ConversationId
import com.wire.kalium.logic.data.id.QualifiedID
import com.wire.kalium.logic.data.notification.LocalNotification
import com.wire.kalium.logic.data.notification.LocalNotificationUpdateMessageAction
import javax.inject.Inject
import javax.inject.Singleton
@Suppress("TooManyFunctions")
@Singleton
class MessageNotificationManager
@Inject constructor(
private val context: Context,
private val notificationManagerCompat: NotificationManagerCompat,
private val notificationManager: NotificationManager,
private val lockCodeTimeManager: LockCodeTimeManager
) {
fun handleNotification(newNotifications: List<LocalNotification>, userId: QualifiedID, userName: String) {
if (newNotifications.isEmpty()) return
addNotifications(newNotifications, userId, userName)
updateNotifications(newNotifications, userId)
appLogger.i("$TAG: handled notifications: newNotifications size ${newNotifications.size}; ")
}
private fun addNotifications(newNotifications: List<LocalNotification>, userId: QualifiedID, userName: String) {
val notificationsToAdd: List<LocalNotification.Conversation> = newNotifications
.filterIsInstance(LocalNotification.Conversation::class.java)
val activeNotifications: Array<StatusBarNotification> = notificationManager.activeNotifications ?: arrayOf()
notificationsToAdd.forEach {
showConversationNotification(it, userId, activeNotifications)
}
showSummaryIfNeeded(userId, activeNotifications, userName)
appLogger.i("$TAG: added notifications: newNotifications size ${notificationsToAdd.size}; ")
}
private fun updateNotifications(newNotifications: List<LocalNotification>, userId: QualifiedID) {
val notificationsToUpdate: List<LocalNotification.UpdateMessage> = newNotifications
.filterIsInstance(LocalNotification.UpdateMessage::class.java)
val activeNotifications: Array<StatusBarNotification> = notificationManager.activeNotifications ?: return
notificationsToUpdate.groupBy { it.conversationId }.forEach { (conversationId, updateMessages) ->
updateConversationNotification(conversationId, updateMessages, userId, activeNotifications)
}
removeSummaryIfNeeded(userId)
appLogger.i("$TAG: added notifications: newNotifications size ${notificationsToUpdate.size}; ")
}
fun hideNotification(conversationsId: ConversationId, userId: QualifiedID) {
val notificationId = getConversationNotificationId(conversationsId.toString(), userId.toString())
if (isThereAnyOtherWireNotification(userId, notificationId)) {
notificationManagerCompat.cancel(notificationId)
} else {
hideAllNotificationsForUser(userId)
}
}
fun hideAllNotifications() {
notificationManager.cancelAll()
}
fun hideAllNotificationsForUser(userId: QualifiedID) {
// removing groupSummary removes all the notifications in a group
notificationManagerCompat.cancel(NotificationConstants.getMessagesSummaryId(userId))
}
private fun showSummaryIfNeeded(userId: QualifiedID, activeNotifications: Array<StatusBarNotification>, userName: String) {
if (activeNotifications.find { it.id == NotificationConstants.getMessagesSummaryId(userId) } != null) return
appLogger.i("$TAG adding groupSummary")
notificationManager.notify(NotificationConstants.getMessagesSummaryId(userId), getSummaryNotification(userId, userName))
}
private fun removeSummaryIfNeeded(userId: QualifiedID) {
if (!isThereAnyOtherWireNotification(userId)) {
hideAllNotificationsForUser(userId)
}
}
private fun showConversationNotification(
localConversation: LocalNotification.Conversation,
userId: QualifiedID,
activeNotifications: Array<StatusBarNotification>
) {
val conversation = localConversation.intoNotificationConversation()
val notificationId = getConversationNotificationId(conversation.id, userId.toString())
getConversationNotification(conversation, userId, activeNotifications)?.let { notification ->
appLogger.i("$TAG adding ConversationNotification")
notificationManagerCompat.notify(notificationId, notification)
}
}
private fun updateConversationNotification(
conversationId: ConversationId,
updateMessages: List<LocalNotification.UpdateMessage>,
userId: QualifiedID,
activeNotifications: Array<StatusBarNotification>
) {
val notificationId = getConversationNotificationId(conversationId.toString(), userId.toString())
getUpdatedConversationNotification(notificationId, userId, updateMessages, activeNotifications)?.let { notification ->
appLogger.i("$TAG updating ConversationNotification")
notificationManagerCompat.notify(notificationId, notification)
} ?: notificationManagerCompat.cancel(notificationId)
}
private fun getSummaryNotification(userId: QualifiedID, userName: String): Notification {
val channelId = NotificationConstants.getMessagesChannelId(userId)
return NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.notification_icon_small)
.setGroup(NotificationConstants.getMessagesGroupKey(userId))
.setStyle(NotificationCompat.InboxStyle().setSummaryText(userName))
.setGroupSummary(true)
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(summaryMessagePendingIntent(context))
.build()
}
/**
* Creates or updates existing [Notification]
* @param [conversation] the notification object containing all the messages for the given conversation
* @param [userId] the id of the user receiving the notifications
* @param [activeNotifications] a list with the notifications that are already be displayed to the user
* @return [Notification] for the conversation with all the messages in it (including previous messages as well)
* OR null if there is no new messages in conversation and no need to update the existed notification.
*/
private fun getConversationNotification(
conversation: NotificationConversation,
userId: QualifiedID,
activeNotifications: Array<StatusBarNotification>
): Notification? {
val userIdString = userId.toString()
val updatedMessageStyle = activeNotifications
.find { it.id == getConversationNotificationId(conversation.id, userIdString) }
?.notification
?.let { NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(it) }
.addMessages(conversation)
?: return null
return setUpNotificationBuilder(context, userId)
.apply {
conversation.messages.firstOrNull()
.let {
when (it) {
is NotificationMessage.ConnectionRequest -> {
setContentIntent(otherUserProfilePendingIntent(context, it.authorId, userIdString))
}
is NotificationMessage.ConversationDeleted -> {
setContentIntent(openAppPendingIntent(context))
}
is NotificationMessage.Comment -> {
val isAppLocked = lockCodeTimeManager.isAppLocked()
setContentIntent(messagePendingIntent(context, conversation.id, userIdString))
addAction(getActionReply(context, conversation.id, userIdString, isAppLocked))
}
is NotificationMessage.Knock -> {
setChannelId(NotificationConstants.getPingsChannelId(userId))
setContentIntent(messagePendingIntent(context, conversation.id, userIdString))
}
is NotificationMessage.Text -> {
val isAppLocked = lockCodeTimeManager.isAppLocked()
setContentIntent(messagePendingIntent(context, conversation.id, userIdString))
addAction(getActionReply(context, conversation.id, userIdString, isAppLocked))
}
is NotificationMessage.ObfuscatedMessage -> {
val isAppLocked = lockCodeTimeManager.isAppLocked()
setContentIntent(messagePendingIntent(context, conversation.id, userIdString))
addAction(getActionReply(context, conversation.id, userIdString, isAppLocked))
}
is NotificationMessage.ObfuscatedKnock -> {
setChannelId(NotificationConstants.getPingsChannelId(userId))
setContentIntent(messagePendingIntent(context, conversation.id, userIdString))
}
null -> {
val isAppLocked = lockCodeTimeManager.isAppLocked()
setContentIntent(messagePendingIntent(context, conversation.id, userIdString))
addAction(getActionReply(context, conversation.id, userIdString, isAppLocked))
}
}
}
setWhen(conversation.lastMessageTime)
setLargeIcon(conversation.image?.toBitmap())
setStyle(updatedMessageStyle)
}.build()
}
/**
* Updates existing [Notification] by applying changes to it's messages
* @param [notificationId] ID of the notification that should be updated
* @param [userId] the id of the user receiving the notifications
* @param [updateMessages] list of changes that should be applied to the messages in that notification
* @param [activeNotifications] a list with the notifications that are already be displayed to the user
* @return [Notification] for the conversation with updated messages in it
* OR null if all the messages in notification were removed and Notification should be removed too.
*/
private fun getUpdatedConversationNotification(
notificationId: Int,
userId: QualifiedID,
updateMessages: List<LocalNotification.UpdateMessage>,
activeNotifications: Array<StatusBarNotification>
): Notification? {
val currentNotification = activeNotifications
.find { it.id == notificationId }
?.notification
val updatedMessageStyle = currentNotification?.updateMessages(updateMessages)
if (updatedMessageStyle == null || updatedMessageStyle.messages.isEmpty()) return null
return setUpNotificationBuilder(context, userId).apply {
setContentIntent(currentNotification.contentIntent)
currentNotification.actions?.forEach { addAction(getActionFromOldOne(it)) }
setWhen(System.currentTimeMillis())
setLargeIcon((currentNotification.getLargeIcon()?.loadDrawable(context) as BitmapDrawable?)?.bitmap)
setStyle(updatedMessageStyle)
}.build()
}
/**
* @return [NotificationCompat.Style] that should be set to Notification with all the messages in it,
* OR null if there is no new messages in conversation and no need to update the existed notification
*/
private fun NotificationCompat.MessagingStyle?.addMessages(conversation: NotificationConversation): NotificationCompat.Style? {
val messagesToAdd = conversation.messages
.map { it.intoStyledMessage() }
.filter { notificationMessage ->
// to not notify about messages that are already there
this?.messages
?.find {
it.text.toString() == notificationMessage.text.toString()
&& it.timestamp == notificationMessage.timestamp
} == null
}
if (messagesToAdd.isEmpty()) {
// there is nothing to add to this notification
return null
}
val receiver = youPerson(context)
val notificationStyle = NotificationCompat.MessagingStyle(receiver)
notificationStyle.conversationTitle = getConversationTitle(conversation)
notificationStyle.isGroupConversation = !conversation.isOneToOneConversation
this?.messages?.forEach { notificationMessage ->
notificationStyle.addMessage(notificationMessage)
}
messagesToAdd.forEach { notificationMessage ->
notificationStyle.addMessage(notificationMessage)
}
return notificationStyle
}
/**
* @return [NotificationCompat.MessagingStyle] that should be set to Notification with all the messages in it,
* OR null if there is no new messages in conversation and no need to update the existed notification
*/
private fun Notification.updateMessages(updateMessages: List<LocalNotification.UpdateMessage>): NotificationCompat.MessagingStyle? {
val activeStyledNotification = this
.let { NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(it) }
?: return null
val messagesToShow = mutableListOf<NotificationCompat.MessagingStyle.Message>()
activeStyledNotification.messages
.forEach { message ->
val updateMessageAction = updateMessages
.firstOrNull { it.messageId == message.extras.getString(MESSAGE_ID_EXTRA) }
?.action
when (updateMessageAction) {
null -> messagesToShow.add(message)
is LocalNotificationUpdateMessageAction.Edit -> {
messagesToShow.add(
NotificationCompat.MessagingStyle.Message(
updateMessageAction.updateText,
message.timestamp,
message.person
).apply {
extras.putString(MESSAGE_ID_EXTRA, updateMessageAction.newMessageId)
}
)
}
is LocalNotificationUpdateMessageAction.Delete -> {
// message was removed, do nothing
}
}
}
val receiver = youPerson(context)
val notificationStyle = NotificationCompat.MessagingStyle(receiver)
notificationStyle.conversationTitle = activeStyledNotification.conversationTitle
notificationStyle.isGroupConversation = activeStyledNotification.isGroupConversation
messagesToShow.forEach { notificationMessage ->
notificationStyle.addMessage(notificationMessage)
}
return notificationStyle
}
private fun getConversationTitle(conversation: NotificationConversation): String? =
if (conversation.isOneToOneConversation) null else conversation.name
private fun italicTextFromResId(@StringRes stringResId: Int): Spannable {
return context.getString(stringResId)
.let {
// On some devices typeface used by default in notifications doesn't support italic, system will fake it by skewing the
// glyphs using `textPaint.textSkewX = -0.25f`, but the width won't be adjusted so we have to add a space after the text.
// https://saket.me/android-fake-vs-true-bold-and-italic/
"$it "
}
.toSpannable()
.apply {
setSpan(StyleSpan(Typeface.ITALIC), 0, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
private fun NotificationMessage.intoStyledMessage(): NotificationCompat.MessagingStyle.Message {
val sender = Person.Builder()
.apply {
if (this@intoStyledMessage is NotificationMessage.ObfuscatedMessage) {
setName(context.getString(R.string.notification_obfuscated_message_title))
} else {
author?.name.also {
setName(it)
}
author?.image?.toBitmap()?.let {
setIcon(IconCompat.createWithAdaptiveBitmap(it))
}
}
}
.build()
val message = when (this@intoStyledMessage) {
is NotificationMessage.Text -> if (isQuotingSelfUser) context.getString(R.string.notification_reply, text) else text
is NotificationMessage.Comment -> italicTextFromResId(textResId.value)
is NotificationMessage.ConnectionRequest -> italicTextFromResId(R.string.notification_connection_request)
is NotificationMessage.ConversationDeleted -> italicTextFromResId(R.string.notification_conversation_deleted)
is NotificationMessage.Knock -> italicTextFromResId(R.string.notification_knock)
is NotificationMessage.ObfuscatedMessage,
is NotificationMessage.ObfuscatedKnock -> italicTextFromResId(
R.string.notification_obfuscated_message_content
)
}
return NotificationCompat.MessagingStyle.Message(message, time, sender).apply {
extras.putString(MESSAGE_ID_EXTRA, this@intoStyledMessage.messageId)
}
}
/**
* @return true if there is at least one Wire message notification except the Summary notification
* and notifications with id [exceptNotificationIds]
*/
private fun isThereAnyOtherWireNotification(userId: QualifiedID, vararg exceptNotificationIds: Int): Boolean {
return notificationManager.activeNotifications
?.any {
it.groupKey.endsWith(NotificationConstants.getMessagesGroupKey(userId))
&& !exceptNotificationIds.contains(it.id)
&& it.id != NotificationConstants.getMessagesSummaryId(userId)
}
?: false
}
companion object {
private const val TAG = "MessageNotificationManager"
private const val MESSAGE_ID_EXTRA = "message_id"
/**
* Update notification by adding [replyText] to the end of messages list with "You" as sender.
* Do nothing if there is no notification for [conversationId] conversation,
* or that notification is not in [NotificationCompat.MessagingStyle].
* @param context Context
* @param conversationId String ConversationId that reply was sent in.
* @param userId String UserId of the user that is replied.
* @param replyText String text the user replied to the conversation.
* If it's null then just update the notification to remove send reply loading.
*/
fun updateNotificationAfterQuickReply(
context: Context,
conversationId: String,
userId: QualifiedID,
replyText: String?
) {
val conversationNotificationId = getConversationNotificationId(conversationId, userId.toString())
val userIdString = userId.toString()
val currentNotification = (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
.activeNotifications
.find { it.id == conversationNotificationId }
?.notification
?: return // if there is no notification for this conversation, then there is nothing to update
val messagesStyle = NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(currentNotification)
?: return // if notification is not in MessagingStyle, then we can't update it
val sender = youPerson(context)
replyText?.let {
val replyMessage = NotificationCompat.MessagingStyle.Message(replyText, System.currentTimeMillis(), sender)
messagesStyle.addMessage(replyMessage)
}
val notification = setUpNotificationBuilder(context, userId).apply {
setContentIntent(messagePendingIntent(context, conversationId, userIdString))
addAction(getActionReply(context, conversationId, userIdString, false))
setWhen(System.currentTimeMillis())
setLargeIcon((currentNotification.getLargeIcon()?.loadDrawable(context) as BitmapDrawable?)?.bitmap)
setStyle(messagesStyle)
}.build()
NotificationManagerCompat.from(context).notify(conversationNotificationId, notification)
}
private fun youPerson(context: Context) = Person.Builder()
.setName(context.getString(R.string.notification_receiver_name))
.build()
/**
* Create NotificationBuilder and set all the parameters that are common for any MessageNotification
* @return resulted [NotificationCompat.Builder] so we can set other specific parameters and build it.
*/
private fun setUpNotificationBuilder(context: Context, userId: QualifiedID): NotificationCompat.Builder {
val channelId = NotificationConstants.getMessagesChannelId(userId)
return NotificationCompat.Builder(context, channelId).apply {
setDefaults(NotificationCompat.DEFAULT_ALL)
priority = NotificationCompat.PRIORITY_MAX
setCategory(NotificationCompat.CATEGORY_MESSAGE)
setSmallIcon(R.drawable.notification_icon_small)
setGroup(NotificationConstants.getMessagesGroupKey(userId))
setAutoCancel(true)
}
}
}
}