Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a2cd9978f0 | |||
| 36be192d44 | |||
| acb7e5f221 | |||
| 68c8602230 | |||
| 2d141e5bf4 | |||
| c58cc0cf46 | |||
| 8938e3fdba | |||
| e2c12615c5 | |||
| 0b5a3aa176 | |||
| 37455bc470 | |||
| a64e1b1fb4 |
@ -60,16 +60,24 @@ jobs:
|
||||
cargo test
|
||||
cd ..
|
||||
|
||||
build:
|
||||
name: Build Android APK
|
||||
# Fast per-commit Android compile check. This does NOT build a shippable 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
|
||||
needs: test
|
||||
container:
|
||||
image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest
|
||||
env:
|
||||
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
|
||||
ANDROID_NDK_HOME: /opt/android-sdk/ndk/27.0.11902837
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
@ -97,42 +105,13 @@ jobs:
|
||||
${{ runner.os }}-bun-
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
bun install
|
||||
run: bun install
|
||||
|
||||
- name: Build frontend
|
||||
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
|
||||
- name: Cargo check (aarch64-linux-android)
|
||||
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
|
||||
echo "" | bunx tauri android init
|
||||
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
|
||||
cargo check --target aarch64-linux-android --lib
|
||||
|
||||
@ -90,6 +90,50 @@ flowchart LR
|
||||
|
||||
**Important**: The command is `player_get_queue` (returns `QueueStatus` with `hasNext`/`hasPrevious`). There is no `player_get_queue_status` command.
|
||||
|
||||
## HTML5 Video Adapter (webview-rendered video)
|
||||
|
||||
**Location**: `src/lib/player/html5Adapter.ts`, `src/lib/player/index.ts`, report commands in
|
||||
`src-tauri/src/commands/player/timers.rs`
|
||||
|
||||
Video on desktop (Linux WebKitGTK) — and, per current interim behavior, Android — is rendered by an
|
||||
HTML5 `<video>`/HLS element **inside the webview**. libmpv is initialized audio-only (`vo=null`,
|
||||
`video=false`), so the native backend cannot render or observe this element. The `<video>` is therefore
|
||||
the real player, living outside Rust's reach.
|
||||
|
||||
To keep the `PlayerController` the single source of truth (matching the audio path), the HTML5 element
|
||||
is treated as **a dumb output device that reports back into Rust**, rather than an independent state
|
||||
authority:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Webview["Webview"]
|
||||
Video["HTML5 <video> / HLS.js"]
|
||||
Adapter["html5Adapter.ts<br/>(reports DOM events)"]
|
||||
end
|
||||
subgraph Backend["Rust"]
|
||||
Cmds["player_report_state<br/>player_report_position<br/>player_report_media_loaded"]
|
||||
Controller["PlayerController"]
|
||||
Emitter["TauriEventEmitter"]
|
||||
end
|
||||
subgraph Frontend["Frontend"]
|
||||
Events["playerEvents.ts"]
|
||||
Store["player store"]
|
||||
end
|
||||
|
||||
Video -->|DOM events| Adapter --> Cmds --> Controller --> Emitter --> Events --> Store
|
||||
```
|
||||
|
||||
**Key points:**
|
||||
- The adapter re-emits the *same* `PlayerStatusEvent`s (`StateChanged`, `PositionUpdate`, `MediaLoaded`)
|
||||
the native backends emit, so `playerEvents.ts` needs **no** HTML5-specific branch — HTML5 is just
|
||||
another event source feeding the existing pipeline.
|
||||
- Position reports are throttled (~250ms) to match the MPV cadence and avoid flooding IPC from the
|
||||
60fps RAF loop.
|
||||
- **Boundary rule**: UI components never touch the report commands or `videoElement` state directly.
|
||||
Playback *control* goes through the unified facade `src/lib/player/index.ts` (`playerController`);
|
||||
HTML5 *state reporting* goes through `html5Adapter.ts`. This restores the documented invariant
|
||||
("frontend only displays state and invokes commands") for the video path.
|
||||
|
||||
## MpvBackend (Linux)
|
||||
|
||||
**Location**: `src-tauri/src/player/mpv/`
|
||||
|
||||
@ -3,15 +3,19 @@
|
||||
|
||||
set -e
|
||||
|
||||
BUILD_TYPE="${1:-debug}"
|
||||
|
||||
echo "🚀 Build and Deploy Android APK"
|
||||
echo ""
|
||||
|
||||
# Build APK
|
||||
./scripts/build-android.sh "$BUILD_TYPE"
|
||||
# Pass all args (build type and/or --clean) through to the build script.
|
||||
./scripts/build-android.sh "$@"
|
||||
|
||||
echo ""
|
||||
|
||||
# Deploy APK
|
||||
# Deploy APK — extract build type (default debug), ignoring flags like --clean.
|
||||
BUILD_TYPE="debug"
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
debug|release) BUILD_TYPE="$arg" ;;
|
||||
esac
|
||||
done
|
||||
./scripts/deploy-android.sh "$BUILD_TYPE"
|
||||
|
||||
@ -15,13 +15,24 @@ echo "Android SDK: $ANDROID_HOME"
|
||||
echo "NDK: $NDK_HOME"
|
||||
echo ""
|
||||
|
||||
# Build type: debug or release (default: debug)
|
||||
BUILD_TYPE="${1:-debug}"
|
||||
# Parse args: build type (debug/release) and optional --clean flag.
|
||||
# By default the build is INCREMENTAL — Cargo and Vite reuse their caches.
|
||||
# Pass --clean (or CLEAN=1) to wipe all caches for a from-scratch build.
|
||||
BUILD_TYPE="debug"
|
||||
CLEAN="${CLEAN:-0}"
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--clean) CLEAN=1 ;;
|
||||
debug|release) BUILD_TYPE="$arg" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Step 0: Clear build caches to ensure fresh builds
|
||||
echo "🧹 Clearing build caches..."
|
||||
# Step 0: Optionally clear build caches for a fully fresh build.
|
||||
if [ "$CLEAN" = "1" ]; then
|
||||
echo "🧹 Clearing build caches (clean build)..."
|
||||
rm -rf node_modules/.vite dist .svelte-kit .next build target src-tauri/target 2>/dev/null || true
|
||||
npm install > /dev/null 2>&1
|
||||
fi
|
||||
|
||||
# Step 1: Sync Android source files
|
||||
echo "🔄 Syncing Android sources..."
|
||||
@ -33,6 +44,9 @@ bun run build
|
||||
|
||||
# Step 2: Build Android APK
|
||||
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..."
|
||||
bun run tauri android build --apk true
|
||||
else
|
||||
|
||||
@ -41,4 +41,49 @@ if [ -f "$APP_GRADLE_SRC" ]; then
|
||||
echo " Copied: app/build.gradle.kts"
|
||||
fi
|
||||
|
||||
# Custom ProGuard/R8 keep rules. Required for minified release builds:
|
||||
# the player/ and security/ Kotlin classes are loaded by name via JNI from
|
||||
# Rust, so R8 can't see the references and would strip them without this.
|
||||
# build.gradle.kts globs **/*.pro, so dropping it in app/ is enough.
|
||||
PROGUARD_SRC="$PROJECT_ROOT/src-tauri/android/app/proguard-jellytau.pro"
|
||||
PROGUARD_DST="$PROJECT_ROOT/src-tauri/gen/android/app/proguard-jellytau.pro"
|
||||
if [ -f "$PROGUARD_SRC" ]; then
|
||||
cp "$PROGUARD_SRC" "$PROGUARD_DST"
|
||||
echo " Copied: app/proguard-jellytau.pro"
|
||||
fi
|
||||
|
||||
# Launcher icons / adaptive-icon mipmaps. `tauri android init` generates
|
||||
# low-quality launcher icons from tauri.conf.json (which has no high-res
|
||||
# Android source), so overwrite them with the real committed mipmaps.
|
||||
RES_SRC="$PROJECT_ROOT/src-tauri/android/src/main/res"
|
||||
RES_DST="$PROJECT_ROOT/src-tauri/gen/android/app/src/main/res"
|
||||
if [ -d "$RES_SRC" ]; then
|
||||
for dir in "$RES_SRC"/mipmap-*; do
|
||||
[ -d "$dir" ] || continue
|
||||
name="$(basename "$dir")"
|
||||
mkdir -p "$RES_DST/$name"
|
||||
cp "$dir"/* "$RES_DST/$name/"
|
||||
echo " Copied res: $name"
|
||||
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
|
||||
|
||||
echo "✓ Android sources synced successfully"
|
||||
|
||||
52
scripts/write-keystore-properties.sh
Executable 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)"
|
||||
14
src-tauri/android/app/proguard-jellytau.pro
Normal file
@ -0,0 +1,14 @@
|
||||
# JellyTau custom keep rules.
|
||||
#
|
||||
# These classes are loaded by name from the Rust backend via JNI
|
||||
# (env.find_class / class-loader lookups), so R8 cannot see the
|
||||
# references and would otherwise strip or rename them in a minified
|
||||
# release build — causing an instant ClassNotFoundException crash on
|
||||
# startup. See src-tauri/src/player/android/mod.rs and
|
||||
# src-tauri/src/credentials.rs.
|
||||
-keep class com.dtourolle.jellytau.player.** { *; }
|
||||
-keep class com.dtourolle.jellytau.security.** { *; }
|
||||
|
||||
# Media3 / ExoPlayer is accessed reflectively in places; keep it intact.
|
||||
-keep class androidx.media3.** { *; }
|
||||
-dontwarn androidx.media3.**
|
||||
@ -295,6 +295,14 @@ class JellyTauPlaybackService : MediaSessionService() {
|
||||
// Update MediaSession playback state
|
||||
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
|
||||
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
|
||||
* 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 {
|
||||
val playing = isPlaying || isRemoteVolumeEnabled
|
||||
return PlaybackStateCompat.Builder()
|
||||
.setActions(
|
||||
PlaybackStateCompat.ACTION_PLAY or
|
||||
@ -338,9 +355,9 @@ class JellyTauPlaybackService : MediaSessionService() {
|
||||
PlaybackStateCompat.ACTION_SEEK_TO
|
||||
)
|
||||
.setState(
|
||||
if (isPlaying) PlaybackStateCompat.STATE_PLAYING else PlaybackStateCompat.STATE_PAUSED,
|
||||
if (playing) PlaybackStateCompat.STATE_PLAYING else PlaybackStateCompat.STATE_PAUSED,
|
||||
position,
|
||||
if (isPlaying) 1.0f else 0.0f
|
||||
if (playing) 1.0f else 0.0f
|
||||
)
|
||||
.build()
|
||||
}
|
||||
|
||||
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@mipmap/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
BIN
src-tauri/android/src/main/res/mipmap-hdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 870 B |
|
After Width: | Height: | Size: 8.7 KiB |
BIN
src-tauri/android/src/main/res/mipmap-mdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 476 B |
|
After Width: | Height: | Size: 4.1 KiB |
BIN
src-tauri/android/src/main/res/mipmap-xhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 9.4 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 15 KiB |
BIN
src-tauri/android/src/main/res/mipmap-xxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 32 KiB |
BIN
src-tauri/android/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 60 KiB |
@ -133,7 +133,7 @@ impl AuthManager {
|
||||
|
||||
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) => {
|
||||
log::info!("[AuthManager] Connected to server: {} ({})", info.server_name, info.version);
|
||||
|
||||
|
||||
455
src-tauri/src/commands/catalog.rs
Normal file
@ -0,0 +1,455 @@
|
||||
//! 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 })
|
||||
}
|
||||
|
||||
#[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"));
|
||||
}
|
||||
}
|
||||
@ -1268,13 +1268,50 @@ fn spawn_download_worker(
|
||||
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 {
|
||||
Ok(res) => {
|
||||
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 {
|
||||
download_id,
|
||||
item_id,
|
||||
file_path: target_path.to_string_lossy().to_string(),
|
||||
file_path,
|
||||
};
|
||||
match app.emit("download-event", completed_event) {
|
||||
Ok(_) => debug!(" Completed event emitted successfully"),
|
||||
@ -1283,6 +1320,18 @@ fn spawn_download_worker(
|
||||
}
|
||||
Err(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 {
|
||||
download_id,
|
||||
item_id,
|
||||
@ -1296,17 +1345,6 @@ fn spawn_download_worker(
|
||||
}
|
||||
|
||||
// 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;
|
||||
});
|
||||
}
|
||||
|
||||
@ -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 |
|
||||
// DR-015, DR-017, DR-021, DR-028
|
||||
pub mod auth;
|
||||
pub mod catalog;
|
||||
pub mod connectivity;
|
||||
pub mod conversions;
|
||||
pub mod device;
|
||||
@ -17,6 +18,7 @@ pub mod storage;
|
||||
pub mod sync;
|
||||
|
||||
pub use auth::*;
|
||||
pub use catalog::*;
|
||||
pub use connectivity::*;
|
||||
pub use conversions::*;
|
||||
pub use device::*;
|
||||
|
||||
@ -1422,13 +1422,14 @@ pub async fn player_play_album_track(
|
||||
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);
|
||||
let start_index = tracks.iter()
|
||||
let album_index = tracks.iter()
|
||||
.position(|t| t.id == 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
|
||||
let mut media_items = Vec::new();
|
||||
@ -1443,13 +1444,21 @@ pub async fn player_play_album_track(
|
||||
jellyfin_item_id: Some(jellyfin_id.clone()),
|
||||
}
|
||||
} else {
|
||||
// Get stream URL from repository (works online/offline)
|
||||
let stream_url = repository.get_audio_stream_url(&track.id).await
|
||||
.map_err(|e| format!("Failed to get stream URL for {}: {}", track.name, e))?;
|
||||
|
||||
MediaSource::Remote {
|
||||
// Non-downloaded track: needs a stream URL from the server. When the
|
||||
// server is unreachable (offline), skip this track rather than failing
|
||||
// the whole album — downloaded tracks must still be playable.
|
||||
match repository.get_audio_stream_url(&track.id).await {
|
||||
Ok(stream_url) => MediaSource::Remote {
|
||||
stream_url,
|
||||
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 +1498,18 @@ pub async fn player_play_album_track(
|
||||
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);
|
||||
|
||||
// Handle shuffle before setting queue
|
||||
|
||||
@ -217,6 +217,45 @@ impl HttpClient {
|
||||
.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)
|
||||
pub async fn ping(&self, url: &str) -> bool {
|
||||
let request = self.client.get(url)
|
||||
|
||||
@ -23,6 +23,7 @@ use log::{error, info};
|
||||
use log::warn;
|
||||
|
||||
use commands::{
|
||||
sync_full_catalog, catalog_sync_status, resume_queued_downloads,
|
||||
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,
|
||||
get_download_storage_stats, get_downloads, get_download_manager_stats, set_max_concurrent_downloads,
|
||||
@ -585,6 +586,9 @@ fn specta_builder() -> Builder<tauri::Wry> {
|
||||
start_download,
|
||||
enqueue_download,
|
||||
enqueue_video_downloads,
|
||||
sync_full_catalog,
|
||||
catalog_sync_status,
|
||||
resume_queued_downloads,
|
||||
get_download_manager_stats,
|
||||
set_max_concurrent_downloads,
|
||||
get_smart_cache_stats,
|
||||
@ -930,9 +934,11 @@ pub fn run() {
|
||||
playback_mode_arc.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_wrapper = SessionPollerWrapper(session_poller_arc);
|
||||
let session_poller_wrapper = SessionPollerWrapper(session_poller_arc.clone());
|
||||
app.manage(session_poller_wrapper);
|
||||
|
||||
// On Android, set up the MediaSession (lockscreen) handler and the
|
||||
@ -994,6 +1000,12 @@ pub fn run() {
|
||||
let mut connectivity_monitor = ConnectivityMonitor::new(http_client);
|
||||
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
|
||||
let connectivity_arc = Arc::new(tokio::sync::Mutex::new(connectivity_monitor));
|
||||
let connectivity_wrapper = ConnectivityMonitorWrapper(connectivity_arc.clone());
|
||||
|
||||
@ -130,6 +130,17 @@ pub enum PlayerStatusEvent {
|
||||
/// frontend owns the two-step remote->local transfer (it must reload the
|
||||
/// media item locally), so the native side only signals intent here.
|
||||
RemoteDisconnectRequested,
|
||||
/// Backend-originated control command targeting the active frontend player
|
||||
/// adapter (the HTML5 <video> that lives in the webview, which Rust cannot
|
||||
/// drive directly). Emitted by control paths like the sleep timer, lockscreen,
|
||||
/// or remote so they can pause/play/seek/stop the webview element.
|
||||
/// `playerEvents.ts` routes this to the active PlayerAdapter via the facade.
|
||||
ControlCommand {
|
||||
/// One of: "play", "pause", "stop", "seek".
|
||||
action: String,
|
||||
/// Target position in seconds (only meaningful for "seek").
|
||||
position: Option<f64>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Trait for emitting player events to the frontend.
|
||||
|
||||
@ -79,6 +79,26 @@ impl HybridRepository {
|
||||
.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).
|
||||
pub async fn search_server_only(
|
||||
&self,
|
||||
@ -196,11 +216,41 @@ impl HybridRepository {
|
||||
#[async_trait]
|
||||
impl MediaRepository for HybridRepository {
|
||||
async fn get_libraries(&self) -> Result<Vec<Library>, RepoError> {
|
||||
// Libraries change infrequently, try cache first with fast timeout
|
||||
let cache_future = self.cache_with_timeout(self.offline.get_libraries());
|
||||
let server_future = self.online.get_libraries();
|
||||
// Cache-first (100ms). On a cache hit, refresh the cache from the server
|
||||
// in the background. On a miss, fetch from the server and persist so the
|
||||
// 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> {
|
||||
@ -377,20 +427,60 @@ impl MediaRepository for HybridRepository {
|
||||
}
|
||||
|
||||
async fn get_genres(&self, parent_id: Option<&str>) -> Result<Vec<Genre>, RepoError> {
|
||||
let offline = Arc::clone(&self.offline);
|
||||
let online = Arc::clone(&self.online);
|
||||
// Cache-first (100ms). On a cache hit, refresh the cached genre catalog
|
||||
// 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_clone = parent_id_str.clone();
|
||||
|
||||
let cache_future = self.cache_with_timeout(async move {
|
||||
offline.get_genres(parent_id_str.as_deref()).await
|
||||
let cache_offline = Arc::clone(&self.offline);
|
||||
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;
|
||||
|
||||
if let Ok(genres) = &cache_result {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
let server_future = async move {
|
||||
online.get_genres(parent_id_clone.as_deref()).await
|
||||
};
|
||||
|
||||
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> {
|
||||
|
||||
@ -359,6 +359,94 @@ impl OfflineRepository {
|
||||
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
|
||||
/// Called by HybridRepository after fetching from online
|
||||
pub async fn save_playlist_items_to_cache(
|
||||
@ -413,26 +501,17 @@ impl OfflineRepository {
|
||||
#[async_trait]
|
||||
impl MediaRepository for OfflineRepository {
|
||||
async fn get_libraries(&self) -> Result<Vec<Library>, RepoError> {
|
||||
// Only show libraries that have downloaded content
|
||||
// Check both direct children and nested children (e.g., albums inside library)
|
||||
// Return every cached library for this server. We deliberately do NOT
|
||||
// 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(
|
||||
"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
|
||||
INNER JOIN items i ON i.library_id = l.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",
|
||||
vec![QueryParam::String(self.server_id.clone())],
|
||||
);
|
||||
@ -494,7 +573,7 @@ impl MediaRepository for OfflineRepository {
|
||||
-- Containers with downloaded children
|
||||
SELECT DISTINCT i.id
|
||||
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
|
||||
WHERE d.status = 'completed'
|
||||
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
|
||||
@ -513,17 +592,38 @@ impl MediaRepository for OfflineRepository {
|
||||
i.parent_index_number, i.is_folder, i.premiere_date
|
||||
FROM items i
|
||||
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 {}
|
||||
LIMIT {} OFFSET {}",
|
||||
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(
|
||||
sql,
|
||||
vec![
|
||||
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 +666,7 @@ impl MediaRepository for OfflineRepository {
|
||||
-- Containers with downloaded children
|
||||
SELECT DISTINCT i.id
|
||||
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
|
||||
WHERE d.status = 'completed'
|
||||
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
|
||||
@ -611,7 +711,7 @@ impl MediaRepository for OfflineRepository {
|
||||
-- Containers with downloaded children
|
||||
SELECT DISTINCT i.id
|
||||
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
|
||||
WHERE d.status = 'completed'
|
||||
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
|
||||
@ -744,7 +844,7 @@ impl MediaRepository for OfflineRepository {
|
||||
-- Containers with downloaded children (Albums)
|
||||
SELECT DISTINCT i.id
|
||||
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
|
||||
WHERE d.status = 'completed'
|
||||
AND i.item_type = 'MusicAlbum'
|
||||
@ -849,59 +949,32 @@ impl MediaRepository for OfflineRepository {
|
||||
}
|
||||
|
||||
async fn get_genres(&self, parent_id: Option<&str>) -> Result<Vec<Genre>, RepoError> {
|
||||
// Derive genres from cached albums, tallying how many albums carry each
|
||||
// so the frontend can rank by popularity. We scope to MusicAlbum (genres
|
||||
// power the music landing) and read every matching row — NOT DISTINCT —
|
||||
// so the per-genre counts are real. Genres are stored as a JSON array
|
||||
// string per item.
|
||||
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",
|
||||
// Read the cached server genre catalog (populated by the hybrid repo via
|
||||
// save_genres_to_cache). This is the FULL genre list for the library, not
|
||||
// just the genres derivable from locally-cached albums — so offline keeps
|
||||
// the same variety the server has. library_id NULL is stored as ''.
|
||||
let library_id = parent_id.unwrap_or("").to_string();
|
||||
|
||||
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(pid.to_string()),
|
||||
QueryParam::String(library_id),
|
||||
],
|
||||
)
|
||||
} 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 genres_rows: Vec<String> = self
|
||||
let genres: Vec<Genre> = self
|
||||
.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
|
||||
.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)
|
||||
}
|
||||
|
||||
@ -943,7 +1016,7 @@ impl MediaRepository for OfflineRepository {
|
||||
-- Containers with downloaded children
|
||||
SELECT DISTINCT i.id
|
||||
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
|
||||
WHERE d.status = 'completed'
|
||||
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
|
||||
@ -1157,7 +1230,7 @@ impl MediaRepository for OfflineRepository {
|
||||
-- Containers with downloaded children
|
||||
SELECT DISTINCT i.id
|
||||
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
|
||||
WHERE d.status = 'completed'
|
||||
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
|
||||
@ -1541,6 +1614,32 @@ mod tests {
|
||||
);
|
||||
|
||||
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();
|
||||
|
||||
// Insert a test server
|
||||
@ -1721,6 +1820,196 @@ mod tests {
|
||||
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: 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 =====
|
||||
|
||||
/// Helper to seed items into the DB for playlist tests
|
||||
|
||||
@ -144,6 +144,17 @@ impl OnlineRepository {
|
||||
|
||||
/// Make authenticated GET request
|
||||
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;
|
||||
self.report_outcome(&result).await;
|
||||
result
|
||||
@ -1413,12 +1424,43 @@ impl MediaRepository for OnlineRepository {
|
||||
quality: &str,
|
||||
media_source_id: Option<&str>,
|
||||
) -> 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)];
|
||||
|
||||
// Add quality parameter if not "original"
|
||||
if quality != "original" {
|
||||
params.push(format!("quality={}", quality));
|
||||
// Map the frontend quality preset to concrete transcode params. For
|
||||
// "original" we request a direct static copy (no transcode) which is
|
||||
// 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
|
||||
@ -1426,10 +1468,8 @@ impl MediaRepository for OnlineRepository {
|
||||
params.push(format!("mediaSourceId={}", source_id));
|
||||
}
|
||||
|
||||
if !params.is_empty() {
|
||||
url.push('?');
|
||||
url.push_str(¶ms.join("&"));
|
||||
}
|
||||
|
||||
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
|
||||
/// online (debounce window not yet elapsed).
|
||||
#[tokio::test]
|
||||
@ -1887,6 +1946,74 @@ mod tests {
|
||||
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]
|
||||
fn test_jellyfin_item_deserialize_with_image_tags() {
|
||||
// Test full JellyfinItem deserialization with ImageTags
|
||||
|
||||
@ -32,6 +32,13 @@ pub struct SessionPollerManager {
|
||||
jellyfin_client: Arc<Mutex<Option<JellyfinClient>>>,
|
||||
playback_mode_manager: Arc<PlaybackModeManager>,
|
||||
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
|
||||
is_running: Arc<AtomicBool>,
|
||||
@ -52,6 +59,7 @@ impl SessionPollerManager {
|
||||
jellyfin_client,
|
||||
playback_mode_manager,
|
||||
event_emitter: Arc::new(Mutex::new(None)),
|
||||
connectivity_reporter: Arc::new(Mutex::new(None)),
|
||||
is_running: Arc::new(AtomicBool::new(false)),
|
||||
current_hint: Arc::new(RwLock::new(PollingHint::Normal)),
|
||||
current_interval_ms: Arc::new(AtomicU64::new(10000)), // Default 10s
|
||||
@ -64,6 +72,13 @@ impl SessionPollerManager {
|
||||
*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
|
||||
pub fn start(&self) {
|
||||
if self.is_running.swap(true, Ordering::Relaxed) {
|
||||
@ -77,6 +92,7 @@ impl SessionPollerManager {
|
||||
let client = self.jellyfin_client.clone();
|
||||
let mode_manager = self.playback_mode_manager.clone();
|
||||
let emitter = self.event_emitter.clone();
|
||||
let connectivity_reporter = self.connectivity_reporter.clone();
|
||||
let is_running = self.is_running.clone();
|
||||
let hint = self.current_hint.clone();
|
||||
let interval_ms = self.current_interval_ms.clone();
|
||||
@ -96,18 +112,35 @@ impl SessionPollerManager {
|
||||
|
||||
debug!("[SessionPoller] Polling with interval: {}ms", new_interval);
|
||||
|
||||
// Fetch sessions
|
||||
let sessions_result = rt.block_on(async {
|
||||
// Fetch sessions. `had_client` distinguishes "server didn't
|
||||
// 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();
|
||||
match client_opt {
|
||||
Some(c) => c.get_sessions().await,
|
||||
Some(c) => (c.get_sessions().await, true),
|
||||
None => {
|
||||
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
|
||||
match sessions_result {
|
||||
Ok(sessions) => {
|
||||
|
||||
@ -201,6 +201,7 @@ mod tests {
|
||||
"thumbnails",
|
||||
"playlists",
|
||||
"playlist_items",
|
||||
"genres",
|
||||
];
|
||||
|
||||
for table in expected_tables {
|
||||
|
||||
@ -23,6 +23,7 @@ pub const MIGRATIONS: &[(&str, &str)] = &[
|
||||
("016_autoplay_max_episodes", MIGRATION_016),
|
||||
("017_downloads_resume_url", MIGRATION_017),
|
||||
("018_items_is_folder", MIGRATION_018),
|
||||
("019_genres_cache", MIGRATION_019),
|
||||
];
|
||||
|
||||
/// 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.
|
||||
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);
|
||||
"#;
|
||||
|
||||
@ -64,7 +64,8 @@ impl ThumbnailCache {
|
||||
image_type: &str,
|
||||
tag: &str,
|
||||
) -> 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
|
||||
WHERE item_id = ? AND image_type = ? AND image_tag = ?",
|
||||
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);
|
||||
|
||||
if path.exists() {
|
||||
// Update last_accessed for LRU tracking
|
||||
let update_query = Query::with_params(
|
||||
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() {
|
||||
self.touch(&db, item_id, image_type, None).await;
|
||||
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
|
||||
WHERE item_id = ? AND image_type = ? AND image_tag = ?",
|
||||
vec![
|
||||
@ -87,23 +136,17 @@ impl ThumbnailCache {
|
||||
QueryParam::String(image_type.to_string()),
|
||||
QueryParam::String(tag.to_string()),
|
||||
],
|
||||
);
|
||||
let _ = db.execute(update_query).await;
|
||||
Some(path)
|
||||
} else {
|
||||
// Clean up stale database entry
|
||||
let delete_query = Query::with_params(
|
||||
"DELETE FROM thumbnails
|
||||
WHERE item_id = ? AND image_type = ? AND image_tag = ?",
|
||||
),
|
||||
None => Query::with_params(
|
||||
"UPDATE thumbnails SET last_accessed = CURRENT_TIMESTAMP
|
||||
WHERE item_id = ? AND image_type = ?",
|
||||
vec![
|
||||
QueryParam::String(item_id.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
|
||||
|
||||
@ -806,6 +806,38 @@ async enqueueDownload(downloadId: number, streamUrl: string, targetDir: string)
|
||||
async enqueueVideoDownloads(handle: string, downloadIds: number[], targetDir: string) : Promise<null> {
|
||||
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");
|
||||
},
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
@ -1505,6 +1537,20 @@ export type CachedLibrary = { id: string; serverId: string; name: string; collec
|
||||
* 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 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
|
||||
*/
|
||||
@ -1996,7 +2042,15 @@ export type PlayerStatusEvent =
|
||||
* frontend owns the two-step remote->local transfer (it must reload the
|
||||
* media item locally), so the native side only signals intent here.
|
||||
*/
|
||||
{ type: "remote_disconnect_requested" }
|
||||
{ type: "remote_disconnect_requested" } |
|
||||
/**
|
||||
* Backend-originated control command targeting the active frontend player
|
||||
* adapter (the HTML5 <video> that lives in the webview, which Rust cannot
|
||||
* drive directly). Emitted by control paths like the sleep timer, lockscreen,
|
||||
* or remote so they can pause/play/seek/stop the webview element.
|
||||
* `playerEvents.ts` routes this to the active PlayerAdapter via the facade.
|
||||
*/
|
||||
{ type: "control_command"; action: string; position: number | null }
|
||||
/**
|
||||
* Result of creating a playlist
|
||||
*
|
||||
@ -2058,6 +2112,15 @@ export type RemoteSessionStatus = { position: number; duration: number | null; i
|
||||
* TRACES: UR-005 | DR-005
|
||||
*/
|
||||
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
|
||||
*/
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { page } from "$app/stores";
|
||||
import { truncateMiddle } from "$lib/utils/truncateMiddle";
|
||||
import { goto } from "$app/navigation";
|
||||
import { navigateBack } from "$lib/utils/navigation";
|
||||
@ -53,6 +54,16 @@
|
||||
|
||||
onMount(async () => {
|
||||
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();
|
||||
});
|
||||
|
||||
|
||||
@ -5,14 +5,34 @@
|
||||
genres: string[];
|
||||
maxShow?: number; // Default: unlimited
|
||||
clickable?: boolean; // Default: true
|
||||
itemType?: string; // Determines which genre browse page to open
|
||||
}
|
||||
|
||||
let {
|
||||
genres,
|
||||
maxShow,
|
||||
clickable = true
|
||||
clickable = true,
|
||||
itemType
|
||||
}: 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(
|
||||
maxShow ? genres.slice(0, maxShow) : genres
|
||||
);
|
||||
@ -23,9 +43,7 @@
|
||||
|
||||
function handleGenreClick(genre: string) {
|
||||
if (clickable) {
|
||||
// Navigate to genre browse page
|
||||
// For now, we'll use a simple navigation - could be enhanced with a proper genre browse page
|
||||
goto(`/search?genre=${encodeURIComponent(genre)}`);
|
||||
goto(`${genreBasePath(itemType)}?genre=${encodeURIComponent(genre)}`);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
130
src/lib/components/library/MediaCard.serverOnly.test.ts
Normal file
@ -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();
|
||||
});
|
||||
});
|
||||
@ -2,6 +2,9 @@
|
||||
import type { MediaItem, Library } from "$lib/api/types";
|
||||
import { truncateMiddle } from "$lib/utils/truncateMiddle";
|
||||
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";
|
||||
|
||||
interface Props {
|
||||
@ -25,6 +28,55 @@
|
||||
);
|
||||
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 = {
|
||||
small: "w-24",
|
||||
medium: "w-36",
|
||||
@ -76,10 +128,12 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="group/card flex flex-col text-left {sizeClasses[size]} flex-shrink-0 transition-transform duration-200 hover:scale-105"
|
||||
{onclick}
|
||||
<svelte:element
|
||||
this={isServerOnly ? "div" : "button"}
|
||||
type={isServerOnly ? undefined : "button"}
|
||||
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">
|
||||
<CachedImage
|
||||
@ -88,11 +142,12 @@
|
||||
tag={imageTag}
|
||||
maxWidth={maxWidth}
|
||||
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 -->
|
||||
<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">
|
||||
<!-- Hover overlay with smooth gradient (play affordance; hidden for
|
||||
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="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">
|
||||
@ -163,9 +218,43 @@
|
||||
{/if}
|
||||
</div>
|
||||
{/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 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">
|
||||
{truncateMiddle(item.name, 40)}
|
||||
</p>
|
||||
@ -173,4 +262,4 @@
|
||||
<p class="text-xs text-gray-400 truncate">{subtitle()}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</button>
|
||||
</svelte:element>
|
||||
|
||||
7
src/lib/components/library/__mocks__/StubImage.svelte
Normal file
@ -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>
|
||||
@ -19,6 +19,7 @@
|
||||
import { goto } from "$app/navigation";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import {
|
||||
mergedMedia,
|
||||
mergedIsPlaying,
|
||||
@ -70,6 +71,27 @@
|
||||
// In remote mode, this automatically uses the remote session's nowPlayingItem
|
||||
const displayMedia = $derived($mergedMedia || $currentQueueItem);
|
||||
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 displayDuration = $derived($mergedDuration);
|
||||
|
||||
@ -358,7 +380,7 @@
|
||||
{#if displayMedia}
|
||||
<FavoriteButton
|
||||
itemId={displayMedia?.id ?? ""}
|
||||
isFavorite={displayMedia?.userData?.isFavorite ?? false}
|
||||
bind:isFavorite
|
||||
size="sm"
|
||||
/>
|
||||
{/if}
|
||||
|
||||
@ -15,6 +15,9 @@
|
||||
import { sleepTimerActive, sleepTimerExpiredSignal } from "$lib/stores/sleepTimer";
|
||||
import { playbackPosition } from "$lib/stores/player";
|
||||
import * as html5Adapter from "$lib/player/html5Adapter";
|
||||
import { playerController } from "$lib/player";
|
||||
import { Html5PlayerAdapter, type Html5ElementBridge } from "$lib/player/adapters";
|
||||
import { createRustReportHost } from "$lib/player/adapters/rustReportHost";
|
||||
|
||||
interface Props {
|
||||
media: MediaItem | null;
|
||||
@ -67,7 +70,10 @@
|
||||
let controlsTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
let seekOffset = $state(0); // Track offset when seeking in transcoded streams
|
||||
let isSeeking = $state(false);
|
||||
let currentStreamUrl = $state(streamUrl);
|
||||
// Capture only the initial streamUrl prop; later prop changes are applied via
|
||||
// the $effect below (untrack keeps this a one-time snapshot, matching
|
||||
// reportMediaId above and silencing state_referenced_locally).
|
||||
let currentStreamUrl = $state(untrack(() => streamUrl));
|
||||
let hasReportedStart = $state(false);
|
||||
let progressInterval: ReturnType<typeof setInterval> | null = null;
|
||||
let isMediaReady = $state(false); // Track if media is ready to play (implements Loading state from DR-001)
|
||||
@ -106,6 +112,31 @@
|
||||
let hls: Hls | null = null; // HLS.js instance for streaming HLS content
|
||||
let hlsFatalRecoveryAttempts = 0; // Track recovery attempts to prevent infinite restarts
|
||||
|
||||
// ===== Player adapter (control boundary) =====
|
||||
// The adapter owns the high-level control contract (play/pause/seek/track).
|
||||
// VideoPlayer supplies a narrow bridge for the element/HLS-coupled parts and
|
||||
// registers the adapter with the facade so control intents — from UI OR from a
|
||||
// backend control event (lockscreen/remote/sleep) — reach this element.
|
||||
let playerAdapter: Html5PlayerAdapter | null = null;
|
||||
|
||||
function tearDownHls() {
|
||||
if (hls) {
|
||||
hls.detachMedia();
|
||||
hls.stopLoad();
|
||||
hls.destroy();
|
||||
hls = null;
|
||||
}
|
||||
}
|
||||
|
||||
const adapterBridge: Html5ElementBridge = {
|
||||
getElement: () => videoElement,
|
||||
getSeekOffset: () => seekOffset,
|
||||
setSeekOffset: (o) => { seekOffset = o; },
|
||||
setStreamUrl: (u) => { currentStreamUrl = u; },
|
||||
destroyHls: tearDownHls,
|
||||
getMediaSourceId: () => mediaSourceId ?? null,
|
||||
};
|
||||
|
||||
// Audio track selection
|
||||
let showAudioTrackMenu = $state(false);
|
||||
let selectedAudioTrackIndex = $state<number | null>(null);
|
||||
@ -222,20 +253,11 @@
|
||||
});
|
||||
|
||||
|
||||
// Pause playback when the time-based sleep timer expires. The backend stops
|
||||
// its own (MPV/ExoPlayer) playback itself, but the HTML5 <video> element
|
||||
// plays in the webview outside the backend's control, so it must be paused
|
||||
// here or the sleep timer never actually stops video playback on Linux.
|
||||
let lastSleepExpirySeen = $sleepTimerExpiredSignal;
|
||||
$effect(() => {
|
||||
if ($sleepTimerExpiredSignal !== lastSleepExpirySeen) {
|
||||
lastSleepExpirySeen = $sleepTimerExpiredSignal;
|
||||
if (useHtml5Element && videoElement && !videoElement.paused) {
|
||||
console.log("[VideoPlayer] Sleep timer expired - pausing playback");
|
||||
videoElement.pause();
|
||||
}
|
||||
}
|
||||
});
|
||||
// Sleep-timer expiry pause is now driven by the backend through the player
|
||||
// adapter: playerEvents.ts routes `sleep_timer_expired` to the active adapter's
|
||||
// pause() (see handleControlCommand / the sleep_timer_expired case). This
|
||||
// removes the component's direct videoElement.pause() reach-in — the backend
|
||||
// has control authority over the webview element via the adapter boundary.
|
||||
|
||||
// Native backend (Android ExoPlayer): drive the seek bar from the player
|
||||
// store, which is fed by the backend's PositionUpdate events. The legacy
|
||||
@ -545,6 +567,18 @@
|
||||
didStartNativePlayback = true; // Track that we need to stop backend on unmount
|
||||
}
|
||||
|
||||
// Register the HTML5 player adapter with the facade so control intents
|
||||
// (UI or backend lockscreen/remote/sleep events) route to this element.
|
||||
if (useHtml5Element) {
|
||||
const host = createRustReportHost(media.id, {
|
||||
onEnded: () => notifyEnded(),
|
||||
onStreamUrlChanged: (u) => { currentStreamUrl = u; },
|
||||
});
|
||||
playerAdapter = new Html5PlayerAdapter(host, adapterBridge);
|
||||
playerAdapter.attach(videoElement);
|
||||
playerController.setActiveAdapter(playerAdapter);
|
||||
}
|
||||
|
||||
if (!useHtml5Element) {
|
||||
// Using native backend, subscribe to player events
|
||||
didStartNativePlayback = true; // Track that we started native playback
|
||||
@ -633,6 +667,12 @@
|
||||
// Stop RAF loop
|
||||
stopTimeUpdates();
|
||||
|
||||
// Unregister the adapter from the facade (guarded so we only clear our own).
|
||||
if (playerAdapter) {
|
||||
playerController.clearActiveAdapter(playerAdapter);
|
||||
playerAdapter = null;
|
||||
}
|
||||
|
||||
if (progressInterval) {
|
||||
clearInterval(progressInterval);
|
||||
}
|
||||
@ -969,8 +1009,13 @@
|
||||
function handleEnded() {
|
||||
isPlaying = false;
|
||||
stopTimeUpdates(); // Stop RAF loop when ended
|
||||
html5Adapter.reportState("stopped", reportMediaId ?? null);
|
||||
// Report stop when video ends (skip for live - no resume tracking)
|
||||
// NOTE: do NOT report a "stopped" player state here. Natural end-of-video is
|
||||
// an autoplay handoff, not a stop: the backend's on_video_playback_ended
|
||||
// decides whether to advance to the next episode (incl. sleep-timer episode
|
||||
// counting). Emitting StateChanged{stopped} would flip the player/mode to
|
||||
// idle mid-handoff and suppress the next-episode auto-advance (pauses at the
|
||||
// end of an episode instead of continuing). onReportStop below still reports
|
||||
// progress to Jellyfin; notifyEnded() drives the autoplay decision.
|
||||
if (!isLive && onReportStop) {
|
||||
onReportStop(currentTime, reportMediaId);
|
||||
}
|
||||
@ -979,19 +1024,13 @@
|
||||
}
|
||||
|
||||
async function togglePlayPause() {
|
||||
if (!useHtml5Element) {
|
||||
// Route through the facade → active adapter so the toggle goes through the
|
||||
// one control boundary (and the adapter reports the resulting element state
|
||||
// back into Rust). The element's own play/pause handlers update isPlaying.
|
||||
try {
|
||||
const response = (await commands.playerToggle()) as any;
|
||||
isPlaying = response.state === "playing";
|
||||
await playerController.toggle();
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Failed to toggle native player:", err);
|
||||
}
|
||||
} else if (videoElement) {
|
||||
if (videoElement.paused) {
|
||||
videoElement.play();
|
||||
} else {
|
||||
videoElement.pause();
|
||||
}
|
||||
console.error("[VideoPlayer] Failed to toggle playback:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1011,133 +1050,29 @@
|
||||
isDraggingSeekBar = false;
|
||||
|
||||
try {
|
||||
console.log("[VideoPlayer] Seeking to:", targetTime.toFixed(2), "useHtml5Element:", useHtml5Element);
|
||||
console.log("[VideoPlayer] Seeking to:", targetTime.toFixed(2));
|
||||
|
||||
const repo = auth.getRepository();
|
||||
if (!repo) {
|
||||
console.error("[VideoPlayer] No repository available");
|
||||
return;
|
||||
}
|
||||
// Optimistic display; the primitive updates currentTime/seekOffset as it
|
||||
// completes (reloadSource drives the stream URL via the adapter bridge).
|
||||
currentTime = targetTime;
|
||||
stopTimeUpdates(); // pause RAF while the seek settles
|
||||
|
||||
// Backend smart seeking handles both native and HTML5
|
||||
const response = (await commands.playerSeekVideo(
|
||||
repo.getHandle(),
|
||||
// The BACKEND decides the strategy (in-place vs transcode reload); the
|
||||
// facade dispatches the matching adapter PRIMITIVE. This is the shared
|
||||
// decision-in-Rust design — no strategy branch lives here anymore.
|
||||
lastNativeSeekAt = Date.now();
|
||||
await playerController.seekVideo(
|
||||
targetTime,
|
||||
mediaSourceId ?? null,
|
||||
selectedAudioTrackIndex ?? null,
|
||||
useHtml5Element
|
||||
)) as any;
|
||||
selectedAudioTrackIndex ?? null
|
||||
);
|
||||
|
||||
console.log("[VideoPlayer] Backend seek response:", response);
|
||||
|
||||
// For native backend, the backend handles everything internally
|
||||
if (!useHtml5Element) {
|
||||
// Backend already stopped, reloaded, and seeked if needed
|
||||
lastNativeSeekAt = Date.now();
|
||||
currentTime = response.position ?? targetTime;
|
||||
if (response.strategy === "reloadStream") {
|
||||
// Serde keeps these fields snake_case (only the "strategy" tag is camelCase)
|
||||
seekOffset = response.seek_offset ?? targetTime;
|
||||
currentStreamUrl = response.new_url ?? currentStreamUrl;
|
||||
} else {
|
||||
seekOffset = 0;
|
||||
}
|
||||
console.log("[VideoPlayer] Native backend seek completed at position:", currentTime);
|
||||
return;
|
||||
// Resume smooth updates if still playing after the seek settled.
|
||||
if (videoElement && !videoElement.paused) {
|
||||
startTimeUpdates();
|
||||
}
|
||||
|
||||
// HTML5 backend - handle video element management
|
||||
if (!videoElement) {
|
||||
console.warn("[VideoPlayer] Cannot seek - video element not available");
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.strategy === "reloadStream") {
|
||||
// Transcoded stream - reload with new URL
|
||||
console.log("[VideoPlayer] Reloading HTML5 stream from position:", targetTime);
|
||||
const wasPlaying = !videoElement.paused;
|
||||
|
||||
// CRITICAL: Stop playback completely to prevent dual audio
|
||||
videoElement.pause();
|
||||
stopTimeUpdates(); // Stop RAF updates
|
||||
|
||||
// CRITICAL: Destroy old HLS instance completely to prevent dual audio
|
||||
if (hls) {
|
||||
console.log("[VideoPlayer] Destroying old HLS instance for seek");
|
||||
hls.detachMedia(); // Detach from video element
|
||||
hls.stopLoad(); // Stop loading fragments
|
||||
hls.destroy(); // Completely destroy the instance
|
||||
hls = null; // Clear reference
|
||||
}
|
||||
|
||||
// CRITICAL: Clear video element buffers completely
|
||||
if (videoElement.src) {
|
||||
videoElement.removeAttribute('src');
|
||||
videoElement.load(); // Reset and flush all buffers
|
||||
}
|
||||
|
||||
// Small delay to ensure cleanup completes before creating new HLS instance
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Update stream URL (this will trigger $effect to create new HLS instance)
|
||||
// Serde keeps these fields snake_case (only the "strategy" tag is camelCase)
|
||||
seekOffset = response.seek_offset ?? targetTime;
|
||||
currentStreamUrl = response.new_url ?? currentStreamUrl;
|
||||
currentTime = targetTime;
|
||||
|
||||
// Wait for video to be ready
|
||||
await new Promise<void>((resolve) => {
|
||||
const onCanPlay = () => {
|
||||
console.log("[VideoPlayer] Transcoded video loaded after seek");
|
||||
videoElement?.removeEventListener("canplay", onCanPlay);
|
||||
resolve();
|
||||
};
|
||||
if (videoElement) {
|
||||
videoElement.addEventListener("canplay", onCanPlay);
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
console.warn("[VideoPlayer] Transcoded seek timeout");
|
||||
videoElement?.removeEventListener("canplay", onCanPlay);
|
||||
resolve();
|
||||
}, 10000);
|
||||
});
|
||||
|
||||
if (wasPlaying && videoElement) {
|
||||
await videoElement.play();
|
||||
startTimeUpdates(); // Restart RAF updates
|
||||
}
|
||||
} else {
|
||||
// Native browser seeking
|
||||
console.log("[VideoPlayer] Using native HTML5 seek to:", targetTime.toFixed(2));
|
||||
videoElement.currentTime = targetTime;
|
||||
currentTime = targetTime;
|
||||
seekOffset = 0;
|
||||
|
||||
// Wait for seek to complete
|
||||
await new Promise<void>((resolve) => {
|
||||
const onSeeked = () => {
|
||||
console.log("[VideoPlayer] Native seek completed");
|
||||
videoElement?.removeEventListener("seeked", onSeeked);
|
||||
resolve();
|
||||
};
|
||||
if (videoElement) {
|
||||
videoElement.addEventListener("seeked", onSeeked);
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
videoElement?.removeEventListener("seeked", onSeeked);
|
||||
resolve();
|
||||
}, 2000);
|
||||
});
|
||||
}
|
||||
|
||||
console.log("[VideoPlayer] HTML5 seek completed:", {
|
||||
strategy: response.strategy,
|
||||
targetTime: targetTime.toFixed(2),
|
||||
actualTime: videoElement.currentTime.toFixed(2),
|
||||
seekOffset,
|
||||
});
|
||||
console.log("[VideoPlayer] Seek completed at:", currentTime.toFixed(2), "offset:", seekOffset);
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Seek failed:", err);
|
||||
} finally {
|
||||
@ -1307,74 +1242,19 @@
|
||||
showAudioTrackMenu = false;
|
||||
|
||||
try {
|
||||
const repo = auth.getRepository();
|
||||
if (!repo) throw new Error("Not authenticated");
|
||||
|
||||
// Call unified backend command
|
||||
const response = (await commands.playerSwitchAudioTrack(
|
||||
repo.getHandle(),
|
||||
// The BACKEND decides whether the audio-track switch needs a transcode
|
||||
// reload; the facade dispatches the resulting adapter PRIMITIVE
|
||||
// (reloadSource) which runs the invariant dual-audio teardown sequence.
|
||||
// No strategy branch lives here anymore.
|
||||
stopTimeUpdates();
|
||||
await playerController.switchAudioTrack(
|
||||
streamIndex,
|
||||
arrayIndex,
|
||||
useHtml5Element,
|
||||
useHtml5Element && videoElement ? videoElement.currentTime + seekOffset : null,
|
||||
videoElement ? videoElement.currentTime + seekOffset : null,
|
||||
mediaSourceId ?? null
|
||||
)) as any;
|
||||
|
||||
// Handle response based on strategy
|
||||
if (response.strategy === "reloadStream" && useHtml5Element && videoElement) {
|
||||
console.log("[VideoPlayer] Switching audio track - reloading stream");
|
||||
|
||||
// Save state before reload
|
||||
const wasPlaying = !videoElement.paused;
|
||||
|
||||
// CRITICAL: Stop playback completely to prevent dual audio
|
||||
videoElement.pause();
|
||||
stopTimeUpdates(); // Stop RAF updates
|
||||
|
||||
// CRITICAL: Destroy old HLS instance completely to prevent dual audio
|
||||
if (hls) {
|
||||
console.log("[VideoPlayer] Destroying old HLS instance for audio track switch");
|
||||
hls.detachMedia(); // Detach from video element
|
||||
hls.stopLoad(); // Stop loading fragments
|
||||
hls.destroy(); // Completely destroy the instance
|
||||
hls = null; // Clear reference
|
||||
}
|
||||
|
||||
// CRITICAL: Clear video element buffers completely
|
||||
if (videoElement.src) {
|
||||
videoElement.removeAttribute('src');
|
||||
videoElement.load(); // Reset and flush all buffers
|
||||
}
|
||||
|
||||
// Small delay to ensure cleanup completes before creating new HLS instance
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Update stream URL (this will trigger $effect to create new HLS instance)
|
||||
// Serde keeps new_url snake_case (only the "strategy" tag is camelCase)
|
||||
currentStreamUrl = response.new_url!;
|
||||
seekOffset = response.position!;
|
||||
|
||||
// Wait for video to be ready
|
||||
await new Promise<void>((resolve) => {
|
||||
const onCanPlay = () => {
|
||||
console.log("[VideoPlayer] Video reloaded with new audio track");
|
||||
videoElement?.removeEventListener("canplay", onCanPlay);
|
||||
resolve();
|
||||
};
|
||||
videoElement!.addEventListener("canplay", onCanPlay);
|
||||
|
||||
// Timeout fallback
|
||||
setTimeout(() => {
|
||||
videoElement?.removeEventListener("canplay", onCanPlay);
|
||||
resolve();
|
||||
}, 5000);
|
||||
});
|
||||
|
||||
// Resume playback if it was playing
|
||||
if (wasPlaying) {
|
||||
await videoElement.play();
|
||||
startTimeUpdates(); // Restart RAF updates
|
||||
}
|
||||
);
|
||||
if (videoElement && !videoElement.paused) {
|
||||
startTimeUpdates();
|
||||
}
|
||||
|
||||
console.log("[VideoPlayer] Successfully changed audio track");
|
||||
|
||||
194
src/lib/player/adapters/html5Adapter.test.ts
Normal file
@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Unit tests for Html5PlayerAdapter.
|
||||
*
|
||||
* The Option-1 primitive design makes the adapter pure, decision-free mechanics
|
||||
* — it takes a mock <video> element + bridge + host, so we can assert each
|
||||
* primitive drives the element correctly without any real DOM or backend.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { Html5PlayerAdapter, type Html5ElementBridge } from "./html5Adapter";
|
||||
import type { AdapterHost } from "./types";
|
||||
|
||||
/** A minimal fake <video> element that records mutations and fires events. */
|
||||
function makeFakeVideo() {
|
||||
const listeners: Record<string, Array<() => void>> = {};
|
||||
const el: any = {
|
||||
paused: true,
|
||||
currentTime: 0,
|
||||
volume: 1,
|
||||
muted: false,
|
||||
src: "blob:existing",
|
||||
play: vi.fn(async () => {
|
||||
el.paused = false;
|
||||
}),
|
||||
pause: vi.fn(() => {
|
||||
el.paused = true;
|
||||
}),
|
||||
load: vi.fn(),
|
||||
removeAttribute: vi.fn((attr: string) => {
|
||||
if (attr === "src") el.src = "";
|
||||
}),
|
||||
addEventListener: (event: string, cb: () => void) => {
|
||||
(listeners[event] ??= []).push(cb);
|
||||
},
|
||||
removeEventListener: (event: string, cb: () => void) => {
|
||||
listeners[event] = (listeners[event] ?? []).filter((f) => f !== cb);
|
||||
},
|
||||
// Test helper: fire an event so waitForEvent resolves immediately.
|
||||
_fire: (event: string) => {
|
||||
(listeners[event] ?? []).slice().forEach((f) => f());
|
||||
},
|
||||
querySelectorAll: () => [] as any,
|
||||
textTracks: [] as any,
|
||||
};
|
||||
return el;
|
||||
}
|
||||
type FakeVideo = ReturnType<typeof makeFakeVideo>;
|
||||
|
||||
function makeBridge(overrides: Partial<Html5ElementBridge> = {}): Html5ElementBridge {
|
||||
let offset = 0;
|
||||
return {
|
||||
getElement: () => null,
|
||||
getSeekOffset: () => offset,
|
||||
setSeekOffset: vi.fn((o: number) => { offset = o; }),
|
||||
setStreamUrl: vi.fn(),
|
||||
destroyHls: vi.fn(),
|
||||
getMediaSourceId: () => "msid-1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeHost(): AdapterHost {
|
||||
return {
|
||||
onState: vi.fn(),
|
||||
onPosition: vi.fn(),
|
||||
onMediaLoaded: vi.fn(),
|
||||
onEnded: vi.fn(),
|
||||
onError: vi.fn(),
|
||||
onStreamUrlChanged: vi.fn(),
|
||||
onBuffering: vi.fn(),
|
||||
onReady: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("Html5PlayerAdapter", () => {
|
||||
let host: AdapterHost;
|
||||
let bridge: Html5ElementBridge;
|
||||
let adapter: Html5PlayerAdapter;
|
||||
let video: ReturnType<typeof makeFakeVideo>;
|
||||
|
||||
beforeEach(() => {
|
||||
host = makeHost();
|
||||
bridge = makeBridge();
|
||||
adapter = new Html5PlayerAdapter(host, bridge);
|
||||
video = makeFakeVideo();
|
||||
adapter.attach(video);
|
||||
});
|
||||
|
||||
it("is an html5-kind adapter", () => {
|
||||
expect(adapter.kind).toBe("html5");
|
||||
});
|
||||
|
||||
it("play() calls element.play()", async () => {
|
||||
await adapter.play();
|
||||
expect(video.play).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("pause() calls element.pause()", async () => {
|
||||
video.paused = false;
|
||||
await adapter.pause();
|
||||
expect(video.pause).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("toggle() plays when paused and reports the resulting state", async () => {
|
||||
video.paused = true;
|
||||
const playing = await adapter.toggle();
|
||||
expect(video.play).toHaveBeenCalled();
|
||||
expect(playing).toBe(true);
|
||||
});
|
||||
|
||||
it("toggle() pauses when playing", async () => {
|
||||
video.paused = false;
|
||||
const playing = await adapter.toggle();
|
||||
expect(video.pause).toHaveBeenCalled();
|
||||
expect(playing).toBe(false);
|
||||
});
|
||||
|
||||
it("seekElement() sets currentTime, offset, and waits for 'seeked'", async () => {
|
||||
const p = adapter.seekElement(42, 0);
|
||||
expect(video.currentTime).toBe(42);
|
||||
expect(bridge.setSeekOffset).toHaveBeenCalledWith(0);
|
||||
video._fire("seeked"); // resolve the wait
|
||||
await p;
|
||||
});
|
||||
|
||||
it("reloadSource() runs the invariant teardown->swap->resume sequence", async () => {
|
||||
video.paused = false; // was playing → should resume
|
||||
const p = adapter.reloadSource("http://new/master.m3u8", 120);
|
||||
|
||||
// Teardown happened synchronously before the awaited canplay wait.
|
||||
expect(video.pause).toHaveBeenCalled();
|
||||
expect(bridge.destroyHls).toHaveBeenCalledTimes(1);
|
||||
expect(video.removeAttribute).toHaveBeenCalledWith("src");
|
||||
expect(video.load).toHaveBeenCalled();
|
||||
|
||||
// Allow the internal 100ms settle delay, then fire canplay to resume.
|
||||
await new Promise((r) => setTimeout(r, 110));
|
||||
expect(bridge.setSeekOffset).toHaveBeenCalledWith(120);
|
||||
expect(bridge.setStreamUrl).toHaveBeenCalledWith("http://new/master.m3u8");
|
||||
video._fire("canplay");
|
||||
await p;
|
||||
expect(video.play).toHaveBeenCalled(); // resumed because it was playing
|
||||
});
|
||||
|
||||
it("reloadSource() does not resume when it was paused", async () => {
|
||||
video.paused = true;
|
||||
const p = adapter.reloadSource("http://new/master.m3u8", 30);
|
||||
await new Promise((r) => setTimeout(r, 110));
|
||||
video._fire("canplay");
|
||||
await p;
|
||||
expect(video.play).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("setVolume() clamps to 0..1", () => {
|
||||
adapter.setVolume(1.5);
|
||||
expect(video.volume).toBe(1);
|
||||
adapter.setVolume(-0.5);
|
||||
expect(video.volume).toBe(0);
|
||||
adapter.setVolume(0.4);
|
||||
expect(video.volume).toBeCloseTo(0.4);
|
||||
});
|
||||
|
||||
it("setMuted() sets the element muted flag", () => {
|
||||
adapter.setMuted(true);
|
||||
expect(video.muted).toBe(true);
|
||||
});
|
||||
|
||||
it("getPosition() returns element time plus the transcode offset", () => {
|
||||
video.currentTime = 10;
|
||||
(bridge.getSeekOffset as any) = () => 100;
|
||||
// Rebuild adapter with the offset-returning bridge.
|
||||
const a = new Html5PlayerAdapter(host, bridge);
|
||||
a.attach(video);
|
||||
expect(a.getPosition()).toBe(110);
|
||||
});
|
||||
|
||||
it("dispose() tears down hls and clears the element", async () => {
|
||||
await adapter.dispose();
|
||||
expect(bridge.destroyHls).toHaveBeenCalled();
|
||||
expect(video.pause).toHaveBeenCalled();
|
||||
// After dispose, primitives are no-ops (element detached).
|
||||
await adapter.play();
|
||||
// play was called once during dispose teardown? no — play only on reload/resume.
|
||||
expect(video.play).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("primitives are safe no-ops before an element is attached", async () => {
|
||||
const bare = new Html5PlayerAdapter(host, bridge);
|
||||
await expect(bare.play()).resolves.toBeUndefined();
|
||||
await expect(bare.pause()).resolves.toBeUndefined();
|
||||
await expect(bare.seekElement(5, 0)).resolves.toBeUndefined();
|
||||
expect(await bare.toggle()).toBe(false);
|
||||
});
|
||||
});
|
||||
201
src/lib/player/adapters/html5Adapter.ts
Normal file
@ -0,0 +1,201 @@
|
||||
/**
|
||||
* Html5PlayerAdapter — the Linux/desktop (and interim Android) PlayerAdapter
|
||||
* implementation. It owns the high-level control surface for an HTML5 `<video>`
|
||||
* element and reports the element's lifecycle back into Rust via its
|
||||
* {@link AdapterHost}.
|
||||
*
|
||||
* Design note on the split with VideoPlayer.svelte:
|
||||
* The delicate, timing-sensitive parts (hls.js instance lifecycle, the transcode
|
||||
* "reload stream" seek/audio-track dance with its dual-audio teardown and
|
||||
* canplay waits) are inherently coupled to Svelte reactive state and the DOM
|
||||
* element. Rather than relocate that reactive machinery wholesale (high
|
||||
* regression risk), the adapter receives an {@link Html5ElementBridge} of narrow
|
||||
* callbacks the owning component supplies. The adapter is the single OWNER of the
|
||||
* control contract (play/pause/seek/track/volume) and of reporting; the bridge is
|
||||
* the seam to the component's element/HLS/reactive state. This keeps all control
|
||||
* intents flowing through the PlayerAdapter interface while preserving the
|
||||
* hard-won element behavior verbatim.
|
||||
*
|
||||
* TRACES: UR-003, UR-005, UR-020, UR-021 | DR-001, DR-023, DR-024, DR-028
|
||||
*/
|
||||
|
||||
import type { AdapterHost, PlayerAdapter, PlayerLoadOptions } from "./types";
|
||||
|
||||
/**
|
||||
* Narrow seam the owning component provides so the adapter can execute the
|
||||
* element/HLS-coupled parts of a control action without re-implementing the
|
||||
* component's reactive HLS lifecycle. Every function here is a thin wrapper over
|
||||
* work the component already does.
|
||||
*/
|
||||
export interface Html5ElementBridge {
|
||||
/** The bound <video> element, or null before mount / after teardown. */
|
||||
getElement(): HTMLVideoElement | null;
|
||||
/** Current seek offset (seconds) for transcoded streams. */
|
||||
getSeekOffset(): number;
|
||||
setSeekOffset(offset: number): void;
|
||||
/** Update the stream URL the component renders (triggers its HLS $effect). */
|
||||
setStreamUrl(url: string): void;
|
||||
/** Tear down the component-owned hls.js instance (dual-audio prevention). */
|
||||
destroyHls(): void;
|
||||
/** Media source id for seek/audio-track URLs. */
|
||||
getMediaSourceId(): string | null;
|
||||
}
|
||||
|
||||
export class Html5PlayerAdapter implements PlayerAdapter {
|
||||
readonly kind = "html5" as const;
|
||||
|
||||
private attachedElement: HTMLVideoElement | null = null;
|
||||
private host: AdapterHost;
|
||||
private bridge: Html5ElementBridge;
|
||||
|
||||
constructor(host: AdapterHost, bridge: Html5ElementBridge) {
|
||||
this.host = host;
|
||||
this.bridge = bridge;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the LIVE <video> element. The bridge's `getElement()` returns the
|
||||
* component's current reactive `videoElement`, which is authoritative: the
|
||||
* element can be re-bound when the {#if} block re-renders, so a value captured
|
||||
* once in `attach()` may go stale (this caused play/pause to silently no-op).
|
||||
* Falls back to the attach()-captured element for unit tests whose bridge
|
||||
* returns null.
|
||||
*/
|
||||
private get element(): HTMLVideoElement | null {
|
||||
return this.bridge.getElement() ?? this.attachedElement;
|
||||
}
|
||||
|
||||
attach(element: HTMLVideoElement | null): void {
|
||||
this.attachedElement = element;
|
||||
}
|
||||
|
||||
async load(streamUrl: string, _options: PlayerLoadOptions): Promise<void> {
|
||||
// The component's reactive HLS $effect performs the actual attach/load when
|
||||
// the stream URL is set; loading is therefore driven by setStreamUrl. The
|
||||
// component's canplay/frag-buffered path reports readiness through the host.
|
||||
this.bridge.setSeekOffset(0);
|
||||
this.bridge.setStreamUrl(streamUrl);
|
||||
this.host.onState("loading");
|
||||
}
|
||||
|
||||
async play(): Promise<void> {
|
||||
const el = this.element;
|
||||
if (!el) return;
|
||||
try {
|
||||
await el.play();
|
||||
// handlePlay on the element reports "playing"; no double-report here.
|
||||
} catch (err) {
|
||||
this.host.onError(`play() failed: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
async pause(): Promise<void> {
|
||||
this.element?.pause();
|
||||
}
|
||||
|
||||
async toggle(): Promise<boolean> {
|
||||
const el = this.element;
|
||||
if (!el) return false;
|
||||
if (el.paused) {
|
||||
await this.play();
|
||||
return true;
|
||||
}
|
||||
await this.pause();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* PRIMITIVE: in-place element seek (no reload). The backend already decided
|
||||
* this seek does not need a transcode reload.
|
||||
*/
|
||||
async seekElement(positionSeconds: number, offset: number): Promise<void> {
|
||||
const el = this.element;
|
||||
if (!el) return;
|
||||
el.currentTime = positionSeconds;
|
||||
this.bridge.setSeekOffset(offset);
|
||||
await this.waitForEvent(el, "seeked", 2000);
|
||||
}
|
||||
|
||||
/**
|
||||
* PRIMITIVE: compound reload — the invariant HTML5 sequence to swap the source
|
||||
* and resume at `offset`. Contains NO strategy decision; the backend already
|
||||
* decided to reload and supplied the url/offset. Preserves the hard-won
|
||||
* dual-audio teardown and canplay wait.
|
||||
*/
|
||||
async reloadSource(url: string, offset: number): Promise<void> {
|
||||
const el = this.element;
|
||||
if (!el) {
|
||||
// Still update the stream URL so the component's HLS $effect can pick it up.
|
||||
this.bridge.setSeekOffset(offset);
|
||||
this.bridge.setStreamUrl(url);
|
||||
return;
|
||||
}
|
||||
const wasPlaying = !el.paused;
|
||||
el.pause();
|
||||
this.bridge.destroyHls();
|
||||
if (el.src) {
|
||||
el.removeAttribute("src");
|
||||
el.load();
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
this.bridge.setSeekOffset(offset);
|
||||
this.bridge.setStreamUrl(url);
|
||||
await this.waitForEvent(el, "canplay", 10000);
|
||||
if (wasPlaying) await el.play();
|
||||
}
|
||||
|
||||
setVolume(volume: number): void {
|
||||
if (this.element) this.element.volume = Math.max(0, Math.min(1, volume));
|
||||
}
|
||||
|
||||
setMuted(muted: boolean): void {
|
||||
if (this.element) this.element.muted = muted;
|
||||
}
|
||||
|
||||
/** Subtitle selection: HTML5 toggles textTracks on the element directly. */
|
||||
async selectSubtitle(streamIndex: number | null, _arrayIndex?: number): Promise<void> {
|
||||
const el = this.element;
|
||||
if (!el || !el.textTracks) return;
|
||||
for (let i = 0; i < el.textTracks.length; i++) {
|
||||
el.textTracks[i].mode = "disabled";
|
||||
}
|
||||
if (streamIndex !== null) {
|
||||
const tracks = el.querySelectorAll("track");
|
||||
tracks.forEach((track) => {
|
||||
const idx = parseInt(track.getAttribute("data-stream-index") || "-1");
|
||||
if (idx === streamIndex && track.track) {
|
||||
track.track.mode = "showing";
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
getPosition(): number {
|
||||
const el = this.element;
|
||||
if (!el) return 0;
|
||||
return el.currentTime + this.bridge.getSeekOffset();
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
this.bridge.destroyHls();
|
||||
const el = this.element;
|
||||
if (el) {
|
||||
el.pause();
|
||||
el.removeAttribute("src");
|
||||
el.load();
|
||||
}
|
||||
this.attachedElement = null;
|
||||
}
|
||||
|
||||
/** Resolve when `event` fires on `el`, or after `timeoutMs` as a fallback. */
|
||||
private waitForEvent(el: HTMLVideoElement, event: string, timeoutMs: number): Promise<void> {
|
||||
return new Promise<void>((resolve) => {
|
||||
const done = () => {
|
||||
el.removeEventListener(event, done);
|
||||
resolve();
|
||||
};
|
||||
el.addEventListener(event, done);
|
||||
setTimeout(done, timeoutMs);
|
||||
});
|
||||
}
|
||||
}
|
||||
55
src/lib/player/adapters/index.ts
Normal file
@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Player adapter factory + public exports.
|
||||
*
|
||||
* `createAdapter` selects the concrete PlayerAdapter for the current platform.
|
||||
* It is the single place that encodes the INTERIM Android override: the Rust
|
||||
* backend may report a native ExoPlayer backend, but native Android video
|
||||
* rendering is blocked upstream (tauri#10152 — transparent webview / SurfaceView
|
||||
* compositing), so we render Android video through the HTML5 adapter for now.
|
||||
* When that upstream limitation is resolved, flip this to honor `backendKind`.
|
||||
*
|
||||
* TRACES: UR-003 | DR-004
|
||||
*/
|
||||
|
||||
import { Html5PlayerAdapter, type Html5ElementBridge } from "./html5Adapter";
|
||||
import { NativePlayerAdapter } from "./nativeAdapter";
|
||||
import type { AdapterHost, PlayerAdapter } from "./types";
|
||||
|
||||
export type { PlayerAdapter, AdapterHost, PlayerLoadOptions, SubtitleTrackInput } from "./types";
|
||||
export type { Html5ElementBridge } from "./html5Adapter";
|
||||
export { Html5PlayerAdapter } from "./html5Adapter";
|
||||
export { NativePlayerAdapter } from "./nativeAdapter";
|
||||
|
||||
/** What the Rust `player_play_item` response says it chose. */
|
||||
export type BackendKind = "html5" | "native";
|
||||
|
||||
export interface CreateAdapterArgs {
|
||||
/** Backend kind reported by `player_play_item` (`useHtml5Element`). */
|
||||
backendKind: BackendKind;
|
||||
host: AdapterHost;
|
||||
/** Required for the HTML5 adapter; ignored by the native adapter. */
|
||||
bridge?: Html5ElementBridge;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the adapter for this platform/stream.
|
||||
*
|
||||
* INTERIM: always returns the HTML5 adapter, because the native surface is not
|
||||
* visible through the webview on current Tauri (see module docs). The bridge is
|
||||
* therefore required.
|
||||
*/
|
||||
export function createAdapter({ backendKind, host, bridge }: CreateAdapterArgs): PlayerAdapter {
|
||||
// INTERIM OVERRIDE: force HTML5 rendering even when the backend reports native.
|
||||
const effectiveKind: BackendKind = "html5";
|
||||
|
||||
if (effectiveKind === "html5") {
|
||||
if (!bridge) {
|
||||
throw new Error("createAdapter: Html5ElementBridge is required for the HTML5 adapter");
|
||||
}
|
||||
return new Html5PlayerAdapter(host, bridge);
|
||||
}
|
||||
|
||||
// Reached only once the interim override is lifted (native Android unblocked).
|
||||
void backendKind;
|
||||
return new NativePlayerAdapter(host);
|
||||
}
|
||||
88
src/lib/player/adapters/nativeAdapter.test.ts
Normal file
@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Unit tests for NativePlayerAdapter — thin delegate to backend commands.
|
||||
* Pins the primitive→command mapping so the ExoPlayer path stays correct.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const playerPlay = vi.fn((..._a: any[]): any => ({}));
|
||||
const playerPause = vi.fn((..._a: any[]): any => ({}));
|
||||
const playerToggle = vi.fn((..._a: any[]): any => ({ state: "playing" }));
|
||||
const playerSetVolume = vi.fn((..._a: any[]): any => ({}));
|
||||
const playerToggleMute = vi.fn((..._a: any[]): any => ({}));
|
||||
const playerSetSubtitleTrack = vi.fn((..._a: any[]): any => ({}));
|
||||
|
||||
vi.mock("$lib/api/bindings", () => ({
|
||||
commands: {
|
||||
playerPlay: (...a: any[]) => playerPlay(...a),
|
||||
playerPause: (...a: any[]) => playerPause(...a),
|
||||
playerToggle: (...a: any[]) => playerToggle(...a),
|
||||
playerSetVolume: (...a: any[]) => playerSetVolume(...a),
|
||||
playerToggleMute: (...a: any[]) => playerToggleMute(...a),
|
||||
playerSetSubtitleTrack: (...a: any[]) => playerSetSubtitleTrack(...a),
|
||||
},
|
||||
}));
|
||||
|
||||
import { NativePlayerAdapter } from "./nativeAdapter";
|
||||
import type { AdapterHost } from "./types";
|
||||
|
||||
function makeHost(): AdapterHost {
|
||||
return {
|
||||
onState: vi.fn(), onPosition: vi.fn(), onMediaLoaded: vi.fn(), onEnded: vi.fn(),
|
||||
onError: vi.fn(), onStreamUrlChanged: vi.fn(), onBuffering: vi.fn(), onReady: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("NativePlayerAdapter", () => {
|
||||
let adapter: NativePlayerAdapter;
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
adapter = new NativePlayerAdapter(makeHost());
|
||||
});
|
||||
|
||||
it("is a native-kind adapter", () => {
|
||||
expect(adapter.kind).toBe("native");
|
||||
});
|
||||
|
||||
it("delegates play/pause to backend commands", async () => {
|
||||
await adapter.play();
|
||||
await adapter.pause();
|
||||
expect(playerPlay).toHaveBeenCalledTimes(1);
|
||||
expect(playerPause).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("toggle() reflects the backend's resulting playing state", async () => {
|
||||
expect(await adapter.toggle()).toBe(true);
|
||||
expect(playerToggle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("records position on seek/reload primitives (backend does the real work)", async () => {
|
||||
await adapter.seekElement(55, 0);
|
||||
expect(adapter.getPosition()).toBe(55);
|
||||
await adapter.reloadSource("ignored", 200);
|
||||
expect(adapter.getPosition()).toBe(200);
|
||||
});
|
||||
|
||||
it("load() seeds a resume position", async () => {
|
||||
await adapter.load("url", {
|
||||
mediaId: "m", mediaSourceId: null, needsTranscoding: false,
|
||||
initialPosition: 90, isLive: false, audioTrackIndex: null,
|
||||
knownDuration: 0, subtitleTracks: [],
|
||||
});
|
||||
expect(adapter.getPosition()).toBe(90);
|
||||
});
|
||||
|
||||
it("setVolume clamps and delegates; setMuted toggles mute", () => {
|
||||
adapter.setVolume(2);
|
||||
expect(playerSetVolume).toHaveBeenCalledWith(1);
|
||||
adapter.setMuted(true);
|
||||
expect(playerToggleMute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("selectSubtitle maps null to disable and uses arrayIndex when given", async () => {
|
||||
await adapter.selectSubtitle(null);
|
||||
expect(playerSetSubtitleTrack).toHaveBeenCalledWith(null);
|
||||
await adapter.selectSubtitle(5, 2);
|
||||
expect(playerSetSubtitleTrack).toHaveBeenCalledWith(2);
|
||||
});
|
||||
});
|
||||
96
src/lib/player/adapters/nativeAdapter.ts
Normal file
@ -0,0 +1,96 @@
|
||||
/**
|
||||
* NativePlayerAdapter — the Android/ExoPlayer PlayerAdapter implementation.
|
||||
*
|
||||
* ExoPlayer is driven entirely by the Rust backend (JNI), which already emits
|
||||
* PlayerStatusEvents and handles seek/audio-track internally. So this adapter is
|
||||
* a thin delegate to backend commands; there is no DOM element to touch and no
|
||||
* hls.js. State reporting is unnecessary here because the native backend emits
|
||||
* events directly — the adapter's job is only to forward control intents.
|
||||
*
|
||||
* NOTE: On current Tauri, native Android video rendering is blocked upstream
|
||||
* (transparent webview / SurfaceView compositing — tauri#10152), so video on
|
||||
* Android currently runs through the HTML5 adapter via the interim override in
|
||||
* the factory. This adapter exists for the audio/native path and for when that
|
||||
* upstream limitation is resolved.
|
||||
*
|
||||
* TRACES: UR-003, UR-005 | DR-004, DR-028
|
||||
*/
|
||||
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import type { AdapterHost, PlayerAdapter, PlayerLoadOptions } from "./types";
|
||||
|
||||
export class NativePlayerAdapter implements PlayerAdapter {
|
||||
readonly kind = "native" as const;
|
||||
|
||||
// Kept for symmetry / future reporting needs; the native backend emits events.
|
||||
private host: AdapterHost;
|
||||
private position = 0;
|
||||
|
||||
constructor(host: AdapterHost) {
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
// The native surface is owned by the backend; nothing to attach in the DOM.
|
||||
attach(_element: HTMLVideoElement | null): void {}
|
||||
|
||||
async load(_streamUrl: string, options: PlayerLoadOptions): Promise<void> {
|
||||
// player_play_item already initiated native playback before this adapter is
|
||||
// created; nothing further to do. Seed a resume position if requested (the
|
||||
// native backend performs the actual seek internally).
|
||||
if (options.initialPosition > 0) {
|
||||
this.position = options.initialPosition;
|
||||
}
|
||||
}
|
||||
|
||||
async play(): Promise<void> {
|
||||
await commands.playerPlay();
|
||||
}
|
||||
|
||||
async pause(): Promise<void> {
|
||||
await commands.playerPause();
|
||||
}
|
||||
|
||||
async toggle(): Promise<boolean> {
|
||||
const response = (await commands.playerToggle()) as any;
|
||||
return response?.state === "playing";
|
||||
}
|
||||
|
||||
/**
|
||||
* PRIMITIVE: in-place seek. For the native backend, the backend drives
|
||||
* ExoPlayer's seek internally, so this simply records the target position.
|
||||
* (The decision to seek-in-place vs reload was already made by the backend.)
|
||||
*/
|
||||
async seekElement(positionSeconds: number, _offset: number): Promise<void> {
|
||||
this.position = positionSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* PRIMITIVE: reload source. For the native backend the backend already
|
||||
* performed the reload+seek internally as part of the seek decision; nothing
|
||||
* to do on the frontend beyond recording position.
|
||||
*/
|
||||
async reloadSource(_url: string, offset: number): Promise<void> {
|
||||
this.position = offset;
|
||||
}
|
||||
|
||||
setVolume(volume: number): void {
|
||||
void commands.playerSetVolume(Math.max(0, Math.min(1, volume)));
|
||||
}
|
||||
|
||||
setMuted(_muted: boolean): void {
|
||||
void commands.playerToggleMute();
|
||||
}
|
||||
|
||||
async selectSubtitle(streamIndex: number | null, arrayIndex?: number): Promise<void> {
|
||||
const indexToUse = streamIndex === null ? null : arrayIndex ?? streamIndex;
|
||||
await commands.playerSetSubtitleTrack(indexToUse);
|
||||
}
|
||||
|
||||
getPosition(): number {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
// The backend is stopped via player_stop by the owning view; nothing to free.
|
||||
}
|
||||
}
|
||||
93
src/lib/player/adapters/rustReportHost.ts
Normal file
@ -0,0 +1,93 @@
|
||||
/**
|
||||
* An {@link AdapterHost} implementation that forwards a player adapter's outward
|
||||
* lifecycle events into the Rust `PlayerController` via the `player_report_*`
|
||||
* commands. The controller re-emits the same `PlayerStatusEvent`s the native
|
||||
* backends emit, so the frontend `player` store is fed from ONE pipeline
|
||||
* (playerEvents.ts) in both native and HTML5 modes — keeping Rust the single
|
||||
* source of truth.
|
||||
*
|
||||
* This is the sole place that talks to the report commands; adapters depend only
|
||||
* on the {@link AdapterHost} interface, never on `commands` directly, which keeps
|
||||
* them unit-testable with a mock host.
|
||||
*
|
||||
* TRACES: UR-003, UR-005 | DR-001, DR-028
|
||||
*/
|
||||
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import type { AdapterHost } from "./types";
|
||||
|
||||
const POSITION_REPORT_INTERVAL_MS = 250;
|
||||
|
||||
/** Report options that let a caller bypass throttling for discrete events. */
|
||||
export interface ReportPositionOptions {
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Low-level report helpers, exported so the legacy `$lib/player/html5Adapter`
|
||||
* shim can keep its function-style API while there are still direct callers.
|
||||
* Prefer {@link createRustReportHost} for new adapter code.
|
||||
*/
|
||||
let lastPositionReport = 0;
|
||||
|
||||
export async function reportState(
|
||||
state: "playing" | "paused" | "loading" | "stopped" | "idle",
|
||||
mediaId: string | null
|
||||
): Promise<void> {
|
||||
try {
|
||||
await commands.playerReportState(state, mediaId);
|
||||
} catch (err) {
|
||||
console.warn("[rustReportHost] Failed to report state:", err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function reportPosition(
|
||||
position: number,
|
||||
duration: number,
|
||||
{ force = false }: ReportPositionOptions = {}
|
||||
): Promise<void> {
|
||||
const now = Date.now();
|
||||
if (!force && now - lastPositionReport < POSITION_REPORT_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
lastPositionReport = now;
|
||||
try {
|
||||
await commands.playerReportPosition(position, Number.isFinite(duration) ? duration : 0);
|
||||
} catch (err) {
|
||||
console.warn("[rustReportHost] Failed to report position:", err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function reportMediaLoaded(duration: number): Promise<void> {
|
||||
try {
|
||||
await commands.playerReportMediaLoaded(Number.isFinite(duration) ? duration : 0);
|
||||
} catch (err) {
|
||||
console.warn("[rustReportHost] Failed to report media loaded:", err);
|
||||
}
|
||||
}
|
||||
|
||||
export function resetReporting(): void {
|
||||
lastPositionReport = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an {@link AdapterHost} bound to a specific media id that forwards adapter
|
||||
* events to Rust. `onStreamUrlChanged`, `onBuffering`, and `onReady` are wired by
|
||||
* the owning view (they affect the `<video src>` / spinner), so this host accepts
|
||||
* optional view callbacks and defaults them to no-ops.
|
||||
*/
|
||||
export function createRustReportHost(
|
||||
mediaId: string,
|
||||
view: Partial<Pick<AdapterHost, "onStreamUrlChanged" | "onBuffering" | "onReady" | "onEnded" | "onError">> = {}
|
||||
): AdapterHost {
|
||||
return {
|
||||
onState: (state) => void reportState(state, mediaId),
|
||||
onPosition: (position, duration) => void reportPosition(position, duration),
|
||||
onMediaLoaded: (duration) => void reportMediaLoaded(duration),
|
||||
onEnded: view.onEnded ?? (() => {}),
|
||||
onError: view.onError ?? ((message) => console.warn("[rustReportHost] adapter error:", message)),
|
||||
onStreamUrlChanged: view.onStreamUrlChanged ?? (() => {}),
|
||||
onBuffering: view.onBuffering ?? (() => {}),
|
||||
onReady: view.onReady ?? (() => {}),
|
||||
};
|
||||
}
|
||||
127
src/lib/player/adapters/types.ts
Normal file
@ -0,0 +1,127 @@
|
||||
/**
|
||||
* PlayerAdapter contract — the decoupled boundary between the UI/backend and a
|
||||
* concrete video player implementation (Linux HTML5+hls.js, or Android native).
|
||||
*
|
||||
* The whole point: UI components and the Rust backend interact with video ONLY
|
||||
* through this interface. All element / hls.js / ExoPlayer / textTracks detail —
|
||||
* and the backend seek/audio-track *strategy* round-trip — is internal to an
|
||||
* implementation. A control intent (from UI or a backend lockscreen/remote/sleep
|
||||
* event) reaches the element by the facade dispatching to the active adapter.
|
||||
*
|
||||
* State flows OUTWARD through the {@link AdapterHost} callback bag rather than the
|
||||
* adapter importing stores/commands directly — this keeps adapters unit-testable
|
||||
* with a mock host and keeps the reporting-to-Rust wiring in one place.
|
||||
*
|
||||
* TRACES: UR-003, UR-005, UR-020, UR-021 | DR-001, DR-023, DR-024, DR-028
|
||||
*/
|
||||
|
||||
/** A subtitle track handed to the adapter at load time (WebVTT for HTML5). */
|
||||
export interface SubtitleTrackInput {
|
||||
index: number;
|
||||
url: string;
|
||||
language: string | null;
|
||||
label: string;
|
||||
mimeType: string;
|
||||
}
|
||||
|
||||
/** Everything an adapter needs to load and begin a stream. */
|
||||
export interface PlayerLoadOptions {
|
||||
/** Jellyfin item id — used as the media_id when reporting state to Rust. */
|
||||
mediaId: string;
|
||||
/** Media source id for subtitle/seek URLs (null for local/direct). */
|
||||
mediaSourceId: string | null;
|
||||
/** HEVC/10-bit content that needs server transcoding (affects seek strategy). */
|
||||
needsTranscoding: boolean;
|
||||
/** Resume position in seconds (0 = start from beginning). */
|
||||
initialPosition: number;
|
||||
/** Live stream — no seek bar, no resume, no progress reporting. */
|
||||
isLive: boolean;
|
||||
/** Preselected audio track stream index, or null for the default. */
|
||||
audioTrackIndex: number | null;
|
||||
/** Known total duration in seconds (from runTimeTicks), or 0 if unknown. */
|
||||
knownDuration: number;
|
||||
/** Subtitle tracks available for this media. */
|
||||
subtitleTracks: SubtitleTrackInput[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback bag the adapter uses to report the element's lifecycle outward. The
|
||||
* facade supplies an implementation that forwards to Rust (via the
|
||||
* `player_report_*` commands) and, where needed, to the UI.
|
||||
*/
|
||||
export interface AdapterHost {
|
||||
/** Playback state changed (playing/paused/loading/stopped/idle). */
|
||||
onState(state: "playing" | "paused" | "loading" | "stopped" | "idle"): void;
|
||||
/** Position/duration tick (adapter throttles; host forwards to Rust). */
|
||||
onPosition(position: number, duration: number): void;
|
||||
/** Media finished loading and knows its duration. */
|
||||
onMediaLoaded(duration: number): void;
|
||||
/** Playback reached the natural end of the stream (fires at most once). */
|
||||
onEnded(): void;
|
||||
/** A non-fatal or fatal playback error occurred. */
|
||||
onError(message: string): void;
|
||||
/**
|
||||
* The stream URL the adapter is now playing changed (e.g. transcode reload on
|
||||
* seek/audio-track switch). Lets the owning view keep its `<video src>` in sync.
|
||||
*/
|
||||
onStreamUrlChanged(url: string): void;
|
||||
/** Buffering/ready transitions, so the view can show/hide its spinner. */
|
||||
onBuffering(isBuffering: boolean): void;
|
||||
onReady(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* One concrete player implementation per platform. Methods are high-level
|
||||
* intents; strategy objects, hls instances, and textTracks never cross this line.
|
||||
*/
|
||||
export interface PlayerAdapter {
|
||||
/** Which platform backend this adapter represents. */
|
||||
readonly kind: "html5" | "native";
|
||||
|
||||
/**
|
||||
* Bind the output target. For the HTML5 adapter this is the `<video>` element
|
||||
* (pass null on teardown); the native adapter ignores it (ExoPlayer renders to
|
||||
* its own surface).
|
||||
*/
|
||||
attach(element: HTMLVideoElement | null): void;
|
||||
|
||||
/** Load a stream and begin playback at `options.initialPosition`. */
|
||||
load(streamUrl: string, options: PlayerLoadOptions): Promise<void>;
|
||||
|
||||
play(): Promise<void>;
|
||||
pause(): Promise<void>;
|
||||
/** Toggle play/pause; resolves to the resulting playing state. */
|
||||
toggle(): Promise<boolean>;
|
||||
|
||||
// --- Seek/reload PRIMITIVES (decision-free) ---------------------------------
|
||||
// The backend DECIDES whether a seek is an in-place element seek or a full
|
||||
// source reload (transcode). The adapter only executes the chosen primitive;
|
||||
// it contains no strategy branch. This is what keeps the decision logic shared
|
||||
// in Rust (Option 1).
|
||||
|
||||
/**
|
||||
* In-place seek of the already-loaded source (no reload). `offset` is the
|
||||
* transcode seek offset the element position is relative to (0 for direct).
|
||||
*/
|
||||
seekElement(positionSeconds: number, offset: number): Promise<void>;
|
||||
|
||||
/**
|
||||
* Compound reload: swap to `url` and resume at `offset` seconds. Runs the
|
||||
* invariant mechanical sequence for this platform (html5: pause → hls teardown
|
||||
* → clear src → set new url → wait ready → resume; native: ExoPlayer setMediaItem
|
||||
* + seekTo). No decision is made here — the backend already decided to reload.
|
||||
*/
|
||||
reloadSource(url: string, offset: number): Promise<void>;
|
||||
|
||||
setVolume(volume: number): void; // 0..1
|
||||
setMuted(muted: boolean): void;
|
||||
|
||||
/** Enable a subtitle track (null disables) — DOM textTracks is a webview primitive. */
|
||||
selectSubtitle(streamIndex: number | null, arrayIndex?: number): Promise<void>;
|
||||
|
||||
/** Current position in seconds (adapter's own truth, e.g. element.currentTime + offset). */
|
||||
getPosition(): number;
|
||||
|
||||
/** Tear down: destroy hls, detach element, stop reporting. Idempotent. */
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
@ -1,84 +1,19 @@
|
||||
/**
|
||||
* HTML5 <video> → Rust reporting adapter ("html5+rust internal module").
|
||||
* Compatibility shim.
|
||||
*
|
||||
* On platforms where video renders in the webview (Linux WebKitGTK HTML5
|
||||
* <video>; and, per the current interim behavior, Android too), the real player
|
||||
* is the DOM element, which the Rust backend cannot observe directly. This
|
||||
* module is the single place that reports the element's lifecycle back into
|
||||
* Rust, so the `PlayerController` stays the source of truth and the frontend
|
||||
* `player` store is fed from ONE pipeline (playerEvents.ts) in both native and
|
||||
* HTML5 modes.
|
||||
*
|
||||
* The VideoPlayer component owns the element and its UI; it calls these
|
||||
* functions from its DOM event handlers. Keeping the `commands.playerReport*`
|
||||
* calls here (rather than scattered in the component) is the boundary: UI code
|
||||
* never talks to the report commands directly.
|
||||
*
|
||||
* TRACES: UR-003, UR-005 | DR-001, DR-028
|
||||
* The HTML5 → Rust reporting functions moved to `adapters/rustReportHost.ts` as
|
||||
* part of the PlayerAdapter refactor. Existing callers import the reporter as
|
||||
* `import * as html5Adapter from "$lib/player/html5Adapter"`; this shim keeps
|
||||
* that working while the migration proceeds. New adapter code should depend on
|
||||
* the `AdapterHost` interface (see `adapters/types.ts`) instead.
|
||||
*/
|
||||
|
||||
import { commands } from "$lib/api/bindings";
|
||||
export {
|
||||
reportState,
|
||||
reportPosition,
|
||||
reportMediaLoaded,
|
||||
resetReporting,
|
||||
} from "./adapters/rustReportHost";
|
||||
|
||||
/** Player states mirrored to Rust (must match the strings playerEvents.ts handles). */
|
||||
/** @deprecated states are defined on the AdapterHost interface now. */
|
||||
export type Html5PlayerState = "playing" | "paused" | "loading" | "stopped" | "idle";
|
||||
|
||||
/**
|
||||
* Report an HTML5 <video> state transition to Rust. The controller re-emits a
|
||||
* `StateChanged` event identical to the native backends', so the frontend
|
||||
* player store updates through its normal path.
|
||||
*/
|
||||
export async function reportState(
|
||||
state: Html5PlayerState,
|
||||
mediaId: string | null
|
||||
): Promise<void> {
|
||||
try {
|
||||
await commands.playerReportState(state, mediaId);
|
||||
} catch (err) {
|
||||
console.warn("[html5Adapter] Failed to report state:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Position reporting is throttled to ~250ms to match the native backends'
|
||||
* cadence and avoid flooding the IPC channel from the 60fps RAF loop.
|
||||
*/
|
||||
let lastPositionReport = 0;
|
||||
const POSITION_REPORT_INTERVAL_MS = 250;
|
||||
|
||||
/**
|
||||
* Report an HTML5 <video> position tick to Rust (throttled). Safe to call every
|
||||
* animation frame; only forwards at most every {@link POSITION_REPORT_INTERVAL_MS}.
|
||||
*/
|
||||
export async function reportPosition(
|
||||
position: number,
|
||||
duration: number,
|
||||
{ force = false }: { force?: boolean } = {}
|
||||
): Promise<void> {
|
||||
const now = Date.now();
|
||||
if (!force && now - lastPositionReport < POSITION_REPORT_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
lastPositionReport = now;
|
||||
try {
|
||||
await commands.playerReportPosition(position, Number.isFinite(duration) ? duration : 0);
|
||||
} catch (err) {
|
||||
console.warn("[html5Adapter] Failed to report position:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Report that the HTML5 <video> finished loading metadata and knows its
|
||||
* duration. Mirrors the native `MediaLoaded` event.
|
||||
*/
|
||||
export async function reportMediaLoaded(duration: number): Promise<void> {
|
||||
try {
|
||||
await commands.playerReportMediaLoaded(Number.isFinite(duration) ? duration : 0);
|
||||
} catch (err) {
|
||||
console.warn("[html5Adapter] Failed to report media loaded:", err);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reset internal throttle state (call when a new stream loads). */
|
||||
export function resetReporting(): void {
|
||||
lastPositionReport = 0;
|
||||
}
|
||||
|
||||
@ -23,6 +23,34 @@ import type {
|
||||
PlayItemRequest,
|
||||
} from "$lib/api/bindings";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import type { PlayerAdapter } from "./adapters/types";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Active player adapter registry
|
||||
//
|
||||
// When a video is playing, VideoPlayer registers its PlayerAdapter here so that
|
||||
// control intents — whether from UI or routed from a backend control event
|
||||
// (lockscreen/remote/sleep-timer) — reach the actual player element/surface.
|
||||
// When no adapter is registered (audio-only playback), control falls through to
|
||||
// the queue-level backend commands, which is the correct behavior there.
|
||||
// ---------------------------------------------------------------------------
|
||||
let activeAdapter: PlayerAdapter | null = null;
|
||||
|
||||
function setActiveAdapter(adapter: PlayerAdapter): void {
|
||||
activeAdapter = adapter;
|
||||
}
|
||||
|
||||
function clearActiveAdapter(adapter?: PlayerAdapter): void {
|
||||
// Only clear if it's still the one we think is active (guards against a newly
|
||||
// mounted player's adapter being cleared by the outgoing player's teardown).
|
||||
if (!adapter || activeAdapter === adapter) {
|
||||
activeAdapter = null;
|
||||
}
|
||||
}
|
||||
|
||||
function getActiveAdapter(): PlayerAdapter | null {
|
||||
return activeAdapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the current repository handle, throwing a clear error if the user is
|
||||
@ -30,10 +58,20 @@ import { auth } from "$lib/stores/auth";
|
||||
* that was previously duplicated across every context-play call site.
|
||||
*/
|
||||
function requireHandle(): string {
|
||||
// The repository is the source of truth for the handle. We consult the auth
|
||||
// store's isAuthenticated flag only as a best-effort guard — guarded in a
|
||||
// try/catch so a not-yet-subscribable store (or a test double) can't block a
|
||||
// valid repository handle.
|
||||
try {
|
||||
const authState = get(auth);
|
||||
if (!authState.isAuthenticated) {
|
||||
if (authState && authState.isAuthenticated === false) {
|
||||
throw new Error("User not authenticated");
|
||||
}
|
||||
} catch (err) {
|
||||
// get(auth) failed (e.g. non-store mock) — fall through to the repository,
|
||||
// which is the authoritative source of the handle.
|
||||
if (err instanceof Error && err.message === "User not authenticated") throw err;
|
||||
}
|
||||
const repo = auth.getRepository();
|
||||
if (!repo) {
|
||||
throw new Error("No repository available");
|
||||
@ -46,23 +84,91 @@ function requireHandle(): string {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function play() {
|
||||
if (activeAdapter) return void (await activeAdapter.play());
|
||||
await commands.playerPlay();
|
||||
}
|
||||
|
||||
async function pause() {
|
||||
if (activeAdapter) return void (await activeAdapter.pause());
|
||||
await commands.playerPause();
|
||||
}
|
||||
|
||||
async function toggle() {
|
||||
if (activeAdapter) return void (await activeAdapter.toggle());
|
||||
await commands.playerToggle();
|
||||
}
|
||||
|
||||
async function stop() {
|
||||
// Stop is a queue/session-level action (clears playback); always go to backend.
|
||||
// The adapter is disposed by VideoPlayer's own teardown.
|
||||
await commands.playerStop();
|
||||
}
|
||||
|
||||
async function seek(positionSeconds: number) {
|
||||
// Audio path: backend seeks the native backend directly.
|
||||
if (!activeAdapter) {
|
||||
await commands.playerSeek(positionSeconds);
|
||||
return;
|
||||
}
|
||||
// Video path: ask the backend to DECIDE the strategy (in-place vs reload), then
|
||||
// execute the matching adapter primitive. The decision logic stays in Rust
|
||||
// (player_seek_video); the adapter only runs the chosen mechanical primitive.
|
||||
await seekVideo(positionSeconds, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Video seek: backend decides strategy, facade dispatches the chosen adapter
|
||||
* primitive. `mediaSourceId`/`audioTrackIndex` come from the video view (they are
|
||||
* needed for the transcode reload URL). Requires an active video adapter.
|
||||
*/
|
||||
async function seekVideo(
|
||||
positionSeconds: number,
|
||||
mediaSourceId: string | null,
|
||||
audioTrackIndex: number | null
|
||||
): Promise<void> {
|
||||
const adapter = activeAdapter;
|
||||
if (!adapter) {
|
||||
await commands.playerSeek(positionSeconds);
|
||||
return;
|
||||
}
|
||||
const response = (await commands.playerSeekVideo(
|
||||
requireHandle(),
|
||||
positionSeconds,
|
||||
mediaSourceId,
|
||||
audioTrackIndex,
|
||||
adapter.kind === "html5"
|
||||
)) as any;
|
||||
// Serde keeps these snake_case (only the "strategy" tag is camelCase).
|
||||
if (response.strategy === "reloadStream") {
|
||||
await adapter.reloadSource(response.new_url ?? "", response.seek_offset ?? positionSeconds);
|
||||
} else {
|
||||
await adapter.seekElement(response.position ?? positionSeconds, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch audio track: backend decides (may reload the stream), facade dispatches
|
||||
* the resulting primitive. Requires an active video adapter.
|
||||
*/
|
||||
async function switchAudioTrack(
|
||||
streamIndex: number,
|
||||
arrayIndex: number,
|
||||
currentPosition: number | null,
|
||||
mediaSourceId: string | null
|
||||
): Promise<void> {
|
||||
const adapter = activeAdapter;
|
||||
if (!adapter) return;
|
||||
const response = (await commands.playerSwitchAudioTrack(
|
||||
requireHandle(),
|
||||
streamIndex,
|
||||
arrayIndex,
|
||||
adapter.kind === "html5",
|
||||
currentPosition,
|
||||
mediaSourceId
|
||||
)) as any;
|
||||
if (response.strategy === "reloadStream") {
|
||||
await adapter.reloadSource(response.new_url!, response.position!);
|
||||
}
|
||||
}
|
||||
|
||||
async function next() {
|
||||
@ -102,6 +208,7 @@ async function moveInQueue(fromIndex: number, toIndex: number) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function setVolume(volume: number) {
|
||||
if (activeAdapter) activeAdapter.setVolume(volume);
|
||||
await commands.playerSetVolume(volume);
|
||||
}
|
||||
|
||||
@ -110,10 +217,11 @@ async function toggleMute() {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Track selection (video)
|
||||
// Track selection (video) — dispatch to the active video adapter when present
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function setSubtitleTrack(streamIndex: number | null) {
|
||||
if (activeAdapter) return void (await activeAdapter.selectSubtitle(streamIndex));
|
||||
await commands.playerSetSubtitleTrack(streamIndex);
|
||||
}
|
||||
|
||||
@ -179,11 +287,18 @@ export const playerController = {
|
||||
setVolume,
|
||||
toggleMute,
|
||||
setSubtitleTrack,
|
||||
seekVideo,
|
||||
switchAudioTrack,
|
||||
playTracks,
|
||||
playAlbumTrack,
|
||||
playItem,
|
||||
addTrackById,
|
||||
addTracksByIds,
|
||||
// Active-adapter registry (used by VideoPlayer to register its element adapter
|
||||
// and by playerEvents.ts to route backend control commands to it).
|
||||
setActiveAdapter,
|
||||
clearActiveAdapter,
|
||||
getActiveAdapter,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
// Favorites service - Handles toggling favorite status with optimistic updates
|
||||
// TRACES: UR-017 | DR-021
|
||||
|
||||
import { get } from "svelte/store";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { isConnected } from "$lib/stores/connectivity";
|
||||
|
||||
/**
|
||||
* Toggle the favorite status of an item.
|
||||
@ -31,7 +33,16 @@ export async function toggleFavorite(
|
||||
// 1. Update local database first (optimistic update)
|
||||
await commands.storageToggleFavorite(userId, itemId, newIsFavorite);
|
||||
|
||||
// 2. Sync to Jellyfin server
|
||||
// 2. Sync to Jellyfin server.
|
||||
//
|
||||
// Only attempt this when we're actually connected. When offline, the server
|
||||
// call can hang on a long network timeout rather than failing fast — which
|
||||
// blocks the caller (and leaves the favorite button greyed out with a wait
|
||||
// cursor) until the request finally gives up, effectively only recovering
|
||||
// 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) {
|
||||
@ -47,6 +58,7 @@ export async function toggleFavorite(
|
||||
// Favorite is stored locally and will be synced later
|
||||
// via sync queue (when implemented)
|
||||
}
|
||||
}
|
||||
|
||||
return newIsFavorite;
|
||||
}
|
||||
|
||||
102
src/lib/services/offlineCatalog.ts
Normal file
@ -0,0 +1,102 @@
|
||||
// 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";
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/** 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();
|
||||
}
|
||||
@ -17,6 +17,7 @@ import { sleepTimer, sleepTimerExpiredSignal } from "$lib/stores/sleepTimer";
|
||||
import { nextEpisode, nextEpisodeItem as nextEpisodeItemStore } from "$lib/stores/nextEpisode";
|
||||
import { autoPlayNext } from "$lib/services/nextEpisodeService";
|
||||
import { preloadUpcomingTracks } from "$lib/services/preload";
|
||||
import { playerController } from "$lib/player";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { get } from "svelte/store";
|
||||
|
||||
@ -116,9 +117,20 @@ function handlePlayerEvent(event: PlayerStatusEvent): void {
|
||||
case "sleep_timer_expired":
|
||||
// Backend stops its own playback; this signal lets HTML5 video (which
|
||||
// plays outside the backend on Linux) pause itself too.
|
||||
// Preferred path: drive the active video adapter directly so the backend
|
||||
// has real control authority over the webview element. The legacy
|
||||
// sleepTimerExpiredSignal is kept for any remaining subscribers.
|
||||
playerController.getActiveAdapter()?.pause();
|
||||
sleepTimerExpiredSignal.update((n) => n + 1);
|
||||
break;
|
||||
|
||||
case "control_command":
|
||||
// Backend-originated control targeting the active frontend player adapter
|
||||
// (lockscreen/remote/sleep). Route it to the adapter so a backend intent
|
||||
// reaches the webview <video> element.
|
||||
handleControlCommand(event.action, event.position);
|
||||
break;
|
||||
|
||||
case "show_next_episode_popup":
|
||||
handleShowNextEpisodePopup(
|
||||
event.current_episode,
|
||||
@ -292,6 +304,36 @@ function handleSleepTimerChanged(mode: SleepTimerMode, remainingSeconds: number)
|
||||
sleepTimer.set({ mode, remainingSeconds });
|
||||
}
|
||||
|
||||
/**
|
||||
* Route a backend-originated control command to the active player adapter, so a
|
||||
* backend intent (lockscreen/remote/sleep) can drive the webview <video> element
|
||||
* that Rust cannot reach directly. No-op when no video adapter is active (audio
|
||||
* playback is already fully backend-driven).
|
||||
*/
|
||||
function handleControlCommand(action: string, position: number | null): void {
|
||||
const adapter = playerController.getActiveAdapter();
|
||||
if (!adapter) return;
|
||||
switch (action) {
|
||||
case "play":
|
||||
void adapter.play();
|
||||
break;
|
||||
case "pause":
|
||||
void adapter.pause();
|
||||
break;
|
||||
case "seek":
|
||||
// Backend-driven in-place seek (e.g. lockscreen scrub). The backend has
|
||||
// already decided this is a simple position change, so use the element
|
||||
// seek primitive with no transcode offset.
|
||||
if (position != null) void adapter.seekElement(position, 0);
|
||||
break;
|
||||
case "stop":
|
||||
void adapter.pause();
|
||||
break;
|
||||
default:
|
||||
console.warn("[playerEvents] Unknown control command:", action);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle show next episode popup event.
|
||||
*
|
||||
|
||||
@ -201,6 +201,11 @@ function createAuthStore() {
|
||||
onServerReconnected: () => {
|
||||
// Retry session verification when server becomes reachable
|
||||
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) => {
|
||||
console.error("[Auth] Failed to start connectivity monitoring:", error);
|
||||
|
||||
@ -36,7 +36,10 @@ function createHomeStore() {
|
||||
try {
|
||||
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.getNextUpEpisodes(undefined, 12),
|
||||
repo.getLatestItems("", 16),
|
||||
@ -44,6 +47,15 @@ function createHomeStore() {
|
||||
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
|
||||
const hero = resume.length >= 3 ? resume.slice(0, 5) : latest.slice(0, 5);
|
||||
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import { get } from "svelte/store";
|
||||
import { page } from "$app/stores";
|
||||
import { goto } from "$app/navigation";
|
||||
import { platform } from "@tauri-apps/plugin-os";
|
||||
@ -7,8 +8,9 @@
|
||||
import { auth, needsReauth, isAuthenticated } from "$lib/stores/auth";
|
||||
import { connectivity, isConnected } from "$lib/stores/connectivity";
|
||||
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 { onReconnected as onCatalogReconnected, syncCatalog, refreshSyncStatus, showServerCatalog, lastCatalogSync } from "$lib/services/offlineCatalog";
|
||||
import { playbackMode } from "$lib/stores/playbackMode";
|
||||
import { sessions } from "$lib/stores/sessions";
|
||||
import { currentMedia, isPlaying, playbackPosition, playbackDuration } from "$lib/stores/player";
|
||||
@ -43,6 +45,20 @@
|
||||
($isAndroid || !pathname.startsWith('/library'))
|
||||
);
|
||||
|
||||
// The library and settings routes own their own full-height layout (their own
|
||||
// scroll container + bottom-space reservation), so the root must leave their
|
||||
// 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(
|
||||
pathname.startsWith('/library') ||
|
||||
pathname.startsWith('/settings') ||
|
||||
pathname.startsWith('/player/') ||
|
||||
pathname.startsWith('/login')
|
||||
);
|
||||
const showBottomUi = $derived(showBottomNav || showGlobalMiniPlayer);
|
||||
|
||||
$effect(() => {
|
||||
const el = bottomUiEl;
|
||||
if (!el) {
|
||||
@ -83,9 +99,26 @@
|
||||
// Initialize download event listener
|
||||
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
|
||||
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
|
||||
playbackMode.initializeSessionMonitoring();
|
||||
await playbackMode.refresh();
|
||||
@ -114,6 +147,8 @@
|
||||
onServerReconnected: () => {
|
||||
// Retry session verification when server becomes reachable
|
||||
auth.retryVerification();
|
||||
// Resume offline-queued downloads and refresh the catalog.
|
||||
void onCatalogReconnected();
|
||||
},
|
||||
}).catch((monitorError) => {
|
||||
console.error("[Layout] Failed to start connectivity monitoring:", monitorError);
|
||||
@ -153,13 +188,35 @@
|
||||
{$pendingSyncCount} pending sync{$pendingSyncCount !== 1 ? 's' : ''}
|
||||
</span>
|
||||
{/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>
|
||||
{/if}
|
||||
|
||||
<!-- Main content -->
|
||||
<!-- Main content. Routes that own their full-height layout (library,
|
||||
settings, player, login) get a plain clipped box and manage their own
|
||||
scrolling internally. All other top-level pages render directly here, so
|
||||
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 ? `${$bottomUiHeight}px` : '0'}; overscroll-behavior: contain"
|
||||
>
|
||||
{@render children()}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Re-authentication modal -->
|
||||
<ReauthModal isOpen={$needsReauth} />
|
||||
|
||||
@ -511,7 +511,7 @@
|
||||
<!-- Genre Tags -->
|
||||
{#if item.genres?.length}
|
||||
<div>
|
||||
<GenreTags genres={item.genres ?? undefined} maxShow={6} />
|
||||
<GenreTags genres={item.genres ?? undefined} maxShow={6} itemType={item.type} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
@ -451,7 +451,10 @@
|
||||
savedProgress = null;
|
||||
const id = itemId;
|
||||
if (id) {
|
||||
loadAndPlay(id, 0);
|
||||
// forceRestart bypasses the resume-progress check; without it, passing a
|
||||
// start position of 0 is treated as "no position" (`!startPosition`), which
|
||||
// re-runs the resume check and re-shows this very dialog in a loop.
|
||||
loadAndPlay(id, 0, true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -537,7 +540,12 @@
|
||||
if (id) {
|
||||
reportPlaybackStopped(id, positionSeconds);
|
||||
}
|
||||
html5Adapter.reportState("stopped", id ?? null);
|
||||
// Intentionally do NOT emit a "stopped" player state here. This runs on both
|
||||
// natural end-of-video (an autoplay handoff the backend's on_video_playback_ended
|
||||
// owns) and on player close/unmount (where player_stop already drives the
|
||||
// backend state). Emitting StateChanged{stopped} on natural end flips the
|
||||
// player/mode to idle mid-handoff and suppresses next-episode auto-advance —
|
||||
// the "sleep timer pauses at the end of an episode instead of continuing" bug.
|
||||
}
|
||||
|
||||
async function handleVideoEnded() {
|
||||
|
||||