package eu.friedcutlet.yokan.services.download import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo import android.graphics.drawable.Icon import android.os.Build import android.os.IBinder import android.net.Uri import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.notifications.NotificationChannel import eu.friedcutlet.yokan.services.notifications.ensureChannel import kotlinx.coroutines.Job import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Keeps the process in the foreground while downloads are pending and mirrors their progress in an ongoing * notification on the Downloads channel. The downloads run in the app's services; this only reads and * cancels them, and stops itself once the queue drains. Without the notification permission it still runs; * only the notification stays hidden. */ class DownloadForegroundService : Service() { private val scope = MainScope() private var mirror: Job? = null private var foregroundBinding: ProfileDownloadBindings.Binding? = null /** The newest start; stopping with it never drops a start that is still on its way. */ private var lastStartId = 0 override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { lastStartId = startId val requested = androidDownloadBindings.resolve( intent?.getStringExtra(ProfileWorkNamespace.OwnerKey), intent?.getStringExtra(ProfileDownloadBindings.TokenKey), ) if (intent?.action == ACTION_CANCEL_ALL) { // A service started only for this action stays alive until the owner has handled it. if (mirror == null && requested != null) { scope.launch { try { requested.run { it.cancelAll() } } finally { if (mirror == null) stopSelf(startId) } } } else { requested?.cancelAll() // A live mirror stops its foreground service once that owner's queue drains. if (mirror == null) stopSelf(startId) } return START_NOT_STICKY } // One service has one foreground indicator. Never retarget a live mirror to another owner. val current = foregroundBinding?.takeIf { it.isActive } val binding = current ?: requested val downloads = binding?.downloads // Always first: a service started for the foreground must call startForeground, even to stop right away. val started = runCatching { val notification = notification(binding, downloads?.queueStatus?.value ?: DownloadQueueStatus(), downloads?.activeDownloadProgress?.value.orEmpty()) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) } else { startForeground(NOTIFICATION_ID, notification) } }.onFailure { AppLogger.warn("Download foreground service could not start: ${it.message.orEmpty()}") } if ((started.isFailure && mirror == null) || downloads == null || !needsKeepAlive(downloads.queueStatus.value)) { stopSelf(startId) } else if (mirror == null || current == null) { mirror?.cancel() foregroundBinding = binding mirror = scope.launch { try { binding.run { mirrorProgress(binding, it) } } finally { if (foregroundBinding === binding) { foregroundBinding = null mirror = null stopSelf(lastStartId) } } } } return START_NOT_STICKY } /** Android 15+ caps dataSync services at 6 hours a day; downloads carry on for as long as the process lives. */ override fun onTimeout(startId: Int, fgsType: Int) { stopForeground(STOP_FOREGROUND_REMOVE) stopSelf() } override fun onDestroy() { scope.cancel() super.onDestroy() } private suspend fun mirrorProgress(binding: ProfileDownloadBindings.Binding, downloads: DownloadService) { combine(downloads.queueStatus, downloads.activeDownloadProgress) { status, active -> status to active } .conflate() .collect { (status, active) -> withContext(Dispatchers.Main.immediate) { if (foregroundBinding === binding) { if (!needsKeepAlive(status)) stopSelf(lastStartId) else runCatching { getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification(binding, status, active)) } } } // Android drops notification updates posted faster than a few per second. delay(UPDATE_INTERVAL_MS) } } private fun notification(binding: ProfileDownloadBindings.Binding?, status: DownloadQueueStatus, active: List): Notification { val channelId = checkNotNull(getSystemService(NotificationManager::class.java).ensureChannel(NotificationChannel.Downloads)) val hidden = runCatching { binding?.hideContent?.invoke() == true }.getOrDefault(false) val current = (active.firstOrNull { !it.isPaused && !it.isCompleted } ?: active.firstOrNull()) ?.let { if (hidden) it.copy(mangaName = "", chapterName = "") else it } val pages = current?.takeIf { it.total > 0 }?.let { "${it.succeeded}/${it.total}" } val cancelAll = PendingIntent.getService( this, 0, ownerIntent(this, binding).setAction(ACTION_CANCEL_ALL), PendingIntent.FLAG_IMMUTABLE, ) val open = packageManager.getLaunchIntentForPackage(packageName) ?.let { PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE) } return Notification.Builder(this, channelId) .setSmallIcon(applicationInfo.icon) .setOngoing(true) .setOnlyAlertOnce(true) .setContentTitle(current?.mangaName?.ifBlank { null } ?: "Downloading") .setContentText(listOfNotNull(current?.chapterName?.ifBlank { null }, pages).joinToString(" • ")) .setSubText(if (status.pending > 1) "${status.pending} chapters left" else null) .setProgress(current?.total ?: 0, current?.succeeded ?: 0, pages == null) .setContentIntent(open) .apply { if (binding != null) addAction(Notification.Action.Builder(Icon.createWithResource(this@DownloadForegroundService, applicationInfo.icon), "Cancel all", cancelAll).build()) } .apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) } .build() } internal companion object { private const val ACTION_CANCEL_ALL = "eu.friedcutlet.yokan.action.CANCEL_ALL_DOWNLOADS" private const val UPDATE_INTERVAL_MS = 1_000L private val NOTIFICATION_ID = "yokan_downloads:foreground".hashCode() private fun ownerIntent(context: Context, binding: ProfileDownloadBindings.Binding?): Intent = Intent(context, DownloadForegroundService::class.java).apply { if (binding != null) { data = Uri.parse(binding.actionIdentity) putExtra(ProfileWorkNamespace.OwnerKey, binding.id.value) putExtra(ProfileDownloadBindings.TokenKey, binding.token) } } /** * Android 12+ refuses this from the background: downloads then continue while the process lives and * resume through the resume job or on the next launch. */ fun start(context: Context, binding: ProfileDownloadBindings.Binding) { runCatching { context.startForegroundService(ownerIntent(context, binding)) } .onFailure { AppLogger.info("Downloads continue without a foreground service: ${it.message.orEmpty()}") } } } }