package org.vikishop.app import android.app.ActivityManager import android.app.KeyguardManager import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.media.AudioAttributes import android.net.Uri import android.os.Build import android.os.Bundle import android.util.Log import java.net.HttpURLConnection import java.net.URL import kotlin.concurrent.thread /** * Certaines surcouches Android laissent passer le message Firebase jusqu'aux * récepteurs de l'app, mais bloquent le démarrage des services qui affichent la * notification. Ce récepteur prend alors le relais, sur toutes les marques et * sans démarrer de service. * * - Notification classique : Firebase doit l'afficher. On lui laisse quelques * secondes, et on ne l'affiche que s'il ne l'a pas fait (pas de doublon). * - Données seules (course, promotion) : ce récepteur est le seul à l'afficher * quand l'app est en arrière-plan (le code Flutter s'abstient sur Android). */ class VikishopPushReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val extras = intent.extras ?: return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return val listed = listOf(Build.MANUFACTURER, Build.BRAND) .any { it.lowercase() in ANDROID_BRANDS } Log.i(TAG, "Message reçu (${Build.MANUFACTURER} / ${Build.BRAND}), marque répertoriée : $listed") // App au premier plan : le code Flutter affiche déjà le message. if (isForeground(context)) return val classicTitle = extras.first("gcm.n.title", "gcm.notification.title") val ride = extras.getString("ride") == "1" val promo = extras.getString("promo") == "1" if (classicTitle == null && !ride && !promo) return val title = classicTitle ?: extras.getString("title") ?: return val body = extras.first("gcm.n.body", "gcm.notification.body", "body") val url = extras.getString("url") val image = extras.first("gcm.n.image", "gcm.notification.image", "image") ?.takeIf { it.startsWith("https://") } val insistent = ride && !promo && classicTitle == null val channelId = extras.first("gcm.n.android_channel_id", "gcm.notification.android_channel_id") val rideChannel = insistent || channelId == RIDE_CHANNEL val id = (extras.getString("google.message_id") ?: url ?: title).hashCode() val receivedAt = System.currentTimeMillis() val pending = goAsync() thread { try { if (classicTitle == null) { // Le texte d'abord : il ne doit pas attendre le réseau. show(context, id, title, body, url, rideChannel, insistent, null) fetch(image)?.let { show(context, id, title, body, url, rideChannel, insistent, it) } } else { // La photo est téléchargée pendant l'attente. val picture = fetch(image) val remaining = FIREBASE_DELAY_MS - (System.currentTimeMillis() - receivedAt) if (remaining > 0) Thread.sleep(remaining) if (alreadyShown(context, id, title, body, receivedAt)) { Log.i(TAG, "Notification déjà affichée par Firebase") } else { show(context, id, title, body, url, rideChannel, insistent, picture) Log.i(TAG, "Notification affichée par le relais (${Build.MANUFACTURER})") } } } catch (e: Exception) { Log.w(TAG, "Affichage impossible", e) } finally { pending.finish() } } } private fun alreadyShown( context: Context, ownId: Int, title: String, body: String?, receivedAt: Long, ): Boolean = context.getSystemService(NotificationManager::class.java) .activeNotifications .any { val shown = it.notification.extras it.id != ownId && it.postTime >= receivedAt - 2000 && shown.getCharSequence(Notification.EXTRA_TITLE)?.toString() == title && shown.getCharSequence(Notification.EXTRA_TEXT)?.toString() == body } /** Android limite la durée d'un récepteur : la photo est abandonnée après 5 s. */ private fun fetch(address: String?): Bitmap? { if (address == null) return null var picture: Bitmap? = null val worker = thread(isDaemon = true) { try { picture = download(address) } catch (e: Exception) { Log.w(TAG, "Photo indisponible", e) } } worker.join(5000) return picture } private fun show( context: Context, id: Int, title: String, body: String?, url: String?, rideChannel: Boolean, insistent: Boolean, picture: Bitmap?, ) { val manager = context.getSystemService(NotificationManager::class.java) val channelId = if (rideChannel) RIDE_CHANNEL else ORDERS_CHANNEL ensureChannel(context, manager, rideChannel) // Ouverture comme un lien de l'app : la page est chargée dans la webview. val open = Intent(context, MainActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) val target = url?.let { Uri.parse(it) } if (target?.scheme == "https" && target.host == "www.vikishop.org") { open.setAction(Intent.ACTION_VIEW).setData(target) } val builder = Notification.Builder(context, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(title) .setContentText(body) .setAutoCancel(true) .setOnlyAlertOnce(true) .setContentIntent( PendingIntent.getActivity( context, id, open, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) ) if (picture != null) { builder.setLargeIcon(picture) .setStyle(Notification.BigPictureStyle().bigPicture(picture)) } else if (body != null) { builder.setStyle(Notification.BigTextStyle().bigText(body)) } if (insistent) { builder.setCategory(Notification.CATEGORY_CALL).setTimeoutAfter(60000) } val notification = builder.build() if (insistent) notification.flags = notification.flags or Notification.FLAG_INSISTENT manager.notify(id, notification) } /** Sans effet si le canal existe déjà : les réglages de l'utilisateur sont conservés. */ private fun ensureChannel(context: Context, manager: NotificationManager, ride: Boolean) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return if (!ride) { manager.createNotificationChannel( NotificationChannel(ORDERS_CHANNEL, "Commandes et services", NotificationManager.IMPORTANCE_HIGH) ) return } val channel = NotificationChannel(RIDE_CHANNEL, "Notifications Vikishop", NotificationManager.IMPORTANCE_HIGH) channel.enableVibration(true) channel.setSound( Uri.parse("android.resource://${context.packageName}/${R.raw.ride_request}"), AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION) .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .build(), ) manager.createNotificationChannel(channel) } private fun isForeground(context: Context): Boolean { if (context.getSystemService(KeyguardManager::class.java).isKeyguardLocked) return false val processes = context.getSystemService(ActivityManager::class.java).runningAppProcesses ?: return false return processes.any { it.processName == context.packageName && it.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND } } private fun download(address: String): Bitmap? { val connection = URL(address).openConnection() as HttpURLConnection connection.connectTimeout = 4000 connection.readTimeout = 4000 return try { if (connection.responseCode == 200) { connection.inputStream.use { BitmapFactory.decodeStream(it) } } else { null } } finally { connection.disconnect() } } private fun Bundle.first(vararg keys: String): String? = keys.firstNotNullOfOrNull { getString(it) } private companion object { const val TAG = "VikishopPush" const val ORDERS_CHANNEL = "vikishop_orders" const val RIDE_CHANNEL = "vikishop_alerts_v2" const val FIREBASE_DELAY_MS = 7000L // Marques Android répertoriées. La liste ne peut pas être complète : elle // sert au diagnostic et n'exclut aucun téléphone du relais. val ANDROID_BRANDS = setOf( "acer", "advan", "agm", "aiwa", "alcatel", "alldocube", "allview", "amazon", "aquos", "archos", "asus", "benco", "benq", "bird", "blackberry", "blackview", "blu", "bluboo", "bluebird", "bq", "brondi", "cat", "caterpillar", "cherry", "cherrymobile", "chuwi", "cloudfone", "condor", "conquest", "coolpad", "crosscall", "cubot", "cyrus", "datalogic", "dexp", "digma", "doke", "doogee", "doro", "echo", "elephone", "emporia", "energizer", "essential", "evercoss", "fairphone", "fcnt", "fossibot", "freetel", "fujitsu", "geotel", "gigabyte", "gigaset", "gionee", "gome", "google", "gplus", "hafury", "haier", "hammer", "hihonor", "hisense", "hmd", "homtom", "honeywell", "honor", "hotpepper", "hotwav", "htc", "huawei", "iiif150", "ikimobile", "infinix", "innos", "inoi", "intex", "iqoo", "irbis", "itel", "jiayu", "jio", "karbonn", "kazam", "kodak", "konrow", "koobee", "kyocera", "lanix", "lava", "leagoo", "leeco", "lenovo", "letv", "lg", "lge", "logicom", "lyf", "meitu", "meizu", "micromax", "mobicel", "mobiistar", "motive", "motorola", "myphone", "myria", "nec", "neffos", "newland", "nokia", "nothing", "nubia", "nuu", "onda", "oneplus", "oppo", "orange", "oscal", "oukitel", "panasonic", "pantech", "philips", "phonemax", "poco", "point-mobile", "polaroid", "positivo", "prestigio", "qmobile", "razer", "realme", "redmagic", "redmi", "samsung", "sharp", "shift", "siswoo", "smartisan", "sonim", "sony", "sparx", "sugar", "symphony", "tcl", "teclast", "tecno", "tecnomobile", "teracube", "thomson", "tinno", "turbox", "ulefone", "umidigi", "unihertz", "unimax", "unisoc", "urovo", "verizon", "vernee", "vertex", "vertu", "vestel", "vivo", "vodafone", "vsmart", "walton", "wiko", "wileyfox", "wingtech", "xgody", "xiaolajiao", "xiaomi", "xolo", "yezz", "yota", "yu", "zebra", "zen", "zopo", "ztc", "zte", "zuk", ) } }