package com.oshicue.tempo.alert import android.Manifest import android.app.AlarmManager 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.content.pm.PackageManager import android.net.Uri import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import com.oshicue.tempo.MainActivity import com.oshicue.tempo.R import com.oshicue.tempo.audio.TempoAudio import com.oshicue.tempo.core.L10n import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow /** * End-of-round alerts for the lock screen and the background. * * iOS uses a local notification per round. The Android equivalent is an exact alarm that * posts a notification on a per-sound channel; the channel owns the sound, so the cue is * correct even when the process has been killed. Each round has one alarm, keyed by its * id, and rescheduling replaces it rather than stacking. */ class TempoNotifications(private val context: Context) { enum class Authorization { NotDetermined, Authorized, Denied } private val manager = NotificationManagerCompat.from(context) private val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager private val _authorization = MutableStateFlow(Authorization.NotDetermined) val authorization: StateFlow = _authorization.asStateFlow() private val _errorMessage = MutableStateFlow(null) val errorMessage: StateFlow = _errorMessage.asStateFlow() init { refresh() } fun refresh() { _authorization.value = when { Build.VERSION.SDK_INT >= 33 -> { val granted = ContextCompat.checkSelfPermission( context, Manifest.permission.POST_NOTIFICATIONS, ) == PackageManager.PERMISSION_GRANTED when { granted -> Authorization.Authorized // Before the first request the permission simply has not been asked for. else -> Authorization.NotDetermined } } manager.areNotificationsEnabled() -> Authorization.Authorized else -> Authorization.Denied } } fun markDenied() { _authorization.value = Authorization.Denied } val isAuthorized: Boolean get() = _authorization.value == Authorization.Authorized val authorizationDescription: String get() = when (_authorization.value) { Authorization.Authorized -> L10n.text("notifications.authorized") Authorization.Denied -> L10n.text("notifications.denied") Authorization.NotDetermined -> L10n.text("notifications.notDetermined") } /** * Schedules the round alert. A missing exact-alarm permission, or denied notifications, * degrades to an inexact alarm: the cue still arrives, just not to the second. */ fun schedule(roundId: String, memberName: String, deadline: Long, soundUri: Uri?) { ensureChannel(soundUri) val triggerAt = maxOf(deadline, System.currentTimeMillis() + 1_000) val pending = pendingIntent(roundId, memberName, soundKindKey(soundUri), triggerAt) val canExact = Build.VERSION.SDK_INT < 31 || alarmManager.canScheduleExactAlarms() try { if (canExact) { alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pending) } else { alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pending) } } catch (_: SecurityException) { alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pending) } catch (error: Exception) { _errorMessage.value = L10n.text("notifications.scheduleFailed") } } fun cancel(roundId: String) { val intent = Intent(context, TempoAlarmReceiver::class.java) val identifier = requestCode(roundId) val pending = PendingIntent.getBroadcast( context, identifier, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) alarmManager.cancel(pending) pending.cancel() manager.cancel(identifier) } fun cancelAll() { // Only alarms this app scheduled are cancelled; ids are derived from the round id. val scheduled = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) scheduled.all.keys.toList().forEach { cancel(it) } scheduled.edit().clear().apply() } /** * Channels are immutable once created, so each distinct sound gets its own channel. * Re-creating an existing channel is a no-op, which keeps rescheduling cheap. */ fun ensureChannel(soundUri: Uri?) { val soundKey = soundKindKey(soundUri) val channelId = channelId(soundKey) if (Build.VERSION.SDK_INT >= 26) { val existing = manager.getNotificationChannel(channelId) if (existing != null) return val channel = NotificationChannel( channelId, L10n.text("sounds.backgroundAlerts"), NotificationManager.IMPORTANCE_HIGH, ).apply { description = L10n.text("notifications.roundFinishedBody") enableVibration(true) if (soundUri != null) { setSound(soundUri, android.media.AudioAttributes.Builder() .setUsage(android.media.AudioAttributes.USAGE_NOTIFICATION_EVENT) .build()) } } manager.createNotificationChannel(channel) } } private fun soundKindKey(soundUri: Uri?): String = soundUri?.lastPathSegment?.substringAfterLast('/')?.ifBlank { "default" } ?: "default" private fun channelId(soundKey: String): String = "tempo-round-" + soundKey.replace(Regex("[^A-Za-z0-9_.-]"), "-") private fun requestCode(roundId: String): Int = roundId.hashCode() and 0x7FFFFFFF private fun pendingIntent(roundId: String, memberName: String, soundKey: String, triggerAt: Long): PendingIntent { val intent = Intent(context, TempoAlarmReceiver::class.java).apply { putExtra(TempoNotifications.EXTRA_ROUND_ID, roundId) putExtra(TempoNotifications.EXTRA_MEMBER, memberName) putExtra(TempoNotifications.EXTRA_CHANNEL, channelId(soundKey)) putExtra(TempoNotifications.EXTRA_NOTIFICATION_ID, requestCode(roundId)) // A distinct data URI keeps PendingIntents for different rounds from matching. data = Uri.parse("tempo://round/$roundId") } context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) .edit().putBoolean(roundId, true).apply() return PendingIntent.getBroadcast( context, requestCode(roundId), intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) } fun clearError() { _errorMessage.value = null } companion object { private const val PREFERENCES = "tempo-scheduled-alerts" const val EXTRA_ROUND_ID = "roundId" const val EXTRA_MEMBER = "member" const val EXTRA_CHANNEL = "channel" const val EXTRA_NOTIFICATION_ID = "notificationId" } } /** Posts the end-of-round notification when its alarm fires. */ class TempoAlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val member = intent.getStringExtra(TempoNotifications.EXTRA_MEMBER) ?: return val channel = intent.getStringExtra(TempoNotifications.EXTRA_CHANNEL) ?: return val identifier = intent.getIntExtra(TempoNotifications.EXTRA_NOTIFICATION_ID, member.hashCode()) val roundId = intent.getStringExtra(TempoNotifications.EXTRA_ROUND_ID) if (roundId != null) { context.getSharedPreferences("tempo-scheduled-alerts", Context.MODE_PRIVATE) .edit().remove(roundId).apply() } val open = Intent(context, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP } val contentIntent = PendingIntent.getActivity( context, identifier, open, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) val notification = NotificationCompat.Builder(context, channel) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(L10n.format("notifications.roundFinishedTitle", member)) .setContentText(L10n.text("notifications.roundFinishedBody")) .setStyle(NotificationCompat.BigTextStyle().bigText(L10n.text("notifications.roundFinishedBody"))) .setPriority(NotificationCompat.PRIORITY_HIGH) .setCategory(NotificationCompat.CATEGORY_ALARM) .setAutoCancel(true) .setContentIntent(contentIntent) .build() runCatching { NotificationManagerCompat.from(context).notify(identifier, notification) } } } /** Kept here so the audio module and the alert module agree on the fallback cue. */ internal fun TempoAudio.notificationUriFor(soundId: String): Uri? = notificationSoundUri(soundId)