package studio.daybreak.mail import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.os.Build import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import org.json.JSONObject import javax.mail.Folder import javax.mail.Store class MailIdleService : Service() { private data class Watcher( val account: JSONObject, val fingerprint: String, val stopped: AtomicBoolean = AtomicBoolean(false), @Volatile var store: Store? = null, @Volatile var folder: Folder? = null, @Volatile var thread: Thread? = null ) { fun stop() { stopped.set(true) try { folder?.close(false) } catch (_: Exception) {} try { store?.close() } catch (_: Exception) {} thread?.interrupt() } } private val watchers = ConcurrentHashMap() override fun onCreate() { super.onCreate() AndroidAccountVault.initialize(applicationContext) createNotificationChannels() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { startForeground(FOREGROUND_NOTIFICATION_ID, foregroundNotification()) Thread { try { reconcile() if (watchers.isEmpty()) stopSelf(startId) } catch (error: Exception) { android.util.Log.e(TAG, "Could not start mailbox watchers (${error.javaClass.simpleName})") } }.start() return START_STICKY } override fun onBind(intent: Intent?): IBinder? = null override fun onDestroy() { watchers.values.forEach(Watcher::stop) watchers.clear() super.onDestroy() } @Synchronized private fun reconcile() { val accounts = AndroidAccountVault.accounts() val desired = LinkedHashMap() for (index in 0 until accounts.length().coerceAtMost(MAX_WATCHERS)) { val account = accounts.getJSONObject(index) desired[account.optString("id")] = account } for ((id, watcher) in watchers) { val account = desired[id] if (account == null || AndroidMailService.accountFingerprint(account) != watcher.fingerprint) { watcher.stop() watchers.remove(id, watcher) } } for ((id, account) in desired) { if (!watchers.containsKey(id)) startWatcher(id, account) } } private fun startWatcher(id: String, account: JSONObject) { val watcher = Watcher(account, AndroidMailService.accountFingerprint(account)) watchers[id] = watcher val thread = Thread({ var failures = 0 while (!watcher.stopped.get()) { try { AndroidMailService.watchInbox( account = account, onNewMail = { count -> onNewMail(account, count) }, shouldStop = { watcher.stopped.get() }, onConnection = { store, folder -> watcher.store = store watcher.folder = folder } ) failures = 0 } catch (error: Exception) { if (!watcher.stopped.get()) { android.util.Log.w(TAG, "IMAP watcher disconnected (${error.javaClass.simpleName})") } failures += 1 } finally { watcher.folder = null watcher.store = null } if (!watcher.stopped.get()) { val delayMs = (15_000L * (1L shl failures.coerceAtMost(5))).coerceAtMost(5 * 60_000L) try { Thread.sleep(delayMs) } catch (_: InterruptedException) { if (watcher.stopped.get()) break } } } }, "ep-mail-idle-$id") thread.isDaemon = true watcher.thread = thread thread.start() } private fun onNewMail(account: JSONObject, count: Int) { notifyNewMail(this, account, count) } private fun foregroundNotification(): Notification = NotificationCompat.Builder(this, SERVICE_CHANNEL_ID) .setSmallIcon(android.R.drawable.ic_dialog_email) .setContentTitle(getString(R.string.app_name)) .setContentText("Checking mail in the background") .setContentIntent(appPendingIntent()) .setOngoing(true) .setPriority(NotificationCompat.PRIORITY_LOW) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .build() private fun appPendingIntent(): PendingIntent { val intent = packageManager.getLaunchIntentForPackage(packageName) ?: Intent(this, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) } private fun createNotificationChannels() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager manager.createNotificationChannel(NotificationChannel( SERVICE_CHANNEL_ID, "Background mail sync", NotificationManager.IMPORTANCE_LOW ).apply { description = "Keeps mail synchronized in the background." }) manager.createNotificationChannel(NotificationChannel( MAIL_CHANNEL_ID, "New mail", NotificationManager.IMPORTANCE_DEFAULT ).apply { description = "Notifies you when new mail arrives." }) } companion object { const val ACTION_MAIL_SYNC = "studio.daybreak.mail.MAIL_SYNC_UPDATE" const val EXTRA_SYNC_UPDATE = "syncUpdate" private const val TAG = "EpMailIdle" private const val MAX_WATCHERS = 2 private const val FOREGROUND_NOTIFICATION_ID = 3410 private const val SERVICE_CHANNEL_ID = "mail-sync-service" private const val MAIL_CHANNEL_ID = "mail-new-message" fun start(context: Context) { AndroidAccountVault.initialize(context) if (AndroidAccountVault.accounts().length() == 0) return MailFallbackWorker.schedule(context) val intent = Intent(context, MailIdleService::class.java) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent) else context.startService(intent) } fun stop(context: Context) { context.stopService(Intent(context, MailIdleService::class.java)) MailFallbackWorker.cancel(context) } fun checkSnoozeReminders(context: Context) { AndroidAccountVault.initialize(context) val accounts = AndroidAccountVault.accounts() for (index in 0 until accounts.length()) { val account = accounts.getJSONObject(index) val reminders = AndroidAccountVault.takeDueSnoozes( account.optString("id"), System.currentTimeMillis() ) for (reminderIndex in 0 until reminders.length()) { notifySnoozeReminder(context, account, reminders.getJSONObject(reminderIndex)) } } } fun notifyNewMail(context: Context, account: JSONObject, count: Int) { if (count <= 0) return val appContext = context.applicationContext val email = account.optString("email") if (account.optBoolean("notificationsEnabled", true)) { val notificationManager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notificationManager.getNotificationChannel(MAIL_CHANNEL_ID) == null) { notificationManager.createNotificationChannel(NotificationChannel( MAIL_CHANNEL_ID, "New mail", NotificationManager.IMPORTANCE_DEFAULT ).apply { description = "Notifies you when new mail arrives." }) } val launchIntent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName) ?: Intent(appContext, MainActivity::class.java) launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) val pendingIntent = PendingIntent.getActivity( appContext, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) val showDetails = runCatching { AndroidAccountVault.notificationDetailsEnabled() }.getOrDefault(false) val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) .setSmallIcon(android.R.drawable.ic_dialog_email) .setContentTitle("New mail") .setContentText(NotificationPrivacyPolicy.newMailText(showDetails, email, count)) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .setPublicVersion(NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) .setSmallIcon(android.R.drawable.ic_dialog_email) .setContentTitle("ep-mail") .setContentText("New mail") .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .build()) .setContentIntent(pendingIntent) .build() try { NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification) } catch (error: SecurityException) { android.util.Log.w(TAG, "Notification permission is unavailable (${error.javaClass.simpleName})") } } val update = JSONObject() .put("accountId", account.optString("id")) .put("newCount", count) .put("foldersChanged", org.json.JSONArray().put("Inbox")) appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC) .setPackage(appContext.packageName) .putExtra(EXTRA_SYNC_UPDATE, update.toString())) } fun notifySnoozeReminder(context: Context, account: JSONObject, reminder: JSONObject) { val appContext = context.applicationContext val email = account.optString("email") if (account.optBoolean("notificationsEnabled", true)) { val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) { manager.createNotificationChannel(NotificationChannel( MAIL_CHANNEL_ID, "Mail reminders", NotificationManager.IMPORTANCE_DEFAULT )) } val showDetails = runCatching { AndroidAccountVault.notificationDetailsEnabled() }.getOrDefault(false) val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) .setSmallIcon(android.R.drawable.ic_dialog_email) .setContentTitle("Mail reminder") .setContentText(NotificationPrivacyPolicy.reminderText(showDetails, reminder.optString("subject"))) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .setPublicVersion(NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) .setSmallIcon(android.R.drawable.ic_dialog_email) .setContentTitle("ep-mail") .setContentText("A mail reminder is due") .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .build()) .setContentIntent(appPendingIntentFor(appContext)) .build() try { NotificationManagerCompat.from(appContext).notify( (email + reminder.optLong("uid")).hashCode(), notification ) } catch (error: SecurityException) { android.util.Log.w(TAG, "Reminder notification permission is unavailable (${error.javaClass.simpleName})") } } val update = JSONObject() .put("accountId", account.optString("id")) .put("snoozeReminder", true) .put("foldersChanged", org.json.JSONArray() .put("Snoozed") .put(reminder.optString("folder", "Inbox"))) appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC) .setPackage(appContext.packageName) .putExtra(EXTRA_SYNC_UPDATE, update.toString())) } private fun appPendingIntentFor(context: Context): PendingIntent { val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: Intent(context, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) return PendingIntent.getActivity( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } } }