package com.cottondb.callingimport android.Manifestimport android.app.Notificationimport android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntentimport android.app.Serviceimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.content.pm.PackageManagerimport android.content.pm.ServiceInfoimport android.media.AudioAttributesimport android.media.RingtoneManagerimport android.os.IBinderimport androidx.core.app.NotificationCompatimport androidx.core.app.NotificationManagerCompatimport androidx.core.app.Personimport androidx.core.app.ServiceCompatimport 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. */classCallNotices(privateval context: Context, privateval engine: CallingEngine) {privateval manager = context.getSystemService(NotificationManager::class.java)privatevar ringing: String? = nullprivatefun channels() {val words = engine.wordsval 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()valopen = 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.callval 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)returnNotificationCompat.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() }privatefun 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)privatefun 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") } }companionobject {constval RING = "calls.ring"constval CALL = "calls.ongoing"constval RING_ID = 4101constval 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. */classCallActionReceiver : BroadcastReceiver() {overridefun onReceive(context: Context, intent: Intent) {val center = CallingEngine.of(context).centerwhen (intent.action) { DECLINE -> center.decline() HANG_UP -> center.end() } }companionobject {constval DECLINE = "com.cottondb.calling.DECLINE"constval 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. */classCallService : Service() {overridefun onBind(intent: Intent?): IBinder? = nulloverridefun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {val engine = CallingEngine.of(this)var types = ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALLif (granted(Manifest.permission.RECORD_AUDIO)) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONEif (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 }privatefun granted(permission: String) = ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTEDcompanionobject {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)) } }}