Compare commits

...
9 Commits
Author SHA1 Message Date
dtourolle 532ffa661a Fix tests
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 4m29s
Traceability Validation / Check Requirement Traces (push) Successful in 19s
🏗️ Build and Test JellyTau / Android Compile Check (push) Successful in 5m4s
Build & Release / Run Tests (push) Successful in 4m52s
Build & Release / Build Linux (push) Successful in 17m55s
Build & Release / Build Android (push) Successful in 22m13s
Build & Release / Create Release (push) Successful in 13s
2026-07-11 22:09:33 +02:00
dtourolle 2a1f1689b4 Layout and search fix
🏗️ Build and Test JellyTau / Run Tests (push) Failing after 2m4s
🏗️ Build and Test JellyTau / Android Compile Check (push) Has been skipped
Traceability Validation / Check Requirement Traces (push) Successful in 23s
Build & Release / Run Tests (push) Failing after 2m45s
Build & Release / Build Linux (push) Has been skipped
Build & Release / Build Android (push) Has been skipped
Build & Release / Create Release (push) Has been skipped
2026-07-11 19:55:55 +02:00
dtourolle a2cd9978f0 build uses android signing key
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 5m18s
Traceability Validation / Check Requirement Traces (push) Successful in 21s
🏗️ Build and Test JellyTau / Android Compile Check (push) Successful in 5m13s
Build & Release / Run Tests (push) Successful in 5m4s
Build & Release / Build Linux (push) Successful in 17m29s
Build & Release / Build Android (push) Successful in 21m44s
Build & Release / Create Release (push) Successful in 15s
2026-07-07 18:05:17 +02:00
dtourolle 36be192d44 offline mode fixes
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 4m39s
Traceability Validation / Check Requirement Traces (push) Successful in 24s
🏗️ Build and Test JellyTau / Android Compile Check (push) Successful in 5m11s
2026-07-07 16:22:12 +02:00
dtourolle acb7e5f221 fix offline mode and layout bugs
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 4m32s
Traceability Validation / Check Requirement Traces (push) Successful in 22s
Build & Release / Run Tests (push) Successful in 5m21s
🏗️ Build and Test JellyTau / Android Compile Check (push) Successful in 4m25s
Build & Release / Build Linux (push) Successful in 17m31s
Build & Release / Build Android (push) Successful in 22m5s
Build & Release / Create Release (push) Successful in 16s
2026-07-06 20:24:46 +02:00
dtourolle 68c8602230 Merge pull request 'fix-launcher-offline-mode' (#9) from fix-android-launcher-icon-conflict into master
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 5m18s
Traceability Validation / Check Requirement Traces (push) Successful in 21s
🏗️ Build and Test JellyTau / Android Compile Check (push) Successful in 4m25s
Reviewed-on: #9
2026-07-03 17:58:30 +00:00
dtourolle 2d141e5bf4 Fix for offline mode
🏗️ Build and Test JellyTau / Run Tests (pull_request) Successful in 4m21s
Traceability Validation / Check Requirement Traces (pull_request) Successful in 20s
🏗️ Build and Test JellyTau / Android Compile Check (pull_request) Successful in 4m54s
2026-07-03 19:37:34 +02:00
dtourolleandClaude Opus 4.8 c58cc0cf46 CI: replace broken per-commit Android APK build with a fast compile check
build-and-test.yml built a full APK on every master push without running
sync-android-sources.sh, so it used the wrong (Tauri-default) sources, was
unsigned, and duplicated the ~15min build that build-release.yml does properly
on tags. Replace it with cargo check --target aarch64-linux-android (~1min),
which catches Android Rust breakage without linking, bundling, or signing.
The signed release APK remains a tag-only artifact from build-release.yml.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 18:48:14 +02:00
dtourolleandClaude Opus 4.8 8938e3fdba Android launcher: drop monochrome (themed) icon, keep color only
The monochrome adaptive-icon layer produced a poor themed-icon rendering.
Remove the <monochrome> reference from mipmap-anydpi-v26/ic_launcher.xml and
delete the ic_launcher_monochrome.png files so Android always uses the color
adaptive icon (background + foreground). sync-android-sources.sh also drops any
monochrome layer Tauri regenerates.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 18:47:50 +02:00
51 changed files with 2974 additions and 1204 deletions
+18 -39
View File
@@ -60,16 +60,24 @@ jobs:
cargo test cargo test
cd .. cd ..
build: # Fast per-commit Android compile check. This does NOT build a shippable APK:
name: Build Android APK # the full signed release APK is built only on tag pushes by build-release.yml
# (which runs sync-android-sources.sh + signing). Running the full bundle here
# too would duplicate a ~15min build and, without the sync step, produced an
# unsigned APK missing our custom sources/icons/proguard rules anyway.
# `cargo check` for the Android target (~1min) catches Android-specific Rust
# breakage without linking, bundling, or signing.
android-check:
name: Android Compile Check
runs-on: linux/amd64 runs-on: linux/amd64
needs: test needs: test
container: container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest
env: env:
ANDROID_HOME: /opt/android-sdk ANDROID_HOME: /opt/android-sdk
NDK_VERSION: 27.0.11902837 ANDROID_SDK_ROOT: /opt/android-sdk
NDK_HOME: /opt/android-sdk/ndk/27.0.11902837 NDK_HOME: /opt/android-sdk/ndk/27.0.11902837
ANDROID_NDK_HOME: /opt/android-sdk/ndk/27.0.11902837
steps: steps:
- name: Checkout repository - name: Checkout repository
@@ -97,42 +105,13 @@ jobs:
${{ runner.os }}-bun- ${{ runner.os }}-bun-
- name: Install dependencies - name: Install dependencies
run: | run: bun install
bun install
- name: Build frontend - name: Cargo check (aarch64-linux-android)
run: bun run build
- name: Ensure Android NDK
run: |
if [ ! -d "$NDK_HOME" ]; then
echo "NDK not found at $NDK_HOME, installing ndk;$NDK_VERSION"
yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --sdk_root="$ANDROID_HOME" "ndk;$NDK_VERSION"
fi
echo "Using NDK at $NDK_HOME"
ls "$NDK_HOME"
- name: Initialize Android project
run: | run: |
TC="$NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin"
export CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER="$TC/aarch64-linux-android24-clang"
export CC_aarch64_linux_android="$TC/aarch64-linux-android24-clang"
export AR_aarch64_linux_android="$TC/llvm-ar"
cd src-tauri cd src-tauri
echo "" | bunx tauri android init cargo check --target aarch64-linux-android --lib
cd ..
- name: Build Android APK
id: build
run: |
mkdir -p artifacts
bun run tauri android build --apk true --target aarch64
# Find the generated APK file
ARTIFACT=$(find src-tauri/gen/android/app/build/outputs/apk -name "*.apk" -type f -print -quit)
echo "artifact=${ARTIFACT}" >> $GITHUB_OUTPUT
echo "Found artifact: ${ARTIFACT}"
- name: Upload build artifact
uses: actions/upload-artifact@v3
with:
name: jellytau-apk
path: ${{ steps.build.outputs.artifact }}
retention-days: 30
if-no-files-found: error
+3
View File
@@ -44,6 +44,9 @@ bun run build
# Step 2: Build Android APK # Step 2: Build Android APK
if [ "$BUILD_TYPE" = "release" ]; then if [ "$BUILD_TYPE" = "release" ]; then
# Configure release signing from .env (single source of truth). Must run
# after sync-android-sources.sh, since gen/android is (re)generated there.
./scripts/write-keystore-properties.sh
echo "📦 Building release APK..." echo "📦 Building release APK..."
bun run tauri android build --apk true bun run tauri android build --apk true
else else
+19
View File
@@ -65,6 +65,25 @@ if [ -d "$RES_SRC" ]; then
cp "$dir"/* "$RES_DST/$name/" cp "$dir"/* "$RES_DST/$name/"
echo " Copied res: $name" echo " Copied res: $name"
done done
# We ship only the color adaptive icon (background + foreground). Drop any
# monochrome layer Tauri may generate: the themed-icon monochrome doesn't
# render well, and our adaptive-icon xml no longer references it, so a stray
# ic_launcher_monochrome.png would just be dead weight.
rm -f "$RES_DST"/mipmap-*/ic_launcher_monochrome.png
# `tauri android init` also emits the Android Studio DEFAULT adaptive icon
# as API-qualified VECTOR drawables:
# drawable/ic_launcher_background.xml (solid #3DDC84 green)
# drawable-v24/ic_launcher_foreground.xml (the Android robot)
# Because drawable-v24 is a more specific match than our unqualified
# mipmap-*/ic_launcher_*.png, on API 24+ the vector WINS and the app ships
# the green square robot instead of our jellyfish. Remove them so the
# adaptive-icon xml resolves @mipmap/ic_launcher_{background,foreground}
# to the real committed PNGs.
rm -f "$RES_DST"/drawable/ic_launcher_background.xml \
"$RES_DST"/drawable-v24/ic_launcher_foreground.xml \
"$RES_DST"/drawable*/ic_launcher_foreground.xml \
"$RES_DST"/drawable*/ic_launcher_background.xml
fi fi
echo "✓ Android sources synced successfully" echo "✓ Android sources synced successfully"
+52
View File
@@ -0,0 +1,52 @@
#!/bin/bash
# Regenerate src-tauri/gen/android/keystore.properties from the gitignored .env.
#
# .env is the single source of truth for local release signing. `tauri android
# init` wipes/regenerates gen/android, so keystore.properties must be rewritten
# from .env before every release build (this is the local mirror of what the CI
# workflow does from Gitea secrets).
#
# Required .env vars:
# ANDROID_KEY_ALIAS, ANDROID_KEYSTORE_PASSWORD, ANDROID_KEY_PASSWORD,
# ANDROID_KEYSTORE_FILE (absolute path to the .jks)
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
ENV_FILE="$PROJECT_ROOT/.env"
PROPS="$PROJECT_ROOT/src-tauri/gen/android/keystore.properties"
if [ ! -f "$ENV_FILE" ]; then
echo "$ENV_FILE not found — cannot configure release signing." >&2
echo " Create it with ANDROID_KEY_ALIAS / ANDROID_KEYSTORE_PASSWORD /" >&2
echo " ANDROID_KEY_PASSWORD / ANDROID_KEYSTORE_FILE." >&2
exit 1
fi
# Load .env without leaking it into the caller's environment beyond what we need.
set -a
# shellcheck disable=SC1090
. "$ENV_FILE"
set +a
: "${ANDROID_KEY_ALIAS:?ANDROID_KEY_ALIAS missing from .env}"
: "${ANDROID_KEYSTORE_PASSWORD:?ANDROID_KEYSTORE_PASSWORD missing from .env}"
: "${ANDROID_KEY_PASSWORD:?ANDROID_KEY_PASSWORD missing from .env}"
: "${ANDROID_KEYSTORE_FILE:?ANDROID_KEYSTORE_FILE missing from .env}"
if [ ! -f "$ANDROID_KEYSTORE_FILE" ]; then
echo "❌ Keystore not found at ANDROID_KEYSTORE_FILE=$ANDROID_KEYSTORE_FILE" >&2
exit 1
fi
mkdir -p "$(dirname "$PROPS")"
umask 077
cat > "$PROPS" <<EOF
storeFile=$ANDROID_KEYSTORE_FILE
storePassword=$ANDROID_KEYSTORE_PASSWORD
keyAlias=$ANDROID_KEY_ALIAS
keyPassword=$ANDROID_KEY_PASSWORD
EOF
echo "🔐 Wrote release signing config to keystore.properties (from .env)"
@@ -295,6 +295,14 @@ class JellyTauPlaybackService : MediaSessionService() {
// Update MediaSession playback state // Update MediaSession playback state
session.setPlaybackState(buildPlaybackState(isPlaying, position)) session.setPlaybackState(buildPlaybackState(isPlaying, position))
// While casting, re-assert the remote volume provider. Metadata pushes
// arrive on the session poller thread and can race with (or arrive
// before) enableRemoteVolume(); this keeps the session routed to the
// remote (absolute) volume slider instead of the local media stream.
if (isRemoteVolumeEnabled) {
volumeProvider?.let { session.setPlaybackToRemote(it) }
}
// Update the notification // Update the notification
updateNotification(title, artist, isPlaying) updateNotification(title, artist, isPlaying)
} }
@@ -326,8 +334,17 @@ class JellyTauPlaybackService : MediaSessionService() {
* *
* The reported playback speed is 1.0 while playing and 0.0 while paused so * The reported playback speed is 1.0 while playing and 0.0 while paused so
* Android does not extrapolate the position past a paused track. * Android does not extrapolate the position past a paused track.
*
* While remote volume control is enabled (casting), the state is forced to
* STATE_PLAYING regardless of [isPlaying]. Android only surfaces the remote
* (absolute) volume slider for a session that is actively playing; if a
* periodic metadata/position push reports paused (e.g. before the remote
* session has actually started), reporting STATE_PAUSED here makes the
* system tear down the remote slider set up by setPlaybackToRemote() and
* fall back to the local media-stream volume.
*/ */
private fun buildPlaybackState(isPlaying: Boolean, position: Long): PlaybackStateCompat { private fun buildPlaybackState(isPlaying: Boolean, position: Long): PlaybackStateCompat {
val playing = isPlaying || isRemoteVolumeEnabled
return PlaybackStateCompat.Builder() return PlaybackStateCompat.Builder()
.setActions( .setActions(
PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PLAY or
@@ -338,9 +355,9 @@ class JellyTauPlaybackService : MediaSessionService() {
PlaybackStateCompat.ACTION_SEEK_TO PlaybackStateCompat.ACTION_SEEK_TO
) )
.setState( .setState(
if (isPlaying) PlaybackStateCompat.STATE_PLAYING else PlaybackStateCompat.STATE_PAUSED, if (playing) PlaybackStateCompat.STATE_PLAYING else PlaybackStateCompat.STATE_PAUSED,
position, position,
if (isPlaying) 1.0f else 0.0f if (playing) 1.0f else 0.0f
) )
.build() .build()
} }
@@ -2,5 +2,4 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@mipmap/ic_launcher_background"/> <background android:drawable="@mipmap/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/> <foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
</adaptive-icon> </adaptive-icon>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

+1 -1
View File
@@ -133,7 +133,7 @@ impl AuthManager {
log::info!("[AuthManager] Connecting to server: {}", normalized_url); log::info!("[AuthManager] Connecting to server: {}", normalized_url);
match self.http_client.get_json_with_retry::<PublicSystemInfo>(&endpoint).await { match self.http_client.get_json_fast::<PublicSystemInfo>(&endpoint).await {
Ok(info) => { Ok(info) => {
log::info!("[AuthManager] Connected to server: {} ({})", info.server_name, info.version); log::info!("[AuthManager] Connected to server: {} ({})", info.server_name, info.version);
+469
View File
@@ -0,0 +1,469 @@
//! Tauri commands for the offline "browse & queue" feature.
//!
//! Two backend pieces support browsing the full server catalog while offline
//! and queueing downloads that fire on reconnect:
//!
//! - [`sync_full_catalog`] walks every library while online and persists all
//! items to the offline cache so the whole catalog is browsable (greyed out)
//! offline. It reuses [`HybridRepository::cache_items_from_server`], which in
//! turn reuses `OfflineRepository::save_to_cache` (sets `synced_at`, which is
//! what `get_items` branch 3 serves offline).
//! - [`resume_queued_downloads`] resolves and pumps the `pending` download rows
//! that were queued offline (they have `stream_url IS NULL`), mirroring the
//! heal-and-pump pattern in `player_preload_upcoming`.
use std::sync::Arc;
use log::{info, warn};
use tauri::State;
use crate::commands::repository::RepositoryManagerWrapper;
use crate::commands::download::{pump_download_queue, DownloadManagerWrapper};
use crate::commands::storage::DatabaseWrapper;
use crate::repository::types::GetItemsOptions;
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
/// app_settings key holding the RFC-3339 timestamp of the last successful
/// full-catalog sync.
const LAST_CATALOG_SYNC_KEY: &str = "last_catalog_sync";
/// Item types worth caching for offline browsing: containers the library
/// landing pages render plus the playable leaves users queue for download.
const CATALOG_ITEM_TYPES: &[&str] = &[
"MusicAlbum",
"Movie",
"Series",
"Season",
"Episode",
"Audio",
"BoxSet",
];
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CatalogSyncResult {
/// Total items persisted to the offline cache across all libraries.
pub items_cached: usize,
/// Libraries that failed to sync (e.g. server hiccup); best-effort.
pub libraries_failed: usize,
}
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CatalogSyncStatus {
/// RFC-3339 timestamp of the last successful sync, if any.
pub last_synced_at: Option<String>,
}
/// Walk every library on the server and persist all items to the offline cache
/// so the full catalog is browsable offline (greyed out when not downloaded).
///
/// Best-effort: a library that fails to fetch is counted and skipped rather than
/// aborting the whole sync. Runs libraries sequentially to avoid hammering the
/// server. Uses `Recursive=true` so a single request per library returns the
/// containers and their playable children.
#[tauri::command]
#[specta::specta]
pub async fn sync_full_catalog(
repository: State<'_, RepositoryManagerWrapper>,
db: State<'_, DatabaseWrapper>,
handle: String,
) -> Result<CatalogSyncResult, String> {
use crate::repository::MediaRepository;
let repo = repository.0.get(&handle).ok_or("Repository not found")?;
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let libraries = repo.get_libraries().await.map_err(|e| e.to_string())?;
info!("[Catalog] Full sync starting across {} libraries", libraries.len());
let include_types: Vec<String> = CATALOG_ITEM_TYPES.iter().map(|s| s.to_string()).collect();
let mut items_cached = 0usize;
let mut libraries_failed = 0usize;
for library in &libraries {
let opts = GetItemsOptions {
recursive: Some(true),
include_item_types: Some(include_types.clone()),
limit: Some(100_000),
..Default::default()
};
match repo.cache_items_from_server(&library.id, Some(opts)).await {
Ok(items) => {
info!(
"[Catalog] Cached {} items from library '{}'",
items.len(),
library.name
);
items_cached += items.len();
}
Err(e) => {
warn!("[Catalog] Failed to sync library '{}': {:?}", library.name, e);
libraries_failed += 1;
}
}
}
// Record the sync time so callers can skip re-syncing too eagerly.
let now = chrono::Utc::now().to_rfc3339();
let upsert = Query::with_params(
"INSERT INTO app_settings (key, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP",
vec![
QueryParam::String(LAST_CATALOG_SYNC_KEY.to_string()),
QueryParam::String(now),
],
);
if let Err(e) = db_service.execute(upsert).await {
warn!("[Catalog] Failed to persist last-sync timestamp: {}", e);
}
info!(
"[Catalog] Full sync complete: {} items cached, {} libraries failed",
items_cached, libraries_failed
);
Ok(CatalogSyncResult {
items_cached,
libraries_failed,
})
}
/// Report the last-synced timestamp so the UI can show a hint / decide whether
/// to trigger a fresh sync.
#[tauri::command]
#[specta::specta]
pub async fn catalog_sync_status(
db: State<'_, DatabaseWrapper>,
) -> Result<CatalogSyncStatus, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let query = Query::with_params(
"SELECT value FROM app_settings WHERE key = ?",
vec![QueryParam::String(LAST_CATALOG_SYNC_KEY.to_string())],
);
let last_synced_at: Option<String> = db_service
.query_optional(query, |row| row.get(0))
.await
.map_err(|e| e.to_string())?;
Ok(CatalogSyncStatus { last_synced_at })
}
/// Control whether offline library queries reveal the full synced catalog
/// (greyed-out, non-downloaded media) or only downloaded/local media.
///
/// The frontend calls this from the "Show all server media" toggle: pass `true`
/// when online, or when offline with the toggle on; pass `false` when offline
/// with the toggle off so library pages show downloaded media only. Fixes the
/// bug where offline library pages showed every server item regardless of the
/// toggle.
#[tauri::command]
#[specta::specta]
pub fn set_show_server_catalog(show: bool) {
crate::repository::offline::set_include_catalog_browse(show);
}
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResumeQueuedResult {
/// Rows whose stream URL was resolved and are now pump-eligible.
pub resolved: usize,
/// Rows that couldn't be resolved (item metadata / URL lookup failed).
pub failed: usize,
}
/// Core of [`resume_queued_downloads`], factored out for testing: select every
/// `pending`/`stream_url IS NULL` row, resolve each via `resolve` (returning
/// `None` leaves the row pending), and heal the row so the pump can start it.
/// The `resolve` closure receives `(item_id, media_type, quality_preset)`.
pub(crate) async fn resolve_pending_download_urls<F, Fut>(
db_service: &Arc<crate::storage::db_service::RusqliteService>,
target_dir: &str,
resolve: F,
) -> Result<ResumeQueuedResult, String>
where
F: Fn(String, String, String) -> Fut,
Fut: std::future::Future<Output = Option<String>>,
{
let rows_query = Query::new(
"SELECT id, item_id, COALESCE(media_type, 'audio'), COALESCE(quality_preset, 'original')
FROM downloads
WHERE status = 'pending' AND stream_url IS NULL",
);
let rows: Vec<(i64, String, String, String)> = db_service
.query_many(rows_query, |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
})
.await
.map_err(|e| e.to_string())?;
if rows.is_empty() {
return Ok(ResumeQueuedResult { resolved: 0, failed: 0 });
}
info!("[Catalog] Resolving {} offline-queued downloads on reconnect", rows.len());
let mut resolved = 0usize;
let mut failed = 0usize;
for (download_id, item_id, media_type, quality) in rows {
let stream_url = match resolve(item_id.clone(), media_type, quality).await {
Some(url) => url,
None => {
failed += 1;
continue;
}
};
// Heal the row so the pump can start it. Guard on stream_url IS NULL so a
// concurrent resolver doesn't clobber an already-started row.
let update = Query::with_params(
"UPDATE downloads SET stream_url = ?, target_dir = ?
WHERE id = ? AND status = 'pending' AND stream_url IS NULL",
vec![
QueryParam::String(stream_url),
QueryParam::String(target_dir.to_string()),
QueryParam::Int64(download_id),
],
);
match db_service.execute(update).await {
Ok(n) if n > 0 => resolved += 1,
Ok(_) => {} // already resolved by someone else; not a failure
Err(e) => {
warn!("[Catalog] Failed to persist URL for download {}: {}", download_id, e);
failed += 1;
}
}
}
Ok(ResumeQueuedResult { resolved, failed })
}
/// Resolve the stream URL for every download row that was queued while offline
/// (`status = 'pending' AND stream_url IS NULL`), then pump the queue so they
/// start. Call this on reconnect.
///
/// Audio rows resolve via `get_audio_stream_url`; video rows (media_type =
/// 'video') via the pure `get_video_download_url` builder using the row's stored
/// `quality_preset` — mirroring `enqueue_video_downloads`. Rows whose URL can't
/// be resolved are left pending (they retry on the next reconnect).
#[tauri::command]
#[specta::specta]
pub async fn resume_queued_downloads(
repository: State<'_, RepositoryManagerWrapper>,
db: State<'_, DatabaseWrapper>,
download_manager: State<'_, DownloadManagerWrapper>,
app: tauri::AppHandle,
handle: String,
) -> Result<ResumeQueuedResult, String> {
use crate::repository::MediaRepository;
use crate::repository::HybridRepository;
let repo = repository.0.get(&handle).ok_or("Repository not found")?;
// The pump needs a target_dir; use the same storage root the other download
// paths use (the database's parent directory — see `storage_get_path`).
let (db_service, target_dir) = {
let database = db.0.lock().map_err(|e| e.to_string())?;
let target_dir = database
.path()
.parent()
.ok_or_else(|| "Database path has no parent directory".to_string())?
.to_string_lossy()
.to_string();
(Arc::new(database.service()), target_dir)
};
// Recover stale downloads: rows left in 'downloading' when the app was killed
// mid-transfer are orphaned — nothing ever restarts them, so they show as
// permanently "downloading". Reset them to 'pending' and clear the stale
// stream_url so they get re-resolved and restarted from scratch below.
let recover_query = Query::new(
"UPDATE downloads SET status = 'pending', stream_url = NULL, progress = 0, \
bytes_downloaded = 0, started_at = NULL \
WHERE status = 'downloading'",
);
match db_service.execute(recover_query).await {
Ok(n) if n > 0 => info!("[Catalog] Reset {} stale 'downloading' rows to pending", n),
Ok(_) => {}
Err(e) => warn!("[Catalog] Failed to reset stale downloads: {}", e),
}
// Resolve each row's URL against the (now reachable) repository.
let repo_for_resolve = Arc::clone(&repo);
let outcome = resolve_pending_download_urls(
&db_service,
&target_dir,
move |item_id: String, media_type: String, quality: String| {
let repo = Arc::clone(&repo_for_resolve);
async move {
if media_type == "video" {
Some(<HybridRepository as MediaRepository>::get_video_download_url(
repo.as_ref(),
&item_id,
&quality,
None,
))
} else {
match repo.get_audio_stream_url(&item_id).await {
Ok(url) => Some(url),
Err(e) => {
warn!("[Catalog] Failed to resolve audio URL for {}: {:?}", item_id, e);
None
}
}
}
}
},
)
.await
.map_err(|e| e.to_string())?;
let ResumeQueuedResult { resolved, failed } = outcome;
// Kick the pump so the newly-resolved rows actually start.
if resolved > 0 {
let active_downloads = {
let manager = download_manager.0.lock().map_err(|e| e.to_string())?;
manager.get_active_downloads()
};
pump_download_queue(app, db_service, active_downloads).await;
}
info!("[Catalog] Resume complete: {} resolved, {} failed", resolved, failed);
Ok(ResumeQueuedResult { resolved, failed })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::storage::db_service::RusqliteService;
use rusqlite::Connection;
use std::sync::Mutex;
fn test_db() -> Arc<RusqliteService> {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
r#"
CREATE TABLE downloads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
item_id TEXT NOT NULL,
status TEXT NOT NULL,
stream_url TEXT,
target_dir TEXT,
media_type TEXT,
quality_preset TEXT
);
"#,
)
.unwrap();
Arc::new(RusqliteService::new(Arc::new(Mutex::new(conn))))
}
async fn insert_download(
db: &Arc<RusqliteService>,
item_id: &str,
status: &str,
stream_url: Option<&str>,
media_type: Option<&str>,
) {
let q = Query::with_params(
"INSERT INTO downloads (item_id, status, stream_url, media_type) VALUES (?, ?, ?, ?)",
vec![
QueryParam::String(item_id.to_string()),
QueryParam::String(status.to_string()),
stream_url.map(|s| QueryParam::String(s.to_string())).unwrap_or(QueryParam::Null),
media_type.map(|s| QueryParam::String(s.to_string())).unwrap_or(QueryParam::Null),
],
);
db.execute(q).await.unwrap();
}
async fn get_row(db: &Arc<RusqliteService>, item_id: &str) -> (String, Option<String>, Option<String>) {
let q = Query::with_params(
"SELECT status, stream_url, target_dir FROM downloads WHERE item_id = ?",
vec![QueryParam::String(item_id.to_string())],
);
db.query_one(q, |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
.await
.unwrap()
}
#[tokio::test]
async fn resolves_offline_queued_row_and_leaves_resolved_rows_untouched() {
let db = test_db();
// A row queued offline: pending with no URL yet.
insert_download(&db, "queued-1", "pending", None, None).await;
// An already-resolved pending row: must NOT be touched.
insert_download(&db, "already", "pending", Some("http://existing/url"), None).await;
// A completed row: irrelevant.
insert_download(&db, "done", "completed", Some("http://done/url"), None).await;
let out = resolve_pending_download_urls(&db, "/data/downloads", |item_id, _mt, _q| async move {
Some(format!("http://resolved/{item_id}"))
})
.await
.unwrap();
assert_eq!(out.resolved, 1);
assert_eq!(out.failed, 0);
// The offline-queued row now has a URL + target dir and stays pending.
let (status, url, target) = get_row(&db, "queued-1").await;
assert_eq!(status, "pending");
assert_eq!(url.as_deref(), Some("http://resolved/queued-1"));
assert_eq!(target.as_deref(), Some("/data/downloads"));
// The already-resolved row is unchanged (not re-resolved).
let (_s, url2, _t) = get_row(&db, "already").await;
assert_eq!(url2.as_deref(), Some("http://existing/url"));
}
#[tokio::test]
async fn counts_unresolvable_rows_as_failed_and_leaves_them_pending() {
let db = test_db();
insert_download(&db, "bad", "pending", None, None).await;
// Resolver returns None (e.g. server lookup failed).
let out = resolve_pending_download_urls(&db, "/data", |_id, _mt, _q| async move { None })
.await
.unwrap();
assert_eq!(out.resolved, 0);
assert_eq!(out.failed, 1);
// Still pending with no URL, so a later reconnect can retry it.
let (status, url, _t) = get_row(&db, "bad").await;
assert_eq!(status, "pending");
assert_eq!(url, None);
}
#[tokio::test]
async fn video_rows_use_media_type_in_resolver() {
let db = test_db();
insert_download(&db, "vid-1", "pending", None, Some("video")).await;
let out = resolve_pending_download_urls(&db, "/data", |item_id, media_type, _q| async move {
assert_eq!(media_type, "video");
Some(format!("http://transcode/{item_id}"))
})
.await
.unwrap();
assert_eq!(out.resolved, 1);
let (_s, url, _t) = get_row(&db, "vid-1").await;
assert_eq!(url.as_deref(), Some("http://transcode/vid-1"));
}
}
+50 -12
View File
@@ -1268,13 +1268,50 @@ fn spawn_download_worker(
debug!(" Unregistered download {}. Active downloads: {}", download_id, active.len()); debug!(" Unregistered download {}. Active downloads: {}", download_id, active.len());
} }
// The pump runs downloads in the background, so the terminal status MUST
// be persisted to the DB here — the frontend event handler only writes it
// when that download happens to be loaded in its store, which is not the
// case for auto-pumped rows (or any completion while the downloads page is
// closed). `check_for_local_download` filters on status = 'completed', so a
// missed write leaves finished files unrecognized: albums never show as
// downloaded and playback never switches from the (expiring) stream to the
// local file, cutting tracks off mid-play.
let db_service = {
let db = app.state::<DatabaseWrapper>();
let database = match db.0.lock() {
Ok(d) => d,
Err(e) => {
error!("[pump] Failed to lock database after download {}: {}", download_id, e);
return;
}
};
Arc::new(database.service())
};
match result { match result {
Ok(res) => { Ok(res) => {
info!("Download completed successfully: {} bytes", res.bytes_downloaded); info!("Download completed successfully: {} bytes", res.bytes_downloaded);
let file_path = target_path.to_string_lossy().to_string();
let update = Query::with_params(
"UPDATE downloads SET status = 'completed', progress = 1.0, \
bytes_downloaded = ?, file_size = ?, file_path = ?, \
completed_at = CURRENT_TIMESTAMP WHERE id = ?",
vec![
QueryParam::Int64(res.bytes_downloaded as i64),
QueryParam::Int64(res.bytes_downloaded as i64),
QueryParam::String(file_path.clone()),
QueryParam::Int64(download_id),
],
);
if let Err(e) = db_service.execute(update).await {
error!("[pump] Failed to persist completed status for download {}: {}", download_id, e);
}
let completed_event = DownloadEvent::Completed { let completed_event = DownloadEvent::Completed {
download_id, download_id,
item_id, item_id,
file_path: target_path.to_string_lossy().to_string(), file_path,
}; };
match app.emit("download-event", completed_event) { match app.emit("download-event", completed_event) {
Ok(_) => debug!(" Completed event emitted successfully"), Ok(_) => debug!(" Completed event emitted successfully"),
@@ -1283,6 +1320,18 @@ fn spawn_download_worker(
} }
Err(e) => { Err(e) => {
error!("Download failed: {:?}", e); error!("Download failed: {:?}", e);
let update = Query::with_params(
"UPDATE downloads SET status = 'failed', error_message = ? WHERE id = ?",
vec![
QueryParam::String(e.to_string()),
QueryParam::Int64(download_id),
],
);
if let Err(db_err) = db_service.execute(update).await {
error!("[pump] Failed to persist failed status for download {}: {}", download_id, db_err);
}
let failed_event = DownloadEvent::Failed { let failed_event = DownloadEvent::Failed {
download_id, download_id,
item_id, item_id,
@@ -1296,17 +1345,6 @@ fn spawn_download_worker(
} }
// A slot just freed — start the next pending download (if any). // A slot just freed — start the next pending download (if any).
let db_service = {
let db = app.state::<DatabaseWrapper>();
let database = match db.0.lock() {
Ok(d) => d,
Err(e) => {
error!("[pump] Failed to lock database after download {}: {}", download_id, e);
return;
}
};
Arc::new(database.service())
};
pump_download_queue(app.clone(), db_service, active_downloads).await; pump_download_queue(app.clone(), db_service, active_downloads).await;
}); });
} }
+2
View File
@@ -2,6 +2,7 @@
// TRACES: UR-002, UR-003, UR-004, UR-005, UR-009, UR-011, UR-012, UR-017, UR-019, UR-025 | // TRACES: UR-002, UR-003, UR-004, UR-005, UR-009, UR-011, UR-012, UR-017, UR-019, UR-025 |
// DR-015, DR-017, DR-021, DR-028 // DR-015, DR-017, DR-021, DR-028
pub mod auth; pub mod auth;
pub mod catalog;
pub mod connectivity; pub mod connectivity;
pub mod conversions; pub mod conversions;
pub mod device; pub mod device;
@@ -17,6 +18,7 @@ pub mod storage;
pub mod sync; pub mod sync;
pub use auth::*; pub use auth::*;
pub use catalog::*;
pub use connectivity::*; pub use connectivity::*;
pub use conversions::*; pub use conversions::*;
pub use device::*; pub use device::*;
+49 -10
View File
@@ -696,6 +696,11 @@ pub async fn player_stop(
let controller = player.0.lock().await; let controller = player.0.lock().await;
controller.stop().map_err(|e| e.to_string())?; controller.stop().map_err(|e| e.to_string())?;
// A genuine local stop returns the manager to Idle so it no longer
// reports Local (or a stale Remote) — otherwise a later play/pause would
// route to the wrong device.
playback_mode.0.set_mode(crate::playback_mode::PlaybackMode::Idle);
// Handle session state based on type (local playback only) // Handle session state based on type (local playback only)
{ {
let mut session_mgr = session.0.lock().map_err(|e| e.to_string())?; let mut session_mgr = session.0.lock().map_err(|e| e.to_string())?;
@@ -1422,13 +1427,14 @@ pub async fn player_play_album_track(
info!(" [{}] {} (ID: {})", idx, track.name, track.id); info!(" [{}] {} (ID: {})", idx, track.name, track.id);
} }
// Find the index of the requested track // Validate the requested track exists in the album (its position in the
// final queue is computed after building, since offline tracks are skipped).
info!("Looking for track_id: {}", request.track_id); info!("Looking for track_id: {}", request.track_id);
let start_index = tracks.iter() let album_index = tracks.iter()
.position(|t| t.id == request.track_id) .position(|t| t.id == request.track_id)
.ok_or_else(|| format!("Track {} not found in album", request.track_id))?; .ok_or_else(|| format!("Track {} not found in album", request.track_id))?;
info!("Track {} is at index {} in album", request.track_id, start_index); info!("Track {} is at index {} in album", request.track_id, album_index);
// Convert tracks to MediaItems // Convert tracks to MediaItems
let mut media_items = Vec::new(); let mut media_items = Vec::new();
@@ -1443,13 +1449,21 @@ pub async fn player_play_album_track(
jellyfin_item_id: Some(jellyfin_id.clone()), jellyfin_item_id: Some(jellyfin_id.clone()),
} }
} else { } else {
// Get stream URL from repository (works online/offline) // Non-downloaded track: needs a stream URL from the server. When the
let stream_url = repository.get_audio_stream_url(&track.id).await // server is unreachable (offline), skip this track rather than failing
.map_err(|e| format!("Failed to get stream URL for {}: {}", track.name, e))?; // the whole album — downloaded tracks must still be playable.
match repository.get_audio_stream_url(&track.id).await {
MediaSource::Remote { Ok(stream_url) => MediaSource::Remote {
stream_url, stream_url,
jellyfin_item_id: jellyfin_id.clone(), jellyfin_item_id: jellyfin_id.clone(),
},
Err(e) => {
warn!(
"[Player] Skipping track {} ({}) — no local download and stream URL unavailable: {}",
track.name, track.id, e
);
continue;
}
} }
}; };
@@ -1489,6 +1503,18 @@ pub async fn player_play_album_track(
media_items.push(media_item); media_items.push(media_item);
} }
if media_items.is_empty() {
return Err("No playable tracks available (offline and nothing downloaded)".to_string());
}
// Tracks with no local download and no reachable server were skipped above,
// so positions shifted. Re-locate the requested track in the built queue.
// If the tapped track itself was skipped, fall back to the first item.
let start_index = media_items
.iter()
.position(|item| item.id == request.track_id)
.unwrap_or(0);
info!("Built queue with {} media items, starting at index {}", media_items.len(), start_index); info!("Built queue with {} media items, starting at index {}", media_items.len(), start_index);
// Handle shuffle before setting queue // Handle shuffle before setting queue
@@ -1517,6 +1543,9 @@ pub async fn player_play_album_track(
play_selection_on_remote(&controller, session_id, &media_items, start_index).await?; play_selection_on_remote(&controller, session_id, &media_items, start_index).await?;
controller.set_queue(media_items, start_index).map_err(|e| e.to_string())?; controller.set_queue(media_items, start_index).map_err(|e| e.to_string())?;
} else { } else {
// Local playback is now authoritative (see player_play_tracks); set it
// before starting so the mode-changed event precedes the state events.
playback_mode.0.set_mode(crate::playback_mode::PlaybackMode::Local);
controller controller
.play_queue(media_items, start_index) .play_queue(media_items, start_index)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
@@ -1693,6 +1722,16 @@ pub async fn player_play_tracks(
.set_queue(media_items, request.start_index) .set_queue(media_items, request.start_index)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
} else { } else {
// Starting local playback makes Local the authoritative mode. Without
// this, a prior Remote mode lingers in the manager and later play/pause
// commands route back to the (stopped) remote session. Set it BEFORE
// starting playback so the PlaybackModeChanged event reaches the frontend
// ahead of the state_changed events it will emit — otherwise the frontend
// (still thinking it's remote) filters those state events out. Skip during
// a transfer: transfer_to_local drives the mode itself once complete.
if !playback_mode.0.is_transferring() {
playback_mode.0.set_mode(crate::playback_mode::PlaybackMode::Local);
}
controller controller
.play_queue_from(media_items, request.start_index, request.start_position) .play_queue_from(media_items, request.start_index, request.start_position)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
+39
View File
@@ -217,6 +217,45 @@ impl HttpClient {
.map_err(|e| format!("Failed to parse JSON: {}", e)) .map_err(|e| format!("Failed to parse JSON: {}", e))
} }
/// Make a GET request and deserialize JSON with a short timeout and no retries.
///
/// Intended for the initial "connect to server" probe on the login screen:
/// a wrong/unreachable URL must fail fast instead of burning through the
/// default 30s-per-attempt timeout and exponential backoff retries.
pub async fn get_json_fast<T: DeserializeOwned>(&self, url: &str) -> Result<T, String> {
// Short timeout so an unreachable host fails quickly.
const FAST_TIMEOUT: Duration = Duration::from_secs(10);
let request = self
.client
.get(url)
.timeout(FAST_TIMEOUT)
.build()
.map_err(|e| format!("Failed to build request: {}", e))?;
// No retry: connection failures on a wrong URL won't succeed on retry,
// they'd only multiply the wait the user sees before an error.
let response = self
.client
.execute(request)
.await
.map_err(|e| format!("Request failed: {}", e))?;
if !response.status().is_success() {
let status = response.status();
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(format!("HTTP {}: {}", status, error_text));
}
response
.json::<T>()
.await
.map_err(|e| format!("Failed to parse JSON: {}", e))
}
/// Quick ping to check if a server is reachable (no retry) /// Quick ping to check if a server is reachable (no retry)
pub async fn ping(&self, url: &str) -> bool { pub async fn ping(&self, url: &str) -> bool {
let request = self.client.get(url) let request = self.client.get(url)
+18 -2
View File
@@ -23,6 +23,7 @@ use log::{error, info};
use log::warn; use log::warn;
use commands::{ use commands::{
sync_full_catalog, catalog_sync_status, set_show_server_catalog, resume_queued_downloads,
cancel_download, clear_stale_downloads, delete_album_downloads, delete_all_downloads, delete_download, cancel_download, clear_stale_downloads, delete_album_downloads, delete_all_downloads, delete_download,
download_album, download_item, download_item_and_start, download_video, download_series, download_season, download_album, download_item, download_item_and_start, download_video, download_series, download_season,
get_download_storage_stats, get_downloads, get_download_manager_stats, set_max_concurrent_downloads, get_download_storage_stats, get_downloads, get_download_manager_stats, set_max_concurrent_downloads,
@@ -585,6 +586,10 @@ fn specta_builder() -> Builder<tauri::Wry> {
start_download, start_download,
enqueue_download, enqueue_download,
enqueue_video_downloads, enqueue_video_downloads,
sync_full_catalog,
catalog_sync_status,
set_show_server_catalog,
resume_queued_downloads,
get_download_manager_stats, get_download_manager_stats,
set_max_concurrent_downloads, set_max_concurrent_downloads,
get_smart_cache_stats, get_smart_cache_stats,
@@ -920,6 +925,9 @@ pub fn run() {
player_arc.clone(), player_arc.clone(),
); );
let playback_mode_arc = Arc::new(playback_mode_manager); let playback_mode_arc = Arc::new(playback_mode_manager);
// Broadcast mode changes so the frontend's mirror store reconciles to
// this authoritative one (prevents remote/local control desync).
playback_mode_arc.set_event_emitter(event_emitter.clone());
let playback_mode_wrapper = PlaybackModeManagerWrapper(playback_mode_arc.clone()); let playback_mode_wrapper = PlaybackModeManagerWrapper(playback_mode_arc.clone());
app.manage(playback_mode_wrapper); app.manage(playback_mode_wrapper);
@@ -930,9 +938,11 @@ pub fn run() {
playback_mode_arc.clone(), playback_mode_arc.clone(),
); );
session_poller.set_event_emitter(event_emitter.clone()); session_poller.set_event_emitter(event_emitter.clone());
session_poller.start(); // Note: start() is deferred until after the connectivity monitor is
// created below, so the poller can report reachability from its first
// poll (it drives offline detection + recovery while the user is idle).
let session_poller_arc = Arc::new(session_poller); let session_poller_arc = Arc::new(session_poller);
let session_poller_wrapper = SessionPollerWrapper(session_poller_arc); let session_poller_wrapper = SessionPollerWrapper(session_poller_arc.clone());
app.manage(session_poller_wrapper); app.manage(session_poller_wrapper);
// On Android, set up the MediaSession (lockscreen) handler and the // On Android, set up the MediaSession (lockscreen) handler and the
@@ -994,6 +1004,12 @@ pub fn run() {
let mut connectivity_monitor = ConnectivityMonitor::new(http_client); let mut connectivity_monitor = ConnectivityMonitor::new(http_client);
connectivity_monitor.set_app_handle(app.handle().clone()); connectivity_monitor.set_app_handle(app.handle().clone());
// Wire the connectivity reporter into the session poller so its
// continuous background polls drive reachability (offline detection
// + recovery) even when the user isn't browsing, then start it.
session_poller_arc.set_connectivity_reporter(connectivity_monitor.reporter());
session_poller_arc.start();
// Wrap in Arc for sharing with AuthManager // Wrap in Arc for sharing with AuthManager
let connectivity_arc = Arc::new(tokio::sync::Mutex::new(connectivity_monitor)); let connectivity_arc = Arc::new(tokio::sync::Mutex::new(connectivity_monitor));
let connectivity_wrapper = ConnectivityMonitorWrapper(connectivity_arc.clone()); let connectivity_wrapper = ConnectivityMonitorWrapper(connectivity_arc.clone());
+119 -4
View File
@@ -9,7 +9,7 @@ use tokio::sync::Mutex as TokioMutex;
use tokio::time::{sleep, Duration}; use tokio::time::{sleep, Duration};
use crate::jellyfin::JellyfinClient; use crate::jellyfin::JellyfinClient;
use crate::player::{PlayerController, QueueContext}; use crate::player::{PlayerController, PlayerEventEmitter, PlayerStatusEvent, QueueContext};
/// Playback mode - local device, remote session, or idle /// Playback mode - local device, remote session, or idle
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
@@ -48,6 +48,9 @@ pub struct PlaybackModeManager {
player_controller: Arc<TokioMutex<PlayerController>>, player_controller: Arc<TokioMutex<PlayerController>>,
current_mode: Arc<RwLock<PlaybackMode>>, current_mode: Arc<RwLock<PlaybackMode>>,
is_transferring: Arc<AtomicBool>, is_transferring: Arc<AtomicBool>,
/// Optional emitter used to notify the frontend when the mode changes, so its
/// mirror store stays in sync with this authoritative one. `None` in tests.
event_emitter: Arc<Mutex<Option<Arc<dyn PlayerEventEmitter>>>>,
} }
impl PlaybackModeManager { impl PlaybackModeManager {
@@ -61,19 +64,53 @@ impl PlaybackModeManager {
player_controller, player_controller,
current_mode: Arc::new(RwLock::new(PlaybackMode::Idle)), current_mode: Arc::new(RwLock::new(PlaybackMode::Idle)),
is_transferring: Arc::new(AtomicBool::new(false)), is_transferring: Arc::new(AtomicBool::new(false)),
event_emitter: Arc::new(Mutex::new(None)),
} }
} }
/// Wire the event emitter so `set_mode` notifies the frontend. Called once
/// during setup; safe to leave unset (tests do), in which case mode changes
/// simply aren't broadcast.
pub fn set_event_emitter(&self, emitter: Arc<dyn PlayerEventEmitter>) {
*self.event_emitter.lock_safe() = Some(emitter);
}
/// Get current playback mode /// Get current playback mode
pub fn get_mode(&self) -> PlaybackMode { pub fn get_mode(&self) -> PlaybackMode {
self.current_mode.read_safe().clone() self.current_mode.read_safe().clone()
} }
/// Set playback mode (internal use) /// Set playback mode (internal use).
///
/// Broadcasts a `PlaybackModeChanged` event when the mode actually changes so
/// the frontend's mirror store reconciles to this authoritative value. The
/// write lock is released before emitting to avoid holding it across the
/// emitter call.
pub fn set_mode(&self, mode: PlaybackMode) { pub fn set_mode(&self, mode: PlaybackMode) {
log::info!("[PlaybackMode] Setting mode to: {:?}", mode); log::info!("[PlaybackMode] Setting mode to: {:?}", mode);
let mut current = self.current_mode.write_safe(); let changed = {
*current = mode; let mut current = self.current_mode.write_safe();
let changed = *current != mode;
*current = mode.clone();
changed
};
if !changed {
return;
}
let (mode_str, session_id) = match &mode {
PlaybackMode::Local => ("local".to_string(), None),
PlaybackMode::Idle => ("idle".to_string(), None),
PlaybackMode::Remote { session_id } => ("remote".to_string(), Some(session_id.clone())),
};
if let Some(emitter) = self.event_emitter.lock_safe().as_ref() {
emitter.emit(PlayerStatusEvent::PlaybackModeChanged {
mode: mode_str,
session_id,
});
}
} }
/// Check if currently transferring /// Check if currently transferring
@@ -702,6 +739,84 @@ mod tests {
); );
} }
/// Capturing emitter so we can assert what `set_mode` broadcasts.
struct CapturingEmitter {
events: Mutex<Vec<PlayerStatusEvent>>,
}
impl PlayerEventEmitter for CapturingEmitter {
fn emit(&self, event: PlayerStatusEvent) {
self.events.lock().unwrap().push(event);
}
}
fn manager_with_emitter() -> (PlaybackModeManager, Arc<CapturingEmitter>) {
let emitter = Arc::new(CapturingEmitter {
events: Mutex::new(Vec::new()),
});
let manager = PlaybackModeManager::new(
Arc::new(Mutex::new(None)),
Arc::new(TokioMutex::new(crate::player::PlayerController::default())),
);
manager.set_event_emitter(emitter.clone());
(manager, emitter)
}
/// set_mode broadcasts a PlaybackModeChanged event with the right payload so
/// the frontend can reconcile its mirror store to this authoritative one.
#[test]
fn test_set_mode_emits_change_event() {
let (manager, emitter) = manager_with_emitter();
manager.set_mode(PlaybackMode::Remote {
session_id: "sess-1".to_string(),
});
manager.set_mode(PlaybackMode::Local);
manager.set_mode(PlaybackMode::Idle);
let events = emitter.events.lock().unwrap();
assert_eq!(events.len(), 3, "one event per real mode change");
match &events[0] {
PlayerStatusEvent::PlaybackModeChanged { mode, session_id } => {
assert_eq!(mode, "remote");
assert_eq!(session_id.as_deref(), Some("sess-1"));
}
other => panic!("expected PlaybackModeChanged, got {:?}", other),
}
match &events[1] {
PlayerStatusEvent::PlaybackModeChanged { mode, session_id } => {
assert_eq!(mode, "local");
assert_eq!(session_id.as_deref(), None);
}
other => panic!("expected PlaybackModeChanged, got {:?}", other),
}
match &events[2] {
PlayerStatusEvent::PlaybackModeChanged { mode, session_id } => {
assert_eq!(mode, "idle");
assert_eq!(session_id.as_deref(), None);
}
other => panic!("expected PlaybackModeChanged, got {:?}", other),
}
}
/// Setting the same mode twice must not re-emit — the frontend reconciler
/// (and the event channel) shouldn't be spammed on no-op transitions.
#[test]
fn test_set_mode_deduplicates_no_op() {
let (manager, emitter) = manager_with_emitter();
manager.set_mode(PlaybackMode::Local);
manager.set_mode(PlaybackMode::Local);
manager.set_mode(PlaybackMode::Local);
assert_eq!(
emitter.events.lock().unwrap().len(),
1,
"repeated identical mode set emits only once"
);
}
/// The resume position handed to a remote session is derived from a live /// The resume position handed to a remote session is derived from a live
/// playback position. Guards the seconds->ticks conversion and the /// playback position. Guards the seconds->ticks conversion and the
/// at-the-start threshold (Bug: casting restarted the track from 0). /// at-the-start threshold (Bug: casting restarted the track from 0).
+15
View File
@@ -124,6 +124,21 @@ pub enum PlayerStatusEvent {
/// All active controllable sessions from Jellyfin /// All active controllable sessions from Jellyfin
sessions: Vec<crate::jellyfin::client::SessionInfo>, sessions: Vec<crate::jellyfin::client::SessionInfo>,
}, },
/// The authoritative playback mode changed in the Rust backend.
///
/// The Rust `PlaybackModeManager` is the single source of truth for which
/// device playback commands route to (local vs a remote session). The
/// frontend keeps a mirror store for the UI; without this event that mirror
/// drifts out of sync (e.g. a mode transition happens inside a transfer or a
/// local stop that the frontend never learns about), and controls then route
/// to the wrong device — the classic "it keeps playing on the remote" bug.
/// The frontend reconciles its store to this payload whenever it fires.
PlaybackModeChanged {
/// New mode: "local", "remote", or "idle".
mode: String,
/// Session id when `mode == "remote"`, otherwise `None`.
session_id: Option<String>,
},
/// The user asked to disconnect from the remote session and resume locally. /// The user asked to disconnect from the remote session and resume locally.
/// ///
/// Emitted when the lockscreen Stop button is pressed while casting. The /// Emitted when the lockscreen Stop button is pressed while casting. The
+104 -14
View File
@@ -79,6 +79,26 @@ impl HybridRepository {
.await .await
} }
/// Fetch a folder's items from the live server and persist them to the
/// offline cache synchronously (unlike `get_items`, which saves in a
/// fire-and-forget background task after a 100ms cache race).
///
/// Used by the full-catalog pre-sync (`sync_full_catalog`) to deterministically
/// walk every library while online so the whole catalog is browsable — greyed
/// out — offline. Returns the items fetched so the caller can recurse into
/// containers. Server-only: errors if unreachable.
pub async fn cache_items_from_server(
&self,
parent_id: &str,
options: Option<GetItemsOptions>,
) -> Result<Vec<MediaItem>, RepoError> {
let result = self.online.get_items(parent_id, options).await?;
if !result.items.is_empty() {
self.offline.save_to_cache(parent_id, &result.items).await?;
}
Ok(result.items)
}
/// Search only the live Jellyfin server (full library). /// Search only the live Jellyfin server (full library).
pub async fn search_server_only( pub async fn search_server_only(
&self, &self,
@@ -196,11 +216,41 @@ impl HybridRepository {
#[async_trait] #[async_trait]
impl MediaRepository for HybridRepository { impl MediaRepository for HybridRepository {
async fn get_libraries(&self) -> Result<Vec<Library>, RepoError> { async fn get_libraries(&self) -> Result<Vec<Library>, RepoError> {
// Libraries change infrequently, try cache first with fast timeout // Cache-first (100ms). On a cache hit, refresh the cache from the server
let cache_future = self.cache_with_timeout(self.offline.get_libraries()); // in the background. On a miss, fetch from the server and persist so the
let server_future = self.online.get_libraries(); // list is available on the next (possibly offline) startup.
let cache_result = self.cache_with_timeout(self.offline.get_libraries()).await;
self.parallel_race(cache_future, server_future).await if let Ok(libs) = &cache_result {
if libs.has_content() {
debug!("[HybridRepo] Cache hit for libraries, returning immediately");
let online = Arc::clone(&self.online);
let offline = Arc::clone(&self.offline);
tokio::spawn(async move {
if let Ok(server_libs) = online.get_libraries().await {
if !server_libs.is_empty() {
if let Err(e) = offline.save_libraries_to_cache(&server_libs).await {
warn!("[HybridRepo] Background library cache update failed: {:?}", e);
}
}
}
});
return cache_result;
}
}
// Cache miss — fetch from server and persist for offline use.
match self.online.get_libraries().await {
Ok(server_libs) => {
if !server_libs.is_empty() {
if let Err(e) = self.offline.save_libraries_to_cache(&server_libs).await {
warn!("[HybridRepo] Failed to cache {} libraries: {:?}", server_libs.len(), e);
}
}
Ok(server_libs)
}
Err(e) => cache_result.or(Err(e)),
}
} }
async fn get_items(&self, parent_id: &str, options: Option<GetItemsOptions>) -> Result<SearchResult, RepoError> { async fn get_items(&self, parent_id: &str, options: Option<GetItemsOptions>) -> Result<SearchResult, RepoError> {
@@ -377,20 +427,60 @@ impl MediaRepository for HybridRepository {
} }
async fn get_genres(&self, parent_id: Option<&str>) -> Result<Vec<Genre>, RepoError> { async fn get_genres(&self, parent_id: Option<&str>) -> Result<Vec<Genre>, RepoError> {
let offline = Arc::clone(&self.offline); // Cache-first (100ms). On a cache hit, refresh the cached genre catalog
let online = Arc::clone(&self.online); // from the server in the background. On a miss, fetch from the server and
// persist so the full genre list is available offline. Mirrors
// get_libraries — NOT parallel_race, whose "any non-empty cache wins"
// rule would pin genres to whatever sparse set the local albums yield.
let parent_id_str = parent_id.map(|s| s.to_string()); let parent_id_str = parent_id.map(|s| s.to_string());
let parent_id_clone = parent_id_str.clone();
let cache_future = self.cache_with_timeout(async move { let cache_offline = Arc::clone(&self.offline);
offline.get_genres(parent_id_str.as_deref()).await let cache_pid = parent_id_str.clone();
}); let cache_result = self
.cache_with_timeout(async move { cache_offline.get_genres(cache_pid.as_deref()).await })
.await;
let server_future = async move { if let Ok(genres) = &cache_result {
online.get_genres(parent_id_clone.as_deref()).await if genres.has_content() {
}; debug!("[HybridRepo] Cache hit for genres, returning immediately");
let online = Arc::clone(&self.online);
let offline = Arc::clone(&self.offline);
let pid = parent_id_str.clone();
tokio::spawn(async move {
if let Ok(server_genres) = online.get_genres(pid.as_deref()).await {
if !server_genres.is_empty() {
if let Err(e) =
offline.save_genres_to_cache(pid.as_deref(), &server_genres).await
{
warn!("[HybridRepo] Background genre cache update failed: {:?}", e);
}
}
}
});
return cache_result;
}
}
self.parallel_race(cache_future, server_future).await // Cache miss — fetch from server and persist for offline use.
match self.online.get_genres(parent_id_str.as_deref()).await {
Ok(server_genres) => {
if !server_genres.is_empty() {
if let Err(e) = self
.offline
.save_genres_to_cache(parent_id_str.as_deref(), &server_genres)
.await
{
warn!(
"[HybridRepo] Failed to cache {} genres: {:?}",
server_genres.len(),
e
);
}
}
Ok(server_genres)
}
Err(e) => cache_result.or(Err(e)),
}
} }
async fn search(&self, query: &str, options: Option<SearchOptions>) -> Result<SearchResult, RepoError> { async fn search(&self, query: &str, options: Option<SearchOptions>) -> Result<SearchResult, RepoError> {
+452 -79
View File
@@ -1,5 +1,6 @@
// Offline repository - queries SQLite database for cached data // Offline repository - queries SQLite database for cached data
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use async_trait::async_trait; use async_trait::async_trait;
use log::debug; use log::debug;
@@ -7,6 +8,30 @@ use log::debug;
use super::{MediaRepository, types::*}; use super::{MediaRepository, types::*};
use crate::storage::db_service::{DatabaseService, Query, QueryParam, RusqliteService}; use crate::storage::db_service::{DatabaseService, Query, QueryParam, RusqliteService};
/// Whether offline library queries may include catalog items that are merely
/// *browsed/synced* but not downloaded (the greyed-out "browse the whole server"
/// view). Defaults to `true` so online browsing (which reads this same cache as
/// a fast path) still sees the full catalog.
///
/// While offline, the frontend drives this from the "Show all server media"
/// toggle: OFF means library pages show only downloaded/local media, ON reveals
/// the full greyed-out catalog. See `set_include_catalog_browse` and the
/// `showServerCatalog` UI flag. Fixes the bug where offline library pages showed
/// every server item regardless of the toggle.
static INCLUDE_CATALOG_BROWSE: AtomicBool = AtomicBool::new(true);
/// Set whether offline `get_items` includes non-downloaded (synced-only) catalog
/// items. Called from the frontend: `true` when online or when the offline
/// "Show all server media" toggle is on; `false` when offline with the toggle
/// off (show downloaded/local media only).
pub fn set_include_catalog_browse(include: bool) {
INCLUDE_CATALOG_BROWSE.store(include, Ordering::Relaxed);
}
fn include_catalog_browse() -> bool {
INCLUDE_CATALOG_BROWSE.load(Ordering::Relaxed)
}
pub struct OfflineRepository { pub struct OfflineRepository {
db_service: Arc<RusqliteService>, db_service: Arc<RusqliteService>,
server_id: String, server_id: String,
@@ -359,6 +384,94 @@ impl OfflineRepository {
Ok(count) Ok(count)
} }
/// Cache the library (view) list from the server into the local database.
/// Called by HybridRepository after a successful online fetch so the list is
/// available offline. Without this, the `libraries` table stays empty and
/// offline startup shows no libraries at all.
pub async fn save_libraries_to_cache(&self, libraries: &[Library]) -> Result<usize, RepoError> {
if libraries.is_empty() {
return Ok(0);
}
let mut count = 0;
for (idx, lib) in libraries.iter().enumerate() {
let query = Query::with_params(
"INSERT OR REPLACE INTO libraries (id, server_id, name, collection_type, image_tag, sort_order, synced_at)
VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)",
vec![
QueryParam::String(lib.id.clone()),
QueryParam::String(self.server_id.clone()),
QueryParam::String(lib.name.clone()),
QueryParam::String(lib.collection_type.clone()),
lib.image_tag.clone().map(QueryParam::String).unwrap_or(QueryParam::Null),
QueryParam::Int(idx as i32),
],
);
self.db_service.execute(query).await
.map_err(|e| RepoError::Database { message: e })?;
count += 1;
}
Ok(count)
}
/// Cache the full server genre catalog for a library, so offline (and the
/// hybrid cache-first race) can return the complete list instead of only the
/// genres derivable from locally-cached albums. Replaces the scope's rows
/// wholesale so genres removed on the server don't linger.
pub async fn save_genres_to_cache(
&self,
parent_id: Option<&str>,
genres: &[Genre],
) -> Result<usize, RepoError> {
if genres.is_empty() {
return Ok(0);
}
// library_id is part of the primary key; NULL keys don't de-dupe in
// SQLite, so store the "no library" scope as an empty string.
let library_id = parent_id.unwrap_or("").to_string();
let server_id = self.server_id.clone();
let genres: Vec<(String, String, Option<u32>)> = genres
.iter()
.map(|g| (g.id.clone(), g.name.clone(), g.album_count))
.collect();
let saved = genres.len();
self.db_service
.transaction(move |tx| {
use crate::storage::db_service::{Query, QueryParam};
// Clear the scope's existing genres, then re-insert the fresh set.
tx.execute(Query::with_params(
"DELETE FROM genres WHERE server_id = ? AND library_id = ?",
vec![
QueryParam::String(server_id.clone()),
QueryParam::String(library_id.clone()),
],
))?;
for (id, name, album_count) in &genres {
tx.execute(Query::with_params(
"INSERT OR REPLACE INTO genres (id, server_id, library_id, name, album_count, synced_at)
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)",
vec![
QueryParam::String(id.clone()),
QueryParam::String(server_id.clone()),
QueryParam::String(library_id.clone()),
QueryParam::String(name.clone()),
album_count.map(|c| QueryParam::Int(c as i32)).unwrap_or(QueryParam::Null),
],
))?;
}
Ok(())
})
.await
.map_err(|e| RepoError::Database { message: e })?;
Ok(saved)
}
/// Cache playlist items from server into local database /// Cache playlist items from server into local database
/// Called by HybridRepository after fetching from online /// Called by HybridRepository after fetching from online
pub async fn save_playlist_items_to_cache( pub async fn save_playlist_items_to_cache(
@@ -413,26 +526,17 @@ impl OfflineRepository {
#[async_trait] #[async_trait]
impl MediaRepository for OfflineRepository { impl MediaRepository for OfflineRepository {
async fn get_libraries(&self) -> Result<Vec<Library>, RepoError> { async fn get_libraries(&self) -> Result<Vec<Library>, RepoError> {
// Only show libraries that have downloaded content // Return every cached library for this server. We deliberately do NOT
// Check both direct children and nested children (e.g., albums inside library) // gate on `items.library_id` here: that column is not populated in the
// cache (the Jellyfin client doesn't parse it), so the old
// `INNER JOIN items i ON i.library_id = l.id` matched nothing and left
// offline startup with zero libraries. Navigating into a library still
// filters to downloaded content via get_items, so listing all cached
// libraries is correct — it's the "local first" list the UI browses.
let query = Query::with_params( let query = Query::with_params(
"SELECT DISTINCT l.id, l.name, l.collection_type, l.image_tag "SELECT l.id, l.name, l.collection_type, l.image_tag
FROM libraries l FROM libraries l
INNER JOIN items i ON i.library_id = l.id
WHERE l.server_id = ? WHERE l.server_id = ?
AND (
-- Direct playable items with downloads
(i.item_type IN ('Audio', 'Movie', 'Episode')
AND EXISTS (SELECT 1 FROM downloads d WHERE d.item_id = i.id AND d.status = 'completed'))
OR
-- Container items with downloaded children
(i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
AND EXISTS (
SELECT 1 FROM items children
INNER JOIN downloads d ON children.id = d.item_id
WHERE children.parent_id = i.id AND d.status = 'completed'
))
)
ORDER BY l.sort_order ASC, l.name ASC", ORDER BY l.sort_order ASC, l.name ASC",
vec![QueryParam::String(self.server_id.clone())], vec![QueryParam::String(self.server_id.clone())],
); );
@@ -479,7 +583,20 @@ impl MediaRepository for OfflineRepository {
// Use CTE to find items that are either: // Use CTE to find items that are either:
// 1. Playable items (Audio, Movie, Episode) with completed downloads (offline mode) // 1. Playable items (Audio, Movie, Episode) with completed downloads (offline mode)
// 2. Container items (MusicAlbum, Series, Season) with at least one downloaded child (offline mode) // 2. Container items (MusicAlbum, Series, Season) with at least one downloaded child (offline mode)
// 3. Cached items with recent synced_at timestamp (online mode - for fast browsing) // 3. Cached items with recent synced_at timestamp (fast online browsing, or the
// offline "Show all server media" catalog view) — only when the catalog-browse
// flag is set. When offline with the toggle off, this branch is omitted so the
// page shows downloaded/local media only. See `set_include_catalog_browse`.
let catalog_branch = if include_catalog_browse() {
"UNION
-- Cached items for fast browsing (online) or the offline catalog view
SELECT DISTINCT i.id
FROM items i
WHERE i.synced_at IS NOT NULL"
} else {
""
};
let sql = format!( let sql = format!(
"WITH available_items AS ( "WITH available_items AS (
-- Playable items with completed downloads -- Playable items with completed downloads
@@ -494,17 +611,12 @@ impl MediaRepository for OfflineRepository {
-- Containers with downloaded children -- Containers with downloaded children
SELECT DISTINCT i.id SELECT DISTINCT i.id
FROM items i FROM items i
INNER JOIN items children ON children.parent_id = i.id INNER JOIN items children ON (children.parent_id = i.id OR children.album_id = i.id OR children.season_id = i.id OR children.series_id = i.id)
INNER JOIN downloads d ON children.id = d.item_id INNER JOIN downloads d ON children.id = d.item_id
WHERE d.status = 'completed' WHERE d.status = 'completed'
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder') AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
UNION {catalog_branch}
-- Cached items for fast browsing (when online)
SELECT DISTINCT i.id
FROM items i
WHERE i.synced_at IS NOT NULL
) )
SELECT i.id, i.name, i.item_type, i.server_id, i.parent_id, i.library_id, i.overview, i.genres, SELECT i.id, i.name, i.item_type, i.server_id, i.parent_id, i.library_id, i.overview, i.genres,
i.runtime_ticks, i.production_year, i.community_rating, i.official_rating, i.runtime_ticks, i.production_year, i.community_rating, i.official_rating,
@@ -513,17 +625,38 @@ impl MediaRepository for OfflineRepository {
i.parent_index_number, i.is_folder, i.premiere_date i.parent_index_number, i.is_folder, i.premiere_date
FROM items i FROM items i
INNER JOIN available_items ai ON i.id = ai.id INNER JOIN available_items ai ON i.id = ai.id
WHERE i.server_id = ? AND i.parent_id = ?{} WHERE i.server_id = ?
AND (
i.parent_id = ? OR i.album_id = ? OR i.season_id = ? OR i.series_id = ?
-- When the requested parent is a LIBRARY, there is no per-item
-- link back to it (library_id/parent_id are NULL in the cache),
-- so match every item on the server and let the type filter
-- (e.g. MusicAlbum / Movie / Series) narrow it. This is what
-- makes library landing pages show albums/movies/shows offline.
OR EXISTS (
SELECT 1 FROM libraries l
WHERE l.id = ? AND l.server_id = i.server_id
)
){}
ORDER BY {} ORDER BY {}
LIMIT {} OFFSET {}", LIMIT {} OFFSET {}",
type_filter, order_by, limit, start_index type_filter, order_by, limit, start_index
); );
// The requested id is compared against every hierarchy-linkage column
// because `parent_id` is not populated for cached items — music tracks
// link to their album via `album_id`, episodes to their season/series
// via `season_id`/`series_id`, and a library parent matches via the
// `libraries` EXISTS clause. See [[offline-libraries-never-cached]].
let query = Query::with_params( let query = Query::with_params(
sql, sql,
vec![ vec![
QueryParam::String(self.server_id.clone()), QueryParam::String(self.server_id.clone()),
QueryParam::String(parent_id.to_string()), QueryParam::String(parent_id.to_string()), // i.parent_id = ?
QueryParam::String(parent_id.to_string()), // i.album_id = ?
QueryParam::String(parent_id.to_string()), // i.season_id = ?
QueryParam::String(parent_id.to_string()), // i.series_id = ?
QueryParam::String(parent_id.to_string()), // libraries.id = ?
], ],
); );
@@ -566,7 +699,7 @@ impl MediaRepository for OfflineRepository {
-- Containers with downloaded children -- Containers with downloaded children
SELECT DISTINCT i.id SELECT DISTINCT i.id
FROM items i FROM items i
INNER JOIN items children ON children.parent_id = i.id INNER JOIN items children ON (children.parent_id = i.id OR children.album_id = i.id OR children.season_id = i.id OR children.series_id = i.id)
INNER JOIN downloads d ON children.id = d.item_id INNER JOIN downloads d ON children.id = d.item_id
WHERE d.status = 'completed' WHERE d.status = 'completed'
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder') AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
@@ -611,7 +744,7 @@ impl MediaRepository for OfflineRepository {
-- Containers with downloaded children -- Containers with downloaded children
SELECT DISTINCT i.id SELECT DISTINCT i.id
FROM items i FROM items i
INNER JOIN items children ON children.parent_id = i.id INNER JOIN items children ON (children.parent_id = i.id OR children.album_id = i.id OR children.season_id = i.id OR children.series_id = i.id)
INNER JOIN downloads d ON children.id = d.item_id INNER JOIN downloads d ON children.id = d.item_id
WHERE d.status = 'completed' WHERE d.status = 'completed'
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder') AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
@@ -744,7 +877,7 @@ impl MediaRepository for OfflineRepository {
-- Containers with downloaded children (Albums) -- Containers with downloaded children (Albums)
SELECT DISTINCT i.id SELECT DISTINCT i.id
FROM items i FROM items i
INNER JOIN items children ON children.parent_id = i.id INNER JOIN items children ON (children.parent_id = i.id OR children.album_id = i.id OR children.season_id = i.id OR children.series_id = i.id)
INNER JOIN downloads d ON children.id = d.item_id INNER JOIN downloads d ON children.id = d.item_id
WHERE d.status = 'completed' WHERE d.status = 'completed'
AND i.item_type = 'MusicAlbum' AND i.item_type = 'MusicAlbum'
@@ -849,59 +982,32 @@ impl MediaRepository for OfflineRepository {
} }
async fn get_genres(&self, parent_id: Option<&str>) -> Result<Vec<Genre>, RepoError> { async fn get_genres(&self, parent_id: Option<&str>) -> Result<Vec<Genre>, RepoError> {
// Derive genres from cached albums, tallying how many albums carry each // Read the cached server genre catalog (populated by the hybrid repo via
// so the frontend can rank by popularity. We scope to MusicAlbum (genres // save_genres_to_cache). This is the FULL genre list for the library, not
// power the music landing) and read every matching row — NOT DISTINCT — // just the genres derivable from locally-cached albums — so offline keeps
// so the per-genre counts are real. Genres are stored as a JSON array // the same variety the server has. library_id NULL is stored as ''.
// string per item. let library_id = parent_id.unwrap_or("").to_string();
let (sql, params) = if let Some(pid) = parent_id {
(
"SELECT genres FROM items WHERE server_id = ? AND library_id = ? \
AND item_type = 'MusicAlbum' AND genres IS NOT NULL",
vec![
QueryParam::String(self.server_id.clone()),
QueryParam::String(pid.to_string()),
],
)
} else {
(
"SELECT genres FROM items WHERE server_id = ? \
AND item_type = 'MusicAlbum' AND genres IS NOT NULL",
vec![QueryParam::String(self.server_id.clone())],
)
};
let query = Query::with_params(sql, params); let query = Query::with_params(
"SELECT id, name, album_count FROM genres WHERE server_id = ? AND library_id = ?",
vec![
QueryParam::String(self.server_id.clone()),
QueryParam::String(library_id),
],
);
let genres_rows: Vec<String> = self let genres: Vec<Genre> = self
.db_service .db_service
.query_many(query, |row| row.get(0)) .query_many(query, |row| {
Ok(Genre {
id: row.get(0)?,
name: row.get(1)?,
album_count: row.get::<_, Option<i64>>(2)?.map(|c| c as u32),
})
})
.await .await
.map_err(|e| RepoError::Database { message: e })?; .map_err(|e| RepoError::Database { message: e })?;
// genre name -> album count
let mut counts: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
for genres_json in genres_rows {
if let Ok(genres_vec) = serde_json::from_str::<Vec<String>>(&genres_json) {
// De-dupe within one album so a genre listed twice counts once.
let mut seen = std::collections::HashSet::new();
for genre in genres_vec {
if seen.insert(genre.clone()) {
*counts.entry(genre).or_insert(0) += 1;
}
}
}
}
let genres = counts
.into_iter()
.map(|(name, count)| Genre {
id: name.clone(),
name,
album_count: Some(count),
})
.collect();
Ok(genres) Ok(genres)
} }
@@ -943,7 +1049,7 @@ impl MediaRepository for OfflineRepository {
-- Containers with downloaded children -- Containers with downloaded children
SELECT DISTINCT i.id SELECT DISTINCT i.id
FROM items i FROM items i
INNER JOIN items children ON children.parent_id = i.id INNER JOIN items children ON (children.parent_id = i.id OR children.album_id = i.id OR children.season_id = i.id OR children.series_id = i.id)
INNER JOIN downloads d ON children.id = d.item_id INNER JOIN downloads d ON children.id = d.item_id
WHERE d.status = 'completed' WHERE d.status = 'completed'
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder') AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
@@ -1157,7 +1263,7 @@ impl MediaRepository for OfflineRepository {
-- Containers with downloaded children -- Containers with downloaded children
SELECT DISTINCT i.id SELECT DISTINCT i.id
FROM items i FROM items i
INNER JOIN items children ON children.parent_id = i.id INNER JOIN items children ON (children.parent_id = i.id OR children.album_id = i.id OR children.season_id = i.id OR children.series_id = i.id)
INNER JOIN downloads d ON children.id = d.item_id INNER JOIN downloads d ON children.id = d.item_id
WHERE d.status = 'completed' WHERE d.status = 'completed'
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder') AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
@@ -1541,6 +1647,32 @@ mod tests {
); );
CREATE INDEX idx_playlist_items_playlist ON playlist_items(playlist_id, sort_order); CREATE INDEX idx_playlist_items_playlist ON playlist_items(playlist_id, sort_order);
CREATE TABLE downloads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
item_id TEXT NOT NULL,
status TEXT NOT NULL
);
CREATE TABLE libraries (
id TEXT PRIMARY KEY,
server_id TEXT NOT NULL,
name TEXT NOT NULL,
collection_type TEXT,
image_tag TEXT,
sort_order INTEGER DEFAULT 0,
synced_at TEXT
);
CREATE TABLE genres (
id TEXT NOT NULL,
server_id TEXT NOT NULL,
library_id TEXT,
name TEXT NOT NULL,
album_count INTEGER,
synced_at TEXT DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (server_id, library_id, name)
);
"#).unwrap(); "#).unwrap();
// Insert a test server // Insert a test server
@@ -1721,6 +1853,247 @@ mod tests {
assert_eq!(result.unwrap(), 3); assert_eq!(result.unwrap(), 3);
} }
/// Regression: a MusicAlbum whose tracks link via `album_id` (and have a
/// NULL `parent_id`, which is how the Jellyfin cache actually stores them)
/// must be recognized as available offline when a track is downloaded.
///
/// Before the fix, `get_item(album_id)` only matched children by
/// `children.parent_id = i.id`, so a fully-downloaded album returned
/// NotFound offline and playback fell through to the (unreachable) server.
#[tokio::test]
async fn test_get_item_album_available_via_album_id_link() {
use crate::storage::db_service::DatabaseService;
let db_service = create_test_db();
for sql in [
// Album container (no children by parent_id).
"INSERT INTO items (id, server_id, name, item_type, album_id, parent_id) \
VALUES ('album-1', 'test-server', 'Hadestown', 'MusicAlbum', NULL, NULL)",
// Track linked to the album ONLY via album_id, parent_id NULL.
"INSERT INTO items (id, server_id, name, item_type, album_id, parent_id) \
VALUES ('track-1', 'test-server', 'Wait For Me', 'Audio', 'album-1', NULL)",
"INSERT INTO downloads (item_id, status) VALUES ('track-1', 'completed')",
] {
db_service.execute(Query::new(sql)).await.unwrap();
}
let repo = OfflineRepository::new(
db_service.clone(),
"test-server".to_string(),
"test-user".to_string(),
);
// The downloaded track itself resolves offline.
assert!(
repo.get_item("track-1").await.is_ok(),
"downloaded track should be available offline"
);
// The album must also resolve offline because it has a downloaded child
// linked by album_id (not parent_id).
let album = repo.get_item("album-1").await;
assert!(
album.is_ok(),
"album with an album_id-linked downloaded track should be available offline, got {:?}",
album.err()
);
assert_eq!(album.unwrap().id, "album-1");
// Browsing into the album (get_items) must return its tracks even though
// they link by album_id and have a NULL parent_id. This is the call
// play_album_track makes to build the queue.
let tracks = repo.get_items("album-1", None).await.unwrap();
assert_eq!(tracks.items.len(), 1, "get_items(album_id) should return the track");
assert_eq!(tracks.items[0].id, "track-1");
}
/// Regression: offline library pages must honor the "Show all server media"
/// toggle. With `include_catalog_browse` off, `get_items` returns only
/// downloaded media — not the whole synced catalog. With it on, the full
/// (synced-but-not-downloaded) catalog is revealed. Fixes the bug where
/// offline library pages showed every server item regardless of the toggle.
#[tokio::test]
async fn test_get_items_toggle_gates_synced_catalog() {
use crate::storage::db_service::DatabaseService;
let db_service = create_test_db();
for sql in [
// Two movies in a library, both merely synced (browsed) — no download.
"INSERT INTO items (id, server_id, name, item_type, library_id, synced_at) \
VALUES ('movie-dl', 'test-server', 'Downloaded', 'Movie', 'lib-1', '2026-01-01')",
"INSERT INTO items (id, server_id, name, item_type, library_id, synced_at) \
VALUES ('movie-cat', 'test-server', 'CatalogOnly', 'Movie', 'lib-1', '2026-01-01')",
// Only the first movie is actually downloaded.
"INSERT INTO downloads (item_id, status) VALUES ('movie-dl', 'completed')",
// A library row so the library-parent EXISTS clause matches.
"INSERT INTO libraries (id, server_id, name) VALUES ('lib-1', 'test-server', 'Movies')",
] {
db_service.execute(Query::new(sql)).await.unwrap();
}
let repo = OfflineRepository::new(
db_service.clone(),
"test-server".to_string(),
"test-user".to_string(),
);
let opts = Some(GetItemsOptions {
include_item_types: Some(vec!["Movie".to_string()]),
..Default::default()
});
// Toggle OFF: only the downloaded movie is returned.
set_include_catalog_browse(false);
let local_only = repo.get_items("lib-1", opts.clone()).await.unwrap();
let ids: Vec<&str> = local_only.items.iter().map(|i| i.id.as_str()).collect();
assert_eq!(ids, vec!["movie-dl"], "toggle off should show downloaded media only");
// Toggle ON: both the downloaded and the catalog-only movie are returned.
set_include_catalog_browse(true);
let full_catalog = repo.get_items("lib-1", opts).await.unwrap();
let mut ids: Vec<&str> = full_catalog.items.iter().map(|i| i.id.as_str()).collect();
ids.sort();
assert_eq!(ids, vec!["movie-cat", "movie-dl"], "toggle on should reveal the full catalog");
// Restore default for other tests sharing this process-global flag.
set_include_catalog_browse(true);
}
/// Regression: TV episodes link to their season/series via `season_id` /
/// `series_id` (NOT `parent_id`, which is NULL in the cache). A downloaded
/// episode must make both its Season and Series available offline, and
/// browsing either container must return the episode.
#[tokio::test]
async fn test_get_item_tv_available_via_season_series_link() {
use crate::storage::db_service::DatabaseService;
let db_service = create_test_db();
for sql in [
"INSERT INTO items (id, server_id, name, item_type, parent_id) \
VALUES ('series-1', 'test-server', 'Gilmore Girls', 'Series', NULL)",
"INSERT INTO items (id, server_id, name, item_type, series_id, parent_id) \
VALUES ('season-1', 'test-server', 'Season 1', 'Season', 'series-1', NULL)",
// Episode links to both season and series; parent_id NULL.
"INSERT INTO items (id, server_id, name, item_type, season_id, series_id, parent_id) \
VALUES ('ep-1', 'test-server', 'Pilot', 'Episode', 'season-1', 'series-1', NULL)",
"INSERT INTO downloads (item_id, status) VALUES ('ep-1', 'completed')",
] {
db_service.execute(Query::new(sql)).await.unwrap();
}
let repo = OfflineRepository::new(
db_service.clone(),
"test-server".to_string(),
"test-user".to_string(),
);
assert!(repo.get_item("ep-1").await.is_ok(), "downloaded episode available offline");
assert!(
repo.get_item("season-1").await.is_ok(),
"season with a season_id-linked downloaded episode should be available offline"
);
assert!(
repo.get_item("series-1").await.is_ok(),
"series with a series_id-linked downloaded episode should be available offline"
);
// Browsing the season returns the episode.
let season_items = repo.get_items("season-1", None).await.unwrap();
assert!(
season_items.items.iter().any(|i| i.id == "ep-1"),
"get_items(season_id) should return the episode"
);
// Browsing the series returns the episode (via series_id link).
let series_items = repo.get_items("series-1", None).await.unwrap();
assert!(
series_items.items.iter().any(|i| i.id == "ep-1"),
"get_items(series_id) should surface the downloaded episode"
);
}
/// Regression: offline startup must list cached libraries. Previously
/// `get_libraries` joined on `items.library_id` (always NULL in the cache),
/// so it returned nothing offline and the app showed no libraries at all.
/// The list must round-trip through `save_libraries_to_cache`.
#[tokio::test]
async fn test_libraries_cache_roundtrip_available_offline() {
let db_service = create_test_db();
let repo = OfflineRepository::new(
db_service.clone(),
"test-server".to_string(),
"test-user".to_string(),
);
// Empty cache → no libraries (this is the state that fell through to the
// server and hung offline).
assert!(repo.get_libraries().await.unwrap().is_empty());
// Simulate the online path persisting the server's library list.
let server_libs = vec![
Library { id: "music".into(), name: "Music".into(), collection_type: "music".into(), image_tag: None },
Library { id: "movies".into(), name: "Movies".into(), collection_type: "movies".into(), image_tag: Some("tag".into()) },
];
let saved = repo.save_libraries_to_cache(&server_libs).await.unwrap();
assert_eq!(saved, 2);
// Now offline get_libraries returns them without touching the server.
let offline_libs = repo.get_libraries().await.unwrap();
let names: Vec<&str> = offline_libs.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, vec!["Music", "Movies"], "cached libraries available offline in sort order");
// Re-saving is idempotent (INSERT OR REPLACE), not duplicating rows.
repo.save_libraries_to_cache(&server_libs).await.unwrap();
assert_eq!(repo.get_libraries().await.unwrap().len(), 2);
}
/// Regression: the music/TV/movie landing pages lost genre variety because
/// offline `get_genres` derived genres from cached albums only — so the
/// hybrid cache-first race pinned the list to whatever sparse set the local
/// albums yielded instead of the server's full catalog. The full genre list
/// must round-trip through `save_genres_to_cache` and come back scoped by
/// library.
#[tokio::test]
async fn test_genres_cache_roundtrip_scoped_by_library() {
let db_service = create_test_db();
let repo = OfflineRepository::new(
db_service.clone(),
"test-server".to_string(),
"test-user".to_string(),
);
// Empty cache → no genres.
assert!(repo.get_genres(Some("music-lib")).await.unwrap().is_empty());
// Simulate the online path persisting the server's full genre catalog.
let server_genres = vec![
Genre { id: "g1".into(), name: "Rock".into(), album_count: Some(42) },
Genre { id: "g2".into(), name: "Jazz".into(), album_count: Some(17) },
Genre { id: "g3".into(), name: "Ambient".into(), album_count: None },
];
let saved = repo.save_genres_to_cache(Some("music-lib"), &server_genres).await.unwrap();
assert_eq!(saved, 3);
// Offline get_genres returns the full set for that library, counts intact.
let mut offline_genres = repo.get_genres(Some("music-lib")).await.unwrap();
offline_genres.sort_by(|a, b| a.name.cmp(&b.name));
let names: Vec<&str> = offline_genres.iter().map(|g| g.name.as_str()).collect();
assert_eq!(names, vec!["Ambient", "Jazz", "Rock"]);
let rock = offline_genres.iter().find(|g| g.name == "Rock").unwrap();
assert_eq!(rock.album_count, Some(42));
// Genres are scoped: a different library sees nothing.
assert!(repo.get_genres(Some("other-lib")).await.unwrap().is_empty());
// Re-saving replaces the scope's rows (server removed "Jazz").
let updated = vec![
Genre { id: "g1".into(), name: "Rock".into(), album_count: Some(50) },
];
repo.save_genres_to_cache(Some("music-lib"), &updated).await.unwrap();
let after = repo.get_genres(Some("music-lib")).await.unwrap();
assert_eq!(after.len(), 1, "stale genres removed on refresh");
assert_eq!(after[0].album_count, Some(50), "counts updated on refresh");
}
// ===== Playlist Tests ===== // ===== Playlist Tests =====
/// Helper to seed items into the DB for playlist tests /// Helper to seed items into the DB for playlist tests
+135 -8
View File
@@ -144,6 +144,17 @@ impl OnlineRepository {
/// Make authenticated GET request /// Make authenticated GET request
async fn get_json<T: for<'de> Deserialize<'de>>(&self, endpoint: &str) -> Result<T, RepoError> { async fn get_json<T: for<'de> Deserialize<'de>>(&self, endpoint: &str) -> Result<T, RepoError> {
// Fast-fail when connectivity is known-offline. Without this every request
// still runs the full HTTP retry/backoff cycle (~7s) before giving up,
// which stalls cache-miss paths and makes offline browsing feel janky.
// The offline recovery probe (connectivity monitor) flips us back to
// reachable the moment the server returns, so this never sticks.
if let Some(reporter) = &self.connectivity {
if !reporter.is_reachable().await {
return Err(RepoError::Offline);
}
}
let result = self.get_json_inner(endpoint).await; let result = self.get_json_inner(endpoint).await;
self.report_outcome(&result).await; self.report_outcome(&result).await;
result result
@@ -1413,12 +1424,43 @@ impl MediaRepository for OnlineRepository {
quality: &str, quality: &str,
media_source_id: Option<&str>, media_source_id: Option<&str>,
) -> String { ) -> String {
let mut url = format!("{}/Videos/{}/download", self.server_url, item_id); // NOTE: Jellyfin's `/Videos/{id}/download` endpoint is not universally
// available (returns 404 on many server configs), which silently broke
// every movie/TV download. Use the progressive `stream.mp4` endpoint
// instead — it is always present and supports HTTP Range, which the
// download worker relies on for resume.
let mut url = format!("{}/Videos/{}/stream.mp4", self.server_url, item_id);
let mut params = vec![format!("api_key={}", self.access_token)]; let mut params = vec![format!("api_key={}", self.access_token)];
// Add quality parameter if not "original" // Map the frontend quality preset to concrete transcode params. For
if quality != "original" { // "original" we request a direct static copy (no transcode) which is
params.push(format!("quality={}", quality)); // byte-range resumable; other presets ask the server to transcode.
match quality {
"high" => {
params.push("videoBitrate=8000000".to_string());
params.push("maxHeight=1080".to_string());
params.push("audioBitrate=384000".to_string());
params.push("videoCodec=h264".to_string());
params.push("audioCodec=aac".to_string());
}
"medium" => {
params.push("videoBitrate=4000000".to_string());
params.push("maxHeight=720".to_string());
params.push("audioBitrate=256000".to_string());
params.push("videoCodec=h264".to_string());
params.push("audioCodec=aac".to_string());
}
"low" => {
params.push("videoBitrate=1500000".to_string());
params.push("maxHeight=480".to_string());
params.push("audioBitrate=128000".to_string());
params.push("videoCodec=h264".to_string());
params.push("audioCodec=aac".to_string());
}
// "original" (and any unknown value) → direct, resumable copy.
_ => {
params.push("Static=true".to_string());
}
} }
// Add media source ID if provided // Add media source ID if provided
@@ -1426,10 +1468,8 @@ impl MediaRepository for OnlineRepository {
params.push(format!("mediaSourceId={}", source_id)); params.push(format!("mediaSourceId={}", source_id));
} }
if !params.is_empty() { url.push('?');
url.push('?'); url.push_str(&params.join("&"));
url.push_str(&params.join("&"));
}
url url
} }
@@ -1759,6 +1799,25 @@ mod tests {
} }
} }
/// When connectivity is known-offline, `get_json` must fast-fail with
/// `RepoError::Offline` instead of running the full HTTP retry cycle (~7s).
/// This is what keeps offline browsing snappy. `test.server.com` is
/// unroutable, so if the guard were absent this would hang on retries; the
/// assertion returning promptly with `Offline` proves the short-circuit.
#[tokio::test]
async fn test_get_json_fast_fails_when_offline() {
let (repo, reporter) = create_test_repository_with_connectivity();
reporter.mark_unreachable_for_test().await;
assert!(!reporter.is_reachable().await, "precondition: offline");
let result: Result<serde_json::Value, RepoError> = repo.get_json("/System/Info").await;
assert!(
matches!(result, Err(RepoError::Offline)),
"known-offline get_json should return Offline immediately, got {:?}",
result
);
}
/// A network error routes through the debounced path. A single failure stays /// A network error routes through the debounced path. A single failure stays
/// online (debounce window not yet elapsed). /// online (debounce window not yet elapsed).
#[tokio::test] #[tokio::test]
@@ -1887,6 +1946,74 @@ mod tests {
assert_eq!(tags.primary(), None); assert_eq!(tags.primary(), None);
} }
// ===== Video download URL (real impl) =====
//
// These exercise the PRODUCTION `OnlineRepository::get_video_download_url`,
// not a mock. A prior mock in online_integration_test.rs used the correct
// `stream.mp4` endpoint while the real impl shipped `/Videos/{id}/download`,
// which returns 404 on real servers and silently broke every movie/TV
// download. Assert the real builder targets the resumable stream endpoint.
//
// @req-test: DR-013 - Repository pattern for online/offline data access
#[test]
fn test_video_download_url_uses_stream_not_download_endpoint() {
let repo = create_test_repository();
let url = repo.get_video_download_url("item123", "original", None);
// Must NOT use the /download endpoint (404 on real servers).
assert!(
!url.contains("/download"),
"download URL must not use the broken /Videos/{{id}}/download endpoint: {url}"
);
// Must use the progressive, range-resumable stream endpoint.
assert!(
url.contains("/Videos/item123/stream.mp4"),
"download URL must target /Videos/{{id}}/stream.mp4: {url}"
);
assert!(url.contains("api_key=test-access-token"), "url: {url}");
}
#[test]
fn test_video_download_url_original_is_static_direct_copy() {
let repo = create_test_repository();
let url = repo.get_video_download_url("item123", "original", None);
// "original" must request a direct static copy (byte-range resumable),
// with no transcode params.
assert!(url.contains("Static=true"), "url: {url}");
assert!(!url.contains("videoBitrate"), "original must not transcode: {url}");
assert!(!url.contains("maxHeight"), "original must not transcode: {url}");
}
#[test]
fn test_video_download_url_quality_presets_transcode() {
let repo = create_test_repository();
for (quality, height) in [("high", "1080"), ("medium", "720"), ("low", "480")] {
let url = repo.get_video_download_url("item123", quality, None);
assert!(
url.contains("/Videos/item123/stream.mp4"),
"{quality} must use stream.mp4: {url}"
);
assert!(url.contains("videoBitrate="), "{quality} must set bitrate: {url}");
assert!(
url.contains(&format!("maxHeight={height}")),
"{quality} must cap height at {height}: {url}"
);
assert!(url.contains("videoCodec=h264"), "{quality}: {url}");
// Transcoded presets must not also ask for a static copy.
assert!(!url.contains("Static=true"), "{quality} must not be Static: {url}");
}
}
#[test]
fn test_video_download_url_passes_media_source_id() {
let repo = create_test_repository();
let url = repo.get_video_download_url("item123", "original", Some("src-42"));
assert!(url.contains("mediaSourceId=src-42"), "url: {url}");
}
#[test] #[test]
fn test_jellyfin_item_deserialize_with_image_tags() { fn test_jellyfin_item_deserialize_with_image_tags() {
// Test full JellyfinItem deserialization with ImageTags // Test full JellyfinItem deserialization with ImageTags
+37 -4
View File
@@ -32,6 +32,13 @@ pub struct SessionPollerManager {
jellyfin_client: Arc<Mutex<Option<JellyfinClient>>>, jellyfin_client: Arc<Mutex<Option<JellyfinClient>>>,
playback_mode_manager: Arc<PlaybackModeManager>, playback_mode_manager: Arc<PlaybackModeManager>,
event_emitter: Arc<Mutex<Option<Arc<dyn PlayerEventEmitter>>>>, event_emitter: Arc<Mutex<Option<Arc<dyn PlayerEventEmitter>>>>,
/// Optional connectivity reporter. The session poller is the one piece of
/// server traffic that runs continuously even when the user is idle (not
/// browsing the library), so feeding its poll outcomes into the reporter is
/// what lets the app detect going offline — and, crucially, recover when the
/// server returns — without any user interaction. Repository traffic alone
/// can't do this because it only happens while browsing.
connectivity_reporter: Arc<Mutex<Option<crate::connectivity::ConnectivityReporter>>>,
// Polling state // Polling state
is_running: Arc<AtomicBool>, is_running: Arc<AtomicBool>,
@@ -52,6 +59,7 @@ impl SessionPollerManager {
jellyfin_client, jellyfin_client,
playback_mode_manager, playback_mode_manager,
event_emitter: Arc::new(Mutex::new(None)), event_emitter: Arc::new(Mutex::new(None)),
connectivity_reporter: Arc::new(Mutex::new(None)),
is_running: Arc::new(AtomicBool::new(false)), is_running: Arc::new(AtomicBool::new(false)),
current_hint: Arc::new(RwLock::new(PollingHint::Normal)), current_hint: Arc::new(RwLock::new(PollingHint::Normal)),
current_interval_ms: Arc::new(AtomicU64::new(10000)), // Default 10s current_interval_ms: Arc::new(AtomicU64::new(10000)), // Default 10s
@@ -64,6 +72,13 @@ impl SessionPollerManager {
*self.event_emitter.lock_safe() = Some(emitter); *self.event_emitter.lock_safe() = Some(emitter);
} }
/// Wire the connectivity reporter so each poll outcome updates reachability.
/// A successful poll recovers the app to online instantly; sustained poll
/// failures flip it offline (subject to the reporter's debounce window).
pub fn set_connectivity_reporter(&self, reporter: crate::connectivity::ConnectivityReporter) {
*self.connectivity_reporter.lock_safe() = Some(reporter);
}
/// Start the background polling thread /// Start the background polling thread
pub fn start(&self) { pub fn start(&self) {
if self.is_running.swap(true, Ordering::Relaxed) { if self.is_running.swap(true, Ordering::Relaxed) {
@@ -77,6 +92,7 @@ impl SessionPollerManager {
let client = self.jellyfin_client.clone(); let client = self.jellyfin_client.clone();
let mode_manager = self.playback_mode_manager.clone(); let mode_manager = self.playback_mode_manager.clone();
let emitter = self.event_emitter.clone(); let emitter = self.event_emitter.clone();
let connectivity_reporter = self.connectivity_reporter.clone();
let is_running = self.is_running.clone(); let is_running = self.is_running.clone();
let hint = self.current_hint.clone(); let hint = self.current_hint.clone();
let interval_ms = self.current_interval_ms.clone(); let interval_ms = self.current_interval_ms.clone();
@@ -96,18 +112,35 @@ impl SessionPollerManager {
debug!("[SessionPoller] Polling with interval: {}ms", new_interval); debug!("[SessionPoller] Polling with interval: {}ms", new_interval);
// Fetch sessions // Fetch sessions. `had_client` distinguishes "server didn't
let sessions_result = rt.block_on(async { // answer" from "no client configured" so we only feed real
// request outcomes into the connectivity reporter.
let (sessions_result, had_client) = rt.block_on(async {
let client_opt = client.lock_safe().clone(); let client_opt = client.lock_safe().clone();
match client_opt { match client_opt {
Some(c) => c.get_sessions().await, Some(c) => (c.get_sessions().await, true),
None => { None => {
debug!("[SessionPoller] Jellyfin client not configured, skipping poll"); debug!("[SessionPoller] Jellyfin client not configured, skipping poll");
Ok(Vec::new()) (Ok(Vec::new()), false)
} }
} }
}); });
// Drive the connectivity reporter from this poll's outcome. This
// is what recovers the app to online when the server returns
// while the user is idle, and detects going offline when no
// library browsing is happening. See connectivity/mod.rs.
if had_client {
if let Some(reporter) = connectivity_reporter.lock_safe().clone() {
rt.block_on(async {
match &sessions_result {
Ok(_) => reporter.report_success().await,
Err(e) => reporter.report_network_failure(Some(e.clone())).await,
}
});
}
}
// Emit event if successful // Emit event if successful
match sessions_result { match sessions_result {
Ok(sessions) => { Ok(sessions) => {
+1
View File
@@ -201,6 +201,7 @@ mod tests {
"thumbnails", "thumbnails",
"playlists", "playlists",
"playlist_items", "playlist_items",
"genres",
]; ];
for table in expected_tables { for table in expected_tables {
+21
View File
@@ -23,6 +23,7 @@ pub const MIGRATIONS: &[(&str, &str)] = &[
("016_autoplay_max_episodes", MIGRATION_016), ("016_autoplay_max_episodes", MIGRATION_016),
("017_downloads_resume_url", MIGRATION_017), ("017_downloads_resume_url", MIGRATION_017),
("018_items_is_folder", MIGRATION_018), ("018_items_is_folder", MIGRATION_018),
("019_genres_cache", MIGRATION_019),
]; ];
/// Initial schema migration /// Initial schema migration
@@ -693,3 +694,23 @@ ALTER TABLE items ADD COLUMN is_folder INTEGER DEFAULT 0;
-- Force re-fetch of all cached items so is_folder is populated from the server. -- Force re-fetch of all cached items so is_folder is populated from the server.
UPDATE items SET synced_at = NULL; UPDATE items SET synced_at = NULL;
"#; "#;
/// Migration to cache the full server genre catalog. Previously genres were
/// derived on the fly from cached albums, which meant offline (and the hybrid
/// cache-first race) only ever saw genres for the handful of locally-cached
/// albums — collapsing the variety on the music/TV/movie landing pages. This
/// table stores the complete genre list per library so offline has the real
/// catalog and cache-first routing returns the right thing.
const MIGRATION_019: &str = r#"
CREATE TABLE IF NOT EXISTS genres (
id TEXT NOT NULL,
server_id TEXT NOT NULL,
library_id TEXT,
name TEXT NOT NULL,
album_count INTEGER,
synced_at TEXT DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (server_id, library_id, name)
);
CREATE INDEX IF NOT EXISTS idx_genres_scope ON genres(server_id, library_id);
"#;
+61 -18
View File
@@ -64,7 +64,8 @@ impl ThumbnailCache {
image_type: &str, image_type: &str,
tag: &str, tag: &str,
) -> Option<PathBuf> { ) -> Option<PathBuf> {
let query = Query::with_params( // Primary lookup: exact (item_id, image_type, tag) match.
let exact = Query::with_params(
"SELECT file_path FROM thumbnails "SELECT file_path FROM thumbnails
WHERE item_id = ? AND image_type = ? AND image_tag = ?", WHERE item_id = ? AND image_type = ? AND image_tag = ?",
vec![ vec![
@@ -74,12 +75,60 @@ impl ThumbnailCache {
], ],
); );
let path_str: String = db.query_optional(query, |row| row.get(0)).await.ok()??; if let Ok(Some(path_str)) = db.query_optional(exact, |row| row.get::<_, String>(0)).await {
let path = PathBuf::from(&path_str); let path = PathBuf::from(&path_str);
if path.exists() {
self.touch(&db, item_id, image_type, Some(tag)).await;
return Some(path);
}
// File gone — drop the stale row and fall through to the tag-agnostic
// lookup below (another cached image for this item may still exist).
let _ = db.execute(Query::with_params(
"DELETE FROM thumbnails WHERE item_id = ? AND image_type = ? AND image_tag = ?",
vec![
QueryParam::String(item_id.to_string()),
QueryParam::String(image_type.to_string()),
QueryParam::String(tag.to_string()),
],
)).await;
}
// Fallback: any cached image for this item + type, newest first. The
// `image_tag` is a cache-busting version, and callers don't always pass
// the same tag the image was cached under — e.g. the mini player asks for
// the album image using the *track's* primary_image_tag. Ignoring the tag
// here lets those still resolve offline instead of hitting the server.
let any_tag = Query::with_params(
"SELECT file_path FROM thumbnails
WHERE item_id = ? AND image_type = ?
ORDER BY cached_at DESC LIMIT 1",
vec![
QueryParam::String(item_id.to_string()),
QueryParam::String(image_type.to_string()),
],
);
let path_str: String = db.query_optional(any_tag, |row| row.get(0)).await.ok()??;
let path = PathBuf::from(&path_str);
if path.exists() { if path.exists() {
// Update last_accessed for LRU tracking self.touch(&db, item_id, image_type, None).await;
let update_query = Query::with_params( Some(path)
} else {
None
}
}
/// Update `last_accessed` for LRU tracking. When `tag` is `Some`, scope to
/// that exact row; when `None`, touch every row for the item + type.
async fn touch(
&self,
db: &Arc<RusqliteService>,
item_id: &str,
image_type: &str,
tag: Option<&str>,
) {
let query = match tag {
Some(tag) => Query::with_params(
"UPDATE thumbnails SET last_accessed = CURRENT_TIMESTAMP "UPDATE thumbnails SET last_accessed = CURRENT_TIMESTAMP
WHERE item_id = ? AND image_type = ? AND image_tag = ?", WHERE item_id = ? AND image_type = ? AND image_tag = ?",
vec![ vec![
@@ -87,23 +136,17 @@ impl ThumbnailCache {
QueryParam::String(image_type.to_string()), QueryParam::String(image_type.to_string()),
QueryParam::String(tag.to_string()), QueryParam::String(tag.to_string()),
], ],
); ),
let _ = db.execute(update_query).await; None => Query::with_params(
Some(path) "UPDATE thumbnails SET last_accessed = CURRENT_TIMESTAMP
} else { WHERE item_id = ? AND image_type = ?",
// Clean up stale database entry
let delete_query = Query::with_params(
"DELETE FROM thumbnails
WHERE item_id = ? AND image_type = ? AND image_tag = ?",
vec![ vec![
QueryParam::String(item_id.to_string()), QueryParam::String(item_id.to_string()),
QueryParam::String(image_type.to_string()), QueryParam::String(image_type.to_string()),
QueryParam::String(tag.to_string()),
], ],
); ),
let _ = db.execute(delete_query).await; };
None let _ = db.execute(query).await;
}
} }
/// Save thumbnail to cache /// Save thumbnail to cache
+80
View File
@@ -806,6 +806,51 @@ async enqueueDownload(downloadId: number, streamUrl: string, targetDir: string)
async enqueueVideoDownloads(handle: string, downloadIds: number[], targetDir: string) : Promise<null> { async enqueueVideoDownloads(handle: string, downloadIds: number[], targetDir: string) : Promise<null> {
return await TAURI_INVOKE("enqueue_video_downloads", { handle, downloadIds, targetDir }); return await TAURI_INVOKE("enqueue_video_downloads", { handle, downloadIds, targetDir });
}, },
/**
* Walk every library on the server and persist all items to the offline cache
* so the full catalog is browsable offline (greyed out when not downloaded).
*
* Best-effort: a library that fails to fetch is counted and skipped rather than
* aborting the whole sync. Runs libraries sequentially to avoid hammering the
* server. Uses `Recursive=true` so a single request per library returns the
* containers and their playable children.
*/
async syncFullCatalog(handle: string) : Promise<CatalogSyncResult> {
return await TAURI_INVOKE("sync_full_catalog", { handle });
},
/**
* Report the last-synced timestamp so the UI can show a hint / decide whether
* to trigger a fresh sync.
*/
async catalogSyncStatus() : Promise<CatalogSyncStatus> {
return await TAURI_INVOKE("catalog_sync_status");
},
/**
* Control whether offline library queries reveal the full synced catalog
* (greyed-out, non-downloaded media) or only downloaded/local media.
*
* The frontend calls this from the "Show all server media" toggle: pass `true`
* when online, or when offline with the toggle on; pass `false` when offline
* with the toggle off so library pages show downloaded media only. Fixes the
* bug where offline library pages showed every server item regardless of the
* toggle.
*/
async setShowServerCatalog(show: boolean) : Promise<void> {
await TAURI_INVOKE("set_show_server_catalog", { show });
},
/**
* Resolve the stream URL for every download row that was queued while offline
* (`status = 'pending' AND stream_url IS NULL`), then pump the queue so they
* start. Call this on reconnect.
*
* Audio rows resolve via `get_audio_stream_url`; video rows (media_type =
* 'video') via the pure `get_video_download_url` builder using the row's stored
* `quality_preset` mirroring `enqueue_video_downloads`. Rows whose URL can't
* be resolved are left pending (they retry on the next reconnect).
*/
async resumeQueuedDownloads(handle: string) : Promise<ResumeQueuedResult> {
return await TAURI_INVOKE("resume_queued_downloads", { handle });
},
/** /**
* Get download manager statistics * Get download manager statistics
*/ */
@@ -1505,6 +1550,20 @@ export type CachedLibrary = { id: string; serverId: string; name: string; collec
* Cached person info returned to frontend * Cached person info returned to frontend
*/ */
export type CachedPerson = { id: string; serverId: string; name: string; overview: string | null; primaryImageTag: string | null; premiereDate: string | null; endDate: string | null } export type CachedPerson = { id: string; serverId: string; name: string; overview: string | null; primaryImageTag: string | null; premiereDate: string | null; endDate: string | null }
export type CatalogSyncResult = {
/**
* Total items persisted to the offline cache across all libraries.
*/
itemsCached: number;
/**
* Libraries that failed to sync (e.g. server hiccup); best-effort.
*/
librariesFailed: number }
export type CatalogSyncStatus = {
/**
* RFC-3339 timestamp of the last successful sync, if any.
*/
lastSyncedAt: string | null }
/** /**
* Connectivity status * Connectivity status
*/ */
@@ -1989,6 +2048,18 @@ export type PlayerStatusEvent =
* Remote sessions updated (for cast/remote control UI) * Remote sessions updated (for cast/remote control UI)
*/ */
{ type: "sessions_updated"; sessions: SessionInfo[] } | { type: "sessions_updated"; sessions: SessionInfo[] } |
/**
* The authoritative playback mode changed in the Rust backend.
*
* The Rust `PlaybackModeManager` is the single source of truth for which
* device playback commands route to (local vs a remote session). The
* frontend keeps a mirror store for the UI; without this event that mirror
* drifts out of sync (e.g. a mode transition happens inside a transfer or a
* local stop that the frontend never learns about), and controls then route
* to the wrong device the classic "it keeps playing on the remote" bug.
* The frontend reconciles its store to this payload whenever it fires.
*/
{ type: "playback_mode_changed"; mode: string; session_id: string | null } |
/** /**
* The user asked to disconnect from the remote session and resume locally. * The user asked to disconnect from the remote session and resume locally.
* *
@@ -2066,6 +2137,15 @@ export type RemoteSessionStatus = { position: number; duration: number | null; i
* TRACES: UR-005 | DR-005 * TRACES: UR-005 | DR-005
*/ */
export type RepeatMode = "off" | "all" | "one" export type RepeatMode = "off" | "all" | "one"
export type ResumeQueuedResult = {
/**
* Rows whose stream URL was resolved and are now pump-eligible.
*/
resolved: number;
/**
* Rows that couldn't be resolved (item metadata / URL lookup failed).
*/
failed: number }
/** /**
* Options for search queries * Options for search queries
*/ */
@@ -1,432 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, waitFor } from "@testing-library/svelte";
/**
* Integration tests for async image loading pattern used in components
*
* Pattern:
* - Component has $state<string> imageUrl = ""
* - Component has async loadImageUrl() function
* - Component uses $effect to call loadImageUrl when dependencies change
* - For lists: uses Map<string, string> to cache URLs per item
*/
// Mock repository with getImageUrl
const createMockRepository = () => ({
getImageUrl: vi.fn(),
});
describe.skip("Async Image Loading Pattern", () => {
// Detailed async pattern tests - core functionality verified in repository-client.test.ts
let mockRepository: any;
beforeEach(() => {
mockRepository = createMockRepository();
vi.clearAllMocks();
});
afterEach(() => {
vi.clearAllTimers();
});
describe("Single Image Loading", () => {
it("should load image URL asynchronously on component mount", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
// Simulating component with async image loading
const imageUrl = await mockRepository.getImageUrl("item123", "Primary");
expect(imageUrl).toBe("https://server.com/image.jpg");
expect(mockRepository.getImageUrl).toHaveBeenCalledWith("item123", "Primary");
});
it("should show placeholder while loading", async () => {
mockRepository.getImageUrl.mockImplementation(
() => new Promise((resolve) => setTimeout(() => resolve("https://server.com/image.jpg"), 100))
);
vi.useFakeTimers();
const promise = mockRepository.getImageUrl("item123", "Primary");
// Initially no URL
expect(promise).toBeInstanceOf(Promise);
vi.advanceTimersByTime(100);
vi.useRealTimers();
const result = await promise;
expect(result).toBe("https://server.com/image.jpg");
});
it("should reload image when item changes", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image1.jpg");
const url1 = await mockRepository.getImageUrl("item1", "Primary");
expect(url1).toBe("https://server.com/image1.jpg");
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image2.jpg");
const url2 = await mockRepository.getImageUrl("item2", "Primary");
expect(url2).toBe("https://server.com/image2.jpg");
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
});
it("should not reload image if item ID hasn't changed", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
// First load
await mockRepository.getImageUrl("item123", "Primary");
// Would normally use $effect to track changes
// If item ID is same, should not reload (handled by component caching)
// This test documents the expected behavior
});
it("should handle load errors gracefully", async () => {
mockRepository.getImageUrl.mockRejectedValue(new Error("Network error"));
// Component should catch error and show placeholder
try {
await mockRepository.getImageUrl("item123", "Primary");
} catch (e) {
expect(e).toBeInstanceOf(Error);
}
});
});
describe("List Image Caching (Map-based)", () => {
it("should cache URLs using Map<string, string>", () => {
// Simulating component state: imageUrls = $state<Map<string, string>>(new Map())
const imageUrls = new Map<string, string>();
// Load first item
imageUrls.set("item1", "https://server.com/image1.jpg");
expect(imageUrls.has("item1")).toBe(true);
expect(imageUrls.get("item1")).toBe("https://server.com/image1.jpg");
// Load second item
imageUrls.set("item2", "https://server.com/image2.jpg");
expect(imageUrls.size).toBe(2);
// Check cache hit
expect(imageUrls.get("item1")).toBe("https://server.com/image1.jpg");
});
it("should load images only once per item", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
const imageUrls = new Map<string, string>();
// Simulate loading multiple items
const items = [
{ id: "item1", name: "Album 1" },
{ id: "item2", name: "Album 2" },
{ id: "item1", name: "Album 1 (again)" }, // Same ID
];
for (const item of items) {
if (!imageUrls.has(item.id)) {
const url = await mockRepository.getImageUrl(item.id, "Primary");
imageUrls.set(item.id, url);
}
}
// Should only call once per unique ID
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
});
it("should update single item without affecting others", async () => {
const imageUrls = new Map<string, string>();
imageUrls.set("item1", "https://server.com/image1.jpg");
imageUrls.set("item2", "https://server.com/image2.jpg");
imageUrls.set("item3", "https://server.com/image3.jpg");
// Update item2
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image2_updated.jpg");
const newUrl = await mockRepository.getImageUrl("item2", "Primary");
imageUrls.set("item2", newUrl);
// Others should remain unchanged
expect(imageUrls.get("item1")).toBe("https://server.com/image1.jpg");
expect(imageUrls.get("item2")).toBe("https://server.com/image2_updated.jpg");
expect(imageUrls.get("item3")).toBe("https://server.com/image3.jpg");
});
it("should clear cache when data changes", () => {
const imageUrls = new Map<string, string>();
imageUrls.set("item1", "https://server.com/image1.jpg");
imageUrls.set("item2", "https://server.com/image2.jpg");
// Clear cache
imageUrls.clear();
expect(imageUrls.size).toBe(0);
expect(imageUrls.has("item1")).toBe(false);
});
it("should support Map operations efficiently", () => {
const imageUrls = new Map<string, string>();
// Add items
for (let i = 0; i < 100; i++) {
imageUrls.set(`item${i}`, `https://server.com/image${i}.jpg`);
}
expect(imageUrls.size).toBe(100);
// Check specific item
expect(imageUrls.has("item50")).toBe(true);
expect(imageUrls.get("item50")).toBe("https://server.com/image50.jpg");
// Iterate
let count = 0;
imageUrls.forEach(() => {
count++;
});
expect(count).toBe(100);
});
});
describe("Component Lifecycle ($effect integration)", () => {
it("should trigger load on prop change", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
// Simulate $effect tracking prop changes
let effectCount = 0;
const trackingEffect = vi.fn(() => {
effectCount++;
return mockRepository.getImageUrl("item123", "Primary");
});
trackingEffect();
expect(effectCount).toBe(1);
trackingEffect();
expect(effectCount).toBe(2);
});
it("should skip load if conditions not met", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
// Simulate conditional loading (e.g., if (!imageUrl && primaryImageTag))
let imageUrl = "";
const primaryImageTag = "";
if (!imageUrl && primaryImageTag) {
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
}
expect(mockRepository.getImageUrl).not.toHaveBeenCalled();
});
it("should handle dependent state updates", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
// Simulate component state changes triggering effects
const state = {
item: { id: "item1", primaryImageTag: "tag1" },
imageUrl: "",
};
const loadImage = async () => {
if (state.item.primaryImageTag) {
state.imageUrl = await mockRepository.getImageUrl(state.item.id, "Primary");
}
};
await loadImage();
expect(state.imageUrl).toBe("https://server.com/image.jpg");
// Change item
state.item = { id: "item2", primaryImageTag: "tag2" };
state.imageUrl = "";
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image2.jpg");
await loadImage();
expect(state.imageUrl).toBe("https://server.com/image2.jpg");
});
});
describe("Error Handling in Async Loading", () => {
it("should set empty string on error", async () => {
mockRepository.getImageUrl.mockRejectedValue(new Error("Network error"));
let imageUrl = "";
try {
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
} catch {
imageUrl = ""; // Set to empty on error
}
expect(imageUrl).toBe("");
});
it("should allow retry after error", async () => {
mockRepository.getImageUrl
.mockRejectedValueOnce(new Error("Network error"))
.mockResolvedValueOnce("https://server.com/image.jpg");
let imageUrl = "";
// First attempt fails
try {
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
} catch {
imageUrl = "";
}
// Retry succeeds
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
expect(imageUrl).toBe("https://server.com/image.jpg");
});
it("should handle concurrent load requests", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
// Simulate loading multiple images concurrently
const imageUrls = new Map<string, string>();
const items = [
{ id: "item1" },
{ id: "item2" },
{ id: "item3" },
];
const promises = items.map(item =>
mockRepository.getImageUrl(item.id, "Primary")
.then((url: string) => imageUrls.set(item.id, url))
.catch(() => imageUrls.set(item.id, ""))
);
await Promise.all(promises);
expect(imageUrls.size).toBe(3);
expect(imageUrls.has("item1")).toBe(true);
expect(imageUrls.has("item2")).toBe(true);
expect(imageUrls.has("item3")).toBe(true);
});
});
describe("Performance Characteristics", () => {
it("should not reload unnecessarily", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
// Simulate $effect with dependency tracking
let dependencyValue = "same";
let previousDependency = "same";
const loadImage = async () => {
if (dependencyValue !== previousDependency) {
previousDependency = dependencyValue;
return await mockRepository.getImageUrl("item123", "Primary");
}
};
await loadImage();
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
// No change in dependency
await loadImage();
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
// Change dependency
dependencyValue = "changed";
await loadImage();
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
});
it("should handle large lists efficiently", async () => {
const imageUrls = new Map<string, string>();
let loadCount = 0;
mockRepository.getImageUrl.mockImplementation(() => {
loadCount++;
return Promise.resolve("https://server.com/image.jpg");
});
// Simulate loading 1000 items but caching URLs
const items = Array.from({ length: 1000 }, (_, i) => ({ id: `item${i % 10}` }));
for (const item of items) {
if (!imageUrls.has(item.id)) {
const url = await mockRepository.getImageUrl(item.id, "Primary");
imageUrls.set(item.id, url);
}
}
// Should only load 10 unique images
expect(loadCount).toBe(10);
expect(imageUrls.size).toBe(10);
});
it("should not block rendering during async loading", () => {
mockRepository.getImageUrl.mockImplementation(
() => new Promise((resolve) =>
setTimeout(() => resolve("https://server.com/image.jpg"), 1000)
)
);
// Async operation should not block component rendering
const renderTiming = {
startRender: Date.now(),
loadStart: null as number | null,
loadComplete: null as number | null,
};
// Render happens immediately
renderTiming.startRender = Date.now();
// Load happens asynchronously
mockRepository.getImageUrl("item123", "Primary").then(() => {
renderTiming.loadComplete = Date.now();
});
// Render should complete before load finishes
expect(Date.now() - renderTiming.startRender).toBeLessThan(1000);
});
});
describe("Backend Integration", () => {
it("should call backend with correct parameters", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
await mockRepository.getImageUrl("item123", "Primary", {
maxWidth: 300,
});
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
"item123",
"Primary",
{
maxWidth: 300,
}
);
});
it("should handle backend URL correctly", async () => {
const backendUrl = "https://server.com/Items/item123/Images/Primary?maxWidth=300&api_key=token";
mockRepository.getImageUrl.mockResolvedValue(backendUrl);
const url = await mockRepository.getImageUrl("item123", "Primary", { maxWidth: 300 });
expect(url).toBe(backendUrl);
// Frontend never constructs URLs directly
expect(url).toContain("api_key=");
});
it("should not require URL construction in frontend", async () => {
// Frontend receives pre-constructed URL from backend
const preConstructedUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
mockRepository.getImageUrl.mockResolvedValue(preConstructedUrl);
const url = await mockRepository.getImageUrl("item123", "Primary");
// Frontend just uses the URL
expect(url).toContain("https://");
expect(url).toContain("item123");
});
});
});
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte"; import { onMount } from "svelte";
import { page } from "$app/stores";
import { truncateMiddle } from "$lib/utils/truncateMiddle"; import { truncateMiddle } from "$lib/utils/truncateMiddle";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { navigateBack } from "$lib/utils/navigation"; import { navigateBack } from "$lib/utils/navigation";
@@ -53,6 +54,16 @@
onMount(async () => { onMount(async () => {
await loadGenres(); await loadGenres();
// Auto-select a genre when linked with ?genre=<name> (e.g. from a genre tag)
const requestedGenre = $page.url.searchParams.get("genre");
if (requestedGenre) {
const match = genres.find(
(g) => g.name.toLowerCase() === requestedGenre.toLowerCase(),
);
if (match) {
await loadGenreItems(match);
}
}
markLoaded(); markLoaded();
}); });
@@ -0,0 +1,154 @@
/**
* Regression test: media-list search must surface server results.
*
* `repository_search` is two-phase `repo.search()` resolves instantly with
* cache-only (downloaded) results, and the merged cache+server union arrives
* later via a `search-event`. A consumer that ignores that event only ever
* shows downloaded content, so search "finds nothing" for un-downloaded media.
*
* This test models that two-phase backend faithfully and would fail against a
* version of GenericMediaListPage that does not subscribe to `search-event`.
*
* TRACES: UR-008
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/svelte";
import GenericMediaListPage from "./GenericMediaListPage.svelte";
import type { MediaListConfig } from "./GenericMediaListPage.svelte";
vi.mock("$app/navigation", () => ({ goto: vi.fn() }));
vi.mock("$lib/stores/library", () => ({
currentLibrary: {
subscribe: vi.fn((fn) => {
fn({ id: "lib123", name: "Music" });
return vi.fn();
}),
},
// Consumed as a store ($viewMode) by LibraryGrid, which this page renders.
viewMode: {
subscribe: vi.fn((fn) => {
fn("grid");
return vi.fn();
}),
},
}));
vi.mock("$lib/stores/auth", () => ({
auth: { getRepository: vi.fn() },
}));
vi.mock("$lib/composables/useServerReachabilityReload", () => ({
useServerReachabilityReload: vi.fn(() => ({ markLoaded: vi.fn() })),
}));
// Capture the `search-event` handler the component registers so the test can
// drive the deferred (server) phase manually.
let searchEventHandler: ((event: { payload: unknown }) => void) | null = null;
vi.mock("@tauri-apps/api/event", () => ({
listen: vi.fn(async (name: string, handler: (event: { payload: unknown }) => void) => {
if (name === "search-event") searchEventHandler = handler;
return () => {};
}),
}));
const ALBUM_CONFIG: MediaListConfig = {
itemType: "MusicAlbum",
title: "Albums",
backPath: "/library/music",
searchPlaceholder: "Search albums...",
sortOptions: [{ key: "SortName", label: "Title" }],
defaultSort: "SortName",
displayComponent: "grid",
};
describe("GenericMediaListPage — two-phase search", () => {
beforeEach(() => {
searchEventHandler = null;
vi.clearAllMocks();
});
it("renders server results that arrive after the cache-only phase", async () => {
// Phase 1 (synchronous) returns cache-only — empty, as it is for a user who
// has downloaded nothing. This is the exact condition that used to show
// "nothing found" even though the server has matching albums.
let capturedRequestId: number | undefined;
const search = vi.fn(async (_q: string, _opts: unknown, requestId: number) => {
capturedRequestId = requestId;
return { items: [], totalRecordCount: 0 };
});
const getItems = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
getItems,
search,
} as any);
const { container } = render(GenericMediaListPage, { props: { config: ALBUM_CONFIG } });
// Let the initial (mount) load finish so the debounced search effect is armed.
await waitFor(() => expect(getItems).toHaveBeenCalled());
const input = container.querySelector("input") as HTMLInputElement;
fireEvent.input(input, { target: { value: "Rumours" } });
// Debounced search fires after 300ms and returns the empty cache result.
// The `search-event` listener is registered lazily as part of searching.
await waitFor(() => expect(search).toHaveBeenCalled());
await waitFor(() => expect(searchEventHandler).not.toBeNull());
// Cache-only phase: nothing to show yet (the results counter reads zero).
await waitFor(() =>
expect(screen.getByText(/0 musicalbums matching/)).toBeTruthy()
);
// Phase 2: backend emits the merged cache+server union for this request.
expect(capturedRequestId).toBeTypeOf("number");
searchEventHandler!({
payload: {
requestId: capturedRequestId,
result: {
items: [{ id: "album1", name: "Rumours", type: "MusicAlbum" }],
totalRecordCount: 1,
},
},
});
// The server result must now be reflected in the list. Old code (no
// listener) never reached this state — the count stayed at zero.
await waitFor(() =>
expect(screen.getByText(/1 musicalbum matching/)).toBeTruthy()
);
});
it("ignores a search-event whose requestId is stale", async () => {
const search = vi.fn(async () => ({ items: [], totalRecordCount: 0 }));
const getItems = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
getItems,
search,
} as any);
const { container } = render(GenericMediaListPage, { props: { config: ALBUM_CONFIG } });
await waitFor(() => expect(getItems).toHaveBeenCalled());
const input = container.querySelector("input") as HTMLInputElement;
fireEvent.input(input, { target: { value: "Rumours" } });
await waitFor(() => expect(search).toHaveBeenCalled());
await waitFor(() => expect(searchEventHandler).not.toBeNull());
// A superseded query's late result (wrong requestId) must not render.
searchEventHandler!({
payload: {
requestId: -999,
result: {
items: [{ id: "stale", name: "Stale Album", type: "MusicAlbum" }],
totalRecordCount: 1,
},
},
});
await new Promise((r) => setTimeout(r, 0));
expect(screen.queryByText("Stale Album")).toBeNull();
});
});
@@ -1,6 +1,7 @@
<!-- TRACES: UR-007, UR-029, UR-030 | DR-007, DR-032, DR-033 --> <!-- TRACES: UR-007, UR-029, UR-030 | DR-007, DR-032, DR-033 -->
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte"; import { onMount, onDestroy } from "svelte";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { navigateBack } from "$lib/utils/navigation"; import { navigateBack } from "$lib/utils/navigation";
import { currentLibrary } from "$lib/stores/library"; import { currentLibrary } from "$lib/stores/library";
@@ -13,7 +14,7 @@
import BackButton from "$lib/components/common/BackButton.svelte"; import BackButton from "$lib/components/common/BackButton.svelte";
import ResultsCounter from "$lib/components/common/ResultsCounter.svelte"; import ResultsCounter from "$lib/components/common/ResultsCounter.svelte";
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload"; import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
import type { MediaItem, Library, ItemType } from "$lib/api/types"; import type { MediaItem, Library, ItemType, SearchResult } from "$lib/api/types";
import LibraryGrid from "./LibraryGrid.svelte"; import LibraryGrid from "./LibraryGrid.svelte";
import TrackList from "./TrackList.svelte"; import TrackList from "./TrackList.svelte";
import AlphabetScrollBar from "./AlphabetScrollBar.svelte"; import AlphabetScrollBar from "./AlphabetScrollBar.svelte";
@@ -54,6 +55,31 @@
let searchTimeout: ReturnType<typeof setTimeout> | null = null; let searchTimeout: ReturnType<typeof setTimeout> | null = null;
let initialLoadDone = false; let initialLoadDone = false;
/**
* Payload of the backend `search-event` (mirrors Rust `SearchUpdateEvent`).
* `repo.search()` resolves instantly with cache-only (downloaded) results;
* the merged cache+server union arrives later via this event.
*/
interface SearchUpdateEvent {
requestId: number;
result: SearchResult;
}
// Monotonic id identifying the latest search request. The deferred
// `search-event` is only applied when its requestId still matches, so
// out-of-order / superseded server results never clobber fresher ones.
let searchRequestId = 0;
let unlistenSearch: UnlistenFn | null = null;
async function ensureSearchListener() {
if (unlistenSearch) return;
unlistenSearch = await listen<SearchUpdateEvent>("search-event", (event) => {
const { requestId, result } = event.payload;
if (requestId !== searchRequestId) return;
items = excludePodcasts(result.items);
});
}
$effect(() => { $effect(() => {
sortBy = config.defaultSort; sortBy = config.defaultSort;
}); });
@@ -82,12 +108,26 @@
// Use backend search if search query is provided, otherwise use getItems with sort // Use backend search if search query is provided, otherwise use getItems with sort
// HACK: excludePodcasts drops the "Podcasts" folder stored in the music library. // HACK: excludePodcasts drops the "Podcasts" folder stored in the music library.
if (debouncedSearchQuery.trim()) { if (debouncedSearchQuery.trim()) {
const result = await repo.search(debouncedSearchQuery, { // Phase 1: instant cache-only (downloaded) results. The merged
includeItemTypes: [config.itemType], // cache+server union arrives later via the `search-event` listener,
limit: 10000, // tagged with this requestId so superseded queries are ignored.
}); await ensureSearchListener();
items = excludePodcasts(result.items); const requestId = ++searchRequestId;
const result = await repo.search(
debouncedSearchQuery,
{
includeItemTypes: [config.itemType],
limit: 10000,
},
requestId
);
// Only apply if this is still the active query.
if (requestId === searchRequestId) {
items = excludePodcasts(result.items);
}
} else { } else {
// Leaving search — invalidate any in-flight server results.
searchRequestId++;
const result = await repo.getItems($currentLibrary.id, { const result = await repo.getItems($currentLibrary.id, {
includeItemTypes: [config.itemType], includeItemTypes: [config.itemType],
sortBy, sortBy,
@@ -120,6 +160,11 @@
}, 300); }, 300);
}); });
onDestroy(() => {
if (unlistenSearch) unlistenSearch();
if (searchTimeout) clearTimeout(searchTimeout);
});
function handleSort(newSort: string) { function handleSort(newSort: string) {
sortBy = newSort; sortBy = newSort;
loadItems(); loadItems();
@@ -15,6 +15,13 @@ vi.mock("$lib/stores/library", () => ({
return vi.fn(); return vi.fn();
}), }),
}, },
// Consumed as a store ($viewMode) by LibraryGrid, which this page renders.
viewMode: {
subscribe: vi.fn((fn) => {
fn("grid");
return vi.fn();
}),
},
})); }));
vi.mock("$lib/stores/auth", () => ({ vi.mock("$lib/stores/auth", () => ({
@@ -32,7 +39,12 @@ vi.mock("$lib/composables/useServerReachabilityReload", () => ({
})), })),
})); }));
describe.skip("GenericMediaListPage", () => { // The component lazily subscribes to the backend `search-event` when searching.
vi.mock("@tauri-apps/api/event", () => ({
listen: vi.fn(async () => () => {}),
}));
describe("GenericMediaListPage", () => {
// Component integration tests - core sorting/search/debouncing logic tested in backend-integration.test.ts // Component integration tests - core sorting/search/debouncing logic tested in backend-integration.test.ts
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
@@ -66,6 +78,16 @@ describe.skip("GenericMediaListPage", () => {
}); });
it("should load items on mount", async () => { it("should load items on mount", async () => {
const mockGetItemsFn = vi.fn().mockResolvedValue({
items: [],
totalRecordCount: 0,
});
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
getItems: mockGetItemsFn,
search: vi.fn(),
} as any);
const config = { const config = {
itemType: "Audio" as const, itemType: "Audio" as const,
title: "Tracks", title: "Tracks",
@@ -80,9 +102,7 @@ describe.skip("GenericMediaListPage", () => {
props: { config }, props: { config },
}); });
await waitFor(() => { await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalledWith("lib123", expect.anything()));
// loadItems should have been called
});
}); });
it("should display sort options", () => { it("should display sort options", () => {
@@ -111,8 +131,14 @@ describe.skip("GenericMediaListPage", () => {
}); });
describe("Search Functionality", () => { describe("Search Functionality", () => {
it("should debounce search input for 300ms", async () => { it("should debounce rapid keystrokes into a single search for the final value", async () => {
vi.useFakeTimers(); const mockSearchFn = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
const mockGetItemsFn = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
getItems: mockGetItemsFn,
search: mockSearchFn,
} as any);
const config = { const config = {
itemType: "Audio" as const, itemType: "Audio" as const,
@@ -128,29 +154,33 @@ describe.skip("GenericMediaListPage", () => {
props: { config }, props: { config },
}); });
// Let the mount load settle so the debounce effect is armed.
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalled());
// Drive the debounce window deterministically with fake timers, flushing
// the async loadItems() microtasks after the timer fires.
vi.useFakeTimers();
const searchInput = container.querySelector("input") as HTMLInputElement; const searchInput = container.querySelector("input") as HTMLInputElement;
// Type into search
fireEvent.input(searchInput, { target: { value: "t" } }); fireEvent.input(searchInput, { target: { value: "t" } });
expect(searchInput.value).toBe("t"); await vi.advanceTimersByTimeAsync(100);
fireEvent.input(searchInput, { target: { value: "te" } });
// Search should not trigger immediately await vi.advanceTimersByTimeAsync(100);
vi.advanceTimersByTime(100); fireEvent.input(searchInput, { target: { value: "tes" } });
await vi.advanceTimersByTimeAsync(100);
// Add more characters
fireEvent.input(searchInput, { target: { value: "test" } }); fireEvent.input(searchInput, { target: { value: "test" } });
// Still shouldn't trigger (only 100ms passed total) // 200ms after the final keystroke: still inside the 300ms window, so no
vi.advanceTimersByTime(100); // search has fired despite four keystrokes.
await vi.advanceTimersByTimeAsync(200);
// Now advance to 300ms total - search should trigger expect(mockSearchFn).not.toHaveBeenCalled();
vi.advanceTimersByTime(100);
await waitFor(() => {
// Search should have been debounced
});
// Cross the threshold: exactly one search, for the final value.
await vi.advanceTimersByTimeAsync(100);
vi.useRealTimers(); vi.useRealTimers();
expect(mockSearchFn).toHaveBeenCalledTimes(1);
expect(mockSearchFn).toHaveBeenCalledWith("test", expect.anything(), expect.any(Number));
}); });
it("should use backend search when search query is provided", async () => { it("should use backend search when search query is provided", async () => {
@@ -159,8 +189,13 @@ describe.skip("GenericMediaListPage", () => {
totalRecordCount: 1, totalRecordCount: 1,
}); });
const mockGetItemsFn = vi.fn().mockResolvedValue({
items: [],
totalRecordCount: 0,
});
const mockRepository = { const mockRepository = {
getItems: vi.fn(), getItems: mockGetItemsFn,
search: mockSearchFn, search: mockSearchFn,
}; };
@@ -178,25 +213,27 @@ describe.skip("GenericMediaListPage", () => {
displayComponent: "tracklist" as const, displayComponent: "tracklist" as const,
}; };
vi.useFakeTimers();
const { container } = render(GenericMediaListPage, { const { container } = render(GenericMediaListPage, {
props: { config }, props: { config },
}); });
// Wait for the initial mount load so the debounced search effect is armed.
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalled());
const searchInput = container.querySelector("input") as HTMLInputElement; const searchInput = container.querySelector("input") as HTMLInputElement;
fireEvent.input(searchInput, { target: { value: "test" } }); fireEvent.input(searchInput, { target: { value: "test" } });
// Advance timer to trigger debounced search // search() is called as search(query, options, requestId).
vi.advanceTimersByTime(300);
await waitFor(() => { await waitFor(() => {
expect(mockSearchFn).toHaveBeenCalledWith("test", expect.objectContaining({ expect(mockSearchFn).toHaveBeenCalledWith(
includeItemTypes: ["Audio"], "test",
limit: 10000, expect.objectContaining({
})); includeItemTypes: ["Audio"],
limit: 10000,
}),
expect.any(Number)
);
}); });
vi.useRealTimers();
}); });
it("should use getItems without search for empty query", async () => { it("should use getItems without search for empty query", async () => {
@@ -416,15 +453,18 @@ describe.skip("GenericMediaListPage", () => {
}); });
it("should include correct itemType in search request", async () => { it("should include correct itemType in search request", async () => {
vi.useFakeTimers();
const mockSearchFn = vi.fn().mockResolvedValue({ const mockSearchFn = vi.fn().mockResolvedValue({
items: [], items: [],
totalRecordCount: 0, totalRecordCount: 0,
}); });
const mockGetItemsFn = vi.fn().mockResolvedValue({
items: [],
totalRecordCount: 0,
});
const mockRepository = { const mockRepository = {
getItems: vi.fn(), getItems: mockGetItemsFn,
search: mockSearchFn, search: mockSearchFn,
}; };
@@ -446,17 +486,20 @@ describe.skip("GenericMediaListPage", () => {
props: { config }, props: { config },
}); });
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalled());
const searchInput = container.querySelector("input") as HTMLInputElement; const searchInput = container.querySelector("input") as HTMLInputElement;
fireEvent.input(searchInput, { target: { value: "album" } }); fireEvent.input(searchInput, { target: { value: "album" } });
vi.advanceTimersByTime(300);
await waitFor(() => { await waitFor(() => {
expect(mockSearchFn).toHaveBeenCalledWith("album", expect.objectContaining({ expect(mockSearchFn).toHaveBeenCalledWith(
includeItemTypes: ["MusicAlbum"], "album",
})); expect.objectContaining({
includeItemTypes: ["MusicAlbum"],
}),
expect.any(Number)
);
}); });
vi.useRealTimers();
}); });
}); });
@@ -536,6 +579,7 @@ describe.skip("GenericMediaListPage", () => {
it("should handle missing library gracefully", async () => { it("should handle missing library gracefully", async () => {
const { goto } = await import("$app/navigation"); const { goto } = await import("$app/navigation");
vi.mocked(goto).mockClear();
const mockGetItemsFn = vi.fn(); const mockGetItemsFn = vi.fn();
@@ -548,14 +592,12 @@ describe.skip("GenericMediaListPage", () => {
mockRepository as any mockRepository as any
); );
// Mock currentLibrary to return null // Deliver a null current library for this test only.
vi.resetModules(); const currentLibrary = vi.mocked((await import("$lib/stores/library")).currentLibrary);
vi.mocked((await import("$lib/stores/library")).currentLibrary.subscribe).mockImplementation( currentLibrary.subscribe.mockImplementation((fn: any) => {
(fn: any) => { fn(null);
fn(null); return vi.fn();
return vi.fn(); });
}
);
const config = { const config = {
itemType: "Audio" as const, itemType: "Audio" as const,
@@ -571,9 +613,15 @@ describe.skip("GenericMediaListPage", () => {
props: { config }, props: { config },
}); });
// Should navigate to back path when library is missing // With no current library, loadItems bails out to the back path and never
await waitFor(() => { // queries the repository.
// goto would be called with config.backPath await waitFor(() => expect(goto).toHaveBeenCalledWith("/library/music"));
expect(mockGetItemsFn).not.toHaveBeenCalled();
// Restore the default (non-null) library for subsequent tests.
currentLibrary.subscribe.mockImplementation((fn: any) => {
fn({ id: "lib123", name: "Music" });
return vi.fn();
}); });
}); });
}); });
+22 -4
View File
@@ -5,14 +5,34 @@
genres: string[]; genres: string[];
maxShow?: number; // Default: unlimited maxShow?: number; // Default: unlimited
clickable?: boolean; // Default: true clickable?: boolean; // Default: true
itemType?: string; // Determines which genre browse page to open
} }
let { let {
genres, genres,
maxShow, maxShow,
clickable = true clickable = true,
itemType
}: Props = $props(); }: Props = $props();
// Map the item type to its genre-browse route
function genreBasePath(type: string | undefined): string {
switch (type) {
case "MusicAlbum":
case "MusicArtist":
case "Audio":
return "/library/music/genres";
case "Series":
case "Season":
case "Episode":
return "/library/shows/genres";
case "Movie":
return "/library/movies/genres";
default:
return "/library/movies/genres";
}
}
const displayGenres = $derived( const displayGenres = $derived(
maxShow ? genres.slice(0, maxShow) : genres maxShow ? genres.slice(0, maxShow) : genres
); );
@@ -23,9 +43,7 @@
function handleGenreClick(genre: string) { function handleGenreClick(genre: string) {
if (clickable) { if (clickable) {
// Navigate to genre browse page goto(`${genreBasePath(itemType)}?genre=${encodeURIComponent(genre)}`);
// For now, we'll use a simple navigation - could be enhanced with a proper genre browse page
goto(`/search?genre=${encodeURIComponent(genre)}`);
} }
} }
</script> </script>
@@ -0,0 +1,130 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/svelte";
// Controllable stores for the offline "server only" branch. Declared via
// vi.hoisted so they exist when the hoisted vi.mock factories run. A tiny
// writable shim avoids importing svelte inside the hoisted block.
const h = vi.hoisted(() => {
function shim<T>(initial: T) {
let value = initial;
const subs = new Set<(v: T) => void>();
return {
set(v: T) {
value = v;
subs.forEach((fn) => fn(value));
},
subscribe(fn: (v: T) => void) {
subs.add(fn);
fn(value);
return () => subs.delete(fn);
},
};
}
return {
isConnectedStore: shim(true),
showServerCatalogStore: shim(false),
downloadsStore: shim({ downloads: {} as Record<string, any> }),
downloadItem: vi.fn(async () => 1),
getUserId: vi.fn(() => "user-1"),
};
});
const { isConnectedStore, showServerCatalogStore, downloadsStore, downloadItem, getUserId } = h;
vi.mock("$lib/stores/connectivity", () => ({
isConnected: { subscribe: h.isConnectedStore.subscribe },
}));
vi.mock("$lib/services/offlineCatalog", () => ({
showServerCatalog: { subscribe: h.showServerCatalogStore.subscribe },
}));
vi.mock("$lib/stores/downloads", () => ({
downloads: { subscribe: h.downloadsStore.subscribe, downloadItem: h.downloadItem },
}));
vi.mock("$lib/stores/auth", () => ({
auth: { getUserId: h.getUserId },
}));
// CachedImage does async repo/image work irrelevant to these tests.
vi.mock("$lib/components/common/CachedImage.svelte", async () => ({
default: (await import("./__mocks__/StubImage.svelte")).default,
}));
import MediaCard from "./MediaCard.svelte";
const track = {
id: "track-1",
name: "Some Song",
type: "Audio" as const,
serverId: "server-1",
artists: ["Artist A"],
albumName: "Album X",
};
describe("MediaCard server-only (offline browse & queue)", () => {
beforeEach(() => {
vi.clearAllMocks();
isConnectedStore.set(true);
showServerCatalogStore.set(false);
downloadsStore.set({ downloads: {} });
});
it("shows no queue button while online", () => {
render(MediaCard, { props: { item: track } });
expect(screen.queryByLabelText(/Queue download/i)).toBeNull();
});
it("shows no queue button when offline but the reveal toggle is off", () => {
isConnectedStore.set(false);
render(MediaCard, { props: { item: track } });
expect(screen.queryByLabelText(/Queue download/i)).toBeNull();
});
it("reveals a queue button when offline and the reveal toggle is on", () => {
isConnectedStore.set(false);
showServerCatalogStore.set(true);
render(MediaCard, { props: { item: track } });
expect(screen.getByLabelText(/Queue download for Some Song/i)).toBeTruthy();
});
it("queues the item for download with its metadata on click", async () => {
isConnectedStore.set(false);
showServerCatalogStore.set(true);
render(MediaCard, { props: { item: track } });
await fireEvent.click(screen.getByLabelText(/Queue download for Some Song/i));
expect(downloadItem).toHaveBeenCalledTimes(1);
const args = downloadItem.mock.calls[0] as unknown as any[];
expect(args[0]).toBe("track-1"); // itemId
expect(args[1]).toBe("user-1"); // userId
expect(args[5]).toBe("Some Song"); // itemName
expect(args[6]).toBe("Artist A"); // artistName
expect(args[7]).toBe("Album X"); // albumName
});
it("shows a Queued badge (not the button) for a pending download", () => {
isConnectedStore.set(false);
showServerCatalogStore.set(true);
downloadsStore.set({
downloads: { "track-1": { itemId: "track-1", status: "pending", progress: 0 } },
});
render(MediaCard, { props: { item: track } });
expect(screen.getByText(/Queued/i)).toBeTruthy();
expect(screen.queryByLabelText(/Queue download/i)).toBeNull();
});
it("does not grey out a completed download", () => {
isConnectedStore.set(false);
showServerCatalogStore.set(true);
downloadsStore.set({
downloads: { "track-1": { itemId: "track-1", status: "completed", progress: 1 } },
});
render(MediaCard, { props: { item: track } });
expect(screen.queryByLabelText(/Queue download/i)).toBeNull();
});
});
+98 -9
View File
@@ -2,6 +2,9 @@
import type { MediaItem, Library } from "$lib/api/types"; import type { MediaItem, Library } from "$lib/api/types";
import { truncateMiddle } from "$lib/utils/truncateMiddle"; import { truncateMiddle } from "$lib/utils/truncateMiddle";
import { downloads } from "$lib/stores/downloads"; import { downloads } from "$lib/stores/downloads";
import { isConnected } from "$lib/stores/connectivity";
import { showServerCatalog } from "$lib/services/offlineCatalog";
import { auth } from "$lib/stores/auth";
import CachedImage from "$lib/components/common/CachedImage.svelte"; import CachedImage from "$lib/components/common/CachedImage.svelte";
interface Props { interface Props {
@@ -25,6 +28,55 @@
); );
const downloadProgress = $derived(downloadInfo?.progress || 0); const downloadProgress = $derived(downloadInfo?.progress || 0);
// A media item (not a library) is "server only" when it exists in the cache
// but isn't downloaded/downloading — and we're offline with the reveal toggle
// on. Such cards render greyed out with a "queue for download" button and are
// inert to tap (nothing to play offline).
const isMediaItem = $derived("type" in item);
const isQueued = $derived(downloadInfo?.status === "pending");
// Actively transferring (as opposed to merely queued/pending for reconnect).
const isActivelyDownloading = $derived(downloadInfo?.status === "downloading");
// "Server only" = offline, reveal on, and not already downloaded or actively
// transferring. A `pending` (queued-for-reconnect) item stays server-only so
// it can show the Queued badge in place of the queue button.
const isServerOnly = $derived(
isMediaItem && !$isConnected && $showServerCatalog && !isDownloaded && !isActivelyDownloading
);
let queueError = $state<string | null>(null);
// Queue this item for download on next reconnect. Offline, this just persists
// a `pending` downloads row (no stream_url); the reconnect handler resolves
// the URL and the pump starts it. See offlineCatalog service.
async function queueForDownload(e: Event) {
e.stopPropagation();
if (!isMediaItem) return;
const media = item as MediaItem;
const userId = auth.getUserId();
if (!userId) {
queueError = "Not signed in";
return;
}
try {
queueError = null;
// Derive a sensible on-disk path; the backend heals stream_url on reconnect.
const filePath = `downloads/${media.id}`;
await downloads.downloadItem(
media.id,
userId,
filePath,
undefined,
undefined,
media.name,
media.artists?.join(", ") ?? undefined,
media.albumName ?? undefined
);
} catch (err) {
console.error("[MediaCard] Failed to queue download:", err);
queueError = "Failed to queue";
}
}
const sizeClasses = { const sizeClasses = {
small: "w-24", small: "w-24",
medium: "w-36", medium: "w-36",
@@ -76,10 +128,12 @@
}); });
</script> </script>
<button <svelte:element
type="button" this={isServerOnly ? "div" : "button"}
class="group/card flex flex-col text-left {sizeClasses[size]} flex-shrink-0 transition-transform duration-200 hover:scale-105" type={isServerOnly ? undefined : "button"}
{onclick} role={isServerOnly ? "group" : undefined}
class="group/card flex flex-col text-left {sizeClasses[size]} flex-shrink-0 transition-transform duration-200 {isServerOnly ? '' : 'hover:scale-105'}"
onclick={isServerOnly ? undefined : onclick}
> >
<div class="relative {aspectRatio()} w-full rounded-lg overflow-hidden bg-[var(--color-surface)] shadow-md group-hover/card:shadow-2xl transition-shadow duration-200"> <div class="relative {aspectRatio()} w-full rounded-lg overflow-hidden bg-[var(--color-surface)] shadow-md group-hover/card:shadow-2xl transition-shadow duration-200">
<CachedImage <CachedImage
@@ -88,11 +142,12 @@
tag={imageTag} tag={imageTag}
maxWidth={maxWidth} maxWidth={maxWidth}
alt={item.name} alt={item.name}
class="w-full h-full object-cover transition-transform duration-300 group-hover/card:scale-110" class="w-full h-full object-cover transition-transform duration-300 group-hover/card:scale-110 {isServerOnly ? 'opacity-40 grayscale' : ''}"
/> />
<!-- Hover overlay with smooth gradient --> <!-- Hover overlay with smooth gradient (play affordance; hidden for
<div class="absolute inset-0 bg-gradient-to-t from-black/60 via-black/0 to-black/0 opacity-0 group-hover/card:opacity-100 transition-opacity duration-300 flex items-center justify-center"> server-only cards, which can't be played offline) -->
<div class="absolute inset-0 bg-gradient-to-t from-black/60 via-black/0 to-black/0 opacity-0 {isServerOnly ? '' : 'group-hover/card:opacity-100'} transition-opacity duration-300 flex items-center justify-center">
<div class="transform scale-90 group-hover/card:scale-100 opacity-0 group-hover/card:opacity-100 transition-all duration-300"> <div class="transform scale-90 group-hover/card:scale-100 opacity-0 group-hover/card:opacity-100 transition-all duration-300">
<div class="w-14 h-14 rounded-full bg-[var(--color-jellyfin)] hover:bg-[var(--color-jellyfin)]/90 flex items-center justify-center shadow-2xl"> <div class="w-14 h-14 rounded-full bg-[var(--color-jellyfin)] hover:bg-[var(--color-jellyfin)]/90 flex items-center justify-center shadow-2xl">
<svg class="w-7 h-7 text-white ml-1" fill="currentColor" viewBox="0 0 24 24"> <svg class="w-7 h-7 text-white ml-1" fill="currentColor" viewBox="0 0 24 24">
@@ -163,9 +218,43 @@
{/if} {/if}
</div> </div>
{/if} {/if}
<!-- Server-only: queue-for-download control (kept at full opacity over the
greyed artwork). Queued items show a "queued" badge instead. -->
{#if isServerOnly}
<div class="absolute inset-0 flex items-center justify-center">
{#if isQueued}
<div class="flex flex-col items-center gap-1 text-white" title="Queued — will download on reconnect">
<div class="w-11 h-11 rounded-full bg-black/60 flex items-center justify-center shadow-lg">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<span class="text-[10px] font-medium bg-black/60 px-1.5 py-0.5 rounded-full">Queued</span>
</div>
{:else}
<button
type="button"
onclick={queueForDownload}
class="w-11 h-11 rounded-full bg-[var(--color-jellyfin)] hover:bg-[var(--color-jellyfin)]/90 flex items-center justify-center shadow-lg transition-colors"
title="Queue download for next connection"
aria-label="Queue download for {item.name}"
>
<svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4v12m0 0l-4-4m4 4l4-4M4 20h16" />
</svg>
</button>
{/if}
</div>
{#if queueError}
<div class="absolute bottom-1 left-1 right-1 text-center text-[10px] text-red-200 bg-black/70 rounded px-1 py-0.5">
{queueError}
</div>
{/if}
{/if}
</div> </div>
<div class="mt-2 space-y-0.5"> <div class="mt-2 space-y-0.5 {isServerOnly ? 'opacity-60' : ''}">
<p class="text-sm font-medium text-white truncate group-hover/card:text-[var(--color-jellyfin)] transition-colors"> <p class="text-sm font-medium text-white truncate group-hover/card:text-[var(--color-jellyfin)] transition-colors">
{truncateMiddle(item.name, 40)} {truncateMiddle(item.name, 40)}
</p> </p>
@@ -173,4 +262,4 @@
<p class="text-xs text-gray-400 truncate">{subtitle()}</p> <p class="text-xs text-gray-400 truncate">{subtitle()}</p>
{/if} {/if}
</div> </div>
</button> </svelte:element>
@@ -1,373 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/svelte";
import MediaCard from "./MediaCard.svelte";
vi.mock("$lib/stores/auth", () => ({
auth: {
getRepository: vi.fn(() => ({
getImageUrl: vi.fn(),
})),
},
}));
describe.skip("MediaCard - Async Image Loading", () => {
// Component rendering tests skipped - core async logic tested in repository-client.test.ts
let mockRepository: any;
beforeEach(() => {
vi.clearAllMocks();
mockRepository = {
getImageUrl: vi.fn(),
};
vi.mocked((global as any).__stores_auth?.auth?.getRepository).mockReturnValue(mockRepository);
});
afterEach(() => {
vi.clearAllTimers();
});
describe("Image Loading", () => {
it("should load image URL asynchronously", async () => {
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
mockRepository.getImageUrl.mockResolvedValue(mockImageUrl);
const mediaItem = {
id: "item123",
name: "Test Album",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "abc123",
};
const { container } = render(MediaCard, {
props: { item: mediaItem },
});
// Component should render immediately with placeholder
expect(container).toBeTruthy();
// Wait for image URL to load
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
"item123",
"Primary",
expect.objectContaining({
maxWidth: 300,
})
);
});
});
it("should show placeholder while image is loading", async () => {
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
mockRepository.getImageUrl.mockImplementation(
() => new Promise((resolve) => setTimeout(() => resolve(mockImageUrl), 100))
);
const mediaItem = {
id: "item123",
name: "Test Album",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "abc123",
};
const { container } = render(MediaCard, {
props: { item: mediaItem },
});
// Placeholder should be visible initially
const placeholder = container.querySelector(".placeholder");
if (placeholder) {
expect(placeholder).toBeTruthy();
}
// Wait for image to load
vi.useFakeTimers();
vi.advanceTimersByTime(100);
vi.useRealTimers();
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalled();
});
});
it("should update image URL when item changes", async () => {
const mockImageUrl1 = "https://server.com/Items/item1/Images/Primary?api_key=token";
const mockImageUrl2 = "https://server.com/Items/item2/Images/Primary?api_key=token";
mockRepository.getImageUrl.mockResolvedValueOnce(mockImageUrl1);
const mediaItem1 = {
id: "item1",
name: "Album 1",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "tag1",
};
const { rerender } = render(MediaCard, {
props: { item: mediaItem1 },
});
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalledWith("item1", "Primary", expect.any(Object));
});
// Change item
mockRepository.getImageUrl.mockResolvedValueOnce(mockImageUrl2);
const mediaItem2 = {
id: "item2",
name: "Album 2",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "tag2",
};
await rerender({ item: mediaItem2 });
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalledWith("item2", "Primary", expect.any(Object));
});
});
it("should not reload image if item ID hasn't changed", async () => {
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
mockRepository.getImageUrl.mockResolvedValue(mockImageUrl);
const mediaItem = {
id: "item123",
name: "Test Album",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "abc123",
};
const { rerender } = render(MediaCard, {
props: { item: mediaItem },
});
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
});
// Rerender with same item
await rerender({ item: mediaItem });
// Should not call getImageUrl again
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
});
it("should handle missing primary image tag gracefully", async () => {
const mediaItem = {
id: "item123",
name: "Test Album",
type: "MusicAlbum" as const,
serverId: "server-1",
// primaryImageTag is undefined
};
const { container } = render(MediaCard, {
props: { item: mediaItem },
});
// Should render without calling getImageUrl
await waitFor(() => {
expect(mockRepository.getImageUrl).not.toHaveBeenCalled();
});
// Should show placeholder
expect(container).toBeTruthy();
});
it("should handle image load errors gracefully", async () => {
mockRepository.getImageUrl.mockRejectedValue(new Error("Failed to load image"));
const mediaItem = {
id: "item123",
name: "Test Album",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "abc123",
};
const { container } = render(MediaCard, {
props: { item: mediaItem },
});
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalled();
});
// Should still render without crashing
expect(container).toBeTruthy();
});
});
describe("Image Options", () => {
it("should pass correct options to getImageUrl", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image");
const mediaItem = {
id: "item123",
name: "Test Album",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "abc123",
};
render(MediaCard, {
props: { item: mediaItem },
});
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
"item123",
"Primary",
{
maxWidth: 300,
}
);
});
});
it("should include tag in image options when available", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image");
const mediaItem = {
id: "item123",
name: "Test Album",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "tag123",
};
render(MediaCard, {
props: { item: mediaItem },
});
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
"item123",
"Primary",
{
maxWidth: 300,
}
);
});
});
});
describe("Caching", () => {
it("should cache image URLs to avoid duplicate requests", async () => {
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
mockRepository.getImageUrl.mockResolvedValue(mockImageUrl);
const mediaItem = {
id: "item123",
name: "Test Album",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "abc123",
};
// Render same item multiple times
const { rerender } = render(MediaCard, {
props: { item: mediaItem },
});
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
});
// Rerender with same item
await rerender({ item: mediaItem });
// Should still only have called once (cached)
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
});
it("should have separate cache entries for different items", async () => {
const mockImageUrl1 = "https://server.com/Items/item1/Images/Primary?api_key=token";
const mockImageUrl2 = "https://server.com/Items/item2/Images/Primary?api_key=token";
let callCount = 0;
mockRepository.getImageUrl.mockImplementation(() => {
callCount++;
return Promise.resolve(callCount === 1 ? mockImageUrl1 : mockImageUrl2);
});
const item1 = {
id: "item1",
name: "Album 1",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "tag1",
};
const item2 = {
id: "item2",
name: "Album 2",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "tag2",
};
const { rerender } = render(MediaCard, {
props: { item: item1 },
});
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
});
await rerender({ item: item2 });
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
});
// Change back to item 1 - should use cached value
await rerender({ item: item1 });
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
});
});
describe("Reactive Updates", () => {
it("should respond to property changes via $effect", async () => {
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image");
const mediaItem = {
id: "item123",
name: "Test Album",
type: "MusicAlbum" as const,
serverId: "server-1",
primaryImageTag: "abc123",
};
const { rerender } = render(MediaCard, {
props: { item: mediaItem },
});
await waitFor(() => {
expect(mockRepository.getImageUrl).toHaveBeenCalled();
});
const previousCallCount = mockRepository.getImageUrl.mock.calls.length;
// Update a property that shouldn't trigger reload
await rerender({
item: {
...mediaItem,
name: "Updated Album Name",
},
});
// Should not call getImageUrl again (same primaryImageTag)
expect(mockRepository.getImageUrl.mock.calls.length).toBe(previousCallCount);
});
});
});
+36 -43
View File
@@ -54,8 +54,9 @@ import { invoke } from "@tauri-apps/api/core";
import TrackList from "./TrackList.svelte"; import TrackList from "./TrackList.svelte";
import type { MediaItem } from "$lib/api/types"; import type { MediaItem } from "$lib/api/types";
import { auth } from "$lib/stores/auth"; import { auth } from "$lib/stores/auth";
import { toast } from "$lib/stores/toast";
describe.skip("TrackList", () => { describe("TrackList", () => {
const mockRepository = { const mockRepository = {
getAudioStreamUrl: vi.fn(), getAudioStreamUrl: vi.fn(),
getImageUrl: vi.fn(), getImageUrl: vi.fn(),
@@ -118,7 +119,8 @@ describe.skip("TrackList", () => {
expect(getAllByText("Song 1").length).toBeGreaterThan(0); expect(getAllByText("Song 1").length).toBeGreaterThan(0);
expect(getAllByText("Song 2").length).toBeGreaterThan(0); expect(getAllByText("Song 2").length).toBeGreaterThan(0);
expect(getAllByText(/Song 3 with a Very Long Name/).length).toBeGreaterThan(0); // Long names are abbreviated in the middle via truncateMiddle(name, 48).
expect(getAllByText(/Song 3 with a Very Long .*Should Be Truncated/).length).toBeGreaterThan(0);
}); });
it("shows loading skeleton when loading=true", () => { it("shows loading skeleton when loading=true", () => {
@@ -137,10 +139,12 @@ describe.skip("TrackList", () => {
}); });
it("shows artist column by default", () => { it("shows artist column by default", () => {
const { getByText } = render(TrackList, { props: { tracks: mockTracks } }); const { getByText, getAllByText } = render(TrackList, { props: { tracks: mockTracks } });
// Header only exists in the desktop table.
expect(getByText("Artist")).toBeTruthy(); expect(getByText("Artist")).toBeTruthy();
expect(getByText("Artist 1")).toBeTruthy(); // Artist name renders in both desktop and mobile views.
expect(getAllByText("Artist 1").length).toBeGreaterThan(0);
}); });
it("hides artist column when showArtist=false", () => { it("hides artist column when showArtist=false", () => {
@@ -153,10 +157,12 @@ describe.skip("TrackList", () => {
}); });
it("shows album column by default", () => { it("shows album column by default", () => {
const { getByText } = render(TrackList, { props: { tracks: mockTracks } }); const { getByText, getAllByText } = render(TrackList, { props: { tracks: mockTracks } });
// Header only exists in the desktop table.
expect(getByText("Album")).toBeTruthy(); expect(getByText("Album")).toBeTruthy();
expect(getByText("Album 1")).toBeTruthy(); // Album name renders in both desktop and mobile views.
expect(getAllByText("Album 1").length).toBeGreaterThan(0);
}); });
it("hides album column when showAlbum=false", () => { it("hides album column when showAlbum=false", () => {
@@ -185,12 +191,13 @@ describe.skip("TrackList", () => {
}, },
]; ];
// Component renders both desktop and mobile views // formatDuration(undefined) renders an empty string, so the row still
// renders without crashing and the track title is present.
const { getAllByText } = render(TrackList, { const { getAllByText } = render(TrackList, {
props: { tracks: tracksWithoutDuration }, props: { tracks: tracksWithoutDuration },
}); });
expect(getAllByText("-").length).toBeGreaterThan(0); expect(getAllByText("Song 1").length).toBeGreaterThan(0);
}); });
it("handles tracks without artist", () => { it("handles tracks without artist", () => {
@@ -198,20 +205,24 @@ describe.skip("TrackList", () => {
{ {
...mockTracks[0], ...mockTracks[0],
artists: undefined, artists: undefined,
artistItems: undefined,
}, },
]; ];
const { getByText } = render(TrackList, { // The artist fallback renders "-" in both desktop and mobile views.
const { getAllByText } = render(TrackList, {
props: { tracks: tracksWithoutArtist }, props: { tracks: tracksWithoutArtist },
}); });
expect(getByText("-")).toBeTruthy(); expect(getAllByText("-").length).toBeGreaterThan(0);
}); });
it("renders multiple artists joined with comma", () => { it("renders multiple artists joined with comma", () => {
const { getByText } = render(TrackList, { props: { tracks: mockTracks } }); // Tracks fall back to artists.join(", ") when artistItems is absent;
// the joined string renders in both desktop and mobile views.
const { getAllByText } = render(TrackList, { props: { tracks: mockTracks } });
expect(getByText("Artist 3, Artist 4")).toBeTruthy(); expect(getAllByText("Artist 3, Artist 4").length).toBeGreaterThan(0);
}); });
}); });
@@ -278,25 +289,8 @@ describe.skip("TrackList", () => {
}); });
}); });
it.skip("calls getAudioStreamUrl for each track", async () => { it("shows error toast when playback fails", async () => {
// NOTE: This test is skipped because the code was refactored to use player_play_tracks const toastSpy = vi.spyOn(toast, "error").mockImplementation(() => "");
// which sends trackIds to the backend. The backend now handles all metadata/stream fetching.
// This test expected the old behavior where frontend called getAudioStreamUrl.
});
it.skip("includes artwork URLs in queue items", async () => {
// NOTE: This test is skipped because the code was refactored.
// Stream URLs and artwork URLs are no longer fetched by frontend.
// Backend handles all metadata and stream URL fetching via player_play_tracks.
});
it.skip("handles tracks without artwork gracefully", async () => {
// NOTE: This test is skipped because the code no longer includes artwork URLs
// in queue items sent to backend. Backend handles artwork fetching independently.
});
it("shows error alert when playback fails", async () => {
const alertSpy = vi.spyOn(window, "alert").mockImplementation(() => {});
(invoke as any).mockRejectedValue(new Error("Network error")); (invoke as any).mockRejectedValue(new Error("Network error"));
const { container } = render(TrackList, { props: { tracks: mockTracks } }); const { container } = render(TrackList, { props: { tracks: mockTracks } });
@@ -309,16 +303,19 @@ describe.skip("TrackList", () => {
await fireEvent.click(firstTrackButton!); await fireEvent.click(firstTrackButton!);
await waitFor(() => { await waitFor(() => {
expect(alertSpy).toHaveBeenCalledWith( expect(toastSpy).toHaveBeenCalledWith(
expect.stringContaining("Failed to play track") expect.stringContaining("Failed to play track"),
expect.anything()
); );
}); });
alertSpy.mockRestore(); toastSpy.mockRestore();
}); });
it("handles auth errors gracefully", async () => { it("handles auth errors gracefully", async () => {
const alertSpy = vi.spyOn(window, "alert").mockImplementation(() => {}); const toastSpy = vi.spyOn(toast, "error").mockImplementation(() => "");
// No repository → requireHandle() throws "No repository available",
// which the default handler surfaces via toast.error.
(auth.getRepository as any).mockReturnValue(null as any); (auth.getRepository as any).mockReturnValue(null as any);
const { container } = render(TrackList, { props: { tracks: mockTracks } }); const { container } = render(TrackList, { props: { tracks: mockTracks } });
@@ -331,22 +328,18 @@ describe.skip("TrackList", () => {
await fireEvent.click(firstTrackButton!); await fireEvent.click(firstTrackButton!);
await waitFor(() => { await waitFor(() => {
expect(alertSpy).toHaveBeenCalledWith( expect(toastSpy).toHaveBeenCalledWith(
expect.stringContaining("Not authenticated") expect.stringContaining("Failed to play track"),
expect.anything()
); );
}); });
alertSpy.mockRestore(); toastSpy.mockRestore();
// Restore mock for other tests // Restore mock for other tests
(auth.getRepository as any).mockReturnValue(mockRepository as any); (auth.getRepository as any).mockReturnValue(mockRepository as any);
}); });
it.skip("handles stream URL generation errors", async () => {
// NOTE: This test is skipped because stream URLs are no longer fetched by frontend.
// The code now uses player_play_tracks which sends trackIds to backend.
// Backend handles all stream URL generation, so this error path no longer exists.
});
}); });
describe("Custom Callback Tests", () => { describe("Custom Callback Tests", () => {
@@ -0,0 +1,7 @@
<script lang="ts">
// Minimal stand-in for CachedImage in unit tests: renders nothing meaningful,
// just accepts the same props so MediaCard renders without hitting the repo.
let { alt = "" }: { alt?: string; [key: string]: unknown } = $props();
</script>
<div data-testid="stub-image" aria-label={alt}></div>
+23 -1
View File
@@ -19,6 +19,7 @@
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import type { MediaItem } from "$lib/api/types"; import type { MediaItem } from "$lib/api/types";
import { auth } from "$lib/stores/auth"; import { auth } from "$lib/stores/auth";
import { commands } from "$lib/api/bindings";
import { import {
mergedMedia, mergedMedia,
mergedIsPlaying, mergedIsPlaying,
@@ -70,6 +71,27 @@
// In remote mode, this automatically uses the remote session's nowPlayingItem // In remote mode, this automatically uses the remote session's nowPlayingItem
const displayMedia = $derived($mergedMedia || $currentQueueItem); const displayMedia = $derived($mergedMedia || $currentQueueItem);
const displayIsPlaying = $derived($mergedIsPlaying); const displayIsPlaying = $derived($mergedIsPlaying);
// The player's MediaItem doesn't carry favorite state, so read it from the
// local user_data cache (offline-safe — same source the optimistic toggle
// writes to). Re-runs whenever the current track changes.
let isFavorite = $state(false);
let favoriteLoadedFor = "";
$effect(() => {
const id = displayMedia?.id;
if (!id || id === favoriteLoadedFor) return;
favoriteLoadedFor = id;
isFavorite = false;
const userId = auth.getUserId();
if (!userId) return;
commands
.storageGetPlaybackProgress(userId, id)
.then((p) => {
// Guard against a race if the track changed while awaiting.
if (displayMedia?.id === id) isFavorite = p?.isFavorite ?? false;
})
.catch(() => {});
});
const displayPosition = $derived($mergedPosition); const displayPosition = $derived($mergedPosition);
const displayDuration = $derived($mergedDuration); const displayDuration = $derived($mergedDuration);
@@ -358,7 +380,7 @@
{#if displayMedia} {#if displayMedia}
<FavoriteButton <FavoriteButton
itemId={displayMedia?.id ?? ""} itemId={displayMedia?.id ?? ""}
isFavorite={displayMedia?.userData?.isFavorite ?? false} bind:isFavorite
size="sm" size="sm"
/> />
{/if} {/if}
+26 -14
View File
@@ -1,8 +1,10 @@
// Favorites service - Handles toggling favorite status with optimistic updates // Favorites service - Handles toggling favorite status with optimistic updates
// TRACES: UR-017 | DR-021 // TRACES: UR-017 | DR-021
import { get } from "svelte/store";
import { commands } from "$lib/api/bindings"; import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth"; import { auth } from "$lib/stores/auth";
import { isConnected } from "$lib/stores/connectivity";
/** /**
* Toggle the favorite status of an item. * Toggle the favorite status of an item.
@@ -31,21 +33,31 @@ export async function toggleFavorite(
// 1. Update local database first (optimistic update) // 1. Update local database first (optimistic update)
await commands.storageToggleFavorite(userId, itemId, newIsFavorite); await commands.storageToggleFavorite(userId, itemId, newIsFavorite);
// 2. Sync to Jellyfin server // 2. Sync to Jellyfin server.
try { //
const repo = auth.getRepository(); // Only attempt this when we're actually connected. When offline, the server
if (newIsFavorite) { // call can hang on a long network timeout rather than failing fast — which
await repo.markFavorite(itemId); // blocks the caller (and leaves the favorite button greyed out with a wait
} else { // cursor) until the request finally gives up, effectively only recovering
await repo.unmarkFavorite(itemId); // once we're back online. The local DB write above keeps the pending_sync
} // flag set, so the change still syncs later; we just don't block the UI on
// an unreachable server here.
if (get(isConnected)) {
try {
const repo = auth.getRepository();
if (newIsFavorite) {
await repo.markFavorite(itemId);
} else {
await repo.unmarkFavorite(itemId);
}
// 3. Mark as synced // 3. Mark as synced
await commands.storageMarkSynced(userId, itemId); await commands.storageMarkSynced(userId, itemId);
} catch (error) { } catch (error) {
console.error("Failed to sync favorite to server:", error); console.error("Failed to sync favorite to server:", error);
// Favorite is stored locally and will be synced later // Favorite is stored locally and will be synced later
// via sync queue (when implemented) // via sync queue (when implemented)
}
} }
return newIsFavorite; return newIsFavorite;
+129
View File
@@ -0,0 +1,129 @@
// Offline catalog service - "browse & queue" for offline mode.
//
// Two responsibilities:
// 1. Full-catalog pre-sync: while online, walk every library and persist all
// items to the offline cache so the whole catalog is browsable (greyed out)
// offline. Backed by the `syncFullCatalog` Rust command.
// 2. Resume-on-reconnect: when the server becomes reachable again, resolve the
// stream URLs of downloads that were queued while offline and let the pump
// start them. Backed by `resumeQueuedDownloads`.
//
// It also owns the `showServerCatalog` UI flag (the offline banner toggle that
// reveals greyed-out, non-downloaded server media).
//
// TRACES: UR-002
import { writable, type Writable } from "svelte/store";
import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
import { isConnected } from "$lib/stores/connectivity";
/**
* When true (and offline), library grids reveal greyed-out versions of media
* that exists on the server but isn't downloaded, each with a button to queue
* a download for the next reconnect. Toggled from the offline banner.
*/
export const showServerCatalog: Writable<boolean> = writable(false);
// Keep the backend's offline library queries in sync with the UI toggle. The
// offline cache holds the whole synced catalog, so `get_items` would otherwise
// return every server item even offline with the toggle off. Include the
// non-downloaded catalog only when online (fast browsing reads the same cache)
// or when the "Show all server media" toggle is on.
let lastIncludeCatalog: boolean | null = null;
function pushCatalogVisibility(connected: boolean, showCatalog: boolean): void {
const include = connected || showCatalog;
if (include === lastIncludeCatalog) return;
lastIncludeCatalog = include;
commands.setShowServerCatalog(include).catch((err) => {
console.warn("[OfflineCatalog] Failed to set catalog visibility:", err);
});
}
let connectedNow = true;
let showCatalogNow = false;
isConnected.subscribe((v) => {
connectedNow = v;
pushCatalogVisibility(connectedNow, showCatalogNow);
});
showServerCatalog.subscribe((v) => {
showCatalogNow = v;
pushCatalogVisibility(connectedNow, showCatalogNow);
});
/** Last time a full catalog sync completed, for a UI hint. */
export const lastCatalogSync: Writable<string | null> = writable(null);
// Guard against overlapping syncs (they can be slow on large libraries).
let syncInProgress = false;
function currentHandle(): string | null {
try {
return auth.getRepository().getHandle();
} catch {
return null; // not connected yet
}
}
/**
* Walk every library and cache the full catalog. Best-effort and non-blocking:
* safe to call on startup (while online) and on reconnect. No-ops if not
* connected or a sync is already running.
*/
export async function syncCatalog(): Promise<void> {
if (syncInProgress) return;
const handle = currentHandle();
if (!handle) return;
syncInProgress = true;
try {
const result = await commands.syncFullCatalog(handle);
console.info(
`[OfflineCatalog] Synced ${result.itemsCached} items (${result.librariesFailed} libraries failed)`
);
await refreshSyncStatus();
} catch (err) {
console.warn("[OfflineCatalog] Full catalog sync failed:", err);
} finally {
syncInProgress = false;
}
}
/**
* Resolve URLs for downloads queued while offline and pump them. Call on
* reconnect. No-ops if not connected.
*/
export async function resumeQueued(): Promise<void> {
const handle = currentHandle();
if (!handle) return;
try {
const result = await commands.resumeQueuedDownloads(handle);
if (result.resolved > 0 || result.failed > 0) {
console.info(
`[OfflineCatalog] Resumed queued downloads: ${result.resolved} resolved, ${result.failed} failed`
);
}
} catch (err) {
console.warn("[OfflineCatalog] Failed to resume queued downloads:", err);
}
}
/** Refresh the last-synced timestamp from the backend. */
export async function refreshSyncStatus(): Promise<void> {
try {
const status = await commands.catalogSyncStatus();
lastCatalogSync.set(status.lastSyncedAt ?? null);
} catch (err) {
console.debug("[OfflineCatalog] Failed to fetch sync status:", err);
}
}
/**
* Called when the server becomes reachable again: resume queued downloads first
* (fast, user-visible), then refresh the catalog in the background.
*/
export async function onReconnected(): Promise<void> {
await resumeQueued();
// Fire-and-forget: don't block reconnection handling on a potentially long walk.
void syncCatalog();
}
+5
View File
@@ -201,6 +201,11 @@ function createAuthStore() {
onServerReconnected: () => { onServerReconnected: () => {
// Retry session verification when server becomes reachable // Retry session verification when server becomes reachable
retryVerification(); retryVerification();
// Resume downloads queued while offline, then refresh the catalog.
// Lazy import to avoid an auth <-> offlineCatalog import cycle.
import("$lib/services/offlineCatalog")
.then((m) => m.onReconnected())
.catch((err) => console.warn("[Auth] Catalog reconnect failed:", err));
}, },
}).catch((error) => { }).catch((error) => {
console.error("[Auth] Failed to start connectivity monitoring:", error); console.error("[Auth] Failed to start connectivity monitoring:", error);
+13 -1
View File
@@ -36,7 +36,10 @@ function createHomeStore() {
try { try {
const repo = auth.getRepository(); const repo = auth.getRepository();
const [resume, nextUp, latest, recentAudio, resumeMovies] = await Promise.all([ // Use allSettled so one failing section (e.g. Next Up is online-only and
// rejects offline) doesn't wipe out the whole homepage. Each section falls
// back to an empty list; cached sections (resume/latest/recent) still show.
const settled = await Promise.allSettled([
repo.getResumeItems(undefined, 12), repo.getResumeItems(undefined, 12),
repo.getNextUpEpisodes(undefined, 12), repo.getNextUpEpisodes(undefined, 12),
repo.getLatestItems("", 16), repo.getLatestItems("", 16),
@@ -44,6 +47,15 @@ function createHomeStore() {
repo.getResumeMovies(12), repo.getResumeMovies(12),
]); ]);
const valueOr = <T>(i: number, fallback: T): T =>
settled[i].status === "fulfilled" ? (settled[i] as PromiseFulfilledResult<T>).value : fallback;
const resume = valueOr(0, [] as typeof initialState.resumeItems);
const nextUp = valueOr(1, [] as typeof initialState.nextUpItems);
const latest = valueOr(2, [] as typeof initialState.latestItems);
const recentAudio = valueOr(3, [] as typeof initialState.recentlyPlayedAudio);
const resumeMovies = valueOr(4, [] as typeof initialState.resumeMovies);
// Use resume items or latest as hero items // Use resume items or latest as hero items
const hero = resume.length >= 3 ? resume.slice(0, 5) : latest.slice(0, 5); const hero = resume.length >= 3 ? resume.slice(0, 5) : latest.slice(0, 5);
+62
View File
@@ -295,6 +295,68 @@ describe("playbackMode store", () => {
}); });
}); });
describe("refresh (reconcile to Rust authoritative mode)", () => {
it("adopts the Rust mode and aligns the selected session", async () => {
const { playbackMode } = await import("./playbackMode");
// Start disagreeing with Rust: store thinks local, Rust says remote.
playbackMode.setMode("local");
mockInvoke.mockResolvedValueOnce({ type: "remote", session_id: "sess-xyz" });
await playbackMode.refresh();
const state = get(playbackMode);
expect(state.mode).toBe("remote");
expect(state.remoteSessionId).toBe("sess-xyz");
// The merged UI stores follow selectedSession, so it must be aligned too.
expect(mockSelectSession).toHaveBeenCalledWith("sess-xyz");
});
it("clears the selected session when Rust reports non-remote", async () => {
const { playbackMode } = await import("./playbackMode");
playbackMode.setMode("remote", "sess-old");
mockInvoke.mockResolvedValueOnce({ type: "idle" });
await playbackMode.refresh();
const state = get(playbackMode);
expect(state.mode).toBe("idle");
expect(state.remoteSessionId).toBeNull();
expect(mockSelectSession).toHaveBeenCalledWith(null);
});
});
describe("transfer reconciles to Rust on completion", () => {
it("refreshes from Rust after a successful transferToRemote", async () => {
const { playbackMode } = await import("./playbackMode");
// First call: the transfer command; second call: the finally refresh.
mockInvoke.mockResolvedValueOnce(undefined);
mockInvoke.mockResolvedValueOnce({ type: "remote", session_id: "session-456" });
await playbackMode.transferToRemote("session-456");
expect(mockInvoke).toHaveBeenCalledWith("playback_mode_get_current");
});
it("still reconciles to Rust when transferToRemote throws mid-transfer", async () => {
const { playbackMode } = await import("./playbackMode");
// Transfer command fails, leaving the optimistic state possibly wrong.
mockInvoke.mockRejectedValueOnce(new Error("boom"));
// The finally refresh reads the true mode (Rust never left local).
mockInvoke.mockResolvedValueOnce({ type: "local" });
await expect(playbackMode.transferToRemote("session-456")).rejects.toThrow("boom");
// The reconciling read must have happened despite the throw.
expect(mockInvoke).toHaveBeenCalledWith("playback_mode_get_current");
const state = get(playbackMode);
expect(state.mode).toBe("local");
});
});
describe("clearError", () => { describe("clearError", () => {
it("should clear transfer error", async () => { it("should clear transfer error", async () => {
const { playbackMode } = await import("./playbackMode"); const { playbackMode } = await import("./playbackMode");
+33 -1
View File
@@ -48,12 +48,16 @@ function createPlaybackModeStore() {
async function refreshMode(): Promise<void> { async function refreshMode(): Promise<void> {
try { try {
const rustMode = (await commands.playbackModeGetCurrent()) as RustPlaybackMode; const rustMode = (await commands.playbackModeGetCurrent()) as RustPlaybackMode;
const remoteSessionId = rustMode.type === "remote" ? rustMode.session_id || null : null;
update((s) => ({ update((s) => ({
...s, ...s,
mode: rustMode.type, mode: rustMode.type,
remoteSessionId: rustMode.type === "remote" ? rustMode.session_id || null : null, remoteSessionId,
})); }));
// Keep the selected session aligned so the merged UI stores follow the
// authoritative mode.
sessions.selectSession(remoteSessionId);
} catch (error) { } catch (error) {
console.error("Failed to get playback mode:", error); console.error("Failed to get playback mode:", error);
} }
@@ -135,6 +139,10 @@ function createPlaybackModeStore() {
throw error; throw error;
} finally { } finally {
currentTransferAbort = null; currentTransferAbort = null;
// Snap back to whatever the Rust manager actually settled on. If any step
// above threw mid-transfer, the optimistic update may not match reality;
// Rust is authoritative, so reconcile to it.
await refreshMode();
} }
} }
@@ -263,6 +271,9 @@ function createPlaybackModeStore() {
console.warn("[PlaybackMode] Failed to clear transferring flag:", e); console.warn("[PlaybackMode] Failed to clear transferring flag:", e);
} }
currentTransferAbort = null; currentTransferAbort = null;
// Reconcile to the authoritative Rust mode in case a step above threw and
// left our optimistic state inconsistent (see transferToRemote).
await refreshMode();
} }
} }
@@ -288,6 +299,27 @@ function createPlaybackModeStore() {
console.error("[PlaybackMode] Lockscreen-triggered transfer failed:", e), console.error("[PlaybackMode] Lockscreen-triggered transfer failed:", e),
); );
} }
return;
}
// The Rust PlaybackModeManager is the single source of truth for routing.
// Reconcile our mirror store to it whenever it changes, so the UI and the
// event filter in playerEvents.ts can't drift and start routing controls to
// the wrong device. We deliberately do NOT reconcile while a transfer is in
// flight: transfers emit intermediate mode changes (and briefly hold the
// transferring flag), and the transfer functions own the final state.
if (event.payload.type === "playback_mode_changed") {
const currentState = get({ subscribe });
if (currentState.isTransferring) {
return;
}
const mode = event.payload.mode as PlaybackMode;
const remoteSessionId =
mode === "remote" ? event.payload.session_id ?? null : null;
console.log("[PlaybackMode] Backend mode changed →", mode, remoteSessionId);
update((s) => ({ ...s, mode, remoteSessionId }));
// Keep the selected session in step so the merged UI stores follow.
sessions.selectSession(remoteSessionId);
} }
}); });
+132
View File
@@ -0,0 +1,132 @@
/**
* Regression tests for the app's fixed bottom-UI (mini player + bottom nav)
* layout rules.
*
* The bug these guard against: on the library route the layout used to render
* its OWN in-flow mini player while the root ALSO painted a fixed bottom nav on
* top of it, and the library scroller only reserved 1rem so the last row hid
* behind the nav. The fix unified everything onto the root: the root owns the
* single fixed bottom UI on every route/platform, and every scroll container
* reserves the measured `bottomUiHeight`.
*
* TRACES: UR-005 | DR-009
*/
import { describe, it, expect } from "vitest";
import {
showBottomNav,
showGlobalMiniPlayer,
routeOwnsLayout,
showBottomUi,
reservedBottomPadding,
} from "./layoutShell";
const authed = (pathname: string) => ({ pathname, isAuthenticated: true });
describe("showGlobalMiniPlayer", () => {
it("shows on the main library page (regression: was hidden on non-Android)", () => {
expect(showGlobalMiniPlayer({ pathname: "/library" })).toBe(true);
});
it("shows on a deep library page", () => {
expect(showGlobalMiniPlayer({ pathname: "/library/abc123" })).toBe(true);
});
it("shows on home, search, downloads", () => {
expect(showGlobalMiniPlayer({ pathname: "/" })).toBe(true);
expect(showGlobalMiniPlayer({ pathname: "/search" })).toBe(true);
expect(showGlobalMiniPlayer({ pathname: "/downloads" })).toBe(true);
});
it("hides on the full-screen player, login, and settings", () => {
expect(showGlobalMiniPlayer({ pathname: "/player/xyz" })).toBe(false);
expect(showGlobalMiniPlayer({ pathname: "/login" })).toBe(false);
expect(showGlobalMiniPlayer({ pathname: "/settings" })).toBe(false);
});
it("does NOT depend on platform or on /library — the root owns it everywhere", () => {
// The signature intentionally has no `isAndroid` input: the old bug was a
// platform/route split that let a second in-flow mini player exist.
expect(showGlobalMiniPlayer({ pathname: "/library" })).toBe(true);
});
});
describe("showBottomNav", () => {
it("shows on authenticated content routes including library", () => {
expect(showBottomNav(authed("/library"))).toBe(true);
expect(showBottomNav(authed("/"))).toBe(true);
expect(showBottomNav(authed("/settings"))).toBe(true);
});
it("hides when unauthenticated", () => {
expect(showBottomNav({ pathname: "/library", isAuthenticated: false })).toBe(false);
});
it("hides on the full-screen player and login", () => {
expect(showBottomNav(authed("/player/xyz"))).toBe(false);
expect(showBottomNav(authed("/login"))).toBe(false);
});
});
describe("routeOwnsLayout", () => {
it("is true for library/settings/player/login (they manage their own scroll)", () => {
expect(routeOwnsLayout({ pathname: "/library" })).toBe(true);
expect(routeOwnsLayout({ pathname: "/library/abc" })).toBe(true);
expect(routeOwnsLayout({ pathname: "/settings" })).toBe(true);
expect(routeOwnsLayout({ pathname: "/player/x" })).toBe(true);
expect(routeOwnsLayout({ pathname: "/login" })).toBe(true);
});
it("is false for routes that render into the root scroller", () => {
expect(routeOwnsLayout({ pathname: "/" })).toBe(false);
expect(routeOwnsLayout({ pathname: "/search" })).toBe(false);
expect(routeOwnsLayout({ pathname: "/downloads" })).toBe(false);
});
});
describe("layout invariant: a reservation owner exists wherever bottom UI shows", () => {
// The core anti-regression check. Every route falls into exactly one of two
// reservation regimes:
// - route owns its layout -> the route's own scroller reserves bottomUiHeight
// - route does NOT own it -> the root scroller reserves bottomUiHeight
// The bug was that the library route was implicitly a THIRD regime: it owned
// its layout, showed a fixed nav from the root, but reserved only 1rem. That
// can't recur now because library both owns its layout (so it reserves
// internally) and the mini player is root-owned (no second in-flow bar).
const routes = ["/", "/search", "/downloads", "/library", "/library/abc", "/settings"];
for (const pathname of routes) {
it(`${pathname}: exactly one reservation owner`, () => {
if (!showBottomUi(authed(pathname))) return; // no bottom UI -> nothing to reserve
// Ownership is a total boolean, so exactly one regime always applies —
// there is no route that shows bottom UI with no reservation owner.
expect(typeof routeOwnsLayout({ pathname })).toBe("boolean");
});
}
it("library shows bottom UI AND owns its layout, so it reserves internally", () => {
// Directly pins the regression: library must NOT rely on the root scroller
// (it has none — the root gives owning routes a clipped, non-scrolling box).
expect(showBottomUi(authed("/library"))).toBe(true);
expect(routeOwnsLayout({ pathname: "/library" })).toBe(true);
});
});
describe("reservedBottomPadding", () => {
it("returns an exact px fit when no extra room requested", () => {
expect(reservedBottomPadding(120)).toBe("120px");
});
it("adds breathing room via calc for layout-owning routes", () => {
expect(reservedBottomPadding(120, 1)).toBe("calc(120px + 1rem)");
});
it("never returns negative padding", () => {
expect(reservedBottomPadding(-50)).toBe("0px");
expect(reservedBottomPadding(-50, 1)).toBe("calc(0px + 1rem)");
});
it("reserves 1rem-only when the bottom UI is collapsed to 0 (nothing playing, nav-only measured elsewhere)", () => {
expect(reservedBottomPadding(0, 1)).toBe("calc(0px + 1rem)");
});
});
+96
View File
@@ -0,0 +1,96 @@
/**
* Pure layout-shell logic for the app's fixed bottom UI (mini player stacked
* over the bottom nav).
*
* These rules used to live as inline `$derived` booleans scattered across the
* root and library `+layout.svelte` files, and diverged per platform/route
* which is exactly how the "last row hidden behind the nav" bug kept coming
* back. The invariant is now a single source of truth:
*
* - The ROOT layout owns the single fixed bottom UI on every route/platform.
* There is no per-route/per-platform second mini player.
* - Whatever fixed bottom UI is showing has a live-measured height
* (`bottomUiHeight`), and every scroll container reserves exactly that much
* bottom space so the last row can never render behind the nav.
*
* Keeping this pure makes the invariant unit-testable (jsdom has no layout
* engine, so the geometry itself can't be tested but the decision logic can).
*
* TRACES: UR-005 | DR-009
*/
export interface BottomUiVisibilityInput {
/** Current route pathname, e.g. `$page.url.pathname`. */
pathname: string;
/** Whether the user is authenticated. */
isAuthenticated: boolean;
}
/**
* The bottom nav is shown on every authenticated route except the full-screen
* player and the login route.
*/
export function showBottomNav({
pathname,
isAuthenticated,
}: BottomUiVisibilityInput): boolean {
return (
isAuthenticated &&
!pathname.startsWith("/player/") &&
!pathname.startsWith("/login")
);
}
/**
* The global (root-owned) mini player is shown on every route except the
* full-screen player, login, and settings. Crucially this is NOT gated on
* platform or on `/library` the root owns the mini player everywhere, so the
* library route must never render its own second one.
*/
export function showGlobalMiniPlayer({ pathname }: { pathname: string }): boolean {
return (
!pathname.startsWith("/player/") &&
!pathname.startsWith("/login") &&
!pathname.startsWith("/settings")
);
}
/**
* Routes that own their own full-height layout (their own scroll container +
* bottom-space reservation). The root leaves these as a plain non-scrolling box
* and does NOT add bottom padding the route reserves `bottomUiHeight` itself.
* Every other route scrolls in the root wrapper, which reserves the space.
*/
export function routeOwnsLayout({ pathname }: { pathname: string }): boolean {
return (
pathname.startsWith("/library") ||
pathname.startsWith("/settings") ||
pathname.startsWith("/player/") ||
pathname.startsWith("/login")
);
}
/**
* Whether any fixed bottom UI is showing for this route (mini player, nav, or
* both). When true, the active scroll container must reserve `bottomUiHeight`.
*/
export function showBottomUi(input: BottomUiVisibilityInput): boolean {
return showBottomNav(input) || showGlobalMiniPlayer({ pathname: input.pathname });
}
/**
* The bottom padding (in CSS) a scroll container must reserve so its last row
* clears the fixed bottom UI. `bottomUiHeight` is the live-measured height of
* the root's fixed bottom UI wrapper.
*
* @param bottomUiHeight measured height in px of the fixed bottom UI (0 if none)
* @param extraRem breathing room added on top (routes that own their
* layout add 1rem; the root wrapper reserves an exact fit)
*/
export function reservedBottomPadding(
bottomUiHeight: number,
extraRem = 0,
): string {
const px = Math.max(0, bottomUiHeight);
return extraRem > 0 ? `calc(${px}px + ${extraRem}rem)` : `${px}px`;
}
+72 -11
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { onMount, onDestroy } from "svelte"; import { onMount, onDestroy } from "svelte";
import { get } from "svelte/store";
import { page } from "$app/stores"; import { page } from "$app/stores";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { platform } from "@tauri-apps/plugin-os"; import { platform } from "@tauri-apps/plugin-os";
@@ -7,8 +8,9 @@
import { auth, needsReauth, isAuthenticated } from "$lib/stores/auth"; import { auth, needsReauth, isAuthenticated } from "$lib/stores/auth";
import { connectivity, isConnected } from "$lib/stores/connectivity"; import { connectivity, isConnected } from "$lib/stores/connectivity";
import { initPlayerEvents, cleanupPlayerEvents } from "$lib/services/playerEvents"; import { initPlayerEvents, cleanupPlayerEvents } from "$lib/services/playerEvents";
import { initDownloadEvents, cleanupDownloadEvents } from "$lib/stores/downloads"; import { downloads, initDownloadEvents, cleanupDownloadEvents } from "$lib/stores/downloads";
import { syncService } from "$lib/services/syncService"; import { syncService } from "$lib/services/syncService";
import { onReconnected as onCatalogReconnected, syncCatalog, refreshSyncStatus, showServerCatalog, lastCatalogSync } from "$lib/services/offlineCatalog";
import { playbackMode } from "$lib/stores/playbackMode"; import { playbackMode } from "$lib/stores/playbackMode";
import { sessions } from "$lib/stores/sessions"; import { sessions } from "$lib/stores/sessions";
import { currentMedia, isPlaying, playbackPosition, playbackDuration } from "$lib/stores/player"; import { currentMedia, isPlaying, playbackPosition, playbackDuration } from "$lib/stores/player";
@@ -18,6 +20,13 @@
import SleepTimerModal from "$lib/components/player/SleepTimerModal.svelte"; import SleepTimerModal from "$lib/components/player/SleepTimerModal.svelte";
import BottomNav from "$lib/components/BottomNav.svelte"; import BottomNav from "$lib/components/BottomNav.svelte";
import { isInitialized, pendingSyncCount, isAndroid, showSleepTimerModal, bottomUiHeight } from "$lib/stores/appState"; import { isInitialized, pendingSyncCount, isAndroid, showSleepTimerModal, bottomUiHeight } from "$lib/stores/appState";
import {
showBottomNav as computeShowBottomNav,
showGlobalMiniPlayer as computeShowGlobalMiniPlayer,
routeOwnsLayout as computeRouteOwnsLayout,
showBottomUi as computeShowBottomUi,
reservedBottomPadding,
} from "$lib/utils/layoutShell";
// Shuffle/repeat/next/previous come from the event-driven queue store, the // Shuffle/repeat/next/previous come from the event-driven queue store, the
// single source of truth (updated instantly on queue_changed). // single source of truth (updated instantly on queue_changed).
import { isShuffle as shuffle, repeatMode as repeat, hasNext, hasPrevious } from "$lib/stores/queue"; import { isShuffle as shuffle, repeatMode as repeat, hasNext, hasPrevious } from "$lib/stores/queue";
@@ -32,15 +41,26 @@
// Route-level visibility for the fixed bottom UI (the mini player itself also // Route-level visibility for the fixed bottom UI (the mini player itself also
// self-gates on playback state; when it renders nothing the in-flow slot // self-gates on playback state; when it renders nothing the in-flow slot
// collapses to 0 and the ResizeObserver shrinks the reserved padding). // collapses to 0 and the ResizeObserver shrinks the reserved padding).
// All layout-shell visibility/reservation rules live in one pure, unit-tested
// module ($lib/utils/layoutShell) so they can't drift per route/platform.
// The root owns the single fixed bottom UI (mini player + nav) on every route;
// the library route used to render its own in-flow mini player, which double-
// stacked with this fixed one and hid the last row behind the nav.
const pathname = $derived($page.url.pathname); const pathname = $derived($page.url.pathname);
const showBottomNav = $derived( const showBottomNav = $derived(
$isAuthenticated && !pathname.startsWith('/player/') && !pathname.startsWith('/login') computeShowBottomNav({ pathname, isAuthenticated: $isAuthenticated })
); );
const showGlobalMiniPlayer = $derived( const showGlobalMiniPlayer = $derived(computeShowGlobalMiniPlayer({ pathname }));
!pathname.startsWith('/player/') &&
!pathname.startsWith('/login') && // The library and settings routes own their own full-height layout (their own
!pathname.startsWith('/settings') && // scroll container + bottom-space reservation), so the root must leave their
($isAndroid || !pathname.startsWith('/library')) // wrapper as a plain non-scrolling box. Every other top-level page (search,
// downloads, sessions, home) renders straight into the root, so the root
// wrapper has to scroll AND reserve the fixed bottom UI's height — otherwise
// the mini player / bottom nav overlay the last rows of content.
const routeOwnsLayout = $derived(computeRouteOwnsLayout({ pathname }));
const showBottomUi = $derived(
computeShowBottomUi({ pathname, isAuthenticated: $isAuthenticated })
); );
$effect(() => { $effect(() => {
@@ -83,9 +103,26 @@
// Initialize download event listener // Initialize download event listener
await initDownloadEvents(); await initDownloadEvents();
// Prime the downloads store from the DB. The store starts empty each launch,
// and download badges (e.g. AlbumDownloadButton) derive purely from it, so
// without an initial refresh a previously-downloaded album shows as
// not-downloaded until the user opens the Downloads page.
const userId = get(auth).user?.id;
if (userId) {
downloads.refresh(userId).catch((err) =>
console.error("Initial downloads refresh failed:", err)
);
}
// Start sync service for offline mutation queue // Start sync service for offline mutation queue
syncService.start(); syncService.start();
// Kick off a best-effort full-catalog pre-sync so the whole server catalog
// is browsable (greyed out) offline, and load the last-sync hint for the
// offline banner. Non-blocking — no-ops when not connected.
void syncCatalog();
void refreshSyncStatus();
// Initialize playback mode and session monitoring // Initialize playback mode and session monitoring
playbackMode.initializeSessionMonitoring(); playbackMode.initializeSessionMonitoring();
await playbackMode.refresh(); await playbackMode.refresh();
@@ -114,6 +151,8 @@
onServerReconnected: () => { onServerReconnected: () => {
// Retry session verification when server becomes reachable // Retry session verification when server becomes reachable
auth.retryVerification(); auth.retryVerification();
// Resume offline-queued downloads and refresh the catalog.
void onCatalogReconnected();
}, },
}).catch((monitorError) => { }).catch((monitorError) => {
console.error("[Layout] Failed to start connectivity monitoring:", monitorError); console.error("[Layout] Failed to start connectivity monitoring:", monitorError);
@@ -153,13 +192,35 @@
{$pendingSyncCount} pending sync{$pendingSyncCount !== 1 ? 's' : ''} {$pendingSyncCount} pending sync{$pendingSyncCount !== 1 ? 's' : ''}
</span> </span>
{/if} {/if}
<button
type="button"
onclick={() => showServerCatalog.update((v) => !v)}
class="ml-1 bg-white/20 hover:bg-white/30 px-2 py-0.5 rounded-full text-xs transition-colors"
aria-pressed={$showServerCatalog}
title={$lastCatalogSync ? `Catalog last synced ${new Date($lastCatalogSync).toLocaleString()}` : 'Catalog not yet synced'}
>
{$showServerCatalog ? 'Hide server media' : 'Show all server media'}
</button>
</div> </div>
{/if} {/if}
<!-- Main content --> <!-- Main content. Routes that own their full-height layout (library,
<div class="flex-1 overflow-hidden"> settings, player, login) get a plain clipped box and manage their own
{@render children()} scrolling internally. All other top-level pages render directly here, so
</div> this wrapper must scroll and reserve the fixed bottom UI's measured
height so the mini player / bottom nav never overlap the last rows. -->
{#if routeOwnsLayout}
<div class="flex-1 overflow-hidden">
{@render children()}
</div>
{:else}
<div
class="flex-1 overflow-y-auto min-h-0"
style="padding-bottom: {showBottomUi ? reservedBottomPadding($bottomUiHeight) : '0'}; overscroll-behavior: contain"
>
{@render children()}
</div>
{/if}
<!-- Re-authentication modal --> <!-- Re-authentication modal -->
<ReauthModal isOpen={$needsReauth} /> <ReauthModal isOpen={$needsReauth} />
+7 -60
View File
@@ -5,13 +5,10 @@
import { commands } from "$lib/api/bindings"; import { commands } from "$lib/api/bindings";
import { auth, isAuthenticated, isLoading as isAuthLoading, currentUser } from "$lib/stores/auth"; import { auth, isAuthenticated, isLoading as isAuthLoading, currentUser } from "$lib/stores/auth";
import { library } from "$lib/stores/library"; import { library } from "$lib/stores/library";
import { currentMedia, isPlaying, playbackPosition, playbackDuration } from "$lib/stores/player"; import { bottomUiHeight } from "$lib/stores/appState";
import { isShuffle, repeatMode, hasNext as hasNextStore, hasPrevious as hasPreviousStore } from "$lib/stores/queue"; import { reservedBottomPadding } from "$lib/utils/layoutShell";
import { isAndroid, bottomUiHeight } from "$lib/stores/appState";
import { useScrollGuard } from "$lib/composables/useScrollGuard"; import { useScrollGuard } from "$lib/composables/useScrollGuard";
import Search from "$lib/components/Search.svelte"; import Search from "$lib/components/Search.svelte";
import MiniPlayer from "$lib/components/player/MiniPlayer.svelte";
import AudioPlayer from "$lib/components/player/AudioPlayer.svelte";
import SleepTimerModal from "$lib/components/player/SleepTimerModal.svelte"; import SleepTimerModal from "$lib/components/player/SleepTimerModal.svelte";
// Scroll guard prevents accidental taps on library cards during/after scrolling (Android) // Scroll guard prevents accidental taps on library cards during/after scrolling (Android)
@@ -21,19 +18,8 @@
let { children } = $props(); let { children } = $props();
let searchQuery = $state(""); let searchQuery = $state("");
let showFullPlayer = $state(false);
let showOverflowMenu = $state(false); let showOverflowMenu = $state(false);
let showSleepTimerModal = $state(false); let showSleepTimerModal = $state(false);
// Queue status (shuffle, repeat, hasNext, hasPrevious) is event-driven via the
// queue store, which listens for queue_changed events from the backend. This
// updates instantly when toggling shuffle/repeat (no polling lag).
const shuffle = $derived($isShuffle);
const repeat = $derived($repeatMode);
const hasNext = $derived($hasNextStore);
const hasPrevious = $derived($hasPreviousStore);
// Platform comes from the shared appState store (set once in the root layout),
// so this layout and the root layout never disagree about Android — otherwise
// both can suppress their mini players and none appears. See $lib/stores/appState.
onMount(() => { onMount(() => {
return () => { return () => {
@@ -204,57 +190,18 @@
</div> </div>
</header> </header>
<!-- Main content. The mini player is an in-flow flex sibling below this <!-- Main content. The fixed bottom UI (mini player + nav) is owned entirely
scroller (not a fixed overlay), so the list can never render behind it. by the root layout on every platform, and its live-measured height is
Android keeps the global fixed bottom UI (nav + mini player), so there we published to `bottomUiHeight`. We reserve exactly that here (plus a
reserve its real measured height (`bottomUiHeight`, observed live in the little breathing room) so the last row never hides behind the nav. -->
root layout) plus a little breathing room. Non-Android reserves none —
the in-flow bar below owns that space. -->
<main <main
class="flex-1 overflow-y-auto p-4 min-h-0" class="flex-1 overflow-y-auto p-4 min-h-0"
style="padding-bottom: {$isAndroid ? `calc(${$bottomUiHeight}px + 1rem)` : '1rem'}; overscroll-behavior: contain" style="padding-bottom: {reservedBottomPadding($bottomUiHeight, 1)}; overscroll-behavior: contain"
onscroll={scrollGuard.onScroll} onscroll={scrollGuard.onScroll}
> >
{@render children()} {@render children()}
</main> </main>
<!-- Mini Player (only show on non-Android platforms - Android uses global mini player) -->
<!-- Hide on player page since full player is already there. Rendered in
normal flex flow so it sits above the list rather than overlapping it. -->
{#if !$isAndroid && !$page.url.pathname.startsWith('/player/')}
<MiniPlayer
media={$currentMedia}
isPlaying={$isPlaying}
position={$playbackPosition}
duration={$playbackDuration}
{shuffle}
{repeat}
{hasNext}
{hasPrevious}
className="flex-shrink-0"
onExpand={() => showFullPlayer = true}
onSleepTimerClick={() => showSleepTimerModal = true}
/>
{/if}
<!-- Full Audio Player -->
{#if showFullPlayer}
<AudioPlayer
media={$currentMedia}
isPlaying={$isPlaying}
position={$playbackPosition}
duration={$playbackDuration}
{shuffle}
{repeat}
{hasNext}
{hasPrevious}
onClose={() => {
showFullPlayer = false;
window.history.back();
}}
/>
{/if}
<!-- Sleep Timer Modal --> <!-- Sleep Timer Modal -->
<SleepTimerModal <SleepTimerModal
isOpen={showSleepTimerModal} isOpen={showSleepTimerModal}
+1 -1
View File
@@ -511,7 +511,7 @@
<!-- Genre Tags --> <!-- Genre Tags -->
{#if item.genres?.length} {#if item.genres?.length}
<div> <div>
<GenreTags genres={item.genres ?? undefined} maxShow={6} /> <GenreTags genres={item.genres ?? undefined} maxShow={6} itemType={item.type} />
</div> </div>
{/if} {/if}