Skip to content

Commit 3e460e3

Browse files
committed
fix(push): correct notification state and previews
1 parent 5461646 commit 3e460e3

19 files changed

Lines changed: 2240 additions & 553 deletions

File tree

‎app/src/androidTest/java/org/monogram/push/ConversationShadeTest.kt‎

Lines changed: 379 additions & 0 deletions
Large diffs are not rendered by default.

‎app/src/main/java/org/monogram/push/NotificationPresenter.kt‎

Lines changed: 282 additions & 78 deletions
Large diffs are not rendered by default.

‎app/src/main/java/org/monogram/push/PushCoordinator.kt‎

Lines changed: 168 additions & 55 deletions
Large diffs are not rendered by default.

‎core/common/src/main/java/org/monogram/core/common/push/NotificationBatch.kt‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ data class NotificationMessage(
1313
val senderName: String? = null,
1414
val senderKey: String? = null,
1515
val topicId: Int? = null,
16+
val pictureUri: String? = null,
17+
val pictureMimeType: String = "image/jpeg",
18+
val edited: Boolean = false,
1619
)
1720

1821
/**
@@ -34,8 +37,27 @@ object NotificationBatch {
3437
max: Int = MAX_MESSAGES,
3538
): List<NotificationMessage> {
3639
if (max <= 0) return emptyList()
37-
val kept = existing.filterNot { it.isRepeatOf(incoming) }
38-
return (kept + incoming).takeLast(max)
40+
val index = existing.indexOfFirst { it.isRepeatOf(incoming) }
41+
if (index >= 0) {
42+
return existing.mapIndexed { i, message ->
43+
if (i == index && (!message.edited || incoming.edited)) incoming.copy(
44+
timestamp = message.timestamp,
45+
pictureUri = incoming.pictureUri ?: message.pictureUri,
46+
pictureMimeType = if (incoming.pictureUri == null) message.pictureMimeType else incoming.pictureMimeType,
47+
)
48+
else message
49+
}.takeLast(max)
50+
}
51+
return (existing + incoming).takeLast(max)
52+
}
53+
54+
fun attachPicture(
55+
existing: List<NotificationMessage>,
56+
messageId: Int,
57+
uri: String,
58+
mimeType: String = "image/jpeg",
59+
): List<NotificationMessage> = existing.map {
60+
if (it.messageId == messageId) it.copy(pictureUri = uri, pictureMimeType = mimeType) else it
3961
}
4062

4163
/**
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package org.monogram.core.common.push
2+
3+
/** Only message identities and cursors are persisted; notification bodies remain owned by Android. */
4+
data class NotificationLedger(
5+
val pending: Map<Int, Int?> = emptyMap(),
6+
val clearedThrough: Int = 0,
7+
val deleted: Set<Int> = emptySet(),
8+
) {
9+
fun accepts(messageId: Int): Boolean =
10+
messageId <= 0 || (messageId > clearedThrough && messageId !in deleted)
11+
12+
fun append(messageId: Int, topicId: Int?): NotificationLedger =
13+
if (messageId <= 0 || !accepts(messageId)) this
14+
else copy(
15+
pending = (pending + (messageId to topicId)).entries.toList().takeLast(MAX_PENDING)
16+
.associate { it.toPair() })
17+
18+
fun retain(dropIds: Set<Int>, upTo: Int?, topicId: Int? = null): NotificationLedger {
19+
val cursor = if (upTo == Int.MAX_VALUE) pending.keys.maxOrNull() ?: clearedThrough else upTo
20+
val removed = if (topicId == null) dropIds else
21+
pending.filter { (id, topic) -> topic == topicId && (id in dropIds || (cursor != null && id <= cursor)) }.keys
22+
val cleared =
23+
if (topicId == null && cursor != null) maxOf(clearedThrough, cursor) else clearedThrough
24+
return copy(
25+
pending = pending.filter { (id, topic) ->
26+
(topicId != null && topic != topicId) || (id !in removed && (cursor == null || id > cursor))
27+
},
28+
clearedThrough = cleared,
29+
deleted = (deleted + removed).filter { it > cleared }.takeLast(MAX_PENDING).toSet(),
30+
)
31+
}
32+
33+
fun dismiss(): NotificationLedger = copy(
34+
pending = emptyMap(), clearedThrough = maxOf(clearedThrough, pending.keys.maxOrNull() ?: 0),
35+
)
36+
37+
fun encode(): String = "$clearedThrough|" +
38+
pending.entries.joinToString(",") { (id, topic) -> "$id:${topic ?: 0}" } + "|" + deleted.joinToString(
39+
","
40+
)
41+
42+
companion object {
43+
const val MAX_PENDING = 4096
44+
45+
fun decode(value: String?): NotificationLedger {
46+
if (value == null) return NotificationLedger()
47+
val sections = value.split('|')
48+
val cursor = sections.firstOrNull()?.toIntOrNull() ?: return NotificationLedger()
49+
val deleted = sections.getOrNull(2).orEmpty().split(',').mapNotNull { it.toIntOrNull() }
50+
.filter { it > cursor }.takeLast(MAX_PENDING).toSet()
51+
val pending = sections.getOrNull(1).orEmpty().split(',').mapNotNull { entry ->
52+
val id = entry.substringBefore(':').toIntOrNull()
53+
?.takeIf { it > cursor && it !in deleted }
54+
?: return@mapNotNull null
55+
val topic = entry.substringAfter(':').toIntOrNull()?.takeIf { it > 0 }
56+
id to topic
57+
}.takeLast(MAX_PENDING).toMap()
58+
return NotificationLedger(pending, cursor, deleted)
59+
}
60+
}
61+
}

