package io.appwrite.flutter import android.Manifest import android.app.Activity import android.content.pm.PackageManager import android.os.Build import android.os.Handler import android.os.Looper import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import io.appwrite.flutter.services.PushBridge import io.appwrite.flutter.services.PushMessage import io.appwrite.flutter.services.PushTaps import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel /** * The Flutter side of [PushBridge]: the SDK's `Push` hosts its background subscriptions here on * Android over a method channel, and receives their messages and errors over an event channel. */ class AppwritePushPlugin : FlutterPlugin, ActivityAware, MethodChannel.MethodCallHandler, EventChannel.StreamHandler { private val main = Handler(Looper.getMainLooper()) private var methods: MethodChannel? = null private var events: EventChannel? = null private var sink: EventChannel.EventSink? = null private var openedListeners = 0 private var stopOpened: (() -> Unit)? = null private var bridge: PushBridge? = null private var activity: Activity? = null override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { bridge = PushBridge( binding.applicationContext, object : PushBridge.Events { override fun onMessage(subscriptionId: String, message: PushMessage, ackToken: String) = send( mapOf( "type" to "message", "id" to subscriptionId, "topic" to message.topic, "payload" to message.payload, "qos" to message.qos, "ackToken" to ackToken, ), ) override fun onError(message: String) = send(mapOf("type" to "error", "message" to message)) override fun onConnection(connected: Boolean) = send(mapOf("type" to "connection", "connected" to connected)) }, ) methods = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL).also { it.setMethodCallHandler(this) } events = EventChannel(binding.binaryMessenger, EVENT_CHANNEL).also { it.setStreamHandler(this) } } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { methods?.setMethodCallHandler(null) events?.setStreamHandler(null) methods = null events = null sink = null stopOpened?.invoke() stopOpened = null openedListeners = 0 } override fun onAttachedToActivity(binding: ActivityPluginBinding) { activity = binding.activity } override fun onDetachedFromActivityForConfigChanges() { activity = null } override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { activity = binding.activity } override fun onDetachedFromActivity() { activity = null } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { val bridge = bridge ?: return result.error(ERROR_CODE, "Push plugin is not attached", null) try { if (call.method == "host") { // Replies once the connection is up and every filter is subscribed, or with why not. bridge.host(call.argument("config")!!, call.argument("subscriptions")!!) { error -> main.post { if (error == null) { result.success(bridge.isConnected()) } else { result.error(ERROR_CODE, error, null) } } } return } result.success( when (call.method) { "requestNotificationPermission" -> requestNotificationPermission() "ack" -> bridge.ack(call.argument("token")!!).let { null } "release" -> bridge.release().let { null } "stop" -> bridge.stop().let { null } "setForeground" -> bridge.setForeground(call.argument("enabled") == true).let { null } "hasSaved" -> bridge.hasSaved() "resume" -> bridge.resume(call.argument("authMethod"), call.argument("credential"), false).let { null } "backgroundStatus" -> bridge.backgroundStatus() "requestExactAlarms" -> bridge.requestExactAlarms() "requestIgnoreBatteryOptimizations" -> bridge.requestIgnoreBatteryOptimizations() "setErrorCallback" -> bridge.setErrorCallback(call.argument("registered") == true) "defaultClientId" -> bridge.defaultClientId(call.argument("authMethod")!!, call.argument("credential")!!) "getInitialNotification" -> PushTaps.take()?.let { mapOf("topic" to it.topic, "payload" to it.payload) } "listenOpened" -> listenOpened(call.argument("listening") == true).let { null } else -> return result.notImplemented() }, ) } catch (e: Exception) { result.error(ERROR_CODE, e.message, null) } } override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { sink = events } override fun onCancel(arguments: Any?) { sink = null } // Android 13+: ask for POST_NOTIFICATIONS, which background notifications are posted with. // Returns false when it could not ask because no Activity is attached, so the caller asks again. private fun requestNotificationPermission(): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { return true } val activity = activity ?: return false if (ContextCompat.checkSelfPermission(activity, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.POST_NOTIFICATIONS), PERMISSION_REQUEST_CODE) } return true } // The bridge calls back on background threads; event sinks must be used on the main thread. private fun send(event: Map) { main.post { sink?.success(event) } } // Sends each tap while Dart listens for them; until then a tap waits for getInitialNotification. private fun listenOpened(listening: Boolean) { openedListeners = (openedListeners + if (listening) 1 else -1).coerceAtLeast(0) if (openedListeners > 0 && stopOpened == null) { stopOpened = PushTaps.listen { tap -> send(mapOf("type" to "opened", "topic" to tap.topic, "payload" to tap.payload)) } } else if (openedListeners == 0) { stopOpened?.invoke() stopOpened = null } } private companion object { const val METHOD_CHANNEL = "appwrite.push" const val EVENT_CHANNEL = "appwrite.push/events" const val ERROR_CODE = "appwrite_push" const val PERMISSION_REQUEST_CODE = 9412 } }