Files
Nekosu/app/src/main/java/ru/risdeveau/pixeldragon/push/PixelDragonNotifier.kt
T
2026-05-07 05:41:13 +03:00

75 lines
2.6 KiB
Kotlin
Executable File

/*
* Created by sweetbread
* Copyright (c) 2026. All rights reserved.
*/
package ru.risdeveau.pixeldragon.push
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import ru.risdeveau.pixeldragon.R
import ru.risdeveau.pixeldragon.ui.activity.MainActivity
private const val MATRIX_CHANNEL_ID = "matrix_messages"
private const val MATRIX_NOTIFICATION_ID = 1001
object PixelDragonNotifier {
fun showWakeUpNotification(context: Context) {
val appContext = context.applicationContext
if (!appContext.canPostNotifications()) return
ensureChannel(appContext)
val intent = Intent(appContext, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
}
val pendingIntent = PendingIntent.getActivity(
appContext,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val notification = NotificationCompat.Builder(appContext, MATRIX_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("New Matrix activity")
.setContentText("Open PixelDragon to sync and decrypt the latest messages.")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
NotificationManagerCompat.from(appContext).notify(MATRIX_NOTIFICATION_ID, notification)
}
private fun ensureChannel(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val notificationManager = context.getSystemService(NotificationManager::class.java)
val channel = NotificationChannel(
MATRIX_CHANNEL_ID,
"Matrix messages",
NotificationManager.IMPORTANCE_DEFAULT,
).apply {
description = "Wake-up notifications from ntfy / UnifiedPush."
}
notificationManager.createNotificationChannel(channel)
}
}
fun Context.canPostNotifications(): Boolean {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(
this,
Manifest.permission.POST_NOTIFICATIONS,
) == PackageManager.PERMISSION_GRANTED
}