email: fix Outlook inbox missing from unified inbox
- Commit
1602f9df9d3851c9cfca834c6e5ba2b0649fb360- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-05 02:40 UTC (4 months ago)
- Parents
afc71d4
Diff
email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.ktindex f7b96aa34f..950027bbd7 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt@@ -25,7 +25,7 @@ import com.vayunmathur.email.Attachment BlockedSender::class, DeletedUid::class, ],- version = 18,+ version = 19, exportSchema = false, ) abstract class EmailDatabase : RoomDatabase() {@@ -96,6 +96,40 @@ abstract class EmailDatabase : RoomDatabase() { it.execSQL("ALTER TABLE DraftEntry ADD COLUMN inlineImageJson TEXT NOT NULL DEFAULT '[]'") } + /**+ * Office 365 / Exchange IMAP reports the inbox as "Inbox", while Gmail and+ * friends report "INBOX". RFC 3501 defines the name case-insensitively, but+ * SQLite TEXT comparison is not, so Outlook rows persisted as "Inbox" never+ * matched the `folderName = 'INBOX'` predicate behind the unified inbox.+ * Fold those legacy rows onto the canonical name. `OR REPLACE` collapses the+ * duplicates created when the IDLE push path (which hardcoded "INBOX") and+ * the sync worker (which used the server's casing) both stored the same UID.+ */+ private val MIGRATION_18_19 = Migration(18, 19) {+ // Matches a mixed-case spelling of the inbox itself ("Inbox", "inbox", ...).+ fun isInbox(column: String) = "$column <> 'INBOX' AND $column = 'INBOX' COLLATE NOCASE"++ // Matches a child of a mixed-case inbox, e.g. "Inbox/Receipts" or "Inbox.Receipts".+ fun isUnderInbox(column: String) =+ "length($column) > 5 AND substr($column, 1, 5) = 'INBOX' COLLATE NOCASE " ++ "AND substr($column, 1, 5) <> 'INBOX' AND substr($column, 6, 1) IN ('/', '.')"++ // Rewrites just the leading "Inbox" segment, preserving the rest of the path.+ fun canonical(column: String) = "'INBOX' || substr($column, 6)"++ for ((table, column) in listOf(+ "EmailMessage" to "folderName",+ "DeletedUid" to "folderName",+ "Attachment" to "folderName",+ "EmailFolder" to "fullName",+ )) {+ it.execSQL("UPDATE OR REPLACE $table SET $column = 'INBOX' WHERE ${isInbox(column)}")+ it.execSQL("UPDATE OR REPLACE $table SET $column = ${canonical(column)} WHERE ${isUnderInbox(column)}")+ }+ it.execSQL("UPDATE EmailFolder SET parentFullName = 'INBOX' WHERE ${isInbox("parentFullName")}")+ it.execSQL("UPDATE EmailFolder SET parentFullName = ${canonical("parentFullName")} WHERE ${isUnderInbox("parentFullName")}")+ }+ private val MIGRATION_5_6 = Migration(5, 6) { it.execSQL("ALTER TABLE EmailMessage ADD COLUMN dateMillis INTEGER NOT NULL DEFAULT 0") }@@ -146,7 +180,7 @@ abstract class EmailDatabase : RoomDatabase() { fun getInstance(context: Context): EmailDatabase { return instance ?: synchronized(this) { instance ?: context.applicationContext.buildDatabase<EmailDatabase>(- migrations = listOf(MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17, MIGRATION_17_18),+ migrations = listOf(MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19), dbName = "email-db" ).also { instance = it } }
email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.ktindex 6a242d3db4..80cb50d1ea 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt@@ -46,7 +46,7 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) : val skipSet = if (account.provider == PROVIDER_GMAIL) ImapClient.GMAIL_VIRTUAL_FOLDERS else emptySet() val messageFolders = if (nonInboxOnly) {- folders.filter { it.holdsMessages && it.fullName !in skipSet && it.fullName != "INBOX" }+ folders.filter { it.holdsMessages && it.fullName !in skipSet && it.fullName != ImapClient.INBOX } } else { folders.filter { it.holdsMessages && it.fullName !in skipSet } }@@ -70,11 +70,11 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) : if (attachments.isNotEmpty()) dao.insertAttachments(attachments) if (!nonInboxOnly) {- if (knownUids.isNotEmpty() && folder.fullName == "INBOX") {+ if (knownUids.isNotEmpty() && folder.fullName == ImapClient.INBOX) { syncReadStatusRaw(applicationContext, account, folder.fullName, knownUids) } - if (folder.fullName == "INBOX" && messages.isNotEmpty()) {+ if (folder.fullName == ImapClient.INBOX && messages.isNotEmpty()) { val lastSeen = lastSeenPrefs(applicationContext) .getLong(lastSeenKey(account.email, folder.fullName), -1L) if (lastSeen >= 0L && !com.vayunmathur.email.util.AppLifecycleTracker.isAppInForeground) {
email/src/main/java/com/vayunmathur/email/imap/ImapClient.kt
diff --git a/email/src/main/java/com/vayunmathur/email/imap/ImapClient.kt b/email/src/main/java/com/vayunmathur/email/imap/ImapClient.ktindex b7a321db2a..45fa1eed2a 100644--- a/email/src/main/java/com/vayunmathur/email/imap/ImapClient.kt+++ b/email/src/main/java/com/vayunmathur/email/imap/ImapClient.kt@@ -22,6 +22,37 @@ object ImapClient { private const val TAG = "ImapClient" + /**+ * Canonical inbox mailbox name. RFC 3501 §5.1 defines INBOX case-insensitively,+ * so servers are free to report it however they like — Gmail/Yahoo/iCloud return+ * `INBOX`, but Office 365 / Exchange returns `Inbox`. Every inbox query in the app+ * (per-account *and* the unified inbox) matches on this exact literal, and SQLite+ * TEXT comparison is case-sensitive, so all persisted folder names must be folded+ * to this constant via [canonicalizeMailbox] before they hit the DB.+ */+ const val INBOX = "INBOX"++ /**+ * Folds a server-reported mailbox path to its canonical form, so `Inbox` and+ * `Inbox/Receipts` (Office 365) are stored the same way as `INBOX` and+ * `INBOX/Receipts` (Gmail). Non-inbox mailboxes are returned untouched — only the+ * inbox has spec-mandated case-insensitivity.+ *+ * @param delimiter the server's hierarchy delimiter; when unknown, the two common+ * ones (`/` and `.`) are both accepted.+ */+ fun canonicalizeMailbox(mailbox: String, delimiter: String? = null): String {+ if (mailbox.equals(INBOX, ignoreCase = true)) return INBOX+ if (mailbox.length <= INBOX.length) return mailbox+ if (!mailbox.regionMatches(0, INBOX, 0, INBOX.length, ignoreCase = true)) return mailbox+ val delims = if (delimiter.isNullOrEmpty()) listOf("/", ".") else listOf(delimiter)+ return if (delims.any { mailbox.startsWith(it, INBOX.length) }) {+ INBOX + mailbox.substring(INBOX.length)+ } else {+ mailbox+ }+ }+ val GMAIL_VIRTUAL_FOLDERS = setOf( "[Gmail]/All Mail", "[Gmail]/Important",@@ -83,9 +114,12 @@ object ImapClient { withConnection(server, user, auth) { conn -> val entries = conn.list("", "*") entries.map { entry ->- val fullName = entry.mailbox val delim = entry.delimiter ?: "/"- val name = if (fullName.contains(delim)) fullName.substringAfterLast(delim) else fullName.substringAfterLast('/')+ // Identify the folder by its canonical path, but keep the server's own+ // casing for the drawer label so Outlook still reads "Inbox", not "INBOX".+ val fullName = canonicalizeMailbox(entry.mailbox, delim)+ val displayPath = entry.mailbox+ val name = if (displayPath.contains(delim)) displayPath.substringAfterLast(delim) else displayPath.substringAfterLast('/') val parent = fullName.lastIndexOf(delim).let { if (it > 0) fullName.substring(0, it).takeIf { it.isNotEmpty() } else null } val holds = !entry.flags.any { it.equals("\\Noselect", ignoreCase = true) } EmailFolder(accountEmail = user, fullName = fullName, name = name.ifBlank { fullName }, parentFullName = parent, holdsMessages = holds, delimiter = delim)@@ -117,7 +151,11 @@ object ImapClient { skipUids: Set<Long>, context: Context?, ): Pair<List<EmailMessage>, List<Attachment>> {+ // SELECT with the exact name the server gave us, but persist under the+ // canonical one so an Office 365 "Inbox" lands in the same bucket as a+ // Gmail "INBOX" (see [canonicalizeMailbox]). val sel = conn.select(folderName)+ val storedFolderName = canonicalizeMailbox(folderName) val total = sel.exists if (total == 0) return Pair(emptyList(), emptyList()) val end = (total - offset).coerceAtLeast(1)@@ -145,7 +183,7 @@ object ImapClient { var isHtmlFlag = false var hasAtt = false if (fetchBodies && fr.bodyBytes != null) {- val triple = try { MimeParser.parseMessage(fr.bodyBytes, fr.uid, user, folderName, context) } catch (_: Exception) { Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) }+ val triple = try { MimeParser.parseMessage(fr.bodyBytes, fr.uid, user, storedFolderName, context) } catch (_: Exception) { Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) } body = triple.first isHtmlFlag = triple.second allAttachments.addAll(triple.third)@@ -155,7 +193,7 @@ object ImapClient { messages.add( EmailMessage( accountEmail = user,- folderName = folderName,+ folderName = storedFolderName, id = fr.uid, serverId = headerMap["message-id"], threadId = gmThrid ?: fr.uid.toString(),@@ -190,7 +228,7 @@ object ImapClient { val res = conn.uidFetchFullSet(uid.toString()).firstOrNull() ?: return@withConnection Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) val bytes = res.bodyBytes ?: return@withConnection Triple(null, false, emptyList())- try { MimeParser.parseMessage(bytes, uid, user, folderName, context) } catch (e: Exception) { Log.w(TAG, "parse failed ${e.message}"); Triple(null, false, emptyList()) }+ try { MimeParser.parseMessage(bytes, uid, user, canonicalizeMailbox(folderName), context) } catch (e: Exception) { Log.w(TAG, "parse failed ${e.message}"); Triple(null, false, emptyList()) } } suspend fun fetchFullForBody(@@ -204,7 +242,7 @@ object ImapClient { conn.select(folderName) val res = conn.uidFetchFullSet(uid.toString()).firstOrNull() ?: return@withConnection EmailManager.FullFetchResult(Triple(null, false, emptyList())) val bytes = res.bodyBytes ?: return@withConnection EmailManager.FullFetchResult(Triple(null, false, emptyList()))- val triple = try { MimeParser.parseMessage(bytes, uid, user, folderName, context.applicationContext) } catch (e: Exception) { Log.w(TAG, "full parse fail ${e.message}"); Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) }+ val triple = try { MimeParser.parseMessage(bytes, uid, user, canonicalizeMailbox(folderName), context.applicationContext) } catch (e: Exception) { Log.w(TAG, "full parse fail ${e.message}"); Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) } EmailManager.FullFetchResult(triple) }
email/src/test/java/com/vayunmathur/email/imap/ImapClientMailboxTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/imap/ImapClientMailboxTest.kt b/email/src/test/java/com/vayunmathur/email/imap/ImapClientMailboxTest.ktnew file mode 100644index 0000000000..4267704947--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/imap/ImapClientMailboxTest.kt@@ -0,0 +1,46 @@+package com.vayunmathur.email.imap++import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Office 365 / Exchange reports the inbox as "Inbox" while Gmail and friends report+ * "INBOX". Everything downstream (notably the unified inbox query) matches on the+ * literal "INBOX" with case-sensitive SQLite comparison, so folding has to happen+ * before folder names are persisted.+ */+class ImapClientMailboxTest {++ @Test+ fun `folds any casing of the inbox onto the canonical name`() {+ assertEquals("INBOX", ImapClient.canonicalizeMailbox("INBOX"))+ assertEquals("INBOX", ImapClient.canonicalizeMailbox("Inbox"))+ assertEquals("INBOX", ImapClient.canonicalizeMailbox("inbox"))+ assertEquals("INBOX", ImapClient.canonicalizeMailbox("iNbOx"))+ }++ @Test+ fun `folds the leading segment of inbox sub-folders`() {+ assertEquals("INBOX/Receipts", ImapClient.canonicalizeMailbox("Inbox/Receipts"))+ assertEquals("INBOX.Receipts", ImapClient.canonicalizeMailbox("Inbox.Receipts"))+ assertEquals("INBOX/Receipts/2024", ImapClient.canonicalizeMailbox("inbox/Receipts/2024"))+ }++ @Test+ fun `honours an explicit hierarchy delimiter`() {+ assertEquals("INBOX/Receipts", ImapClient.canonicalizeMailbox("Inbox/Receipts", "/"))+ // A dot is not the delimiter here, so "Inbox.Receipts" is an unrelated mailbox.+ assertEquals("Inbox.Receipts", ImapClient.canonicalizeMailbox("Inbox.Receipts", "/"))+ }++ @Test+ fun `leaves non-inbox mailboxes untouched`() {+ assertEquals("Sent", ImapClient.canonicalizeMailbox("Sent"))+ assertEquals("Deleted Items", ImapClient.canonicalizeMailbox("Deleted Items"))+ assertEquals("[Gmail]/All Mail", ImapClient.canonicalizeMailbox("[Gmail]/All Mail"))+ // Only the inbox is case-insensitive — a sibling that merely starts with the+ // same letters must not be rewritten.+ assertEquals("Inboxes", ImapClient.canonicalizeMailbox("Inboxes"))+ assertEquals("Inbox Archive", ImapClient.canonicalizeMailbox("Inbox Archive"))+ }+}