diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts index b3b7a49c..5a16f7f3 100644 --- a/app/android/app/build.gradle.kts +++ b/app/android/app/build.gradle.kts @@ -53,4 +53,10 @@ flutter { dependencies { coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4") + // The background notification socket (notify/NotificationService). + implementation("com.squareup.okhttp3:okhttp:4.12.0") + // JVM tests for the notification protocol and ledger (`gradlew :app:testDebugUnitTest`). + testImplementation("junit:junit:4.13.2") + // Android's org.json is a stub on the JVM; tests use the real implementation. + testImplementation("org.json:json:20180813") } diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml index c34704da..73d806a8 100644 --- a/app/android/app/src/main/AndroidManifest.xml +++ b/app/android/app/src/main/AndroidManifest.xml @@ -4,6 +4,14 @@ + + + + + + + + + + + + + + + + + NotificationService.start(context) + } + } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/DeliveryLedger.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/DeliveryLedger.kt new file mode 100644 index 00000000..15758d1e --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/DeliveryLedger.kt @@ -0,0 +1,95 @@ +package net.awan.pipelines_app.notify + +/** The few persisted strings the ledger needs; SharedPreferences in the app. */ +interface LedgerStore { + fun getString(key: String): String? + fun putString(key: String, value: String?) +} + +/** + * What this device has already delivered for one server: the replay cursor + * (the last notification id received), a bounded set of shown ids so a replay + * never alerts twice, and the clears waiting to be sent. + * + * Switching to another server ([bindServer]) forgets the previous server's + * cursor and history, because notification ids are only unique per server. + */ +class DeliveryLedger(private val store: LedgerStore, private val maxShown: Int = 500) { + val cursor: String? get() = store.getString(CURSOR)?.takeIf { it.isNotEmpty() } + + /** Returns true when [serverId] differs from the bound server (state was reset). */ + fun bindServer(serverId: String): Boolean { + if (store.getString(SERVER) == serverId) return false + store.putString(SERVER, serverId) + store.putString(CURSOR, null) + store.putString(SHOWN, null) + store.putString(PENDING, null) + return true + } + + /** + * Records a received batch and returns only the notifications not shown + * before, in order. The cursor advances to the last id in the batch even + * when every item was a duplicate. + */ + fun accept(batch: List): List { + if (batch.isEmpty()) return emptyList() + val shown = shownIds().toMutableList() + val fresh = mutableListOf() + for (notification in batch) { + if (notification.id in shown) continue + shown.add(notification.id) + fresh.add(notification) + } + while (shown.size > maxShown) shown.removeAt(0) + store.putString(SHOWN, encode(shown)) + store.putString(CURSOR, batch.last().id) + return fresh + } + + fun shownIds(): List = decode(store.getString(SHOWN)) + + /** Queues ids the user dismissed or opened, until a socket can send them. */ + fun queueClear(ids: Collection) { + if (ids.isEmpty()) return + val pending = LinkedHashSet(pendingClears()) + pending.addAll(ids.filter { it.isNotEmpty() }) + store.putString(PENDING, encode(pending.toList())) + } + + fun pendingClears(): List = decode(store.getString(PENDING)) + + /** Drops [ids] from the queue once they were written to an open socket. */ + fun clearsSent(ids: Collection) { + val remaining = pendingClears().filterNot { it in ids } + store.putString(PENDING, if (remaining.isEmpty()) null else encode(remaining)) + } + + companion object { + const val SERVER = "ledger.server" + const val CURSOR = "ledger.cursor" + const val SHOWN = "ledger.shown" + const val PENDING = "ledger.pendingClears" + + // Ids are opaque server strings; newline is not a valid id character. + private fun encode(ids: List) = ids.joinToString("\n") + private fun decode(raw: String?): List = + raw?.split('\n')?.filter { it.isNotEmpty() } ?: emptyList() + + /** A stable Android notification id for a server id string. */ + fun notificationId(id: String): Int { + // FNV-1a keeps the mapping stable across processes and releases, + // unlike String.hashCode collisions with the reserved ids below. + var hash = 0x811c9dc5.toInt() + for (char in id) { + hash = hash xor char.code + hash *= 0x01000193 + } + val positive = hash and 0x7fffffff + return if (positive <= RESERVED_IDS) positive + RESERVED_IDS + 1 else positive + } + + /** Ids at or below this are reserved for the service's own notifications. */ + const val RESERVED_IDS = 16 + } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationDismissReceiver.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationDismissReceiver.kt new file mode 100644 index 00000000..1d223c4d --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationDismissReceiver.kt @@ -0,0 +1,31 @@ +package net.awan.pipelines_app.notify + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +/** + * A swiped-away notification is cleared on the server, so every device drops + * it. The id is queued durably and sent by the service when it is connected. + */ +class NotificationDismissReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != ACTION) return + val id = intent.getStringExtra(NotificationPresenter.EXTRA_NOTIFICATION_ID) ?: return + queueClear(context, id) + } + + companion object { + const val ACTION = "net.awan.pipelines.notify.DISMISSED" + + /** Shared by dismissals and taps (see MainActivity). */ + fun queueClear(context: Context, id: String) { + DeliveryLedger(ServiceSettings(context)).queueClear(listOf(id)) + // Only nudge a running service; a stopped one sends the queue on + // its next connection. + if (NotificationService.running != null) { + NotificationService.start(context, NotificationService.ACTION_FLUSH) + } + } + } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt new file mode 100644 index 00000000..4db340a1 --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt @@ -0,0 +1,239 @@ +package net.awan.pipelines_app.notify + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationChannelGroup +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Build +import net.awan.pipelines_app.MainActivity +import net.awan.pipelines_app.R + +/** + * Posts server notifications in the system tray: one channel per kind and + * priority (created lazily, grouped by kind), Android groups by the server's + * `group`, a tap opens the app at the `click` deep link, and a dismissal is + * reported back so the server clears it everywhere. + */ +class NotificationPresenter(private val context: Context) { + private val manager = context.getSystemService(NotificationManager::class.java) + + fun connectionNotification(status: DeliveryStatus): Notification { + ensureChannel(CONNECTION_CHANNEL, "Connection", NotificationManager.IMPORTANCE_MIN, null) + val text = when (status) { + DeliveryStatus.CONNECTED -> "Pipelines is connected" + DeliveryStatus.WAITING_FOR_NETWORK -> "Pipelines is waiting for a network" + DeliveryStatus.CONNECTING -> "Pipelines is connecting…" + else -> "Pipelines is reconnecting…" + } + val open = PendingIntent.getActivity( + context, + 0, + Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + return builder(CONNECTION_CHANNEL) + .setSmallIcon(R.drawable.ic_stat_pipelines) + .setContentTitle(text) + .setContentText("Delivering notifications from your server") + .setOngoing(true) + .setShowWhen(false) + .setContentIntent(open) + .setCategory(Notification.CATEGORY_SERVICE) + .build() + } + + fun updateConnection(status: DeliveryStatus) { + manager.notify(CONNECTION_ID, connectionNotification(status)) + } + + fun show(notification: ServerNotification) { + val id = DeliveryLedger.notificationId(notification.id) + val channel = channelFor(notification) + val title = notification.title.ifEmpty { "Pipelines" } + val builder = builder(channel) + .setSmallIcon(R.drawable.ic_stat_pipelines) + .setContentTitle(title) + .setContentText(notification.message) + .setStyle(Notification.BigTextStyle().bigText(notification.message)) + .setAutoCancel(true) + .setContentIntent(openIntent(notification, id)) + .setDeleteIntent(dismissIntent(notification.id, id)) + createdMillis(notification.createdAt)?.let { builder.setWhen(it).setShowWhen(true) } + if (notification.group.isNotEmpty()) builder.setGroup(notification.group) + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + @Suppress("DEPRECATION") + builder.setPriority(effectivePriority(notification.kind, notification.priority) - 3) + } + manager.notify(id, builder.build()) + if (notification.group.isNotEmpty()) updateSummary(notification.group, channel) + } + + /** Removes notifications cleared on this or another device. */ + fun cancel(ids: Collection) { + val groups = mutableSetOf() + val active = manager.activeNotifications + for (id in ids) { + val notificationId = DeliveryLedger.notificationId(id) + active.firstOrNull { it.id == notificationId }?.notification?.group?.let(groups::add) + manager.cancel(notificationId) + } + groups.forEach { updateSummary(it, null) } + } + + /** Removes every server notification, keeping the connection one. */ + fun cancelAll() { + manager.activeNotifications + .filter { it.id != CONNECTION_ID } + .forEach { manager.cancel(it.tag, it.id) } + } + + private fun updateSummary(group: String, channel: String?) { + val summaryId = DeliveryLedger.notificationId("group:$group") + val members = manager.activeNotifications.count { + it.notification.group == group && it.id != summaryId + } + if (members < 2) { + if (members == 0) manager.cancel(summaryId) + return + } + val existing = manager.activeNotifications.firstOrNull { it.id == summaryId } + val summaryChannel = channel ?: existing?.notification?.channelIdCompat() ?: return + manager.notify( + summaryId, + builder(summaryChannel) + .setSmallIcon(R.drawable.ic_stat_pipelines) + .setContentTitle("Pipelines") + .setContentText("$members notifications") + .setGroup(group) + .setGroupSummary(true) + .setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN) + .setAutoCancel(true) + .build(), + ) + } + + private fun Notification.channelIdCompat(): String? = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) channelId else CONNECTION_CHANNEL + + private fun openIntent(notification: ServerNotification, requestCode: Int): PendingIntent { + val intent = Intent(context, MainActivity::class.java) + .addFlags( + Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or + Intent.FLAG_ACTIVITY_CLEAR_TOP, + ) + .putExtra(EXTRA_NOTIFICATION_ID, notification.id) + // Only the app's own links are routed; Flutter's deep-link handling + // turns pipelines://run/ and pipelines://chat/ into a route. + val click = Uri.parse(notification.click) + if (click.scheme == "pipelines") intent.setAction(Intent.ACTION_VIEW).setData(click) + return PendingIntent.getActivity( + context, + requestCode, + intent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + } + + private fun dismissIntent(serverId: String, requestCode: Int): PendingIntent = + PendingIntent.getBroadcast( + context, + requestCode, + Intent(context, NotificationDismissReceiver::class.java) + .setAction(NotificationDismissReceiver.ACTION) + .putExtra(EXTRA_NOTIFICATION_ID, serverId), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + + private fun channelFor(notification: ServerNotification): String { + val kind = notification.kind.replace(Regex("[^A-Za-z0-9_.-]"), "_") + val priority = effectivePriority(kind, notification.priority) + val id = "pipelines.$kind.p$priority" + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val groupId = "pipelines.kind.$kind" + manager.createNotificationChannelGroup(NotificationChannelGroup(groupId, kindLabel(kind))) + val name = if (priority == kindPriority(kind)) kindLabel(kind) + else "${kindLabel(kind)} (${priorityLabel(priority)})" + ensureChannel(id, name, importance(priority), groupId) + } + return id + } + + private fun ensureChannel(id: String, name: String, importance: Int, group: String?) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + if (manager.getNotificationChannel(id) != null) return + val channel = NotificationChannel(id, name, importance) + if (group != null) channel.group = group + if (id == CONNECTION_CHANNEL) { + channel.description = "Shown while Pipelines keeps its notification connection open" + channel.setShowBadge(false) + } + manager.createNotificationChannel(channel) + } + + @Suppress("DEPRECATION") + private fun builder(channel: String): Notification.Builder = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(context, channel) + else Notification.Builder(context) + + companion object { + const val CONNECTION_ID = 1 + const val CONNECTION_CHANNEL = "pipelines.connection" + const val EXTRA_NOTIFICATION_ID = "net.awan.pipelines.notification_id" + + private val KIND_LABELS = mapOf( + "run_waiting" to "Run waiting for you", + "run_failed" to "Run failed", + "run_succeeded" to "Run succeeded", + "stage_failed" to "Stage failed", + "stage_succeeded" to "Stage succeeded", + "chat_question" to "Chat question", + "chat_approval" to "Chat approval", + "chat_reply" to "Chat reply", + ) + + fun importance(priority: Int): Int = when (priority) { + 1 -> NotificationManager.IMPORTANCE_MIN + 2 -> NotificationManager.IMPORTANCE_LOW + 3 -> NotificationManager.IMPORTANCE_DEFAULT + else -> NotificationManager.IMPORTANCE_HIGH + } + + fun priorityLabel(priority: Int): String = when (priority) { + 1 -> "Min priority" + 2 -> "Low priority" + 3 -> "Default priority" + 4 -> "High priority" + else -> "Urgent" + } + + /** + * The server sends the default priority (3) for everything, so the + * kind decides how loudly a notification arrives; an explicit + * non-default priority still wins. + */ + fun effectivePriority(kind: String, priority: Int): Int = + if (priority != 3) priority else kindPriority(kind) + + fun kindPriority(kind: String): Int = when (kind) { + "run_waiting", "run_failed", "stage_failed", "chat_question", "chat_approval" -> 4 + "stage_succeeded" -> 2 + else -> 3 + } + + fun kindLabel(kind: String): String = KIND_LABELS[kind] ?: + kind.split('_', '-', '.').filter { it.isNotEmpty() } + .joinToString(" ") { it.replaceFirstChar(Char::uppercaseChar) } + .ifEmpty { "Notifications" } + + fun createdMillis(createdAt: String): Long? = try { + if (createdAt.isEmpty()) null + else java.time.OffsetDateTime.parse(createdAt).toInstant().toEpochMilli() + } catch (_: Exception) { + null + } + } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationProtocol.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationProtocol.kt new file mode 100644 index 00000000..5fa8a595 --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationProtocol.kt @@ -0,0 +1,115 @@ +package net.awan.pipelines_app.notify + +import org.json.JSONArray +import org.json.JSONObject + +/** One server notification as pushed on the shared socket. */ +data class ServerNotification( + val id: String, + val kind: String, + val title: String, + val message: String, + val click: String, + /** ntfy-style priority, clamped to 1..5 (3 is the default). */ + val priority: Int, + val tags: List, + val createdAt: String, + val group: String, +) + +/** The frames the notification service reacts to; everything else is [Ignored]. */ +sealed interface NotificationFrame { + /** [clearedIds]: notifications cleared recently (while this device was away). */ + data class Subscribed( + val notifications: List, + val clearedIds: List = emptyList(), + ) : NotificationFrame + data class Pushed(val notification: ServerNotification) : NotificationFrame + data class Cleared(val ids: List) : NotificationFrame + data class Refused(val requestId: String, val error: String) : NotificationFrame + data object Ignored : NotificationFrame +} + +/** + * The wire contract of `subscribe_notifications`, `notification`, + * `notifications_cleared` and `clear_notifications`. Pure, so it is covered by + * JVM unit tests without a device. + */ +object NotificationProtocol { + fun subscribe(requestId: String, after: String?): String { + val frame = JSONObject() + .put("type", "subscribe_notifications") + .put("id", requestId) + if (!after.isNullOrEmpty()) frame.put("after", after) + return frame.toString() + } + + fun clear(requestId: String, ids: Collection): String = + JSONObject() + .put("type", "clear_notifications") + .put("id", requestId) + .put("ids", JSONArray(ids.toList())) + .toString() + + /** Parses one text frame; malformed input is [NotificationFrame.Ignored]. */ + fun parse(text: String, subscribeRequestId: String?): NotificationFrame { + val frame = try { + JSONObject(text) + } catch (_: Exception) { + return NotificationFrame.Ignored + } + return when (frame.optString("type")) { + "notifications_subscribed" -> NotificationFrame.Subscribed( + notifications(frame.optJSONArray("notifications")), + strings(frame.optJSONArray("ids")), + ) + "notification" -> notification(frame.optJSONObject("notification") ?: frame) + ?.let { NotificationFrame.Pushed(it) } + ?: NotificationFrame.Ignored + "notifications_cleared" -> NotificationFrame.Cleared(strings(frame.optJSONArray("ids"))) + "error" -> { + val id = frame.optString("id") + if (subscribeRequestId != null && id == subscribeRequestId) { + NotificationFrame.Refused(id, frame.text("error")) + } else { + NotificationFrame.Ignored + } + } + else -> NotificationFrame.Ignored + } + } + + private fun notifications(array: JSONArray?): List { + if (array == null) return emptyList() + return (0 until array.length()).mapNotNull { index -> + array.optJSONObject(index)?.let(::notification) + } + } + + fun notification(json: JSONObject): ServerNotification? { + val id = json.text("id").trim() + if (id.isEmpty()) return null + return ServerNotification( + id = id, + kind = json.text("kind").trim().ifEmpty { "general" }, + title = json.text("title"), + message = json.text("message"), + click = json.text("click").trim(), + priority = json.optInt("priority", 3).let { if (it in 1..5) it else 3 }, + tags = strings(json.optJSONArray("tags")), + createdAt = json.text("created_at"), + group = json.text("group").trim(), + ) + } + + /** org.json renders a JSON null as the text "null"; treat it as absent. */ + private fun JSONObject.text(key: String): String = + if (isNull(key)) "" else optString(key) + + private fun strings(array: JSONArray?): List { + if (array == null) return emptyList() + return (0 until array.length()).mapNotNull { index -> + array.optString(index, "").trim().takeIf { it.isNotEmpty() } + } + } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt new file mode 100644 index 00000000..870bb358 --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt @@ -0,0 +1,293 @@ +package net.awan.pipelines_app.notify + +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.net.ConnectivityManager +import android.net.Network +import android.os.Build +import android.os.Handler +import android.os.HandlerThread +import android.os.IBinder +import android.util.Log +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener +import java.util.concurrent.TimeUnit + +/** + * Keeps one authenticated websocket to the configured Pipelines server while + * the app is in the background, like ntfy's instant delivery: no Flutter + * engine runs here. It subscribes with the replay cursor, posts each pushed + * notification, mirrors cross-device clears and sends the user's own clears. + * + * All state is confined to [handler]'s thread; OkHttp and connectivity + * callbacks post onto it. + */ +class NotificationService : Service() { + private lateinit var settings: ServiceSettings + private lateinit var ledger: DeliveryLedger + private lateinit var presenter: NotificationPresenter + private lateinit var thread: HandlerThread + private lateinit var handler: Handler + private val client = OkHttpClient.Builder() + .connectTimeout(15, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.MILLISECONDS) + .pingInterval(45, TimeUnit.SECONDS) + .followRedirects(false) + .build() + private val backoff = Backoff() + private var socket: WebSocket? = null + private var generation = 0 + private var endpointIndex = 0 + private var subscribeId: String? = null + private var sequence = 0 + private var networkAvailable = true + private var currentNetwork: Network? = null + private var networkCallback: ConnectivityManager.NetworkCallback? = null + private val reconnect = Runnable { connect() } + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onCreate() { + super.onCreate() + settings = ServiceSettings(this) + ledger = DeliveryLedger(settings) + presenter = NotificationPresenter(this) + thread = HandlerThread("pipelines-notifications").also { it.start() } + handler = Handler(thread.looper) + goForeground(DeliveryStatus.CONNECTING) + watchNetwork() + running = this + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + val action = intent?.action + handler.post { + when { + !settings.enabled || !settings.configured -> stopEverything() + action == ACTION_FLUSH -> flushClears() + action == ACTION_RESTART || socket == null -> restart() + } + } + return START_STICKY + } + + override fun onDestroy() { + running = null + networkCallback?.let { + getSystemService(ConnectivityManager::class.java).unregisterNetworkCallback(it) + } + handler.removeCallbacksAndMessages(null) + handler.post { + generation++ + socket?.close(1000, "service stopped") + socket = null + } + thread.quitSafely() + if (settings.status != DeliveryStatus.UNCONFIGURED) setStatus(DeliveryStatus.OFF, notify = false) + super.onDestroy() + } + + private fun goForeground(status: DeliveryStatus) { + val notification = presenter.connectionNotification(status) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + startForeground( + NotificationPresenter.CONNECTION_ID, + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE, + ) + } else { + startForeground(NotificationPresenter.CONNECTION_ID, notification) + } + } + + private fun stopEverything() { + generation++ + socket?.close(1000, "disabled") + socket = null + setStatus(if (settings.configured) DeliveryStatus.OFF else DeliveryStatus.UNCONFIGURED, notify = false) + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + } + + /** Server changed, credentials changed, or the first start: reopen now. */ + private fun restart() { + if (ledger.bindServer(settings.serverId)) presenter.cancelAll() + handler.removeCallbacks(reconnect) + backoff.reset() + endpointIndex = 0 + connect() + } + + private fun connect() { + handler.removeCallbacks(reconnect) + generation++ + socket?.cancel() + socket = null + subscribeId = null + val endpoints = settings.endpoints + if (endpoints.isEmpty()) return stopEverything() + if (!networkAvailable) return setStatus(DeliveryStatus.WAITING_FOR_NETWORK) + val endpoint = endpoints[endpointIndex % endpoints.size] + val request = try { + Request.Builder().url(endpoint).apply { + if (settings.cookie.isNotEmpty()) header("Cookie", settings.cookie) + }.build() + } catch (error: IllegalArgumentException) { + Log.w(TAG, "invalid endpoint $endpoint", error) + return scheduleReconnect() + } + setStatus(if (backoff.attempt == 0) DeliveryStatus.CONNECTING else DeliveryStatus.RECONNECTING) + val current = generation + socket = client.newWebSocket(request, Listener(current)) + } + + private fun scheduleReconnect() { + generation++ + socket?.cancel() + socket = null + subscribeId = null + if (!networkAvailable) return setStatus(DeliveryStatus.WAITING_FOR_NETWORK) + setStatus(DeliveryStatus.RECONNECTING) + // Rotate through the server's trusted aliases on each failure. + endpointIndex++ + handler.postDelayed(reconnect, backoff.next()) + } + + private fun onOpen(webSocket: WebSocket) { + backoff.reset() + val id = "notify-${++sequence}" + subscribeId = id + webSocket.send(NotificationProtocol.subscribe(id, ledger.cursor)) + setStatus(DeliveryStatus.CONNECTED) + flushClears() + } + + private fun onText(text: String) { + when (val frame = NotificationProtocol.parse(text, subscribeId)) { + is NotificationFrame.Subscribed -> { + presenter.cancel(frame.clearedIds) + ledger.accept(frame.notifications) + .filterNot { it.id in frame.clearedIds } + .forEach(presenter::show) + } + is NotificationFrame.Pushed -> ledger.accept(listOf(frame.notification)).forEach(presenter::show) + is NotificationFrame.Cleared -> presenter.cancel(frame.ids) + is NotificationFrame.Refused -> { + Log.w(TAG, "subscribe_notifications refused: ${frame.error}") + scheduleReconnect() + } + NotificationFrame.Ignored -> Unit + } + } + + private fun flushClears() { + val open = socket ?: return + if (settings.status != DeliveryStatus.CONNECTED) return + val pending = ledger.pendingClears() + if (pending.isEmpty()) return + if (open.send(NotificationProtocol.clear("clear-${++sequence}", pending))) { + ledger.clearsSent(pending) + } + } + + private fun setStatus(status: DeliveryStatus, notify: Boolean = true) { + if (settings.status == status) return + settings.status = status + if (notify) presenter.updateConnection(status) + statusListener?.invoke(status) + } + + private fun watchNetwork() { + val connectivity = getSystemService(ConnectivityManager::class.java) + currentNetwork = connectivity.activeNetwork + networkAvailable = currentNetwork != null + val callback = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + handler.post { + val previous = currentNetwork + currentNetwork = network + networkAvailable = true + // A new default network invalidates the old socket's route; + // a returning network retries at once instead of waiting + // out the backoff. + val moved = previous != null && previous != network + val idle = settings.status == DeliveryStatus.WAITING_FOR_NETWORK || + settings.status == DeliveryStatus.RECONNECTING + if (settings.configured && (moved || previous == null || idle)) { + backoff.reset() + connect() + } + } + } + + override fun onLost(network: Network) { + handler.post { + if (network != currentNetwork) return@post + currentNetwork = null + networkAvailable = false + scheduleReconnect() + } + } + } + connectivity.registerDefaultNetworkCallback(callback) + networkCallback = callback + } + + private inner class Listener(private val owner: Int) : WebSocketListener() { + private fun current(block: () -> Unit) { + handler.post { if (owner == generation) block() } + } + + override fun onOpen(webSocket: WebSocket, response: Response) = current { onOpen(webSocket) } + override fun onMessage(webSocket: WebSocket, text: String) = current { onText(text) } + override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { + webSocket.close(1000, null) + } + + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = current { scheduleReconnect() } + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = current { + Log.i(TAG, "socket failed (${response?.code}): ${t.message}") + scheduleReconnect() + } + } + + companion object { + private const val TAG = "PipelinesNotify" + const val ACTION_RESTART = "net.awan.pipelines.notify.RESTART" + const val ACTION_FLUSH = "net.awan.pipelines.notify.FLUSH" + + @Volatile + var running: NotificationService? = null + private set + + /** Settings' live status; called on the service thread. */ + @Volatile + var statusListener: ((DeliveryStatus) -> Unit)? = null + + /** Starts (or nudges) the service when it is enabled and configured. */ + fun start(context: Context, action: String? = null): Boolean { + val settings = ServiceSettings(context) + if (!settings.enabled || !settings.configured) return false + val intent = Intent(context, NotificationService::class.java).setAction(action) + return try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent) + else context.startService(intent) + true + } catch (error: Exception) { + // Android 12+ refuses a foreground start from some background + // contexts; the next app launch or boot starts it instead. + Log.w(TAG, "could not start the notification service", error) + false + } + } + + fun stop(context: Context) { + context.stopService(Intent(context, NotificationService::class.java)) + } + } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt new file mode 100644 index 00000000..17da5587 --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt @@ -0,0 +1,120 @@ +package net.awan.pipelines_app.notify + +import android.annotation.SuppressLint +import android.app.Activity +import android.content.Intent +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.os.PowerManager +import android.provider.Settings +import android.app.NotificationManager +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel + +/** + * The Flutter side's handle on background delivery (`pipelines/notification_service`). + * + * Dart hands over the server it is connected to (`configure`), switches + * delivery on or off (`setEnabled`), reads `status` and asks for the battery + * exemption. Status changes are pushed back as `statusChanged`. + */ +class NotificationServiceChannel(private val activity: Activity, messenger: BinaryMessenger) : + MethodChannel.MethodCallHandler { + private val channel = MethodChannel(messenger, NAME) + private val settings = ServiceSettings(activity) + private val main = Handler(Looper.getMainLooper()) + + init { + channel.setMethodCallHandler(this) + NotificationService.statusListener = { main.post { channel.invokeMethod("statusChanged", status()) } } + } + + fun dispose() { + channel.setMethodCallHandler(null) + NotificationService.statusListener = null + } + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "status" -> result.success(status()) + "start" -> { + NotificationService.start(activity) + result.success(status()) + } + "configure" -> { + val serverId = call.argument("serverId") ?: "" + val endpoints = call.argument>("endpoints") ?: emptyList() + val cookie = call.argument("cookie") ?: "" + if (endpoints.isEmpty()) { + result.error("invalid", "configure needs at least one endpoint", null) + return + } + val changed = settings.configure(serverId, endpoints, cookie) + val running = NotificationService.running != null + if (changed || !running) { + NotificationService.start(activity, if (changed) NotificationService.ACTION_RESTART else null) + } + result.success(status()) + } + "setEnabled" -> { + val enabled = call.argument("enabled") ?: true + settings.enabled = enabled + if (enabled) { + NotificationService.start(activity, NotificationService.ACTION_RESTART) + } else { + NotificationService.stop(activity) + settings.status = DeliveryStatus.OFF + } + result.success(status()) + } + "requestBatteryExemption" -> { + result.success(requestBatteryExemption()) + } + else -> result.notImplemented() + } + } + + private fun status(): Map { + val running = NotificationService.running != null + val status = when { + !settings.configured -> DeliveryStatus.UNCONFIGURED + !settings.enabled || !running -> DeliveryStatus.OFF + else -> settings.status + } + return mapOf( + "enabled" to settings.enabled, + "configured" to settings.configured, + "status" to status.wire, + "notificationsAllowed" to activity.getSystemService(NotificationManager::class.java).areNotificationsEnabled(), + "batteryExempt" to batteryExempt(), + ) + } + + private fun batteryExempt(): Boolean = + activity.getSystemService(PowerManager::class.java).isIgnoringBatteryOptimizations(activity.packageName) + + /** Opens the system's exemption prompt; true when it could be shown. */ + @SuppressLint("BatteryLife") + private fun requestBatteryExemption(): Boolean { + if (batteryExempt()) return true + val direct = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) + .setData(Uri.parse("package:${activity.packageName}")) + return try { + activity.startActivity(direct) + true + } catch (_: Exception) { + try { + activity.startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) + true + } catch (_: Exception) { + false + } + } + } + + companion object { + const val NAME = "pipelines/notification_service" + } +} diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ServiceSettings.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ServiceSettings.kt new file mode 100644 index 00000000..08984eec --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ServiceSettings.kt @@ -0,0 +1,73 @@ +package net.awan.pipelines_app.notify + +import android.content.Context +import android.content.SharedPreferences + +/** Connection states the service reports to Settings. */ +enum class DeliveryStatus(val wire: String) { + OFF("off"), + UNCONFIGURED("unconfigured"), + CONNECTING("connecting"), + CONNECTED("connected"), + RECONNECTING("reconnecting"), + WAITING_FOR_NETWORK("waiting_for_network"), +} + +/** + * The service's own preferences. The Flutter app hands over the server it is + * connected to (its trusted endpoints and the web sign-in cookie) through the + * method channel; the service never reads Flutter's storage. + */ +class ServiceSettings(context: Context) : LedgerStore { + private val prefs: SharedPreferences = + context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE) + + /** On by default: the app delivers its own notifications unless switched off. */ + var enabled: Boolean + get() = prefs.getBoolean(ENABLED, true) + set(value) = prefs.edit().putBoolean(ENABLED, value).apply() + + val serverId: String get() = prefs.getString(SERVER_ID, "") ?: "" + val endpoints: List + get() = (prefs.getString(ENDPOINTS, "") ?: "").split('\n').filter { it.isNotEmpty() } + val cookie: String get() = prefs.getString(COOKIE, "") ?: "" + val configured: Boolean get() = endpoints.isNotEmpty() + + /** Returns true when the server, addresses or credentials changed. */ + fun configure(serverId: String, endpoints: List, cookie: String): Boolean { + val joined = endpoints.filter { it.isNotEmpty() }.joinToString("\n") + val changed = serverId != this.serverId || + joined != prefs.getString(ENDPOINTS, "") || + cookie != this.cookie + if (changed) { + prefs.edit() + .putString(SERVER_ID, serverId) + .putString(ENDPOINTS, joined) + .putString(COOKIE, cookie) + .commit() + } + return changed + } + + var status: DeliveryStatus + get() = DeliveryStatus.entries.firstOrNull { it.wire == prefs.getString(STATUS, null) } + ?: DeliveryStatus.OFF + set(value) = prefs.edit().putString(STATUS, value.wire).apply() + + override fun getString(key: String): String? = prefs.getString(key, null) + + override fun putString(key: String, value: String?) { + // Ledger writes are committed so a process kill cannot replay an alert. + if (value == null) prefs.edit().remove(key).commit() + else prefs.edit().putString(key, value).commit() + } + + companion object { + const val FILE = "pipelines.notification_service" + private const val ENABLED = "enabled" + private const val SERVER_ID = "serverId" + private const val ENDPOINTS = "endpoints" + private const val COOKIE = "cookie" + private const val STATUS = "status" + } +} diff --git a/app/android/app/src/main/res/drawable/ic_stat_pipelines.xml b/app/android/app/src/main/res/drawable/ic_stat_pipelines.xml new file mode 100644 index 00000000..59018a0a --- /dev/null +++ b/app/android/app/src/main/res/drawable/ic_stat_pipelines.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/DeliveryLedgerTest.kt b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/DeliveryLedgerTest.kt new file mode 100644 index 00000000..99848ddc --- /dev/null +++ b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/DeliveryLedgerTest.kt @@ -0,0 +1,93 @@ +package net.awan.pipelines_app.notify + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class DeliveryLedgerTest { + private class MemoryStore : LedgerStore { + val values = mutableMapOf() + override fun getString(key: String) = values[key] + override fun putString(key: String, value: String?) { + if (value == null) values.remove(key) else values[key] = value + } + } + + private fun n(id: String) = ServerNotification(id, "k", "t", "m", "", 3, emptyList(), "", "") + + @Test + fun cursorFollowsTheLastReceivedId() { + val ledger = DeliveryLedger(MemoryStore()) + ledger.bindServer("s") + assertNull(ledger.cursor) + ledger.accept(listOf(n("a"), n("b"))) + assertEquals("b", ledger.cursor) + } + + @Test + fun replayedIdsAreNotShownTwice() { + val ledger = DeliveryLedger(MemoryStore()) + ledger.bindServer("s") + assertEquals(listOf("a", "b"), ledger.accept(listOf(n("a"), n("b"))).map { it.id }) + assertEquals(listOf("c"), ledger.accept(listOf(n("b"), n("c"), n("c"))).map { it.id }) + assertEquals("c", ledger.cursor) + } + + @Test + fun stateSurvivesANewLedgerOnTheSameStore() { + val store = MemoryStore() + DeliveryLedger(store).apply { bindServer("s"); accept(listOf(n("a"))) } + val reopened = DeliveryLedger(store) + assertFalse(reopened.bindServer("s")) + assertEquals("a", reopened.cursor) + assertTrue(reopened.accept(listOf(n("a"))).isEmpty()) + } + + @Test + fun anotherServerResetsCursorHistoryAndClears() { + val ledger = DeliveryLedger(MemoryStore()) + ledger.bindServer("one") + ledger.accept(listOf(n("a"))) + ledger.queueClear(listOf("a")) + assertTrue(ledger.bindServer("two")) + assertNull(ledger.cursor) + assertTrue(ledger.pendingClears().isEmpty()) + assertEquals(1, ledger.accept(listOf(n("a"))).size) + } + + @Test + fun shownHistoryIsBounded() { + val ledger = DeliveryLedger(MemoryStore(), maxShown = 3) + ledger.bindServer("s") + ledger.accept((1..5).map { n("$it") }) + assertEquals(listOf("3", "4", "5"), ledger.shownIds()) + } + + @Test + fun pendingClearsAreDedupedAndRemovedOnceSent() { + val ledger = DeliveryLedger(MemoryStore()) + ledger.queueClear(listOf("a", "b")) + ledger.queueClear(listOf("b", "c")) + assertEquals(listOf("a", "b", "c"), ledger.pendingClears()) + ledger.clearsSent(listOf("a", "b")) + assertEquals(listOf("c"), ledger.pendingClears()) + } + + @Test + fun notificationIdsAreStableAndAvoidReservedIds() { + val first = DeliveryLedger.notificationId("n-7") + assertEquals(first, DeliveryLedger.notificationId("n-7")) + assertTrue(first > DeliveryLedger.RESERVED_IDS) + assertTrue(DeliveryLedger.notificationId("n-8") != first) + } + + @Test + fun backoffDoublesUpToTheCapAndResets() { + val backoff = Backoff(baseMillis = 1000, maxMillis = 5000) + assertEquals(listOf(1000L, 2000L, 4000L, 5000L, 5000L), (1..5).map { backoff.next() }) + backoff.reset() + assertEquals(1000L, backoff.next()) + } +} diff --git a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt new file mode 100644 index 00000000..27ad1b58 --- /dev/null +++ b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/NotificationProtocolTest.kt @@ -0,0 +1,130 @@ +package net.awan.pipelines_app.notify + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class NotificationProtocolTest { + private val pushed = """ + {"type":"notification","id":"n-7","kind":"run_failed","title":"Run 12 failed", + "message":"Step build failed","click":"pipelines://run/12","priority":4, + "tags":["x","warning"],"created_at":"2026-11-01T10:00:00Z","group":"run-12"} + """.trimIndent() + + @Test + fun subscribeOmitsAfterWithoutCursor() { + val frame = JSONObject(NotificationProtocol.subscribe("r1", null)) + assertEquals("subscribe_notifications", frame.getString("type")) + assertEquals("r1", frame.getString("id")) + assertFalse(frame.has("after")) + } + + @Test + fun subscribeSendsCursor() { + val frame = JSONObject(NotificationProtocol.subscribe("r1", "n-9")) + assertEquals("n-9", frame.getString("after")) + } + + @Test + fun clearListsIds() { + val frame = JSONObject(NotificationProtocol.clear("c1", listOf("a", "b"))) + assertEquals("clear_notifications", frame.getString("type")) + assertEquals(2, frame.getJSONArray("ids").length()) + assertEquals("b", frame.getJSONArray("ids").getString(1)) + } + + @Test + fun parsesPushedNotification() { + val frame = NotificationProtocol.parse(pushed, "r1") as NotificationFrame.Pushed + val n = frame.notification + assertEquals("n-7", n.id) + assertEquals("run_failed", n.kind) + assertEquals("Run 12 failed", n.title) + assertEquals("pipelines://run/12", n.click) + assertEquals(4, n.priority) + assertEquals(listOf("x", "warning"), n.tags) + assertEquals("run-12", n.group) + assertEquals("2026-11-01T10:00:00Z", n.createdAt) + } + + @Test + fun parsesNestedNotificationObject() { + val text = """{"type":"notification","notification":{"id":"n-1","title":"t"}}""" + val frame = NotificationProtocol.parse(text, null) as NotificationFrame.Pushed + assertEquals("n-1", frame.notification.id) + assertEquals("general", frame.notification.kind) + assertEquals(3, frame.notification.priority) + } + + @Test + fun nullsAndOutOfRangePriorityFallBack() { + val text = """{"type":"notification","id":"n-1","click":null,"group":null,"priority":9}""" + val n = (NotificationProtocol.parse(text, null) as NotificationFrame.Pushed).notification + assertEquals("", n.click) + assertEquals("", n.group) + assertEquals(3, n.priority) + } + + @Test + fun parsesSubscribedReplayAndSkipsItemsWithoutId() { + val text = """{"type":"notifications_subscribed","id":"r1","notifications":[ + {"id":"a","title":"A"},{"title":"no id"},{"id":"b","title":"B"}]}""" + val frame = NotificationProtocol.parse(text, "r1") as NotificationFrame.Subscribed + assertEquals(listOf("a", "b"), frame.notifications.map { it.id }) + } + + @Test + fun parsesServerShapesWithRecentlyClearedIdsAndExtraFields() { + val text = """{"type":"notifications_subscribed","id":"1","build":"abc","protocol":3, + "notifications":[{"id":"run:4:2:failed","kind":"run_failed","title":"t","message":"m", + "click":"pipelines://run/4","priority":3,"tags":[],"created_at":"2026-11-01T10:00:00.123456789Z", + "group":"run:4"}],"ids":["chat:9:reply:1"]}""" + val frame = NotificationProtocol.parse(text, "1") as NotificationFrame.Subscribed + assertEquals("run:4", frame.notifications.single().group) + assertEquals(listOf("chat:9:reply:1"), frame.clearedIds) + val push = """{"type":"notification","build":"abc","notification":{"id":"chat:9:form:2", + "kind":"chat_question","priority":3,"group":"chat:9","click":"pipelines://chat/9"}}""" + val pushed = (NotificationProtocol.parse(push, "1") as NotificationFrame.Pushed).notification + assertEquals("chat:9:form:2", pushed.id) + assertEquals("pipelines://chat/9", pushed.click) + val reply = """{"type":"notifications_cleared","id":"2","ids":["chat:9:form:2"]}""" + assertEquals(listOf("chat:9:form:2"), (NotificationProtocol.parse(reply, "1") as NotificationFrame.Cleared).ids) + } + + @Test + fun kindDecidesImportanceWhenPriorityIsDefault() { + assertEquals(4, NotificationPresenter.effectivePriority("run_waiting", 3)) + assertEquals(4, NotificationPresenter.effectivePriority("chat_approval", 3)) + assertEquals(3, NotificationPresenter.effectivePriority("chat_reply", 3)) + assertEquals(2, NotificationPresenter.effectivePriority("stage_succeeded", 3)) + assertEquals(5, NotificationPresenter.effectivePriority("stage_succeeded", 5)) + assertEquals("Run waiting for you", NotificationPresenter.kindLabel("run_waiting")) + assertEquals("Custom Kind", NotificationPresenter.kindLabel("custom_kind")) + assertEquals(1761991200123L, NotificationPresenter.createdMillis("2025-11-01T10:00:00.123456789Z")) + } + + @Test + fun parsesCleared() { + val frame = NotificationProtocol.parse( + """{"type":"notifications_cleared","ids":["a","","b"]}""", + null, + ) as NotificationFrame.Cleared + assertEquals(listOf("a", "b"), frame.ids) + } + + @Test + fun onlyTheSubscribeErrorIsARefusal() { + val error = """{"type":"error","id":"r1","error":"unknown type"}""" + assertTrue(NotificationProtocol.parse(error, "r1") is NotificationFrame.Refused) + assertEquals(NotificationFrame.Ignored, NotificationProtocol.parse(error, "r2")) + } + + @Test + fun ignoresMalformedAndUnrelatedFrames() { + assertEquals(NotificationFrame.Ignored, NotificationProtocol.parse("not json", null)) + assertEquals(NotificationFrame.Ignored, NotificationProtocol.parse("""{"type":"run_event"}""", null)) + assertEquals(NotificationFrame.Ignored, NotificationProtocol.parse("""{"type":"notification"}""", null)) + } +} diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 49ccbdc9..e78e4a8d 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -13,6 +13,8 @@ import '../shell/destination.dart'; import '../features/attention/notify/notification_controller.dart'; import '../features/attention/notify/chat_question_notices.dart'; import '../features/attention/notify/notification_store.dart'; +import '../features/notification_service/notification_service_bridge.dart'; +import '../features/notification_service/notification_service_handoff.dart'; import '../features/attention/runtime/attention_ack_queue.dart'; import '../features/attention/runtime/attention_ack_sync.dart'; import '../features/attention/runtime/attention_controller.dart'; @@ -147,6 +149,11 @@ class _PipelinesAppState extends State /// The count the shell's Runs tab shows; only a changed count rebuilds it. final ValueNotifier _attentionCount = ValueNotifier(0); + /// Android background delivery (no service elsewhere). + final NotificationServiceBridge _deliveryService = + createNotificationServiceBridge(); + NotificationServiceHandoff? _deliveryHandoff; + @override void initState() { super.initState(); @@ -157,6 +164,12 @@ class _PipelinesAppState extends State knownServer: widget.knownServer, addresses: widget.serverAddresses, ); + // The service authenticates like the app: hand over each proven server. + _deliveryHandoff = NotificationServiceHandoff( + bridge: _deliveryService, + client: _session.client, + serverId: widget.serverId, + ); bindServerIdentity(_session.gateway, widget.serverId); _ownsProvider = widget.routeInformationProvider == null; _provider = @@ -228,6 +241,7 @@ class _PipelinesAppState extends State @override void dispose() { WidgetsBinding.instance.removeObserver(this); + _deliveryHandoff?.dispose(); _session.removeListener(_attentionSessionChanged); unawaited(_attentionFrames?.cancel()); _attention.removeListener(_attentionChanged); @@ -552,6 +566,7 @@ class _PipelinesAppState extends State ), onOpenTemplates: _delegate.openTemplates, notifications: _notifications, + deliveryService: _deliveryService, ), }, ); diff --git a/app/lib/features/notification_service/host_platform_io.dart b/app/lib/features/notification_service/host_platform_io.dart new file mode 100644 index 00000000..e0751e49 --- /dev/null +++ b/app/lib/features/notification_service/host_platform_io.dart @@ -0,0 +1,4 @@ +import 'dart:io'; + +/// The real host OS, not the (test-overridable) target platform. +bool get runsOnAndroid => Platform.isAndroid; diff --git a/app/lib/features/notification_service/host_platform_stub.dart b/app/lib/features/notification_service/host_platform_stub.dart new file mode 100644 index 00000000..8a19de0c --- /dev/null +++ b/app/lib/features/notification_service/host_platform_stub.dart @@ -0,0 +1,2 @@ +/// Browsers have no background service. +bool get runsOnAndroid => false; diff --git a/app/lib/features/notification_service/notification_service_bridge.dart b/app/lib/features/notification_service/notification_service_bridge.dart new file mode 100644 index 00000000..18dc289b --- /dev/null +++ b/app/lib/features/notification_service/notification_service_bridge.dart @@ -0,0 +1,139 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import 'host_platform_stub.dart' if (dart.library.io) 'host_platform_io.dart'; +import 'notification_service_status.dart'; + +export 'notification_service_status.dart'; + +/// The app's handle on Android background delivery: a native foreground +/// service (android/…/notify/NotificationService.kt) that keeps its own +/// socket to the server and shows the server's notifications, so the ntfy app +/// is not needed. Other platforms have no service ([supported] is false). +abstract interface class NotificationServiceBridge { + bool get supported; + + /// Status pushed by the service whenever its connection changes. + Stream get changes; + + Future status(); + + /// Starts the service if delivery is enabled and a server was handed over. + Future start(); + + /// Hands over the server the app is connected to: its trusted addresses + /// (tried in order) and the web sign-in cookie, empty when none. + Future configure({ + required String serverId, + required List endpoints, + required String cookie, + }); + + Future setEnabled(bool enabled); + + /// Opens Android's "ignore battery optimisations" prompt. + Future requestBatteryExemption(); +} + +/// The bridge for this platform. One instance owns the channel's handler. +NotificationServiceBridge createNotificationServiceBridge() => runsOnAndroid + ? MethodChannelNotificationServiceBridge.instance + : const UnsupportedNotificationServiceBridge(); + +/// `pipelines/notification_service`, implemented by NotificationServiceChannel.kt. +class MethodChannelNotificationServiceBridge + implements NotificationServiceBridge { + @visibleForTesting + MethodChannelNotificationServiceBridge([ + this._channel = const MethodChannel(channelName), + ]) { + _channel.setMethodCallHandler(_onCall); + } + + static const channelName = 'pipelines/notification_service'; + static final instance = MethodChannelNotificationServiceBridge(); + + final MethodChannel _channel; + final _changes = StreamController.broadcast(); + + @override + bool get supported => true; + + @override + Stream get changes => _changes.stream; + + Future _onCall(MethodCall call) async { + if (call.method == 'statusChanged') { + _changes.add(NotificationServiceStatus.fromMap(call.arguments)); + } + } + + Future _invoke( + String method, [ + Map? arguments, + ]) async { + final reply = await _channel.invokeMethod(method, arguments); + final status = NotificationServiceStatus.fromMap(reply); + _changes.add(status); + return status; + } + + @override + Future status() => _invoke('status'); + + @override + Future start() => _invoke('start'); + + @override + Future configure({ + required String serverId, + required List endpoints, + required String cookie, + }) => _invoke('configure', { + 'serverId': serverId, + 'endpoints': endpoints, + 'cookie': cookie, + }); + + @override + Future setEnabled(bool enabled) => + _invoke('setEnabled', {'enabled': enabled}); + + @override + Future requestBatteryExemption() async => + await _channel.invokeMethod('requestBatteryExemption') ?? false; +} + +/// Web, iOS and desktop: no background service; nothing is pretended. +class UnsupportedNotificationServiceBridge + implements NotificationServiceBridge { + const UnsupportedNotificationServiceBridge(); + + @override + bool get supported => false; + + @override + Stream get changes => const Stream.empty(); + + @override + Future status() async => + NotificationServiceStatus.unsupported; + + @override + Future start() => status(); + + @override + Future configure({ + required String serverId, + required List endpoints, + required String cookie, + }) => status(); + + @override + Future setEnabled(bool enabled) => status(); + + @override + Future requestBatteryExemption() async => false; +} diff --git a/app/lib/features/notification_service/notification_service_controller.dart b/app/lib/features/notification_service/notification_service_controller.dart new file mode 100644 index 00000000..711e6a53 --- /dev/null +++ b/app/lib/features/notification_service/notification_service_controller.dart @@ -0,0 +1,84 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import 'notification_service_bridge.dart'; + +/// Settings' view of background delivery: the switch, the live status and the +/// battery exemption, all read from the native service (never guessed). +class NotificationServiceController extends ChangeNotifier { + NotificationServiceController( + this.bridge, { + this.requestNotificationPermission, + }) { + _changes = bridge.changes.listen(_apply); + } + + final NotificationServiceBridge bridge; + + /// Asks Android 13+ for POST_NOTIFICATIONS (the app's existing request). + final Future Function()? requestNotificationPermission; + + late final StreamSubscription _changes; + NotificationServiceStatus? _status; + bool _busy = false; + String _error = ''; + bool _disposed = false; + + NotificationServiceStatus? get status => _status; + bool get busy => _busy; + String get error => _error; + + Future load() => _run(bridge.status); + + /// Re-reads after returning from a system screen (permission, battery). + Future refresh() => load(); + + Future setEnabled(bool enabled) => _run(() async { + if (enabled && _status?.notificationsAllowed == false) { + await requestNotificationPermission?.call(); + } + return bridge.setEnabled(enabled); + }); + + Future allowNotifications() => _run(() async { + await requestNotificationPermission?.call(); + return bridge.status(); + }); + + Future allowBackgroundDelivery() => _run(() async { + await bridge.requestBatteryExemption(); + return bridge.status(); + }); + + Future _run(Future Function() action) async { + if (_busy) return; + _busy = true; + _error = ''; + _notify(); + try { + _status = await action(); + } catch (error) { + _error = 'Background delivery is unavailable: $error'; + } finally { + _busy = false; + _notify(); + } + } + + void _apply(NotificationServiceStatus status) { + _status = status; + _notify(); + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + unawaited(_changes.cancel()); + super.dispose(); + } +} diff --git a/app/lib/features/notification_service/notification_service_handoff.dart b/app/lib/features/notification_service/notification_service_handoff.dart new file mode 100644 index 00000000..a3e5099b --- /dev/null +++ b/app/lib/features/notification_service/notification_service_handoff.dart @@ -0,0 +1,74 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../core/session/server_session.dart'; +import '../../core/transport/pipelines_client.dart'; +import 'notification_service_bridge.dart'; + +/// Shares the app's proven connection with the background service. +/// +/// Whenever the shared client connects, the server it reached (its trusted +/// addresses and the web sign-in cookie the socket used) is handed to the +/// service, so the service authenticates exactly like the app. On creation it +/// starts the service if delivery is enabled and a server was handed over +/// before, which covers app launches after the service was stopped. +class NotificationServiceHandoff { + NotificationServiceHandoff({ + required this.bridge, + required this.client, + required this.serverId, + @visibleForTesting Map Function(Uri endpoint)? headersFor, + }) : _headersFor = headersFor ?? ServerSession.headersFor { + if (!bridge.supported) return; + unawaited(_guard(bridge.start())); + _states = client.states.listen(_onState); + if (client.state.kind == ConnectionKind.connected) _handOver(); + } + + final NotificationServiceBridge bridge; + final PipelinesClient client; + + /// The logical server; falls back to the connected address when absent. + final String? serverId; + final Map Function(Uri endpoint) _headersFor; + StreamSubscription? _states; + + void _onState(ConnectionState state) { + if (state.kind == ConnectionKind.connected) _handOver(); + } + + void _handOver() { + final endpoint = client.endpoint; + if (endpoint == null) return; + final addresses = client.endpoints.isEmpty ? [endpoint] : client.endpoints; + // Connected address first: it is the one known to work right now. + final ordered = { + endpoint.toString(), + for (final address in addresses) address.toString(), + }.toList(); + final id = serverId; + unawaited( + _guard( + bridge.configure( + serverId: id == null || id.isEmpty ? ordered.first : id, + endpoints: ordered, + cookie: _headersFor(endpoint)['Cookie'] ?? '', + ), + ), + ); + } + + /// A missing or failing platform side must never break the app. + Future _guard(Future call) async { + try { + await call; + } catch (error) { + debugPrint('Notification service: $error'); + } + } + + void dispose() { + unawaited(_states?.cancel()); + } +} diff --git a/app/lib/features/notification_service/notification_service_status.dart b/app/lib/features/notification_service/notification_service_status.dart new file mode 100644 index 00000000..d44d09e7 --- /dev/null +++ b/app/lib/features/notification_service/notification_service_status.dart @@ -0,0 +1,65 @@ +/// The background connection's state, in the service's wire words. +enum DeliveryState { + off('off'), + unconfigured('unconfigured'), + connecting('connecting'), + connected('connected'), + reconnecting('reconnecting'), + waitingForNetwork('waiting_for_network'); + + const DeliveryState(this.wire); + + final String wire; + + static DeliveryState parse(Object? value) => DeliveryState.values.firstWhere( + (state) => state.wire == value, + orElse: () => DeliveryState.off, + ); +} + +/// What the native service reports: the switch, whether a server was handed +/// over, the connection, and the two Android permissions delivery relies on. +class NotificationServiceStatus { + const NotificationServiceStatus({ + required this.enabled, + required this.configured, + required this.state, + required this.notificationsAllowed, + required this.batteryExempt, + }); + + static const unsupported = NotificationServiceStatus( + enabled: false, + configured: false, + state: DeliveryState.off, + notificationsAllowed: false, + batteryExempt: false, + ); + + final bool enabled; + final bool configured; + final DeliveryState state; + final bool notificationsAllowed; + final bool batteryExempt; + + factory NotificationServiceStatus.fromMap(Object? raw) { + final map = raw is Map ? raw : const {}; + return NotificationServiceStatus( + enabled: map['enabled'] == true, + configured: map['configured'] == true, + state: DeliveryState.parse(map['status']), + notificationsAllowed: map['notificationsAllowed'] == true, + batteryExempt: map['batteryExempt'] == true, + ); + } + + /// One short line for Settings. + String get label => switch (state) { + DeliveryState.connected => 'Connected', + DeliveryState.connecting => 'Connecting…', + DeliveryState.reconnecting => 'Reconnecting…', + DeliveryState.waitingForNetwork => 'Waiting for a network', + DeliveryState.unconfigured => 'Starts after the app connects to a server', + DeliveryState.off => enabled ? 'Not running' : 'Off', + }; +} diff --git a/app/lib/features/settings/ntfy_settings_controller.dart b/app/lib/features/settings/ntfy_settings_controller.dart index 7e729a78..1f7d6772 100644 --- a/app/lib/features/settings/ntfy_settings_controller.dart +++ b/app/lib/features/settings/ntfy_settings_controller.dart @@ -27,6 +27,14 @@ const ntfySettings = [ NtfySetting('chat_reply_finished', 'Chat reply finished'), ]; +/// The server's switch for also publishing to ntfy. Optional: older servers +/// do not send it, and Settings hides the switch then. +const ntfyEnabledSetting = NtfySetting( + 'ntfy_enabled', + 'Also send to ntfy', + subtitle: 'For devices that still use the ntfy app', +); + /// Loads and changes the server's ntfy notification settings through the /// shared gateway (`notification_settings` / `set_notification_settings`). /// @@ -112,6 +120,8 @@ class NtfySettingsController extends ChangeNotifier { } result[setting.key] = value; } + final ntfy = raw[ntfyEnabledSetting.key]; + if (ntfy is bool) result[ntfyEnabledSetting.key] = ntfy; return result; } diff --git a/app/lib/features/settings/settings_device_delivery_section.dart b/app/lib/features/settings/settings_device_delivery_section.dart new file mode 100644 index 00000000..200b5195 --- /dev/null +++ b/app/lib/features/settings/settings_device_delivery_section.dart @@ -0,0 +1,148 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../notification_service/notification_service_bridge.dart'; +import '../notification_service/notification_service_controller.dart'; +import 'settings_group.dart'; +import 'settings_row.dart'; +import 'settings_theme.dart'; + +const deviceDeliveryTitle = 'Notifications in Pipelines'; +const deviceDeliverySwitchLabel = 'Receive notifications in Pipelines'; +const deviceDeliveryNote = + 'Pipelines keeps its own connection to the server and shows its ' + 'notifications, so the ntfy app is no longer needed. Android shows a ' + 'quiet "Pipelines is connected" notification while it runs.'; +const deviceDeliveryBatteryLabel = 'Allow background delivery'; +const deviceDeliveryNotificationsLabel = 'Allow notifications'; + +abstract final class DeviceDeliveryKeys { + static const toggle = ValueKey('settings.deviceDelivery.toggle'); + static const status = ValueKey('settings.deviceDelivery.status'); + static const battery = ValueKey('settings.deviceDelivery.battery'); + static const permission = ValueKey( + 'settings.deviceDelivery.permission', + ); + static const error = ValueKey('settings.deviceDelivery.error'); +} + +/// Android background delivery in Settings: the switch, the service's live +/// status, and the two system grants it relies on (notification permission and +/// the battery-optimisation exemption). Absent where there is no service. +class SettingsDeviceDeliverySection extends StatefulWidget { + const SettingsDeviceDeliverySection({ + super.key, + required this.bridge, + this.requestNotificationPermission, + }); + + final NotificationServiceBridge bridge; + final Future Function()? requestNotificationPermission; + + @override + State createState() => + _SettingsDeviceDeliverySectionState(); +} + +class _SettingsDeviceDeliverySectionState + extends State { + late final NotificationServiceController _controller = + NotificationServiceController( + widget.bridge, + requestNotificationPermission: widget.requestNotificationPermission, + ); + + // System prompts (permission, battery) return by resuming the app. + late final AppLifecycleListener _lifecycle = AppLifecycleListener( + onResume: () => unawaited(_controller.refresh()), + ); + + @override + void initState() { + super.initState(); + _lifecycle; + unawaited(_controller.load()); + } + + @override + void dispose() { + _lifecycle.dispose(); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: _controller, + builder: (context, _) => _body(context), + ); + + Widget _body(BuildContext context) { + final cupertino = usesCupertinoControls(context); + final status = _controller.status; + final enabled = status?.enabled ?? false; + final onChanged = status == null || _controller.busy + ? null + : (bool value) => unawaited(_controller.setEnabled(value)); + return SettingsGroup( + title: deviceDeliveryTitle, + footer: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text(deviceDeliveryNote), + if (_controller.error.isNotEmpty) + Text( + _controller.error, + key: DeviceDeliveryKeys.error, + style: TextStyle(color: settingsErrorColor(context)), + ), + ], + ), + children: [ + if (cupertino) + CupertinoListTile( + key: DeviceDeliveryKeys.toggle, + title: const Text(deviceDeliverySwitchLabel), + trailing: CupertinoSwitch(value: enabled, onChanged: onChanged), + onTap: onChanged == null ? null : () => onChanged(!enabled), + ) + else + SwitchListTile( + key: DeviceDeliveryKeys.toggle, + title: const Text(deviceDeliverySwitchLabel), + value: enabled, + onChanged: onChanged, + ), + SettingsRow( + key: DeviceDeliveryKeys.status, + title: const Text('Status'), + subtitle: Text(status == null ? 'Loading…' : status.label), + ), + if (status != null && enabled && !status.notificationsAllowed) + SettingsRow( + key: DeviceDeliveryKeys.permission, + title: const Text(deviceDeliveryNotificationsLabel), + subtitle: const Text('Android is blocking Pipelines notifications'), + action: true, + enabled: !_controller.busy, + onTap: () => unawaited(_controller.allowNotifications()), + ), + if (status != null && enabled) + SettingsRow( + key: DeviceDeliveryKeys.battery, + title: const Text(deviceDeliveryBatteryLabel), + subtitle: Text( + status.batteryExempt + ? 'Allowed: battery optimisation will not pause delivery' + : 'Keeps notifications instant while the phone is idle', + ), + action: !status.batteryExempt, + enabled: !status.batteryExempt && !_controller.busy, + onTap: () => unawaited(_controller.allowBackgroundDelivery()), + ), + ], + ); + } +} diff --git a/app/lib/features/settings/settings_ntfy_section.dart b/app/lib/features/settings/settings_ntfy_section.dart index 1b339b1d..90526546 100644 --- a/app/lib/features/settings/settings_ntfy_section.dart +++ b/app/lib/features/settings/settings_ntfy_section.dart @@ -15,6 +15,12 @@ const ntfySectionTitle = 'Phone notifications'; const ntfySectionSubtitle = 'Sent through ntfy to the devices subscribed to this server.'; +/// The subtitle once the server delivers to the app itself (it reports +/// `ntfy_enabled`). +const ntfySectionAppSubtitle = + 'What the server notifies about: shown by the Pipelines app and, when ' + 'enabled, also sent through ntfy.'; + /// Shown instead of loading while the shared connection is down. const ntfyOfflineText = 'Connect to a server to change these.'; @@ -84,8 +90,12 @@ class _SettingsNtfySectionState extends State { : _controller.loading && values == null ? 'Loading…' : ''; + final hasNtfySwitch = values?.containsKey(ntfyEnabledSetting.key) ?? false; final tiles = [ - for (final setting in ntfySettings) + for (final setting in [ + ...ntfySettings, + if (hasNtfySwitch) ntfyEnabledSetting, + ]) _tile( cupertino, setting, @@ -99,7 +109,7 @@ class _SettingsNtfySectionState extends State { footer: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - const Text(ntfySectionSubtitle), + Text(hasNtfySwitch ? ntfySectionAppSubtitle : ntfySectionSubtitle), if (status.isNotEmpty) Text(status), if (_controller.error.isNotEmpty) Semantics( diff --git a/app/lib/features/settings/settings_screen.dart b/app/lib/features/settings/settings_screen.dart index bbbf1a8a..4911a0ce 100644 --- a/app/lib/features/settings/settings_screen.dart +++ b/app/lib/features/settings/settings_screen.dart @@ -14,6 +14,8 @@ import 'settings_group.dart'; import 'settings_page_body.dart'; import 'settings_notifications_section.dart'; import 'settings_ntfy_section.dart'; +import 'settings_device_delivery_section.dart'; +import '../notification_service/notification_service_bridge.dart'; import 'settings_android_download_section.dart'; import 'settings_schedules_section.dart'; import 'settings_sections.dart'; @@ -48,8 +50,12 @@ class SettingsScreen extends StatefulWidget { this.showSignIn = false, this.showAndroidDownload = false, this.servers, + this.deliveryService, }); + /// Android background delivery; hidden when absent or unsupported. + final NotificationServiceBridge? deliveryService; + final transport.PipelinesClient client; /// Whether to offer the web sign-in (the native app; a browser has its own). @@ -183,6 +189,15 @@ class _SettingsScreenState extends State { ), if (widget.notifications case final notifications?) SettingsNotificationsSection(controller: notifications), + if (widget.deliveryService case final service? when service.supported) + SettingsDeviceDeliverySection( + bridge: service, + requestNotificationPermission: widget.notifications == null + ? null + : () async { + await widget.notifications!.requestPermission(); + }, + ), // The server's ntfy choices, beside the in-app permission. SettingsNtfySection( gateway: widget.client, diff --git a/app/notes/android-background-delivery.md b/app/notes/android-background-delivery.md new file mode 100644 index 00000000..be9898b1 --- /dev/null +++ b/app/notes/android-background-delivery.md @@ -0,0 +1,32 @@ +# Android background delivery (notifications without ntfy) + +## Design +- `android/app/src/main/kotlin/net/awan/pipelines_app/notify/`: native foreground + service (`specialUse`, no Flutter engine), OkHttp websocket with the app's + session cookie, exponential backoff (1 s .. 5 min) rotating through the + server's trusted addresses, default-network callback (reconnect on network + change, "waiting for network" when none), quiet "Pipelines is connected" + notification. It starts at boot or after an app update (`BootReceiver`) and + at app launch. +- Protocol: `subscribe_notifications` with `after` = last received id; + `notifications_subscribed` (`notifications`, plus recently cleared `ids` that + are dismissed), `notification` (`{"notification": N}`), `notifications_cleared`. + Taps (MainActivity) and dismissals (`NotificationDismissReceiver`) queue + `clear_notifications` durably until the socket is connected. +- `DeliveryLedger`: cursor, bounded shown-id dedupe, pending clears; reset when + the server changes. Stable notification id = FNV-1a of the server id. +- Channels per kind (and non-default priority), grouped by kind; importance from + kind because the server sends priority 3. Android groups by `group`, with a summary. +- Dart: `lib/features/notification_service/` (MethodChannel bridge + `pipelines/notification_service`, handoff of the connected server and cookie + on every connect, Settings controller); Settings section + `settings_device_delivery_section.dart`; the server's optional `ntfy_enabled` + appears as "Also send to ntfy". + +## Checks +- Kotlin JVM tests: `cd android && ./gradlew :app:testDebugUnitTest` + (needs a JDK Gradle supports, e.g. Android Studio's JBR via `JAVA_HOME`). +- On-device check against a loopback stand-in server: + `python3 -I tool/fake_notification_server.py --port 18765 --log /tmp/notify.log`, + connect the emulator app to `ws://10.0.2.2:18765/connect`, then + `curl -X POST 'http://127.0.0.1:18765/push?id=run:1:0:failed&click=pipelines://run/1'`. diff --git a/app/test/features/notification_service/fake_notification_service.dart b/app/test/features/notification_service/fake_notification_service.dart new file mode 100644 index 00000000..050be179 --- /dev/null +++ b/app/test/features/notification_service/fake_notification_service.dart @@ -0,0 +1,88 @@ +import 'dart:async'; + +import 'package:pipelines_app/features/notification_service/notification_service_bridge.dart'; + +/// A scripted background service: records calls and reports [current]. +class FakeNotificationService implements NotificationServiceBridge { + FakeNotificationService({NotificationServiceStatus? status}) + : current = + status ?? + const NotificationServiceStatus( + enabled: true, + configured: true, + state: DeliveryState.connected, + notificationsAllowed: true, + batteryExempt: false, + ); + + NotificationServiceStatus current; + final calls = <(String, Map)>[]; + final _changes = StreamController.broadcast(); + bool batteryGranted = true; + + void push(NotificationServiceStatus status) { + current = status; + _changes.add(status); + } + + NotificationServiceStatus copy({ + bool? enabled, + DeliveryState? state, + bool? notificationsAllowed, + bool? batteryExempt, + }) => NotificationServiceStatus( + enabled: enabled ?? current.enabled, + configured: current.configured, + state: state ?? current.state, + notificationsAllowed: notificationsAllowed ?? current.notificationsAllowed, + batteryExempt: batteryExempt ?? current.batteryExempt, + ); + + @override + bool get supported => true; + + @override + Stream get changes => _changes.stream; + + @override + Future status() async { + calls.add(('status', const {})); + return current; + } + + @override + Future start() async { + calls.add(('start', const {})); + return current; + } + + @override + Future configure({ + required String serverId, + required List endpoints, + required String cookie, + }) async { + calls.add(( + 'configure', + {'serverId': serverId, 'endpoints': endpoints, 'cookie': cookie}, + )); + return current; + } + + @override + Future setEnabled(bool enabled) async { + calls.add(('setEnabled', {'enabled': enabled})); + current = copy( + enabled: enabled, + state: enabled ? DeliveryState.connecting : DeliveryState.off, + ); + return current; + } + + @override + Future requestBatteryExemption() async { + calls.add(('requestBatteryExemption', const {})); + if (batteryGranted) current = copy(batteryExempt: true); + return true; + } +} diff --git a/app/test/features/notification_service/notification_service_bridge_test.dart b/app/test/features/notification_service/notification_service_bridge_test.dart new file mode 100644 index 00000000..da9fe55f --- /dev/null +++ b/app/test/features/notification_service/notification_service_bridge_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/notification_service/notification_service_bridge.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('test/notification_service'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + late List calls; + + Map reply({String status = 'connected'}) => { + 'enabled': true, + 'configured': true, + 'status': status, + 'notificationsAllowed': true, + 'batteryExempt': false, + }; + + setUp(() { + calls = []; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return call.method == 'requestBatteryExemption' ? true : reply(); + }); + }); + + tearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + test('the production channel name matches the Kotlin side', () { + expect( + MethodChannelNotificationServiceBridge.channelName, + 'pipelines/notification_service', + ); + }); + + test('configure hands over the server, addresses and cookie', () async { + final bridge = MethodChannelNotificationServiceBridge(channel); + final status = await bridge.configure( + serverId: 'home', + endpoints: ['wss://a:8443/connect', 'ws://b:8081/connect'], + cookie: 'pipelines_session=abc', + ); + expect(calls.single.method, 'configure'); + expect(calls.single.arguments, { + 'serverId': 'home', + 'endpoints': ['wss://a:8443/connect', 'ws://b:8081/connect'], + 'cookie': 'pipelines_session=abc', + }); + expect(status.state, DeliveryState.connected); + expect(status.enabled, isTrue); + expect(status.batteryExempt, isFalse); + }); + + test('setEnabled, start, status and the battery prompt', () async { + final bridge = MethodChannelNotificationServiceBridge(channel); + await bridge.setEnabled(false); + await bridge.start(); + await bridge.status(); + expect(await bridge.requestBatteryExemption(), isTrue); + expect(calls.map((call) => call.method), [ + 'setEnabled', + 'start', + 'status', + 'requestBatteryExemption', + ]); + expect(calls.first.arguments, {'enabled': false}); + }); + + test('statusChanged from the service reaches listeners', () async { + final bridge = MethodChannelNotificationServiceBridge(channel); + final next = bridge.changes.first; + await messenger.handlePlatformMessage( + channel.name, + channel.codec.encodeMethodCall( + MethodCall('statusChanged', reply(status: 'waiting_for_network')), + ), + (_) {}, + ); + expect((await next).state, DeliveryState.waitingForNetwork); + }); + + test('unknown or malformed status falls back to off', () { + expect( + NotificationServiceStatus.fromMap({'status': 'weird'}).state, + DeliveryState.off, + ); + expect(NotificationServiceStatus.fromMap(null).enabled, isFalse); + }); + + test('the host test platform has no service', () async { + final bridge = createNotificationServiceBridge(); + expect(bridge.supported, isFalse); + expect((await bridge.status()).state, DeliveryState.off); + }); +} diff --git a/app/test/features/notification_service/notification_service_handoff_test.dart b/app/test/features/notification_service/notification_service_handoff_test.dart new file mode 100644 index 00000000..9c949c91 --- /dev/null +++ b/app/test/features/notification_service/notification_service_handoff_test.dart @@ -0,0 +1,82 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/notification_service/notification_service_bridge.dart'; +import 'package:pipelines_app/features/notification_service/notification_service_handoff.dart'; + +import '../settings/fake_channel.dart'; +import 'fake_notification_service.dart'; + +void main() { + test('each connection hands the proven server to the service', () async { + final channels = []; + final client = PipelinesClient( + channelFactory: (uri) { + final channel = FakeChannel(uri)..markReady(); + channels.add(channel); + return channel; + }, + ); + final service = FakeNotificationService(); + final handoff = NotificationServiceHandoff( + bridge: service, + client: client, + serverId: 'home', + headersFor: (uri) => uri.host == 'b' + ? {'Cookie': 'pipelines_session=abc'} + : const {}, + ); + // The app starts the service at launch when it is enabled. + expect(service.calls.single.$1, 'start'); + + await client.connectAny([ + Uri.parse('wss://b:8443/connect'), + Uri.parse('ws://a:8081/connect'), + ]); + await pumpEventQueue(); + final configure = service.calls.last; + expect(configure.$1, 'configure'); + expect(configure.$2, { + 'serverId': 'home', + 'endpoints': ['wss://b:8443/connect', 'ws://a:8081/connect'], + 'cookie': 'pipelines_session=abc', + }); + + handoff.dispose(); + await client.dispose(); + }); + + test('without a server id the connected address names the server', () async { + final client = PipelinesClient( + channelFactory: (uri) => FakeChannel(uri)..markReady(), + ); + final service = FakeNotificationService(); + final handoff = NotificationServiceHandoff( + bridge: service, + client: client, + serverId: null, + headersFor: (_) => const {}, + ); + await client.connect(Uri.parse('ws://a:8081/connect')); + await pumpEventQueue(); + expect(service.calls.last.$2['serverId'], 'ws://a:8081/connect'); + expect(service.calls.last.$2['cookie'], ''); + handoff.dispose(); + await client.dispose(); + }); + + test('an unsupported platform is never called', () async { + final client = PipelinesClient( + channelFactory: (uri) => FakeChannel(uri)..markReady(), + ); + final handoff = NotificationServiceHandoff( + bridge: const UnsupportedNotificationServiceBridge(), + client: client, + serverId: 'home', + headersFor: (_) => throw StateError('must not read credentials'), + ); + await client.connect(Uri.parse('ws://a:8081/connect')); + await pumpEventQueue(); + handoff.dispose(); + await client.dispose(); + }); +} diff --git a/app/test/features/settings/settings_device_delivery_section_test.dart b/app/test/features/settings/settings_device_delivery_section_test.dart new file mode 100644 index 00000000..1e22ade5 --- /dev/null +++ b/app/test/features/settings/settings_device_delivery_section_test.dart @@ -0,0 +1,154 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/notification_service/notification_service_bridge.dart'; +import 'package:pipelines_app/features/settings/settings_device_delivery_section.dart'; + +import '../notification_service/fake_notification_service.dart'; + +Widget _host( + NotificationServiceBridge bridge, { + required bool cupertino, + Future Function()? requestPermission, +}) => MaterialApp( + theme: ThemeData( + platform: cupertino ? TargetPlatform.iOS : TargetPlatform.android, + ), + home: Scaffold( + body: SingleChildScrollView( + child: SettingsDeviceDeliverySection( + bridge: bridge, + requestNotificationPermission: requestPermission, + ), + ), + ), +); + +bool _switchValue(WidgetTester tester, {required bool cupertino}) { + final tile = find.byKey(DeviceDeliveryKeys.toggle); + if (cupertino) { + return tester + .widget( + find.descendant(of: tile, matching: find.byType(CupertinoSwitch)), + ) + .value; + } + return tester.widget(tile).value; +} + +void main() { + for (final cupertino in [false, true]) { + final style = cupertino ? 'Cupertino' : 'Material'; + + testWidgets('$style shows the switch, status and ntfy note', ( + tester, + ) async { + final service = FakeNotificationService(); + await tester.pumpWidget(_host(service, cupertino: cupertino)); + await tester.pumpAndSettle(); + expect(find.text(deviceDeliverySwitchLabel), findsOneWidget); + expect(_switchValue(tester, cupertino: cupertino), isTrue); + expect(find.text('Connected'), findsOneWidget); + expect(find.text(deviceDeliveryNote), findsOneWidget); + expect(find.text(deviceDeliveryBatteryLabel), findsOneWidget); + expect(find.byKey(DeviceDeliveryKeys.permission), findsNothing); + }); + + testWidgets('$style switching off stops delivery', (tester) async { + final service = FakeNotificationService(); + await tester.pumpWidget(_host(service, cupertino: cupertino)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(DeviceDeliveryKeys.toggle)); + await tester.pumpAndSettle(); + expect(service.calls.last.$1, 'setEnabled'); + expect(service.calls.last.$2, {'enabled': false}); + expect(_switchValue(tester, cupertino: cupertino), isFalse); + expect(find.text('Off'), findsOneWidget); + // The grants only matter while delivery is on. + expect(find.text(deviceDeliveryBatteryLabel), findsNothing); + }); + } + + testWidgets('live status pushed by the service is shown', (tester) async { + final service = FakeNotificationService(); + await tester.pumpWidget(_host(service, cupertino: false)); + await tester.pumpAndSettle(); + service.push(service.copy(state: DeliveryState.reconnecting)); + await tester.pumpAndSettle(); + expect(find.text('Reconnecting…'), findsOneWidget); + }); + + testWidgets('allow background delivery asks for the exemption', ( + tester, + ) async { + final service = FakeNotificationService(); + await tester.pumpWidget(_host(service, cupertino: false)); + await tester.pumpAndSettle(); + await tester.tap(find.text(deviceDeliveryBatteryLabel)); + await tester.pumpAndSettle(); + expect( + service.calls.map((call) => call.$1), + contains('requestBatteryExemption'), + ); + expect( + find.text('Allowed: battery optimisation will not pause delivery'), + findsOneWidget, + ); + }); + + testWidgets('blocked notifications offer the permission request', ( + tester, + ) async { + var asked = 0; + final service = FakeNotificationService(); + service.current = service.copy(notificationsAllowed: false); + await tester.pumpWidget( + _host( + service, + cupertino: false, + requestPermission: () async { + asked++; + service.current = service.copy(notificationsAllowed: true); + }, + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(DeviceDeliveryKeys.permission)); + await tester.pumpAndSettle(); + expect(asked, 1); + expect(find.byKey(DeviceDeliveryKeys.permission), findsNothing); + }); + + testWidgets('switching on asks for notifications when blocked', ( + tester, + ) async { + var asked = 0; + final service = FakeNotificationService(); + service.current = service.copy( + enabled: false, + state: DeliveryState.off, + notificationsAllowed: false, + ); + await tester.pumpWidget( + _host(service, cupertino: false, requestPermission: () async => asked++), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(DeviceDeliveryKeys.toggle)); + await tester.pumpAndSettle(); + expect(asked, 1); + expect(service.calls.last.$1, 'setEnabled'); + expect(service.calls.last.$2, {'enabled': true}); + }); + + testWidgets('a failing platform is reported, not hidden', (tester) async { + await tester.pumpWidget(_host(_FailingService(), cupertino: false)); + await tester.pumpAndSettle(); + expect(find.byKey(DeviceDeliveryKeys.error), findsOneWidget); + }); +} + +class _FailingService extends FakeNotificationService { + @override + Future status() async => + throw StateError('no service'); +} diff --git a/app/test/features/settings/settings_ntfy_section_test.dart b/app/test/features/settings/settings_ntfy_section_test.dart index 8c7d8014..294a692f 100644 --- a/app/test/features/settings/settings_ntfy_section_test.dart +++ b/app/test/features/settings/settings_ntfy_section_test.dart @@ -200,4 +200,50 @@ void main() { isFalse, ); }); + + group('ntfy_enabled', () { + JsonMap withNtfy(bool ntfy) => { + 'type': 'notification_settings', + 'notification_settings': { + ...(_reply(true, true, false)['notification_settings'] as Map), + 'ntfy_enabled': ntfy, + }, + }; + + testWidgets('hidden when the server does not send it', (tester) async { + final gateway = _Gateway((_, _) => _reply(true, true, false)); + await tester.pumpWidget(_host(gateway, cupertino: false)); + await tester.pumpAndSettle(); + expect(find.byKey(ntfySettingKey('ntfy_enabled')), findsNothing); + expect(find.text(ntfySectionSubtitle), findsOneWidget); + }); + + for (final cupertino in [false, true]) { + testWidgets( + '${cupertino ? 'Cupertino' : 'Material'} shows and writes it', + (tester) async { + final gateway = _Gateway( + (type, _) => withNtfy(type == 'set_notification_settings'), + ); + await tester.pumpWidget(_host(gateway, cupertino: cupertino)); + await tester.pumpAndSettle(); + expect(find.text('Also send to ntfy'), findsOneWidget); + expect(find.text(ntfySectionAppSubtitle), findsOneWidget); + expect( + _checked(tester, 'ntfy_enabled', cupertino: cupertino), + isFalse, + ); + await tester.tap(find.byKey(ntfySettingKey('ntfy_enabled'))); + await tester.pumpAndSettle(); + expect(gateway.calls.last.$2, { + 'notification_settings': {'ntfy_enabled': true}, + }); + expect( + _checked(tester, 'ntfy_enabled', cupertino: cupertino), + isTrue, + ); + }, + ); + } + }); } diff --git a/app/tool/fake_notification_server.py b/app/tool/fake_notification_server.py new file mode 100644 index 00000000..b39b4773 --- /dev/null +++ b/app/tool/fake_notification_server.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""A loopback stand-in for the Pipelines server's notification socket. + +For checking Android background delivery on the managed emulator without the +real server: the emulator reaches it at ws://10.0.2.2:/connect. + + python3 -I tool/fake_notification_server.py --port 0 --log /tmp/notify.log + +* GET /login answers 302, so the app treats the device as signed in. +* /connect speaks the notification protocol: `subscribe_notifications` + (replayed with `notifications_subscribed`), `clear_notifications` (logged and + echoed to every socket as `notifications_cleared`). Any other request gets an + `error` reply so the app does not wait for its timeout. +* POST /push?id=&kind=&title=&message=&click=&priority=&group= pushes + `{"type":"notification","notification":{...}}`. +* POST /clear?id=a,b pushes `notifications_cleared` (another device cleared). + +Every frame received is appended to --log as one JSON line. Standard library +only; not a general websocket server (text frames, no fragmentation). +""" + +import argparse +import base64 +import datetime +import hashlib +import json +import socketserver +import struct +import threading +import urllib.parse +from http.server import BaseHTTPRequestHandler + +GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" +clients = [] +store = [] # active notifications, oldest first +cleared = [] # recently cleared ids, sent with notifications_subscribed +lock = threading.Lock() +log_path = None + + +def log(entry): + line = json.dumps(entry) + print(line, flush=True) + if log_path: + with open(log_path, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def frame(text): + data = text.encode() + header = bytearray([0x81]) + if len(data) < 126: + header.append(len(data)) + elif len(data) < 65536: + header += bytes([126]) + struct.pack(">H", len(data)) + else: + header += bytes([127]) + struct.pack(">Q", len(data)) + return bytes(header) + data + + +def broadcast(message): + payload = frame(json.dumps(message)) + with lock: + for wfile in list(clients): + try: + wfile.write(payload) + wfile.flush() + except OSError: + clients.remove(wfile) + + +def read_frame(rfile): + head = rfile.read(2) + if len(head) < 2: + return None, None + opcode = head[0] & 0x0F + length = head[1] & 0x7F + if length == 126: + length = struct.unpack(">H", rfile.read(2))[0] + elif length == 127: + length = struct.unpack(">Q", rfile.read(8))[0] + mask = rfile.read(4) if head[1] & 0x80 else b"\0\0\0\0" + data = bytes(b ^ mask[i % 4] for i, b in enumerate(rfile.read(length))) + return opcode, data + + +class Handler(BaseHTTPRequestHandler): + # Clients reject an "HTTP/1.0 101" upgrade. + protocol_version = "HTTP/1.1" + def log_message(self, *args): + pass + + def do_GET(self): + path = urllib.parse.urlparse(self.path).path + if path == "/login": + self.send_response(302) + self.send_header("Location", "/") + self.send_header("Content-Length", "0") + self.end_headers() + elif path == "/connect" and self.headers.get("Upgrade", "").lower() == "websocket": + self.websocket() + else: + self.send_response(404) + self.send_header("Content-Length", "0") + self.end_headers() + + def do_POST(self): + url = urllib.parse.urlparse(self.path) + query = {k: v[-1] for k, v in urllib.parse.parse_qs(url.query).items()} + if url.path == "/push": + notification = { + "id": query.get("id", "n-%d" % len(store)), + "kind": query.get("kind", "run_failed"), + "title": query.get("title", "Run failed"), + "message": query.get("message", "A step failed"), + "click": query.get("click", "pipelines://run/1"), + "priority": int(query.get("priority", "3")), + "tags": [], + "created_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "group": query.get("group", ""), + } + store.append(notification) + broadcast({"type": "notification", "notification": notification}) + elif url.path == "/clear": + ids = [i for i in query.get("id", "").split(",") if i] + store[:] = [n for n in store if n["id"] not in ids] + cleared.extend(ids) + broadcast({"type": "notifications_cleared", "ids": ids}) + else: + self.send_response(404) + self.send_header("Content-Length", "0") + self.end_headers() + return + self.send_response(204) + self.send_header("Content-Length", "0") + self.end_headers() + + def websocket(self): + key = self.headers["Sec-WebSocket-Key"] + accept = base64.b64encode(hashlib.sha1((key + GUID).encode()).digest()).decode() + self.send_response(101) + self.send_header("Upgrade", "websocket") + self.send_header("Connection", "Upgrade") + self.send_header("Sec-WebSocket-Accept", accept) + self.end_headers() + self.wfile.flush() + log({"event": "connect", "cookie": self.headers.get("Cookie", ""), + "agent": self.headers.get("User-Agent", "")}) + with lock: + clients.append(self.wfile) + try: + while True: + opcode, data = read_frame(self.rfile) + if opcode is None or opcode == 0x8: + break + if opcode == 0x9: # ping -> pong + with lock: + self.wfile.write(bytes([0x8A, len(data)]) + data) + self.wfile.flush() + continue + if opcode != 0x1: + continue + self.on_message(json.loads(data)) + finally: + with lock: + if self.wfile in clients: + clients.remove(self.wfile) + log({"event": "disconnect"}) + + def send(self, message): + with lock: + self.wfile.write(frame(json.dumps(message))) + self.wfile.flush() + + def on_message(self, message): + log({"event": "received", "message": message}) + kind, request = message.get("type"), message.get("id") + if kind == "subscribe_notifications": + after = message.get("after") + ids = [n["id"] for n in store] + replay = store[ids.index(after) + 1:] if after in ids else list(store) + self.send({"type": "notifications_subscribed", "id": request, + "notifications": replay, "ids": cleared[-50:]}) + elif kind == "clear_notifications": + ids = message.get("ids", []) + store[:] = [n for n in store if n["id"] not in ids] + cleared.extend(ids) + self.send({"type": "notifications_cleared", "id": request, "ids": ids}) + broadcast({"type": "notifications_cleared", "ids": ids}) + elif request: + self.send({"type": "error", "id": request, "error": "fake server: %s" % kind}) + + +class Server(socketserver.ThreadingMixIn, socketserver.TCPServer): + allow_reuse_address = True + daemon_threads = True + + +def main(): + global log_path + parser = argparse.ArgumentParser() + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=0) + parser.add_argument("--log") + args = parser.parse_args() + log_path = args.log + with Server((args.host, args.port), Handler) as server: + log({"event": "listening", "port": server.server_address[1]}) + server.serve_forever() + + +if __name__ == "__main__": + main()