# Download Management
**Referenced Files in This Document**
- [DownloadService.kt](file://app/src/main/java/com/suvojeet/suvmusic/service/DownloadService.kt)
- [DownloadRepository.kt](file://app/src/main/java/com/suvojeet/suvmusic/data/repository/DownloadRepository.kt)
- [DownloadQuality.kt](file://app/src/main/java/com/suvojeet/suvmusic/data/model/DownloadQuality.kt)
- [AudioQuality.kt](file://app/src/main/java/com/suvojeet/suvmusic/data/model/AudioQuality.kt)
- [DownloadsScreen.kt](file://app/src/main/java/com/suvojeet/suvmusic/ui/screens/DownloadsScreen.kt)
- [DownloadsViewModel.kt](file://app/src/main/java/com/suvojeet/suvmusic/ui/viewmodel/DownloadsViewModel.kt)
- [NetworkMonitor.kt](file://app/src/main/java/com/suvojeet/suvmusic/util/NetworkMonitor.kt)
- [NewPipeDownloaderImpl.kt](file://extractor/src/main/java/com/suvojeet/suvmusic/newpipe/NewPipeDownloaderImpl.kt)
- [LikedSongsSyncWorker.kt](file://app/src/main/java/com/suvojeet/suvmusic/data/worker/LikedSongsSyncWorker.kt)
- [NewReleaseWorker.kt](file://app/src/main/java/com/suvojeet/suvmusic/workers/NewReleaseWorker.kt)
## Table of Contents
1. [Introduction](#introduction)
2. [Project Structure](#project-structure)
3. [Core Components](#core-components)
4. [Architecture Overview](#architecture-overview)
5. [Detailed Component Analysis](#detailed-component-analysis)
6. [Dependency Analysis](#dependency-analysis)
7. [Performance Considerations](#performance-considerations)
8. [Troubleshooting Guide](#troubleshooting-guide)
9. [Conclusion](#conclusion)
10. [Appendices](#appendices)
## Introduction
This document explains SuvMusic’s download management system with a focus on:
- Download queue architecture and background service lifecycle
- Offline playback support and storage management
- WorkManager-based scheduling for related tasks
- Network-awareness and bandwidth optimization
- Download quality selection and format handling
- Progress tracking, error recovery, caching, and cleanup
- User storage preferences and concurrent download controls
## Project Structure
The download system spans three layers:
- UI: Screens and ViewModels that present downloads, selections, and actions
- Repository: Centralized download orchestration, queue management, storage, and progress
- Service: Foreground service for continuous background downloads and notifications
```mermaid
graph TB
subgraph "UI Layer"
DS["DownloadsScreen.kt"]
DVM["DownloadsViewModel.kt"]
end
subgraph "Repository Layer"
DR["DownloadRepository.kt"]
NWM["NetworkMonitor.kt"]
end
subgraph "Service Layer"
DLS["DownloadService.kt"]
end
subgraph "Workers"
LSW["LikedSongsSyncWorker.kt"]
NRW["NewReleaseWorker.kt"]
end
subgraph "Extractor"
NPDI["NewPipeDownloaderImpl.kt"]
end
DS --> DVM
DVM --> DR
DR --> DLS
DR --> NWM
DR -. uses .-> NPDI
LSW -. schedules .-> DR
NRW -. schedules .-> DR
```
**Diagram sources**
- [DownloadsScreen.kt:103-109](file://app/src/main/java/com/suvojeet/suvmusic/ui/screens/DownloadsScreen.kt#L103-L109)
- [DownloadsViewModel.kt:18-27](file://app/src/main/java/com/suvojeet/suvmusic/ui/viewmodel/DownloadsViewModel.kt#L18-L27)
- [DownloadRepository.kt:39-46](file://app/src/main/java/com/suvojeet/suvmusic/data/repository/DownloadRepository.kt#L39-L46)
- [DownloadService.kt:33-94](file://app/src/main/java/com/suvojeet/suvmusic/service/DownloadService.kt#L33-L94)
- [NetworkMonitor.kt:20-24](file://app/src/main/java/com/suvojeet/suvmusic/util/NetworkMonitor.kt#L20-L24)
- [NewPipeDownloaderImpl.kt:16-19](file://extractor/src/main/java/com/suvojeet/suvmusic/newpipe/NewPipeDownloaderImpl.kt#L16-L19)
- [LikedSongsSyncWorker.kt:12-16](file://app/src/main/java/com/suvojeet/suvmusic/data/worker/LikedSongsSyncWorker.kt#L12-L16)
- [NewReleaseWorker.kt:22-27](file://app/src/main/java/com/suvojeet/suvmusic/workers/NewReleaseWorker.kt#L22-L27)
**Section sources**
- [DownloadsScreen.kt:103-109](file://app/src/main/java/com/suvojeet/suvmusic/ui/screens/DownloadsScreen.kt#L103-L109)
- [DownloadsViewModel.kt:18-27](file://app/src/main/java/com/suvojeet/suvmusic/ui/viewmodel/DownloadsViewModel.kt#L18-L27)
- [DownloadRepository.kt:39-46](file://app/src/main/java/com/suvojeet/suvmusic/data/repository/DownloadRepository.kt#L39-L46)
- [DownloadService.kt:33-94](file://app/src/main/java/com/suvojeet/suvmusic/service/DownloadService.kt#L33-L94)
- [NetworkMonitor.kt:20-24](file://app/src/main/java/com/suvojeet/suvmusic/util/NetworkMonitor.kt#L20-L24)
- [NewPipeDownloaderImpl.kt:16-19](file://extractor/src/main/java/com/suvojeet/suvmusic/newpipe/NewPipeDownloaderImpl.kt#L16-L19)
- [LikedSongsSyncWorker.kt:12-16](file://app/src/main/java/com/suvojeet/suvmusic/data/worker/LikedSongsSyncWorker.kt#L12-L16)
- [NewReleaseWorker.kt:22-27](file://app/src/main/java/com/suvojeet/suvmusic/workers/NewReleaseWorker.kt#L22-L27)
## Core Components
- DownloadService: Foreground service that processes the download queue, updates progress notifications, and handles cancellation.
- DownloadRepository: Orchestrates downloads, manages queues, tracks progress, persists metadata, writes files to storage, and cleans up caches.
- DownloadsScreen and DownloadsViewModel: Present downloads, collections, selection, and trigger deletion and refresh actions.
- NetworkMonitor: Provides connectivity and Wi-Fi awareness for network-aware decisions.
- NewPipeDownloaderImpl: Bridges NewPipeExtractor with OkHttp for authenticated extraction and rate-limit handling.
- Workers: Scheduled tasks for syncing liked songs and notifying new releases (not direct downloads, but part of the ecosystem).
**Section sources**
- [DownloadService.kt:33-305](file://app/src/main/java/com/suvojeet/suvmusic/service/DownloadService.kt#L33-L305)
- [DownloadRepository.kt:39-1301](file://app/src/main/java/com/suvojeet/suvmusic/data/repository/DownloadRepository.kt#L39-L1301)
- [DownloadsScreen.kt:103-109](file://app/src/main/java/com/suvojeet/suvmusic/ui/screens/DownloadsScreen.kt#L103-L109)
- [DownloadsViewModel.kt:18-152](file://app/src/main/java/com/suvojeet/suvmusic/ui/viewmodel/DownloadsViewModel.kt#L18-L152)
- [NetworkMonitor.kt:20-98](file://app/src/main/java/com/suvojeet/suvmusic/util/NetworkMonitor.kt#L20-L98)
- [NewPipeDownloaderImpl.kt:16-112](file://extractor/src/main/java/com/suvojeet/suvmusic/newpipe/NewPipeDownloaderImpl.kt#L16-L112)
- [LikedSongsSyncWorker.kt:12-34](file://app/src/main/java/com/suvojeet/suvmusic/data/worker/LikedSongsSyncWorker.kt#L12-L34)
- [NewReleaseWorker.kt:22-132](file://app/src/main/java/com/suvojeet/suvmusic/workers/NewReleaseWorker.kt#L22-L132)
## Architecture Overview
The system uses a foreground service to continuously drain a concurrent queue, delegating actual download work to the repository. The repository streams data via OkHttp, writes to storage using MediaStore or public folders, embeds metadata, and maintains progress and queue state. UI observes repository state to render lists, collections, and progress.
```mermaid
sequenceDiagram
participant UI as "DownloadsScreen"
participant VM as "DownloadsViewModel"
participant Repo as "DownloadRepository"
participant Svc as "DownloadService"
participant Net as "NetworkMonitor"
UI->>VM : "User triggers download/add to queue"
VM->>Repo : "downloadSongToQueue(...)"
Repo->>Svc : "startBatchDownload(context)"
Svc->>Repo : "popFromQueue()"
Repo->>Net : "observe connectivity (optional)"
Repo->>Repo : "downloadUsingSharedCache(...)"
Repo-->>Svc : "update downloadProgress"
Svc->>Svc : "updateForegroundNotification(...)"
Repo-->>VM : "downloadedSongs, queueState, progress"
VM-->>UI : "Compose UI updates"
```
**Diagram sources**
- [DownloadService.kt:164-211](file://app/src/main/java/com/suvojeet/suvmusic/service/DownloadService.kt#L164-L211)
- [DownloadRepository.kt:1250-1262](file://app/src/main/java/com/suvojeet/suvmusic/data/repository/DownloadRepository.kt#L1250-L1262)
- [DownloadsViewModel.kt:29-81](file://app/src/main/java/com/suvojeet/suvmusic/ui/viewmodel/DownloadsViewModel.kt#L29-L81)
- [NetworkMonitor.kt:29-76](file://app/src/main/java/com/suvojeet/suvmusic/util/NetworkMonitor.kt#L29-L76)
## Detailed Component Analysis
### DownloadService
Responsibilities:
- Foreground service lifecycle for long-running downloads
- Queue processing loop with progress notifications
- Cancellation delegation to repository
- Batch progress tracking and completion notifications
Key behaviors:
- Starts foreground early to satisfy platform restrictions
- Processes queue items sequentially, updating active tracking and notifications
- Observes repository progress flow to reflect real-time progress
- Emits completion notifications per song
```mermaid
flowchart TD
Start(["onStartCommand"]) --> Decide{"Action?"}
Decide --> |START_DOWNLOAD| Enqueue["downloadRepository.downloadSongToQueue(song)"]
Decide --> |PROCESS_QUEUE| Loop["processQueue()"]
Decide --> |CANCEL_DOWNLOAD| Cancel["cancelDownload(songId)"]
Enqueue --> Loop
Loop --> Pop["popFromQueue()"]
Pop --> HasItem{"Item?"}
HasItem --> |No| Stop["stopForeground + stopSelf"]
HasItem --> |Yes| Track["activeDownloads + batchProgress"]
Track --> Notify["updateForegroundNotification(...)"]
Notify --> Download["downloadRepository.downloadSong(song)"]
Download --> Done{"Success?"}
Done --> |Yes| Complete["showCompleteNotification(title, true)"]
Done --> |No| Fail["showCompleteNotification(title, false)"]
Complete --> Cleanup["cleanup activeDownloads"]
Fail --> Cleanup
Cleanup --> Loop
```
**Diagram sources**
- [DownloadService.kt:118-211](file://app/src/main/java/com/suvojeet/suvmusic/service/DownloadService.kt#L118-L211)
**Section sources**
- [DownloadService.kt:33-305](file://app/src/main/java/com/suvojeet/suvmusic/service/DownloadService.kt#L33-L305)
### DownloadRepository
Responsibilities:
- Queue management (ConcurrentLinkedDeque) and batch progress
- Download orchestration: fetching stream URLs, streaming via DataSource/OkHttp, writing to storage
- Metadata embedding and thumbnail caching
- Storage scanning, migration, and cleanup
- Deletion with scoped storage permission handling
- Progressive playback support with early trigger threshold
- Video download support (MP4 muxed streams)
- Storage info and cache clearing
Concurrency and progress:
- Mutex guards duplicate downloads and ensures idempotency
- Tracks active jobs via ConcurrentHashMap for cancellation
- Exposes StateFlows for downloaded songs, queue, progress, and downloading IDs
Storage and locations:
- Public Music/SuvMusic folder (Q+) or legacy Downloads/SuvMusic migration
- Custom SAF tree location via user preference
- MediaStore integration for Q+ and fallback to public folder for older versions
```mermaid
classDiagram
class DownloadRepository {
+downloadSong(song) : Boolean
+downloadSongProgressive(song, onReadyToPlay) : Boolean
+downloadVideo(song, maxResolution) : Boolean
+downloadSongs(songs)
+downloadSongToQueue(song)
+popFromQueue() : Song?
+updateBatchProgress(current,total)
+deleteDownload(songId)
+deleteDownloads(songIds)
+deleteAllDownloads()
+refreshDownloads()
+getStorageInfo() : StorageInfo
+clearCache()
+isDownloaded(songId) : Boolean
+isDownloading(songId) : Boolean
+downloadedSongs : StateFlow>
+queueState : StateFlow>
+downloadProgress : StateFlow