Yokan / rebuild
Course 1 8624561

DownloadForegroundService.kt

composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadForegroundService.kt

implementation173 lines
1package eu.friedcutlet.yokan.services.download23import android.app.Notification4import android.app.NotificationManager5import android.app.PendingIntent6import android.app.Service7import android.content.Context8import android.content.Intent9import android.content.pm.ServiceInfo10import android.graphics.drawable.Icon11import android.os.Build12import android.os.IBinder13import android.net.Uri14import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace15import eu.friedcutlet.yokan.services.logging.AppLogger16import eu.friedcutlet.yokan.services.notifications.NotificationChannel17import eu.friedcutlet.yokan.services.notifications.ensureChannel18import kotlinx.coroutines.Job19import kotlinx.coroutines.Dispatchers20import kotlinx.coroutines.MainScope21import kotlinx.coroutines.cancel22import kotlinx.coroutines.delay23import kotlinx.coroutines.flow.combine24import kotlinx.coroutines.flow.conflate25import kotlinx.coroutines.launch26import kotlinx.coroutines.withContext2728/**29 * Keeps the process in the foreground while downloads are pending and mirrors their progress in an ongoing30 * notification on the Downloads channel. The downloads run in the app's services; this only reads and31 * cancels them, and stops itself once the queue drains. Without the notification permission it still runs;32 * only the notification stays hidden.33 */34class DownloadForegroundService : Service() {35    private val scope = MainScope()36    private var mirror: Job? = null37    private var foregroundBinding: ProfileDownloadBindings.Binding? = null3839    /** The newest start; stopping with it never drops a start that is still on its way. */40    private var lastStartId = 04142    override fun onBind(intent: Intent?): IBinder? = null4344    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {45        lastStartId = startId46        val requested = androidDownloadBindings.resolve(47            intent?.getStringExtra(ProfileWorkNamespace.OwnerKey),48            intent?.getStringExtra(ProfileDownloadBindings.TokenKey),49        )50        if (intent?.action == ACTION_CANCEL_ALL) {51            // A service started only for this action stays alive until the owner has handled it.52            if (mirror == null && requested != null) {53                scope.launch {54                    try { requested.run { it.cancelAll() } }55                    finally { if (mirror == null) stopSelf(startId) }56                }57            } else {58                requested?.cancelAll()59                // A live mirror stops its foreground service once that owner's queue drains.60                if (mirror == null) stopSelf(startId)61            }62            return START_NOT_STICKY63        }64        // One service has one foreground indicator. Never retarget a live mirror to another owner.65        val current = foregroundBinding?.takeIf { it.isActive }66        val binding = current ?: requested67        val downloads = binding?.downloads68        // Always first: a service started for the foreground must call startForeground, even to stop right away.69        val started = runCatching {70            val notification = notification(binding, downloads?.queueStatus?.value ?: DownloadQueueStatus(), downloads?.activeDownloadProgress?.value.orEmpty())71            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {72                startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)73            } else {74                startForeground(NOTIFICATION_ID, notification)75            }76        }.onFailure { AppLogger.warn("Download foreground service could not start: ${it.message.orEmpty()}") }77        if ((started.isFailure && mirror == null) || downloads == null || !needsKeepAlive(downloads.queueStatus.value)) {78            stopSelf(startId)79        } else if (mirror == null || current == null) {80            mirror?.cancel()81            foregroundBinding = binding82            mirror = scope.launch {83                try { binding.run { mirrorProgress(binding, it) } }84                finally {85                    if (foregroundBinding === binding) {86                        foregroundBinding = null87                        mirror = null88                        stopSelf(lastStartId)89                    }90                }91            }92        }93        return START_NOT_STICKY94    }9596    /** Android 15+ caps dataSync services at 6 hours a day; downloads carry on for as long as the process lives. */97    override fun onTimeout(startId: Int, fgsType: Int) {98        stopForeground(STOP_FOREGROUND_REMOVE)99        stopSelf()100    }101102    override fun onDestroy() {103        scope.cancel()104        super.onDestroy()105    }106107    private suspend fun mirrorProgress(binding: ProfileDownloadBindings.Binding, downloads: DownloadService) {108        combine(downloads.queueStatus, downloads.activeDownloadProgress) { status, active -> status to active }109            .conflate()110            .collect { (status, active) ->111                withContext(Dispatchers.Main.immediate) {112                    if (foregroundBinding === binding) {113                        if (!needsKeepAlive(status)) stopSelf(lastStartId)114                        else runCatching { getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification(binding, status, active)) }115                    }116                }117                // Android drops notification updates posted faster than a few per second.118                delay(UPDATE_INTERVAL_MS)119            }120    }121122    private fun notification(binding: ProfileDownloadBindings.Binding?, status: DownloadQueueStatus, active: List<DownloadProgress>): Notification {123        val channelId = checkNotNull(getSystemService(NotificationManager::class.java).ensureChannel(NotificationChannel.Downloads))124        val hidden = runCatching { binding?.hideContent?.invoke() == true }.getOrDefault(false)125        val current = (active.firstOrNull { !it.isPaused && !it.isCompleted } ?: active.firstOrNull())126            ?.let { if (hidden) it.copy(mangaName = "", chapterName = "") else it }127        val pages = current?.takeIf { it.total > 0 }?.let { "${it.succeeded}/${it.total}" }128        val cancelAll = PendingIntent.getService(129            this,130            0,131            ownerIntent(this, binding).setAction(ACTION_CANCEL_ALL),132            PendingIntent.FLAG_IMMUTABLE,133        )134        val open = packageManager.getLaunchIntentForPackage(packageName)135            ?.let { PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE) }136        return Notification.Builder(this, channelId)137            .setSmallIcon(applicationInfo.icon)138            .setOngoing(true)139            .setOnlyAlertOnce(true)140            .setContentTitle(current?.mangaName?.ifBlank { null } ?: "Downloading")141            .setContentText(listOfNotNull(current?.chapterName?.ifBlank { null }, pages).joinToString(" • "))142            .setSubText(if (status.pending > 1) "${status.pending} chapters left" else null)143            .setProgress(current?.total ?: 0, current?.succeeded ?: 0, pages == null)144            .setContentIntent(open)145            .apply { if (binding != null) addAction(Notification.Action.Builder(Icon.createWithResource(this@DownloadForegroundService, applicationInfo.icon), "Cancel all", cancelAll).build()) }146            .apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) }147            .build()148    }149150    internal companion object {151        private const val ACTION_CANCEL_ALL = "eu.friedcutlet.yokan.action.CANCEL_ALL_DOWNLOADS"152        private const val UPDATE_INTERVAL_MS = 1_000L153        private val NOTIFICATION_ID = "yokan_downloads:foreground".hashCode()154155        private fun ownerIntent(context: Context, binding: ProfileDownloadBindings.Binding?): Intent =156            Intent(context, DownloadForegroundService::class.java).apply {157                if (binding != null) {158                    data = Uri.parse(binding.actionIdentity)159                    putExtra(ProfileWorkNamespace.OwnerKey, binding.id.value)160                    putExtra(ProfileDownloadBindings.TokenKey, binding.token)161                }162            }163164        /**165         * Android 12+ refuses this from the background: downloads then continue while the process lives and166         * resume through the resume job or on the next launch.167         */168        fun start(context: Context, binding: ProfileDownloadBindings.Binding) {169            runCatching { context.startForegroundService(ownerIntent(context, binding)) }170                .onFailure { AppLogger.info("Downloads continue without a foreground service: ${it.message.orEmpty()}") }171        }172    }173}174

Search chapters, reference and source filenames.