diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 6e38c67..b1b5bdb 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -62,23 +62,36 @@ - - - - - + android:stopWithTask="false"> + + android:exported="true" + android:enabled="true"> + + + + + + + + + + + @@ -86,31 +99,18 @@ + + + + + - - - - - - - - - - - - - - - - - - diff --git a/android/app/src/main/java/com/paarrot/app/BootReceiver.kt b/android/app/src/main/java/com/paarrot/app/BootReceiver.kt index 1195590..1c7b4ba 100644 --- a/android/app/src/main/java/com/paarrot/app/BootReceiver.kt +++ b/android/app/src/main/java/com/paarrot/app/BootReceiver.kt @@ -5,17 +5,23 @@ import android.content.Context import android.content.Intent /** - * Re-registers UnifiedPush after boot when credentials still exist. + * Starts the message listener again after boot / update when credentials still exist. */ class BootReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { - if (intent.action != Intent.ACTION_BOOT_COMPLETED) return - - val prefs = context.getSharedPreferences(SyncServicePlugin.PREFS, Context.MODE_PRIVATE) - prefs.getString(MatrixSyncService.EXTRA_HOMESERVER, null) ?: return - prefs.getString(MatrixSyncService.EXTRA_TOKEN, null) ?: return - - UnifiedPushManager.register(context, activity = null) + val action = intent.action ?: return + when (action) { + Intent.ACTION_BOOT_COMPLETED, + Intent.ACTION_LOCKED_BOOT_COMPLETED, + Intent.ACTION_MY_PACKAGE_REPLACED, + "android.intent.action.QUICKBOOT_POWERON", + "com.htc.intent.action.QUICKBOOT_POWERON", + -> { + if (!MatrixSyncService.hasCredentials(context)) return + MatrixSyncService.scheduleKeepAlive(context) + MatrixSyncService.requestSyncFetch(context, "boot:$action") + } + } } } diff --git a/android/app/src/main/java/com/paarrot/app/ListenerWatchdogReceiver.kt b/android/app/src/main/java/com/paarrot/app/ListenerWatchdogReceiver.kt new file mode 100644 index 0000000..39ab139 --- /dev/null +++ b/android/app/src/main/java/com/paarrot/app/ListenerWatchdogReceiver.kt @@ -0,0 +1,45 @@ +package com.paarrot.app + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.util.Log + +/** + * Keeps the Matrix message listener alive after OEM kills, idle, or package update. + * Each fire re-chains the next one-shot watchdog alarm. + * + * Health is the persisted sync heartbeat (works across UI vs `:listener` processes). + */ +class ListenerWatchdogReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent?) { + val action = intent?.action ?: ACTION_WATCHDOG + val healthy = MatrixSyncService.isListenerHealthy(context) + val ageMs = MatrixSyncService.heartbeatAgeMs(context) + val inProc = MatrixSyncService.isListenerRunning() + Log.i( + TAG, + "watchdog fired action=$action healthy=$healthy heartbeatAgeMs=$ageMs inProcAlive=$inProc", + ) + if (!MatrixSyncService.hasCredentials(context)) { + Log.w(TAG, "watchdog skip — no credentials") + return + } + // Always re-arm the chain first — even if start fails under OEM limits. + MatrixSyncService.scheduleKeepAlive(context) + val needsRestart = action == ACTION_RESTART || !healthy + if (needsRestart) { + Log.w(TAG, "watchdog restarting reason=${if (action == ACTION_RESTART) "explicit" else "stale-or-missing-heartbeat"}") + MatrixSyncService.requestSyncFetch(context, "watchdog:$action") + } else { + Log.i(TAG, "watchdog ok — listener healthy, no restart") + } + } + + companion object { + private const val TAG = "PaarrotWatchdog" + const val ACTION_WATCHDOG = "com.paarrot.app.LISTENER_WATCHDOG" + const val ACTION_RESTART = "com.paarrot.app.LISTENER_RESTART" + } +} diff --git a/android/app/src/main/java/com/paarrot/app/MainActivity.java b/android/app/src/main/java/com/paarrot/app/MainActivity.java index 7511f19..e009a44 100644 --- a/android/app/src/main/java/com/paarrot/app/MainActivity.java +++ b/android/app/src/main/java/com/paarrot/app/MainActivity.java @@ -1,11 +1,18 @@ package com.paarrot.app; +import android.Manifest; +import android.content.pm.PackageManager; +import android.os.Build; import android.os.Bundle; import android.webkit.WebView; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; import androidx.core.view.ViewCompat; import com.getcapacitor.BridgeActivity; public class MainActivity extends BridgeActivity { + private boolean askedNotifications = false; + @Override protected void onCreate(Bundle savedInstanceState) { registerPlugin(SyncServicePlugin.class); @@ -13,18 +20,47 @@ public class MainActivity extends BridgeActivity { registerPlugin(PluginStoragePlugin.class); super.onCreate(savedInstanceState); setupImageKeyboardSupport(); + ensureListener(); } @Override public void onResume() { super.onResume(); - // Keep native sync suppression in sync with the real Activity lifecycle. - MatrixSyncService.appInForeground = true; + MatrixSyncService.setAppInForeground(this, true); + ensureListener(); + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == REQUEST_NOTIFICATIONS + && grantResults.length > 0 + && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + MatrixSyncService.requestSyncFetch(this, MatrixSyncService.MODE_LISTENER); + } + } + + /** Keep the foreground listener up once this phone has a saved login. */ + private void ensureListener() { + if (Build.VERSION.SDK_INT >= 33 + && ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) + != PackageManager.PERMISSION_GRANTED) { + if (!askedNotifications) { + askedNotifications = true; + ActivityCompat.requestPermissions( + this, + new String[] {Manifest.permission.POST_NOTIFICATIONS}, + REQUEST_NOTIFICATIONS + ); + } + return; + } + MatrixSyncService.requestSyncFetch(this, MatrixSyncService.MODE_LISTENER); } @Override public void onPause() { - MatrixSyncService.appInForeground = false; + MatrixSyncService.setAppInForeground(this, false); super.onPause(); } @@ -39,4 +75,6 @@ public class MainActivity extends BridgeActivity { new ImageKeyboardContentReceiver() ); } + + private static final int REQUEST_NOTIFICATIONS = 4101; } diff --git a/android/app/src/main/java/com/paarrot/app/MatrixSyncService.kt b/android/app/src/main/java/com/paarrot/app/MatrixSyncService.kt index f68ca9c..13eabd8 100644 --- a/android/app/src/main/java/com/paarrot/app/MatrixSyncService.kt +++ b/android/app/src/main/java/com/paarrot/app/MatrixSyncService.kt @@ -1,5 +1,6 @@ package com.paarrot.app +import android.app.AlarmManager import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager @@ -8,8 +9,12 @@ import android.app.Service import android.media.AudioAttributes import android.content.Context import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ServiceInfo import android.net.Uri import android.os.Build +import android.os.PowerManager +import android.os.SystemClock import android.util.Base64 import android.util.Log import android.graphics.Bitmap @@ -21,6 +26,7 @@ import android.graphics.PorterDuffXfermode import android.graphics.Rect import androidx.core.app.NotificationCompat import androidx.core.app.Person +import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.core.content.pm.ShortcutInfoCompat import androidx.core.content.pm.ShortcutManagerCompat @@ -30,6 +36,8 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.json.JSONArray @@ -39,15 +47,18 @@ import java.io.FileOutputStream import java.net.HttpURLConnection import java.net.URL import java.net.URLEncoder +import java.util.concurrent.atomic.AtomicBoolean /** - * ForegroundService that performs a short, one-shot Matrix /sync fetch after - * a wake ping from UnifiedPush or a manual diagnostic trigger. + * Foreground service that keeps a Matrix /sync long-poll open and posts message + * notifications. It stays up across battery limits with a partial wake lock. */ class MatrixSyncService : Service() { private val job = SupervisorJob() private val serviceScope = CoroutineScope(Dispatchers.IO + job) + private val listenerStarted = AtomicBoolean(false) + private var wakeLock: PowerManager.WakeLock? = null /** Event IDs already shown as notifications this session — prevents duplicates on restart. */ private val shownEventIds = HashSet(64) @@ -69,44 +80,158 @@ class MatrixSyncService : Service() { ?: prefs.getString(EXTRA_HOMESERVER, null) val token = intent?.getStringExtra(EXTRA_TOKEN) ?: prefs.getString(EXTRA_TOKEN, null) - val userId = intent?.getStringExtra(EXTRA_USER_ID) - ?: prefs.getString(EXTRA_USER_ID, null) ?: "" if (homeserver == null || token == null) { stopSelf() return START_NOT_STICKY } - val triggerReason = intent?.getStringExtra(EXTRA_TRIGGER_REASON) ?: MODE_ONE_SHOT - startForeground(NOTIF_ID_STATUS, buildStatusNotification()) + scheduleKeepAlive(applicationContext) + holdWakeLock() + try { + promoteToForeground() + } catch (e: Exception) { + Log.e(TAG, "startForeground failed: ${e.message}", e) + scheduleRestart(applicationContext, 15_000L) + releaseWakeLock() + stopSelf() + return START_STICKY + } + listenerAlive.set(true) + markListenerHeartbeat(applicationContext) + Log.i( + TAG, + "listener started reason=${intent?.getStringExtra(EXTRA_TRIGGER_REASON) ?: "sticky"} " + + "pid=${android.os.Process.myPid()} exactAlarms=${canExactAlarms(applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager)}", + ) - serviceScope.launch { - try { - runSingleSyncFetch(homeserver, token, userId, triggerReason) - Log.d(TAG, "One-shot sync completed (reason=$triggerReason)") - } finally { - stopForegroundCompat() - stopSelf(startId) + if (listenerStarted.compareAndSet(false, true)) { + serviceScope.launch { + var backoffMs = 0L + try { + while (isActive) { + if (backoffMs > 0) delay(backoffMs) + holdWakeLock() + val live = applicationContext.getSharedPreferences( + SyncServicePlugin.PREFS, + Context.MODE_PRIVATE, + ) + val liveHomeserver = live.getString(EXTRA_HOMESERVER, null) + val liveToken = live.getString(EXTRA_TOKEN, null) + val liveUserId = live.getString(EXTRA_USER_ID, null) ?: "" + if (liveHomeserver == null || liveToken == null) break + val keepGoing = runSingleSyncFetch( + liveHomeserver, + liveToken, + liveUserId, + ) + // Heartbeat for the watchdog — even if the process stays up with a stuck loop. + markListenerHeartbeat(applicationContext) + if (!keepGoing) break + backoffMs = 0L + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Listener loop error: ${e.message}") + } finally { + listenerStarted.set(false) + listenerAlive.set(false) + val shouldRestart = hasCredentials(applicationContext) + releaseWakeLock() + if (shouldRestart) { + Log.w(TAG, "Listener loop ended — relaunching") + scheduleKeepAlive(applicationContext) + scheduleRestart(applicationContext, 3_000L) + // Immediate revive when possible; alarm covers OEM/LMK gaps. + requestSyncFetch(applicationContext, "loop-relaunch") + } else { + stopForegroundCompat() + } + stopSelf() + } } } - return START_NOT_STICKY + return START_STICKY + } + + override fun onTaskRemoved(rootIntent: Intent?) { + if (hasCredentials(applicationContext)) { + scheduleRestart(applicationContext, 2_000L) + scheduleKeepAlive(applicationContext) + } + super.onTaskRemoved(rootIntent) + } + + /** + * Android 14+ / 15 dataSync quota (and OEM FGS timeouts). Must stop promptly + * or the process is crashed — then revive via exact alarm. + */ + override fun onTimeout(startId: Int) { + handleFgsTimeout(startId, -1) + } + + override fun onTimeout(startId: Int, fgsType: Int) { + handleFgsTimeout(startId, fgsType) + } + + private fun handleFgsTimeout(startId: Int, fgsType: Int) { + Log.e(TAG, "FGS onTimeout startId=$startId type=$fgsType — stopping and scheduling revive") + listenerStarted.set(false) + listenerAlive.set(false) + if (hasCredentials(applicationContext)) { + scheduleRestart(applicationContext, 15_000L) + scheduleKeepAlive(applicationContext) + } + releaseWakeLock() + stopForegroundCompat() + job.cancel() + stopSelf() } override fun onDestroy() { - super.onDestroy() + listenerStarted.set(false) + listenerAlive.set(false) + if (hasCredentials(applicationContext)) { + scheduleRestart(applicationContext, 5_000L) + } + releaseWakeLock() job.cancel() + super.onDestroy() } + private fun holdWakeLock() { + val pm = getSystemService(POWER_SERVICE) as PowerManager + val existing = wakeLock + if (existing == null) { + wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Paarrot:message-listener").apply { + setReferenceCounted(false) + // Refresh often so OEM idle policies do not drop an "infinite" lock. + acquire(12 * 60 * 1000L) + } + } else if (!existing.isHeld) { + existing.acquire(12 * 60 * 1000L) + } else { + // Renew the lease while the loop is healthy. + existing.acquire(12 * 60 * 1000L) + } + } + + private fun releaseWakeLock() { + val lock = wakeLock ?: return + if (lock.isHeld) lock.release() + wakeLock = null + } + + /** @return false when credentials are dead and the listener should stop. */ private suspend fun runSingleSyncFetch( homeserver: String, token: String, userId: String, - triggerReason: String, - ) { + ): Boolean { val prefs = applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) val since = prefs.getString(KEY_SINCE, null) - val isFirstSync = since == null try { val url = buildSyncUrl(homeserver.trimEnd('/'), since) @@ -118,27 +243,18 @@ class MatrixSyncService : Service() { val nextBatch = json.optString("next_batch").takeIf { it.isNotBlank() } if (nextBatch != null) { + val backlog = since == null prefs.edit().putString(KEY_SINCE, nextBatch).apply() - - // Push wakes should still notify even if the WebView leftover - // "foreground" flag is stale; JS path is suppressed while backgrounded. - val fromPush = triggerReason.startsWith("unifiedpush") - val suppressBecauseUi = appInForeground && !fromPush - if (!isFirstSync) { - // Always dismiss trays when another device (or this one) marked rooms read, - // even while the UI is foregrounded and posting is suppressed. - dismissClearedRoomNotifications(json) - if (!suppressBecauseUi) { - processRoomEvents(json, userId) - } else { - Log.d( - TAG, - "Skipping notification posts (foreground=$appInForeground, reason=$triggerReason)", - ) + val appForeground = isAppInForeground(applicationContext) + val notifiedRooms = if (backlog || appForeground) { + if (appForeground && !backlog) { + Log.d(TAG, "Skipping native notification posts while Paarrot is foregrounded") } + emptySet() } else { - Log.d(TAG, "Skipping notifications (firstSync=true, reason=$triggerReason)") + processRoomEvents(json, userId) } + dismissClearedRoomNotifications(json, notifiedRooms) } } 401, 403 -> { @@ -148,24 +264,29 @@ class MatrixSyncService : Service() { .edit() .clear() .apply() + return false } else -> { Log.w(TAG, "Sync fetch failed with HTTP $responseCode") + delay(8_000) } } } catch (e: CancellationException) { throw e } catch (e: Exception) { Log.w(TAG, "Sync error: ${e.message}") + delay(8_000) } + return true } private fun buildSyncUrl(base: String, since: String?): String { - // Include encrypted events — most DMs/rooms are E2EE and never emit plaintext m.room.message. - val filter = """{"room":{"timeline":{"limit":10,"types":["m.room.message","m.room.encrypted","m.sticker"]},"state":{"types":[]},"account_data":{"types":[]},"ephemeral":{"types":[]}},"account_data":{"types":[]},"presence":{"types":[]}}""" + // Keep the filter light so encrypted DMs and normal rooms all appear in /sync. + val filter = + """{"room":{"timeline":{"limit":20},"state":{"lazy_load_members":true},"ephemeral":{"types":[]},"account_data":{"types":[]}},"presence":{"types":[]},"account_data":{"types":[]}}""" val encodedFilter = URLEncoder.encode(filter, "UTF-8") val sinceParam = if (since != null) "&since=${URLEncoder.encode(since, "UTF-8")}" else "" - return "$base/_matrix/client/v3/sync?timeout=12000&filter=$encodedFilter$sinceParam" + return "$base/_matrix/client/v3/sync?timeout=25000&filter=$encodedFilter$sinceParam" } private suspend fun doHttpGet(urlString: String, token: String): Pair = @@ -175,8 +296,8 @@ class MatrixSyncService : Service() { conn.requestMethod = "GET" conn.setRequestProperty("Authorization", "Bearer $token") conn.setRequestProperty("Accept", "application/json") - conn.connectTimeout = 5_000 - conn.readTimeout = 35_000 + conn.connectTimeout = 15_000 + conn.readTimeout = 45_000 val code = conn.responseCode val body = if (code == 200) conn.inputStream.bufferedReader().readText() else null Pair(code, body) @@ -207,9 +328,10 @@ class MatrixSyncService : Service() { * Covers “marked as read on another device” while this phone is backgrounded. * Only acts when [unread_notifications] is present in this sync batch (count changed). */ - private fun dismissClearedRoomNotifications(sync: JSONObject) { + private fun dismissClearedRoomNotifications(sync: JSONObject, justNotified: Set) { val joinedRooms = sync.optJSONObject("rooms")?.optJSONObject("join") ?: return for (roomId in joinedRooms.keys().asSequence()) { + if (roomId in justNotified) continue val roomData = joinedRooms.optJSONObject(roomId) ?: continue if (!roomData.has("unread_notifications")) continue val unread = roomData.optJSONObject("unread_notifications") @@ -220,120 +342,104 @@ class MatrixSyncService : Service() { } } - private fun processRoomEvents(sync: JSONObject, myUserId: String) { + private fun processRoomEvents(sync: JSONObject, myUserId: String): Set { + val notified = mutableSetOf() val prefs = applicationContext.getSharedPreferences(SyncServicePlugin.PREFS, Context.MODE_PRIVATE) - val homeserver = prefs.getString(EXTRA_HOMESERVER, null)?.trimEnd('/') ?: return - val token = prefs.getString(EXTRA_TOKEN, null) ?: return - val joinedRooms = sync.optJSONObject("rooms")?.optJSONObject("join") ?: return + val homeserver = prefs.getString(EXTRA_HOMESERVER, null)?.trimEnd('/') ?: return notified + val token = prefs.getString(EXTRA_TOKEN, null) ?: return notified + val joinedRooms = sync.optJSONObject("rooms")?.optJSONObject("join") ?: return notified val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager ensureMessageChannels(nm) val notifyCtx = loadNotifyContext(homeserver, token, myUserId) val roomIds = joinedRooms.keys().asSequence().toList() + Log.i(TAG, "processRoomEvents rooms=${roomIds.size}") for (roomId in roomIds) { val roomData = joinedRooms.optJSONObject(roomId) ?: continue val mode = resolveRoomNotifyMode(roomId, notifyCtx) - - // Homeserver unread counts already apply push rules — skip rooms with nothing to notify. - val unread = roomData.optJSONObject("unread_notifications") - val notificationCount = unread?.optInt("notification_count", 0) ?: 0 - val highlightCount = unread?.optInt("highlight_count", 0) ?: 0 - if (mode == RoomNotifyMode.MUTE || notificationCount <= 0) continue - - val mentionsOnly = mode == RoomNotifyMode.MENTIONS_AND_KEYWORDS - if (mentionsOnly && highlightCount <= 0) { - // Mentions-only rooms: without a highlight, skip (encrypted bodies can't be scanned). + if (mode == RoomNotifyMode.MUTE) { + Log.i(TAG, "skip muted $roomId") continue } - val timeline = roomData.optJSONObject("timeline") ?: continue - val events = timeline.optJSONArray("events") ?: continue - + val timeline = roomData.optJSONObject("timeline") + val events = timeline?.optJSONArray("events") var notifiedForRoom = false - for (i in 0 until events.length()) { - val event = events.optJSONObject(i) ?: continue - val eventId = event.optString("event_id") - val eventType = event.optString("type") - val isMessageLike = - eventType == "m.room.message" || - eventType == "m.room.encrypted" || - eventType == "m.sticker" - if (!isMessageLike) continue - if (event.optString("sender") == myUserId) continue - if (eventId.isNotBlank() && !shownEventIds.add(eventId)) continue + if (events != null) { + for (i in 0 until events.length()) { + val event = events.optJSONObject(i) ?: continue + val eventId = event.optString("event_id") + val eventType = event.optString("type") + val sender = event.optString("sender") - val content = event.optJSONObject("content") ?: JSONObject() + val isMessageLike = + eventType == "m.room.message" || + eventType == "m.room.encrypted" || + eventType == "m.sticker" + if (!isMessageLike) continue + if (sender.isNotBlank() && sender == myUserId) continue + if (eventId.isNotBlank() && !shownEventIds.add(eventId)) continue - // Plaintext mention/keyword filter; encrypted events already passed highlight_count. - if ( - mentionsOnly && - eventType != "m.room.encrypted" && - !isSpecialMessage(content, notifyCtx) - ) { - continue - } - - val body = when { - eventType == "m.room.encrypted" -> "Encrypted message" - eventType == "m.sticker" -> "🖼️ Sticker" - else -> { - val msgtype = content.optString("msgtype") - val rawBody = content.optString("body") - when (msgtype) { - // Skip Matrix body for images/stickers — it's usually a useless filename. - "m.image" -> "📷 Photo" - "m.video" -> if (rawBody.isNotBlank()) "🎥 $rawBody" else "🎥 Video" - "m.audio" -> if (rawBody.isNotBlank()) "🎵 $rawBody" else "🎵 Audio" - "m.file" -> if (rawBody.isNotBlank()) "📎 $rawBody" else "📎 File" - "m.sticker" -> "🖼️ Sticker" - else -> rawBody.takeIf { it.isNotBlank() } + val content = event.optJSONObject("content") ?: JSONObject() + val encrypted = eventType == "m.room.encrypted" + val body = when { + encrypted -> "Encrypted message" + eventType == "m.sticker" -> "Sticker" + else -> { + val msgtype = content.optString("msgtype") + val rawBody = content.optString("body") + when (msgtype) { + "m.image" -> "Photo" + "m.video" -> rawBody.ifBlank { "Video" } + "m.audio" -> rawBody.ifBlank { "Audio" } + "m.file" -> rawBody.ifBlank { "File" } + else -> rawBody.takeIf { it.isNotBlank() } + } } + } ?: continue + + val profile = try { + resolveProfile(sender, homeserver, token) + } catch (e: Exception) { + Log.w(TAG, "profile fetch failed: ${e.message}") + UserProfile(sender.substringAfter("@").substringBefore(":").ifBlank { "Someone" }, null) } - } ?: continue - val sender = event.optString("sender") - val profile = resolveProfile(sender, homeserver, token) - - val msgtype = content.optString("msgtype") - val inlineImage: Bitmap? = if ( - eventType != "m.room.encrypted" && - (msgtype == "m.image" || msgtype == "m.sticker" || eventType == "m.sticker") && - !content.has("file") - ) { - content.optString("url").takeIf { it.startsWith("mxc://") }?.let { mxc -> - mxcToDownloadUrls(mxc, homeserver) - .firstNotNullOfOrNull { downloadBitmap(it, token) } - } - } else null - - showMessageNotification( - nm, - roomId, - profile.displayName, - body, - profile.avatar, - inlineImage, - resolveGroupInfo(roomId, notifyCtx), - ) - notifiedForRoom = true + Log.i(TAG, "notify room=$roomId type=$eventType sender=$sender") + showMessageNotification( + nm, + roomId, + profile.displayName, + body, + profile.avatar, + null, + resolveGroupInfo(roomId, notifyCtx), + ) + notifiedForRoom = true + } } - // Fallback: HS says there are notifications but timeline filter missed usable events. + val unread = roomData.optJSONObject("unread_notifications") + val notificationCount = unread?.optInt("notification_count", 0) ?: 0 if (!notifiedForRoom && notificationCount > 0) { val groupInfo = resolveGroupInfo(roomId, notifyCtx) + Log.i(TAG, "fallback notify room=$roomId count=$notificationCount") showMessageNotification( nm, roomId, groupInfo.roomName.ifBlank { "New message" }, - if (mentionsOnly) "New mention" else "New message", + "New message", null, null, groupInfo, ) + notifiedForRoom = true } + if (notifiedForRoom) notified.add(roomId) } + return notified } /** Load push rules, DM list, keywords, and own display name for notification filtering. */ @@ -636,6 +742,9 @@ class MatrixSyncService : Service() { groupInfo: NotificationGroupInfo, ) { val isDm = groupInfo.kind == "direct" + val navPath = + if (isDm) "/direct/${Uri.encode(roomId)}/" + else "/home/${Uri.encode(roomId)}/" postMessageNotification( this, roomId = roomId, @@ -647,29 +756,66 @@ class MatrixSyncService : Service() { kind = groupInfo.kind, largeIcon = largeIcon, inlineImage = inlineImage, - path = null, + path = navPath, ) } + private fun promoteToForeground() { + val notification = buildStatusNotification() + if (Build.VERSION.SDK_INT >= 34) { + // specialUse avoids the Android 15 6-hour dataSync background quota. + startForeground( + NOTIF_ID_STATUS, + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE, + ) + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + startForeground( + NOTIF_ID_STATUS, + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC, + ) + } else { + startForeground(NOTIF_ID_STATUS, notification) + } + } + private fun buildStatusNotification(): Notification { val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + nm.deleteNotificationChannel(CHANNEL_STATUS) val channel = NotificationChannel( - CHANNEL_STATUS, "Sync Status", - NotificationManager.IMPORTANCE_MIN, + CHANNEL_LISTENER, + "Message listener", + NotificationManager.IMPORTANCE_LOW, ).apply { - description = "Paarrot background sync status" + description = "Shows while Paarrot is listening for messages" setShowBadge(false) + setSound(null, null) + enableVibration(false) + lockscreenVisibility = Notification.VISIBILITY_SECRET } nm.createNotificationChannel(channel) } - return NotificationCompat.Builder(this, CHANNEL_STATUS) + val open = PendingIntent.getActivity( + this, + 0, + Intent(this, MainActivity::class.java), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + return NotificationCompat.Builder(this, CHANNEL_LISTENER) .setSmallIcon(R.drawable.ic_stat_paarrot) .setContentTitle("Paarrot") - .setContentText("Checking for new messages") - .setPriority(NotificationCompat.PRIORITY_MIN) + .setContentText("Listening for messages") .setOngoing(true) + .setOnlyAlertOnce(true) + .setShowWhen(false) + .setSilent(true) + .setCategory(NotificationCompat.CATEGORY_SERVICE) + .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setContentIntent(open) .build() } @@ -698,19 +844,226 @@ class MatrixSyncService : Service() { const val KEY_NOTIFICATION_GROUPS = "notification_groups" const val PREFS = "matrix_sync_prefs" const val KEY_SINCE = "since_token" - private const val KEY_LAST_WAKE_MS = "last_wake_ms" + private const val HEARTBEAT_FILE = "listener_heartbeat_ms" + private const val FOREGROUND_FILE = "app_in_foreground" private const val NOTIF_ID_STATUS = 1001 private const val CHANNEL_STATUS = "sync_status" - private const val CHANNEL_MESSAGES = "messages_paarrot" - private const val CHANNEL_DIRECTS = "messages_directs" - private const val CHANNEL_SPACES = "messages_spaces" - private const val CHANNEL_HOME = "messages_home" + // Bump id so IMPORTANCE_LOW applies (Android won't lower an existing channel). + private const val CHANNEL_LISTENER = "paarrot_listening_v2" + // New id required — Android will not raise importance on an existing channel. + private const val CHANNEL_POPUP = "paarrot_priority_v2" + private const val CHANNEL_MESSAGES = "paarrot_messages" + private const val CHANNEL_DIRECTS = "paarrot_directs_messages" + private const val CHANNEL_SPACES = "paarrot_spaces" + private const val CHANNEL_HOME = "paarrot_rooms" private const val GROUP_DIRECTS = "paarrot_directs" private const val GROUP_HOME = "paarrot_home" - private const val MIN_WAKE_INTERVAL_MS = 7_500L private const val MAX_MESSAGING_HISTORY = 8 private const val KEY_MSG_HISTORY_PREFIX = "notif_hist_" + /** Chained one-shot interval when battery unrestricted. */ + private const val WATCHDOG_FAST_MS = 90_000L + /** Gentler interval when still battery-optimized. */ + private const val WATCHDOG_SLOW_MS = 3 * 60 * 1000L + /** + * If no sync heartbeat within this window, treat the listener as dead even when + * the in-process alive flag is still set (hung long-poll after LMK pressure). + */ + private const val HEARTBEAT_STALE_MS = 90_000L + private const val PI_WATCHDOG = 9101 + private const val PI_RESTART = 9102 const val MODE_ONE_SHOT = "one_shot" + const val MODE_LISTENER = "listener" + + @JvmStatic + fun hasCredentials(context: Context): Boolean { + val prefs = context.getSharedPreferences(SyncServicePlugin.PREFS, Context.MODE_PRIVATE) + return !prefs.getString(EXTRA_HOMESERVER, null).isNullOrBlank() && + !prefs.getString(EXTRA_TOKEN, null).isNullOrBlank() + } + + /** Cross-process heartbeat file — SharedPreferences caches per-process and lie. */ + private fun heartbeatFile(context: Context): File = + File(context.applicationContext.filesDir, HEARTBEAT_FILE) + + private fun readHeartbeatMs(context: Context): Long { + return try { + val f = heartbeatFile(context) + if (!f.isFile) return 0L + f.readText().trim().toLongOrNull() ?: 0L + } catch (e: Exception) { + Log.w(TAG, "heartbeat read failed: ${e.message}") + 0L + } + } + + @JvmStatic + fun markListenerHeartbeat(context: Context) { + val now = System.currentTimeMillis() + try { + val f = heartbeatFile(context) + f.parentFile?.mkdirs() + // Atomic-ish write so a mid-kill read never sees a partial timestamp. + val tmp = File(f.parentFile, "${f.name}.tmp") + FileOutputStream(tmp).use { out -> + out.write(now.toString().toByteArray(Charsets.UTF_8)) + out.fd.sync() + } + if (!tmp.renameTo(f)) { + tmp.copyTo(f, overwrite = true) + tmp.delete() + } + } catch (e: Exception) { + Log.w(TAG, "heartbeat write failed: ${e.message}") + } + Log.d(TAG, "heartbeat ts=$now") + } + + /** + * Heartbeat-only health check — works across the UI process and `:listener`. + * Do not require the in-process alive flag (that is always false from the UI process). + */ + @JvmStatic + fun isListenerHealthy(context: Context): Boolean { + val last = readHeartbeatMs(context) + if (last <= 0L) return false + val age = System.currentTimeMillis() - last + val ok = age < HEARTBEAT_STALE_MS + if (!ok) { + Log.w(TAG, "heartbeat stale ageMs=$age threshold=$HEARTBEAT_STALE_MS") + } + return ok + } + + @JvmStatic + fun heartbeatAgeMs(context: Context): Long { + val last = readHeartbeatMs(context) + if (last <= 0L) return -1L + return System.currentTimeMillis() - last + } + + /** Persist UI visibility so the `:listener` process can suppress tray dupes. */ + @JvmStatic + fun setAppInForeground(context: Context, foreground: Boolean) { + // File + sync so `:listener` sees the flip without SharedPreferences cache lies. + try { + val f = File(context.applicationContext.filesDir, FOREGROUND_FILE) + FileOutputStream(f).use { out -> + out.write(if (foreground) '1'.code else '0'.code) + out.fd.sync() + } + } catch (e: Exception) { + Log.w(TAG, "foreground flag write failed: ${e.message}") + } + } + + @JvmStatic + fun isAppInForeground(context: Context): Boolean { + return try { + val f = File(context.applicationContext.filesDir, FOREGROUND_FILE) + if (!f.isFile) return false + f.readText().trim() == "1" + } catch (_: Exception) { + false + } + } + + private fun isBatteryUnrestricted(context: Context): Boolean { + val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager + return pm.isIgnoringBatteryOptimizations(context.packageName) + } + + private fun canExactAlarms(am: AlarmManager): Boolean { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + am.canScheduleExactAlarms() + } else { + true + } + } + + /** Prefer exact-while-idle; fall back to inexact while-idle when denied. */ + private fun setWakeupAlarm(am: AlarmManager, atElapsed: Long, pi: PendingIntent) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (canExactAlarms(am)) { + try { + am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, atElapsed, pi) + return + } catch (e: SecurityException) { + Log.w(TAG, "exact alarm denied: ${e.message}") + } + } + am.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, atElapsed, pi) + } else { + @Suppress("DEPRECATION") + am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, atElapsed, pi) + } + } + + /** + * Chained one-shot wake so OEM battery savers / Google Home LMK cannot leave + * the listener dead for a full inexact 5‑minute window. + */ + @JvmStatic + fun scheduleKeepAlive(context: Context) { + if (!hasCredentials(context)) return + val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + val intent = Intent(context, ListenerWatchdogReceiver::class.java).apply { + action = ListenerWatchdogReceiver.ACTION_WATCHDOG + } + val pi = PendingIntent.getBroadcast( + context, + PI_WATCHDOG, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + val interval = if (isBatteryUnrestricted(context)) WATCHDOG_FAST_MS else WATCHDOG_SLOW_MS + // Cancel stale inexact repeating from older builds. + am.cancel(pi) + val exact = canExactAlarms(am) + setWakeupAlarm(am, SystemClock.elapsedRealtime() + interval, pi) + Log.i(TAG, "keepalive armed intervalMs=$interval exact=$exact") + } + + /** One-shot restart after the service was killed or the sync loop ended. */ + @JvmStatic + fun scheduleRestart(context: Context, delayMs: Long) { + if (!hasCredentials(context)) return + val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + val intent = Intent(context, ListenerWatchdogReceiver::class.java).apply { + action = ListenerWatchdogReceiver.ACTION_RESTART + } + val pi = PendingIntent.getBroadcast( + context, + PI_RESTART, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + val at = SystemClock.elapsedRealtime() + delayMs.coerceAtLeast(1_000L) + setWakeupAlarm(am, at, pi) + Log.i(TAG, "restart armed delayMs=$delayMs exact=${canExactAlarms(am)}") + } + + @JvmStatic + fun cancelKeepAlive(context: Context) { + val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + val watchdog = PendingIntent.getBroadcast( + context, + PI_WATCHDOG, + Intent(context, ListenerWatchdogReceiver::class.java).apply { + action = ListenerWatchdogReceiver.ACTION_WATCHDOG + }, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + val restart = PendingIntent.getBroadcast( + context, + PI_RESTART, + Intent(context, ListenerWatchdogReceiver::class.java).apply { + action = ListenerWatchdogReceiver.ACTION_RESTART + }, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + am.cancel(watchdog) + am.cancel(restart) + } /** Same hashing scheme as JS `notificationIdForRoom` so clear-on-read hits both paths. */ fun notificationIdForRoom(roomId: String): Int { @@ -730,11 +1083,7 @@ class MatrixSyncService : Service() { fun notificationIdForGroupSummary(groupId: String): Int = notificationIdForRoom("summary:$groupId") - private fun channelIdForKindStatic(kind: String): String = when (kind) { - "direct" -> CHANNEL_DIRECTS - "space" -> CHANNEL_SPACES - else -> CHANNEL_HOME - } + private fun channelIdForKindStatic(kind: String): String = CHANNEL_POPUP fun ensureMessageChannels(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return @@ -745,20 +1094,24 @@ class MatrixSyncService : Service() { .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .build() - val channels = listOf( - Triple(CHANNEL_DIRECTS, "Direct messages", "One-to-one Matrix conversations"), - Triple(CHANNEL_SPACES, "Spaces", "Messages from rooms inside Spaces"), - Triple(CHANNEL_HOME, "Other rooms", "Rooms that are not in a Space"), - Triple(CHANNEL_MESSAGES, "Messages", "Legacy message channel"), - ) + nm.deleteNotificationChannel("paarrot_popup") - for ((id, name, description) in channels) { - val channel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH).apply { - this.description = description - setSound(soundUri, soundAttrs) - } - nm.createNotificationChannel(channel) + val popup = NotificationChannel( + CHANNEL_POPUP, + "Priority message alerts", + NotificationManager.IMPORTANCE_HIGH, + ).apply { + description = "High-priority heads-up when a message arrives" + setSound(soundUri, soundAttrs) + enableVibration(true) + vibrationPattern = longArrayOf(0, 250, 120, 250) + enableLights(true) + lightColor = 0xFFFF8A00.toInt() + lockscreenVisibility = Notification.VISIBILITY_PUBLIC + setShowBadge(true) + setBypassDnd(false) } + nm.createNotificationChannel(popup) } fun decodeBase64Bitmap(base64: String?): Bitmap? { @@ -988,154 +1341,188 @@ class MatrixSyncService : Service() { title: String? = null, body: String? = null, ) { - val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - ensureMessageChannels(context) + try { + val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + ensureMessageChannels(context) - val resolvedSender = senderName.ifBlank { title ?: "Someone" } - val resolvedMessage = sanitizeNotificationText( - messageText.ifBlank { body ?: "New message" }, - ) - val isDm = kind == "direct" - val resolvedConversation = - conversationTitle?.takeIf { it.isNotBlank() } - ?: title?.takeIf { !isDm && it != resolvedSender } + val resolvedSender = senderName.ifBlank { title ?: "Someone" } + val resolvedMessage = sanitizeNotificationText( + messageText.ifBlank { body ?: "New message" }, + ) + val isDm = kind == "direct" + val resolvedConversation = + conversationTitle?.takeIf { it.isNotBlank() } + ?: title?.takeIf { !isDm && it != resolvedSender } - val launchIntent = Intent(context, MainActivity::class.java).apply { - action = NotificationNavStore.ACTION_OPEN_NOTIFICATION - flags = Intent.FLAG_ACTIVITY_NEW_TASK or - Intent.FLAG_ACTIVITY_SINGLE_TOP or - Intent.FLAG_ACTIVITY_CLEAR_TOP or - Intent.FLAG_ACTIVITY_REORDER_TO_FRONT - putExtra(EXTRA_ROOM_ID, roomId) - if (!path.isNullOrBlank()) { - putExtra(NotificationNavStore.EXTRA_NAV_PATH, path) + val launchIntent = Intent(context, MainActivity::class.java).apply { + action = NotificationNavStore.ACTION_OPEN_NOTIFICATION + flags = Intent.FLAG_ACTIVITY_NEW_TASK or + Intent.FLAG_ACTIVITY_SINGLE_TOP or + Intent.FLAG_ACTIVITY_REORDER_TO_FRONT + putExtra(EXTRA_ROOM_ID, roomId) + if (!path.isNullOrBlank()) { + putExtra(NotificationNavStore.EXTRA_NAV_PATH, path) + } } - } - val roomNotifId = notificationIdForRoom(roomId) - val pi = PendingIntent.getActivity( - context, roomNotifId, launchIntent, - PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, - ) + val roomNotifId = notificationIdForRoom(roomId) + val pi = PendingIntent.getActivity( + context, roomNotifId, launchIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) - val avatar = largeIcon?.let { toCircularBitmap(it) } - val personBuilder = Person.Builder() - .setName(resolvedSender) - .setKey("$roomId:$resolvedSender") - .setImportant(true) - if (avatar != null) { - personBuilder.setIcon(IconCompat.createWithBitmap(avatar)) - } - val senderPerson = personBuilder.build() - - val imageUri = inlineImage?.let { persistNotificationImage(context, it) }?.toString() - val history = appendMessageHistory( - context, - roomId, - resolvedSender, - resolvedMessage, - imageUri, - ) - - val channelId = channelIdForKindStatic(kind) - val collapsedTitle = if (isDm || resolvedConversation.isNullOrBlank()) { - resolvedSender - } else { - resolvedConversation - } - val collapsedText = if (isDm || resolvedConversation.isNullOrBlank()) { - resolvedMessage - } else { - "$resolvedSender: $resolvedMessage" - } - - val shortcut = publishConversationShortcut( - context, - roomId, - collapsedTitle, - senderPerson, - launchIntent, - ) - - val selfPerson = Person.Builder() - .setName("Me") - .setKey("self") - .build() - val messagingStyle = NotificationCompat.MessagingStyle(selfPerson) - .setGroupConversation(!isDm) - if (!isDm && !resolvedConversation.isNullOrBlank()) { - messagingStyle.conversationTitle = resolvedConversation - } - for (msg in history) { - val person = if (msg.sender == resolvedSender) { - senderPerson + val collapsedTitle = if (isDm || resolvedConversation.isNullOrBlank()) { + resolvedSender } else { - Person.Builder() - .setName(msg.sender) - .setKey("$roomId:${msg.sender}") - .setImportant(true) - .build() + resolvedConversation } - val line = NotificationCompat.MessagingStyle.Message( - msg.text, - msg.timestamp, - person, - ) - // Attach image on the message itself so multi-message history keeps thumbnails - // (BigPictureStyle replaces MessagingStyle and culls prior lines). - if (!msg.imageUri.isNullOrBlank()) { - line.setData("image/jpeg", Uri.parse(msg.imageUri)) + val collapsedText = if (isDm || resolvedConversation.isNullOrBlank()) { + resolvedMessage + } else { + "$resolvedSender: $resolvedMessage" } - messagingStyle.addMessage(line) - } - val builder = NotificationCompat.Builder(context, channelId) - .setSmallIcon(R.drawable.ic_stat_paarrot) - .setContentTitle(collapsedTitle) - .setContentText(collapsedText) - .setAutoCancel(true) - .setContentIntent(pi) - .setPriority(NotificationCompat.PRIORITY_HIGH) - .setCategory(NotificationCompat.CATEGORY_MESSAGE) - .setGroup(groupId) - .setOnlyAlertOnce(true) - .setNumber(history.size) - .setSubText(groupName) - .setShortcutId(shortcut.id) - .setShortcutInfo(shortcut) - // Prevent system "Open link in Chrome/Firefox" contextual actions on URL bodies. - .setAllowSystemGeneratedContextualActions(false) - .setStyle(messagingStyle) + val avatar = largeIcon?.let { toCircularBitmap(it) } + val channelId = channelIdForKindStatic(kind) - builder.extras.putString(EXTRA_ROOM_ID, roomId) - builder.extras.putString(EXTRA_GROUP_ID, groupId) - if (!path.isNullOrBlank()) { - builder.extras.putString(NotificationNavStore.EXTRA_NAV_PATH, path) - } + val personBuilder = Person.Builder() + .setName(resolvedSender) + .setKey("$roomId:$resolvedSender") + .setImportant(true) + if (avatar != null) { + personBuilder.setIcon(IconCompat.createWithBitmap(avatar)) + } + val senderPerson = personBuilder.build() - // Collapsed shade avatar (large icon). Small icon must stay the monochrome app mark. - if (avatar != null) builder.setLargeIcon(avatar) - - nm.notify(roomNotifId, builder.build()) - - val summaryId = notificationIdForGroupSummary(groupId) - val summary = NotificationCompat.Builder(context, channelId) - .setSmallIcon(R.drawable.ic_stat_paarrot) - .setContentTitle(groupName) - .setContentText("New messages") - .setAutoCancel(true) - .setContentIntent(pi) - .setPriority(NotificationCompat.PRIORITY_HIGH) - .setCategory(NotificationCompat.CATEGORY_MESSAGE) - .setGroup(groupId) - .setGroupSummary(true) - .setAllowSystemGeneratedContextualActions(false) - .setStyle( - NotificationCompat.InboxStyle() - .setBigContentTitle(groupName) - .setSummaryText(groupName) + val imageUri = inlineImage?.let { persistNotificationImage(context, it) }?.toString() + val history = appendMessageHistory( + context, + roomId, + resolvedSender, + resolvedMessage, + imageUri, ) - summary.extras.putString(EXTRA_GROUP_ID, groupId) - nm.notify(summaryId, summary.build()) + + val shortcut = publishConversationShortcut( + context, + roomId, + collapsedTitle, + senderPerson, + launchIntent, + ) + + val selfPerson = Person.Builder() + .setName("Me") + .setKey("self") + .build() + val messagingStyle = NotificationCompat.MessagingStyle(selfPerson) + .setGroupConversation(!isDm) + if (!isDm && !resolvedConversation.isNullOrBlank()) { + messagingStyle.conversationTitle = resolvedConversation + } + for (msg in history) { + val person = if (msg.sender == resolvedSender) { + senderPerson + } else { + Person.Builder() + .setName(msg.sender) + .setKey("$roomId:${msg.sender}") + .setImportant(true) + .build() + } + val line = NotificationCompat.MessagingStyle.Message( + msg.text, + msg.timestamp, + person, + ) + // Attach image on the message itself so multi-message history keeps thumbnails + // (BigPictureStyle replaces MessagingStyle and culls prior lines). + if (!msg.imageUri.isNullOrBlank()) { + line.setData("image/jpeg", Uri.parse(msg.imageUri)) + } + messagingStyle.addMessage(line) + } + + val builder = NotificationCompat.Builder(context, channelId) + .setSmallIcon(R.drawable.ic_stat_paarrot) + .setContentTitle(collapsedTitle) + .setContentText(collapsedText) + .setAutoCancel(true) + .setContentIntent(pi) + .setPriority(NotificationCompat.PRIORITY_MAX) + .setCategory(NotificationCompat.CATEGORY_MESSAGE) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .setOnlyAlertOnce(false) + .setDefaults(NotificationCompat.DEFAULT_ALL) + .setVibrate(longArrayOf(0, 250, 120, 250)) + .setLights(0xFFFF8A00.toInt(), 600, 800) + .setTicker(collapsedText) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setGroup(groupId) + .setNumber(history.size) + .setSubText(groupName) + .setShortcutId(shortcut.id) + .setShortcutInfo(shortcut) + .setAllowSystemGeneratedContextualActions(false) + .setStyle(messagingStyle) + + builder.extras.putString(EXTRA_ROOM_ID, roomId) + builder.extras.putString(EXTRA_GROUP_ID, groupId) + if (!path.isNullOrBlank()) { + builder.extras.putString(NotificationNavStore.EXTRA_NAV_PATH, path) + } + + // Collapsed shade avatar (large icon). Small icon must stay the monochrome app mark. + if (avatar != null) builder.setLargeIcon(avatar) + + // Wake the lock screen only — do not launch the app. + wakeScreenForAlert(context) + nm.notify(roomNotifId, builder.build()) + + val summaryId = notificationIdForGroupSummary(groupId) + val summary = NotificationCompat.Builder(context, channelId) + .setSmallIcon(R.drawable.ic_stat_paarrot) + .setContentTitle(groupName) + .setContentText("New messages") + .setAutoCancel(true) + .setContentIntent(pi) + .setPriority(NotificationCompat.PRIORITY_MAX) + .setCategory(NotificationCompat.CATEGORY_MESSAGE) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .setGroup(groupId) + .setGroupSummary(true) + .setAllowSystemGeneratedContextualActions(false) + .setStyle( + NotificationCompat.InboxStyle() + .setBigContentTitle(groupName) + .setSummaryText(groupName), + ) + summary.extras.putString(EXTRA_GROUP_ID, groupId) + nm.notify(summaryId, summary.build()) + + Log.i(TAG, "posted alert id=$roomNotifId title=$collapsedTitle history=${history.size}") + } catch (e: Exception) { + Log.e(TAG, "postMessageNotification failed: ${e.message}", e) + } + } + + /** Briefly light the lock screen so the heads-up can appear. Never starts an Activity. */ + private fun wakeScreenForAlert(context: Context) { + try { + val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager + if (pm.isInteractive) return + @Suppress("DEPRECATION") + val lock = pm.newWakeLock( + PowerManager.SCREEN_BRIGHT_WAKE_LOCK or + PowerManager.ACQUIRE_CAUSES_WAKEUP or + PowerManager.ON_AFTER_RELEASE, + "Paarrot:message-alert", + ) + lock.setReferenceCounted(false) + lock.acquire(3_000L) + } catch (e: Exception) { + Log.w(TAG, "wakeScreenForAlert failed: ${e.message}") + } } /** Cancel the tray notification posted for [roomId], if any. */ @@ -1176,29 +1563,39 @@ class MatrixSyncService : Service() { } } - /** Set by [SyncServicePlugin] / [MainActivity] — true when the Capacitor UI is visible. */ - @JvmField - @Volatile - var appInForeground = false + /** In-process listener state; cross-process health uses the persisted heartbeat. */ + private val listenerAlive = AtomicBoolean(false) + + @JvmStatic + fun isListenerRunning(): Boolean = listenerAlive.get() /** * Starts a one-shot sync fetch if credentials are available and the call is not rate-limited. */ + @JvmStatic fun requestSyncFetch(context: Context, reason: String) { val credsPrefs = context.getSharedPreferences(SyncServicePlugin.PREFS, Context.MODE_PRIVATE) - val homeserver = credsPrefs.getString(EXTRA_HOMESERVER, null) ?: return - val token = credsPrefs.getString(EXTRA_TOKEN, null) ?: return + val homeserver = credsPrefs.getString(EXTRA_HOMESERVER, null) ?: run { + Log.w(TAG, "requestSyncFetch($reason): no homeserver saved") + return + } + val token = credsPrefs.getString(EXTRA_TOKEN, null) ?: run { + Log.w(TAG, "requestSyncFetch($reason): no token saved") + return + } val userId = credsPrefs.getString(EXTRA_USER_ID, null) ?: "" val deviceId = credsPrefs.getString(EXTRA_DEVICE_ID, null) ?: "" - val syncPrefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) - val now = System.currentTimeMillis() - val lastWake = syncPrefs.getLong(KEY_LAST_WAKE_MS, 0L) - if (now - lastWake < MIN_WAKE_INTERVAL_MS) { - Log.d(TAG, "Skipping wake: rate-limited ($reason)") - return + if (Build.VERSION.SDK_INT >= 33) { + val allowed = ContextCompat.checkSelfPermission( + context, + android.Manifest.permission.POST_NOTIFICATIONS, + ) == PackageManager.PERMISSION_GRANTED + if (!allowed) { + Log.w(TAG, "requestSyncFetch($reason): POST_NOTIFICATIONS denied") + return + } } - syncPrefs.edit().putLong(KEY_LAST_WAKE_MS, now).apply() val intent = Intent(context, MatrixSyncService::class.java).apply { putExtra(EXTRA_HOMESERVER, homeserver) @@ -1208,10 +1605,17 @@ class MatrixSyncService : Service() { putExtra(EXTRA_TRIGGER_REASON, reason) } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - context.startForegroundService(intent) - } else { - context.startService(intent) + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + context.startForegroundService(intent) + } else { + context.startService(intent) + } + Log.i(TAG, "requestSyncFetch($reason): started healthy=${isListenerHealthy(context)} ageMs=${heartbeatAgeMs(context)}") + } catch (e: Exception) { + Log.e(TAG, "requestSyncFetch($reason) failed: ${e.message}", e) + scheduleKeepAlive(context) + scheduleRestart(context, 60_000L) } } } diff --git a/android/app/src/main/java/com/paarrot/app/SyncServicePlugin.kt b/android/app/src/main/java/com/paarrot/app/SyncServicePlugin.kt index 4037342..8658315 100644 --- a/android/app/src/main/java/com/paarrot/app/SyncServicePlugin.kt +++ b/android/app/src/main/java/com/paarrot/app/SyncServicePlugin.kt @@ -1,7 +1,16 @@ package com.paarrot.app +import android.Manifest +import android.app.Activity import android.content.Context import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.os.PowerManager +import android.provider.Settings +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat import com.getcapacitor.JSObject import com.getcapacitor.Plugin import com.getcapacitor.PluginCall @@ -12,13 +21,12 @@ import com.getcapacitor.annotation.CapacitorPlugin * Capacitor plugin that controls [MatrixSyncService] from JS. * * JS API: - * - `start({ homeserverUrl, accessToken, userId, deviceId })` — persist credentials and register UnifiedPush - * - `triggerPing({ reason })` — force a one-shot fetch (for testing/manual wake) - * - `stop()` — clear persisted credentials and unregister UnifiedPush + * - `start({ homeserverUrl, accessToken, userId, deviceId })` — persist credentials and keep the listener running + * - `triggerPing({ reason })` — make sure the listener is running + * - `stop()` — clear persisted credentials and stop the listener * - `setAppForeground({ foreground })` — tell the service whether the app UI is visible - * - `getStatus()` — returns current fetch and UnifiedPush state - * - `requestDistributorSetup()` — clear saved distributor and re-open OS picker - * - `resolveUnifiedPushGateway({ endpoint })` — native Matrix gateway discovery + * - `getStatus()` — returns whether the listener is running and battery is unrestricted + * - `requestBatteryExemption()` — ask Android to leave the listener unrestricted * - `clearRoomNotifications({ roomId })` — dismiss native tray notifs for a room * - `setNotificationGroups({ rooms })` — persist space/DM grouping for tray nesting * - `showNotification({ title, body, roomId, groupId, groupName, kind, largeIconBase64 })` @@ -26,13 +34,8 @@ import com.getcapacitor.annotation.CapacitorPlugin @CapacitorPlugin(name = "MatrixBackgroundSync") class SyncServicePlugin : Plugin() { - fun emitUnifiedPushEvent(eventName: String, payload: JSObject) { - notifyListeners(eventName, payload, true) - } - override fun load() { super.load() - UnifiedPushManager.setPlugin(this) NotificationNavStore.plugin = this NotificationNavStore.handleIntent(activity?.intent) } @@ -46,7 +49,6 @@ class SyncServicePlugin : Plugin() { } override fun handleOnDestroy() { - UnifiedPushManager.clearPlugin(this) if (NotificationNavStore.plugin === this) { NotificationNavStore.plugin = null } @@ -71,7 +73,7 @@ class SyncServicePlugin : Plugin() { call.resolve(result) } - /** Persists Matrix credentials and starts UnifiedPush registration. */ + /** Persists Matrix credentials and keeps the message listener in the foreground. */ @PluginMethod fun start(call: PluginCall) { val homeserver = call.getString("homeserverUrl") @@ -86,11 +88,13 @@ class SyncServicePlugin : Plugin() { .putString(MatrixSyncService.EXTRA_TOKEN, token) .putString(MatrixSyncService.EXTRA_USER_ID, userId) .putString(MatrixSyncService.EXTRA_DEVICE_ID, deviceId) - .apply() + .commit() - UnifiedPushManager.register(context, activity) - - call.resolve() + askNotificationPermission() + MatrixSyncService.scheduleKeepAlive(context) + MatrixSyncService.requestSyncFetch(context, MatrixSyncService.MODE_LISTENER) + val ignored = askBatteryExemption(context, activity) + call.resolve(JSObject().put("batteryIgnored", ignored)) } /** Manually triggers a one-shot sync fetch (mainly for diagnostics/testing). */ @@ -104,9 +108,9 @@ class SyncServicePlugin : Plugin() { /** Stops the sync service and erases persisted credentials. */ @PluginMethod fun stop(call: PluginCall) { + MatrixSyncService.cancelKeepAlive(context) context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().clear().apply() context.stopService(Intent(context, MatrixSyncService::class.java)) - UnifiedPushManager.unregister(context) call.resolve() } @@ -117,49 +121,40 @@ class SyncServicePlugin : Plugin() { */ @PluginMethod fun setAppForeground(call: PluginCall) { - MatrixSyncService.appInForeground = call.getBoolean("foreground", false) ?: false + val foreground = call.getBoolean("foreground", false) ?: false + MatrixSyncService.setAppInForeground(context, foreground) call.resolve() } /** Returns whether the sync service is currently running. */ @PluginMethod fun getStatus(call: PluginCall) { - val am = context.getSystemService(Context.ACTIVITY_SERVICE) - as android.app.ActivityManager - @Suppress("DEPRECATION") - val running = am.getRunningServices(Int.MAX_VALUE) - .any { it.service.className == MatrixSyncService::class.java.name } - val result = UnifiedPushManager.getStatus(context).apply { put("running", running) } - call.resolve(result) - } - - /** - * Clears the saved UnifiedPush distributor and opens the OS default-distributor - * picker (`unifiedpush://link`), then re-registers on success. - */ - @PluginMethod - fun requestDistributorSetup(call: PluginCall) { - val currentActivity = activity - ?: return call.reject("Activity required to select a UnifiedPush distributor") - UnifiedPushManager.requestDistributorSetup(context, currentActivity) { success -> - call.resolve(JSObject().put("success", success)) + try { + val result = JSObject() + // The service runs in :listener, so its in-memory flag is not shared with this plugin process. + val running = + MatrixSyncService.hasCredentials(context) && MatrixSyncService.isListenerHealthy(context) + result.put("running", running) + result.put("listening", running) + result.put("batteryIgnored", isBatteryIgnored(context)) + val notificationsAllowed = + Build.VERSION.SDK_INT < 33 || + ContextCompat.checkSelfPermission( + context, + Manifest.permission.POST_NOTIFICATIONS, + ) == PackageManager.PERMISSION_GRANTED + result.put("notificationsAllowed", notificationsAllowed) + call.resolve(result) + } catch (e: Exception) { + call.reject("getStatus failed: ${e.message}", e) } } - /** - * Resolves the Matrix push gateway for a UnifiedPush endpoint using native HTTP - * so discovery is not blocked by missing CORS headers in the WebView. - */ + /** Asks Android to leave Paarrot out of battery optimization so the listener stays up. */ @PluginMethod - fun resolveUnifiedPushGateway(call: PluginCall) { - val endpoint = call.getString("endpoint") - ?: return call.reject("endpoint required") - Thread { - val gateway = UnifiedPushManager.resolveMatrixGateway(endpoint) - bridge?.executeOnMainThread { - call.resolve(JSObject().put("gatewayUrl", gateway)) - } - }.start() + fun requestBatteryExemption(call: PluginCall) { + val ignored = askBatteryExemption(context, activity) + call.resolve(JSObject().put("ignored", ignored)) } /** @@ -227,5 +222,39 @@ class SyncServicePlugin : Plugin() { companion object { const val PREFS = "sync_service_prefs" + + fun isBatteryIgnored(context: Context): Boolean { + val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager + return pm.isIgnoringBatteryOptimizations(context.packageName) + } + + fun askBatteryExemption(context: Context, activity: Activity?): Boolean { + if (isBatteryIgnored(context)) return true + val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply { + data = Uri.parse("package:${context.packageName}") + } + if (activity != null) { + activity.startActivity(intent) + } else { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + } + return false + } + } + + private fun askNotificationPermission() { + if (Build.VERSION.SDK_INT < 33) return + val act = activity ?: return + if (ContextCompat.checkSelfPermission(act, Manifest.permission.POST_NOTIFICATIONS) + == PackageManager.PERMISSION_GRANTED + ) { + return + } + ActivityCompat.requestPermissions( + act, + arrayOf(Manifest.permission.POST_NOTIFICATIONS), + 4101, + ) } } diff --git a/android/app/src/main/java/com/paarrot/app/UnifiedPushManager.kt b/android/app/src/main/java/com/paarrot/app/UnifiedPushManager.kt deleted file mode 100644 index 8ec51aa..0000000 --- a/android/app/src/main/java/com/paarrot/app/UnifiedPushManager.kt +++ /dev/null @@ -1,390 +0,0 @@ -package com.paarrot.app - -import android.app.Activity -import android.app.AlertDialog -import android.app.AppOpsManager -import android.content.Context -import android.content.pm.PackageManager -import android.os.Build -import android.os.Handler -import android.os.Looper -import android.os.Process -import android.os.SystemClock -import android.util.Log -import com.getcapacitor.JSArray -import com.getcapacitor.JSObject -import org.json.JSONObject -import org.unifiedpush.android.connector.FailedReason -import org.unifiedpush.android.connector.INSTANCE_DEFAULT -import org.unifiedpush.android.connector.UnifiedPush -import java.net.HttpURLConnection -import java.net.URL - -/** Coordinates UnifiedPush registration state and bridges events back to JS. */ -object UnifiedPushManager { - private const val TAG = "UnifiedPushManager" - private const val PREFS = "unifiedpush_prefs" - private const val KEY_ENDPOINT = "endpoint" - private const val KEY_INSTANCE = "instance" - private const val KEY_LAST_FAILURE = "last_failure" - private const val EVENT_NEW_ENDPOINT = "unifiedPushNewEndpoint" - private const val EVENT_UNREGISTERED = "unifiedPushUnregistered" - private const val EVENT_REGISTRATION_FAILED = "unifiedPushRegistrationFailed" - private const val DEFAULT_MESSAGE = "Paarrot notifications" - private const val REGISTER_DELAY_MS = 750L - private const val IGNORE_UNREGISTER_MS = 2_500L - const val DEFAULT_MATRIX_GATEWAY = "https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify" - - private val mainHandler = Handler(Looper.getMainLooper()) - - @Volatile - private var plugin: SyncServicePlugin? = null - - @Volatile - private var setupGeneration = 0 - - @Volatile - private var ignoreUnregisteredUntilElapsed = 0L - - fun setPlugin(plugin: SyncServicePlugin) { - this.plugin = plugin - } - - fun clearPlugin(plugin: SyncServicePlugin) { - if (this.plugin === plugin) { - this.plugin = null - } - } - - fun register(context: Context, activity: Activity?) { - val savedDistributor = runCatching { UnifiedPush.getSavedDistributor(context) }.getOrNull().orEmpty() - if (savedDistributor.isNotBlank()) { - requestRegistration(context) - return - } - - if (activity == null) { - dispatchRegistrationFailed(FailedReason.ACTION_REQUIRED.name, INSTANCE_DEFAULT) - return - } - - // Prefer an explicit in-app picker so the user always sees something; - // tryUseDefaultDistributor is silent when only one distributor is installed. - requestDistributorSetup(context, activity) { success -> - if (!success) { - dispatchRegistrationFailed(FailedReason.ACTION_REQUIRED.name, INSTANCE_DEFAULT) - } - } - } - - /** - * Shows an in-app distributor picker, then registers after a short delay. - * - * Important: we intentionally avoid calling [UnifiedPush.removeDistributor] before the - * user picks. That sent an UNREGISTER that could arrive *after* the new REGISTER and - * wipe the fresh endpoint (looked like "found ntfy but never connects"). - */ - fun requestDistributorSetup(context: Context, activity: Activity, onDone: (Boolean) -> Unit) { - val gen = ++setupGeneration - ignoreUnregisteredUntilElapsed = SystemClock.elapsedRealtime() + IGNORE_UNREGISTER_MS - clearEndpoint(context) - clearLastFailure(context) - - val distributors = runCatching { UnifiedPush.getDistributors(context) } - .getOrDefault(emptyList()) - Log.i(TAG, "Distributor setup: found=${distributors.joinToString()}") - if (distributors.isEmpty()) { - Log.w(TAG, "No UnifiedPush distributors installed") - persistLastFailure(context, "NO_DISTRIBUTOR") - dispatchRegistrationFailed(FailedReason.ACTION_REQUIRED.name, INSTANCE_DEFAULT) - onDone(false) - return - } - - val labels = distributors.map { packageName -> - distributorLabel(context, packageName) - }.toTypedArray() - - // Guard against cancel + dismiss double-firing the callback. - val finished = java.util.concurrent.atomic.AtomicBoolean(false) - val finish: (Boolean) -> Unit = { success -> - if (finished.compareAndSet(false, true)) onDone(success) - } - - activity.runOnUiThread { - AlertDialog.Builder(activity) - .setTitle("Choose push distributor") - .setItems(labels) { _, which -> - val chosen = distributors.getOrNull(which) - if (chosen.isNullOrBlank()) { - finish(false) - return@setItems - } - activateDistributor(context, chosen, gen, finish) - } - .setNegativeButton(android.R.string.cancel) { _, _ -> finish(false) } - .setOnCancelListener { finish(false) } - .show() - } - } - - /** - * Saves [chosen] as the distributor and registers after a delay so any prior - * UNREGISTER from a distributor switch can settle first. - */ - private fun activateDistributor( - context: Context, - chosen: String, - gen: Int, - finish: (Boolean) -> Unit, - ) { - ignoreUnregisteredUntilElapsed = SystemClock.elapsedRealtime() + IGNORE_UNREGISTER_MS - val previous = runCatching { UnifiedPush.getSavedDistributor(context) }.getOrNull().orEmpty() - Log.i(TAG, "Activating distributor=$chosen previous=$previous") - - if (previous.isNotBlank() && previous != chosen) { - runCatching { UnifiedPush.removeDistributor(context) } - .onFailure { Log.w(TAG, "removeDistributor failed: ${it.message}") } - } - - mainHandler.postDelayed({ - if (gen != setupGeneration) { - Log.w(TAG, "Skipping stale distributor activation gen=$gen current=$setupGeneration") - finish(false) - return@postDelayed - } - - runCatching { UnifiedPush.saveDistributor(context, chosen) } - .onFailure { - Log.w(TAG, "saveDistributor failed: ${it.message}") - persistLastFailure(context, "SAVE_FAILED") - finish(false) - return@postDelayed - } - - val saved = runCatching { UnifiedPush.getSavedDistributor(context) }.getOrNull() - if (saved != chosen) { - Log.e(TAG, "Distributor not saved after saveDistributor (got=$saved)") - persistLastFailure(context, "SAVE_NOT_PERSISTED") - finish(false) - return@postDelayed - } - - requestRegistration(context) - // Report true once register was requested; JS polls for the endpoint. - finish(true) - - // One retry if the distributor is slow to ack. - mainHandler.postDelayed({ - if (gen != setupGeneration) return@postDelayed - if (!getEndpoint(context).isNullOrBlank()) return@postDelayed - Log.w(TAG, "No endpoint yet after ${REGISTER_DELAY_MS}ms — retrying register") - requestRegistration(context) - - // OEM "App Boot" / AUTO_START can silently drop NEW_ENDPOINT (seen on TCL). - mainHandler.postDelayed({ - if (gen != setupGeneration) return@postDelayed - if (!getEndpoint(context).isNullOrBlank()) return@postDelayed - val reason = if (isAutoStartRestricted(context)) { - "AUTO_START_BLOCKED" - } else { - "NO_ENDPOINT" - } - Log.w(TAG, "Still no endpoint after register retries — $reason") - persistLastFailure(context, reason) - dispatchRegistrationFailed(reason, INSTANCE_DEFAULT) - }, 4_000L) - }, REGISTER_DELAY_MS) - }, if (previous.isNotBlank() && previous != chosen) REGISTER_DELAY_MS else 150L) - } - - /** Human-readable label for a distributor package (falls back to package name). */ - private fun distributorLabel(context: Context, packageName: String): String { - return try { - val pm = context.packageManager - val appInfo = pm.getApplicationInfo(packageName, 0) - val label = pm.getApplicationLabel(appInfo)?.toString().orEmpty() - if (label.isNotBlank() && label != packageName) "$label ($packageName)" else packageName - } catch (_: PackageManager.NameNotFoundException) { - packageName - } - } - - /** - * Discovers the Matrix push gateway for a UnifiedPush endpoint via native HTTP - * (WebView `fetch` fails — ntfy responses omit CORS headers). - */ - fun resolveMatrixGateway(endpoint: String): String { - return try { - val endpointUrl = URL(endpoint) - val discoveryUrl = URL( - endpointUrl.protocol, - endpointUrl.host, - endpointUrl.port, - "/_matrix/push/v1/notify", - ) - val conn = discoveryUrl.openConnection() as HttpURLConnection - try { - conn.requestMethod = "GET" - conn.connectTimeout = 4_000 - conn.readTimeout = 6_000 - conn.setRequestProperty("Accept", "application/json") - if (conn.responseCode != 200) return DEFAULT_MATRIX_GATEWAY - - val body = JSONObject(conn.inputStream.bufferedReader().readText()) - val gateway = - body.optString("gateway").takeIf { it.isNotBlank() } - ?: body.optJSONObject("unifiedpush")?.optString("gateway") - if (gateway == "matrix") discoveryUrl.toString() else DEFAULT_MATRIX_GATEWAY - } finally { - conn.disconnect() - } - } catch (e: Exception) { - Log.w(TAG, "Matrix gateway discovery failed: ${e.message}") - DEFAULT_MATRIX_GATEWAY - } - } - - fun unregister(context: Context) { - runCatching { - UnifiedPush.unregister(context, INSTANCE_DEFAULT) - }.onFailure { - Log.w(TAG, "Failed to unregister UnifiedPush: ${it.message}") - } - val previousEndpoint = getEndpoint(context) - clearEndpoint(context) - dispatchUnregistered(previousEndpoint, INSTANCE_DEFAULT) - } - - fun getStatus(context: Context): JSObject { - val status = JSObject() - status.put("endpoint", getEndpoint(context) ?: "") - status.put("instance", getInstance(context) ?: INSTANCE_DEFAULT) - status.put("registered", !getEndpoint(context).isNullOrBlank()) - status.put("distributor", runCatching { UnifiedPush.getSavedDistributor(context) }.getOrDefault("")) - status.put("lastFailure", getLastFailure(context) ?: "") - status.put("autoStartBlocked", isAutoStartRestricted(context)) - val distributors = JSArray() - runCatching { UnifiedPush.getDistributors(context) } - .getOrDefault(emptyList()) - .forEach { distributors.put(it) } - status.put("distributors", distributors) - return status - } - - /** - * TCL / some OEMs expose an AUTO_START app-op. When it is not MODE_ALLOWED, - * [AppBootManager] drops distributor broadcasts such as NEW_ENDPOINT, so - * UnifiedPush never finishes registering even though ntfy is selected. - */ - private fun isAutoStartRestricted(context: Context): Boolean { - return try { - val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager - val mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - appOps.unsafeCheckOpNoThrow("android:auto_start", Process.myUid(), context.packageName) - } else { - @Suppress("DEPRECATION") - appOps.checkOpNoThrow("android:auto_start", Process.myUid(), context.packageName) - } - mode != AppOpsManager.MODE_ALLOWED && mode != AppOpsManager.MODE_DEFAULT - } catch (_: Exception) { - false - } - } - - fun onNewEndpoint(context: Context, endpoint: String, instance: String) { - Log.i(TAG, "onNewEndpoint instance=$instance endpoint=$endpoint") - clearLastFailure(context) - val previousEndpoint = getEndpoint(context) - persistEndpoint(context, endpoint, instance) - val payload = JSObject().apply { - put("endpoint", endpoint) - put("instance", instance) - put("previousEndpoint", previousEndpoint ?: "") - } - dispatch(EVENT_NEW_ENDPOINT, payload) - } - - fun onRegistrationFailed(context: Context, reason: String, instance: String) { - Log.w(TAG, "onRegistrationFailed reason=$reason instance=$instance") - persistLastFailure(context, reason) - dispatchRegistrationFailed(reason, instance) - } - - fun onUnregistered(context: Context, instance: String) { - if (SystemClock.elapsedRealtime() < ignoreUnregisteredUntilElapsed) { - Log.i(TAG, "Ignoring unregistered during setup window instance=$instance") - return - } - Log.i(TAG, "onUnregistered instance=$instance") - val previousEndpoint = getEndpoint(context) - clearEndpoint(context) - dispatchUnregistered(previousEndpoint, instance) - } - - private fun requestRegistration(context: Context) { - runCatching { - Log.i(TAG, "Calling UnifiedPush.register instance=$INSTANCE_DEFAULT") - UnifiedPush.register(context, INSTANCE_DEFAULT, DEFAULT_MESSAGE, null) - }.onFailure { - Log.w(TAG, "UnifiedPush register failed: ${it.message}") - persistLastFailure(context, FailedReason.INTERNAL_ERROR.name) - dispatchRegistrationFailed(FailedReason.INTERNAL_ERROR.name, INSTANCE_DEFAULT) - } - } - - private fun dispatchUnregistered(previousEndpoint: String?, instance: String) { - val payload = JSObject().apply { - put("previousEndpoint", previousEndpoint ?: "") - put("instance", instance) - } - dispatch(EVENT_UNREGISTERED, payload) - } - - private fun dispatchRegistrationFailed(reason: String, instance: String) { - val payload = JSObject().apply { - put("reason", reason) - put("instance", instance) - } - dispatch(EVENT_REGISTRATION_FAILED, payload) - } - - private fun dispatch(eventName: String, payload: JSObject) { - plugin?.emitUnifiedPushEvent(eventName, payload) - } - - private fun persistEndpoint(context: Context, endpoint: String, instance: String) { - context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() - .putString(KEY_ENDPOINT, endpoint) - .putString(KEY_INSTANCE, instance) - .apply() - } - - private fun clearEndpoint(context: Context) { - context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() - .remove(KEY_ENDPOINT) - .remove(KEY_INSTANCE) - .apply() - } - - private fun persistLastFailure(context: Context, reason: String) { - context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() - .putString(KEY_LAST_FAILURE, reason) - .apply() - } - - private fun clearLastFailure(context: Context) { - context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() - .remove(KEY_LAST_FAILURE) - .apply() - } - - private fun getLastFailure(context: Context): String? = - context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY_LAST_FAILURE, null) - - private fun getEndpoint(context: Context): String? = - context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY_ENDPOINT, null) - - private fun getInstance(context: Context): String? = - context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY_INSTANCE, null) -} diff --git a/android/app/src/main/java/com/paarrot/app/UnifiedPushService.kt b/android/app/src/main/java/com/paarrot/app/UnifiedPushService.kt deleted file mode 100644 index 29d6260..0000000 --- a/android/app/src/main/java/com/paarrot/app/UnifiedPushService.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.paarrot.app - -import android.util.Log -import org.unifiedpush.android.connector.FailedReason -import org.unifiedpush.android.connector.PushService -import org.unifiedpush.android.connector.data.PushEndpoint -import org.unifiedpush.android.connector.data.PushMessage - -/** Receives UnifiedPush events and turns push messages into Matrix fetch wakes. */ -class UnifiedPushService : PushService() { - - override fun onNewEndpoint(endpoint: PushEndpoint, instance: String) { - Log.i(TAG, "UnifiedPush endpoint updated for instance=$instance") - UnifiedPushManager.onNewEndpoint(applicationContext, endpoint.url, instance) - } - - override fun onMessage(message: PushMessage, instance: String) { - Log.d(TAG, "UnifiedPush wake ping received for instance=$instance, bytes=${message.content.size}") - MatrixSyncService.requestSyncFetch(applicationContext, "unifiedpush_message") - } - - override fun onRegistrationFailed(reason: FailedReason, instance: String) { - Log.w(TAG, "UnifiedPush registration failed: $reason") - UnifiedPushManager.onRegistrationFailed(applicationContext, reason.name, instance) - } - - override fun onUnregistered(instance: String) { - Log.i(TAG, "UnifiedPush unregistered for instance=$instance") - UnifiedPushManager.onUnregistered(applicationContext, instance) - } - - private companion object { - const val TAG = "UnifiedPushService" - } -} diff --git a/overlay/src/app/features/settings/notifications/SystemNotification.tsx b/overlay/src/app/features/settings/notifications/SystemNotification.tsx index ad1aa78..d0e0dd6 100644 --- a/overlay/src/app/features/settings/notifications/SystemNotification.tsx +++ b/overlay/src/app/features/settings/notifications/SystemNotification.tsx @@ -14,8 +14,10 @@ import { isCapacitorNative, requestSystemNotificationPermission } from '../../.. import { isBackgroundSyncSupported, getBackgroundSyncStatus, - requestResetPushRegistration, + requestBatteryExemption, + startBackgroundSync, triggerBackgroundSyncPing, + type ListenerStatus, } from '../../../utils/backgroundSync'; function EmailNotification() { @@ -166,119 +168,107 @@ export function SystemNotification() { ); } -type PushStatus = { - registered: boolean; - distributor: string; - endpoint: string; - distributors: string[]; - lastFailure: string; - autoStartBlocked: boolean; -}; - -/** Android-only section showing UnifiedPush registration status and controls. */ +/** Android-only controls for Paarrot's persistent message listener. */ function AndroidPushNotifications() { - const [status, setStatus] = useState(undefined); + const mx = useMatrixClient(); + const [status, setStatus] = useState(undefined); const [loading, setLoading] = useState(true); - const [lastError, setLastError] = useState(undefined); const refresh = useCallback(async () => { - setLoading(true); - const s = await getBackgroundSyncStatus(); - const distributors = Array.isArray(s?.distributors) - ? s.distributors - : typeof s?.distributors === 'string' && s.distributors && s.distributors !== '[]' - ? [s.distributors] - : []; - setStatus( - s - ? { - registered: s.registered, - distributor: s.distributor || '', - endpoint: s.endpoint || '', - distributors, - lastFailure: s.lastFailure || '', - autoStartBlocked: Boolean(s.autoStartBlocked), - } - : undefined - ); + setStatus(await getBackgroundSyncStatus()); setLoading(false); }, []); useEffect(() => { void refresh(); + const id = window.setInterval(() => void refresh(), 4000); + return () => window.clearInterval(id); }, [refresh]); - const [resetState, reset] = useAsyncCallback( + const [batteryState, allowBattery] = useAsyncCallback( useCallback(async () => { - setLastError(undefined); - const result = await requestResetPushRegistration(); + await requestBatteryExemption(); await refresh(); - if (!result.success) { - setLastError( - 'Selected distributor but did not get a push endpoint. In ntfy: enable UnifiedPush, allow unrestricted battery, then try Reset again.' - ); - } }, [refresh]) ); + const [startState, startListener] = useAsyncCallback( + useCallback(async () => { + await requestSystemNotificationPermission(); + await startBackgroundSync(mx); + await refresh(); + }, [mx, refresh]) + ); + const [pingState, ping] = useAsyncCallback( useCallback(async () => { await triggerBackgroundSyncPing('manual-test'); - }, []) + await refresh(); + }, [refresh]) ); const isBusy = loading || - resetState.status === AsyncStatus.Loading || + batteryState.status === AsyncStatus.Loading || + startState.status === AsyncStatus.Loading || pingState.status === AsyncStatus.Loading; + const actionError = + startState.status === AsyncStatus.Error + ? startState.error + : batteryState.status === AsyncStatus.Error + ? batteryState.error + : pingState.status === AsyncStatus.Error + ? pingState.error + : undefined; + const statusDescription = (() => { if (loading) return 'Loading status…'; if (status === undefined) { return ( - Failed to read push status. + Failed to read the message listener status. ); } - if (status.registered) { + if (status.error) { + return ( + + {status.error} + + ); + } + if (status.notificationsAllowed === false) { + return ( + + Allow notifications for Paarrot, then tap Start. + + ); + } + if (status.listening && status.batteryIgnored) { return ( - {`Distributor: ${status.distributor || 'unknown'}`} + Paarrot is listening for messages. ); } - if (status.lastFailure === 'AUTO_START_BLOCKED' || status.autoStartBlocked) { + if (status.listening) { return ( - - Phone is blocking auto-start for Paarrot. Open App Boot / Auto-start settings, allow Paarrot (and ntfy), then tap Reset. - - ); - } - if (status.lastFailure) { - return ( - - {`Registration failed (${status.lastFailure}). Tap Reset and pick ntfy again.`} - - ); - } - if (status.distributors.length === 0) { - return ( - - No UnifiedPush distributor found. Install ntfy from Play Store/F-Droid and enable UnifiedPush in ntfy settings. + + Paarrot is listening. Allow unrestricted battery so Android leaves it running. ); } return ( - - {`Found ${status.distributors.join(', ')} but not registered yet. Tap Reset and pick ntfy.`} + + The message listener is stopped. Tap Start. ); })(); return ( - Android Push (UnifiedPush) + Android Notifications {statusDescription} - {lastError ? ( + {actionError !== undefined && ( - {lastError} + {actionError instanceof Error ? actionError.message : String(actionError)} - ) : null} + )} } - after={loading ? : undefined} + after={ + loading ? ( + + ) : ( + + ) + } /> void reset()} + disabled={isBusy || Boolean(status?.batteryIgnored)} + onClick={() => + void allowBattery().catch((err) => + console.error('[AndroidNotifications] Failed to request battery exemption:', err) + ) + } > - {resetState.status === AsyncStatus.Loading ? ( + {batteryState.status === AsyncStatus.Loading ? ( ) : ( - Reset + {status?.batteryIgnored ? 'Allowed' : 'Allow'} )} } /> void ping()} + onClick={() => + void ping().catch((err) => + console.error('[AndroidNotifications] Failed to trigger listener sync:', err) + ) + } > {pingState.status === AsyncStatus.Loading ? ( diff --git a/overlay/src/app/pages/client/ClientNonUIFeatures.tsx b/overlay/src/app/pages/client/ClientNonUIFeatures.tsx index 206a6db..74c2360 100644 --- a/overlay/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/overlay/src/app/pages/client/ClientNonUIFeatures.tsx @@ -724,7 +724,7 @@ function MessageNotifications() { } /** - * Configures native Android push-ping background sync on login, keeps it + * Configures the native Android message listener on login, keeps it * informed of foreground state so it doesn't double-fire notifications, * and clears it cleanly on unmount (logout). * Only active on Android Capacitor builds. @@ -741,15 +741,25 @@ function BackgroundSyncSetup() { useEffect(() => { console.log('BackgroundSyncSetup: Starting background sync for', mx.getUserId()); - startBackgroundSync(mx); + void startBackgroundSync(mx).catch((err) => { + console.error('[BackgroundSyncSetup] Failed to start message listener:', err); + }); - const onVisibility = () => setAppForegroundState(!document.hidden); + const onVisibility = () => { + void setAppForegroundState(!document.hidden).catch((err) => { + console.error('[BackgroundSyncSetup] Failed to update foreground state:', err); + }); + }; document.addEventListener('visibilitychange', onVisibility); - setAppForegroundState(!document.hidden); + void setAppForegroundState(!document.hidden).catch((err) => { + console.error('[BackgroundSyncSetup] Failed to set initial foreground state:', err); + }); return () => { document.removeEventListener('visibilitychange', onVisibility); - stopBackgroundSync(); + void stopBackgroundSync().catch((err) => { + console.error('[BackgroundSyncSetup] Failed to stop message listener:', err); + }); }; }, [mx]); diff --git a/overlay/src/app/utils/backgroundSync.ts b/overlay/src/app/utils/backgroundSync.ts index e62d9c0..54f0e1c 100644 --- a/overlay/src/app/utils/backgroundSync.ts +++ b/overlay/src/app/utils/backgroundSync.ts @@ -1,627 +1,191 @@ -import { Capacitor, registerPlugin, type PluginListenerHandle } from '@capacitor/core'; import type { IPusherRequest, MatrixClient } from 'matrix-js-sdk'; -type UnifiedPushStatus = { +export type ListenerStatus = { running: boolean; - endpoint: string; - instance: string; - registered: boolean; - distributor: string; - distributors: string[] | string; - lastFailure?: string; - /** OEM App Boot / AUTO_START is blocking distributor broadcasts (e.g. TCL). */ - autoStartBlocked?: boolean; -}; - -type ClearRoomNotificationsResult = { - cleared: boolean; -}; - -type UnifiedPushEndpointEvent = { - endpoint: string; - previousEndpoint: string; - instance: string; -}; - -type UnifiedPushUnregisteredEvent = { - previousEndpoint: string; - instance: string; -}; - -type UnifiedPushRegistrationFailedEvent = { - reason: string; - instance: string; + listening: boolean; + batteryIgnored: boolean; + notificationsAllowed?: boolean; + error?: string; }; interface MatrixBackgroundSyncPlugin { - /** Persist credentials and request UnifiedPush registration. */ start(options: { homeserverUrl: string; accessToken: string; userId: string; deviceId: string; - }): Promise; - /** Trigger a one-shot fetch as if a push ping arrived. */ + }): Promise<{ batteryIgnored?: boolean }>; triggerPing(options: { reason?: string }): Promise; - /** Re-open distributor setup flow and retry registration. */ - requestDistributorSetup(): Promise<{ success: boolean }>; - /** Stop any in-flight fetch, clear credentials, and unregister UnifiedPush. */ stop(): Promise; - /** - * Notify the service whether the app UI is visible. - * When foreground is true, the service suppresses native notifications - * because the JS layer handles them via LocalNotifications. - */ setAppForeground(options: { foreground: boolean }): Promise; - /** Returns fetch state and current UnifiedPush registration details. */ - getStatus(): Promise; - /** Native Matrix gateway discovery for a UnifiedPush endpoint (avoids WebView CORS). */ - resolveUnifiedPushGateway(options: { endpoint: string }): Promise<{ gatewayUrl: string }>; - /** Cancel native tray notifications posted for a Matrix room. */ - clearRoomNotifications(options: { roomId: string }): Promise; - /** - * Persist room → space/group metadata so background notifications can nest - * under Direct messages / Space name / Home. - */ + getStatus(): Promise; + requestBatteryExemption(): Promise<{ ignored: boolean }>; + getPendingNotificationNav(): Promise; + clearRoomNotifications(options: { roomId: string }): Promise; setNotificationGroups(options: { - rooms: Record< - string, - { groupId: string; groupName: string; roomName: string; kind: string } - >; - }): Promise<{ success: boolean }>; - /** Post a message notification with optional avatar (base64) from the JS layer. */ - showNotification(options: { - title?: string; - body?: string; - senderName?: string; - messageText?: string; - conversationTitle?: string; - path?: string; - roomId: string; - groupId: string; - groupName: string; - kind: string; - largeIconBase64?: string; - bigPictureBase64?: string; - }): Promise<{ shown: boolean }>; - /** Pending navigation target from a native notification tap. */ - getPendingNotificationNav(): Promise<{ path?: string | null; roomId?: string | null }>; - addListener( + rooms: Record; + }): Promise; + showNotification(options: NativeNotificationOptions): Promise<{ shown: boolean }>; + addListener?( eventName: 'notificationOpened', - listenerFunc: (event: { path?: string; roomId?: string }) => void - ): Promise; - addListener( - eventName: 'unifiedPushNewEndpoint', - listenerFunc: (event: UnifiedPushEndpointEvent) => void - ): Promise; - addListener( - eventName: 'unifiedPushUnregistered', - listenerFunc: (event: UnifiedPushUnregisteredEvent) => void - ): Promise; - addListener( - eventName: 'unifiedPushRegistrationFailed', - listenerFunc: (event: UnifiedPushRegistrationFailedEvent) => void - ): Promise; + listener: (target: NotificationNavTarget) => void + ): Promise<{ remove: () => void }>; } -type StoredPusherState = { - endpoint: string; - appId: string; +type CapacitorGlobal = { + isNativePlatform?: () => boolean; + getPlatform?: () => string; + isPluginAvailable?: (name: string) => boolean; + registerPlugin?: (name: string) => T; + nativePromise?: (plugin: string, method: string, options?: unknown) => Promise; + Plugins?: Record | undefined>; }; -const MatrixBackgroundSync = registerPlugin('MatrixBackgroundSync'); -const DEFAULT_UNIFIED_PUSH_GATEWAY = 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify'; -const PUSHER_APP_ID_BASE = 'com.paarrot.app.android'; -const PUSHER_STORAGE_PREFIX = 'paarrot.unifiedpush'; +const PLUGIN = 'MatrixBackgroundSync'; +const LEGACY_PUSHER_APP_ID = 'com.paarrot.app.android'; +const LEGACY_PUSHER_STORAGE_PREFIX = 'paarrot.unifiedpush'; + +const capacitor = (): CapacitorGlobal | undefined => + (window as typeof window & { Capacitor?: CapacitorGlobal }).Capacitor; /** Returns true when the current platform is Android Capacitor. */ -export const isBackgroundSyncSupported = (): boolean => - Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android'; - -const getStoredPusherKey = (userId: string | null, deviceId: string | null): string => - `${PUSHER_STORAGE_PREFIX}:${userId ?? 'unknown'}:${deviceId ?? 'unknown'}`; - -const buildPusherAppId = (deviceId: string | null): string => { - const raw = deviceId ? `${PUSHER_APP_ID_BASE}.${deviceId}` : PUSHER_APP_ID_BASE; - return raw.length > 64 ? raw.slice(0, 64) : raw; +export const isBackgroundSyncSupported = (): boolean => { + const cap = capacitor(); + return Boolean(cap?.isNativePlatform?.() && cap.getPlatform?.() === 'android'); }; -const loadStoredPusherState = ( - userId: string | null, - deviceId: string | null -): StoredPusherState | undefined => { - if (typeof window === 'undefined' || !window.localStorage) return undefined; - - const raw = window.localStorage.getItem(getStoredPusherKey(userId, deviceId)); - if (!raw) return undefined; - - try { - return JSON.parse(raw) as StoredPusherState; - } catch { - return undefined; +const waitForBridge = async (tries = 50): Promise => { + for (let i = 0; i < tries; i += 1) { + const cap = capacitor(); + if ( + cap?.isNativePlatform?.() && + (cap.Plugins?.[PLUGIN] || cap.nativePromise || cap.registerPlugin) + ) { + return cap; + } + await new Promise((resolve) => window.setTimeout(resolve, 100)); } + throw new Error('Capacitor bridge did not become ready'); }; -const saveStoredPusherState = ( - userId: string | null, - deviceId: string | null, - state: StoredPusherState -): void => { - if (typeof window === 'undefined' || !window.localStorage) return; - window.localStorage.setItem(getStoredPusherKey(userId, deviceId), JSON.stringify(state)); -}; - -const clearStoredPusherState = (userId: string | null, deviceId: string | null): void => { - if (typeof window === 'undefined' || !window.localStorage) return; - window.localStorage.removeItem(getStoredPusherKey(userId, deviceId)); -}; - -const normalizeDistributors = (raw: UnifiedPushStatus['distributors']): string[] => { - if (Array.isArray(raw)) return raw; - if (typeof raw !== 'string') return []; - - const trimmed = raw.trim(); - if (!trimmed || trimmed === '[]') return []; - - if (trimmed.startsWith('[') && trimmed.endsWith(']')) { - return trimmed - .slice(1, -1) - .split(',') - .map((entry) => entry.trim()) - .filter(Boolean); +/** Android injects plugins on Capacitor.Plugins — registerPlugin is often missing. */ +const plugin = async (): Promise => { + const cap = await waitForBridge(); + const existing = cap.Plugins?.[PLUGIN]; + if (existing?.getStatus && existing.start) { + return existing as MatrixBackgroundSyncPlugin; } - return [trimmed]; -}; - -const resolveUnifiedPushGateway = async (endpoint: string): Promise => { - // Prefer native HTTP — ntfy/Matrix gateway responses omit CORS headers, so - // WebView fetch fails with TypeError: Failed to fetch and wrongly falls back. - try { - const result = await MatrixBackgroundSync.resolveUnifiedPushGateway({ endpoint }); - if (result?.gatewayUrl) return result.gatewayUrl; - } catch (err) { - console.warn('[BackgroundSync] Native UnifiedPush gateway discovery failed:', err); - } - - try { - const discoveryUrl = new URL(endpoint); - discoveryUrl.pathname = '/_matrix/push/v1/notify'; - discoveryUrl.search = ''; - - const response = await fetch(discoveryUrl.toString(), { method: 'GET' }); - if (!response.ok) return DEFAULT_UNIFIED_PUSH_GATEWAY; - - const body = (await response.json()) as { - gateway?: string; - unifiedpush?: { gateway?: string }; + if (typeof cap.nativePromise === 'function') { + const call = (method: string, options?: unknown) => + cap.nativePromise!(PLUGIN, method, options ?? {}) as Promise; + return { + start: (options) => call('start', options), + triggerPing: (options) => call('triggerPing', options), + stop: () => call('stop'), + setAppForeground: (options) => call('setAppForeground', options), + getStatus: () => call('getStatus'), + requestBatteryExemption: () => call('requestBatteryExemption'), + getPendingNotificationNav: () => call('getPendingNotificationNav'), + clearRoomNotifications: (options) => call('clearRoomNotifications', options), + setNotificationGroups: (options) => call('setNotificationGroups', options), + showNotification: (options) => call('showNotification', options), }; + } - if (body.gateway === 'matrix' || body.unifiedpush?.gateway === 'matrix') { - return discoveryUrl.toString(); + if (cap.registerPlugin) { + return cap.registerPlugin(PLUGIN); + } + + throw new Error('MatrixBackgroundSync is unavailable on this Capacitor bridge'); +}; + +/** Keep Paarrot's native message listener running without a push distributor. */ +export const startBackgroundSync = async (mx: MatrixClient): Promise => { + if (!isBackgroundSyncSupported()) return; + + const homeserverUrl = mx.getHomeserverUrl(); + const accessToken = mx.getAccessToken(); + const userId = mx.getUserId(); + const deviceId = mx.getDeviceId(); + if (!homeserverUrl || !accessToken || !userId) return; + + const legacyAppId = `${LEGACY_PUSHER_APP_ID}${deviceId ? `.${deviceId}` : ''}`.slice(0, 64); + try { + const pushers = (await mx.getPushers())?.pushers ?? []; + for (const pusher of pushers) { + if (pusher.kind === 'http' && pusher.app_id === legacyAppId) { + await mx.setPusher({ + pushkey: pusher.pushkey, + app_id: pusher.app_id, + kind: null, + } as unknown as IPusherRequest); + } } } catch (err) { - console.warn('[BackgroundSync] UnifiedPush gateway discovery failed:', err); + console.warn('[BackgroundSync] Failed to remove the previous UnifiedPush pusher:', err); + } + if (typeof window !== 'undefined' && window.localStorage) { + window.localStorage.removeItem( + `${LEGACY_PUSHER_STORAGE_PREFIX}:${userId}:${deviceId ?? 'unknown'}` + ); } - return DEFAULT_UNIFIED_PUSH_GATEWAY; + await (await plugin()).start({ + homeserverUrl, + accessToken, + userId, + deviceId: deviceId ?? '', + }); }; -class AndroidUnifiedPushManager { - private client: MatrixClient | undefined; - - private listenerHandles: PluginListenerHandle[] = []; - - private listenersReady = false; - - private distributorSetupAttempted = false; - - private distributorPromptShown = false; - - /** Start native UnifiedPush registration and synchronize the Matrix pusher. */ - async start(mx: MatrixClient): Promise { - console.log('[BackgroundSync] start() called, platform:', Capacitor.getPlatform(), 'isNative:', Capacitor.isNativePlatform()); - - if (!isBackgroundSyncSupported()) { - console.log('[BackgroundSync] Background sync not supported on this platform'); - return; - } - - const homeserverUrl = mx.getHomeserverUrl(); - const accessToken = mx.getAccessToken(); - const userId = mx.getUserId(); - const deviceId = mx.getDeviceId(); - - console.log('[BackgroundSync] Credentials check:', { userId, deviceId, hasToken: !!accessToken, hasUrl: !!homeserverUrl }); - - if (!homeserverUrl || !accessToken || !userId) { - console.warn('[BackgroundSync] Missing credentials, not starting'); - return; - } - - this.client = mx; - this.distributorSetupAttempted = false; - this.distributorPromptShown = false; - await this.ensureListeners(); - - try { - console.log('[BackgroundSync] Calling plugin.start()...'); - await MatrixBackgroundSync.start({ - homeserverUrl, - accessToken, - userId, - deviceId: deviceId ?? '', - }); - console.log('[BackgroundSync] plugin.start() completed'); - } catch (err) { - console.error('[BackgroundSync] plugin.start() failed:', err); - throw err; - } - - await this.syncExistingEndpoint(); - await this.ensureDistributorPromptFromStatus(); - console.log('[BackgroundSync] UnifiedPush registration requested'); - } - - /** Stop native UnifiedPush integration and remove the Matrix pusher for this device. */ - async stop(): Promise { - if (!isBackgroundSyncSupported()) return; - - const client = this.client; - if (client) { - const deviceId = client.getDeviceId(); - const userId = client.getUserId(); - const status = await this.safeGetStatus(); - const stored = loadStoredPusherState(userId, deviceId); - const endpoint = status?.endpoint || stored?.endpoint; - const appId = stored?.appId ?? buildPusherAppId(deviceId); - - if (endpoint) { - await this.removePusher(client, endpoint, appId); - } - clearStoredPusherState(userId, deviceId); - } - - await MatrixBackgroundSync.stop(); - await this.disposeListeners(); - this.client = undefined; - console.log('[BackgroundSync] UnifiedPush stopped'); - } - - /** Update the Matrix pusher when a new native endpoint is published. */ - private async handleNewEndpoint(event: UnifiedPushEndpointEvent): Promise { - const client = this.client; - if (!client) return; - - if (event.previousEndpoint) { - await this.removePusher(client, event.previousEndpoint); - } - - await this.upsertPusher(client, event.endpoint); - } - - /** Remove the Matrix pusher when UnifiedPush unregisters this instance. */ - private async handleUnregistered(event: UnifiedPushUnregisteredEvent): Promise { - const client = this.client; - if (!client) return; - - const stored = loadStoredPusherState(client.getUserId(), client.getDeviceId()); - const endpoint = event.previousEndpoint || stored?.endpoint; - const appId = stored?.appId ?? buildPusherAppId(client.getDeviceId()); - - if (endpoint) { - await this.removePusher(client, endpoint, appId); - } - - clearStoredPusherState(client.getUserId(), client.getDeviceId()); - } - - /** Log native registration failures so the missing distributor path is visible. */ - private handleRegistrationFailed(event: UnifiedPushRegistrationFailedEvent): void { - console.warn('[BackgroundSync] UnifiedPush registration failed:', event.reason); - - if (event.reason !== 'ACTION_REQUIRED' || this.distributorSetupAttempted) { - return; - } - - this.distributorSetupAttempted = true; - void this.tryRequestDistributorSetup(); - } - - /** Re-opens distributor selection once after ACTION_REQUIRED and logs actionable status. */ - private async tryRequestDistributorSetup(): Promise { - try { - const setupResult = await MatrixBackgroundSync.requestDistributorSetup(); - console.warn('[BackgroundSync] requestDistributorSetup result:', setupResult); - const status = await this.safeGetStatus(); - console.warn('[BackgroundSync] UnifiedPush status after setup attempt:', status); - const distributors = normalizeDistributors(status?.distributors ?? []); - if (distributors.length === 0) { - console.error( - '[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.' - ); - this.showNoDistributorPrompt(); - } - } catch (err) { - console.warn('[BackgroundSync] requestDistributorSetup failed:', err); - } - } - - /** Fallback check so users still get prompted even when ACTION_REQUIRED event is missed. */ - private async ensureDistributorPromptFromStatus(): Promise { - const status = await this.safeGetStatus(); - if (!status) return; - - const distributors = normalizeDistributors(status.distributors); - if (!status.registered && distributors.length === 0) { - console.error( - '[BackgroundSync] No UnifiedPush distributor installed. Install one (for example ntfy) to enable Android background notifications.' - ); - this.showNoDistributorPrompt(); - } - } - - /** Show a one-time actionable prompt when no distributor app is installed. */ - private showNoDistributorPrompt(): void { - if (this.distributorPromptShown) return; - this.distributorPromptShown = true; - - const message = - 'Android background notifications need a UnifiedPush distributor app. Install one (for example ntfy), then reopen Paarrot.'; - const docsUrl = 'https://unifiedpush.org/users/distributors/'; - - if (typeof window === 'undefined') return; - - try { - const openDocs = window.confirm(`${message}\n\nOpen distributor list now?`); - if (openDocs) { - window.open(docsUrl, '_blank', 'noopener,noreferrer'); - } - } catch { - window.alert(message); - } - } - - /** Install plugin listeners once for the active Matrix client. */ - private async ensureListeners(): Promise { - if (this.listenersReady) return; - - this.listenerHandles = [ - await MatrixBackgroundSync.addListener('unifiedPushNewEndpoint', (event) => { - void this.handleNewEndpoint(event).catch((err) => { - console.error('[BackgroundSync] handleNewEndpoint failed:', err); - }); - }), - await MatrixBackgroundSync.addListener('unifiedPushUnregistered', (event) => { - void this.handleUnregistered(event); - }), - await MatrixBackgroundSync.addListener('unifiedPushRegistrationFailed', (event) => { - this.handleRegistrationFailed(event); - }), - ]; - this.listenersReady = true; - } - - /** Remove all plugin listeners when the manager stops. */ - private async disposeListeners(): Promise { - await Promise.all(this.listenerHandles.map((handle) => handle.remove())); - this.listenerHandles = []; - this.listenersReady = false; - } - - /** Reconcile an already-persisted native endpoint after app startup. */ - private async syncExistingEndpoint(): Promise { - const client = this.client; - if (!client) return; - - const status = await this.safeGetStatus(); - console.log('[BackgroundSync] Native status before pusher sync:', status); - if (status?.registered && status.endpoint) { - await this.upsertPusher(client, status.endpoint); - } - } - - /** Create or refresh the Matrix HTTP pusher for the current device. */ - private async upsertPusher(mx: MatrixClient, endpoint: string): Promise { - const deviceId = mx.getDeviceId(); - const userId = mx.getUserId(); - const appId = buildPusherAppId(deviceId); - const gatewayUrl = await resolveUnifiedPushGateway(endpoint); - - console.log('[BackgroundSync] Upserting Matrix pusher', { - appId, - endpoint, - gatewayUrl, - deviceId, - userId, - }); - - try { - await mx.setPusher({ - kind: 'http', - app_id: appId, - pushkey: endpoint, - app_display_name: 'Paarrot', - device_display_name: deviceId ?? 'Android', - lang: 'en', - data: { - url: gatewayUrl, - format: 'event_id_only', - }, - append: false, - device_id: deviceId ?? undefined, - } as unknown as IPusherRequest); - - const pushers = (await mx.getPushers())?.pushers ?? []; - const thisPusher = pushers.find((p) => p.pushkey === endpoint && p.app_id === appId); - console.log('[BackgroundSync] Matrix pusher upserted successfully', { - totalPushers: pushers.length, - foundThisPusher: Boolean(thisPusher), - }); - } catch (err) { - console.error('[BackgroundSync] Matrix pusher upsert failed:', err); - throw err; - } - - saveStoredPusherState(userId, deviceId, { endpoint, appId }); - } - - /** Remove a previously-registered Matrix HTTP pusher for this device. */ - private async removePusher( - mx: MatrixClient, - endpoint: string, - appId = buildPusherAppId(mx.getDeviceId()) - ): Promise { - try { - await mx.setPusher({ - pushkey: endpoint, - app_id: appId, - kind: null, - } as unknown as IPusherRequest); - } catch (err) { - console.warn('[BackgroundSync] Failed to remove UnifiedPush pusher:', err); - } - } - - /** Read native registration state without failing the caller. */ - private async safeGetStatus(): Promise { - try { - return await MatrixBackgroundSync.getStatus(); - } catch (err) { - console.warn('[BackgroundSync] Failed to read UnifiedPush status:', err); - return undefined; - } - } -} - -const unifiedPushManager = new AndroidUnifiedPushManager(); - -/** Start native UnifiedPush registration and sync the Matrix pusher. */ -export const startBackgroundSync = async (mx: MatrixClient): Promise => { - await unifiedPushManager.start(mx); +/** Stop the listener and drop saved credentials. Call this on logout. */ +export const stopBackgroundSync = async (): Promise => { + if (!isBackgroundSyncSupported()) return; + await (await plugin()).stop(); }; -/** - * Manually triggers a one-shot native fetch. - * Useful for diagnostics and bridge testing. - */ +/** Ask the listener to sync now. */ export const triggerBackgroundSyncPing = async (reason?: string): Promise => { if (!isBackgroundSyncSupported()) return; - - try { - await MatrixBackgroundSync.triggerPing({ reason }); - } catch (err) { - console.warn('[BackgroundSync] triggerPing failed:', err); - } + await (await plugin()).triggerPing({ reason }); }; -/** Stop UnifiedPush integration and remove the Matrix pusher for this session. */ -export const stopBackgroundSync = async (): Promise => { - await unifiedPushManager.stop(); -}; - -/** - * Tells the native service whether the app UI is in the foreground. - * Call when document visibility changes so the service can suppress - * duplicate notifications while the JS layer is active. - * @param foreground true if the WebView UI is currently visible - */ +/** Tell the listener whether the chat UI is on screen. */ export const setAppForegroundState = async (foreground: boolean): Promise => { if (!isBackgroundSyncSupported()) return; - - try { - await MatrixBackgroundSync.setAppForeground({ foreground }); - } catch (err) { - console.warn('[BackgroundSync] setAppForeground failed:', err); - } + await (await plugin()).setAppForeground({ foreground }); }; -/** - * Re-opens the UnifiedPush distributor selection dialog. - * Allows users to re-select or change their push notification distributor without terminal access. - * Useful when the current endpoint becomes unavailable. - * Waits briefly for the distributor to return an endpoint so the settings UI can refresh accurately. - */ -export const requestResetPushRegistration = async (): Promise<{ success: boolean }> => { - if (!isBackgroundSyncSupported()) { - console.warn('[BackgroundSync] Background sync not supported on this platform'); - return { success: false }; - } - - try { - const result = await MatrixBackgroundSync.requestDistributorSetup(); - console.log('[BackgroundSync] requestDistributorSetup completed:', result); - if (!result?.success) return { success: false }; - - // Endpoint arrives asynchronously from the distributor after register(). - for (let i = 0; i < 40; i += 1) { - await new Promise((resolve) => setTimeout(resolve, 250)); - const status = await getBackgroundSyncStatus(); - if (status?.registered && status.endpoint) { - return { success: true }; - } - if (status?.lastFailure) { - console.warn('[BackgroundSync] Registration failed while waiting:', status.lastFailure); - return { success: false }; - } - } - - console.warn('[BackgroundSync] Distributor selected but no endpoint received in time'); - return { success: false }; - } catch (err) { - console.error('[BackgroundSync] requestDistributorSetup failed:', err); - return { success: false }; - } +/** Ask Android to leave the listener out of battery optimization. */ +export const requestBatteryExemption = async (): Promise<{ ignored: boolean }> => { + if (!isBackgroundSyncSupported()) return { ignored: false }; + return (await plugin()).requestBatteryExemption(); }; -/** Returns the current native UnifiedPush status, or undefined if unavailable. */ -export const getBackgroundSyncStatus = async (): Promise => { +/** Returns listener and battery-exemption state. */ +export const getBackgroundSyncStatus = async (): Promise => { if (!isBackgroundSyncSupported()) return undefined; try { - return await MatrixBackgroundSync.getStatus(); + return await (await plugin()).getStatus(); } catch (err) { + const message = err instanceof Error ? err.message : String(err); console.warn('[BackgroundSync] getStatus failed:', err); - return undefined; + return { + running: false, + listening: false, + batteryIgnored: false, + error: message, + }; } }; -/** - * Clears native (MatrixSyncService) tray notifications for a room after it is read. - * No-op when background sync / native Android is unavailable. - */ -export const clearNativeRoomNotifications = async (roomId: string): Promise => { - if (!isBackgroundSyncSupported() || !roomId) return; - - try { - await MatrixBackgroundSync.clearRoomNotifications({ roomId }); - } catch (err) { - console.warn('[BackgroundSync] clearRoomNotifications failed:', err); - } +export type NotificationNavTarget = { + path?: string | null; + roomId?: string | null; }; -/** - * Syncs space/DM grouping metadata to the native layer for background notifications. - */ -export const syncNotificationGroupMap = async ( - rooms: Record< - string, - { groupId: string; groupName: string; roomName: string; kind: string } - > -): Promise => { - if (!isBackgroundSyncSupported()) return; - - try { - await MatrixBackgroundSync.setNotificationGroups({ rooms }); - } catch (err) { - console.warn('[BackgroundSync] setNotificationGroups failed:', err); - } -}; - -/** - * Posts a native tray notification (supports dynamic/authenticated avatar icons). - * Prefer this over Capacitor LocalNotifications on Android. - */ -export const showNativeNotification = async (options: { +export type NativeNotificationOptions = { title?: string; body?: string; senderName?: string; @@ -634,41 +198,122 @@ export const showNativeNotification = async (options: { kind: string; largeIconBase64?: string; bigPictureBase64?: string; -}): Promise => { - if (!isBackgroundSyncSupported()) return false; +}; +/** Read a tray-tap target that opened the app before JS listeners attached. */ +export const getPendingNotificationNav = async (): Promise => { + if (!isBackgroundSyncSupported()) return undefined; try { - await MatrixBackgroundSync.showNotification(options); - return true; + const cap = await waitForBridge(); + if (typeof cap.nativePromise === 'function') { + return (await cap.nativePromise( + PLUGIN, + 'getPendingNotificationNav', + {} + )) as NotificationNavTarget; + } + const existing = cap.Plugins?.[PLUGIN] as + | { getPendingNotificationNav?: () => Promise } + | undefined; + if (existing?.getPendingNotificationNav) { + return existing.getPendingNotificationNav(); + } + } catch (err) { + console.warn('[BackgroundSync] getPendingNotificationNav failed:', err); + } + return undefined; +}; + +/** Subscribe to tray notification taps while the app is already running. */ +export const subscribeNotificationOpened = async ( + callback: (target: NotificationNavTarget) => void +): Promise<() => void> => { + if (!isBackgroundSyncSupported()) return () => undefined; + try { + const cap = await waitForBridge(); + const existing = cap.Plugins?.[PLUGIN] as + | { + addListener?: ( + event: string, + cb: (data: NotificationNavTarget) => void + ) => Promise<{ remove: () => void }> | { remove: () => void }; + } + | undefined; + const nativePlugin = + existing?.addListener + ? existing + : cap.registerPlugin?.(PLUGIN); + if (!nativePlugin?.addListener) return () => undefined; + const handle = await nativePlugin.addListener('notificationOpened', callback); + return () => { + void handle.remove(); + }; + } catch (err) { + console.warn('[BackgroundSync] subscribeNotificationOpened failed:', err); + return () => undefined; + } +}; + +/** Dismiss native tray notifications for a room after it is opened / marked read. */ +export const clearRoomNotifications = async (roomId: string): Promise => { + if (!isBackgroundSyncSupported() || !roomId) return; + try { + const cap = await waitForBridge(); + if (typeof cap.nativePromise === 'function') { + await cap.nativePromise(PLUGIN, 'clearRoomNotifications', { roomId }); + return; + } + const existing = cap.Plugins?.[PLUGIN] as + | { clearRoomNotifications?: (o: { roomId: string }) => Promise } + | undefined; + await existing?.clearRoomNotifications?.({ roomId }); + } catch (err) { + console.warn('[BackgroundSync] clearRoomNotifications failed:', err); + } +}; + +/** Compatibility name used by the notification utility layer. */ +export const clearNativeRoomNotifications = clearRoomNotifications; + +/** Keep background notification grouping in sync with the active room list. */ +export const syncNotificationGroupMap = async ( + rooms: Record +): Promise => { + if (!isBackgroundSyncSupported()) return; + try { + const cap = await waitForBridge(); + if (typeof cap.nativePromise === 'function') { + await cap.nativePromise(PLUGIN, 'setNotificationGroups', { rooms }); + return; + } + const existing = cap.Plugins?.[PLUGIN] as + | { setNotificationGroups?: (options: { rooms: typeof rooms }) => Promise } + | undefined; + await existing?.setNotificationGroups?.({ rooms }); + } catch (err) { + console.warn('[BackgroundSync] setNotificationGroups failed:', err); + } +}; + +/** Post a notification using Android's native NotificationManager. */ +export const showNativeNotification = async ( + options: NativeNotificationOptions +): Promise => { + if (!isBackgroundSyncSupported()) return false; + try { + const cap = await waitForBridge(); + if (typeof cap.nativePromise === 'function') { + const result = (await cap.nativePromise(PLUGIN, 'showNotification', options)) as { + shown?: boolean; + }; + return result.shown === true; + } + const existing = cap.Plugins?.[PLUGIN] as + | { showNotification?: (options: NativeNotificationOptions) => Promise<{ shown: boolean }> } + | undefined; + return (await existing?.showNotification?.(options))?.shown === true; } catch (err) { console.warn('[BackgroundSync] showNotification failed:', err); return false; } }; - -/** Consume a pending native notification navigation target, if any. */ -export const getPendingNotificationNav = async (): Promise<{ - path?: string | null; - roomId?: string | null; -}> => { - if (!isBackgroundSyncSupported()) return {}; - try { - return await MatrixBackgroundSync.getPendingNotificationNav(); - } catch (err) { - console.warn('[BackgroundSync] getPendingNotificationNav failed:', err); - return {}; - } -}; - -/** Subscribe to native notification taps that open the app. */ -export const listenForNotificationOpens = async ( - listener: (event: { path?: string; roomId?: string }) => void -): Promise => { - if (!isBackgroundSyncSupported()) return undefined; - try { - return await MatrixBackgroundSync.addListener('notificationOpened', listener); - } catch (err) { - console.warn('[BackgroundSync] notificationOpened listener failed:', err); - return undefined; - } -}; diff --git a/overlay/src/app/utils/tauri.ts b/overlay/src/app/utils/tauri.ts index 8bde8b2..941f4c0 100644 --- a/overlay/src/app/utils/tauri.ts +++ b/overlay/src/app/utils/tauri.ts @@ -226,7 +226,7 @@ export const setupNotificationTapListener = async (onTap: (path: string) => void try { const { getPendingNotificationNav, - listenForNotificationOpens, + subscribeNotificationOpened, } = await import('./backgroundSync'); const deliver = (path?: string | null, roomId?: string | null) => { @@ -241,9 +241,9 @@ export const setupNotificationTapListener = async (onTap: (path: string) => void }; const pending = await getPendingNotificationNav(); - deliver(pending.path, pending.roomId); + deliver(pending?.path, pending?.roomId); - await listenForNotificationOpens((event) => { + await subscribeNotificationOpened((event) => { void focusWindow(); deliver(event.path, event.roomId); });