Group Android notifications by chat
Persist bounded conversation history and rebuild MessagingStyle chat notifications across service restarts. Keep run alerts grouped separately, update summaries when chats are cleared, and retain reliable background delivery behavior and client integration changes.
This commit is contained in:
@@ -12,6 +12,11 @@
|
||||
<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"/>
|
||||
<!-- Reconnects are alarms that fire during Doze; exact timing needs this
|
||||
grant (Android 12+, user-revocable), otherwise idle-tolerant alarms.
|
||||
The short connect hold uses a partial wake lock. -->
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
||||
<!-- "Find servers on this network" browses _pipelines._tcp with NSD;
|
||||
Wi-Fi drops multicast without a multicast lock, held only while a
|
||||
scan runs (lib/features/onboarding/discovery/). -->
|
||||
@@ -69,6 +74,11 @@
|
||||
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>
|
||||
<!-- Periodic check that restarts the notification service if it is down. -->
|
||||
<service
|
||||
android:name=".notify.NotificationWatchdog"
|
||||
android:exported="false"
|
||||
android:permission="android.permission.BIND_JOB_SERVICE"/>
|
||||
<receiver
|
||||
android:name=".notify.NotificationDismissReceiver"
|
||||
android:exported="false"/>
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import android.content.Context
|
||||
import android.os.PowerManager
|
||||
|
||||
/**
|
||||
* A short partial wake lock held while the service opens its socket, so the
|
||||
* CPU stays awake through the handshake. The timeout bounds it if no answer
|
||||
* comes; [release] runs as soon as the socket opens or fails.
|
||||
*/
|
||||
class ConnectWakeLock(context: Context) {
|
||||
private val lock = context.getSystemService(PowerManager::class.java)
|
||||
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pipelines:connect")
|
||||
.apply { setReferenceCounted(false) }
|
||||
|
||||
fun hold() {
|
||||
lock.acquire(HOLD_MILLIS)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (lock.isHeld) lock.release()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val HOLD_MILLIS = 30_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
/** One entry of the connection log: when, what happened, and the error or HTTP code. */
|
||||
data class ConnectionEvent(
|
||||
val timeMillis: Long,
|
||||
val event: String,
|
||||
val error: String?,
|
||||
val code: Int?,
|
||||
)
|
||||
|
||||
/**
|
||||
* The last [CAPACITY] connection events, kept in the service's preferences so
|
||||
* Settings can show why delivery stalled. Newest first. Error text is trimmed;
|
||||
* the session cookie never reaches the log.
|
||||
*/
|
||||
class ConnectionLog(
|
||||
private val store: LedgerStore,
|
||||
private val clock: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
/** Read-modify-write: the main thread (task removal) and the service thread both log. */
|
||||
@Synchronized
|
||||
fun record(event: String, error: String? = null, code: Int? = null) {
|
||||
val entry = ConnectionEvent(clock(), event, error?.take(MAX_ERROR_LENGTH), code)
|
||||
store.putString(KEY, encode((listOf(entry) + entries()).take(CAPACITY)))
|
||||
}
|
||||
|
||||
fun entries(): List<ConnectionEvent> = decode(store.getString(KEY))
|
||||
|
||||
companion object {
|
||||
const val CAPACITY = 50
|
||||
const val KEY = "connection.log"
|
||||
private const val MAX_ERROR_LENGTH = 200
|
||||
|
||||
private fun encode(events: List<ConnectionEvent>): String {
|
||||
val array = JSONArray()
|
||||
for (event in events) {
|
||||
array.put(
|
||||
JSONObject()
|
||||
.put("t", event.timeMillis)
|
||||
.put("e", event.event)
|
||||
.apply {
|
||||
event.error?.let { put("x", it) }
|
||||
event.code?.let { put("c", it) }
|
||||
},
|
||||
)
|
||||
}
|
||||
return array.toString()
|
||||
}
|
||||
|
||||
/** A corrupt log reads as empty rather than breaking Settings. */
|
||||
private fun decode(raw: String?): List<ConnectionEvent> {
|
||||
if (raw.isNullOrEmpty()) return emptyList()
|
||||
return try {
|
||||
val array = JSONArray(raw)
|
||||
(0 until array.length()).map { index ->
|
||||
val item = array.getJSONObject(index)
|
||||
ConnectionEvent(
|
||||
timeMillis = item.getLong("t"),
|
||||
event = item.getString("e"),
|
||||
error = if (item.has("x")) item.getString("x") else null,
|
||||
code = if (item.has("c")) item.getInt("c") else null,
|
||||
)
|
||||
}
|
||||
} catch (_: JSONException) {
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
-7
@@ -32,21 +32,16 @@ class NotificationPresenter(private val context: Context) {
|
||||
DeliveryStatus.CONNECTED -> "Pipelines is connected"
|
||||
DeliveryStatus.WAITING_FOR_NETWORK -> "Pipelines is waiting for a network"
|
||||
DeliveryStatus.CONNECTING -> "Pipelines is connecting…"
|
||||
DeliveryStatus.SIGN_IN_REQUIRED -> "Pipelines needs you to sign in"
|
||||
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)
|
||||
.setContentIntent(openApp())
|
||||
.setCategory(NotificationCompat.CATEGORY_SERVICE)
|
||||
.build()
|
||||
}
|
||||
@@ -55,6 +50,30 @@ class NotificationPresenter(private val context: Context) {
|
||||
manager.notify(CONNECTION_ID, connectionNotification(status))
|
||||
}
|
||||
|
||||
/** Posted when the server refuses the session; cleared once a connection opens. */
|
||||
fun signInRequired() {
|
||||
ensureChannel(ACCOUNT_CHANNEL, "Sign-in", NotificationManager.IMPORTANCE_DEFAULT, null)
|
||||
val notification = builder(ACCOUNT_CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_stat_pipelines)
|
||||
.setContentTitle("Sign in to Pipelines again to keep notifications")
|
||||
.setContentText("Notifications are paused until you sign in.")
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(openApp())
|
||||
.build()
|
||||
manager.notify(SIGN_IN_ID, notification)
|
||||
}
|
||||
|
||||
fun clearSignIn() {
|
||||
manager.cancel(SIGN_IN_ID)
|
||||
}
|
||||
|
||||
private fun openApp(): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
0,
|
||||
Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
/** A notification without a group is posted on its own; otherwise it joins its thread. */
|
||||
fun show(notification: ServerNotification) {
|
||||
if (notification.group.isEmpty()) return showAlone(notification)
|
||||
@@ -249,6 +268,9 @@ class NotificationPresenter(private val context: Context) {
|
||||
companion object {
|
||||
const val CONNECTION_ID = 1
|
||||
const val CONNECTION_CHANNEL = "pipelines.connection"
|
||||
/** The "sign in again" notice; ids up to RESERVED_IDS are the service's own. */
|
||||
const val SIGN_IN_ID = 2
|
||||
const val ACCOUNT_CHANNEL = "pipelines.account"
|
||||
/** Holds the server id(s) a tap or dismissal clears, newline-separated. */
|
||||
const val EXTRA_NOTIFICATION_ID = "net.awan.pipelines.notification_id"
|
||||
/** Lines of a thread shown in its conversation; the unread count still counts all. */
|
||||
|
||||
+104
-10
@@ -24,6 +24,10 @@ import java.util.concurrent.TimeUnit
|
||||
* engine runs here. It subscribes with the replay cursor, posts each pushed
|
||||
* notification, mirrors cross-device clears and sends the user's own clears.
|
||||
*
|
||||
* Reconnects are alarms (ReconnectAlarms), so they fire during Doze; a
|
||||
* periodic NotificationWatchdog restarts the service if it is down. A refused
|
||||
* session (HTTP 401/403) stops the retry loop until a fresh cookie arrives.
|
||||
*
|
||||
* All state is confined to [handler]'s thread; OkHttp and connectivity
|
||||
* callbacks post onto it.
|
||||
*/
|
||||
@@ -31,6 +35,8 @@ class NotificationService : Service() {
|
||||
private lateinit var settings: ServiceSettings
|
||||
private lateinit var ledger: DeliveryLedger
|
||||
private lateinit var presenter: NotificationPresenter
|
||||
private lateinit var log: ConnectionLog
|
||||
private lateinit var wakeLock: ConnectWakeLock
|
||||
private lateinit var thread: HandlerThread
|
||||
private lateinit var handler: Handler
|
||||
private val client = OkHttpClient.Builder()
|
||||
@@ -48,7 +54,8 @@ class NotificationService : Service() {
|
||||
private var networkAvailable = true
|
||||
private var currentNetwork: Network? = null
|
||||
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
||||
private val reconnect = Runnable { connect() }
|
||||
/** A reconnect alarm is pending for the socket that is down. */
|
||||
private var reconnectPending = false
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
@@ -57,6 +64,8 @@ class NotificationService : Service() {
|
||||
settings = ServiceSettings(this)
|
||||
ledger = DeliveryLedger(settings)
|
||||
presenter = NotificationPresenter(this)
|
||||
log = ConnectionLog(settings)
|
||||
wakeLock = ConnectWakeLock(this)
|
||||
thread = HandlerThread("pipelines-notifications").also { it.start() }
|
||||
handler = Handler(thread.looper)
|
||||
goForeground(DeliveryStatus.CONNECTING)
|
||||
@@ -66,16 +75,36 @@ class NotificationService : Service() {
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
val action = intent?.action
|
||||
// Alarms and the watchdog may start the service from the background;
|
||||
// it must be foreground promptly, so do that before queuing the work.
|
||||
goForeground(settings.status.let { if (it == DeliveryStatus.OFF) DeliveryStatus.CONNECTING else it })
|
||||
handler.post {
|
||||
when {
|
||||
!settings.enabled || !settings.configured -> stopEverything()
|
||||
action == ACTION_FLUSH -> flushClears()
|
||||
action == ACTION_WATCHDOG -> if (isDown()) {
|
||||
log.record("watchdog_restart")
|
||||
restart()
|
||||
}
|
||||
action == ACTION_RECONNECT -> if (socket == null && settings.status != DeliveryStatus.SIGN_IN_REQUIRED) connect()
|
||||
action == ACTION_RESTART || socket == null -> restart()
|
||||
}
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
/**
|
||||
* The app was swiped away. The foreground service keeps running, so this
|
||||
* only queues a watchdog check shortly after, in case the process is lost.
|
||||
*/
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
log.record("task_removed")
|
||||
if (settings.enabled && settings.configured) {
|
||||
ReconnectAlarms.schedule(this, TASK_REMOVED_CHECK_MILLIS, ACTION_WATCHDOG)
|
||||
}
|
||||
super.onTaskRemoved(rootIntent)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
running = null
|
||||
networkCallback?.let {
|
||||
@@ -87,6 +116,7 @@ class NotificationService : Service() {
|
||||
socket?.close(1000, "service stopped")
|
||||
socket = null
|
||||
}
|
||||
wakeLock.release()
|
||||
thread.quitSafely()
|
||||
if (settings.status != DeliveryStatus.UNCONFIGURED) setStatus(DeliveryStatus.OFF, notify = false)
|
||||
super.onDestroy()
|
||||
@@ -109,22 +139,33 @@ class NotificationService : Service() {
|
||||
generation++
|
||||
socket?.close(1000, "disabled")
|
||||
socket = null
|
||||
cancelReconnect()
|
||||
wakeLock.release()
|
||||
log.record("stopped")
|
||||
setStatus(if (settings.configured) DeliveryStatus.OFF else DeliveryStatus.UNCONFIGURED, notify = false)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivery is meant to be running but no socket is open or on its way.
|
||||
* Waiting for the network and a refused session are deliberate states.
|
||||
*/
|
||||
private fun isDown(): Boolean =
|
||||
socket == null && !reconnectPending &&
|
||||
settings.status != DeliveryStatus.SIGN_IN_REQUIRED &&
|
||||
settings.status != DeliveryStatus.WAITING_FOR_NETWORK
|
||||
|
||||
/** 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)
|
||||
cancelReconnect()
|
||||
generation++
|
||||
socket?.cancel()
|
||||
socket = null
|
||||
@@ -139,9 +180,12 @@ class NotificationService : Service() {
|
||||
}.build()
|
||||
} catch (error: IllegalArgumentException) {
|
||||
Log.w(TAG, "invalid endpoint $endpoint", error)
|
||||
log.record("invalid_endpoint", endpoint)
|
||||
return scheduleReconnect()
|
||||
}
|
||||
setStatus(if (backoff.attempt == 0) DeliveryStatus.CONNECTING else DeliveryStatus.RECONNECTING)
|
||||
log.record("connecting", endpoint)
|
||||
wakeLock.hold()
|
||||
val current = generation
|
||||
socket = client.newWebSocket(request, Listener(current))
|
||||
}
|
||||
@@ -151,15 +195,46 @@ class NotificationService : Service() {
|
||||
socket?.cancel()
|
||||
socket = null
|
||||
subscribeId = null
|
||||
if (!networkAvailable) return setStatus(DeliveryStatus.WAITING_FOR_NETWORK)
|
||||
wakeLock.release()
|
||||
if (!networkAvailable) {
|
||||
cancelReconnect()
|
||||
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())
|
||||
val delay = backoff.next()
|
||||
reconnectPending = true
|
||||
ReconnectAlarms.schedule(this, delay, ACTION_RECONNECT)
|
||||
log.record("retry_scheduled", "in ${delay / 1000}s")
|
||||
}
|
||||
|
||||
private fun cancelReconnect() {
|
||||
reconnectPending = false
|
||||
ReconnectAlarms.cancel(this, ACTION_RECONNECT)
|
||||
}
|
||||
|
||||
/**
|
||||
* The server refused the session cookie. Retrying cannot succeed, so the
|
||||
* loop stops here; a fresh cookie from the app restarts it.
|
||||
*/
|
||||
private fun signInRequired(code: Int) {
|
||||
generation++
|
||||
socket?.cancel()
|
||||
socket = null
|
||||
subscribeId = null
|
||||
wakeLock.release()
|
||||
cancelReconnect()
|
||||
log.record("sign_in_required", "HTTP $code", code)
|
||||
setStatus(DeliveryStatus.SIGN_IN_REQUIRED)
|
||||
presenter.signInRequired()
|
||||
}
|
||||
|
||||
private fun onOpen(webSocket: WebSocket) {
|
||||
backoff.reset()
|
||||
wakeLock.release()
|
||||
presenter.clearSignIn()
|
||||
log.record("connected")
|
||||
val id = "notify-${++sequence}"
|
||||
subscribeId = id
|
||||
webSocket.send(NotificationProtocol.subscribe(id, ledger.cursor))
|
||||
@@ -179,6 +254,7 @@ class NotificationService : Service() {
|
||||
is NotificationFrame.Cleared -> presenter.cancel(frame.ids)
|
||||
is NotificationFrame.Refused -> {
|
||||
Log.w(TAG, "subscribe_notifications refused: ${frame.error}")
|
||||
log.record("refused", "${frame.error}")
|
||||
scheduleReconnect()
|
||||
}
|
||||
NotificationFrame.Ignored -> Unit
|
||||
@@ -212,13 +288,16 @@ class NotificationService : Service() {
|
||||
val previous = currentNetwork
|
||||
currentNetwork = network
|
||||
networkAvailable = true
|
||||
log.record("network_available")
|
||||
// A new default network invalidates the old socket's route;
|
||||
// a returning network retries at once instead of waiting
|
||||
// out the backoff.
|
||||
// out the backoff. A refused session waits for a cookie.
|
||||
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)) {
|
||||
if (settings.configured && settings.status != DeliveryStatus.SIGN_IN_REQUIRED &&
|
||||
(moved || previous == null || idle)
|
||||
) {
|
||||
backoff.reset()
|
||||
connect()
|
||||
}
|
||||
@@ -230,6 +309,7 @@ class NotificationService : Service() {
|
||||
if (network != currentNetwork) return@post
|
||||
currentNetwork = null
|
||||
networkAvailable = false
|
||||
log.record("network_lost")
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
@@ -249,17 +329,27 @@ class NotificationService : Service() {
|
||||
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}")
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = current {
|
||||
log.record("closed", "close $code ${reason}".trim())
|
||||
scheduleReconnect()
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = current {
|
||||
val code = response?.code
|
||||
Log.i(TAG, "socket failed ($code): ${t.message}")
|
||||
log.record("failed", t.message ?: t.javaClass.simpleName, code)
|
||||
if (ReconnectPolicy.isAuthRejection(code) && code != null) signInRequired(code)
|
||||
else 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"
|
||||
const val ACTION_RECONNECT = "net.awan.pipelines.notify.RECONNECT"
|
||||
const val ACTION_WATCHDOG = "net.awan.pipelines.notify.WATCHDOG"
|
||||
private const val TASK_REMOVED_CHECK_MILLIS = 2_000L
|
||||
|
||||
@Volatile
|
||||
var running: NotificationService? = null
|
||||
@@ -277,6 +367,7 @@ class NotificationService : Service() {
|
||||
return try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
|
||||
else context.startService(intent)
|
||||
NotificationWatchdog.schedule(context)
|
||||
true
|
||||
} catch (error: Exception) {
|
||||
// Android 12+ refuses a foreground start from some background
|
||||
@@ -287,6 +378,9 @@ class NotificationService : Service() {
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
ReconnectAlarms.cancel(context, ACTION_RECONNECT)
|
||||
ReconnectAlarms.cancel(context, ACTION_WATCHDOG)
|
||||
NotificationWatchdog.cancel(context)
|
||||
context.stopService(Intent(context, NotificationService::class.java))
|
||||
}
|
||||
}
|
||||
|
||||
+15
-4
@@ -52,10 +52,9 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina
|
||||
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)
|
||||
}
|
||||
// A null action still restarts a service whose socket is down,
|
||||
// which is how a refused session resumes with a fresh cookie.
|
||||
NotificationService.start(activity, if (changed) NotificationService.ACTION_RESTART else null)
|
||||
result.success(status())
|
||||
}
|
||||
"setEnabled" -> {
|
||||
@@ -69,6 +68,7 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina
|
||||
}
|
||||
result.success(status())
|
||||
}
|
||||
"connectionEvents" -> result.success(connectionEvents())
|
||||
"requestBatteryExemption" -> {
|
||||
result.success(requestBatteryExemption())
|
||||
}
|
||||
@@ -92,6 +92,17 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina
|
||||
)
|
||||
}
|
||||
|
||||
/** The last connection events, newest first, for Settings' diagnosis. */
|
||||
private fun connectionEvents(): List<Map<String, Any>> =
|
||||
ConnectionLog(settings).entries().map { event ->
|
||||
buildMap {
|
||||
put("time", event.timeMillis)
|
||||
put("event", event.event)
|
||||
event.error?.let { put("error", it) }
|
||||
event.code?.let { put("code", it) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun batteryExempt(): Boolean =
|
||||
activity.getSystemService(PowerManager::class.java).isIgnoringBatteryOptimizations(activity.packageName)
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import android.app.job.JobInfo
|
||||
import android.app.job.JobParameters
|
||||
import android.app.job.JobScheduler
|
||||
import android.app.job.JobService
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
|
||||
/**
|
||||
* A periodic check that the notification service is alive and connected while
|
||||
* delivery is on. If the process was killed, or the socket is down with no
|
||||
* reconnect pending, it starts the service again. JobScheduler defers jobs in
|
||||
* Doze, so the reconnect alarms remain the primary path; this is the net under
|
||||
* them.
|
||||
*/
|
||||
class NotificationWatchdog : JobService() {
|
||||
override fun onStartJob(params: JobParameters?): Boolean {
|
||||
val settings = ServiceSettings(this)
|
||||
if (settings.enabled && settings.configured) {
|
||||
NotificationService.start(this, NotificationService.ACTION_WATCHDOG)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override fun onStopJob(params: JobParameters?): Boolean = true
|
||||
|
||||
companion object {
|
||||
private const val JOB_ID = 4201
|
||||
private const val PERIOD_MILLIS = 15 * 60_000L
|
||||
|
||||
fun schedule(context: Context) {
|
||||
val scheduler = context.getSystemService(JobScheduler::class.java)
|
||||
if (scheduler.getPendingJob(JOB_ID) != null) return
|
||||
val job = JobInfo.Builder(JOB_ID, ComponentName(context, NotificationWatchdog::class.java))
|
||||
.setPeriodic(PERIOD_MILLIS)
|
||||
.setPersisted(true)
|
||||
.build()
|
||||
scheduler.schedule(job)
|
||||
}
|
||||
|
||||
fun cancel(context: Context) {
|
||||
context.getSystemService(JobScheduler::class.java).cancel(JOB_ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
|
||||
/**
|
||||
* Wakes the notification service when a reconnect, restart or watchdog check
|
||||
* is due. A Handler delay pauses while the device dozes; an alarm does not.
|
||||
* Each action has one pending alarm: scheduling again replaces it.
|
||||
*/
|
||||
object ReconnectAlarms {
|
||||
fun schedule(context: Context, delayMillis: Long, action: String) {
|
||||
val manager = context.getSystemService(AlarmManager::class.java)
|
||||
val at = SystemClock.elapsedRealtime() + delayMillis
|
||||
val pending = pendingFor(context, action)
|
||||
val exact = ReconnectPolicy.alarmMode(exactPermitted(context)) ==
|
||||
ReconnectPolicy.AlarmMode.EXACT_WHILE_IDLE
|
||||
try {
|
||||
if (exact) {
|
||||
manager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending)
|
||||
} else {
|
||||
manager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending)
|
||||
}
|
||||
} catch (_: SecurityException) {
|
||||
// The exact-alarm grant was revoked between the check and the call.
|
||||
manager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending)
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel(context: Context, action: String) {
|
||||
val existing = lookup(context, action) ?: return
|
||||
context.getSystemService(AlarmManager::class.java).cancel(existing)
|
||||
existing.cancel()
|
||||
}
|
||||
|
||||
fun exactPermitted(context: Context): Boolean =
|
||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
|
||||
context.getSystemService(AlarmManager::class.java).canScheduleExactAlarms()
|
||||
|
||||
/**
|
||||
* Schedule and cancel must build the same kind of PendingIntent (a
|
||||
* foreground-service one on Android 8+), or a cancel matches nothing.
|
||||
* An alarm may start the service from the background; on Android 8+ that
|
||||
* must be a foreground start, which the service then satisfies.
|
||||
*/
|
||||
private fun pendingFor(context: Context, action: String): PendingIntent =
|
||||
checkNotNull(build(context, action, PendingIntent.FLAG_UPDATE_CURRENT)) {
|
||||
"FLAG_UPDATE_CURRENT always yields a PendingIntent"
|
||||
}
|
||||
|
||||
private fun lookup(context: Context, action: String): PendingIntent? =
|
||||
build(context, action, PendingIntent.FLAG_NO_CREATE)
|
||||
|
||||
private fun build(context: Context, action: String, mode: Int): PendingIntent? {
|
||||
val intent = Intent(context, NotificationService::class.java).setAction(action)
|
||||
val flags = PendingIntent.FLAG_IMMUTABLE or mode
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
PendingIntent.getForegroundService(context, requestCode(action), intent, flags)
|
||||
} else {
|
||||
PendingIntent.getService(context, requestCode(action), intent, flags)
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestCode(action: String): Int = action.hashCode()
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
/** Decisions the service makes on a failed socket, kept free of Android types. */
|
||||
object ReconnectPolicy {
|
||||
/**
|
||||
* HTTP 401/403 on the websocket handshake: the session cookie is no longer
|
||||
* accepted. Retrying cannot succeed, so the service waits for a fresh cookie.
|
||||
*/
|
||||
fun isAuthRejection(code: Int?): Boolean = code == 401 || code == 403
|
||||
|
||||
/**
|
||||
* Exact alarms need SCHEDULE_EXACT_ALARM (Android 12+, user-revocable). When
|
||||
* it is not granted the reconnect still fires during Doze, just inexactly.
|
||||
*/
|
||||
fun alarmMode(exactPermitted: Boolean): AlarmMode =
|
||||
if (exactPermitted) AlarmMode.EXACT_WHILE_IDLE else AlarmMode.WHILE_IDLE
|
||||
|
||||
enum class AlarmMode { EXACT_WHILE_IDLE, WHILE_IDLE }
|
||||
}
|
||||
@@ -11,6 +11,8 @@ enum class DeliveryStatus(val wire: String) {
|
||||
CONNECTED("connected"),
|
||||
RECONNECTING("reconnecting"),
|
||||
WAITING_FOR_NETWORK("waiting_for_network"),
|
||||
/** The server refused the session; delivery resumes when the app hands over a fresh cookie. */
|
||||
SIGN_IN_REQUIRED("sign_in_required"),
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ConnectionLogTest {
|
||||
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 class Clock(var now: Long = 1_000L) {
|
||||
fun tick(): Long = now++
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsTheLastFiftyEventsNewestFirst() {
|
||||
val store = MemoryStore()
|
||||
val clock = Clock()
|
||||
val log = ConnectionLog(store, clock::tick)
|
||||
repeat(ConnectionLog.CAPACITY + 10) { index -> log.record("event-$index") }
|
||||
val entries = log.entries()
|
||||
assertEquals(ConnectionLog.CAPACITY, entries.size)
|
||||
assertEquals("event-59", entries.first().event)
|
||||
assertEquals("event-10", entries.last().event)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun errorAndCodeSurviveAReload() {
|
||||
val store = MemoryStore()
|
||||
ConnectionLog(store) { 42L }.record("failed", "Expected HTTP 101", 403)
|
||||
val entry = ConnectionLog(store).entries().single()
|
||||
assertEquals(42L, entry.timeMillis)
|
||||
assertEquals("failed", entry.event)
|
||||
assertEquals("Expected HTTP 101", entry.error)
|
||||
assertEquals(403, entry.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun eventsWithoutErrorOrCodeReadBackAsNull() {
|
||||
val store = MemoryStore()
|
||||
ConnectionLog(store).record("connected")
|
||||
val entry = ConnectionLog(store).entries().single()
|
||||
assertNull(entry.error)
|
||||
assertNull(entry.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun longErrorTextIsTrimmed() {
|
||||
val store = MemoryStore()
|
||||
ConnectionLog(store).record("failed", "x".repeat(500))
|
||||
val error = ConnectionLog(store).entries().single().error!!
|
||||
assertEquals(200, error.length)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun corruptLogReadsAsEmptyInsteadOfThrowing() {
|
||||
val store = MemoryStore()
|
||||
store.values[ConnectionLog.KEY] = "not json"
|
||||
assertTrue(ConnectionLog(store).entries().isEmpty())
|
||||
ConnectionLog(store).record("connected")
|
||||
assertEquals("connected", ConnectionLog(store).entries().single().event)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import net.awan.pipelines_app.notify.ReconnectPolicy.AlarmMode
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ReconnectPolicyTest {
|
||||
@Test
|
||||
fun http401And403StopTheRetryLoop() {
|
||||
assertTrue(ReconnectPolicy.isAuthRejection(401))
|
||||
assertTrue(ReconnectPolicy.isAuthRejection(403))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun otherFailuresKeepRetrying() {
|
||||
assertFalse(ReconnectPolicy.isAuthRejection(null))
|
||||
assertFalse(ReconnectPolicy.isAuthRejection(500))
|
||||
assertFalse(ReconnectPolicy.isAuthRejection(503))
|
||||
assertFalse(ReconnectPolicy.isAuthRejection(404))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exactAlarmsWhenPermittedOtherwiseIdleTolerant() {
|
||||
assertEquals(AlarmMode.EXACT_WHILE_IDLE, ReconnectPolicy.alarmMode(true))
|
||||
assertEquals(AlarmMode.WHILE_IDLE, ReconnectPolicy.alarmMode(false))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user