iOS songs download through a background URL session, and on iOS 26+ a continued processing task keeps the app running with a Live Activity. Android keeps the app alive with a dataSync foreground service while songs are queued. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
165 lines
5.1 KiB
TypeScript
165 lines
5.1 KiB
TypeScript
import { requireOptionalNativeModule } from "expo"
|
|
import Constants from "expo-constants"
|
|
import { useCallback, useEffect, useRef } from "react"
|
|
import { AppState, Platform } from "react-native"
|
|
import {
|
|
ContinuedTasks,
|
|
type ContinuedTask,
|
|
} from "react-native-continued-task"
|
|
|
|
import { setKeptRunning } from "@/lib/downloads"
|
|
import type { DownloadQueue } from "@otunes/convex/client/download-queue"
|
|
|
|
const downloadService = requireOptionalNativeModule<{
|
|
update: (remaining: number) => void
|
|
}>("DownloadService")
|
|
|
|
/** Songs downloading at once while the app runs, as the queue defaults to. */
|
|
const RUNNING_CONCURRENCY = 2
|
|
|
|
// Stopping right after starting can beat the service to `startForeground`,
|
|
// which Android treats as a crash.
|
|
const STOP_DELAY_MS = 2000
|
|
|
|
// Must match `identifierPrefixes` in app.config.ts.
|
|
const TASK_PREFIX = `${Constants.expoConfig?.ios?.bundleIdentifier}.downloads`
|
|
|
|
function songsLeft(count: number) {
|
|
return count === 1 ? "1 song left" : `${count} songs left`
|
|
}
|
|
|
|
/**
|
|
* Keeps downloads going while the app is in the background. Call the returned
|
|
* function right after the person starts a download.
|
|
*
|
|
* iOS 26+: a continued processing task keeps the app running, with progress
|
|
* in a Live Activity, so songs keep downloading a few at a time with fresh
|
|
* sign-in tokens. It must start from the person's action, so it covers
|
|
* downloads they start, not playlist syncs.
|
|
*
|
|
* iOS otherwise (and once that task ends): songs download in a background URL
|
|
* session. Songs started while suspended may wait for Wi-Fi and power, so
|
|
* every waiting song is handed over as the app leaves the screen.
|
|
*
|
|
* Android: a foreground service keeps the app running while songs are queued.
|
|
*/
|
|
export function useBackgroundDownloads(queue: DownloadQueue | null) {
|
|
const startTask = useRef<() => void>(() => {})
|
|
|
|
useEffect(() => {
|
|
if (!queue) return
|
|
|
|
if (Platform.OS === "ios") {
|
|
let active = AppState.currentState === "active"
|
|
let task: ContinuedTask | null = null
|
|
let submitting = false
|
|
let total = 0
|
|
let lastPending = 0
|
|
|
|
const updateConcurrency = () =>
|
|
queue.setConcurrency(
|
|
active || task?.state === "running" ? RUNNING_CONCURRENCY : Infinity
|
|
)
|
|
|
|
const end = () => {
|
|
task = null
|
|
setKeptRunning(false)
|
|
updateConcurrency()
|
|
}
|
|
|
|
const report = () => {
|
|
const pending = queue.pendingCount()
|
|
if (pending > lastPending) total += pending - lastPending
|
|
lastPending = pending
|
|
if (task?.state !== "running") return
|
|
if (pending === 0) {
|
|
task.complete(true)
|
|
end()
|
|
return
|
|
}
|
|
task.setProgress(total - pending, total)
|
|
task.updateTitle("Downloading", songsLeft(pending))
|
|
}
|
|
|
|
startTask.current = () => {
|
|
if (!ContinuedTasks.isSupported || task || submitting) return
|
|
const pending = queue.pendingCount()
|
|
if (pending === 0) return
|
|
submitting = true
|
|
total = pending
|
|
lastPending = pending
|
|
ContinuedTasks.submit({
|
|
identifierPrefix: TASK_PREFIX,
|
|
title: "Downloading",
|
|
subtitle: songsLeft(pending),
|
|
totalUnitCount: total,
|
|
// A task that cannot start now is no use once the app is closed.
|
|
ios: { submissionStrategy: "fail" },
|
|
})
|
|
.then((submitted) => {
|
|
task = submitted
|
|
submitted.addOnStartListener(() => {
|
|
setKeptRunning(true)
|
|
updateConcurrency()
|
|
report()
|
|
})
|
|
// iOS reports a cancel from the Live Activity as expiry too, so
|
|
// either way the songs carry on in the background session.
|
|
submitted.addOnStopListener(() => {
|
|
if (task === submitted) end()
|
|
})
|
|
})
|
|
.catch(() => {
|
|
// Not permitted or unavailable: the background session covers it.
|
|
})
|
|
.finally(() => {
|
|
submitting = false
|
|
})
|
|
}
|
|
|
|
updateConcurrency()
|
|
const unsubscribe = queue.subscribe(report)
|
|
const subscription = AppState.addEventListener("change", (state) => {
|
|
active = state === "active"
|
|
updateConcurrency()
|
|
})
|
|
return () => {
|
|
startTask.current = () => {}
|
|
unsubscribe()
|
|
subscription.remove()
|
|
task?.cancel()
|
|
end()
|
|
}
|
|
}
|
|
|
|
if (!downloadService) return
|
|
const service = downloadService
|
|
let shown = 0
|
|
let stopTimer: ReturnType<typeof setTimeout> | null = null
|
|
const update = () => {
|
|
const remaining = queue.pendingCount()
|
|
if (remaining === shown) return
|
|
if (stopTimer) clearTimeout(stopTimer)
|
|
stopTimer = null
|
|
if (remaining > 0) {
|
|
shown = remaining
|
|
service.update(remaining)
|
|
} else {
|
|
stopTimer = setTimeout(() => {
|
|
shown = 0
|
|
service.update(0)
|
|
}, STOP_DELAY_MS)
|
|
}
|
|
}
|
|
update()
|
|
const unsubscribe = queue.subscribe(update)
|
|
return () => {
|
|
unsubscribe()
|
|
if (stopTimer) clearTimeout(stopTimer)
|
|
service.update(0)
|
|
}
|
|
}, [queue])
|
|
|
|
return useCallback(() => startTask.current(), [])
|
|
}
|