package com.cottondb.calling import android.Manifest import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.content.pm.ServiceInfo import android.media.AudioAttributes import android.media.RingtoneManager import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.Person import androidx.core.app.ServiceCompat import androidx.core.content.ContextCompat /** * What the call shows outside the app: the ring (a full-screen, insistent call notification with Answer and Decline, * Android's CallStyle, which is how a self-managed call rings like a phone call) and, while a call is up, the * ongoing call's notification with Hang up, held by [CallService], the foreground service that keeps the call's * microphone and camera while the app is not in front. The channels are named in the core's words. */ class CallNotices(private val context: Context, private val engine: CallingEngine) { private val manager = context.getSystemService(NotificationManager::class.java) private var ringing: String? = null private fun channels() { val words = engine.words val ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE) manager.createNotificationChannel(NotificationChannel(RING, words.line("android.ring_channel"), NotificationManager.IMPORTANCE_HIGH).apply { setSound(ringtone, AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build()) enableVibration(true) }) manager.createNotificationChannel(NotificationChannel(CALL, words.line("android.call_channel"), NotificationManager.IMPORTANCE_LOW)) } /** The ring of call [uuid]: the caller's name (the core's, else its words for a ring), Answer opening the app to answer. */ fun ring(uuid: String, title: String, video: Boolean, again: Boolean = false) { if (again && ringing != uuid) return ringing = uuid channels() // The caller's picture on the ring, when the ring's sealed box named someone whose picture is on this phone. val photo = engine.center.caller?.photoPath?.let { path -> runCatching { android.graphics.BitmapFactory.decodeFile(path) }.getOrNull() } val caller = Person.Builder().setName(title.ifEmpty { engine.words.line("phase.ringing_in") }).setImportant(true) .apply { photo?.let { setIcon(androidx.core.graphics.drawable.IconCompat.createWithBitmap(it)) } }.build() val open = activity(CallingActivity.RING, 1) val answer = activity(CallingActivity.ANSWER, 2) val decline = PendingIntent.getBroadcast(context, 3, Intent(context, CallActionReceiver::class.java).setAction(CallActionReceiver.DECLINE), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) val notice = NotificationCompat.Builder(context, RING) .setSmallIcon(android.R.drawable.sym_call_incoming) .setStyle(NotificationCompat.CallStyle.forIncomingCall(caller, decline, answer).setIsVideo(video)) .setFullScreenIntent(open, true) .setContentIntent(open) .setCategory(NotificationCompat.CATEGORY_CALL) .setPriority(NotificationCompat.PRIORITY_MAX) .setOngoing(true) .setOnlyAlertOnce(again) .build() notice.flags = notice.flags or Notification.FLAG_INSISTENT post(RING_ID, notice) } /** The ring is over (answered, declined, stopped, ended). */ fun ringOver(uuid: String) { if (ringing != null && ringing != uuid) return ringing = null manager.cancel(RING_ID) } /** The ongoing call's notification, for [CallService]: the other side's name, Hang up, a tap back into the call. */ fun ongoing(): Notification { channels() val call = engine.center.call val other = Person.Builder().setName(call.name ?: call.number ?: engine.words.line("phase.connecting")).build() val hangUp = PendingIntent.getBroadcast(context, 4, Intent(context, CallActionReceiver::class.java).setAction(CallActionReceiver.HANG_UP), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) return NotificationCompat.Builder(context, CALL) .setSmallIcon(android.R.drawable.sym_action_call) .setStyle(NotificationCompat.CallStyle.forOngoingCall(other, hangUp).setIsVideo(call.video)) .setContentIntent(activity(CallingActivity.RING, 5)) .setCategory(NotificationCompat.CATEGORY_CALL) .setOngoing(true) .build() } private fun activity(action: String, code: Int): PendingIntent = PendingIntent.getActivity(context, code, CallingActivity.intent(context, action).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) private fun post(id: Int, notice: Notification) { if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return engine.log.i("calls: no leave to notify, the ring is not shown") runCatching { NotificationManagerCompat.from(context).notify(id, notice) }.onFailure { engine.log.i("calls: the notice was refused: $it") } } companion object { const val RING = "calls.ring" const val CALL = "calls.ongoing" const val RING_ID = 4101 const val CALL_ID = 4102 } } /** Decline on the ring and Hang up on the ongoing call: the engine's asks, as a tap in the app would make them. */ class CallActionReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val center = CallingEngine.of(context).center when (intent.action) { DECLINE -> center.decline() HANG_UP -> center.end() } } companion object { const val DECLINE = "com.cottondb.calling.DECLINE" const val HANG_UP = "com.cottondb.calling.HANG_UP" } } /** * The foreground service a call holds while it is up (dialling to ended): the ongoing call's notification, typed * phone call, and microphone and camera where the person gave leave for them, so the call keeps its audio and * video when the app goes behind another. It stops when the call ends. */ class CallService : Service() { override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val engine = CallingEngine.of(this) var types = ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL if (granted(Manifest.permission.RECORD_AUDIO)) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE if (engine.center.call.video && granted(Manifest.permission.CAMERA)) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA runCatching { ServiceCompat.startForeground(this, CallNotices.CALL_ID, engine.notices.ongoing(), types) } .onFailure { engine.log.i("calls: the call's service could not stand in front: $it") stopSelf() } return START_NOT_STICKY } private fun granted(permission: String) = ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED companion object { fun start(context: Context) { runCatching { ContextCompat.startForegroundService(context, Intent(context, CallService::class.java)) } .onFailure { CallingEngine.of(context).log.i("calls: the call's service was refused: $it") } } fun stop(context: Context) { context.stopService(Intent(context, CallService::class.java)) } } }