‎core/common/src/main/java/org/monogram/core/common/push/NotificationLocalStore.kt‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,29 @@ class NotificationLocalStore(context: Context) {
7373
get() = prefs.getLong(LAST_SHOWN_CHAT, 0L)
7474
set(value) { prefs.edit().putLong(LAST_SHOWN_CHAT, value).apply() }
7575

76+
fun notificationLedger(chatId: Long): NotificationLedger =
77+
NotificationLedger.decode(prefs.getString("notification_ledger_$chatId", null))
78+
79+
fun saveNotificationLedger(chatId: Long, ledger: NotificationLedger) {
80+
if (!prefs.edit().putString("notification_ledger_$chatId", ledger.encode()).commit()) {
81+
org.monogram.core.common.AppLog.warn(
82+
"notify",
83+
"notification identity persistence failed"
84+
)
85+
}
86+
}
87+
88+
fun notificationChatIds(): Set<Long> = prefs.all.keys.mapNotNull {
89+
it.takeIf { key -> key.startsWith("notification_ledger_") }
90+
?.removePrefix("notification_ledger_")?.toLongOrNull()
91+
}.toSet()
92+
93+
fun clearNotificationLedgers() {
94+
val editor = prefs.edit()
95+
prefs.all.keys.filter { it.startsWith("notification_ledger_") }.forEach(editor::remove)
96+
editor.commit()
97+
}
98+
7699
fun categoryVibrate(kind: String): Boolean = prefs.getBoolean("${kind}_vibrate", true)
77100
fun setCategoryVibrate(kind: String, value: Boolean) {
78101
prefs.edit().putBoolean("${kind}_vibrate", value).apply()

‎core/common/src/main/java/org/monogram/core/common/push/PushPayload.kt‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,8 @@ fun liveMessagePayload(
121121
val body = text?.takeIf { it.isNotBlank() } ?: fileName?.takeIf { it.isNotBlank() } ?: ""
122122
return PushPayload(
123123
locKey = locKey,
124-
locArgs = listOf(shownTitle, body),
124+
locArgs = if (kind == PushChannelKind.Group) listOf(senderName.orEmpty(), shownTitle, body)
125+
else listOf(shownTitle, body),
125126
title = shownTitle,
126127
body = body,
127128
chatId = chatId,

‎core/common/src/test/java/org/monogram/core/common/push/NotificationBatchTest.kt‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,44 @@ class NotificationBatchTest {
1919
val retried = NotificationBatch.append(batch, message(2, "two", at = 500L))
2020
assertEquals(2, retried.size)
2121
assertEquals(listOf(1, 2), retried.map { it.messageId })
22-
assertEquals(500L, retried.last().timestamp)
22+
assertEquals(0L, retried.last().timestamp)
23+
}
24+
25+
@Test
26+
fun staleDuplicateCannotOverwriteAnAuthoritativeEdit() {
27+
val edited = message(1, "edited", 10L).copy(edited = true, pictureUri = "content://photo/1")
28+
val batch = listOf(edited, message(2, "newer", 20L))
29+
assertEquals(batch, NotificationBatch.append(batch, message(1, "original", 30L)))
30+
val updated = NotificationBatch.append(batch, edited.copy(text = "edited again"))
31+
assertEquals("edited again", updated.first().text)
32+
assertEquals(updated, NotificationBatch.append(updated, message(1, "original", 40L)))
33+
}
34+
35+
@Test
36+
fun editingOlderMessagePreservesOrderAndAttachment() {
37+
val batch = listOf(
38+
message(1, "old", 10L).copy(
39+
pictureUri = "content://photo/1",
40+
pictureMimeType = "image/webp"
41+
), message(2, "new", 20L)
42+
)
43+
val edited = NotificationBatch.append(batch, message(1, "edited", 99L))
44+
assertEquals(listOf(1, 2), edited.map { it.messageId })
45+
assertEquals("edited", edited.first().text)
46+
assertEquals(10L, edited.first().timestamp)
47+
assertEquals("content://photo/1", edited.first().pictureUri)
48+
assertEquals("image/webp", edited.first().pictureMimeType)
49+
}
50+
51+
@Test
52+
fun latePictureUpdatesOnlyItsMessageAndDoesNotResurrectDeletedMessages() {
53+
val batch = listOf(message(1, "photo"), message(2, "text"))
54+
val refreshed = NotificationBatch.attachPicture(batch, 1, "content://photo/1")
55+
assertEquals("content://photo/1", refreshed.first().pictureUri)
56+
assertEquals(null, refreshed.last().pictureUri)
57+
val deleted = NotificationBatch.retain(refreshed, dropIds = setOf(1))
58+
assertEquals(deleted, NotificationBatch.attachPicture(deleted, 1, "content://photo/1"))
59+
assertEquals(refreshed, NotificationBatch.append(refreshed, message(2, "text")))
2360
}
2461

2562
@Test
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package org.monogram.core.common.push
2+
3+
import org.junit.Assert.assertEquals
4+
import org.junit.Assert.assertFalse
5+
import org.junit.Assert.assertTrue
6+
import org.junit.Test
7+
8+
class NotificationLedgerTest {
9+
@Test
10+
fun countAndDuplicateIdentitySurviveSerializationBeyondVisibleHistory() {
11+
var state = NotificationLedger()
12+
repeat(20) { state = state.append(it + 1, null) }
13+
val restored = NotificationLedger.decode(state.encode())
14+
assertEquals(20, restored.pending.size)
15+
assertEquals(restored, restored.append(2, null))
16+
assertEquals(20, restored.append(2, null).pending.size)
17+
}
18+
19+
@Test
20+
fun readAndDeleteMarkersPreventRedeliveryAcrossRestart() {
21+
val state = NotificationLedger().append(1, null).append(3, null).append(5, null)
22+
.retain(setOf(3), 1)
23+
val restored = NotificationLedger.decode(state.encode())
24+
assertFalse(restored.accepts(1))
25+
assertFalse(restored.accepts(3))
26+
assertTrue(restored.accepts(2))
27+
assertEquals(setOf(5), restored.pending.keys)
28+
assertEquals(setOf(5), restored.append(3, null).pending.keys)
29+
}
30+
31+
@Test
32+
fun dismissalAndUnboundedReadDoNotBlockFutureMessages() {
33+
val state = NotificationLedger().append(3, null).append(5, null)
34+
for (cleared in listOf(state.dismiss(), state.retain(emptySet(), Int.MAX_VALUE))) {
35+
val restored = NotificationLedger.decode(cleared.encode())
36+
assertFalse(restored.accepts(5))
37+
assertTrue(restored.accepts(6))
38+
assertEquals(setOf(6), restored.append(6, null).pending.keys)
39+
}
40+
}
41+
42+
@Test
43+
fun topicReadKeepsOtherTopicsAndSurvivesRestart() {
44+
val state = NotificationLedger().append(1, 10).append(2, 20).append(3, 10)
45+
.retain(emptySet(), 2, 10)
46+
val restored = NotificationLedger.decode(state.encode())
47+
assertEquals(setOf(2, 3), restored.pending.keys)
48+
assertTrue(restored.accepts(2))
49+
assertFalse(restored.accepts(1))
50+
}
51+
52+
@Test
53+
fun malformedStorageIsSafeAndStateIsBounded() {
54+
assertEquals(NotificationLedger(), NotificationLedger.decode("invalid"))
55+
val encoded = "0|" + (1..5000).joinToString(",") { "$it:0" } + "|"
56+
assertEquals(
57+
NotificationLedger.MAX_PENDING,
58+
NotificationLedger.decode(encoded).pending.size
59+
)
60+
}
61+
}

‎core/common/src/test/java/org/monogram/core/common/push/PushPayloadTest.kt‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,18 @@ import org.monogram.core.models.PeerId
99
import org.monogram.core.models.PushTokenType
1010

1111
class PushPayloadTest {
12+
@Test
13+
fun liveGroupMessageKeepsSenderAndConversationSeparate() {
14+
val payload = liveMessagePayload(
15+
-5L, 10, false, "hello", null, "Ada", 42L, "Group", PushChannelKind.Group,
16+
)!!
17+
val style = conversationStyle(payload, false, 0L, 10_000L)
18+
assertEquals("Group", style.conversationTitle)
19+
assertEquals("Ada", style.messageSenderName)
20+
assertEquals("peer:42", style.messagePersonKey)
21+
assertEquals("hello", payload.body)
22+
}
23+
1224
@Test
1325
fun tokenTypesMatchTelegramDocs() {
1426
assertEquals(2, PushTokenType.Fcm.code)

0 commit comments

Comments
 (0)