feat(mobile): keep downloads going in the background (#143)
This commit was merged in pull request #143.
This commit is contained in:
1 parent
682aff44fa
commit
d7d476e5ec
15 files changed
+490
-19
No files matched your search
@@ -32,6 +32,13 @@ export default ({ config }: ConfigContext): ExpoConfig => {
|
||||
...config,
|
||||
plugins: [
|
||||
...(config.plugins ?? []),
|
||||
[
|
||||
"react-native-continued-task",
|
||||
{
|
||||
// Matches TASK_PREFIX in hooks/use-background-downloads.ts.
|
||||
identifierPrefixes: [`${bundleIdentifier}.downloads`],
|
||||
},
|
||||
],
|
||||
...(process.env.MAC_CATALYST === "1"
|
||||
? ["./plugins/with-mac-catalyst"]
|
||||
: []),
|
||||
|
||||
@@ -25,6 +25,7 @@ import { AndroidSheet } from "@/components/android-sheet"
|
||||
import { AudioFormatBadge } from "@/components/audio-format-badge"
|
||||
import { useCacheScope } from "@/contexts/persistent-cache"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useBackgroundDownloads } from "@/hooks/use-background-downloads"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { getAuthCookieHeader } from "@/lib/auth-cookies"
|
||||
import {
|
||||
@@ -344,6 +345,7 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
|
||||
target: DownloadTarget
|
||||
response: DownloadOptionsResponse
|
||||
} | null>(null)
|
||||
const keepDownloading = useBackgroundDownloads(queue)
|
||||
|
||||
useEffect(() => {
|
||||
if (!queue) return
|
||||
@@ -391,6 +393,7 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
|
||||
const remembered = await readRememberedDownloadQuality()
|
||||
if (remembered) {
|
||||
await startDownload(queue, target, response.songs, remembered)
|
||||
keepDownloading()
|
||||
toast(`Downloading ${target.title}`)
|
||||
} else {
|
||||
setPending({ target, response })
|
||||
@@ -399,7 +402,7 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
|
||||
showError(error instanceof Error ? error.message : "Download failed")
|
||||
}
|
||||
},
|
||||
[cacheScope, config, convex, queue]
|
||||
[cacheScope, config, convex, keepDownloading, queue]
|
||||
)
|
||||
|
||||
const removeDownload = useCallback(
|
||||
@@ -417,9 +420,14 @@ export function DownloadsProvider({ children }: { children: ReactNode }) {
|
||||
if (!pending || !queue) return
|
||||
setPending(null)
|
||||
if (remember) void writeRememberedDownloadQuality(quality)
|
||||
void startDownload(queue, pending.target, pending.response.songs, quality)
|
||||
void startDownload(
|
||||
queue,
|
||||
pending.target,
|
||||
pending.response.songs,
|
||||
quality
|
||||
).then(keepDownloading)
|
||||
},
|
||||
[pending, queue]
|
||||
[keepDownloading, pending, queue]
|
||||
)
|
||||
|
||||
const value = useMemo(
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
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(), [])
|
||||
}
|
||||
@@ -16,9 +16,16 @@ function authCookieNames(serverUrl: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cookies that sign a request to the server in. Pass `refresh: false` for
|
||||
* requests that may run after the JWT expires (iOS background downloads): the
|
||||
* server would spend the refresh token, and the app's next refresh of the same
|
||||
* token would then end the session.
|
||||
*/
|
||||
export async function getAuthCookieHeader(
|
||||
serverUrl: string,
|
||||
convexUrl: string
|
||||
convexUrl: string,
|
||||
{ refresh = true }: { refresh?: boolean } = {}
|
||||
): Promise<string | null> {
|
||||
const [jwt, refreshToken] = await Promise.all([
|
||||
secureGetItem(authStorageKey(JWT_STORAGE_KEY, convexUrl)),
|
||||
@@ -31,7 +38,7 @@ export async function getAuthCookieHeader(
|
||||
|
||||
const names = authCookieNames(serverUrl)
|
||||
const parts = [`${names.jwt}=${jwt}`]
|
||||
if (refreshToken) {
|
||||
if (refresh && refreshToken) {
|
||||
parts.push(`${names.refresh}=${refreshToken}`)
|
||||
}
|
||||
|
||||
|
||||
@@ -12,19 +12,28 @@ const secureStoreOptions: SecureStore.SecureStoreOptions = {
|
||||
keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK,
|
||||
}
|
||||
|
||||
// The last value read or written per key, for when the keychain refuses a
|
||||
// read (say, while the phone is locked and downloads continue).
|
||||
const remembered = new Map<string, string>()
|
||||
|
||||
export async function secureGetItem(key: string): Promise<string | null> {
|
||||
try {
|
||||
return await SecureStore.getItemAsync(key, secureStoreOptions)
|
||||
const value = await SecureStore.getItemAsync(key, secureStoreOptions)
|
||||
if (value === null) remembered.delete(key)
|
||||
else remembered.set(key, value)
|
||||
return value
|
||||
} catch {
|
||||
return null
|
||||
return remembered.get(key) ?? null
|
||||
}
|
||||
}
|
||||
|
||||
export async function secureSetItem(key: string, value: string): Promise<void> {
|
||||
remembered.set(key, value)
|
||||
await SecureStore.setItemAsync(key, value, secureStoreOptions)
|
||||
}
|
||||
|
||||
export async function secureRemoveItem(key: string): Promise<void> {
|
||||
remembered.delete(key)
|
||||
try {
|
||||
await SecureStore.deleteItemAsync(key, secureStoreOptions)
|
||||
} catch {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage"
|
||||
import { Directory, File, Paths } from "expo-file-system"
|
||||
import { Directory, DownloadTask, File, Paths } from "expo-file-system"
|
||||
import { Platform } from "react-native"
|
||||
|
||||
import {
|
||||
@@ -73,6 +73,82 @@ function audioFile(folder: Directory) {
|
||||
return folder.list().find((entry): entry is File => entry instanceof File)
|
||||
}
|
||||
|
||||
type SongDownload = {
|
||||
url: string
|
||||
destination: Directory
|
||||
headers: Record<string, string>
|
||||
signal: AbortSignal
|
||||
/** Checks and keeps the downloaded file, returning its size. */
|
||||
finish: (file: File) => number
|
||||
}
|
||||
|
||||
// Whether a continued processing task keeps the app running in the
|
||||
// background (iOS 26+, see `useBackgroundDownloads`).
|
||||
let keptRunning = false
|
||||
const regularSessionDownloads = new Set<() => void>()
|
||||
|
||||
/**
|
||||
* While a continued task keeps the app running, songs download through the
|
||||
* regular session: iOS treats background session downloads started from the
|
||||
* background as deferrable until Wi-Fi and power. When the task ends, running
|
||||
* songs restart in the background session before iOS suspends the app.
|
||||
*/
|
||||
export function setKeptRunning(running: boolean) {
|
||||
keptRunning = running
|
||||
if (!running) for (const handOff of regularSessionDownloads) handOff()
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads through an iOS URL session. The background one keeps going while
|
||||
* the app is suspended and wakes it when done; iOS keeps the app awake until
|
||||
* `finish` returns (up to 25 seconds). Downloads still running when iOS
|
||||
* terminates the app are lost.
|
||||
*/
|
||||
async function runDownloadTask(
|
||||
{ url, destination, headers, signal, finish }: SongDownload,
|
||||
sessionType: "foreground" | "background"
|
||||
) {
|
||||
const task = new DownloadTask(url, destination, {
|
||||
headers,
|
||||
signal,
|
||||
sessionType,
|
||||
deferBackgroundSessionCompletion: sessionType === "background",
|
||||
})
|
||||
const handOff = () => task.cancel()
|
||||
if (sessionType === "foreground") regularSessionDownloads.add(handOff)
|
||||
try {
|
||||
const file = await task.downloadAsync()
|
||||
if (!file) throw new Error("Download paused")
|
||||
return finish(file)
|
||||
} finally {
|
||||
regularSessionDownloads.delete(handOff)
|
||||
if (task.state === "completed") {
|
||||
await task.acknowledgeBackgroundCompletionAsync().catch(() => {})
|
||||
}
|
||||
task.release()
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadOnIOS(download: SongDownload) {
|
||||
if (keptRunning) {
|
||||
try {
|
||||
return await runDownloadTask(download, "foreground")
|
||||
} catch (error) {
|
||||
// Still running means a real failure; otherwise it was handed off.
|
||||
if (keptRunning || download.signal.aborted) throw error
|
||||
}
|
||||
}
|
||||
return runDownloadTask(download, "background")
|
||||
}
|
||||
|
||||
/** Android keeps the app running with a foreground service instead. */
|
||||
async function downloadInForeground(download: SongDownload) {
|
||||
const { url, destination, headers, signal, finish } = download
|
||||
return finish(
|
||||
await File.downloadFileAsync(url, destination, { headers, signal })
|
||||
)
|
||||
}
|
||||
|
||||
function createStorage(config: ServerConfig): DownloadStorage {
|
||||
const root = serverDirectory(config)
|
||||
const indexFile = new File(root, "index.json")
|
||||
@@ -116,7 +192,8 @@ function createStorage(config: ServerConfig): DownloadStorage {
|
||||
async save({ songId, requested, quality, albumId }, signal) {
|
||||
const cookieHeader = await getAuthCookieHeader(
|
||||
config.serverUrl,
|
||||
config.convexUrl
|
||||
config.convexUrl,
|
||||
{ refresh: Platform.OS !== "ios" }
|
||||
)
|
||||
if (!cookieHeader) throw new Error("Sign in to download")
|
||||
|
||||
@@ -126,17 +203,26 @@ function createStorage(config: ServerConfig): DownloadStorage {
|
||||
if (partial.exists) partial.delete()
|
||||
partial.create()
|
||||
try {
|
||||
const path = songDownloadPath(songId, requested, {
|
||||
const url = `${config.serverUrl}${songDownloadPath(songId, requested, {
|
||||
losslessFormat: Platform.OS === "ios" ? "alac" : undefined,
|
||||
})}`
|
||||
const download =
|
||||
Platform.OS === "ios" ? downloadOnIOS : downloadInForeground
|
||||
return await download({
|
||||
url,
|
||||
destination: partial,
|
||||
headers: { Cookie: cookieHeader },
|
||||
signal,
|
||||
finish(file) {
|
||||
signal.throwIfAborted()
|
||||
// A lapsed sign-in redirects to the sign-in page instead of failing.
|
||||
if (file.extension === ".html") {
|
||||
throw new Error("Sign in to download")
|
||||
}
|
||||
partial.rename(name)
|
||||
return file.size ?? 0
|
||||
},
|
||||
})
|
||||
const file = await File.downloadFileAsync(
|
||||
`${config.serverUrl}${path}`,
|
||||
partial,
|
||||
{ headers: { Cookie: cookieHeader }, signal }
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
partial.rename(name)
|
||||
return file.size ?? 0
|
||||
} catch (error) {
|
||||
if (partial.exists) partial.delete()
|
||||
throw error
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
plugins {
|
||||
id 'com.android.library'
|
||||
id 'expo-module-gradle-plugin'
|
||||
}
|
||||
|
||||
group = 'expo.modules.downloadservice'
|
||||
version = '1.0.0'
|
||||
|
||||
android {
|
||||
namespace 'expo.modules.downloadservice'
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
|
||||
<application>
|
||||
<service
|
||||
android:name="expo.modules.downloadservice.DownloadService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
</application>
|
||||
</manifest>
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package expo.modules.downloadservice
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
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.os.Build
|
||||
import android.os.IBinder
|
||||
|
||||
/**
|
||||
* Keeps the app running while songs download, so Android does not freeze the
|
||||
* JS downloads when the app leaves the screen. Started with the number of
|
||||
* songs left, and stopped by the module once none are.
|
||||
*/
|
||||
class DownloadService : Service() {
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
val remaining = intent?.getIntExtra(EXTRA_REMAINING, 0) ?: 0
|
||||
val notification = notification(remaining)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
|
||||
} else {
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
}
|
||||
// A restarted service would have no downloads to keep alive.
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
// Android 15 limits data sync services to six hours a day.
|
||||
override fun onTimeout(startId: Int, fgsType: Int) {
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
private fun notification(remaining: Int): Notification {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(CHANNEL_ID, "Downloads", NotificationManager.IMPORTANCE_LOW)
|
||||
)
|
||||
}
|
||||
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
Notification.Builder(this, CHANNEL_ID)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
Notification.Builder(this)
|
||||
}
|
||||
val launch = packageManager.getLaunchIntentForPackage(packageName)?.let {
|
||||
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE)
|
||||
}
|
||||
return builder
|
||||
.setSmallIcon(android.R.drawable.stat_sys_download)
|
||||
.setContentTitle(if (remaining == 1) "Downloading 1 song" else "Downloading $remaining songs")
|
||||
.setContentIntent(launch)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.build()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "downloads"
|
||||
private const val NOTIFICATION_ID = 7301
|
||||
private const val EXTRA_REMAINING = "remaining"
|
||||
|
||||
fun update(context: Context, remaining: Int) {
|
||||
val intent = Intent(context, DownloadService::class.java)
|
||||
if (remaining == 0) {
|
||||
context.stopService(intent)
|
||||
return
|
||||
}
|
||||
intent.putExtra(EXTRA_REMAINING, remaining)
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
context.startForegroundService(intent)
|
||||
} else {
|
||||
context.startService(intent)
|
||||
}
|
||||
} catch (_: IllegalStateException) {
|
||||
// Android 12+ refuses to start one from the background (say, a
|
||||
// playlist syncing); downloads then run only while the app does.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package expo.modules.downloadservice
|
||||
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
|
||||
class DownloadServiceModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("DownloadService")
|
||||
|
||||
/** Shows how many songs are left, or stops the service at zero. */
|
||||
Function("update") { remaining: Int ->
|
||||
DownloadService.update(requireNotNull(appContext.reactContext), remaining)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"platforms": ["android"],
|
||||
"android": {
|
||||
"modules": ["expo.modules.downloadservice.DownloadServiceModule"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "otunes-download-service",
|
||||
"version": "1.0.0",
|
||||
"private": true
|
||||
}
|
||||
@@ -48,8 +48,10 @@
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0",
|
||||
"react-native": "0.88.0",
|
||||
"react-native-continued-task": "0.1.0",
|
||||
"react-native-gesture-handler": "~3.3.0",
|
||||
"react-native-image-colors": "^2.6.0",
|
||||
"react-native-nitro-modules": "0.37.2",
|
||||
"react-native-reanimated": "4.7.1",
|
||||
"react-native-safe-area-context": "~5.10.1",
|
||||
"react-native-screens": "4.30.0",
|
||||
|
||||
@@ -125,8 +125,9 @@ function collectionKey({ kind, id }: CollectionRef) {
|
||||
*/
|
||||
export function createDownloadQueue(
|
||||
storage: DownloadStorage,
|
||||
{ concurrency = 2 }: { concurrency?: number } = {}
|
||||
options: { concurrency?: number } = {}
|
||||
) {
|
||||
let concurrency = options.concurrency ?? 2
|
||||
const downloaded = new Map<string, DownloadedSong>()
|
||||
const collections = new Map<string, DownloadedCollection>()
|
||||
const otherSongIds = new Set<string>()
|
||||
@@ -372,6 +373,17 @@ export function createDownloadQueue(
|
||||
collections: () => [...collections.values()],
|
||||
isQueued,
|
||||
status,
|
||||
/** Songs downloading or waiting to. */
|
||||
pendingCount: () => running.size + waiting.length,
|
||||
|
||||
/**
|
||||
* How many songs download at once. Raising it starts waiting songs now;
|
||||
* lowering it lets running songs finish.
|
||||
*/
|
||||
setConcurrency(limit: number) {
|
||||
concurrency = limit
|
||||
pump()
|
||||
},
|
||||
|
||||
/** Songs downloaded on their own, in the order they were added. */
|
||||
otherSongIds: () => [...otherSongIds],
|
||||
|
||||
Generated
+40
@@ -363,12 +363,18 @@ importers:
|
||||
react-native:
|
||||
specifier: 0.88.0
|
||||
version: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
|
||||
react-native-continued-task:
|
||||
specifier: 0.1.0
|
||||
version: 0.1.0(react-native-nitro-modules@0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
|
||||
react-native-gesture-handler:
|
||||
specifier: ~3.3.0
|
||||
version: 3.3.0(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
|
||||
react-native-image-colors:
|
||||
specifier: ^2.6.0
|
||||
version: 2.6.0(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1)
|
||||
react-native-nitro-modules:
|
||||
specifier: 0.37.2
|
||||
version: 0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
|
||||
react-native-reanimated:
|
||||
specifier: 4.7.1
|
||||
version: 4.7.1(patch_hash=badfed6babfff7fa495b3a06ba8f324be0e5ff82cedb6084f9f4d1dad65984d3)(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
|
||||
@@ -5438,6 +5444,9 @@ packages:
|
||||
sass:
|
||||
optional: true
|
||||
|
||||
nitro-core@0.37.2:
|
||||
resolution: {integrity: sha512-dhagikz9VXXzfidRH/vPNJfYWPmTBArDOo9wE/wEqeERU9C8uRWz9YccOyNUOvADccPAZq319yzhDMoJ9excSQ==}
|
||||
|
||||
node-exports-info@1.6.2:
|
||||
resolution: {integrity: sha512-kXs9Go0cah0qHVV2v389IXQLdLCeE1xfFtjOAF+iobu0OIoG1pje8At2vMHyaPMiPMnG/LWP50twML21eMcAag==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -5889,6 +5898,16 @@ packages:
|
||||
react-is@19.2.7:
|
||||
resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==}
|
||||
|
||||
react-native-continued-task@0.1.0:
|
||||
resolution: {integrity: sha512-6x9YesK++u6vraaReebWEKbcDjMeRInsQzd+uWXAbNiXasgZ2zulTextzK/zBZ2mBrCZqTZVK60eoPp07BF0MA==}
|
||||
peerDependencies:
|
||||
react: '*'
|
||||
react-native: '*'
|
||||
react-native-nitro-modules: '*'
|
||||
peerDependenciesMeta:
|
||||
react-native-nitro-modules:
|
||||
optional: true
|
||||
|
||||
react-native-drawer-layout@4.2.12:
|
||||
resolution: {integrity: sha512-qYmntEctkMSodN7pnC2llV21nswImLFPHJeT3PJXSJqZdU4jzDATR8iVi66sXkrtoOLJ2+EvXxgd7sMMpV4ViA==}
|
||||
peerDependencies:
|
||||
@@ -5916,6 +5935,12 @@ packages:
|
||||
react: '*'
|
||||
react-native: '*'
|
||||
|
||||
react-native-nitro-modules@0.37.2:
|
||||
resolution: {integrity: sha512-Odnrq/p6/q0R01qZlkqeXu9VHHMuGEnZZmyxMvehEu6QiACNHhBCmAHgyBDqOSo9Lb3G0TscFAT+HG0uxsR/GA==}
|
||||
peerDependencies:
|
||||
react: '*'
|
||||
react-native: '*'
|
||||
|
||||
react-native-reanimated@4.7.1:
|
||||
resolution: {integrity: sha512-HviDFSZ6V4KTRsrLS6hRbBJ4j63l/L8a5az0EoWdJwaMLYnBNyYISTDxwXpEYkMbAbLzCMCviIdiOxXHYQWcNA==}
|
||||
peerDependencies:
|
||||
@@ -12473,6 +12498,8 @@ snapshots:
|
||||
- '@types/node'
|
||||
- babel-plugin-macros
|
||||
|
||||
nitro-core@0.37.2: {}
|
||||
|
||||
node-exports-info@1.6.2:
|
||||
dependencies:
|
||||
array.prototype.flatmap: 1.3.3
|
||||
@@ -12936,6 +12963,13 @@ snapshots:
|
||||
|
||||
react-is@19.2.7: {}
|
||||
|
||||
react-native-continued-task@0.1.0(react-native-nitro-modules@0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0):
|
||||
dependencies:
|
||||
react: 19.3.0
|
||||
react-native: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
|
||||
optionalDependencies:
|
||||
react-native-nitro-modules: 0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)
|
||||
|
||||
react-native-drawer-layout@4.2.12(309f9235979e0472ca5a2d24f8d225b6):
|
||||
dependencies:
|
||||
color: 4.2.3
|
||||
@@ -12967,6 +13001,12 @@ snapshots:
|
||||
react: 19.3.0
|
||||
react-native: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
|
||||
|
||||
react-native-nitro-modules@0.37.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0):
|
||||
dependencies:
|
||||
nitro-core: 0.37.2
|
||||
react: 19.3.0
|
||||
react-native: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1)
|
||||
|
||||
react-native-reanimated@4.7.1(patch_hash=badfed6babfff7fa495b3a06ba8f324be0e5ff82cedb6084f9f4d1dad65984d3)(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1))(react@19.3.0):
|
||||
dependencies:
|
||||
react: 19.3.0
|
||||
|
||||
Reference in new issue
Block a user