Files
jellytau/architecture/06-downloads-and-offline.html
T

531 lines
32 KiB
HTML

<!DOCTYPE HTML>
<html lang="en" class="navy" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Downloads &amp; Offline - JellyTau Documentation</title>
<!-- Custom HTML head -->
<meta name="description" content="Requirements, traceability, and architecture for the JellyTau Jellyfin client.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="../favicon.svg">
<link rel="shortcut icon" href="../favicon.png">
<link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/general.css">
<link rel="stylesheet" href="../css/chrome.css">
<link rel="stylesheet" href="../css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="../fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="../highlight.css">
<link rel="stylesheet" href="../tomorrow-night.css">
<link rel="stylesheet" href="../ayu-highlight.css">
<!-- Custom theme stylesheets -->
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "navy";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('navy')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded affix "><a href="../index.html">Introduction</a></li><li class="chapter-item expanded affix "><li class="part-title">Requirements & Traceability</li><li class="chapter-item expanded "><a href="../requirements.html"><strong aria-hidden="true">1.</strong> Requirements Specification</a></li><li class="chapter-item expanded "><a href="../traceability.html"><strong aria-hidden="true">2.</strong> Traceability Matrix</a></li><li class="chapter-item expanded "><a href="../traceability-ci.html"><strong aria-hidden="true">3.</strong> Traceability CI</a></li><li class="chapter-item expanded "><a href="../traces-quick-ref.html"><strong aria-hidden="true">4.</strong> Traces Quick Reference</a></li><li class="chapter-item expanded affix "><li class="part-title">Architecture</li><li class="chapter-item expanded "><a href="../architecture/index.html"><strong aria-hidden="true">5.</strong> Overview</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../architecture/01-rust-backend.html"><strong aria-hidden="true">5.1.</strong> Rust Backend</a></li><li class="chapter-item "><a href="../architecture/02-svelte-frontend.html"><strong aria-hidden="true">5.2.</strong> Svelte Frontend</a></li><li class="chapter-item "><a href="../architecture/03-data-flow.html"><strong aria-hidden="true">5.3.</strong> Data Flow</a></li><li class="chapter-item "><a href="../architecture/04-type-sync-and-threading.html"><strong aria-hidden="true">5.4.</strong> Type Sync & Threading</a></li><li class="chapter-item "><a href="../architecture/05-platform-backends.html"><strong aria-hidden="true">5.5.</strong> Platform Backends</a></li><li class="chapter-item expanded "><a href="../architecture/06-downloads-and-offline.html" class="active"><strong aria-hidden="true">5.6.</strong> Downloads & Offline</a></li><li class="chapter-item "><a href="../architecture/07-connectivity.html"><strong aria-hidden="true">5.7.</strong> Connectivity</a></li><li class="chapter-item "><a href="../architecture/08-database-design.html"><strong aria-hidden="true">5.8.</strong> Database Design</a></li><li class="chapter-item "><a href="../architecture/09-security.html"><strong aria-hidden="true">5.9.</strong> Security</a></li></ol></li><li class="chapter-item expanded "><li class="part-title">UX</li><li class="chapter-item expanded "><a href="../ux-flows.html"><strong aria-hidden="true">6.</strong> UX Flows</a></li><li class="chapter-item expanded affix "><li class="part-title">Specs — Pending Work</li><li class="chapter-item expanded "><a href="../specs/index.html"><strong aria-hidden="true">7.</strong> Specs Index</a></li><li class="chapter-item expanded "><a href="../specs/SPEC-TEMPLATE.html"><strong aria-hidden="true">8.</strong> Spec Template</a></li><li class="chapter-item expanded "><a href="../specs/SPEC-REVIEW-CHECKLIST.html"><strong aria-hidden="true">9.</strong> Spec Review Checklist</a></li><li class="chapter-item expanded "><a href="../specs/playback-backend-unification.html"><strong aria-hidden="true">10.</strong> Playback Backend Unification</a></li><li class="chapter-item expanded "><a href="../specs/linux-native-video-spike.html"><strong aria-hidden="true">11.</strong> Linux Native Video Spike</a></li><li class="chapter-item expanded "><a href="../specs/backend-owned-stream-selection.html"><strong aria-hidden="true">12.</strong> Backend-Owned Stream Selection</a></li><li class="chapter-item expanded "><a href="../specs/player-facade-enforcement.html"><strong aria-hidden="true">13.</strong> Player Facade Enforcement</a></li><li class="chapter-item expanded "><a href="../specs/windows-native-audio-backend.html"><strong aria-hidden="true">14.</strong> Windows Native Audio Backend</a></li><li class="chapter-item expanded "><a href="../specs/libmpv2-migration.html"><strong aria-hidden="true">15.</strong> libmpv2 Migration</a></li><li class="chapter-item expanded "><a href="../specs/read-through-media-cache.html"><strong aria-hidden="true">16.</strong> Read-Through Media Cache</a></li><li class="chapter-item expanded "><a href="../specs/scoped-search.html"><strong aria-hidden="true">17.</strong> Scoped Search</a></li><li class="chapter-item expanded "><a href="../specs/scoped-search-boundary.html"><strong aria-hidden="true">18.</strong> Scoped Search Boundary</a></li><li class="chapter-item expanded "><a href="../specs/scoped-search-boundary-implementation.html"><strong aria-hidden="true">19.</strong> Scoped Search Boundary — Implementation</a></li><li class="chapter-item expanded "><a href="../specs/frontend-domain-model.html"><strong aria-hidden="true">20.</strong> Frontend Domain Model</a></li><li class="chapter-item expanded "><a href="../specs/build-provenance.html"><strong aria-hidden="true">21.</strong> Build Provenance</a></li><li class="chapter-item expanded affix "><li class="part-title">Build & Release</li><li class="chapter-item expanded "><a href="../build/build-release.html"><strong aria-hidden="true">22.</strong> Build & Release</a></li><li class="chapter-item expanded "><a href="../release-checklist.html"><strong aria-hidden="true">23.</strong> Release Checklist</a></li><li class="chapter-item expanded "><a href="../build/build-desktop-packages.html"><strong aria-hidden="true">24.</strong> Desktop Packaging</a></li><li class="chapter-item expanded "><a href="../build/build-windows.html"><strong aria-hidden="true">25.</strong> Windows Build</a></li><li class="chapter-item expanded "><a href="../defect-windows.html"><strong aria-hidden="true">26.</strong> Defect Windows</a></li><li class="chapter-item expanded "><a href="../build/docker.html"><strong aria-hidden="true">27.</strong> Docker</a></li><li class="chapter-item expanded "><a href="../build/build-builder-image.html"><strong aria-hidden="true">28.</strong> Builder Image</a></li><li class="chapter-item expanded affix "><li class="spacer"></li><li class="chapter-item expanded affix "><a href="../api-redirect.html">Rust API Reference (rustdoc)</a></li></ol>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">JellyTau Documentation</h1>
<div class="right-buttons">
<a href="../print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://gitea.tourolle.paris/dtourolle/jellytau" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://gitea.tourolle.paris/dtourolle/jellytau/_edit/master/docs/../docs/architecture/06-downloads-and-offline.md" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="download-manager--offline-architecture"><a class="header" href="#download-manager--offline-architecture">Download Manager &amp; Offline Architecture</a></h1>
<h2 id="overview"><a class="header" href="#overview">Overview</a></h2>
<p><strong>Location</strong>: <code>src-tauri/src/download/</code></p>
<p>The download manager provides offline media support with priority-based queue management, progress tracking, retry logic, and smart caching.</p>
<pre><code class="language-mermaid">flowchart TB
subgraph Frontend["Frontend"]
DownloadButton["DownloadButton.svelte"]
DownloadsPage["/downloads"]
DownloadsStore["downloads.ts store"]
end
subgraph Backend["Rust Backend"]
Commands["Download Commands"]
DownloadManager["DownloadManager"]
DownloadWorker["DownloadWorker"]
SmartCache["SmartCache Engine"]
end
subgraph Storage["Storage"]
SQLite[("SQLite DB")]
MediaFiles[("Downloaded Files")]
end
DownloadButton --&gt;|"invoke('download_item')"| Commands
DownloadsPage --&gt;|"invoke('get_downloads')"| Commands
Commands --&gt; DownloadManager
DownloadManager --&gt; DownloadWorker
DownloadManager --&gt; SmartCache
DownloadWorker --&gt;|"HTTP Stream"| MediaFiles
DownloadWorker --&gt;|"Events"| DownloadsStore
Commands &lt;--&gt; SQLite
SmartCache &lt;--&gt; SQLite
</code></pre>
<h2 id="download-worker"><a class="header" href="#download-worker">Download Worker</a></h2>
<p><strong>Location</strong>: <code>src-tauri/src/download/worker.rs</code></p>
<p>The download worker handles HTTP streaming with retry logic and resume support:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct DownloadWorker {
client: reqwest::Client,
max_retries: u32,
}
pub struct DownloadTask {
pub id: i64,
pub item_id: String,
pub user_id: String,
pub priority: i32,
pub url: String,
pub target_path: PathBuf,
pub mime_type: Option&lt;String&gt;,
pub expected_size: Option&lt;i64&gt;,
}
<span class="boring">}</span></code></pre></pre>
<p><strong>Retry Strategy</strong>:</p>
<ul>
<li>Exponential backoff: 5s, 15s, 45s</li>
<li>Maximum 3 retry attempts</li>
<li>HTTP Range requests for resume support</li>
<li>Progress events emitted every 1MB</li>
</ul>
<p><strong>Download Flow</strong>:</p>
<pre><code class="language-mermaid">sequenceDiagram
participant UI
participant Command as download_item
participant DB as SQLite
participant Worker as DownloadWorker
participant Jellyfin as Jellyfin Server
participant Store as downloads store
UI-&gt;&gt;Command: download_item(itemId, userId)
Command-&gt;&gt;DB: INSERT INTO downloads
Command-&gt;&gt;Worker: Start download task
Worker-&gt;&gt;Jellyfin: GET /Items/{id}/Download
loop Progress Updates
Jellyfin-&gt;&gt;Worker: Stream chunks
Worker-&gt;&gt;Worker: Write to .part file
Worker-&gt;&gt;Store: Emit progress event
Store-&gt;&gt;UI: Update progress bar
end
Worker-&gt;&gt;Worker: Rename .part to final
Worker-&gt;&gt;DB: UPDATE status='completed'
Worker-&gt;&gt;Store: Emit completed event
Store-&gt;&gt;UI: Show completed
</code></pre>
<h2 id="smart-caching-engine"><a class="header" href="#smart-caching-engine">Smart Caching Engine</a></h2>
<p><strong>Location</strong>: <code>src-tauri/src/download/cache.rs</code></p>
<p>The smart caching system provides predictive downloads based on listening patterns:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct SmartCache {
config: Arc&lt;Mutex&lt;CacheConfig&gt;&gt;,
album_play_history: Arc&lt;Mutex&lt;HashMap&lt;String, Vec&lt;String&gt;&gt;&gt;&gt;,
}
pub struct CacheConfig {
pub queue_precache_enabled: bool,
pub queue_precache_count: usize, // Default: 5
pub album_affinity_enabled: bool,
pub album_affinity_threshold: usize, // Default: 3
pub storage_limit: u64, // Default: 10GB
pub wifi_only: bool, // Default: true
}
<span class="boring">}</span></code></pre></pre>
<p><strong>Caching Strategies</strong>:</p>
<ol>
<li><strong>Queue Pre-caching</strong>: Auto-download next 5 tracks when playing (WiFi only)</li>
<li><strong>Album Affinity</strong>: If user plays 3+ tracks from album, cache entire album</li>
<li><strong>LRU Eviction</strong>: Remove least recently accessed when storage limit reached</li>
</ol>
<pre><code class="language-mermaid">flowchart TB
Play["Track Played"] --&gt; CheckQueue{"Queue&lt;br/&gt;Pre-cache?"}
CheckQueue --&gt;|"Yes"| CacheNext5["Download&lt;br/&gt;Next 5 Tracks"]
Play --&gt; TrackHistory["Track Play History"]
TrackHistory --&gt; CheckAlbum{"3+ Tracks&lt;br/&gt;from Album?"}
CheckAlbum --&gt;|"Yes"| CacheAlbum["Download&lt;br/&gt;Full Album"]
CacheNext5 --&gt; CheckStorage{"Storage&lt;br/&gt;Limit?"}
CacheAlbum --&gt; CheckStorage
CheckStorage --&gt;|"Exceeded"| EvictLRU["Evict LRU Items"]
CheckStorage --&gt;|"OK"| Download["Queue Download"]
</code></pre>
<h2 id="one-storage-model-cache-entries-are-downloads"><a class="header" href="#one-storage-model-cache-entries-are-downloads">One Storage Model: Cache Entries Are Downloads</a></h2>
<p><strong>TRACES</strong>: UR-071 | DR-126, DR-127</p>
<p>A cache entry <strong>is</strong> a download with a shorter life: the same <code>downloads</code> row and
the same file handling, distinguished by <code>download_source</code> plus an expiry. There
is one storage model rather than a cache and a download library that can
disagree about what is on disk.</p>
<div class="table-wrapper"><table><thead><tr><th><code>download_source</code></th><th>Life</th><th>Reclaimed by</th></tr></thead><tbody>
<tr><td><code>'auto'</code> (temporary)</td><td>Expiry, or eviction under space pressure</td><td>Both</td></tr>
<tr><td><code>'user'</code> (permanent)</td><td>No expiry</td><td>Neither</td></tr>
</tbody></table>
</div>
<p><strong>Eviction only reclaims the temporary tier.</strong> <code>evict_lru_async</code> originally
selected every completed download ordered by <code>completed_at ASC</code> with no source
filter, so hitting the storage limit deleted the <em>oldest</em> download — typically a
film saved deliberately for offline — to make room for a newly precached track.
It now evicts only <code>COALESCE(download_source, 'user') = 'auto'</code> rows.
<code>COALESCE</code> rather than a bare equality is load-bearing: rows predating the
migration can be NULL, and <strong>unknown provenance must be treated as the user's,
never as disposable</strong>. Freeing less than requested is the correct outcome when
only user downloads remain — the caller reports "unable to free enough".</p>
<p>A temporary row can be <strong>promoted</strong> to permanent when the user chooses to keep
it. That only clears the expiry and flips the source; the bytes never move.</p>
<h2 id="offline-catalog-visibility"><a class="header" href="#offline-catalog-visibility">Offline Catalog Visibility</a></h2>
<p><strong>TRACES</strong>: UR-052 | DR-078, DR-079, DR-080</p>
<p>Offline, a library page shows <strong>only media on the device</strong>. A "Show all server
media" toggle additionally reveals the cached server catalog, greyed out and
queueable for download on reconnect.</p>
<p>The gate is a process-global <code>INCLUDE_CATALOG_BROWSE</code> in
<code>repository/offline.rs</code>, written by the <code>set_show_server_catalog</code> command. It
gates the synced-catalog leg of <code>get_items</code>; without it the toggle rendered but
every server item still appeared, which is the defect the spec was written for.
<code>isConnected</code> derives from backend-reported reachability alone (DR-079) — see
<a href="07-connectivity.html">07-connectivity.md</a>.</p>
<p>Per-item disk usage comes from <code>repository_get_download_disk_usage</code>
(<code>DownloadDiskUsage</code>), aggregated from <code>downloads.file_size</code> — used by the
Downloaded browse cards, detail pages, the device total and the remove
confirmation (DR-085).</p>
<h2 id="download-commands"><a class="header" href="#download-commands">Download Commands</a></h2>
<p><strong>Location</strong>: <code>src-tauri/src/commands/download/</code><code>mod.rs</code> (the commands below), <code>pinning.rs</code>, <code>smart_cache.rs</code></p>
<div class="table-wrapper"><table><thead><tr><th>Command</th><th>Parameters</th><th>Description</th></tr></thead><tbody>
<tr><td><code>download_item</code></td><td><code>item_id, user_id, file_path</code></td><td>Queue single item download</td></tr>
<tr><td><code>download_album</code></td><td><code>album_id, user_id</code></td><td>Queue all tracks in album</td></tr>
<tr><td><code>get_downloads</code></td><td><code>user_id, status_filter</code></td><td>Get download list</td></tr>
<tr><td><code>pause_download</code></td><td><code>download_id</code></td><td>Pause active download</td></tr>
<tr><td><code>resume_download</code></td><td><code>download_id</code></td><td>Resume paused download</td></tr>
<tr><td><code>cancel_download</code></td><td><code>download_id</code></td><td>Cancel and delete partial</td></tr>
<tr><td><code>delete_download</code></td><td><code>download_id</code></td><td>Delete completed download</td></tr>
<tr><td><code>download_video</code> / <code>download_series</code> / <code>download_season</code></td><td>item ids</td><td>Queue video content</td></tr>
<tr><td><code>get_download_storage_stats</code></td><td><code>user_id</code></td><td>Device totals for the downloads screen</td></tr>
<tr><td><code>delete_album_downloads</code> / <code>delete_downloads_under</code> / <code>delete_all_downloads</code></td><td>container id</td><td>Bulk removal</td></tr>
<tr><td><code>pin_item</code> / <code>unpin_item</code> / <code>is_item_pinned</code></td><td><code>item_id</code></td><td>Protect metadata from a cache clear</td></tr>
<tr><td><code>set_max_concurrent_downloads</code></td><td><code>max</code></td><td>Worker concurrency (3 by default)</td></tr>
</tbody></table>
</div>
<h2 id="offline-commands"><a class="header" href="#offline-commands">Offline Commands</a></h2>
<p><strong>Location</strong>: <code>src-tauri/src/commands/offline.rs</code></p>
<div class="table-wrapper"><table><thead><tr><th>Command</th><th>Parameters</th><th>Description</th></tr></thead><tbody>
<tr><td><code>offline_is_available</code></td><td><code>item_id</code></td><td>Check if item downloaded</td></tr>
<tr><td><code>offline_get_items</code></td><td><code>user_id</code></td><td>Get all offline items</td></tr>
<tr><td><code>offline_search</code></td><td><code>user_id, query</code></td><td>Search downloaded items</td></tr>
</tbody></table>
</div>
<h2 id="player-integration"><a class="header" href="#player-integration">Player Integration</a></h2>
<p><strong>Location</strong>: <code>src-tauri/src/commands/player.rs</code> (modified)</p>
<p>The player checks for local downloads before streaming:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn create_media_item(req: PlayItemRequest, db: Option&lt;&amp;DatabaseWrapper&gt;) -&gt; MediaItem {
let local_path = db.and_then(|db_wrapper| {
check_for_local_download(db_wrapper, &amp;jellyfin_id).ok().flatten()
});
let source = if let Some(path) = local_path {
MediaSource::Local {
file_path: PathBuf::from(path),
jellyfin_item_id: Some(jellyfin_id.clone())
}
} else {
MediaSource::Remote {
stream_url: req.stream_url,
jellyfin_item_id: jellyfin_id.clone()
}
};
MediaItem { source, /* ... */ }
}
<span class="boring">}</span></code></pre></pre>
<h2 id="frontend-downloads-store"><a class="header" href="#frontend-downloads-store">Frontend Downloads Store</a></h2>
<p><strong>Location</strong>: <code>src/lib/stores/downloads.ts</code></p>
<pre><code class="language-typescript">interface DownloadsState {
downloads: Record&lt;number, DownloadInfo&gt;;
activeCount: number;
queuedCount: number;
}
const downloads = createDownloadsStore();
// Actions
downloads.downloadItem(itemId, userId, filePath)
downloads.downloadAlbum(albumId, userId)
downloads.pause(downloadId)
downloads.resume(downloadId)
downloads.cancel(downloadId)
downloads.delete(downloadId)
downloads.refresh(userId, statusFilter)
// Derived stores
export const activeDownloads = derived(downloads, ($d) =&gt;
Object.values($d.downloads).filter((d) =&gt; d.status === 'downloading')
);
</code></pre>
<p><strong>Event Handling</strong>:</p>
<p>The store listens to Tauri events for real-time updates:</p>
<pre><code class="language-typescript">listen&lt;DownloadEvent&gt;('download-event', (event) =&gt; {
const payload = event.payload;
switch (payload.type) {
case 'started':
// Update status to 'downloading'
case 'progress':
// Update progress and bytes_downloaded
case 'completed':
// Update status to 'completed', progress to 1.0
case 'failed':
// Update status to 'failed', store error message
}
});
</code></pre>
<h2 id="download-ui-components"><a class="header" href="#download-ui-components">Download UI Components</a></h2>
<p><strong>DownloadButton</strong> (<code>src/lib/components/library/DownloadButton.svelte</code>):</p>
<ul>
<li>Multiple states: available, downloading, completed, failed, paused</li>
<li>Circular progress ring during download</li>
<li>Size variants: sm, md, lg</li>
<li>Integrated into TrackList with <code>showDownload={true}</code> prop</li>
</ul>
<p><strong>DownloadItem</strong> (<code>src/lib/components/downloads/DownloadItem.svelte</code>):</p>
<ul>
<li>Individual download list item with progress bar</li>
<li>Action buttons: pause, resume, cancel, delete</li>
<li>Status indicators with color coding</li>
</ul>
<p><strong>Downloads Page</strong> (<code>src/routes/downloads/+page.svelte</code>):</p>
<ul>
<li>Active/Completed tabs</li>
<li>Bulk actions: Pause All, Resume All, Clear Completed</li>
<li>Empty states with helpful instructions</li>
</ul>
<h2 id="database-schema"><a class="header" href="#database-schema">Database Schema</a></h2>
<p><strong>downloads table</strong>:</p>
<pre><code class="language-sql">CREATE TABLE downloads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
item_id TEXT NOT NULL,
user_id TEXT NOT NULL,
file_path TEXT,
file_size INTEGER,
mime_type TEXT,
status TEXT DEFAULT 'pending', -- pending, downloading, completed, failed, paused
progress REAL DEFAULT 0.0,
bytes_downloaded INTEGER DEFAULT 0,
priority INTEGER DEFAULT 0,
error_message TEXT,
retry_count INTEGER DEFAULT 0,
queued_at TEXT DEFAULT CURRENT_TIMESTAMP,
started_at TEXT,
completed_at TEXT
);
CREATE INDEX idx_downloads_queue
ON downloads(status, priority DESC, queued_at ASC)
WHERE status IN ('pending', 'downloading');
</code></pre>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../architecture/05-platform-backends.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="../architecture/07-connectivity.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="../architecture/05-platform-backends.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="../architecture/07-connectivity.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="../elasticlunr.min.js"></script>
<script src="../mark.min.js"></script>
<script src="../searcher.js"></script>
<script src="../clipboard.min.js"></script>
<script src="../highlight.js"></script>
<script src="../book.js"></script>
<!-- Custom JS scripts -->
</div>
</body>
</html>