|
| 1 | +package xyz.block.buzz.mobile |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import android.os.Handler |
| 5 | +import android.os.Looper |
| 6 | +import android.os.SystemClock |
| 7 | +import android.util.Log |
| 8 | +import androidx.core.app.NotificationManagerCompat |
| 9 | +import androidx.lifecycle.Lifecycle |
| 10 | +import androidx.lifecycle.ProcessLifecycleOwner |
| 11 | +import io.flutter.FlutterInjector |
| 12 | +import io.flutter.embedding.engine.FlutterEngine |
| 13 | +import io.flutter.embedding.engine.dart.DartExecutor |
| 14 | +import io.flutter.plugin.common.MethodChannel |
| 15 | +import java.util.concurrent.CountDownLatch |
| 16 | +import java.util.concurrent.TimeUnit |
| 17 | + |
| 18 | +/** |
| 19 | + * Turns a push wake into notifications. |
| 20 | + * |
| 21 | + * A wake carries nothing about any message. When the app is in the foreground |
| 22 | + * the handler does nothing, since the running app already shows new messages. |
| 23 | + * Otherwise it starts the app's Dart code in a background engine, which reads |
| 24 | + * the relays and answers with every message worth a notification, and posts |
| 25 | + * them directly: the category, and so the channel the user may have silenced, |
| 26 | + * is known only after the fetch. |
| 27 | + * |
| 28 | + * If nothing has been posted after [GENERIC_AFTER_MS] the handler posts a |
| 29 | + * generic notification in the "Other" channel, which the result then replaces |
| 30 | + * silently, or removes when it finds nothing. A watchdog ends the work at |
| 31 | + * [WATCHDOG_MS] whatever Dart does, inside the time FCM gives a handler, and |
| 32 | + * leaves the generic notification when no result came. |
| 33 | + * |
| 34 | + * One run exists per process. A wake that arrives while it runs is passed to |
| 35 | + * the Dart code, which folds it into the run in progress. |
| 36 | + */ |
| 37 | +internal object PushWake { |
| 38 | + private const val TAG = "BuzzPushWake" |
| 39 | + const val GENERIC_AFTER_MS = 2_000L |
| 40 | + const val WATCHDOG_MS = 8_000L |
| 41 | + |
| 42 | + /** |
| 43 | + * Watchdog time held back from Dart's lookup: its claim grace, the answer's |
| 44 | + * trip back and posting. A slow engine start then shortens the lookup |
| 45 | + * instead of letting the watchdog end it after messages were recorded as |
| 46 | + * shown but before they were posted. |
| 47 | + */ |
| 48 | + const val RESULT_RESERVE_MS = 1_000L |
| 49 | + private const val ENTRYPOINT = "androidPushWakeMain" |
| 50 | + private const val CHANNEL = "buzz/push_wake" |
| 51 | + |
| 52 | + private val main = Handler(Looper.getMainLooper()) |
| 53 | + |
| 54 | + // Main thread only. |
| 55 | + private var run: Run? = null |
| 56 | + |
| 57 | + /** |
| 58 | + * Handles a wake and returns when it is handled, so the process stays |
| 59 | + * alive for it. Call it off the main thread, as FCM does. |
| 60 | + */ |
| 61 | + fun handle(context: Context) { |
| 62 | + check(Looper.myLooper() != Looper.getMainLooper()) { "Handle a wake off the main thread" } |
| 63 | + val app = context.applicationContext |
| 64 | + val handled = CountDownLatch(1) |
| 65 | + main.post { begin(app, handled) } |
| 66 | + // The watchdog ends the run; the extra time covers only its own posting. |
| 67 | + handled.await(WATCHDOG_MS + 2_000, TimeUnit.MILLISECONDS) |
| 68 | + } |
| 69 | + |
| 70 | + private fun begin(context: Context, handled: CountDownLatch) { |
| 71 | + // Declined permission costs nothing else: nothing is fetched, so |
| 72 | + // nothing is recorded as shown, and a later grant sees new messages. |
| 73 | + val foreground = ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) |
| 74 | + if (foreground || !NotificationManagerCompat.from(context).areNotificationsEnabled()) { |
| 75 | + Log.i(TAG, "wake ignored foreground=$foreground") |
| 76 | + handled.countDown() |
| 77 | + return |
| 78 | + } |
| 79 | + val current = run |
| 80 | + if (current != null) { |
| 81 | + current.join(handled) |
| 82 | + return |
| 83 | + } |
| 84 | + Run(context).also { |
| 85 | + run = it |
| 86 | + it.join(handled) |
| 87 | + it.start() |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + private class Run(private val context: Context) { |
| 92 | + private val startedAt = SystemClock.elapsedRealtime() |
| 93 | + private val notifier = WakeNotifier(context) |
| 94 | + private val waiting = mutableListOf<CountDownLatch>() |
| 95 | + private var engine: FlutterEngine? = null |
| 96 | + private var channel: MethodChannel? = null |
| 97 | + private var ready = false |
| 98 | + private var wakeQueued = true |
| 99 | + private var outstanding = 0 |
| 100 | + private var answered = false |
| 101 | + private var genericShown = false |
| 102 | + private var finished = false |
| 103 | + private val genericCheck = Runnable { |
| 104 | + if (!answered) { |
| 105 | + log("generic_after_${GENERIC_AFTER_MS}ms") |
| 106 | + showGeneric() |
| 107 | + } |
| 108 | + } |
| 109 | + private val watchdog = Runnable { finish("watchdog") } |
| 110 | + |
| 111 | + private fun log(stage: String) = |
| 112 | + Log.i(TAG, "stage=$stage t=${SystemClock.elapsedRealtime() - startedAt}ms") |
| 113 | + |
| 114 | + fun join(latch: CountDownLatch) { |
| 115 | + waiting += latch |
| 116 | + // Wakes before Dart is ready are covered by its first pass. |
| 117 | + if (ready) requestWake() |
| 118 | + } |
| 119 | + |
| 120 | + fun start() { |
| 121 | + log("wake") |
| 122 | + notifier.createChannels() |
| 123 | + main.postDelayed(genericCheck, GENERIC_AFTER_MS) |
| 124 | + main.postDelayed(watchdog, WATCHDOG_MS) |
| 125 | + try { |
| 126 | + val engine = FlutterEngine(context).also { engine = it } |
| 127 | + log("engine_created") |
| 128 | + channel = MethodChannel(engine.dartExecutor.binaryMessenger, CHANNEL).also { |
| 129 | + it.setMethodCallHandler { call, result -> |
| 130 | + when (call.method) { |
| 131 | + "ready" -> { |
| 132 | + log("dart_ready") |
| 133 | + ready = true |
| 134 | + if (wakeQueued) { |
| 135 | + wakeQueued = false |
| 136 | + requestWake() |
| 137 | + } |
| 138 | + result.success(null) |
| 139 | + } |
| 140 | + else -> result.notImplemented() |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + engine.dartExecutor.executeDartEntrypoint( |
| 145 | + DartExecutor.DartEntrypoint( |
| 146 | + FlutterInjector.instance().flutterLoader().findAppBundlePath(), |
| 147 | + ENTRYPOINT, |
| 148 | + ), |
| 149 | + ) |
| 150 | + } catch (error: Exception) { |
| 151 | + Log.e(TAG, "background engine failed to start", error) |
| 152 | + finish("engine_failed") |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + private fun requestWake() { |
| 157 | + outstanding++ |
| 158 | + val remaining = WATCHDOG_MS - RESULT_RESERVE_MS - (SystemClock.elapsedRealtime() - startedAt) |
| 159 | + channel!!.invokeMethod( |
| 160 | + "wake", |
| 161 | + mapOf("remainingMillis" to remaining.coerceAtLeast(0)), |
| 162 | + object : MethodChannel.Result { |
| 163 | + override fun success(result: Any?) = answer { handleResult(result) } |
| 164 | + override fun error(code: String, message: String?, details: Any?) = |
| 165 | + answer { |
| 166 | + Log.w(TAG, "dart wake failed: $code $message") |
| 167 | + answered = true |
| 168 | + showGeneric() |
| 169 | + } |
| 170 | + override fun notImplemented() = error("not_implemented", null, null) |
| 171 | + }, |
| 172 | + ) |
| 173 | + } |
| 174 | + |
| 175 | + private fun answer(handle: () -> Unit) { |
| 176 | + if (finished) return |
| 177 | + outstanding-- |
| 178 | + try { |
| 179 | + handle() |
| 180 | + } catch (error: Exception) { |
| 181 | + // A result the handler can't read is a failed fetch, not a crash. |
| 182 | + Log.e(TAG, "unreadable wake result", error) |
| 183 | + answered = true |
| 184 | + if (!genericShown) showGeneric() |
| 185 | + } |
| 186 | + if (outstanding == 0) finish("done") |
| 187 | + } |
| 188 | + |
| 189 | + private fun handleResult(result: Any?) { |
| 190 | + val map = result as? Map<*, *> ?: throw IllegalArgumentException("Not a wake result") |
| 191 | + if (map["joined"] == true) return |
| 192 | + log("dart_result") |
| 193 | + val notifications = (map["notifications"] as List<*>).map { WakeNotification.fromDart(it) } |
| 194 | + answered = true |
| 195 | + when { |
| 196 | + notifications.isNotEmpty() -> { |
| 197 | + notifier.postConversations(notifications, silent = genericShown) |
| 198 | + log("posted count=${notifications.size}") |
| 199 | + removeGeneric() |
| 200 | + } |
| 201 | + map["incomplete"] == true -> showGeneric() |
| 202 | + else -> removeGeneric() |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + private fun showGeneric() { |
| 207 | + if (genericShown) return |
| 208 | + genericShown = true |
| 209 | + notifier.postGeneric() |
| 210 | + } |
| 211 | + |
| 212 | + /** Also clears the generic notification an earlier run left behind. */ |
| 213 | + private fun removeGeneric() { |
| 214 | + genericShown = false |
| 215 | + notifier.cancelGeneric() |
| 216 | + } |
| 217 | + |
| 218 | + private fun finish(why: String) { |
| 219 | + if (finished) return |
| 220 | + finished = true |
| 221 | + main.removeCallbacks(genericCheck) |
| 222 | + main.removeCallbacks(watchdog) |
| 223 | + // No result at all (watchdog, failed engine): the wake must not be silent. |
| 224 | + if (!answered) showGeneric() |
| 225 | + engine?.destroy() |
| 226 | + engine = null |
| 227 | + run = null |
| 228 | + waiting.forEach { it.countDown() } |
| 229 | + log("finished_$why") |
| 230 | + } |
| 231 | + } |
| 232 | +} |
0 commit comments