Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion app/src/main/java/com/anindra/messages/data/ReplyNudgePolicy.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@ object ReplyNudgePolicy {
/** A nudge per conversation per day at most, even if the thread stays open. */
const val REPEAT_HOURS = 24L

/**
* Past this age the thread is history, not a reply still owed (#604).
*
* The rule above only says how long to wait before reminding, so without a
* ceiling every read-but-unanswered conversation ever — including one from
* three months ago — came due on the first run with the switch on.
*/
const val MAX_AGE_HOURS = 24 * 7

val MAX_AGE_MILLIS: Long = MAX_AGE_HOURS * HOUR_MILLIS

fun intervalMillis(hours: Int): Long =
hours.coerceIn(1, 24 * 7).toLong() * HOUR_MILLIS

Expand All @@ -45,7 +56,8 @@ object ReplyNudgePolicy {
muted: Boolean,
lastNudgedAt: Long,
now: Long,
intervalMillis: Long
intervalMillis: Long,
maxAgeMillis: Long = MAX_AGE_MILLIS
): Boolean {
// A thread whose newest message is ours is answered by definition.
if (row.lastIsMine) return false
Expand All @@ -55,6 +67,9 @@ object ReplyNudgePolicy {
if (row.newest <= 0L) return false
// Not old enough yet: the reply may still be on its way.
if (now - row.newest < intervalMillis) return false
// Too old to be a reminder: the moment has passed, and a card for it is
// noise rather than a nudge.
if (now - row.newest > maxAgeMillis) return false
if (lastNudgedAt > 0 && now - lastNudgedAt < REPEAT_HOURS * HOUR_MILLIS) return false
return true
}
Expand Down
82 changes: 64 additions & 18 deletions app/src/main/java/com/anindra/messages/data/Repository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2917,13 +2917,16 @@ class Repository(private val context: Context) {
*/
fun replyNudgeRowsBlocking(): List<ReplyNudgeRow> {
val out = mutableListOf<ReplyNudgeRow>()
// The policy owns the age ceiling; this only keeps a long history from
// being loaded to reach it.
val oldest = System.currentTimeMillis() - ReplyNudgePolicy.MAX_AGE_MILLIS
db.readableDatabase.rawQuery(
"""SELECT id,address,snippet,timestamp,last_is_me,unread_count,archived,blocked,deleted_at
FROM conversations
WHERE deleted_at=0 AND archived=0 AND blocked=0
AND unread_count=0 AND last_is_me=0
AND unread_count=0 AND last_is_me=0 AND timestamp>=?
ORDER BY timestamp DESC""",
null
arrayOf(oldest.toString())
).use { c ->
while (c.moveToNext()) {
out.add(
Expand Down Expand Up @@ -3805,6 +3808,8 @@ class Repository(private val context: Context) {
return ImportResult.Error("Failed to replace database file", attempts)
}
db = Db(context)
// The swapped file carries its own blocklist.
blockedCache.clear()
// A restored backup should be fully visible: lift any
// conversations that were in the trash when the backup was made,
// and keep them out of the Archive for the same reason (#405).
Expand Down Expand Up @@ -3986,16 +3991,29 @@ class Repository(private val context: Context) {
val convoMap = HashMap<Long, Long>()
// Newest message per live conversation, refreshed only when merged rows are newer
val newest = HashMap<Long, Triple<Long, String, Int>>()
// Restored incoming messages make the conversation unread (like a fresh receive)
val unreadBump = HashMap<Long, Int>()
// Merging rows into a conversation already on this device must not
// make the whole thread unread again (#604); RestoreUnread decides
// how much of the backup's unread count is still genuinely new.
val restoredUnread = HashMap<Long, Int>()
val createdConversations = HashSet<Long>()
val inboundAdded = HashMap<Long, Int>()
// Blocked conversations restored before the blocklist table existed
// still have to show up on the Blocklist screen.
val restoredBlocks = ArrayList<Pair<String, Long>>()
target.beginTransaction()
try {
backup.rawQuery(
"""SELECT id,address,name,snippet,timestamp,unread_count,last_is_me,
archived,pinned,draft,draft_date,deleted_at FROM conversations""", null
).use { c ->
val conversationColumns = mutableSetOf<String>()
backup.rawQuery("PRAGMA table_info(conversations)", null).use { columns ->
while (columns.moveToNext()) conversationColumns.add(columns.getString(1))
}
val conversationQuery = LegacyBackupSchema.conversationsQuery(conversationColumns)
backup.rawQuery(conversationQuery, null).use { c ->
while (c.moveToNext()) {
val address = c.getString(1)
val blocked = c.getInt(LegacyBackupSchema.BLOCKED_INDEX) == 1
val blockedAt = c.getLong(LegacyBackupSchema.BLOCKED_AT_INDEX)
.takeIf { it > 0 } ?: c.getLong(4)
var isNew = false
val tId: Long =
if (existing.contains(address)) {
conflicts.count(Conflict.CONVERSATION_MERGED)
Expand All @@ -4009,7 +4027,7 @@ class Repository(private val context: Context) {
mergedId
} else {
existing.add(address)
target.insert(
val inserted = target.insert(
"conversations", null,
ContentValues().apply {
put("address", address)
Expand All @@ -4024,12 +4042,23 @@ class Repository(private val context: Context) {
put("draft_date", c.getLong(10))
// 0: lift conversations trashed in the backup
put("deleted_at", 0)
// Same: a restored blocked sender belongs
// under Spam & blocked, not in the inbox.
put("blocked", if (blocked) 1 else 0)
put("blocked_at", if (blocked) blockedAt else 0L)
}
)
if (inserted > 0) isNew = true
inserted
}
}
if (tId == -1L) continue
convoMap[c.getLong(0)] = tId
restoredUnread[tId] = c.getInt(5)
if (isNew) {
createdConversations.add(tId)
if (blocked) restoredBlocks.add(address to blockedAt)
}
}
}

Expand Down Expand Up @@ -4103,7 +4132,7 @@ class Repository(private val context: Context) {
conflicts.count(Conflict.RECORD_UNREADABLE)
}
if (isMe == 0) {
unreadBump[tId] = (unreadBump[tId] ?: 0) + 1
inboundAdded[tId] = (inboundAdded[tId] ?: 0) + 1
}
val snippet = when (m.getString(5)) {
"text" -> body
Expand All @@ -4124,21 +4153,35 @@ class Repository(private val context: Context) {
)
}

for ((tId, n) in unreadBump) {
for ((tId, incoming) in inboundAdded) {
val extra = RestoreUnread.toAdd(
conversationCreated = tId in createdConversations,
backupUnread = restoredUnread[tId] ?: 0,
incomingAdded = incoming
)
if (extra <= 0) continue
target.execSQL(
"UPDATE conversations SET unread_count=unread_count+? WHERE id=?",
arrayOf<Any?>(n, tId)
arrayOf<Any?>(extra, tId)
)
}

backup.rawQuery("SELECT number,timestamp FROM blocked_numbers", null).use { c ->
while (c.moveToNext()) {
target.execSQL(
"INSERT OR IGNORE INTO blocked_numbers(number,timestamp) VALUES(?,?)",
arrayOf(c.getString(0), c.getLong(1))
)
if (backupHasTable(backup, "blocked_numbers")) {
backup.rawQuery("SELECT number,timestamp FROM blocked_numbers", null).use { c ->
while (c.moveToNext()) {
target.execSQL(
"INSERT OR IGNORE INTO blocked_numbers(number,timestamp) VALUES(?,?)",
arrayOf(c.getString(0), c.getLong(1))
)
}
}
}
for ((address, at) in restoredBlocks) {
target.execSQL(
"INSERT OR IGNORE INTO blocked_numbers(number,timestamp) VALUES(?,?)",
arrayOf(address, at)
)
}

// conversation_notifications arrived after v8, so a backup from an
// older build simply does not have the table. Per-conversation
Expand Down Expand Up @@ -4178,6 +4221,9 @@ class Repository(private val context: Context) {
target.endTransaction()
}
}
// Blocked numbers can arrive from the backup; a cached "not blocked"
// would let the next message from one of them through.
blockedCache.clear()
return MergeReport(added, conflicts)
}

Expand Down
29 changes: 29 additions & 0 deletions app/src/main/java/com/anindra/messages/data/RestoreUnread.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.anindra.messages.data

/**
* How many unread messages a merge should add to a conversation it already had
* (#604).
*
* The database has no per-message read flag: read state lives in one number per
* conversation, `unread_count`, and the messages it covers are that thread's
* newest incoming ones. So a backup's read state is that number, and it must be
* carried — not re-derived by marking every restored message unread, which is
* what turned an 80-message thread into 80 unread after a restore.
*/
object RestoreUnread {

/**
* @param conversationCreated the row was inserted from the backup, so it
* already carries the backup's `unread_count` verbatim and needs nothing
* added.
* @param backupUnread the conversation's `unread_count` in the backup.
* @param incomingAdded incoming messages this merge actually inserted;
* some of the backup's unread ones may already have been on this device.
*
* A merge can only add what the backup could still account for: at most its
* unread count, and at most the messages it actually inserted.
*/
fun toAdd(conversationCreated: Boolean, backupUnread: Int, incomingAdded: Int): Int =
if (conversationCreated) 0
else minOf(backupUnread.coerceAtLeast(0), incomingAdded.coerceAtLeast(0))
}
31 changes: 31 additions & 0 deletions app/src/main/java/com/anindra/messages/data/SmsIeBackup.kt
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,33 @@ object LegacyBackupSchema {
return "SELECT $select FROM messages $where ORDER BY timestamp"
}

/**
* Absent in backups older than the blocklist. Blocking arrived after soft
* delete, so a backup can have `deleted_at` and still no `blocked` — the
* reason the same literal trick is needed for conversations.
*/
private val OPTIONAL_CONVERSATIONS = listOf("blocked" to "0", "blocked_at" to "0")

/** Every conversation column the merge reads, before the optional tail. */
private val REQUIRED_CONVERSATIONS = listOf(
"id", "address", "name", "snippet", "timestamp", "unread_count",
"last_is_me", "archived", "pinned", "draft", "draft_date", "deleted_at"
)

/**
* The conversation merge's SELECT, shaped the same way as [messagesQuery]:
* a missing optional column becomes a constant of the right type so the
* positional reads stay put.
*/
fun conversationsQuery(available: Set<String>): String {
val select = (REQUIRED_CONVERSATIONS + OPTIONAL_CONVERSATIONS.map { it.first })
.joinToString(",") { column ->
if (column in available) column
else OPTIONAL_CONVERSATIONS.first { it.first == column }.second
}
return "SELECT $select FROM conversations"
}

/**
* Provider ids are meaningful only on the device that issued them.
*
Expand All @@ -301,4 +328,8 @@ object LegacyBackupSchema {
const val LOCKED_INDEX = 9
const val SUB_ID_INDEX = 10
const val TRANSPORT_INDEX = 11

/** Same, for [conversationsQuery]. */
const val BLOCKED_INDEX = 12
const val BLOCKED_AT_INDEX = 13
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,34 @@ class LegacyBackupSchemaTest {
}
}

/** Conversations in a backup made before blocklisting existed: soft delete
* is there, `blocked` and `blocked_at` are not. */
private val preBlockColumns = setOf(
"id", "address", "name", "snippet", "timestamp", "unread_count",
"last_is_me", "archived", "pinned", "draft", "draft_date", "deleted_at"
)

@Test
fun aPreBlocklistConversationsQueryUsesLiteralsAndKeepsItsShape() {
val q = LegacyBackupSchema.conversationsQuery(preBlockColumns)
assertFalse("must not select a column the file lacks: $q", "blocked" in q)
assertTrue("blocked falls back to 0: $q", q.endsWith(",0,0 FROM conversations"))

fun select(cols: Set<String>) = LegacyBackupSchema.conversationsQuery(cols)
.removePrefix("SELECT ").substringBefore(" FROM")
.split(",").map { it.trim() }

val old = select(preBlockColumns)
val now = select(preBlockColumns + setOf("blocked", "blocked_at"))
assertEquals("column count must be stable", 14, old.size)
assertEquals(14, now.size)
assertEquals("deleted_at keeps index 11", "deleted_at", old[11])
assertEquals("blocked lands at 12", "0", old[LegacyBackupSchema.BLOCKED_INDEX])
assertEquals("blocked_at lands at 13", "0", old[LegacyBackupSchema.BLOCKED_AT_INDEX])
assertEquals("blocked", now[LegacyBackupSchema.BLOCKED_INDEX])
assertEquals("blocked_at", now[LegacyBackupSchema.BLOCKED_AT_INDEX])
}

@Test
fun theGeneratedQueryActuallyRunsAgainstARealOldBackup() {
// The real file is the user's, not part of the repo, so this only runs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,36 @@ class ReplyNudgePolicyTest {
)
}

@Test
fun aThreadFromMonthsAgoIsHistoryNotAReminder() {
val day = ReplyNudgePolicy.intervalMillis(24)
assertTrue(
"a week is still a reply the user meant to send",
ReplyNudgePolicy.shouldNudge(row(newest = now - 6 * 24 * hour), false, 0, now, day)
)
assertFalse(
"three months on, the message is history and a card for it is noise (#604)",
ReplyNudgePolicy.shouldNudge(row(newest = now - 90 * 24 * hour), false, 0, now, day)
)
assertTrue(
"the ceiling is a week",
ReplyNudgePolicy.MAX_AGE_MILLIS == 7 * 24 * hour
)
}

@Test
fun theQueryUsesTheSameCeilingAsThePolicy() {
val repo = src("java/com/anindra/messages/data/Repository.kt")
assertTrue(
"the prefilter must take its age from the policy, or the two drift",
repo.contains("ReplyNudgePolicy.MAX_AGE_MILLIS")
)
assertTrue(
"a conversation older than the ceiling cannot be a nudge candidate",
Regex("""timestamp>=\?""").containsMatchIn(repo)
)
}

@Test
fun anAnsweredThreadIsNeverNudged() {
assertFalse(
Expand Down
Loading