Modern Apps git

← Modern-Apps.git

email: fix build after canonical migration

Commit
fdcc9f44fb17cbf0ff630ecb5305a2b9d0533ac3
Author
vayun-mathur <[email protected]>
When
2026-08-15 22:04 UTC (3 months ago)
Parents
c2419fe

Diff

email/src/main/java/com/vayunmathur/email/Navigation.kt
diff --git a/email/src/main/java/com/vayunmathur/email/Navigation.kt b/email/src/main/java/com/vayunmathur/email/Navigation.ktindex eb2a5a173f..1232f682e3 100644--- a/email/src/main/java/com/vayunmathur/email/Navigation.kt+++ b/email/src/main/java/com/vayunmathur/email/Navigation.kt@@ -4,6 +4,7 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.verticalScroll@@ -19,6 +20,8 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.email.data.accountColor+import com.vayunmathur.email.data.EmailAccount+import com.vayunmathur.email.data.OutboxEntry import com.vayunmathur.email.platform.EmailViewModel import com.vayunmathur.email.platform.IntentState import com.vayunmathur.email.ui.AddAccountScreen
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 815377a497..79eb206454 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt@@ -1,238 +1,238 @@-package com.vayunmathur.email.data--import android.content.Context-import android.util.Log-import androidx.core.content.edit-import androidx.work.*-import com.vayunmathur.email.network.imap.ImapClient-import com.vayunmathur.email.data.imapServer-import com.vayunmathur.email.data.loginUser-import com.vayunmathur.email.data.resolveAuth-import com.vayunmathur.email.widget.EmailWidget-import androidx.glance.appwidget.updateAll-import java.util.concurrent.TimeUnit--/**- * Sync worker — now uses raw IMAP client only (no Jakarta dependency).- * - Non-INBOX hourly via WorkManager- * - Full one-off for folder discovery + INBOX + body backfill- * - Notification baseline per account/folder- */-class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :-    CoroutineWorker(appContext, workerParams) {--    override suspend fun doWork(): Result {-        val nonInboxOnly = inputData.getBoolean(KEY_NON_INBOX_ONLY, false)-        val repository = EmailRepository.get(applicationContext)-        val dao = repository.getDatabase().emailDao()-        val accounts = dao.getAccounts()--        if (accounts.isEmpty()) {-            Log.d("EmailSync", "No accounts to sync")-            return Result.success()-        }--        EmailSyncState.start()-        var hasErrors = false-        var accountsProcessed = 0--        for (account in accounts) {-            try {-                Log.d("EmailSync", ">>> RAW Starting sync for ${account.email} (nonInboxOnly=$nonInboxOnly)")-                val auth = account.resolveAuth(applicationContext)--                val folders = ImapClient.fetchFolders(account.imapServer(), account.loginUser(), auth)-                dao.insertFolders(folders)-                Log.d("EmailSync", "Synced ${folders.size} folders.")--                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 != ImapClient.INBOX }-                } else {-                    folders.filter { it.holdsMessages && it.fullName !in skipSet }-                }-                val totalUnits = (accounts.size * messageFolders.size).coerceAtLeast(1)--                for ((index, folder) in messageFolders.withIndex()) {-                    try {-                        val knownUids = dao.getKnownUids(account.email, folder.fullName).toSet()-                        val deletedUids = dao.getDeletedUids(account.email, folder.fullName).toSet()-                        val (messages, attachments) = ImapClient.fetchMessages(-                            server = account.imapServer(),-                            user = account.loginUser(),-                            auth = auth,-                            folderName = folder.fullName,-                            limit = 50,-                            fetchBodies = false,-                            skipUids = knownUids + deletedUids,-                            context = applicationContext,-                        )-                        if (messages.isNotEmpty()) dao.insertMessages(messages)-                        if (attachments.isNotEmpty()) dao.insertAttachments(attachments)--                        if (!nonInboxOnly) {-                            if (knownUids.isNotEmpty() && folder.fullName == ImapClient.INBOX) {-                                syncReadStatusRaw(applicationContext, account, folder.fullName, knownUids)-                            }--                            if (folder.fullName == ImapClient.INBOX && messages.isNotEmpty()) {-                                val lastSeen = lastSeenPrefs(applicationContext)-                                    .getLong(lastSeenKey(account.email, folder.fullName), -1L)-                                if (lastSeen >= 0L && !com.vayunmathur.email.platform.AppLifecycleTracker.isAppInForeground) {-                                    val notifiable = messages.filter { it.id > lastSeen }-                                    com.vayunmathur.email.platform.EmailNotifications.postForNewMessages(-                                        applicationContext, account.email, notifiable,-                                    )-                                }-                                val maxUid = messages.maxOf { it.id }-                                if (maxUid > lastSeen) {-                                    lastSeenPrefs(applicationContext).edit {-                                        putLong(lastSeenKey(account.email, folder.fullName), maxUid)-                                    }-                                }-                            }-                        }--                        Log.d("EmailSync", "[${index + 1}/${messageFolders.size}] ${folder.fullName}: ${messages.size} new (skipped ${knownUids.size}).")-                    } catch (e: Exception) {-                        Log.e("EmailSync", "   x Failed folder ${folder.fullName}", e)-                    }-                    val unitsDone = accountsProcessed * messageFolders.size + (index + 1)-                    EmailSyncState.setProgress(unitsDone.toFloat() / totalUnits)-                }--                if (!nonInboxOnly) {-                    val missing = dao.getMessagesWithoutBody(account.email, BACKFILL_LIMIT)-                    if (missing.isNotEmpty()) {-                        Log.d("EmailSync", "Body backfill: ${missing.size} message(s)")-                        EmailSyncState.setProgress(0f)-                        for ((idx, msg) in missing.withIndex()) {-                            if (isStopped) {-                                Log.d("EmailSync", "Backfill stopped at ${idx}/${missing.size}")-                                break-                            }-                            try {-                                val current = dao.getMessage(msg.accountEmail, msg.folderName, msg.id) ?: continue-                                if (current.body != null) continue-                                val (body, isHtml, attachments) = ImapClient.fetchMessageBody(-                                    server = account.imapServer(),-                                    user = account.loginUser(),-                                    auth = auth,-                                    folderName = msg.folderName,-                                    uid = msg.id,-                                    context = applicationContext,-                                )-                                if (body != null || attachments.isNotEmpty()) {-                                    dao.insertMessages(listOf(current.copy(-                                        body = body,-                                        isHtml = isHtml,-                                        hasAttachments = attachments.isNotEmpty(),-                                    )))-                                    if (attachments.isNotEmpty()) dao.insertAttachments(attachments)-                                }-                            } catch (e: Exception) {-                                Log.w("EmailSync", "   x Backfill failed for UID ${msg.id}: ${e.message}")-                            }-                            EmailSyncState.setProgress((idx + 1f) / missing.size)-                        }-                        Log.d("EmailSync", "Backfill done for ${account.email}")-                    }-                }--                Log.d("EmailSync", "<<< Completed RAW sync for ${account.email}")-            } catch (e: Exception) {-                Log.e("EmailSync", "Failed to sync account ${account.email}", e)-                hasErrors = true-            }-            accountsProcessed++-        }--        if (!nonInboxOnly) EmailWidget().updateAll(applicationContext)-        EmailSyncState.finish()-        return if (hasErrors) Result.retry() else Result.success()-    }--    companion object {-        private const val SYNC_WORK_NAME = "EmailSyncWorker"-        private const val HOURLY_NON_INBOX_WORK_NAME = "EmailNonInboxHourlySync"-        private const val KEY_NON_INBOX_ONLY = "non_inbox_only"--        /** Sync read status via raw FETCH FLAGS */-        private suspend fun syncReadStatusRaw(-            context: Context,-            account: com.vayunmathur.email.data.EmailAccount,-            folderName: String,-            knownUids: Set<Long>,-        ) {-            try {-                val db = EmailRepository.get(context).getDatabase()-                val dao = db.emailDao()-                val uidsToCheck = knownUids.sortedDescending().take(50)-                if (uidsToCheck.isEmpty()) return-                val auth = account.resolveAuth(context)-                val server = account.imapServer()-                val user = account.loginUser()--                ImapClient.withConnection(server, user, auth) { conn ->-                    conn.select(folderName)-                    val uidSet = uidsToCheck.joinToString(",")-                    val results = conn.uidFetchHeaders(uidSet)-                    for (r in results) {-                        val isRead = r.flags.any { it.equals("\\Seen", ignoreCase = true) }-                        try { dao.updateReadStatus(account.email, folderName, r.uid, isRead) } catch (_: Exception) {}-                    }-                }-            } catch (_: Exception) {}-        }--        private val GMAIL_VIRTUAL_FOLDERS = setOf(-            "[Gmail]/All Mail",-            "[Gmail]/Important",-            "[Gmail]/Starred",-            "[Gmail]/Chats",-        )--        private const val BACKFILL_LIMIT = 200--        private fun lastSeenPrefs(context: Context) =-            context.getSharedPreferences("email_notif_last_seen", Context.MODE_PRIVATE)--        private fun lastSeenKey(accountEmail: String, folderName: String) =-            "$accountEmail::$folderName"--        @Deprecated("IDLE-only push: periodic polling removed.")-        fun schedulePeriodicSync(context: Context) {-            WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)-            WorkManager.getInstance(context).cancelUniqueWork(HOURLY_NON_INBOX_WORK_NAME)-        }--        fun scheduleHourlyNonInboxSync(context: Context) {-            WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)-            val constraints = Constraints.Builder()-                .setRequiredNetworkType(NetworkType.CONNECTED)-                .build()-            val data = Data.Builder().putBoolean(KEY_NON_INBOX_ONLY, true).build()-            val req = PeriodicWorkRequestBuilder<EmailSyncWorker>(1, TimeUnit.HOURS)-                .setConstraints(constraints)-                .setInputData(data)-                .build()-            WorkManager.getInstance(context).enqueueUniquePeriodicWork(-                HOURLY_NON_INBOX_WORK_NAME,-                ExistingPeriodicWorkPolicy.KEEP,-                req,-            )-        }--        fun runOneOffSync(context: Context) {-            val syncRequest = OneTimeWorkRequestBuilder<EmailSyncWorker>()-                .setInputData(Data.Builder().putBoolean(KEY_NON_INBOX_ONLY, false).build())-                .build()-            WorkManager.getInstance(context).enqueue(syncRequest)-        }--        fun cancelSync(context: Context) {-            WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)-            WorkManager.getInstance(context).cancelUniqueWork(HOURLY_NON_INBOX_WORK_NAME)-        }-    }-}+package com.vayunmathur.email.data++import android.content.Context+import android.util.Log+import androidx.core.content.edit+import androidx.work.*+import com.vayunmathur.email.network.imap.ImapClient+import com.vayunmathur.email.platform.imapServer+import com.vayunmathur.email.platform.loginUser+import com.vayunmathur.email.platform.resolveAuth+import com.vayunmathur.email.widget.EmailWidget+import androidx.glance.appwidget.updateAll+import java.util.concurrent.TimeUnit++/**+ * Sync worker — now uses raw IMAP client only (no Jakarta dependency).+ * - Non-INBOX hourly via WorkManager+ * - Full one-off for folder discovery + INBOX + body backfill+ * - Notification baseline per account/folder+ */+class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :+    CoroutineWorker(appContext, workerParams) {++    override suspend fun doWork(): Result {+        val nonInboxOnly = inputData.getBoolean(KEY_NON_INBOX_ONLY, false)+        val repository = EmailRepository.get(applicationContext)+        val dao = repository.getDatabase().emailDao()+        val accounts = dao.getAccounts()++        if (accounts.isEmpty()) {+            Log.d("EmailSync", "No accounts to sync")+            return Result.success()+        }++        EmailSyncState.start()+        var hasErrors = false+        var accountsProcessed = 0++        for (account in accounts) {+            try {+                Log.d("EmailSync", ">>> RAW Starting sync for ${account.email} (nonInboxOnly=$nonInboxOnly)")+                val auth = account.resolveAuth(applicationContext)++                val folders = ImapClient.fetchFolders(account.imapServer(), account.loginUser(), auth)+                dao.insertFolders(folders)+                Log.d("EmailSync", "Synced ${folders.size} folders.")++                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 != ImapClient.INBOX }+                } else {+                    folders.filter { it.holdsMessages && it.fullName !in skipSet }+                }+                val totalUnits = (accounts.size * messageFolders.size).coerceAtLeast(1)++                for ((index, folder) in messageFolders.withIndex()) {+                    try {+                        val knownUids = dao.getKnownUids(account.email, folder.fullName).toSet()+                        val deletedUids = dao.getDeletedUids(account.email, folder.fullName).toSet()+                        val (messages, attachments) = ImapClient.fetchMessages(+                            server = account.imapServer(),+                            user = account.loginUser(),+                            auth = auth,+                            folderName = folder.fullName,+                            limit = 50,+                            fetchBodies = false,+                            skipUids = knownUids + deletedUids,+                            context = applicationContext,+                        )+                        if (messages.isNotEmpty()) dao.insertMessages(messages)+                        if (attachments.isNotEmpty()) dao.insertAttachments(attachments)++                        if (!nonInboxOnly) {+                            if (knownUids.isNotEmpty() && folder.fullName == ImapClient.INBOX) {+                                syncReadStatusRaw(applicationContext, account, folder.fullName, knownUids)+                            }++                            if (folder.fullName == ImapClient.INBOX && messages.isNotEmpty()) {+                                val lastSeen = lastSeenPrefs(applicationContext)+                                    .getLong(lastSeenKey(account.email, folder.fullName), -1L)+                                if (lastSeen >= 0L && !com.vayunmathur.email.platform.AppLifecycleTracker.isAppInForeground) {+                                    val notifiable = messages.filter { it.id > lastSeen }+                                    com.vayunmathur.email.platform.EmailNotifications.postForNewMessages(+                                        applicationContext, account.email, notifiable,+                                    )+                                }+                                val maxUid = messages.maxOf { it.id }+                                if (maxUid > lastSeen) {+                                    lastSeenPrefs(applicationContext).edit {+                                        putLong(lastSeenKey(account.email, folder.fullName), maxUid)+                                    }+                                }+                            }+                        }++                        Log.d("EmailSync", "[${index + 1}/${messageFolders.size}] ${folder.fullName}: ${messages.size} new (skipped ${knownUids.size}).")+                    } catch (e: Exception) {+                        Log.e("EmailSync", "   x Failed folder ${folder.fullName}", e)+                    }+                    val unitsDone = accountsProcessed * messageFolders.size + (index + 1)+                    EmailSyncState.setProgress(unitsDone.toFloat() / totalUnits)+                }++                if (!nonInboxOnly) {+                    val missing = dao.getMessagesWithoutBody(account.email, BACKFILL_LIMIT)+                    if (missing.isNotEmpty()) {+                        Log.d("EmailSync", "Body backfill: ${missing.size} message(s)")+                        EmailSyncState.setProgress(0f)+                        for ((idx, msg) in missing.withIndex()) {+                            if (isStopped) {+                                Log.d("EmailSync", "Backfill stopped at ${idx}/${missing.size}")+                                break+                            }+                            try {+                                val current = dao.getMessage(msg.accountEmail, msg.folderName, msg.id) ?: continue+                                if (current.body != null) continue+                                val (body, isHtml, attachments) = ImapClient.fetchMessageBody(+                                    server = account.imapServer(),+                                    user = account.loginUser(),+                                    auth = auth,+                                    folderName = msg.folderName,+                                    uid = msg.id,+                                    context = applicationContext,+                                )+                                if (body != null || attachments.isNotEmpty()) {+                                    dao.insertMessages(listOf(current.copy(+                                        body = body,+                                        isHtml = isHtml,+                                        hasAttachments = attachments.isNotEmpty(),+                                    )))+                                    if (attachments.isNotEmpty()) dao.insertAttachments(attachments)+                                }+                            } catch (e: Exception) {+                                Log.w("EmailSync", "   x Backfill failed for UID ${msg.id}: ${e.message}")+                            }+                            EmailSyncState.setProgress((idx + 1f) / missing.size)+                        }+                        Log.d("EmailSync", "Backfill done for ${account.email}")+                    }+                }++                Log.d("EmailSync", "<<< Completed RAW sync for ${account.email}")+            } catch (e: Exception) {+                Log.e("EmailSync", "Failed to sync account ${account.email}", e)+                hasErrors = true+            }+            accountsProcessed+++        }++        if (!nonInboxOnly) EmailWidget().updateAll(applicationContext)+        EmailSyncState.finish()+        return if (hasErrors) Result.retry() else Result.success()+    }++    companion object {+        private const val SYNC_WORK_NAME = "EmailSyncWorker"+        private const val HOURLY_NON_INBOX_WORK_NAME = "EmailNonInboxHourlySync"+        private const val KEY_NON_INBOX_ONLY = "non_inbox_only"++        /** Sync read status via raw FETCH FLAGS */+        private suspend fun syncReadStatusRaw(+            context: Context,+            account: com.vayunmathur.email.data.EmailAccount,+            folderName: String,+            knownUids: Set<Long>,+        ) {+            try {+                val db = EmailRepository.get(context).getDatabase()+                val dao = db.emailDao()+                val uidsToCheck = knownUids.sortedDescending().take(50)+                if (uidsToCheck.isEmpty()) return+                val auth = account.resolveAuth(context)+                val server = account.imapServer()+                val user = account.loginUser()++                ImapClient.withConnection(server, user, auth) { conn ->+                    conn.select(folderName)+                    val uidSet = uidsToCheck.joinToString(",")+                    val results = conn.uidFetchHeaders(uidSet)+                    for (r in results) {+                        val isRead = r.flags.any { it.equals("\\Seen", ignoreCase = true) }+                        try { dao.updateReadStatus(account.email, folderName, r.uid, isRead) } catch (_: Exception) {}+                    }+                }+            } catch (_: Exception) {}+        }++        private val GMAIL_VIRTUAL_FOLDERS = setOf(+            "[Gmail]/All Mail",+            "[Gmail]/Important",+            "[Gmail]/Starred",+            "[Gmail]/Chats",+        )++        private const val BACKFILL_LIMIT = 200++        private fun lastSeenPrefs(context: Context) =+            context.getSharedPreferences("email_notif_last_seen", Context.MODE_PRIVATE)++        private fun lastSeenKey(accountEmail: String, folderName: String) =+            "$accountEmail::$folderName"++        @Deprecated("IDLE-only push: periodic polling removed.")+        fun schedulePeriodicSync(context: Context) {+            WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)+            WorkManager.getInstance(context).cancelUniqueWork(HOURLY_NON_INBOX_WORK_NAME)+        }++        fun scheduleHourlyNonInboxSync(context: Context) {+            WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)+            val constraints = Constraints.Builder()+                .setRequiredNetworkType(NetworkType.CONNECTED)+                .build()+            val data = Data.Builder().putBoolean(KEY_NON_INBOX_ONLY, true).build()+            val req = PeriodicWorkRequestBuilder<EmailSyncWorker>(1, TimeUnit.HOURS)+                .setConstraints(constraints)+                .setInputData(data)+                .build()+            WorkManager.getInstance(context).enqueueUniquePeriodicWork(+                HOURLY_NON_INBOX_WORK_NAME,+                ExistingPeriodicWorkPolicy.KEEP,+                req,+            )+        }++        fun runOneOffSync(context: Context) {+            val syncRequest = OneTimeWorkRequestBuilder<EmailSyncWorker>()+                .setInputData(Data.Builder().putBoolean(KEY_NON_INBOX_ONLY, false).build())+                .build()+            WorkManager.getInstance(context).enqueue(syncRequest)+        }++        fun cancelSync(context: Context) {+            WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)+            WorkManager.getInstance(context).cancelUniqueWork(HOURLY_NON_INBOX_WORK_NAME)+        }+    }+}
email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.ktindex b98fe5f940..6b74de1590 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt@@ -1,305 +1,305 @@-@file:OptIn(kotlin.concurrent.atomics.ExperimentalAtomicApi::class)--package com.vayunmathur.email.data--import kotlin.concurrent.atomics.*-import android.app.Notification-import android.app.NotificationChannel-import android.app.NotificationManager-import android.app.Service-import android.content.Context-import android.content.Intent-import android.content.pm.ServiceInfo-import android.os.Build-import android.os.IBinder-import android.util.Log-import androidx.core.app.NotificationCompat-import androidx.core.content.edit-import com.vayunmathur.email.data.EmailAccount-import com.vayunmathur.email.data.EmailFolder-import com.vayunmathur.email.platform.EmailManager-import com.vayunmathur.email.R-import com.vayunmathur.email.network.imap.ImapAuthException-import com.vayunmathur.email.network.imap.ImapClient-import com.vayunmathur.email.network.imap.RawImapConnection-import com.vayunmathur.email.network.imap.TrustAll-import com.vayunmathur.email.data.resolveAuth-import com.vayunmathur.email.data.imapServer-import com.vayunmathur.email.data.loginUser-import com.vayunmathur.email.platform.AppLifecycleTracker-import com.vayunmathur.email.platform.EmailNotifications-import com.vayunmathur.email.widget.EmailWidget-import androidx.glance.appwidget.updateAll-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.Job-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.cancel-import kotlinx.coroutines.delay-import kotlinx.coroutines.isActive-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext--/**- * Foreground service — raw IMAP IDLE (no Jakarta), app-password + Outlook OAuth XOAUTH2.- * Fix for BOOT_COMPLETED crash: start() returns Boolean, onStartCommand catches FGS exception.- */-class ImapIdleService : Service() {--    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)-    private val accountJobs = mutableMapOf<String, Job>()--    override fun onBind(intent: Intent?): IBinder? = null--    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {-        try {-            startForeground(NOTIFICATION_ID, buildOngoingNotification(), foregroundServiceType())-        } catch (e: Exception) {-            Log.w(TAG, "startForeground failed: ${e.message}", e)-            stopSelf()-            return START_NOT_STICKY-        }-        scope.launch { startIdleLoops() }-        return START_STICKY-    }--    override fun onDestroy() { scope.cancel(); super.onDestroy() }--    private suspend fun startIdleLoops() {-        val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()-        val accounts = dao.getAccounts()-        if (accounts.isEmpty()) { stopSelf(); return }-        try { EmailSyncWorker.scheduleHourlyNonInboxSync(applicationContext) } catch (_: Throwable) {}-        val current = accounts.map { it.email }.toSet()-        accountJobs.keys.filter { it !in current }.forEach { accountJobs[it]?.cancel(); accountJobs.remove(it) }-        for (account in accounts) {-            accountJobs[account.email]?.cancel()-            accountJobs[account.email] = scope.launch { idleLoop(account) }-        }-    }--    private suspend fun idleLoop(account: EmailAccount) {-        var backoffMs = 2_000L-        val maxBackoffMs = 60_000L-        while (scope.coroutineContext.isActive) {-            try {-                runIdleSessionRaw(account)-                backoffMs = 2_000L-                delay(1_000L)-            } catch (e: ImapAuthException) {-                Log.w(TAG, "IDLE auth failed for ${account.email}; stop")-                return-            } catch (e: Exception) {-                val msg = e.message?.lowercase() ?: ""-                if (msg.contains("auth") && msg.contains("fail")) { Log.w(TAG, "IDLE auth fail ${account.email}"); return }-                Log.w(TAG, "IDLE err ${account.email}: ${e.javaClass.simpleName}: ${e.message}")-                delay(backoffMs)-                backoffMs = (backoffMs * 2).coerceAtMost(maxBackoffMs)-            }-        }-    }--    private suspend fun runIdleSessionRaw(account: EmailAccount) = withContext(Dispatchers.IO) {-        val server = account.imapServer()-        val user = account.loginUser()-        val auth = account.resolveAuth(applicationContext)-        val useTrustAll = !TrustAll.isKnownHost(server.host)-        val rawConn = RawImapConnection(server, trustAll = useTrustAll)-        try {-            rawConn.connect()-            var caps = rawConn.capability()-            if (!server.useSsl && caps.has("STARTTLS")) {-                try { rawConn.startTls(); caps = rawConn.capability() } catch (e: Exception) { Log.w(TAG, "STARTTLS fail ${account.email}: ${e.message}") }-            }--            when (auth) {-                is EmailManager.AuthType.OAuth -> rawConn.authenticateXoauth2(user, auth.token)-                is EmailManager.AuthType.Password -> {-                    try { rawConn.login(user, auth.value) } catch (e: Exception) {-                        if (caps.has("AUTH=PLAIN")) rawConn.authenticatePlain(user, auth.value) else throw e-                    }-                }-            }--            val supportsIdle = caps.has("IDLE")-            Log.d(TAG, "Raw IDLE supports $supportsIdle for ${account.email}")--            if (!supportsIdle) {-                while (scope.coroutineContext.isActive) {-                    delay(FALLBACK_NO_IDLE_POLL_MS)-                    try {-                        val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()-                        val known = dao.getKnownUids(account.email, "INBOX").toSet()-                        val deleted = dao.getDeletedUids(account.email, "INBOX").toSet()-                        val (msgs, atts) = ImapClient.fetchMessagesInConnection(rawConn, account.email, "INBOX", 50, 0, false, known + deleted, applicationContext)-                        if (msgs.isNotEmpty()) { dao.insertMessages(msgs); if (atts.isNotEmpty()) dao.insertAttachments(atts); postNewMailNotification(account.email, msgs) }-                        syncReadStatusPullRaw(applicationContext, account, known)-                    } catch (t: Throwable) { Log.w(TAG, "Raw poll fail: ${t.message}") }-                }-                return@withContext-            }--            val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()-            while (scope.coroutineContext.isActive) {-                val sel = rawConn.select("INBOX")-                Log.d(TAG, "SELECT INBOX ${account.email} exists=${sel.exists}")-                try {-                    val folders = rawConn.list("", "*").map { entry ->-                        val fullName = entry.mailbox-                        val delim = entry.delimiter ?: "/"-                        val nm = if (fullName.contains(delim)) fullName.substringAfterLast(delim) else fullName.substringAfterLast('/')-                        val parent = fullName.lastIndexOf(delim).let { if (it > 0) fullName.substring(0, it) else null }-                        val holds = !entry.flags.any { f -> f.equals("\\Noselect", ignoreCase = true) }-                        EmailFolder(account.email, fullName, nm.ifBlank { fullName }, parent, holds, delim)-                    }-                    dao.insertFolders(folders)-                } catch (t: Throwable) { Log.w(TAG, "folder discovery fail: ${t.message}") }--                var sawNewMail = false-                var sawExpunge = false-                var sawFlags = false-                val expungedSeqs = mutableListOf<Int>()-                var needReopen = false-                var isProactiveRefresh = false--                while (scope.coroutineContext.isActive && !needReopen) {-                    val idleTag = rawConn.sendIdle()-                    Log.d(TAG, "IDLE start ${account.email} tag=$idleTag")--                    val watchdog = scope.launch {-                        delay(IDLE_REFRESH_MS)-                        if (isActive) { Log.d(TAG, "proactive refresh ${account.email}"); isProactiveRefresh = true; try { rawConn.sendIdleDone() } catch (_: Throwable) {} }-                    }--                    var idleEnded = false-                    var idleLoopActive = true-                    while (idleLoopActive && scope.coroutineContext.isActive) {-                        val line = withContext(Dispatchers.IO) { try { rawConn.readIdleLine() } catch (_: Exception) { null } } ?: break-                        Log.d(TAG, "IDLE line ${account.email}: $line")-                        if (line.startsWith(idleTag)) { idleEnded = true; idleLoopActive = false; break }-                        when {-                            Regex("""^\* (\d+) EXISTS""").containsMatchIn(line) -> sawNewMail = true-                            Regex("""^\* (\d+) EXPUNGE""").containsMatchIn(line) -> {-                                val seq = Regex("""^\* (\d+) EXPUNGE""").find(line)?.groupValues?.get(1)?.toIntOrNull() ?: -1-                                if (seq != -1) expungedSeqs.add(seq); sawExpunge = true-                            }-                            line.contains("FETCH") && line.contains("FLAGS") -> sawFlags = true-                        }-                        if (sawNewMail || sawExpunge || sawFlags) { try { rawConn.sendIdleDone() } catch (_: Throwable) {} }-                    }--                    if (!idleEnded) { try { rawConn.sendIdleDone() } catch (_: Throwable) {}; try { rawConn.readIdleResponseForTag(idleTag) } catch (_: Throwable) {} }--                    watchdog.cancel()--                    if (isProactiveRefresh) { Log.d(TAG, "24-min refresh ${account.email}"); isProactiveRefresh = false; needReopen = true; delay(200L); break }--                    if (sawNewMail && !needReopen) {-                        sawNewMail = false-                        try {-                            val known = dao.getKnownUids(account.email, "INBOX").toSet()-                            val deleted = dao.getDeletedUids(account.email, "INBOX").toSet()-                            val (msgs, atts) = ImapClient.fetchMessagesInConnection(rawConn, account.email, "INBOX", 50, 0, false, known + deleted, applicationContext)-                            if (msgs.isNotEmpty()) { dao.insertMessages(msgs); if (atts.isNotEmpty()) dao.insertAttachments(atts); postNewMailNotification(account.email, msgs) }-                        } catch (t: Throwable) { Log.w(TAG, "quick fetch fail: ${t.message}") }-                    }--                    if (sawExpunge && expungedSeqs.isNotEmpty() && !needReopen) {-                        sawExpunge = false; expungedSeqs.clear(); try { EmailWidget().updateAll(applicationContext) } catch (_: Throwable) {}-                    }--                    if (sawFlags && !needReopen) {-                        sawFlags = false-                        try { syncReadStatusPullRaw(applicationContext, account, dao.getKnownUids(account.email, "INBOX").toSet()) } catch (t: Throwable) { Log.w(TAG, "flag sync fail: ${t.message}") }-                    }--                    if (needReopen) break-                    if (scope.coroutineContext.isActive) delay(500L)-                }-                if (!scope.coroutineContext.isActive) break-                if (needReopen) continue-                delay(500L)-            }-        } catch (e: Exception) { try { rawConn.close() } catch (_: Throwable) {}; throw e }-    }--    private suspend fun postNewMailNotification(accountEmail: String, messages: List<com.vayunmathur.email.data.EmailMessage>) {-        if (messages.isEmpty()) return-        val ctx = applicationContext ?: return-        val prefs = ctx.getSharedPreferences("email_notif_last_seen", Context.MODE_PRIVATE)-        val lastSeen = prefs.getLong("$accountEmail::INBOX", -1L)-        val notifiable = if (lastSeen == -1L) messages else messages.filter { it.id > lastSeen }-        if (notifiable.isNotEmpty() && !AppLifecycleTracker.isAppInForeground) {-            EmailNotifications.postForNewMessages(ctx, accountEmail, notifiable)-        }-        val maxUid = messages.maxOfOrNull { it.id } ?: lastSeen-        if (maxUid > lastSeen) prefs.edit { putLong("$accountEmail::INBOX", maxUid) }-        try { EmailWidget().updateAll(ctx) } catch (t: Throwable) { Log.w(TAG, "widget fail ${t.message}") }-    }--    private suspend fun syncReadStatusPullRaw(context: Context, account: EmailAccount, knownUids: Set<Long>) {-        if (knownUids.isEmpty()) return-        try {-            val dao = EmailRepository.get(context).getDatabase().emailDao()-            val uidsToCheck = knownUids.sortedDescending().take(50)-            val auth = account.resolveAuth(context)-            ImapClient.withConnection(account.imapServer(), account.loginUser(), auth) { conn ->-                conn.select("INBOX")-                val results = conn.uidFetchHeaders(uidsToCheck.joinToString(","))-                for (r in results) {-                    val isRead = r.flags.any { it.equals("\\Seen", ignoreCase = true) }-                    try { dao.updateReadStatus(account.email, "INBOX", r.uid, isRead) } catch (_: Exception) {}-                }-            }-        } catch (_: Exception) {}-    }--    private fun buildOngoingNotification(): Notification {-        ensureChannel(applicationContext)-        return androidx.core.app.NotificationCompat.Builder(applicationContext, CHANNEL_ID)-            .setSmallIcon(R.drawable.ic_notification_mail)-            .setContentTitle(getString(R.string.app_name))-            .setContentText(getString(R.string.listening_for_new_mail))-            .setPriority(androidx.core.app.NotificationCompat.PRIORITY_LOW)-            .setOngoing(true)-            .setShowWhen(false)-            .build()-    }--    private fun foregroundServiceType(): Int {-        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {-            ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC-        } else 0-    }--    companion object {-        private const val TAG = "ImapIdle"-        private const val CHANNEL_ID = "imap_idle"-        private const val NOTIFICATION_ID = 9001-        const val IDLE_REFRESH_MS = 24L * 60 * 1000-        const val FALLBACK_NO_IDLE_POLL_MS = 5L * 60 * 1000--        private fun ensureChannel(context: Context) {-            val nm = context.getSystemService(NotificationManager::class.java) ?: return-            if (nm.getNotificationChannel(CHANNEL_ID) != null) return-            nm.createNotificationChannel(-                NotificationChannel(CHANNEL_ID, context.getString(R.string.email_sync_channel_name), NotificationManager.IMPORTANCE_LOW).apply {-                    description = context.getString(R.string.email_sync_channel_desc)-                    setShowBadge(false)-                }-            )-        }--        fun start(context: Context): Boolean {-            return try {-                val intent = Intent(context, ImapIdleService::class.java)-                context.startForegroundService(intent)-                true-            } catch (e: Exception) {-                Log.w(TAG, "start failed: ${e.message}", e); false-            }-        }--        fun stop(context: Context) { context.stopService(Intent(context, ImapIdleService::class.java)) }-    }-}+@file:OptIn(kotlin.concurrent.atomics.ExperimentalAtomicApi::class)++package com.vayunmathur.email.data++import kotlin.concurrent.atomics.*+import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.content.edit+import com.vayunmathur.email.data.EmailAccount+import com.vayunmathur.email.data.EmailFolder+import com.vayunmathur.email.platform.EmailManager+import com.vayunmathur.email.R+import com.vayunmathur.email.network.imap.ImapAuthException+import com.vayunmathur.email.network.imap.ImapClient+import com.vayunmathur.email.network.imap.RawImapConnection+import com.vayunmathur.email.network.imap.TrustAll+import com.vayunmathur.email.platform.resolveAuth+import com.vayunmathur.email.platform.imapServer+import com.vayunmathur.email.platform.loginUser+import com.vayunmathur.email.platform.AppLifecycleTracker+import com.vayunmathur.email.platform.EmailNotifications+import com.vayunmathur.email.widget.EmailWidget+import androidx.glance.appwidget.updateAll+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Foreground service — raw IMAP IDLE (no Jakarta), app-password + Outlook OAuth XOAUTH2.+ * Fix for BOOT_COMPLETED crash: start() returns Boolean, onStartCommand catches FGS exception.+ */+class ImapIdleService : Service() {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+    private val accountJobs = mutableMapOf<String, Job>()++    override fun onBind(intent: Intent?): IBinder? = null++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        try {+            startForeground(NOTIFICATION_ID, buildOngoingNotification(), foregroundServiceType())+        } catch (e: Exception) {+            Log.w(TAG, "startForeground failed: ${e.message}", e)+            stopSelf()+            return START_NOT_STICKY+        }+        scope.launch { startIdleLoops() }+        return START_STICKY+    }++    override fun onDestroy() { scope.cancel(); super.onDestroy() }++    private suspend fun startIdleLoops() {+        val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()+        val accounts = dao.getAccounts()+        if (accounts.isEmpty()) { stopSelf(); return }+        try { EmailSyncWorker.scheduleHourlyNonInboxSync(applicationContext) } catch (_: Throwable) {}+        val current = accounts.map { it.email }.toSet()+        accountJobs.keys.filter { it !in current }.forEach { accountJobs[it]?.cancel(); accountJobs.remove(it) }+        for (account in accounts) {+            accountJobs[account.email]?.cancel()+            accountJobs[account.email] = scope.launch { idleLoop(account) }+        }+    }++    private suspend fun idleLoop(account: EmailAccount) {+        var backoffMs = 2_000L+        val maxBackoffMs = 60_000L+        while (scope.coroutineContext.isActive) {+            try {+                runIdleSessionRaw(account)+                backoffMs = 2_000L+                delay(1_000L)+            } catch (e: ImapAuthException) {+                Log.w(TAG, "IDLE auth failed for ${account.email}; stop")+                return+            } catch (e: Exception) {+                val msg = e.message?.lowercase() ?: ""+                if (msg.contains("auth") && msg.contains("fail")) { Log.w(TAG, "IDLE auth fail ${account.email}"); return }+                Log.w(TAG, "IDLE err ${account.email}: ${e.javaClass.simpleName}: ${e.message}")+                delay(backoffMs)+                backoffMs = (backoffMs * 2).coerceAtMost(maxBackoffMs)+            }+        }+    }++    private suspend fun runIdleSessionRaw(account: EmailAccount) = withContext(Dispatchers.IO) {+        val server = account.imapServer()+        val user = account.loginUser()+        val auth = account.resolveAuth(applicationContext)+        val useTrustAll = !TrustAll.isKnownHost(server.host)+        val rawConn = RawImapConnection(server, trustAll = useTrustAll)+        try {+            rawConn.connect()+            var caps = rawConn.capability()+            if (!server.useSsl && caps.has("STARTTLS")) {+                try { rawConn.startTls(); caps = rawConn.capability() } catch (e: Exception) { Log.w(TAG, "STARTTLS fail ${account.email}: ${e.message}") }+            }++            when (auth) {+                is EmailManager.AuthType.OAuth -> rawConn.authenticateXoauth2(user, auth.token)+                is EmailManager.AuthType.Password -> {+                    try { rawConn.login(user, auth.value) } catch (e: Exception) {+                        if (caps.has("AUTH=PLAIN")) rawConn.authenticatePlain(user, auth.value) else throw e+                    }+                }+            }++            val supportsIdle = caps.has("IDLE")+            Log.d(TAG, "Raw IDLE supports $supportsIdle for ${account.email}")++            if (!supportsIdle) {+                while (scope.coroutineContext.isActive) {+                    delay(FALLBACK_NO_IDLE_POLL_MS)+                    try {+                        val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()+                        val known = dao.getKnownUids(account.email, "INBOX").toSet()+                        val deleted = dao.getDeletedUids(account.email, "INBOX").toSet()+                        val (msgs, atts) = ImapClient.fetchMessagesInConnection(rawConn, account.email, "INBOX", 50, 0, false, known + deleted, applicationContext)+                        if (msgs.isNotEmpty()) { dao.insertMessages(msgs); if (atts.isNotEmpty()) dao.insertAttachments(atts); postNewMailNotification(account.email, msgs) }+                        syncReadStatusPullRaw(applicationContext, account, known)+                    } catch (t: Throwable) { Log.w(TAG, "Raw poll fail: ${t.message}") }+                }+                return@withContext+            }++            val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()+            while (scope.coroutineContext.isActive) {+                val sel = rawConn.select("INBOX")+                Log.d(TAG, "SELECT INBOX ${account.email} exists=${sel.exists}")+                try {+                    val folders = rawConn.list("", "*").map { entry ->+                        val fullName = entry.mailbox+                        val delim = entry.delimiter ?: "/"+                        val nm = if (fullName.contains(delim)) fullName.substringAfterLast(delim) else fullName.substringAfterLast('/')+                        val parent = fullName.lastIndexOf(delim).let { if (it > 0) fullName.substring(0, it) else null }+                        val holds = !entry.flags.any { f -> f.equals("\\Noselect", ignoreCase = true) }+                        EmailFolder(account.email, fullName, nm.ifBlank { fullName }, parent, holds, delim)+                    }+                    dao.insertFolders(folders)+                } catch (t: Throwable) { Log.w(TAG, "folder discovery fail: ${t.message}") }++                var sawNewMail = false+                var sawExpunge = false+                var sawFlags = false+                val expungedSeqs = mutableListOf<Int>()+                var needReopen = false+                var isProactiveRefresh = false++                while (scope.coroutineContext.isActive && !needReopen) {+                    val idleTag = rawConn.sendIdle()+                    Log.d(TAG, "IDLE start ${account.email} tag=$idleTag")++                    val watchdog = scope.launch {+                        delay(IDLE_REFRESH_MS)+                        if (isActive) { Log.d(TAG, "proactive refresh ${account.email}"); isProactiveRefresh = true; try { rawConn.sendIdleDone() } catch (_: Throwable) {} }+                    }++                    var idleEnded = false+                    var idleLoopActive = true+                    while (idleLoopActive && scope.coroutineContext.isActive) {+                        val line = withContext(Dispatchers.IO) { try { rawConn.readIdleLine() } catch (_: Exception) { null } } ?: break+                        Log.d(TAG, "IDLE line ${account.email}: $line")+                        if (line.startsWith(idleTag)) { idleEnded = true; idleLoopActive = false; break }+                        when {+                            Regex("""^\* (\d+) EXISTS""").containsMatchIn(line) -> sawNewMail = true+                            Regex("""^\* (\d+) EXPUNGE""").containsMatchIn(line) -> {+                                val seq = Regex("""^\* (\d+) EXPUNGE""").find(line)?.groupValues?.get(1)?.toIntOrNull() ?: -1+                                if (seq != -1) expungedSeqs.add(seq); sawExpunge = true+                            }+                            line.contains("FETCH") && line.contains("FLAGS") -> sawFlags = true+                        }+                        if (sawNewMail || sawExpunge || sawFlags) { try { rawConn.sendIdleDone() } catch (_: Throwable) {} }+                    }++                    if (!idleEnded) { try { rawConn.sendIdleDone() } catch (_: Throwable) {}; try { rawConn.readIdleResponseForTag(idleTag) } catch (_: Throwable) {} }++                    watchdog.cancel()++                    if (isProactiveRefresh) { Log.d(TAG, "24-min refresh ${account.email}"); isProactiveRefresh = false; needReopen = true; delay(200L); break }++                    if (sawNewMail && !needReopen) {+                        sawNewMail = false+                        try {+                            val known = dao.getKnownUids(account.email, "INBOX").toSet()+                            val deleted = dao.getDeletedUids(account.email, "INBOX").toSet()+                            val (msgs, atts) = ImapClient.fetchMessagesInConnection(rawConn, account.email, "INBOX", 50, 0, false, known + deleted, applicationContext)+                            if (msgs.isNotEmpty()) { dao.insertMessages(msgs); if (atts.isNotEmpty()) dao.insertAttachments(atts); postNewMailNotification(account.email, msgs) }+                        } catch (t: Throwable) { Log.w(TAG, "quick fetch fail: ${t.message}") }+                    }++                    if (sawExpunge && expungedSeqs.isNotEmpty() && !needReopen) {+                        sawExpunge = false; expungedSeqs.clear(); try { EmailWidget().updateAll(applicationContext) } catch (_: Throwable) {}+                    }++                    if (sawFlags && !needReopen) {+                        sawFlags = false+                        try { syncReadStatusPullRaw(applicationContext, account, dao.getKnownUids(account.email, "INBOX").toSet()) } catch (t: Throwable) { Log.w(TAG, "flag sync fail: ${t.message}") }+                    }++                    if (needReopen) break+                    if (scope.coroutineContext.isActive) delay(500L)+                }+                if (!scope.coroutineContext.isActive) break+                if (needReopen) continue+                delay(500L)+            }+        } catch (e: Exception) { try { rawConn.close() } catch (_: Throwable) {}; throw e }+    }++    private suspend fun postNewMailNotification(accountEmail: String, messages: List<com.vayunmathur.email.data.EmailMessage>) {+        if (messages.isEmpty()) return+        val ctx = applicationContext ?: return+        val prefs = ctx.getSharedPreferences("email_notif_last_seen", Context.MODE_PRIVATE)+        val lastSeen = prefs.getLong("$accountEmail::INBOX", -1L)+        val notifiable = if (lastSeen == -1L) messages else messages.filter { it.id > lastSeen }+        if (notifiable.isNotEmpty() && !AppLifecycleTracker.isAppInForeground) {+            EmailNotifications.postForNewMessages(ctx, accountEmail, notifiable)+        }+        val maxUid = messages.maxOfOrNull { it.id } ?: lastSeen+        if (maxUid > lastSeen) prefs.edit { putLong("$accountEmail::INBOX", maxUid) }+        try { EmailWidget().updateAll(ctx) } catch (t: Throwable) { Log.w(TAG, "widget fail ${t.message}") }+    }++    private suspend fun syncReadStatusPullRaw(context: Context, account: EmailAccount, knownUids: Set<Long>) {+        if (knownUids.isEmpty()) return+        try {+            val dao = EmailRepository.get(context).getDatabase().emailDao()+            val uidsToCheck = knownUids.sortedDescending().take(50)+            val auth = account.resolveAuth(context)+            ImapClient.withConnection(account.imapServer(), account.loginUser(), auth) { conn ->+                conn.select("INBOX")+                val results = conn.uidFetchHeaders(uidsToCheck.joinToString(","))+                for (r in results) {+                    val isRead = r.flags.any { it.equals("\\Seen", ignoreCase = true) }+                    try { dao.updateReadStatus(account.email, "INBOX", r.uid, isRead) } catch (_: Exception) {}+                }+            }+        } catch (_: Exception) {}+    }++    private fun buildOngoingNotification(): Notification {+        ensureChannel(applicationContext)+        return androidx.core.app.NotificationCompat.Builder(applicationContext, CHANNEL_ID)+            .setSmallIcon(R.drawable.ic_notification_mail)+            .setContentTitle(getString(R.string.app_name))+            .setContentText(getString(R.string.listening_for_new_mail))+            .setPriority(androidx.core.app.NotificationCompat.PRIORITY_LOW)+            .setOngoing(true)+            .setShowWhen(false)+            .build()+    }++    private fun foregroundServiceType(): Int {+        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+            ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC+        } else 0+    }++    companion object {+        private const val TAG = "ImapIdle"+        private const val CHANNEL_ID = "imap_idle"+        private const val NOTIFICATION_ID = 9001+        const val IDLE_REFRESH_MS = 24L * 60 * 1000+        const val FALLBACK_NO_IDLE_POLL_MS = 5L * 60 * 1000++        private fun ensureChannel(context: Context) {+            val nm = context.getSystemService(NotificationManager::class.java) ?: return+            if (nm.getNotificationChannel(CHANNEL_ID) != null) return+            nm.createNotificationChannel(+                NotificationChannel(CHANNEL_ID, context.getString(R.string.email_sync_channel_name), NotificationManager.IMPORTANCE_LOW).apply {+                    description = context.getString(R.string.email_sync_channel_desc)+                    setShowBadge(false)+                }+            )+        }++        fun start(context: Context): Boolean {+            return try {+                val intent = Intent(context, ImapIdleService::class.java)+                context.startForegroundService(intent)+                true+            } catch (e: Exception) {+                Log.w(TAG, "start failed: ${e.message}", e); false+            }+        }++        fun stop(context: Context) { context.stopService(Intent(context, ImapIdleService::class.java)) }+    }+}
email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt b/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.ktindex be7125c912..a19b3b49b8 100644--- a/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt@@ -1,6 +1,6 @@ package com.vayunmathur.email.data -import com.vayunmathur.email.ServerConfig+import com.vayunmathur.email.platform.ServerConfig  /**  * Built-in email provider with pre-filled IMAP/SMTP server settings + a short
email/src/main/java/com/vayunmathur/email/intents/EmailDataMapper.kt
diff --git a/email/src/main/java/com/vayunmathur/email/intents/EmailDataMapper.kt b/email/src/main/java/com/vayunmathur/email/intents/EmailDataMapper.ktindex 37d7889a97..75b4d9e63a 100644--- a/email/src/main/java/com/vayunmathur/email/intents/EmailDataMapper.kt+++ b/email/src/main/java/com/vayunmathur/email/intents/EmailDataMapper.kt@@ -1,14 +1,14 @@-package com.vayunmathur.email.intents--import com.vayunmathur.email.data.EmailMessage-import com.vayunmathur.email.plainTextBody-import com.vayunmathur.library.intents.email.EmailData--fun EmailMessage.toEmailData() = EmailData(-    subject = subject,-    from = from,-    to = to,-    date = date,-    body = plainTextBody()?.take(2000),-    isRead = isRead,-)+package com.vayunmathur.email.intents++import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.plainTextBody+import com.vayunmathur.library.intents.email.EmailData++fun EmailMessage.toEmailData() = EmailData(+    subject = subject,+    from = from,+    to = to,+    date = date,+    body = plainTextBody()?.take(2000),+    isRead = isRead,+)
email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailManager.ktindex 1c4eee5df5..b3e53d2c38 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt@@ -1,162 +1,166 @@-package com.vayunmathur.email.platform--import android.content.Context-import android.net.Uri-import com.vayunmathur.email.ui.composer.InlineAttachment-import com.vayunmathur.email.data.CredentialCrypto-import com.vayunmathur.email.data.OutlookOAuth-import com.vayunmathur.email.network.imap.ImapClient-import com.vayunmathur.email.network.smtp.SmtpClient-import java.io.File-import java.io.OutputStream--/**- * Email server config + auth resolution + raw IMAP/SMTP facade.- * Outlook uses OAuth2 (XOAUTH2), others use app passwords.- * Raw sockets only — no Jakarta Mail.- */--data class ServerConfig(val host: String, val port: Int, val useSsl: Boolean) {-    val imapProtocol: String get() = if (useSsl) "imaps" else "imap"-    val smtpProtocol: String get() = if (useSsl) "smtps" else "smtp"-}--fun EmailAccount.imapServer(): ServerConfig = ServerConfig(imapHost, imapPort, imapUseSsl)-fun EmailAccount.smtpServer(): ServerConfig = ServerConfig(smtpHost, smtpPort, smtpUseSsl)-fun EmailAccount.loginUser(): String = username.ifBlank { email }--suspend fun EmailAccount.resolveAuth(context: Context): EmailManager.AuthType {-    if (authType == "oauth2") {-        if (provider == "outlook" || provider == com.vayunmathur.email.data.PROVIDER_OUTLOOK) {-            val token = OutlookOAuth.freshAccessToken(context, this)-                ?: error("Account $email is missing an OAuth access token")-            return EmailManager.AuthType.OAuth(token)-        }-        // Legacy non-Outlook oauth2 account — fall back to encrypted password if present-        val cipher = passwordEncrypted-        val iv = passwordIv-        if (cipher != null && iv != null) {-            return EmailManager.AuthType.Password(CredentialCrypto.decrypt(cipher, iv))-        }-        error("OAuth account $email needs to be re-added with an app password")-    }-    val cipher = passwordEncrypted ?: error("Account $email is missing passwordEncrypted")-    val iv = passwordIv ?: error("Account $email is missing passwordIv")-    return EmailManager.AuthType.Password(CredentialCrypto.decrypt(cipher, iv))-}--class EmailManager {--    sealed class AuthType {-        data class Password(val value: String) : AuthType()-        data class OAuth(val token: String) : AuthType()-    }--    data class FullFetchResult(val contentTriple: Triple<String?, Boolean, List<Attachment>>)--    suspend fun fetchFolders(server: ServerConfig, user: String, auth: AuthType): List<EmailFolder> =-        ImapClient.fetchFolders(server, user, auth)--    suspend fun fetchMessages(-        server: ServerConfig,-        user: String,-        auth: AuthType,-        folderName: String,-        limit: Int,-        offset: Int = 0,-        fetchBodies: Boolean = false,-        skipUids: Set<Long> = emptySet(),-    ): Pair<List<EmailMessage>, List<Attachment>> =-        ImapClient.fetchMessages(server, user, auth, folderName, limit, offset, fetchBodies, skipUids, null)--    suspend fun fetchMessageBody(-        server: ServerConfig,-        user: String,-        auth: AuthType,-        folderName: String,-        uid: Long,-    ): Triple<String?, Boolean, List<Attachment>> =-        ImapClient.fetchMessageBody(server, user, auth, folderName, uid, null)--    suspend fun fetchFullForBody(-        context: Context,-        server: ServerConfig,-        user: String,-        auth: AuthType,-        folderName: String,-        uid: Long,-    ): FullFetchResult = ImapClient.fetchFullForBody(context, server, user, auth, folderName, uid)--    suspend fun fetchCidMap(-        context: Context,-        server: ServerConfig,-        user: String,-        auth: AuthType,-        folderName: String,-        uid: Long,-    ): Map<String, File> = ImapClient.fetchCidMap(context, server, user, auth, folderName, uid)--    suspend fun setSeenFlag(-        server: ServerConfig,-        user: String,-        auth: AuthType,-        folderName: String,-        uid: Long,-        seen: Boolean,-    ) = ImapClient.setSeenFlag(server, user, auth, folderName, uid, seen)--    suspend fun deleteMessage(-        server: ServerConfig,-        user: String,-        auth: AuthType,-        folderName: String,-        uid: Long,-    ) = ImapClient.deleteMessage(server, user, auth, folderName, uid)--    suspend fun downloadAttachment(-        context: Context,-        server: ServerConfig,-        user: String,-        auth: AuthType,-        folderName: String,-        uid: Long,-        partId: String,-        fileName: String,-        mimeType: String,-    ): String = ImapClient.downloadAttachment(context, server, user, auth, folderName, uid, partId, fileName, mimeType)--    suspend fun fetchRawMessageBytes(-        server: ServerConfig,-        user: String,-        auth: AuthType,-        folderName: String,-        uid: Long,-    ): ByteArray = ImapClient.fetchRawMessageBytes(server, user, auth, folderName, uid)--    suspend fun fetchRawMessageTo(-        server: ServerConfig,-        user: String,-        auth: AuthType,-        folderName: String,-        uid: Long,-        output: OutputStream,-    ) = ImapClient.fetchRawMessageTo(server, user, auth, folderName, uid, output)--    suspend fun sendMessage(-        context: Context,-        server: ServerConfig,-        user: String,-        auth: AuthType,-        to: String,-        subject: String,-        body: String,-        cc: String? = null,-        bcc: String? = null,-        attachments: List<Uri> = emptyList(),-        inlineImages: List<InlineAttachment> = emptyList(),-        inReplyTo: String? = null,-        references: String? = null,-        from: String? = null,-        asHtml: Boolean = false,-    ) = SmtpClient.sendMessage(context, server, user, auth, to, subject, body, cc, bcc, attachments, inlineImages, inReplyTo, references, from, asHtml)-}+package com.vayunmathur.email.platform++import android.content.Context+import android.net.Uri+import com.vayunmathur.email.ui.composer.InlineAttachment+import com.vayunmathur.email.data.CredentialCrypto+import com.vayunmathur.email.data.EmailAccount+import com.vayunmathur.email.data.EmailFolder+import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.Attachment+import com.vayunmathur.email.data.OutlookOAuth+import com.vayunmathur.email.network.imap.ImapClient+import com.vayunmathur.email.network.smtp.SmtpClient+import java.io.File+import java.io.OutputStream++/**+ * Email server config + auth resolution + raw IMAP/SMTP facade.+ * Outlook uses OAuth2 (XOAUTH2), others use app passwords.+ * Raw sockets only — no Jakarta Mail.+ */++data class ServerConfig(val host: String, val port: Int, val useSsl: Boolean) {+    val imapProtocol: String get() = if (useSsl) "imaps" else "imap"+    val smtpProtocol: String get() = if (useSsl) "smtps" else "smtp"+}++fun EmailAccount.imapServer(): ServerConfig = ServerConfig(imapHost, imapPort, imapUseSsl)+fun EmailAccount.smtpServer(): ServerConfig = ServerConfig(smtpHost, smtpPort, smtpUseSsl)+fun EmailAccount.loginUser(): String = username.ifBlank { email }++suspend fun EmailAccount.resolveAuth(context: Context): EmailManager.AuthType {+    if (authType == "oauth2") {+        if (provider == "outlook" || provider == com.vayunmathur.email.data.PROVIDER_OUTLOOK) {+            val token = OutlookOAuth.freshAccessToken(context, this)+                ?: error("Account $email is missing an OAuth access token")+            return EmailManager.AuthType.OAuth(token)+        }+        // Legacy non-Outlook oauth2 account — fall back to encrypted password if present+        val cipher = passwordEncrypted+        val iv = passwordIv+        if (cipher != null && iv != null) {+            return EmailManager.AuthType.Password(CredentialCrypto.decrypt(cipher, iv))+        }+        error("OAuth account $email needs to be re-added with an app password")+    }+    val cipher = passwordEncrypted ?: error("Account $email is missing passwordEncrypted")+    val iv = passwordIv ?: error("Account $email is missing passwordIv")+    return EmailManager.AuthType.Password(CredentialCrypto.decrypt(cipher, iv))+}++class EmailManager {++    sealed class AuthType {+        data class Password(val value: String) : AuthType()+        data class OAuth(val token: String) : AuthType()+    }++    data class FullFetchResult(val contentTriple: Triple<String?, Boolean, List<Attachment>>)++    suspend fun fetchFolders(server: ServerConfig, user: String, auth: AuthType): List<EmailFolder> =+        ImapClient.fetchFolders(server, user, auth)++    suspend fun fetchMessages(+        server: ServerConfig,+        user: String,+        auth: AuthType,+        folderName: String,+        limit: Int,+        offset: Int = 0,+        fetchBodies: Boolean = false,+        skipUids: Set<Long> = emptySet(),+    ): Pair<List<EmailMessage>, List<Attachment>> =+        ImapClient.fetchMessages(server, user, auth, folderName, limit, offset, fetchBodies, skipUids, null)++    suspend fun fetchMessageBody(+        server: ServerConfig,+        user: String,+        auth: AuthType,+        folderName: String,+        uid: Long,+    ): Triple<String?, Boolean, List<Attachment>> =+        ImapClient.fetchMessageBody(server, user, auth, folderName, uid, null)++    suspend fun fetchFullForBody(+        context: Context,+        server: ServerConfig,+        user: String,+        auth: AuthType,+        folderName: String,+        uid: Long,+    ): FullFetchResult = ImapClient.fetchFullForBody(context, server, user, auth, folderName, uid)++    suspend fun fetchCidMap(+        context: Context,+        server: ServerConfig,+        user: String,+        auth: AuthType,+        folderName: String,+        uid: Long,+    ): Map<String, File> = ImapClient.fetchCidMap(context, server, user, auth, folderName, uid)++    suspend fun setSeenFlag(+        server: ServerConfig,+        user: String,+        auth: AuthType,+        folderName: String,+        uid: Long,+        seen: Boolean,+    ) = ImapClient.setSeenFlag(server, user, auth, folderName, uid, seen)++    suspend fun deleteMessage(+        server: ServerConfig,+        user: String,+        auth: AuthType,+        folderName: String,+        uid: Long,+    ) = ImapClient.deleteMessage(server, user, auth, folderName, uid)++    suspend fun downloadAttachment(+        context: Context,+        server: ServerConfig,+        user: String,+        auth: AuthType,+        folderName: String,+        uid: Long,+        partId: String,+        fileName: String,+        mimeType: String,+    ): String = ImapClient.downloadAttachment(context, server, user, auth, folderName, uid, partId, fileName, mimeType)++    suspend fun fetchRawMessageBytes(+        server: ServerConfig,+        user: String,+        auth: AuthType,+        folderName: String,+        uid: Long,+    ): ByteArray = ImapClient.fetchRawMessageBytes(server, user, auth, folderName, uid)++    suspend fun fetchRawMessageTo(+        server: ServerConfig,+        user: String,+        auth: AuthType,+        folderName: String,+        uid: Long,+        output: OutputStream,+    ) = ImapClient.fetchRawMessageTo(server, user, auth, folderName, uid, output)++    suspend fun sendMessage(+        context: Context,+        server: ServerConfig,+        user: String,+        auth: AuthType,+        to: String,+        subject: String,+        body: String,+        cc: String? = null,+        bcc: String? = null,+        attachments: List<Uri> = emptyList(),+        inlineImages: List<InlineAttachment> = emptyList(),+        inReplyTo: String? = null,+        references: String? = null,+        from: String? = null,+        asHtml: Boolean = false,+    ) = SmtpClient.sendMessage(context, server, user, auth, to, subject, body, cc, bcc, attachments, inlineImages, inReplyTo, references, from, asHtml)+}
email/src/main/java/com/vayunmathur/email/platform/EmailNotificationActionReceiver.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailNotificationActionReceiver.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailNotificationActionReceiver.ktindex 21e4db9e70..dbc5033b63 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailNotificationActionReceiver.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailNotificationActionReceiver.kt@@ -5,11 +5,11 @@ import android.content.Context import android.content.Intent import android.util.Log import androidx.core.app.NotificationManagerCompat-import com.vayunmathur.email.data.EmailManager-import com.vayunmathur.email.data.resolveAuth+import com.vayunmathur.email.platform.EmailManager+import com.vayunmathur.email.platform.resolveAuth import com.vayunmathur.email.data.EmailRepository-import com.vayunmathur.email.data.imapServer-import com.vayunmathur.email.data.loginUser+import com.vayunmathur.email.platform.imapServer+import com.vayunmathur.email.platform.loginUser import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch
email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.ktindex 7787bc981d..2811674c4a 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt@@ -1,597 +1,603 @@-package com.vayunmathur.email.platform--import android.app.Application-import android.content.ComponentName-import android.content.Intent-import android.net.Uri-import android.os.Handler-import android.os.Looper-import androidx.lifecycle.AndroidViewModel-import androidx.lifecycle.viewModelScope-import com.vayunmathur.email.data.EmailRepository-import com.vayunmathur.email.data.EmailSyncState-import com.vayunmathur.email.data.EmailSyncWorker-import com.vayunmathur.email.data.OutboxManager-import com.vayunmathur.email.data.OutboxSendWorker-import com.vayunmathur.email.platform.MessageListActions-import com.vayunmathur.email.platform.MessageThreadActions-import com.vayunmathur.library.util.SecureResultReceiver-import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.flow.*-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.jsonObject-import kotlinx.serialization.json.jsonPrimitive--@OptIn(ExperimentalCoroutinesApi::class)-class EmailViewModel(application: Application) :-    AndroidViewModel(application), MessageListActions, MessageThreadActions {-    private val repository = EmailRepository.get(application)-    private val dao: com.vayunmathur.email.data.EmailDao get() = repository.getDatabase().emailDao()-    private val emailManager = EmailManager()-    private val appContext = application.applicationContext-    -    val accounts: StateFlow<List<EmailAccount>> =-        dao.getAccountsFlow().stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())--    /** Active sync state — drives the linear progress bar at the top of the inbox. */-    val isSyncing: StateFlow<Boolean> = EmailSyncState.isSyncing-    val syncProgress: StateFlow<Float> = EmailSyncState.progress--    val outbox: Flow<List<OutboxEntry>> = dao.getOutboxFlow()-    val drafts: Flow<List<com.vayunmathur.email.data.DraftEntry>> = dao.getDraftsFlow()--    /** Load a draft for resuming in the composer. */-    suspend fun loadDraft(id: Long): com.vayunmathur.email.data.DraftEntry? = dao.getDraft(id)--    /** Insert or update a draft; returns its id (new id when [id] is null). */-    fun saveDraft(-        id: Long?,-        accountEmail: String,-        to: String,-        cc: String,-        bcc: String,-        subject: String,-        body: String,-        onSaved: (Long) -> Unit = {},-    ) {-        viewModelScope.launch {-            val rowId = dao.insertDraft(-                com.vayunmathur.email.data.DraftEntry(-                    id = id ?: 0,-                    accountEmail = accountEmail,-                    to = to, cc = cc, bcc = bcc, subject = subject, body = body,-                    updatedAt = System.currentTimeMillis(),-                )-            )-            onSaved(if (id != null && id != 0L) id else rowId)-        }-    }--    fun deleteDraft(id: Long) {-        viewModelScope.launch { dao.deleteDraftById(id) }-    }--    /** Block a sender (matched by email address) so their mail is hidden from the inbox. */-    override fun blockSender(from: String) {-        val address = extractEmailAddress(from)-        if (address.isBlank()) return-        viewModelScope.launch { dao.insertBlockedSender(com.vayunmathur.email.data.BlockedSender(address.lowercase())) }-    }--    fun unblockSender(address: String) {-        viewModelScope.launch { dao.deleteBlockedSender(address) }-    }--    /** Queue a message to send at [scheduledAt] (epoch millis) via the outbox. */-    fun scheduleSend(-        account: EmailAccount,-        to: String,-        subject: String,-        body: String,-        cc: String? = null,-        bcc: String? = null,-        attachments: List<Uri> = emptyList(),-        inlineImages: List<com.vayunmathur.email.ui.composer.InlineAttachment> = emptyList(),-        inReplyTo: String? = null,-        references: String? = null,-        scheduledAt: Long,-        asHtml: Boolean = false,-        onDone: () -> Unit = {},-    ) {-        viewModelScope.launch {-            OutboxManager.enqueue(-                context = getApplication(),-                accountEmail = account.email,-                to = to, subject = subject, body = body,-                cc = cc, bcc = bcc, attachments = attachments,-                inlineImages = inlineImages,-                inReplyTo = inReplyTo, references = references,-                scheduledAt = scheduledAt,-                isHtml = asHtml,-            )-            onDone()-        }-    }--    private val _aiSummary = MutableStateFlow<String?>(null)-    val aiSummary: StateFlow<String?> = _aiSummary--    private val _aiSummaryLoading = MutableStateFlow(false)-    val aiSummaryLoading: StateFlow<Boolean> = _aiSummaryLoading-    -    private val _selectedAccountEmail = MutableStateFlow<String?>(null)-    val selectedAccountEmail: StateFlow<String?> = _selectedAccountEmail--    val selectedAccount = _selectedAccountEmail.flatMapLatest { email ->-        if (email == null) flowOf(null)-        else accounts.map { list -> list.find { it.email == email } }-    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)--    val folders = _selectedAccountEmail.flatMapLatest { email ->-        if (email == null) flowOf(emptyList())-        else dao.getFoldersFlow(email)-    }-    -    private val _selectedFolderName = MutableStateFlow("INBOX")-    val selectedFolderName: StateFlow<String> = _selectedFolderName--    private val _searchQuery = MutableStateFlow("")-    val searchQuery: StateFlow<String> = _searchQuery--    private val _selectedMessageUids = MutableStateFlow<Set<Long>>(emptySet())-    val selectedMessageUids: StateFlow<Set<Long>> = _selectedMessageUids--    private val messagesRaw: Flow<List<EmailMessage>> = combine(-        _selectedAccountEmail,-        _selectedFolderName,-        _searchQuery-    ) { email, folder, query ->-        Triple(email, folder, query)-    }.flatMapLatest { (email, folder, query) ->-        val now = System.currentTimeMillis()-        if (email == null) {-            // Unified Inbox-            if (query.isEmpty()) dao.getUnifiedMessagesFlow("INBOX", now)-            else dao.searchUnifiedMessagesFlow("INBOX", query, now)-        } else {-            if (query.isEmpty()) {-                dao.getMessagesFlow(email, folder, now)-            } else {-                dao.searchMessagesFlow(email, folder, query, now)-            }-        }-    }--    val blockedSenders: Flow<List<com.vayunmathur.email.data.BlockedSender>> = dao.getBlockedSendersFlow()--    // Hide messages from blocked senders (matched by email address substring).-    val messages: Flow<List<EmailMessage>> = combine(messagesRaw, blockedSenders) { msgs, blocked ->-        val addrs = blocked.map { it.address.lowercase() }-        if (addrs.isEmpty()) msgs-        else msgs.filter { m -> addrs.none { m.from.lowercase().contains(it) } }-    }--    init {-        viewModelScope.launch {-            dao.getAccounts().firstOrNull()?.let {-                _selectedAccountEmail.value = it.email-            }-        }-    }--    fun selectAccount(email: String) {-        _selectedAccountEmail.value = if (email.isEmpty()) null else email-        _selectedFolderName.value = "INBOX"-        _searchQuery.value = ""-    }--    /** Persist the per-account signature appended to outgoing messages. */-    fun setSignature(email: String, signature: String) {-        viewModelScope.launch {-            dao.setSignature(email, signature)-        }-    }--    fun selectFolder(folderName: String) {-        _selectedFolderName.value = folderName-        _searchQuery.value = ""-    }--    override fun setSearchQuery(query: String) {-        _searchQuery.value = query-        if (query.isEmpty()) {-            _aiSummary.value = null-            _aiSummaryLoading.value = false-        }-    }--    override fun requestAiSummary(messages: List<EmailMessage>) {-        if (_aiSummaryLoading.value) return--        val pm = appContext.packageManager-        try {-            pm.getPackageInfo(OA_PACKAGE, 0)-        } catch (_: Exception) {-            return-        }--        _aiSummaryLoading.value = true-        _aiSummary.value = null--        val emailSnippets = messages.take(5).joinToString("\n---\n") { msg ->-            val plainBody = msg.previewText(150)-            "Subject: ${msg.subject}\nFrom: ${senderDisplayName(msg.from)}\n$plainBody"-        }-        val prompt = "Summarize these emails in 1-2 sentences:\n\n$emailSnippets"-        val schema = """{"type":"object","properties":{"summary":{"type":"string"}},"required":["summary"]}"""--        val receiver = SecureResultReceiver(Handler(Looper.getMainLooper())) { code, data ->-            if (code == 0) {-                val json = data?.getString("json_result")-                if (json != null) {-                    try {-                        val obj = Json.parseToJsonElement(json).jsonObject-                        _aiSummary.value = obj["summary"]?.jsonPrimitive?.content-                    } catch (_: Exception) { }-                }-            }-            _aiSummaryLoading.value = false-        }--        val intent = Intent().apply {-            component = ComponentName(OA_PACKAGE, OA_SERVICE)-            putExtra("user_text", prompt)-            putExtra("schema", schema)-            putExtra("RECEIVER", receiver as android.os.ResultReceiver)-        }--        try {-            appContext.startForegroundService(intent)-        } catch (_: Exception) {-            _aiSummaryLoading.value = false-        }-    }--    override fun toggleMessageSelection(uid: Long) {-        _selectedMessageUids.update { if (uid in it) it - uid else it + uid }-    }--    override fun clearSelection() {-        _selectedMessageUids.value = emptySet()-    }--    /** Delete a message: remove locally (with a tombstone so sync won't re-add it) and expunge it on the IMAP server. */-    override fun deleteMessage(accountEmail: String, folderName: String, uid: Long) {-        viewModelScope.launch {-            dao.deleteMessageRow(accountEmail, folderName, uid, tombstone = true)-            val account = dao.getAccountByEmail(accountEmail) ?: return@launch-            try {-                emailManager.deleteMessage(-                    server = account.imapServer(),-                    user = account.loginUser(),-                    auth = account.resolveAuth(appContext),-                    folderName = folderName,-                    uid = uid,-                )-            } catch (e: Exception) {-                android.util.Log.w("EmailViewModel", "Failed to delete message on server: ${e.message}")-            }-        }-    }--    /** Snooze a message: hide from the inbox until [until] (epoch millis), then resurface. */-    override fun snoozeMessage(accountEmail: String, folderName: String, uid: Long, until: Long) {-        viewModelScope.launch {-            dao.setSnooze(accountEmail, folderName, uid, until)-            com.vayunmathur.email.data.SnoozeWorker.scheduleNext(getApplication(), until)-        }-    }--    override fun markAsRead(accountEmail: String, folderName: String, uid: Long, isRead: Boolean) {-        viewModelScope.launch {-            dao.updateReadStatus(accountEmail, folderName, uid, isRead)-            // Sync read status to IMAP server-            val account = dao.getAccountByEmail(accountEmail) ?: return@launch-            try {-                emailManager.setSeenFlag(-                    server = account.imapServer(),-                    user = account.loginUser(),-                    auth = account.resolveAuth(appContext),-                    folderName = folderName,-                    uid = uid,-                    seen = isRead,-                )-            } catch (e: Exception) {-                android.util.Log.w("EmailViewModel", "Failed to sync read status to server: ${e.message}")-            }-        }-    }--    override fun bulkMarkAsRead(accountEmail: String, uids: List<Long>, isRead: Boolean) {-        viewModelScope.launch {-            dao.updateBulkReadStatus(accountEmail, uids, isRead)-            clearSelection()-        }-    }--    override fun refresh(context: android.content.Context) {-        EmailSyncWorker.runOneOffSync(context)-    }--    suspend fun getMessage(accountEmail: String, folderName: String, uid: Long): EmailMessage? {-        return dao.getMessage(accountEmail, folderName, uid)-    }--    fun getThread(accountEmail: String, threadId: String): Flow<List<EmailMessage>> {-        return dao.getThreadFlow(accountEmail, threadId)-    }--    override suspend fun getAttachments(accountEmail: String, messageId: Long): List<Attachment> {-        return dao.getAttachments(accountEmail, messageId)-    }--    fun logout(context: android.content.Context) {-        val currentEmail = _selectedAccountEmail.value ?: return-        viewModelScope.launch {-            dao.getAccounts().find { it.email == currentEmail }?.let { account ->-                dao.deleteAccount(account)-                dao.clearFolders(currentEmail)-                dao.clearMessages(currentEmail)-            }-            val remaining = dao.getAccounts()-            _selectedAccountEmail.value = remaining.firstOrNull()?.email-            if (remaining.isEmpty()) {-                EmailSyncWorker.cancelSync(context)-                com.vayunmathur.email.data.ImapIdleService.stop(context)-            }-        }-    }--    fun sendEmailFrom(-        account: EmailAccount,-        to: String,-        subject: String,-        body: String,-        cc: String? = null,-        bcc: String? = null,-        attachments: List<Uri> = emptyList(),-        inlineImages: List<com.vayunmathur.email.ui.composer.InlineAttachment> = emptyList(),-        inReplyTo: String? = null,-        references: String? = null,-        asHtml: Boolean = false,-        onSuccess: () -> Unit,-        onError: (String) -> Unit,-    ) {-        viewModelScope.launch {-            try {-                emailManager.sendMessage(-                    context = getApplication(),-                    server = account.smtpServer(),-                    user = account.loginUser(),-                    auth = account.resolveAuth(appContext),-                    to = to,-                    subject = subject,-                    body = body,-                    cc = cc,-                    bcc = bcc,-                    attachments = attachments,-                    inlineImages = inlineImages,-                    inReplyTo = inReplyTo,-                    references = references,-                    from = account.email,-                    asHtml = asHtml,-                )-                onSuccess()-            } catch (e: Exception) {-                val msg = e.message ?: e::class.simpleName ?: "Unknown error"-                try {-                    OutboxManager.enqueue(-                        context = getApplication(),-                        accountEmail = account.email,-                        to = to,-                        subject = subject,-                        body = body,-                        cc = cc,-                        bcc = bcc,-                        attachments = attachments,-                        inlineImages = inlineImages,-                        inReplyTo = inReplyTo,-                        references = references,-                        initialError = msg,-                        isHtml = asHtml,-                    )-                } catch (queueError: Exception) {-                    onError("$msg (and outbox save failed: ${queueError.message})")-                    return@launch-                }-                onError(msg)-            }-        }-    }--    /**-     * Lazy-load the body + attachments for a single message. Called by-     * MessageItem when a stored row has `body == null` (the sync only fetches-     * headers — bodies are downloaded on first open). Updates the row in the-     * DB; the Flow-based UI will recompose automatically.-     * Also extracts inline CID images to cache/cid/<uid>/ for viewer rendering.-     */-    override fun fetchBodyIfNeeded(message: EmailMessage) {-        if (message.body != null) return-        viewModelScope.launch {-            val account = dao.getAccountByEmail(message.accountEmail) ?: return@launch-            try {-                // We need raw mime to extract CID files-                val ctx = getApplication<Application>()-                val full = emailManager.fetchFullForBody(-                    context = ctx,-                    server = account.imapServer(),-                    user = account.loginUser(),-                    auth = account.resolveAuth(appContext),-                    folderName = message.folderName,-                    uid = message.id,-                )-                val (body, isHtml, attachments) = full.contentTriple-                if (body != null || attachments.isNotEmpty()) {-                    dao.insertMessages(listOf(message.copy(body = body, isHtml = isHtml, hasAttachments = attachments.isNotEmpty())))-                    if (attachments.isNotEmpty()) dao.insertAttachments(attachments)-                }-            } catch (e: Exception) {-                android.util.Log.w("EmailViewModel", "fetchBodyIfNeeded for ${message.id} failed: ${e.message}")-            }-        }-    }--    /** CID map loader for already-fetched message – extracts inline files to cache and returns map */-    override suspend fun loadCidMap(context: android.content.Context, message: EmailMessage): Map<String, java.io.File> {-        return try {-            val account = dao.getAccountByEmail(message.accountEmail) ?: return emptyMap()-            val auth = account.resolveAuth(appContext)-            emailManager.fetchCidMap(-                context = context,-                server = account.imapServer(),-                user = account.loginUser(),-                auth = auth,-                folderName = message.folderName,-                uid = message.id,-            )-        } catch (e: Exception) {-            android.util.Log.w("EmailViewModel", "loadCidMap failed: ${e.message}")-            emptyMap()-        }-    }--    /**-     * Perform an RFC 8058 one-click unsubscribe: an HTTPS POST to [url] with the-     * body `List-Unsubscribe=One-Click`. Runs off the main thread and reports-     * success (a 2xx response) via [onResult] on the main thread.-     */-    override fun oneClickUnsubscribe(url: String, onResult: (Boolean) -> Unit) {-        viewModelScope.launch {-            val ok = withContext(Dispatchers.IO) {-                try {-                    val connection = (java.net.URL(url).openConnection() as java.net.HttpURLConnection).apply {-                        requestMethod = "POST"-                        doOutput = true-                        connectTimeout = 15_000-                        readTimeout = 15_000-                        setRequestProperty("Content-Type", "application/x-www-form-urlencoded")-                    }-                    try {-                        connection.outputStream.use { it.write("List-Unsubscribe=One-Click".toByteArray()) }-                        connection.responseCode in 200..299-                    } finally {-                        connection.disconnect()-                    }-                } catch (e: Exception) {-                    android.util.Log.w("EmailViewModel", "one-click unsubscribe failed: ${e.message}")-                    false-                }-            }-            onResult(ok)-        }-    }--    fun deleteOutboxEntry(entry: OutboxEntry) {-        viewModelScope.launch {-            OutboxManager.delete(getApplication(), entry)-        }-    }--    fun sendOutboxNow(context: android.content.Context) {-        OutboxSendWorker.runNow(context)-    }--    override fun downloadAttachment(-        attachment: Attachment,-        onSuccess: (String) -> Unit,-        onError: (String) -> Unit-    ) {-        val account = selectedAccount.value ?: return onError("No account selected")-        viewModelScope.launch {-            try {-                val path = emailManager.downloadAttachment(-                    context = getApplication(),-                    server = account.imapServer(),-                    user = account.loginUser(),-                    auth = account.resolveAuth(appContext),-                    folderName = attachment.folderName,-                    uid = attachment.messageId,-                    partId = attachment.partId,-                    fileName = attachment.fileName,-                    mimeType = attachment.mimeType-                )-                dao.updateAttachmentLocalUri(account.email, attachment.messageId, attachment.partId, path)-                onSuccess(path)-            } catch (e: Exception) {-                onError(e.message ?: "Unknown error")-            }-        }-    }--    /**-     * Export a single email as a .eml file to a SAF [targetUri] (from CreateDocument).-     * Streams the raw RFC822 bytes directly to avoid OOM on large messages.-     */-    override fun exportEml(-        accountEmail: String,-        folderName: String,-        uid: Long,-        targetUri: Uri,-        onResult: (Boolean, String?) -> Unit,-    ) {-        viewModelScope.launch(Dispatchers.IO) {-            try {-                val account = dao.getAccountByEmail(accountEmail)-                    ?: run {-                        withContext(Dispatchers.Main) { onResult(false, "Account not found") }-                        return@launch-                    }-                val server = account.imapServer()-                val user = account.loginUser()-                val auth = account.resolveAuth(appContext)-                val ctx = getApplication<Application>()-                ctx.contentResolver.openOutputStream(targetUri)?.use { out ->-                    emailManager.fetchRawMessageTo(server, user, auth, folderName, uid, out)-                } ?: run {-                    withContext(Dispatchers.Main) { onResult(false, "Could not open destination") }-                    return@launch-                }-                withContext(Dispatchers.Main) { onResult(true, null) }-            } catch (e: Exception) {-                android.util.Log.w("EmailViewModel", "exportEml failed: ${e.message}", e)-                withContext(Dispatchers.Main) { onResult(false, e.message ?: e.javaClass.simpleName) }-            }-        }-    }--    companion object {-        private const val OA_PACKAGE = "com.vayunmathur.openassistant"-        private const val OA_SERVICE = "$OA_PACKAGE.util.InferenceService"-    }-}--/** Extract the bare email address from a "Name <addr@x>" header, or "" if none. */-private fun extractEmailAddress(from: String): String {-    val trimmed = from.trim()-    if (trimmed.isEmpty()) return ""-    val angleMatch = Regex("""<([^>]+@[^>]+)>""").find(trimmed)-    if (angleMatch != null) {-        val addr = angleMatch.groupValues[1].trim()-        if (addr.contains("@")) return addr-    }-    // Try bare address token-    val tokens = trimmed.split(Regex("[\\s,;<>]+"))-    for (t in tokens) {-        if (t.contains("@") && t.contains(".")) return t.trim().trim('"', '\'', '<', '>')-    }-    // Fallback: contains @ anywhere-    if (trimmed.contains("@")) {-        val maybe = trimmed.substringAfterLast(' ').trim()-        if (maybe.contains("@")) return maybe.trim('<', '>', '"', '\'')-    }-    return ""-}+package com.vayunmathur.email.platform++import android.app.Application+import android.content.ComponentName+import android.content.Intent+import android.net.Uri+import android.os.Handler+import android.os.Looper+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.email.data.EmailAccount+import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.Attachment+import com.vayunmathur.email.data.previewText+import com.vayunmathur.email.data.senderDisplayName+import com.vayunmathur.email.data.EmailRepository+import com.vayunmathur.email.data.EmailSyncState+import com.vayunmathur.email.data.EmailSyncWorker+import com.vayunmathur.email.data.OutboxEntry+import com.vayunmathur.email.data.OutboxManager+import com.vayunmathur.email.data.OutboxSendWorker+import com.vayunmathur.email.platform.MessageListActions+import com.vayunmathur.email.platform.MessageThreadActions+import com.vayunmathur.library.util.SecureResultReceiver+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.*+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive++@OptIn(ExperimentalCoroutinesApi::class)+class EmailViewModel(application: Application) :+    AndroidViewModel(application), MessageListActions, MessageThreadActions {+    private val repository = EmailRepository.get(application)+    private val dao: com.vayunmathur.email.data.EmailDao get() = repository.getDatabase().emailDao()+    private val emailManager = EmailManager()+    private val appContext = application.applicationContext+    +    val accounts: StateFlow<List<EmailAccount>> =+        dao.getAccountsFlow().stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    /** Active sync state — drives the linear progress bar at the top of the inbox. */+    val isSyncing: StateFlow<Boolean> = EmailSyncState.isSyncing+    val syncProgress: StateFlow<Float> = EmailSyncState.progress++    val outbox: Flow<List<OutboxEntry>> = dao.getOutboxFlow()+    val drafts: Flow<List<com.vayunmathur.email.data.DraftEntry>> = dao.getDraftsFlow()++    /** Load a draft for resuming in the composer. */+    suspend fun loadDraft(id: Long): com.vayunmathur.email.data.DraftEntry? = dao.getDraft(id)++    /** Insert or update a draft; returns its id (new id when [id] is null). */+    fun saveDraft(+        id: Long?,+        accountEmail: String,+        to: String,+        cc: String,+        bcc: String,+        subject: String,+        body: String,+        onSaved: (Long) -> Unit = {},+    ) {+        viewModelScope.launch {+            val rowId = dao.insertDraft(+                com.vayunmathur.email.data.DraftEntry(+                    id = id ?: 0,+                    accountEmail = accountEmail,+                    to = to, cc = cc, bcc = bcc, subject = subject, body = body,+                    updatedAt = System.currentTimeMillis(),+                )+            )+            onSaved(if (id != null && id != 0L) id else rowId)+        }+    }++    fun deleteDraft(id: Long) {+        viewModelScope.launch { dao.deleteDraftById(id) }+    }++    /** Block a sender (matched by email address) so their mail is hidden from the inbox. */+    override fun blockSender(from: String) {+        val address = extractEmailAddress(from)+        if (address.isBlank()) return+        viewModelScope.launch { dao.insertBlockedSender(com.vayunmathur.email.data.BlockedSender(address.lowercase())) }+    }++    fun unblockSender(address: String) {+        viewModelScope.launch { dao.deleteBlockedSender(address) }+    }++    /** Queue a message to send at [scheduledAt] (epoch millis) via the outbox. */+    fun scheduleSend(+        account: EmailAccount,+        to: String,+        subject: String,+        body: String,+        cc: String? = null,+        bcc: String? = null,+        attachments: List<Uri> = emptyList(),+        inlineImages: List<com.vayunmathur.email.ui.composer.InlineAttachment> = emptyList(),+        inReplyTo: String? = null,+        references: String? = null,+        scheduledAt: Long,+        asHtml: Boolean = false,+        onDone: () -> Unit = {},+    ) {+        viewModelScope.launch {+            OutboxManager.enqueue(+                context = getApplication(),+                accountEmail = account.email,+                to = to, subject = subject, body = body,+                cc = cc, bcc = bcc, attachments = attachments,+                inlineImages = inlineImages,+                inReplyTo = inReplyTo, references = references,+                scheduledAt = scheduledAt,+                isHtml = asHtml,+            )+            onDone()+        }+    }++    private val _aiSummary = MutableStateFlow<String?>(null)+    val aiSummary: StateFlow<String?> = _aiSummary++    private val _aiSummaryLoading = MutableStateFlow(false)+    val aiSummaryLoading: StateFlow<Boolean> = _aiSummaryLoading+    +    private val _selectedAccountEmail = MutableStateFlow<String?>(null)+    val selectedAccountEmail: StateFlow<String?> = _selectedAccountEmail++    val selectedAccount = _selectedAccountEmail.flatMapLatest { email ->+        if (email == null) flowOf(null)+        else accounts.map { list -> list.find { it.email == email } }+    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)++    val folders = _selectedAccountEmail.flatMapLatest { email ->+        if (email == null) flowOf(emptyList())+        else dao.getFoldersFlow(email)+    }+    +    private val _selectedFolderName = MutableStateFlow("INBOX")+    val selectedFolderName: StateFlow<String> = _selectedFolderName++    private val _searchQuery = MutableStateFlow("")+    val searchQuery: StateFlow<String> = _searchQuery++    private val _selectedMessageUids = MutableStateFlow<Set<Long>>(emptySet())+    val selectedMessageUids: StateFlow<Set<Long>> = _selectedMessageUids++    private val messagesRaw: Flow<List<EmailMessage>> = combine(+        _selectedAccountEmail,+        _selectedFolderName,+        _searchQuery+    ) { email, folder, query ->+        Triple(email, folder, query)+    }.flatMapLatest { (email, folder, query) ->+        val now = System.currentTimeMillis()+        if (email == null) {+            // Unified Inbox+            if (query.isEmpty()) dao.getUnifiedMessagesFlow("INBOX", now)+            else dao.searchUnifiedMessagesFlow("INBOX", query, now)+        } else {+            if (query.isEmpty()) {+                dao.getMessagesFlow(email, folder, now)+            } else {+                dao.searchMessagesFlow(email, folder, query, now)+            }+        }+    }++    val blockedSenders: Flow<List<com.vayunmathur.email.data.BlockedSender>> = dao.getBlockedSendersFlow()++    // Hide messages from blocked senders (matched by email address substring).+    val messages: Flow<List<EmailMessage>> = combine(messagesRaw, blockedSenders) { msgs, blocked ->+        val addrs = blocked.map { it.address.lowercase() }+        if (addrs.isEmpty()) msgs+        else msgs.filter { m -> addrs.none { m.from.lowercase().contains(it) } }+    }++    init {+        viewModelScope.launch {+            dao.getAccounts().firstOrNull()?.let {+                _selectedAccountEmail.value = it.email+            }+        }+    }++    fun selectAccount(email: String) {+        _selectedAccountEmail.value = if (email.isEmpty()) null else email+        _selectedFolderName.value = "INBOX"+        _searchQuery.value = ""+    }++    /** Persist the per-account signature appended to outgoing messages. */+    fun setSignature(email: String, signature: String) {+        viewModelScope.launch {+            dao.setSignature(email, signature)+        }+    }++    fun selectFolder(folderName: String) {+        _selectedFolderName.value = folderName+        _searchQuery.value = ""+    }++    override fun setSearchQuery(query: String) {+        _searchQuery.value = query+        if (query.isEmpty()) {+            _aiSummary.value = null+            _aiSummaryLoading.value = false+        }+    }++    override fun requestAiSummary(messages: List<EmailMessage>) {+        if (_aiSummaryLoading.value) return++        val pm = appContext.packageManager+        try {+            pm.getPackageInfo(OA_PACKAGE, 0)+        } catch (_: Exception) {+            return+        }++        _aiSummaryLoading.value = true+        _aiSummary.value = null++        val emailSnippets = messages.take(5).joinToString("\n---\n") { msg ->+            val plainBody = msg.previewText(150)+            "Subject: ${msg.subject}\nFrom: ${senderDisplayName(msg.from)}\n$plainBody"+        }+        val prompt = "Summarize these emails in 1-2 sentences:\n\n$emailSnippets"+        val schema = """{"type":"object","properties":{"summary":{"type":"string"}},"required":["summary"]}"""++        val receiver = SecureResultReceiver(Handler(Looper.getMainLooper())) { code, data ->+            if (code == 0) {+                val json = data?.getString("json_result")+                if (json != null) {+                    try {+                        val obj = Json.parseToJsonElement(json).jsonObject+                        _aiSummary.value = obj["summary"]?.jsonPrimitive?.content+                    } catch (_: Exception) { }+                }+            }+            _aiSummaryLoading.value = false+        }++        val intent = Intent().apply {+            component = ComponentName(OA_PACKAGE, OA_SERVICE)+            putExtra("user_text", prompt)+            putExtra("schema", schema)+            putExtra("RECEIVER", receiver as android.os.ResultReceiver)+        }++        try {+            appContext.startForegroundService(intent)+        } catch (_: Exception) {+            _aiSummaryLoading.value = false+        }+    }++    override fun toggleMessageSelection(uid: Long) {+        _selectedMessageUids.update { if (uid in it) it - uid else it + uid }+    }++    override fun clearSelection() {+        _selectedMessageUids.value = emptySet()+    }++    /** Delete a message: remove locally (with a tombstone so sync won't re-add it) and expunge it on the IMAP server. */+    override fun deleteMessage(accountEmail: String, folderName: String, uid: Long) {+        viewModelScope.launch {+            dao.deleteMessageRow(accountEmail, folderName, uid, tombstone = true)+            val account = dao.getAccountByEmail(accountEmail) ?: return@launch+            try {+                emailManager.deleteMessage(+                    server = account.imapServer(),+                    user = account.loginUser(),+                    auth = account.resolveAuth(appContext),+                    folderName = folderName,+                    uid = uid,+                )+            } catch (e: Exception) {+                android.util.Log.w("EmailViewModel", "Failed to delete message on server: ${e.message}")+            }+        }+    }++    /** Snooze a message: hide from the inbox until [until] (epoch millis), then resurface. */+    override fun snoozeMessage(accountEmail: String, folderName: String, uid: Long, until: Long) {+        viewModelScope.launch {+            dao.setSnooze(accountEmail, folderName, uid, until)+            com.vayunmathur.email.data.SnoozeWorker.scheduleNext(getApplication(), until)+        }+    }++    override fun markAsRead(accountEmail: String, folderName: String, uid: Long, isRead: Boolean) {+        viewModelScope.launch {+            dao.updateReadStatus(accountEmail, folderName, uid, isRead)+            // Sync read status to IMAP server+            val account = dao.getAccountByEmail(accountEmail) ?: return@launch+            try {+                emailManager.setSeenFlag(+                    server = account.imapServer(),+                    user = account.loginUser(),+                    auth = account.resolveAuth(appContext),+                    folderName = folderName,+                    uid = uid,+                    seen = isRead,+                )+            } catch (e: Exception) {+                android.util.Log.w("EmailViewModel", "Failed to sync read status to server: ${e.message}")+            }+        }+    }++    override fun bulkMarkAsRead(accountEmail: String, uids: List<Long>, isRead: Boolean) {+        viewModelScope.launch {+            dao.updateBulkReadStatus(accountEmail, uids, isRead)+            clearSelection()+        }+    }++    override fun refresh(context: android.content.Context) {+        EmailSyncWorker.runOneOffSync(context)+    }++    suspend fun getMessage(accountEmail: String, folderName: String, uid: Long): EmailMessage? {+        return dao.getMessage(accountEmail, folderName, uid)+    }++    fun getThread(accountEmail: String, threadId: String): Flow<List<EmailMessage>> {+        return dao.getThreadFlow(accountEmail, threadId)+    }++    override suspend fun getAttachments(accountEmail: String, messageId: Long): List<Attachment> {+        return dao.getAttachments(accountEmail, messageId)+    }++    fun logout(context: android.content.Context) {+        val currentEmail = _selectedAccountEmail.value ?: return+        viewModelScope.launch {+            dao.getAccounts().find { it.email == currentEmail }?.let { account ->+                dao.deleteAccount(account)+                dao.clearFolders(currentEmail)+                dao.clearMessages(currentEmail)+            }+            val remaining = dao.getAccounts()+            _selectedAccountEmail.value = remaining.firstOrNull()?.email+            if (remaining.isEmpty()) {+                EmailSyncWorker.cancelSync(context)+                com.vayunmathur.email.data.ImapIdleService.stop(context)+            }+        }+    }++    fun sendEmailFrom(+        account: EmailAccount,+        to: String,+        subject: String,+        body: String,+        cc: String? = null,+        bcc: String? = null,+        attachments: List<Uri> = emptyList(),+        inlineImages: List<com.vayunmathur.email.ui.composer.InlineAttachment> = emptyList(),+        inReplyTo: String? = null,+        references: String? = null,+        asHtml: Boolean = false,+        onSuccess: () -> Unit,+        onError: (String) -> Unit,+    ) {+        viewModelScope.launch {+            try {+                emailManager.sendMessage(+                    context = getApplication(),+                    server = account.smtpServer(),+                    user = account.loginUser(),+                    auth = account.resolveAuth(appContext),+                    to = to,+                    subject = subject,+                    body = body,+                    cc = cc,+                    bcc = bcc,+                    attachments = attachments,+                    inlineImages = inlineImages,+                    inReplyTo = inReplyTo,+                    references = references,+                    from = account.email,+                    asHtml = asHtml,+                )+                onSuccess()+            } catch (e: Exception) {+                val msg = e.message ?: e::class.simpleName ?: "Unknown error"+                try {+                    OutboxManager.enqueue(+                        context = getApplication(),+                        accountEmail = account.email,+                        to = to,+                        subject = subject,+                        body = body,+                        cc = cc,+                        bcc = bcc,+                        attachments = attachments,+                        inlineImages = inlineImages,+                        inReplyTo = inReplyTo,+                        references = references,+                        initialError = msg,+                        isHtml = asHtml,+                    )+                } catch (queueError: Exception) {+                    onError("$msg (and outbox save failed: ${queueError.message})")+                    return@launch+                }+                onError(msg)+            }+        }+    }++    /**+     * Lazy-load the body + attachments for a single message. Called by+     * MessageItem when a stored row has `body == null` (the sync only fetches+     * headers — bodies are downloaded on first open). Updates the row in the+     * DB; the Flow-based UI will recompose automatically.+     * Also extracts inline CID images to cache/cid/<uid>/ for viewer rendering.+     */+    override fun fetchBodyIfNeeded(message: EmailMessage) {+        if (message.body != null) return+        viewModelScope.launch {+            val account = dao.getAccountByEmail(message.accountEmail) ?: return@launch+            try {+                // We need raw mime to extract CID files+                val ctx = getApplication<Application>()+                val full = emailManager.fetchFullForBody(+                    context = ctx,+                    server = account.imapServer(),+                    user = account.loginUser(),+                    auth = account.resolveAuth(appContext),+                    folderName = message.folderName,+                    uid = message.id,+                )+                val (body, isHtml, attachments) = full.contentTriple+                if (body != null || attachments.isNotEmpty()) {+                    dao.insertMessages(listOf(message.copy(body = body, isHtml = isHtml, hasAttachments = attachments.isNotEmpty())))+                    if (attachments.isNotEmpty()) dao.insertAttachments(attachments)+                }+            } catch (e: Exception) {+                android.util.Log.w("EmailViewModel", "fetchBodyIfNeeded for ${message.id} failed: ${e.message}")+            }+        }+    }++    /** CID map loader for already-fetched message – extracts inline files to cache and returns map */+    override suspend fun loadCidMap(context: android.content.Context, message: EmailMessage): Map<String, java.io.File> {+        return try {+            val account = dao.getAccountByEmail(message.accountEmail) ?: return emptyMap()+            val auth = account.resolveAuth(appContext)+            emailManager.fetchCidMap(+                context = context,+                server = account.imapServer(),+                user = account.loginUser(),+                auth = auth,+                folderName = message.folderName,+                uid = message.id,+            )+        } catch (e: Exception) {+            android.util.Log.w("EmailViewModel", "loadCidMap failed: ${e.message}")+            emptyMap()+        }+    }++    /**+     * Perform an RFC 8058 one-click unsubscribe: an HTTPS POST to [url] with the+     * body `List-Unsubscribe=One-Click`. Runs off the main thread and reports+     * success (a 2xx response) via [onResult] on the main thread.+     */+    override fun oneClickUnsubscribe(url: String, onResult: (Boolean) -> Unit) {+        viewModelScope.launch {+            val ok = withContext(Dispatchers.IO) {+                try {+                    val connection = (java.net.URL(url).openConnection() as java.net.HttpURLConnection).apply {+                        requestMethod = "POST"+                        doOutput = true+                        connectTimeout = 15_000+                        readTimeout = 15_000+                        setRequestProperty("Content-Type", "application/x-www-form-urlencoded")+                    }+                    try {+                        connection.outputStream.use { it.write("List-Unsubscribe=One-Click".toByteArray()) }+                        connection.responseCode in 200..299+                    } finally {+                        connection.disconnect()+                    }+                } catch (e: Exception) {+                    android.util.Log.w("EmailViewModel", "one-click unsubscribe failed: ${e.message}")+                    false+                }+            }+            onResult(ok)+        }+    }++    fun deleteOutboxEntry(entry: OutboxEntry) {+        viewModelScope.launch {+            OutboxManager.delete(getApplication(), entry)+        }+    }++    fun sendOutboxNow(context: android.content.Context) {+        OutboxSendWorker.runNow(context)+    }++    override fun downloadAttachment(+        attachment: Attachment,+        onSuccess: (String) -> Unit,+        onError: (String) -> Unit+    ) {+        val account = selectedAccount.value ?: return onError("No account selected")+        viewModelScope.launch {+            try {+                val path = emailManager.downloadAttachment(+                    context = getApplication(),+                    server = account.imapServer(),+                    user = account.loginUser(),+                    auth = account.resolveAuth(appContext),+                    folderName = attachment.folderName,+                    uid = attachment.messageId,+                    partId = attachment.partId,+                    fileName = attachment.fileName,+                    mimeType = attachment.mimeType+                )+                dao.updateAttachmentLocalUri(account.email, attachment.messageId, attachment.partId, path)+                onSuccess(path)+            } catch (e: Exception) {+                onError(e.message ?: "Unknown error")+            }+        }+    }++    /**+     * Export a single email as a .eml file to a SAF [targetUri] (from CreateDocument).+     * Streams the raw RFC822 bytes directly to avoid OOM on large messages.+     */+    override fun exportEml(+        accountEmail: String,+        folderName: String,+        uid: Long,+        targetUri: Uri,+        onResult: (Boolean, String?) -> Unit,+    ) {+        viewModelScope.launch(Dispatchers.IO) {+            try {+                val account = dao.getAccountByEmail(accountEmail)+                    ?: run {+                        withContext(Dispatchers.Main) { onResult(false, "Account not found") }+                        return@launch+                    }+                val server = account.imapServer()+                val user = account.loginUser()+                val auth = account.resolveAuth(appContext)+                val ctx = getApplication<Application>()+                ctx.contentResolver.openOutputStream(targetUri)?.use { out ->+                    emailManager.fetchRawMessageTo(server, user, auth, folderName, uid, out)+                } ?: run {+                    withContext(Dispatchers.Main) { onResult(false, "Could not open destination") }+                    return@launch+                }+                withContext(Dispatchers.Main) { onResult(true, null) }+            } catch (e: Exception) {+                android.util.Log.w("EmailViewModel", "exportEml failed: ${e.message}", e)+                withContext(Dispatchers.Main) { onResult(false, e.message ?: e.javaClass.simpleName) }+            }+        }+    }++    companion object {+        private const val OA_PACKAGE = "com.vayunmathur.openassistant"+        private const val OA_SERVICE = "$OA_PACKAGE.util.InferenceService"+    }+}++/** Extract the bare email address from a "Name <addr@x>" header, or "" if none. */+private fun extractEmailAddress(from: String): String {+    val trimmed = from.trim()+    if (trimmed.isEmpty()) return ""+    val angleMatch = Regex("""<([^>]+@[^>]+)>""").find(trimmed)+    if (angleMatch != null) {+        val addr = angleMatch.groupValues[1].trim()+        if (addr.contains("@")) return addr+    }+    // Try bare address token+    val tokens = trimmed.split(Regex("[\\s,;<>]+"))+    for (t in tokens) {+        if (t.contains("@") && t.contains(".")) return t.trim().trim('"', '\'', '<', '>')+    }+    // Fallback: contains @ anywhere+    if (trimmed.contains("@")) {+        val maybe = trimmed.substringAfterLast(' ').trim()+        if (maybe.contains("@")) return maybe.trim('<', '>', '"', '\'')+    }+    return ""+}
email/src/main/java/com/vayunmathur/email/ui/ComposerHelpers.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/ComposerHelpers.kt b/email/src/main/java/com/vayunmathur/email/ui/ComposerHelpers.ktindex e1b1fc1653..0b9a414792 100644--- a/email/src/main/java/com/vayunmathur/email/ui/ComposerHelpers.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/ComposerHelpers.kt@@ -20,7 +20,7 @@ import com.vayunmathur.library.ui.* import com.vayunmathur.library.ui.R as UiR  @Composable-private fun EmailComposerFormatToolbar(+internal fun EmailComposerFormatToolbar(     controller: com.vayunmathur.email.ui.composer.EmailHtmlEditorController,     onInsertImage: () -> Unit, ) {@@ -252,7 +252,7 @@ private fun EmailColorPickerDialog(     ) } -private fun copyInlineToCache(context: android.content.Context, uri: Uri, name: String): Uri? {+internal fun copyInlineToCache(context: android.content.Context, uri: Uri, name: String): Uri? {     return try {         val dir = java.io.File(context.cacheDir, "inline").also { it.mkdirs() }         val safeName = name.replace(Regex("[/\\\\]"), "_").ifBlank { "image_${System.currentTimeMillis()}.jpg" }
email/src/main/java/com/vayunmathur/email/ui/ComposerScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/ComposerScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/ComposerScreen.ktindex c115811d9b..0a1d4b54f7 100644--- a/email/src/main/java/com/vayunmathur/email/ui/ComposerScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/ComposerScreen.kt@@ -15,6 +15,7 @@ import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle
email/src/main/java/com/vayunmathur/email/ui/DraftsScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/DraftsScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/DraftsScreen.ktindex 3c98c3ff82..1731302979 100644--- a/email/src/main/java/com/vayunmathur/email/ui/DraftsScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/DraftsScreen.kt@@ -54,6 +54,4 @@ fun DraftsScreen(             }         }     }-}--private fun uriName(context: android.content.Context, uri: android.net.Uri): String =\ No newline at end of file+}\ No newline at end of file
email/src/main/java/com/vayunmathur/email/ui/EmailUiHelpers.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/EmailUiHelpers.kt b/email/src/main/java/com/vayunmathur/email/ui/EmailUiHelpers.ktindex a111860746..6a322f9017 100644--- a/email/src/main/java/com/vayunmathur/email/ui/EmailUiHelpers.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/EmailUiHelpers.kt@@ -15,13 +15,14 @@ import com.vayunmathur.library.util.AppMessages import androidx.core.net.toUri import com.vayunmathur.library.ui.R as UiR +internal fun uriName(context: android.content.Context, uri: android.net.Uri): String =     runCatching {         context.contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use {             if (it.moveToFirst()) it.getString(0) else null         }     }.getOrNull() ?: uri.lastPathSegment ?: "attachment" -private fun uriSize(context: android.content.Context, uri: android.net.Uri): Long =+internal fun uriSize(context: android.content.Context, uri: android.net.Uri): Long =     runCatching {         context.contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.SIZE), null, null, null)?.use {             if (it.moveToFirst() && !it.isNull(0)) it.getLong(0) else 0L@@ -29,7 +30,7 @@ private fun uriSize(context: android.content.Context, uri: android.net.Uri): Lon     }.getOrNull() ?: 0L  /** Epoch millis for [hour]:00 today (or tomorrow if that time already passed, or sameDay=false forces next day). */-private fun scheduleTime(hour: Int, sameDay: Boolean): Long {+internal fun scheduleTime(hour: Int, sameDay: Boolean): Long {     val c = java.util.Calendar.getInstance()     c.set(java.util.Calendar.HOUR_OF_DAY, hour)     c.set(java.util.Calendar.MINUTE, 0)@@ -42,14 +43,14 @@ private fun scheduleTime(hour: Int, sameDay: Boolean): Long { }  /** Append an email to a comma-separated recipient field, avoiding duplicates. */-private fun appendRecipient(field: String, email: String): String {+internal fun appendRecipient(field: String, email: String): String {     val existing = field.split(",").map { it.trim() }.filter { it.isNotEmpty() }     if (existing.any { it.equals(email, ignoreCase = true) }) return field     return if (existing.isEmpty()) email else existing.joinToString(", ") + ", " + email }  /** Read the email address from a contact-picker result URI (granted per-item, no permission needed). */-private fun contactEmail(context: android.content.Context, uri: android.net.Uri): String? =+internal fun contactEmail(context: android.content.Context, uri: android.net.Uri): String? =     runCatching {         context.contentResolver.query(             uri,
email/src/main/java/com/vayunmathur/email/ui/MessageListScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MessageListScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/MessageListScreen.ktindex 28b69d6488..2ee7d1692d 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MessageListScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageListScreen.kt@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height
email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.ktindex ac77ecd0a4..d7e6f10c0c 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageThreadScreen.kt@@ -44,7 +44,7 @@ import com.vayunmathur.email.data.senderDisplayName import com.vayunmathur.email.platform.EmailViewModel import com.vayunmathur.email.platform.EmlUtils import com.vayunmathur.email.platform.MessageThreadActions-import com.vayunmathur.email.platform.UnsubscribeMethod+import com.vayunmathur.email.data.UnsubscribeMethod import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.DropdownMenu@@ -310,13 +310,3 @@ private fun performUnsubscribe(method: UnsubscribeMethod, context: android.conte         is UnsubscribeMethod.SendMail -> onCompose(method.address, "Unsubscribe")     } }--private fun scheduleTime(hour: Int, sameDay: Boolean): Long {-    val c = java.util.Calendar.getInstance()-    c.set(java.util.Calendar.HOUR_OF_DAY, hour)-    c.set(java.util.Calendar.MINUTE, 0)-    c.set(java.util.Calendar.SECOND, 0)-    c.set(java.util.Calendar.MILLISECOND, 0)-    if (!sameDay || c.timeInMillis <= System.currentTimeMillis()) c.add(java.util.Calendar.DAY_OF_YEAR, 1)-    return c.timeInMillis-}
email/src/main/java/com/vayunmathur/email/ui/OutboxScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/OutboxScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/OutboxScreen.ktindex f234861729..527e9a5650 100644--- a/email/src/main/java/com/vayunmathur/email/ui/OutboxScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/OutboxScreen.kt@@ -130,7 +130,7 @@ private fun OutboxRow(entry: OutboxEntry, onDelete: () -> Unit) { }  /** The signature block (HTML) appended to an outgoing message body, or "" if none. */-private fun signatureBlockHtml(acc: com.vayunmathur.email.data.EmailAccount?): String {+internal fun signatureBlockHtml(acc: com.vayunmathur.email.data.EmailAccount?): String {     val s = acc?.signature?.trim().orEmpty()     if (s.isEmpty()) return ""     val escaped = s.htmlEncode().replace("\n", "<br>")
email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.ktindex e8eca5b1b4..638fed0433 100644--- a/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/SettingsScreen.kt@@ -9,6 +9,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalResources 

Diff truncated.