Deliver server notifications from the Android app itself

A native foreground service keeps an authenticated websocket to the
connected server (handed over by the app on every connect), subscribes with
a replay cursor, shows each notification with kind-based channels and
grouping, opens pipelines:// links on tap, and clears taps, dismissals and
cross-device clears. It starts at boot and app launch, backs off and follows
network changes. Settings gains the delivery switch, status, notification
and battery-exemption actions, and the server's optional ntfy_enabled
toggle.
This commit is contained in:
2026-11-01 02:21:22 +00:00
parent 6c7c32078c
commit 826e420423
33 changed files with 2589 additions and 3 deletions
+6
View File
@@ -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")
}
@@ -4,6 +4,14 @@
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<!-- The client reaches the Pipelines server over the shared socket. -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Background delivery (notify/NotificationService): a foreground
service keeps the notification socket open, starts at boot, follows
network changes and may ask to be exempt from battery optimisation. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<!-- Explicit ws:// LAN/VPN profiles are supported; no automatic TLS
downgrade or discovery is performed. Settings warns about cleartext. -->
<application
@@ -45,6 +53,28 @@
<data android:scheme="pipelines" android:host="chat" />
</intent-filter>
</activity>
<!-- Instant delivery of server notifications without the ntfy app.
specialUse: a persistent push connection to a self-hosted server
has no dedicated type, and dataSync is time-limited on Android 15. -->
<service
android:name=".notify.NotificationService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Persistent connection to the user's self-hosted Pipelines server for instant notifications"/>
</service>
<receiver
android:name=".notify.NotificationDismissReceiver"
android:exported="false"/>
<receiver
android:name=".notify.BootReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
</intent-filter>
</receiver>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
@@ -1,5 +1,44 @@
package net.awan.pipelines_app
import android.content.Intent
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import net.awan.pipelines_app.notify.NotificationDismissReceiver
import net.awan.pipelines_app.notify.NotificationPresenter
import net.awan.pipelines_app.notify.NotificationServiceChannel
class MainActivity : FlutterActivity()
class MainActivity : FlutterActivity() {
private var notificationChannel: NotificationServiceChannel? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
notificationChannel = NotificationServiceChannel(this, flutterEngine.dartExecutor.binaryMessenger)
}
override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {
notificationChannel?.dispose()
notificationChannel = null
super.cleanUpFlutterEngine(flutterEngine)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) clearOpenedNotification(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
clearOpenedNotification(intent)
}
/**
* A tapped server notification is opened here (Flutter routes its
* pipelines:// link) and cleared on the server, so other devices drop it.
*/
private fun clearOpenedNotification(intent: Intent?) {
val id = intent?.getStringExtra(NotificationPresenter.EXTRA_NOTIFICATION_ID) ?: return
intent.removeExtra(NotificationPresenter.EXTRA_NOTIFICATION_ID)
NotificationDismissReceiver.queueClear(this, id)
}
}
@@ -0,0 +1,17 @@
package net.awan.pipelines_app.notify
/** Exponential reconnect delay: base, 2x, 4x … capped at [maxMillis]. */
class Backoff(private val baseMillis: Long = 1_000, private val maxMillis: Long = 5 * 60_000) {
var attempt = 0
private set
fun next(): Long {
val shift = attempt.coerceAtMost(20)
attempt++
return (baseMillis shl shift).coerceAtMost(maxMillis)
}
fun reset() {
attempt = 0
}
}
@@ -0,0 +1,16 @@
package net.awan.pipelines_app.notify
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
/** Restarts background delivery after a reboot or an app update. */
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_BOOT_COMPLETED,
Intent.ACTION_MY_PACKAGE_REPLACED,
-> NotificationService.start(context)
}
}
}
@@ -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<ServerNotification>): List<ServerNotification> {
if (batch.isEmpty()) return emptyList()
val shown = shownIds().toMutableList()
val fresh = mutableListOf<ServerNotification>()
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<String> = decode(store.getString(SHOWN))
/** Queues ids the user dismissed or opened, until a socket can send them. */
fun queueClear(ids: Collection<String>) {
if (ids.isEmpty()) return
val pending = LinkedHashSet(pendingClears())
pending.addAll(ids.filter { it.isNotEmpty() })
store.putString(PENDING, encode(pending.toList()))
}
fun pendingClears(): List<String> = decode(store.getString(PENDING))
/** Drops [ids] from the queue once they were written to an open socket. */
fun clearsSent(ids: Collection<String>) {
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<String>) = ids.joinToString("\n")
private fun decode(raw: String?): List<String> =
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
}
}
@@ -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)
}
}
}
}
@@ -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<String>) {
val groups = mutableSetOf<String>()
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/<id> and pipelines://chat/<id> 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
}
}
}
@@ -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<String>,
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<ServerNotification>,
val clearedIds: List<String> = emptyList(),
) : NotificationFrame
data class Pushed(val notification: ServerNotification) : NotificationFrame
data class Cleared(val ids: List<String>) : 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>): 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<ServerNotification> {
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<String> {
if (array == null) return emptyList()
return (0 until array.length()).mapNotNull { index ->
array.optString(index, "").trim().takeIf { it.isNotEmpty() }
}
}
}
@@ -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))
}
}
}
@@ -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<String>("serverId") ?: ""
val endpoints = call.argument<List<String>>("endpoints") ?: emptyList()
val cookie = call.argument<String>("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<Boolean>("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<String, Any> {
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"
}
}
@@ -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<String>
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<String>, 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"
}
}
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Status-bar icon for background delivery: a small pipeline graph (two
stages feeding a third). Monochrome, as Android requires. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M3,3h6v6H3z M3,15h6v6H3z M15,9h6v6h-6z M9,5.25h3.75v6h2.25v1.5h-2.25v6H9v-1.5h2.25V6.75H9z" />
</vector>
@@ -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<String, String>()
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())
}
}
@@ -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))
}
}