Downloads
Status: built and in use on phones; the TV app has no downloads. The queue decides through the state machine of ADR 0003 since its step 3, and takes its clocks, dispatcher and scope from its constructor since step 4. Since step 5 the Downloader port is in application and answers in our own types, since step 6 the queue itself is a service of application, and since step 8 the rules DownloaderImpl held (the sweep, the paths, the finalize’s steps) are in domain (#970). As of 2026-12-02.
Start here
Section titled “Start here”- The queue is
DownloadQueue(application/.../application/downloads/service/, pure Kotlin since ADR 0003 step 6); what it needs from Android goes through ports thatdownloadsimplements inDownloadQueueAndroid.kt(the pump service, the failure notification, the words, the log). The bytes areMediaDownloadEngine(downloads/.../utils/download/); the rows areDownloaderImplthrough the roles of the download store (#967:DownloadList,DownloadedItemRows,DownloadSources,DownloadMediaStreams,DownloadSegmentsAndTrickplay,DownloadUserData,QueuedDownloads). - What happens to one download is decided by the state machine in
domain(DownloadStage?.on, the table in ADR 0003, #970).DownloadQueuesends it every event and carries out its effects. What starts next is a rule ofdomaintoo (nextDownloads,mayStart). A change to what the queue does is a change to a row of the table: the machine,DownloadTransitionTestand the ADR change together. - Finished or not is
DownloadStateindomain: only it names the.downloadsuffix (rule R13). downloadsmay not usecore,dataor an adapter (rule R15): what it needs from them comes through a port inapplication(the roles of the download store,DownloadSettings,CurrentServerId), and whatcore/modes/filmneed fromdownloadsgoes throughDownloadQueuePort,DownloadDeleter, andSmartDownloadCheckerinapplication(soapp/tvbindsNonewithout linkingdownloads, #1048).- Test fast:
./gradlew :application:test --tests '*DownloadQueue*'for the queue (plain JVM, seconds),./gradlew :downloads:testDebugUnitTestfor the engine andDownloaderImpl. On a device: usertester(may download) andnodownload, Plain Movie or Short Movie,iptablesto cut the server. - A download that failed for want of the server goes on by itself when the server is back (
ServerAvailability, #912); one the server refused stays failed.
What it does
Section titled “What it does”A download keeps an item (a movie or an episode) on the device so it plays without the server. A home video or a music video is a Movie with its own Movie.kind (#1068, #1076): MovieEntity.kind keeps it (schema 22), and the Downloads screen, its storage bar, Favorites and the stored libraries list each kind apart (movieSection in modes/film). A row stored before schema 22 is a movie until getMovie reads it from the server, which corrects its kind (StoredItems.correctMovieKind). The user picks a quality in DownloadQualityDialog. DownloadQueue schedules the downloads and runs a few at a time. MediaDownloadEngine writes each file over OkHttp and can resume a cut-off transfer. A file is written as <path>.download and renamed when it is done: the name says whether it is finished (DownloadState). Smart downloads keep the next episodes of a show ready and remove the ones you have watched. There is no offline mode (#281): when the server fails or takes over 3 s, the repository shows the Room copy of a downloaded item (StoredFallback.kt), and playback picks a finished download before it asks the server. While the server is away, Home, Media, Favorites and search show what is downloaded (#775, #1054; see the home and library guide).
Where the code is
Section titled “Where the code is”| Path | What |
|---|---|
application/.../application/downloads/service/DownloadQueue.kt |
The scheduler: entries, slots, auto-retry, restore after process death. A service of application since ADR 0003 step 6, with its published view (DownloadQueueStages.kt), the speed (DownloadSpeed.kt) and the service’s notice (DownloadPumpNotice.kt) next to it |
downloads/.../core/presentation/downloader/DownloadQueueAndroid.kt |
The queue’s Android side: DownloadPumpStarter (DownloadPump), DownloadFailureNotification (DownloadFailureNotice), DownloadQueueTextsImpl (DownloadQueueTexts, the words of DownloadTexts.failureText as a DownloadText), TimberDownloadQueueLog (DownloadQueueLog). The ports are in application/.../application/downloads/port/ |
application/.../application/downloads/port/Downloader.kt |
The Downloader port (ADR 0003 step 5): a start returns a DownloadStart (the download id, or a DownloadFailure of domain), the engine’s state is an EngineStatus. No text: the queue asks its DownloadQueueTexts port, which downloads makes with DownloadTexts.failureText (DownloadFailureText.kt). Tests fake it with FakeDownloader in testing |
downloads/.../utils/DownloaderImpl.kt |
Downloader: stores the item rows, starts the engine, finalizes, deletes, runs the orphan sweep. It reads the disk and the engine and asks the rules in domain (ADR 0003 step 8). The engine reports an EngineStatus itself since ADR 0003 step 7 |
downloads/.../utils/download/MediaDownloadEngine.kt |
The OkHttp engine: Range resume, pause on the network rule (shouldPauseTransfer in domain), HTTP errors |
downloads/.../utils/download/ResumeValidators.kt |
If-Range validator per partial file, so a changed source is not appended to (#850) |
downloads/.../core/presentation/downloader/SmartDownloads.kt, SmartDownloadPlanner.kt |
Smart downloads; the planner is pure and tested |
downloads/.../core/presentation/downloader/DownloadPumpService.kt |
Foreground service that keeps the process alive while the queue has work |
downloads/.../work/ |
OrphanSweepWorker, ImagesDownloaderWorker |
downloads/.../di/ |
The module’s Hilt bindings. DownloaderModule.provideDownloadQueue builds the queue with the wall clock, System.nanoTime, Dispatchers.IO and a scope that lives as long as the app (ADR 0003 step 4), and with the adapters of DownloadQueueAndroid.kt (step 6) |
domain/.../models/DownloadState.kt |
DownloadState and DownloadFiles: the only place that knows the .download suffix |
domain/.../domain/downloads/ |
The download state machine of ADR 0003 (#970): DownloadStage, DownloadEvent, DownloadEffect and DownloadStage?.on, tested row by row in DownloadTransitionTest; what starts next (nextDownloads, NextDownloadsTest) and the size of a capped transcode (estimateCappedDownloadSize). Since step 8 also DownloaderImpl’s rules, in rule/: the orphan sweep (OrphanSweep.kt), the paths and file names (DownloadPaths.kt), which streams are kept as files of their own (SidecarStreams.kt), transferPercent, trickplaySheetCount, the engine’s network rule (shouldPauseTransfer) and the finalize in steps (FinalizeSteps.kt, tested as a table in FinalizeStepsTest). DownloadQueue decides through it since step 3 of the ADR and carries out its effects, and stores each download’s stage since step 7 (Entry in DownloadQueueStages.kt keeps what the stage does not: the item, a failure’s words, the numbers on screen). The screens read the stage’s view, DownloadStageView (queued, waiting for the network, running, paused, finished, failed) |
application/.../repository/DownloadSources.kt |
One of the roles of the download store (#967: DownloadList, DownloadedItemRows, DownloadSources, DownloadMediaStreams, DownloadSegmentsAndTrickplay, DownloadUserData, QueuedDownloads); the row types are in StoredDownloads.kt; Room implementation in data/.../database/RoomDownloadStore.kt |
application/.../repository/DownloadSettings.kt, CurrentServerId.kt |
The settings the engine reads, as ports; implemented over AppPreferences in core/.../di/AppPreferencesPorts.kt (#926) |
application/.../device/StorageVolumes.kt, device/.../StorageVolumesImpl.kt |
The storage the Downloads screen’s space bar measures: the chosen volume (or the first), its free space, the app’s internal files. DownloadsViewModel takes it instead of a Context, and CurrentServerId and DownloadSettings instead of AppPreferences (#969, R23) |
application/.../repository/ServerAvailability.kt |
The port that says the server was found to answer again; ServerReachability in core implements it, DownloadQueue collects it (#912) |
application/.../repository/StoredFallback.kt |
The Room copy when the server fails or is slow (3 s) |
downloads/.../utils/download/DownloadTexts.kt |
Texts from core’s resources; implemented by app/phone/.../utils/CoreDownloadTexts.kt (with core/.../utils/DownloadErrorText.kt for downloadErrorText and DownloadText.toUiText) |
application/.../repository/DownloadQueuePort.kt, DownloadDeleter.kt, SmartDownloadChecker.kt |
Ports consumed by core and modes/film; implemented in downloads, bound as .None on TV in app/tv/.../di/TvDownloadsModule.kt (#1048) |
core/.../presentation/downloader/DownloaderViewModel.kt |
Collects DownloadQueuePort.queueEntries into DownloaderState (the stage’s view, the progress, a failure’s words) for the item screens; toDownloaderState is the mapping, tested in DownloaderStateTest |
modes/film/.../presentation/downloads/ |
DownloadsViewModel, DownloadedShowViewModel |
app/phone/.../presentation/film/DownloadsScreen.kt, DownloadedShowScreen.kt |
The Downloads screens |
app/phone/.../presentation/film/components/DownloadQualityDialog.kt |
The quality asked for each download; also DownloadRow, DownloaderCard, DownloadProgressButton, ItemButtonsBar there |
core/.../core/reachability/ |
ServerReachability: whether the server answers. Not reachable from downloads (R15) |
How the screens use it: they go through the queue (DownloadQueuePort) and DownloadDeleter; only downloads names the Downloader port. DownloaderViewModel turns the queue’s entries into DownloaderState. The storage location is AppPreferences.downloadStorageIndex, so a download never asks for one; it does ask for a quality (DownloadQualityDialog). ItemButtonsBar takes canDownload and isDownloaded overrides, so a season or a show passes a value computed over its episodes instead of item.isDownloaded() (which reads DownloadState). The Downloads screens never ask the server: they read DownloadList, DownloadSources and ItemLists.getDownloads (MediaRepositoryImpl reads the movies and shows through the store role StoredItems, #966). Screens that need the server show the unreachable banner. Without the server, MediaRepositoryImpl.getPlaybackSources picks a finished download before it asks the server, and user data written meanwhile is marked toBeSynced (PendingUserDataStore) and sent later by UserDataSync and SyncWorker.
Strings: the English CE strings of the module are in downloads/src/main/res/values/strings.xml, their translations in values-<lang>/strings_ce.xml.
- R13: only
DownloadState.ktnames the.downloadsuffix, also inside SQL. AskItemSource.downloadStateorDownloadFiles. - R15:
downloadsdoes not depend ondata,server/jellyfin,coreor an app outside its tests; no file outsidedownloadsnamesDownloaderImpl,MediaDownloadEngine,ResumeValidatorStore,SharedPreferencesResumeValidatorStore,DownloadHttpClientorImagesDownloaderWorker. Others useDownloader,DownloadQueue,SmartDownloads. - R24:
DownloadQueue, its Android sideDownloadQueueAndroid.kt(at most 150 lines, ADR 0003) andDownloaderImplmay not grow past their line ceilings inarchitecture/size-ceilings.txt(ADR 0003, #970). The steps of the ADR lower them. - R9, R4: only the apps depend on
data; onlydataimportsServerDatabaseDao. Room access goes through the roles of the download store. - R10: ids are value classes (
ItemId,MediaSourceId,MediaStreamId, … indomain/.../models/Ids.kt); nojava.util.UUIDand noStringid outside the adapter. Don’t add a line toarchitecture/baseline/to get past it. - R1, R2: no SDK and no
JellyfinApihere; the engine gets its URLs through the repository’s roles (PlaybackMedia,ItemCatalog,CurrentAccount, #967). - Project rules (
CLAUDE.md): thelibreflavour stays free of Google code; every CE string in 36 languages (translate-stringsskill); a Room migration gets an independent review when no bot reviewed the PR.
How to test it
Section titled “How to test it”Unit tests, pure modules first:
./gradlew :domain:test :application:test :architecture:test # DownloadStateTest, DownloadTransitionTest, NextDownloadsTest, FinalizeStepsTest, OrphanSweepHelpersTest, DownloadPathTest, NetworkPauseTest, R13, R15, R24./gradlew :application:test # DownloadQueue*Test (the queue, plain JVM), StoredFallbackTest, MediaRepositoryImplTest (the repository over fakes)./gradlew :downloads:testDebugUnitTest # MediaDownloadEngine*Test, ResumeValidatorsTest, SmartDownloadPlannerTest, OrphanSweepTest, DownloadFinalizeFailureTest, SubtitleFinalizeTest, DownloadTrickplayRestartTest, DownloadQueueAndroidTest./gradlew :data:testDebugUnitTest # StoredItemFallbackTest, UnfinishedDownloadPlaybackTest (the repository over Room)./gradlew :modes:film:testDebugUnitTest # DownloadsViewModelUserSwitchTest, QueueCountsTest, EpisodeDownloadSelectionTest, ActiveDownloadMappingTest, EpisodeDownloadProgressTest./gradlew :core:testLibreDebugUnitTest # DownloadErrorTextTest, DownloaderStateTest (core has a libre flavour)./gradlew :app:phone:testLibreDebugUnitTest # DownloadQualityDialogTest, DownloadStatusTextTest (the words of each stage), ServerUnreachableTestOne class: add --tests '*MediaDownloadEngineResumeTest*'.
DownloadQueueCharacterisationTest and PendingDownloadRestoreTest pin the rows of the download table in ADR 0003 that no other test covered, each named by its row number (#970). A change that fails one of them changes what the queue does today, so it goes in a fix PR with its own issue, and the ADR’s table changes with it. The downloads tests build the real stores over Room (testImplementation(projects.data)) and fake the settings with TestDownloadSettings (in testing since step 6). The queue tests are in application since ADR 0003 step 6 and run on the JVM, without Robolectric: they fake the source rows with queueSources, the words with TestQueueTexts and the failure notices with RecordedNotices (QueueVirtualTime.kt); DownloadQueueAndroidTest in downloads checks what the notice and the words become on Android. They fake the downloader with FakeDownloader from testing: set what a start returns (startResult, onStart) and what the engine reports (progress, progressOf), and read the calls it recorded.
The DownloadQueue*Test classes run the queue in the virtual time of runTest (QueueVirtualTime.kt, ADR 0003 step 4). queueInVirtualTime gives the queue the test’s scheduler, backgroundScope and clocks that read the virtual time, and runQueueUntil moves that time on until the queue gets where the test expects. A backoff of minutes takes no real time, so no test sleeps. Only DownloadQueueMachineReviewTest still writes the queue’s list by reflection, for two entries of one item that no short run of events reaches. The queue’s coroutines run on the test’s scope, so an exception that escapes one fails the test instead of vanishing on the queue’s own scope. That includes a fake that throws NotImplementedError.
On a device: the test server (docs/dev-environment.md, tools/test-server/setup.sh, test-server skill) at http://10.0.2.2:8096 from an emulator.
- Users:
testermay download;nodownloadmay not (no download button: the server’scanDownload). Use your own user when someone else tests at the same time (python3 tools/test-server/user.py add <name>). - Items: Plain Movie and Short Movie (the normal case, a quick one); Versions Movie (two versions); Tracks Movie (external
.de.srt, finalized with the video, #573); Image Subs Movie and Tracks Show at a 1.5 Mbps quality (a transcoded download); Test Show, Long Season Show and Resume Show (season downloads, smart downloads); Empty Season Show (nothing to download). - Without the server, internet still up (phone or tablet AVD):
adb root, thenadb shell iptables -I OUTPUT -d 10.0.2.2 -p tcp --dport 8096 -j REJECT --reject-with tcp-reset;-Dinstead of-Ibrings it back. Use the port the app is logged in on: 8097 when it goes throughforward.py(below). That shows the unreachable banner, the stored fallback and the queue’s failure path. - A slow transfer, to pause or cut one mid-way:
python3 tools/test-server/forward.py 8097 8096 600(600 kbit/s) and log in tohttp://10.0.2.2:8097; stop the script to cut the connection. - No network at all:
adb shell cmd connectivity airplane-mode enable; a queued download waits for the network (#530). - Restart during a season download with one download slot and episodes still queued. On the next start, the partial episode resumes first and the queued episodes follow in their original order. The debug build is
nl.midasvo.findroid.ce.debug. - Scripted taps: dump the screen (
uiautomator dump) and check it before each tap.
Before a PR
Section titled “Before a PR”./gradlew ktfmtCheck./gradlew :domain:test :application:test :architecture:test./gradlew :downloads:testDebugUnitTest :data:testDebugUnitTest :modes:film:testDebugUnitTest./gradlew :app:phone:compileLibreDebugKotlinpython3 .claude/skills/translate-strings/scripts/check-translations.py # when strings changedOr all of it: ./gradlew testDebugUnitTest.
Then on an emulator: start a download, cut the server off with iptables (see above), bring it back, and check what the queue shows.
Decisions and history
Section titled “Decisions and history”- #38: Android’s DownloadManager replaced by the OkHttp engine with resume (#26).
- #116: smart downloads.
- #281: no Offline Mode; stored copies while the server is away, reachability banner.
- #560: the pump service runs as long as the queue has work.
- #1054: Home shows the downloads while the server is away (rows from
StoredItemLists; a new DAO query, no schema change). - #718 (open) and #724: stored copies looked up by the current server.
- #848: a failed finalize is not shown as completed.
- #850:
If-Rangeon resume. - #897:
DownloadStateinstead of the suffix in every file (R13). - #899 / #911: the rows behind the download store (split by role in #967).
- #912: a failed entry flagged
retryWhenServerReturnsgoes back to Pending onServerAvailability.serverConfirmed(a probe that reached the server, or a request answered while it counted as unreachable). - #1124: automatic recovery keeps the queue timestamp in memory and in the pending row. Manual Retry assigns a fresh timestamp. An entry in retry backoff becomes eligible at its scheduled time. Schema 23 records the pending row’s last write in
savedAtfor the 30-day cleanup of unresolvable rows. Rows saved before the upgrade fall back to their original timestamp. - #901 / #914:
downloadsas its own module (R15). - #918 / #926: the engine reads its settings through
DownloadSettings(part 2; part 1 is #927, and rule R17 now guards both). - #1002:
DownloadQueue.startDownloadkeeps the pending row untildownloadItemwrites a source row, so a start that fails online while the server is away survives process death (restoreAllskips any pending row whose item already has an active source). - ADRs:
docs/architecture/adr/0002-hexagonal-ddd.md; T5, T7 and T9 indocs/architecture/5-hexagonal-ddd.md. Proposed:docs/architecture/adr/0003-playback-and-download-use-cases.md(#970), the life of one download as a state machine indomainand the queue as a service inapplication, without a Room schema change of its own (#1124 added schema 23 outside the series).
Pitfalls
Section titled “Pitfalls”- Smart Downloads keeps files held by the local playlist (#1143).
PlaybackEvents.queuedDownloadIdsaccumulates resolved downloads before and after the current item; moving to Previous must not let Smart Downloads delete Next. Holds last until player release, including across jumps and failed queue replacements, because engine queue installation is asynchronous. Smart Downloads can remove those files on its next check after release. Protection changes deletion only; played neighbours still count towards the series’ progress when planning new downloads. The delete loop checks again after resolving the stored source. A new lookup can still race with a deletion already underway insideDownloaderImpl. - A failed download resumes by itself only when the server gave no answer.
DownloadQueueflags a failure at the start (also after an app restart with the server away) and an engine failure with no HTTP status once its three auto-retries are used (30 s, 2 min, 10 min,afterFailure);ServerAvailability.serverConfirmedputs them back to Pending (#912). A refusal (an HTTP status, a failed finalize) stays failed until Retry. It only fires while the app is in front: the reachability monitor does not probe in the background. A start that failed for a local reason (storage) is flagged too and fails again at once. - One item id is stored for one server. The item tables have the item id as primary key: a download of the same id from a second server replaces the first one’s copy, and the queue dedups by item id (#718). A restore can still bring back two live entries of one item (two partial rows): the poll matches each one to its own download ID, and a start takes the entry the pump chose, so neither takes the other’s updates or retry time (#1106). Each entry keeps the download ID of its row while it waits (
Entry.resumeDownloadId) and names it indownloadItem, so it resumes its own partial; a start that names none resumes the item’s first partial (#1109). The poll’s subtitle retry names the entry’s download ID too, so it restarts that partial’s failed subtitles (#1118). The download path of a movie or an episode has no source ID, so two rows the app wrote for one item can share one file: those are one download, and both entries resume the first. - Re-downloading does not refresh metadata: the item inserts in
ServerDatabaseDaouseOnConflictStrategy.IGNORE(data-02 indocs/open-decisions.md). - The engine is in-process. It does not survive process death;
restoreAllputs the partial downloads back as pending and resumes them by Range, and restores queued downloads whose start had not written a source row yet. WithoutDownloadPumpServicethe transfers stop when the app is closed. - Trickplay across restarts and from lists:
downloadTrickplayDatawrites each sheet to disk before inserting thetrickplayInfosrow, andDownloaderImplensures missing trickplay on resume and finalization (resolving fromItemCatalogwhen the caller or Room copy lacked it, #1015). - External subtitles have their own
.downloadname and finalize step (#573); check them when you change finalizing. The order of both finalizes isFinalizeSteps.ktindomain, one row ofFinalizeStepsTestper case: a change there is a change of what is kept on disk. - Every download needs a path of its own.
buildDownloadPath(indomain,DownloadPaths.kt) names a movie’s folderName (year) [<item id>](#1068): without the id, two items with the same name and year (home videos have no year and often the same name) shared one file, a new download deleted the other’s partial file and its finish replaced the other’s finished one. An episode isSeries [<series id>]/S01/S01E05 - Name [<episode id>]for the same reason (#1079): two shows with one name (in different libraries, or on two servers) had one path, and so did episodes without a number (allS00E00) with the same name. Movie, series and episode titles are cut to 180 UTF-8 bytes, so with the id a name stays under the 255 bytes of ext4. Old downloads keep the path in their rows. - The orphan sweep deletes files: a finished file with no row goes after 24 h (
ORPHAN_MIN_AGE_MS). A path change that the rows do not follow loses downloads. DownloadsViewModel’s reads, sorting and storage walk run onioDispatcher(Dispatchers.IOin the app). A test passes its own test dispatcher, asDownloadsViewModelUserSwitchTestdoes: on the real IO threads a load the test had already left (cancelled by a newer one) went on after the test, and its return toDispatchers.MainafterresetMain()failed whicheverrunTestcame next in the module, oftenFavoritesViewModelUserSwitchTestorMediaViewModelUserSwitchTest(#921). A new test of a ViewModel inmodes/filmdoes the same: no real dispatcher, everything on the test scheduler.- Partial downloads resume first after a restart.
restoreAllassigns them an earlier queue timestamp, and restored pending rows keep their original timestamps (#1098).DownloadQueueCharacterisationTestchecks the first start with one slot and the order of the pending entries. - Downgrade: builds with the #1127 startup check preserve the database, including download rows. Use a compatible build when the launcher reports that it cannot open the saved data. APKs released before #1127 can still erase the database on downgrade, including download metadata and logins.
Source: docs/areas/downloads.md · raw Markdown