Compare commits

...
35 Commits
Author SHA1 Message Date
dtourolle 674c8e5cd0 ci(release): fix release-notes generation breaking jq publish step
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 3m11s
Traceability Validation / Check Requirement Traces (push) Successful in 20s
Build & Release / Run Tests (push) Successful in 3m40s
🏗️ Build and Test JellyTau / Build Android APK (push) Successful in 18m36s
Build & Release / Build Linux (push) Successful in 15m56s
Build & Release / Build Android (push) Successful in 18m33s
Build & Release / Create Release (push) Successful in 7s
The release-notes echo lines used unescaped backticks, which the shell ran
as command substitution; their output leaked control characters into
release_notes.md, so jq failed with 'Invalid string: control characters ...
must be escaped' when building the release payload.

- Escape the backticks so they are literal markdown.
- Remove emoji from the release-notes content (plain ASCII headings).
- Handle an already-existing release (HTTP 409) by reusing its id for
  asset upload instead of failing.
2026-06-23 20:38:09 +02:00
dtourolleandClaude Opus 4.8 45aa029916 fix(connectivity): drive reachability from real repository traffic
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 3m32s
Traceability Validation / Check Requirement Traces (push) Successful in 20s
🏗️ Build and Test JellyTau / Build Android APK (push) Successful in 18m27s
Build & Release / Run Tests (push) Successful in 3m36s
Build & Release / Build Linux (push) Successful in 15m43s
Build & Release / Build Android (push) Successful in 18m40s
Build & Release / Create Release (push) Failing after 22s
The offline/online switch was janky because two independent systems decided
"online" and never communicated:

- ConnectivityMonitor owned is_server_reachable (drove the UI banner) but
  learned reachability only from a standalone /System/Info/Public ping loop
  and from auth/login calls.
- HybridRepository served all real data by racing cache-vs-server but never
  read or wrote reachability.

So the banner reflected a side-channel poller, not the system the user actually
experienced: a successful ping could read "online" while authenticated data
calls 401'd or timed out, and three different timeout regimes (5s ping / 30s
data / 100ms cache race) flapped against each other.

Unify into a single source of truth:

- Extract a cheap, cloneable ConnectivityReporter that owns all reachability
  transitions and event emission.
- OnlineRepository reports the outcome of every server request to the reporter,
  classified via RepoError: Ok/Authentication/NotFound/Server => reachable
  (the server answered), Network => offline candidate, Database/Offline =>
  ignored (not a server signal).
- Time-window debounce (OFFLINE_CONFIRM_WINDOW = 5s): flip offline only after
  sustained network failure; recover instantly on the first success.
- Demote the ping loop to an offline-only recovery probe (no online polling;
  real traffic is the signal when online).
- Frontend: navigator.onLine is now advisory (triggers a recheck instead of
  forcing offline); removed the dead markReachable/markUnreachable store methods.

Docs updated (README, 07-connectivity, 03-data-flow, 02-svelte-frontend) to
describe the new model and fix pre-existing drift (HTTP client is 30s timeout +
5s ping, not the documented 10s/base_url).

Tests: 12 connectivity tests (debounce, instant recovery, RepoError
classification through report_outcome). Full suite: 398 Rust + 384 frontend
passing, svelte-check clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 21:56:14 +02:00
dtourolleandClaude Opus 4.8 3faa595b76 fix(android): track VideoOverlayManager.kt in canonical source tree
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 2m28s
Traceability Validation / Check Requirement Traces (push) Successful in 20s
Build & Release / Run Tests (push) Successful in 3m11s
🏗️ Build and Test JellyTau / Build Android APK (push) Successful in 17m51s
Build & Release / Build Linux (push) Successful in 15m29s
Build & Release / Build Android (push) Failing after 18m9s
Build & Release / Create Release (push) Has been skipped
JellyTauPlayer.kt references com.dtourolle.jellytau.VideoOverlayManager,
but the file existed only in the gitignored gen/android dir, so it
survived locally but vanished in CI (which regenerates gen/android via
'tauri android init'). sync-android-sources.sh copies top-level *.kt
from src-tauri/android, so adding it there gets it synced into the build.

Fixes: 'Unresolved reference: VideoOverlayManager' in
:app:compileUniversalReleaseKotlin.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 21:55:30 +02:00
dtourolleandClaude Opus 4.8 7fb866a583 ci: fix release Android build --apk flag requires explicit value
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 2m26s
Traceability Validation / Check Requirement Traces (push) Successful in 19s
Build & Release / Run Tests (push) Successful in 2m29s
🏗️ Build and Test JellyTau / Build Android APK (push) Successful in 17m57s
Build & Release / Build Linux (push) Successful in 15m38s
Build & Release / Build Android (push) Failing after 14m48s
Build & Release / Create Release (push) Has been skipped
Tauri CLI requires '--apk true'; bare '--apk' fails with
"a value is required for '--apk <APK>'". The release workflow
only reached this step now that checkout/container issues are fixed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 20:44:23 +02:00
dtourolle 0c3ed74fe1 ci: Improvements
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 12m47s
Traceability Validation / Check Requirement Traces (push) Successful in 22s
Build & Release / Run Tests (push) Successful in 2m27s
🏗️ Build and Test JellyTau / Build Android APK (push) Successful in 28m0s
Build & Release / Build Linux (push) Successful in 15m45s
Build & Release / Build Android (push) Failing after 49s
Build & Release / Create Release (push) Has been skipped
2026-06-21 17:38:06 +02:00
dtourolle a5b6266a6d Permanent CI fix
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 6m54s
Traceability Validation / Check Requirement Traces (push) Successful in 22s
🏗️ Build and Test JellyTau / Build Android APK (push) Successful in 1h14m25s
Build & Release / Run Tests (push) Failing after 7s
Build & Release / Build Linux (push) Has been skipped
Build & Release / Build Android (push) Has been skipped
Build & Release / Create Release (push) Has been skipped
2026-06-21 10:48:26 +02:00
dtourolle a816c84f8c fix CI
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 4m31s
Traceability Validation / Check Requirement Traces (push) Successful in 21s
🏗️ Build and Test JellyTau / Build Android APK (push) Has been cancelled
2026-06-21 10:35:14 +02:00
dtourolle 87762c03b6 Fix linux playback
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 4m38s
Traceability Validation / Check Requirement Traces (push) Successful in 22s
🏗️ Build and Test JellyTau / Build Android APK (push) Has been cancelled
2026-06-21 10:16:25 +02:00
dtourolle 975936b902 Merge pull request 'chore: clean up repo organization' (#2) from chore/repo-cleanup into master
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 4m44s
Traceability Validation / Check Requirement Traces (push) Successful in 30s
🏗️ Build and Test JellyTau / Build Android APK (push) Has been cancelled
Reviewed-on: #2
2026-06-21 07:53:30 +00:00
dtourolle 5ba9e0e958 chore: clean up repo organization
🏗️ Build and Test JellyTau / Run Tests (pull_request) Successful in 5m6s
Traceability Validation / Check Requirement Traces (pull_request) Successful in 30s
🏗️ Build and Test JellyTau / Build Android APK (pull_request) Failing after 19m30s
- Standardize on bun: remove package-lock.json, add packageManager field,
  gitignore non-bun lockfiles, fix stray npm install in android:build:clean
- Remove stale build logs and empty dirs (src-tauri/plugins, docs/tickets)
- Move android-dev.sh into scripts/
- Consolidate root docs into docs/ (docker/builder under docs/build/);
  move the architecture overview to docs/architecture/README.md
- Extract Requirements Specification from README into docs/requirements.md
  and slim README down to a project intro + docs index
- Fix internal references to the moved files
2026-06-21 09:52:09 +02:00
dtourolle ccc9dca924 fix: resolve all Rust test compile warnings without suppression
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 4m16s
Traceability Validation / Check Requirement Traces (push) Successful in 22s
🏗️ Build and Test JellyTau / Build Android APK (push) Has been cancelled
Remove unused imports and a dead test helper, and strengthen tests that
held unused bindings/fields so the values are actually exercised:
- drop unused imports (HttpConfig, MediaType, std::io::Write)
- remove unused TestEventEmitter::clear helper
- replace meaningless size_of asserts with real empty-manager checks
- assert on MockTrack.name in sorting tests
2026-06-21 09:33:50 +02:00
dtourolle 60bb6c72d1 ci: stop committing machine-specific Android cargo config
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 5m10s
Traceability Validation / Check Requirement Traces (push) Successful in 21s
🏗️ Build and Test JellyTau / Build Android APK (push) Has been cancelled
src-tauri/.cargo/config.toml hardcoded absolute NDK paths under
/home/dtourolle, which only exist on the dev laptop. In CI this made
ring's build script fail to find aarch64-linux-android34-clang. Tauri
derives the linker/CC paths from NDK_HOME automatically during
'android build', so the file is unnecessary there. Untrack it and
gitignore it; local dev copies are preserved on disk.
2026-06-21 09:22:34 +02:00
dtourolle 37cc9b424d ci: ensure Android NDK is available in build-and-test job
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 4m48s
Traceability Validation / Check Requirement Traces (push) Successful in 27s
🏗️ Build and Test JellyTau / Build Android APK (push) Failing after 5m32s
Set ANDROID_HOME/NDK_HOME/NDK_VERSION at the job level and add a step
that installs the NDK via sdkmanager when missing, so the Android init
step no longer fails when the builder image lacks NDK_HOME.
2026-06-21 09:10:41 +02:00
dtourolle 2daee7ec2d fix extract traces
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 4m10s
Traceability Validation / Check Requirement Traces (push) Successful in 21s
🏗️ Build and Test JellyTau / Build Android APK (push) Failing after 2m20s
2026-06-21 08:48:39 +02:00
dtourolle 01c6423154 Merge pull request 'Migrate all IPC call sites to typed tauri-specta commands.*' (#1) from ipc-commands-migration into master
🏗️ Build and Test JellyTau / Run Tests (push) Has been cancelled
🏗️ Build and Test JellyTau / Build Android APK (push) Has been cancelled
Traceability Validation / Check Requirement Traces (push) Has been cancelled
Reviewed-on: #1
2026-06-21 06:48:08 +00:00
dtourolle d01c2aab9f Migrate all IPC call sites to typed tauri-specta commands.*
🏗️ Build and Test JellyTau / Run Tests (pull_request) Successful in 4m39s
Traceability Validation / Check Requirement Traces (pull_request) Failing after 36s
🏗️ Build and Test JellyTau / Build Android APK (pull_request) Failing after 1m57s
Replace the remaining ~155 untyped invoke() calls across stores, services,
components, and routes with the generated commands.* wrappers from
$lib/api/bindings, so every IPC call is compile-time-checked against the
command signatures.

- Register repository_get_subtitle_url and repository_get_video_download_url
  in specta_builder() and the invoke_handler; regenerate bindings.ts.
- Source duplicated wire types (AutoplaySettings, CacheConfig, Session,
  ConnectivityStatus, audio/video settings, etc.) from bindings.
- Fix two bugs surfaced by the typed wrappers:
  - VideoDownloadButton passed an un-awaited Promise as the stream URL.
  - setAutoplaySettings omitted the required userId argument.
- Update unit tests asserting the old invoke(name, args) shape.
- Remove the five param-naming guard tests; the compiler and codegen now
  enforce what they checked.

svelte-check: 0 errors. vitest: green. cargo test --lib: green.
2026-06-21 08:47:04 +02:00
dtourolle 14e9d7e03a E frontend reconciliation (2/2): align consumers to generated bindings; svelte-check clean
Traceability Validation / Check Requirement Traces (push) Failing after 21s
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 13m21s
🏗️ Build and Test JellyTau / Build Android APK (push) Failing after 2m14s
Reconcile the ~50 frontend files that consumed the old hand-written types against
the stricter generated bindings (141 -> 0 svelte-check errors):

- Nullable strictness: null-coalesce/guard at consumer sites; widen shared helpers
  (CachedImage.tag, ticksToSeconds, formatDuration, getSessionIcon, session store
  send*/transferToRemote) to accept null.
- Field-name fixes exposed by codegen: userData.played -> isPlayed; remote
  NowPlayingItem uses album (not albumName); ArtistItem id/name.
- player.ts: normalize remote NowPlayingItem -> MediaItem in mergedMedia.
- ArtistItem now serializes camelCase (PascalCase alias retained for Jellyfin
  deserialize); update its serialize test.
- Update downloads.test.ts to the bundled { request } shape; complete the
  sessions.test.ts NowPlayingItem mock.

Frontend: svelte-check 0 errors, vitest 448 passing. Backend: 387 passing.
2026-06-20 20:49:20 +02:00
dtourolle 76c78e2edc E frontend reconciliation (1/2): types.ts sources from bindings; backend field fixes
- types.ts now re-exports wire types from generated bindings (single source of
  truth); keeps frontend-only unions (ItemType/LibraryType/PersonType/
  SessionCommand) and aliases Session = SessionInfo.
- Backend: MediaItem.runtime_ticks serializes as runTimeTicks (matches frontend,
  fixes a latent undefined-read bug); ArtistItem serializes camelCase id/name
  (PascalCase aliases retained for Jellyfin deserialize).
- player.ts: normalize remote NowPlayingItem -> MediaItem in mergedMedia so
  display components treat local/remote items uniformly.
- Reduces svelte-check errors 141 -> 70 (remaining: nullable guards + played->isPlayed).
2026-06-20 20:30:08 +02:00
dtourolle 6146d70bc5 Linux: render video via HTML5 WebView instead of the MPV backend
🏗️ Build and Test JellyTau / Run Tests (push) Failing after 1m37s
🏗️ Build and Test JellyTau / Build Android APK (push) Has been skipped
Traceability Validation / Check Requirement Traces (push) Failing after 22s
- online.rs: on Linux, advertise only WebView-decodable codecs (h264 video;
  aac/mp3/opus/vorbis/flac audio) in PlaybackInfo so Jellyfin transcodes
  HEVC/AV1/VP9/etc. to h264 HLS for the WebKitGTK <video> element.
- player: on Linux, don't load video into MPV (no embedded window — it would
  start a redundant decode the frontend immediately stops). Add
  PlayerController::set_current_item to keep queue/UI/remote-transfer state in
  sync without loading the item into the playback backend.
2026-06-20 19:31:57 +02:00
dtourolle ea342d76e3 Fix download + casting breakages from the specta migration
Casting: restore camelCase serialization on SessionInfo/NowPlayingItem/PlayState
(container rename_all = "camelCase" + per-field PascalCase serde aliases so Jellyfin
PascalCase still deserializes). Bindings and the existing frontend are camelCase
again — casting works with no frontend session changes.

Downloads: migrate DownloadButton.svelte and downloads.ts to the typed
commands.downloadItemAndStart / downloadItem / downloadVideo wrappers (request
objects), matching the bundled backend signatures.

Tooling:
- Enable tauri-specta ErrorHandlingMode::Throw so commands.* return Promise<T>
  and throw (drop-in for invoke()).
- Disambiguate specta name collisions: player MediaItem/MediaSource ->
  PlayerMediaItem/PlayerMediaSource, auth ServerInfo -> AuthServerInfo.
- Regenerate bindings.ts; svelte-check passes (0 errors).
2026-06-20 19:27:29 +02:00
dtourolle 7d07b38d50 Exclude generated bindings.ts from Tailwind content scan
Tailwind v4 auto-scans all source files; the 3000-line generated bindings.ts has
no CSS classes and a large generated TS file can confuse class detection. Add an
@source not exclusion.
2026-06-20 18:38:59 +02:00
dtourolle dc1f516da7 Fix Android insta-crash: don't export TS bindings at runtime
🏗️ Build and Test JellyTau / Run Tests (push) Failing after 2m18s
🏗️ Build and Test JellyTau / Build Android APK (push) Has been skipped
Traceability Validation / Check Requirement Traces (push) Failing after 18s
The tauri-specta `.export(...)` call ran inside run() on every debug app start
and tried to write `../src/lib/api/bindings.ts`, a path that doesn't exist on a
device — `.expect()` panicked at startup, crashing the app instantly on Android.
Bindings are generated by the `export_typescript_bindings` test instead.
2026-06-20 18:36:57 +02:00
dtourolle 731966246f Workstream E: generate bindings.ts via reusable specta_builder + export test
🏗️ Build and Test JellyTau / Run Tests (push) Failing after 3m41s
🏗️ Build and Test JellyTau / Build Android APK (push) Has been skipped
Traceability Validation / Check Requirement Traces (push) Failing after 48s
- Extract specta_builder() so run() and a #[test] share one command list.
- Add export_typescript_bindings test that writes src/lib/api/bindings.ts.
- Configure the TS exporter bigint behavior to Number (matches existing frontend).
- Commit the generated bindings.ts (typed commands.* wrappers + all DTO types).
2026-06-20 18:25:54 +02:00
dtourolle 57ff364f54 Add dep to docker file
🏗️ Build and Test JellyTau / Run Tests (push) Has been cancelled
🏗️ Build and Test JellyTau / Build Android APK (push) Has been cancelled
Traceability Validation / Check Requirement Traces (push) Has been cancelled
2026-06-20 18:20:38 +02:00
dtourolle ada3ed64ab Workstream E (backend): wire tauri-specta — annotate commands, derive Type, generate-ready Builder
- Add #[specta::specta] to all 201 #[tauri::command] functions.
- Derive specta::Type on all IPC DTOs (repository/types, settings, player/storage/
  download command DTOs, player enums, jellyfin SessionInfo/NowPlayingItem/PlayState,
  ThumbnailCacheStats, DownloadInfo, CacheConfig, etc.).
- Replace tauri::generate_handler! with a tauri_specta::Builder + collect_commands!
  in lib.rs (exports bindings.ts in debug builds).

Two contract changes required by specta constraints (frontend migration follows):
- specta caps command arity at 10 args: download_item_and_start / download_item /
  download_video now take a single request struct (params bundled, body unchanged
  via destructuring).
- specta can't parse split serde rename_all: SessionInfo/NowPlayingItem/PlayState
  switched to rename_all = "PascalCase" (Jellyfin deserialization preserved; these
  now serialize PascalCase to the frontend).

cargo check --lib is clean (0 errors). Frontend migration to bindings.ts is the next step.
2026-06-20 18:20:25 +02:00
dtourolle 55f1b85f12 Fix CI
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 7m4s
Traceability Validation / Check Requirement Traces (push) Failing after 24s
🏗️ Build and Test JellyTau / Build Android APK (push) Failing after 2m5s
2026-06-20 17:51:58 +02:00
dtourolle 26286ac6e7 sign build
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 10m47s
Traceability Validation / Check Requirement Traces (push) Failing after 4s
🏗️ Build and Test JellyTau / Build Android APK (push) Failing after 1m41s
2026-06-20 17:37:48 +02:00
dtourolle 144abb2f8b Workstream C: convert commands/storage to a folder module, extract thumbnail/people/series-prefs commands
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 14m27s
Traceability Validation / Check Requirement Traces (push) Failing after 4s
🏗️ Build and Test JellyTau / Build Android APK (push) Failing after 1m42s
- Move commands/storage.rs to commands/storage/mod.rs.
- Extract three cohesive, self-contained clusters:
  - storage/thumbnails.rs: thumbnail cache + image-URL commands.
  - storage/people.rs: person/cast metadata cache commands.
  - storage/series_prefs.rs: per-series preferred audio track commands.
- Re-exported via pub use so command names stay at commands::storage::*;
  invoke_handler unchanged. mod.rs shrinks from 1979 to 1500 lines, all tests pass.
2026-06-20 17:08:34 +02:00
dtourolle 642ec17069 Workstream C: convert commands/download to a folder module, extract pinning and smart-cache commands
🏗️ Build and Test JellyTau / Build Android APK (push) Has been cancelled
🏗️ Build and Test JellyTau / Run Tests (push) Has been cancelled
Traceability Validation / Check Requirement Traces (push) Has been cancelled
- Move commands/download.rs to commands/download/mod.rs.
- Extract pin/unpin/is_pinned into download/pinning.rs.
- Extract smart-cache stats/config + album recommendation commands into
  download/smart_cache.rs.
- Re-exported via pub use so command names stay at commands::download::*;
  invoke_handler unchanged, all tests pass.
2026-06-20 16:56:22 +02:00
dtourolle e560258a4b Workstream C: extract player settings and queue-manipulation commands into submodules
- commands/player/settings.rs: audio/video settings commands (4).
- commands/player/queue.rs: queue add/remove/move/skip + by-id commands (6) and
  their request DTOs.
- Make check_for_local_download and get_queue_status pub(super) for reuse.
- mod.rs now ~1834 lines (from 2720); invoke_handler unchanged, all tests pass.
2026-06-20 16:44:06 +02:00
dtourolle d1e5ba4c5d Workstream C: extract player sleep-timer/autoplay and session commands into submodules
- commands/player/timers.rs: sleep-timer + autoplay commands (8).
- commands/player/session.rs: media session get/dismiss commands (2).
- Make create_media_item and get_player_status pub(super) so the submodules can
  reuse them. mod.rs shrinks from ~2720 to ~2229 lines; invoke_handler unchanged.
2026-06-20 16:32:29 +02:00
dtourolle 8ddad497bf Workstream C: convert commands/player to a folder module, extract remote-session commands
🏗️ Build and Test JellyTau / Run Tests (push) Failing after 10m49s
🏗️ Build and Test JellyTau / Build Android APK (push) Has been skipped
Traceability Validation / Check Requirement Traces (push) Failing after 5s
- Move commands/player.rs to commands/player/mod.rs (folder module).
- Extract the 5 self-contained remote-session control commands
  (remote_play_on_session/send_command/session_seek/set_volume/toggle_mute)
  into commands/player/remote.rs, re-exported via `pub use remote::*` so the
  command names remain at commands::player::* and the invoke_handler is unchanged.

No behavior change; establishes the submodule split pattern for the oversized
command file.
2026-06-20 16:25:43 +02:00
dtourolle 46b9d328ab More CI fixes
🏗️ Build and Test JellyTau / Build Android APK (push) Has been cancelled
Traceability Validation / Check Requirement Traces (push) Has been cancelled
🏗️ Build and Test JellyTau / Run Tests (push) Has been cancelled
2026-06-20 16:15:33 +02:00
dtourolle dd5d648d21 Workstream C: relocate video seek-strategy logic into player core
Move the pure determine_video_seek_strategy function and its VideoSeekStrategy
enum (plus the 5 seek-strategy unit tests) out of the command layer into
player/seek.rs, where they belong and are testable without the Tauri State
harness. commands/player.rs now imports them from crate::player. No behavior
change.
2026-06-20 16:13:59 +02:00
dtourolle 6866f03c55 Architecture remediation A/B/F: poison-tolerant locks, graceful backend init, doc fixes
Workstream A — poison-tolerant locking:
- Add utils/lock.rs with MutexSafe/RwLockSafe extension traits that recover a
  poisoned std::sync lock instead of panicking, plus unit tests.
- Replace all 153 .lock().unwrap() and 4 .read()/.write().unwrap() production
  sites with _safe variants across 14 files, eliminating the player
  crash-cascade class. Tokio async mutexes are unchanged.

Workstream B — graceful backend init:
- create_player_backend no longer panics when MPV/ExoPlayer fail to initialize;
  it falls back to NullBackend and emits a backend-init-failed event so the UI
  can show "playback unavailable" instead of the app crashing. Fatal DB-setup
  panics are kept.

Workstream F — doc reconciliation:
- Rewrite software-architecture.md's inaccurate "thin UI / ~800 lines" claims to
  reflect reality (~20.5k non-test frontend) and document the events+polling
  hybrid plus the new locking/backend-init behavior.
2026-06-20 16:03:54 +02:00
145 changed files with 7207 additions and 15925 deletions
+18 -5
View File
@@ -31,9 +31,9 @@ jobs:
~/.cargo/registry
~/.cargo/git
src-tauri/target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
key: ${{ runner.os }}-cargo-host-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
${{ runner.os }}-cargo-host-
- name: Cache Node dependencies
uses: actions/cache@v3
@@ -66,6 +66,10 @@ jobs:
needs: test
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest
env:
ANDROID_HOME: /opt/android-sdk
NDK_VERSION: 27.0.11902837
NDK_HOME: /opt/android-sdk/ndk/27.0.11902837
steps:
- name: Checkout repository
@@ -78,9 +82,9 @@ jobs:
~/.cargo/registry
~/.cargo/git
src-tauri/target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
key: ${{ runner.os }}-cargo-android-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
${{ runner.os }}-cargo-android-
- name: Cache Node dependencies
uses: actions/cache@v3
@@ -99,6 +103,15 @@ jobs:
- 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
run: |
cd src-tauri
@@ -109,7 +122,7 @@ jobs:
id: build
run: |
mkdir -p artifacts
bun run tauri android build --apk true
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)
+145 -142
View File
@@ -18,37 +18,40 @@ jobs:
test:
name: Run Tests
runs-on: linux/amd64
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
- name: Setup Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Cache Rust dependencies
uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
~/.cargo/registry
~/.cargo/git
src-tauri/target
key: ${{ runner.os }}-cargo-host-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
${{ runner.os }}-cargo-host-
- name: Cache Node dependencies
uses: actions/cache@v3
with:
path: |
~/.bun/install/cache
node_modules
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-
- name: Install dependencies
run: bun install
- name: Run frontend tests
run: bun run test --run
run: |
bunx svelte-kit sync
bun run test --run
continue-on-error: false
- name: Run Rust tests
@@ -63,45 +66,32 @@ jobs:
name: Build Linux
runs-on: linux/amd64
needs: test
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
- name: Setup Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
libwebkit2gtk-4.1-dev \
build-essential \
curl \
wget \
file \
libssl-dev \
libgtk-3-dev \
libayatana-appindicator3-dev \
librsvg2-dev
- name: Cache Rust dependencies
uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
~/.cargo/registry
~/.cargo/git
src-tauri/target
key: ${{ runner.os }}-cargo-host-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
${{ runner.os }}-cargo-host-
- name: Cache Node dependencies
uses: actions/cache@v3
with:
path: |
~/.bun/install/cache
node_modules
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-
- name: Install dependencies
run: bun install
@@ -135,74 +125,79 @@ jobs:
name: Build Android
runs-on: linux/amd64
needs: test
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest
env:
ANDROID_HOME: /opt/android-sdk
ANDROID_SDK_ROOT: /opt/android-sdk
ANDROID_NDK_HOME: /opt/android-sdk/ndk/27.0.11902837
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
- name: Setup Java
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '17'
- name: Setup Android SDK
uses: android-actions/setup-android@v2
with:
api-level: 33
- name: Setup Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Add Android targets
run: |
rustup target add aarch64-linux-android
rustup target add armv7-linux-androideabi
rustup target add x86_64-linux-android
- name: Install Android NDK
run: |
sdkmanager "ndk;25.1.8937393"
- name: Cache Rust dependencies
uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
~/.cargo/registry
~/.cargo/git
src-tauri/target
key: ${{ runner.os }}-cargo-android-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-android-
- name: Cache Node dependencies
uses: actions/cache@v3
with:
path: |
~/.bun/install/cache
node_modules
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-
- name: Install dependencies
run: bun install
- name: Build for Android
run: bun run tauri android build
env:
ANDROID_NDK_HOME: ${{ android.ndk-home }}
ANDROID_SDK_ROOT: ${{ android.sdk-root }}
ANDROID_HOME: ${{ android.sdk-root }}
- name: Set app version from tag
run: |
REF="${GITHUB_REF#refs/tags/v}"
VERSION="${REF#refs/heads/}"
# On non-tag runs keep whatever is in tauri.conf.json
if echo "$GITHUB_REF" | grep -q '^refs/tags/v'; then
echo "Setting version to $VERSION"
sed -i "s/\"version\": \"[^\"]*\"/\"version\": \"$VERSION\"/" src-tauri/tauri.conf.json
fi
grep '"version"' src-tauri/tauri.conf.json
- name: Prepare Android artifacts
- name: Initialize Android project
run: bun run tauri android init
- name: Sync custom Android sources & gradle config
run: ./scripts/sync-android-sources.sh
- name: Write signing keystore
run: |
echo "${{ secrets.ANDROID_KEYSTORE_BASE64 }}" | base64 -d > "$RUNNER_TEMP/jellytau-release.jks"
cat > src-tauri/gen/android/keystore.properties <<EOF
storeFile=$RUNNER_TEMP/jellytau-release.jks
storePassword=${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
keyAlias=${{ secrets.ANDROID_KEY_ALIAS }}
keyPassword=${{ secrets.ANDROID_KEY_PASSWORD }}
EOF
- name: Build signed Android APK
run: bun run tauri android build --apk true --target aarch64
- name: Collect & verify signed APK
run: |
mkdir -p dist/android
# Copy APK
if [ -f "src-tauri/gen/android/app/build/outputs/apk/release/app-release.apk" ]; then
cp src-tauri/gen/android/app/build/outputs/apk/release/app-release.apk dist/android/jellytau-release.apk
fi
# Copy AAB (Android App Bundle) if built
if [ -f "src-tauri/gen/android/app/build/outputs/bundle/release/app-release.aab" ]; then
cp src-tauri/gen/android/app/build/outputs/bundle/release/app-release.aab dist/android/jellytau-release.aab
fi
APK=$(find src-tauri/gen/android/app/build/outputs/apk -name '*-release.apk' | head -1)
if [ -z "$APK" ]; then echo "❌ No release APK produced"; exit 1; fi
cp "$APK" dist/android/jellytau-release.apk
APKSIGNER=$(find "$ANDROID_SDK_ROOT/build-tools" -name apksigner | sort -V | tail -1)
echo "🔏 Verifying signature with $APKSIGNER"
"$APKSIGNER" verify --print-certs dist/android/jellytau-release.apk
ls -lah dist/android/
- name: Upload Android build artifact
@@ -217,6 +212,8 @@ jobs:
runs-on: linux/amd64
needs: [build-linux, build-android]
if: startsWith(github.ref, 'refs/tags/v')
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
@@ -243,23 +240,23 @@ jobs:
id: release_notes
run: |
VERSION="${{ steps.tag_name.outputs.VERSION }}"
echo "## 📱 JellyTau $VERSION Release" > release_notes.md
echo "## JellyTau $VERSION Release" > release_notes.md
echo "" >> release_notes.md
echo "### 📦 Downloads" >> release_notes.md
echo "### Downloads" >> release_notes.md
echo "" >> release_notes.md
echo "#### Linux" >> release_notes.md
echo "- **AppImage** - Run directly on most Linux distributions" >> release_notes.md
echo "- **DEB** - Install via `sudo dpkg -i jellytau_*.deb` (Ubuntu/Debian)" >> release_notes.md
echo "- **DEB** - Install via \`sudo dpkg -i jellytau_*.deb\` (Ubuntu/Debian)" >> release_notes.md
echo "" >> release_notes.md
echo "#### Android" >> release_notes.md
echo "- **APK** - Install via `adb install jellytau-release.apk` or sideload via file manager" >> release_notes.md
echo "- **APK** - Install via \`adb install jellytau-release.apk\` or sideload via file manager" >> release_notes.md
echo "- **AAB** - Upload to Google Play Console or testing platforms" >> release_notes.md
echo "" >> release_notes.md
echo "### What's New" >> release_notes.md
echo "### What's New" >> release_notes.md
echo "" >> release_notes.md
echo "See [CHANGELOG.md](CHANGELOG.md) for detailed changes." >> release_notes.md
echo "" >> release_notes.md
echo "### 🔧 Installation" >> release_notes.md
echo "### Installation" >> release_notes.md
echo "" >> release_notes.md
echo "#### Linux (AppImage)" >> release_notes.md
echo "\`\`\`bash" >> release_notes.md
@@ -277,11 +274,11 @@ jobs:
echo "- Sideload: Download APK and install via file manager or ADB" >> release_notes.md
echo "- Play Store: Coming soon" >> release_notes.md
echo "" >> release_notes.md
echo "### 🐛 Known Issues" >> release_notes.md
echo "### Known Issues" >> release_notes.md
echo "" >> release_notes.md
echo "See [GitHub Issues](../../issues) for reported bugs." >> release_notes.md
echo "" >> release_notes.md
echo "### 📝 Requirements" >> release_notes.md
echo "### Requirements" >> release_notes.md
echo "" >> release_notes.md
echo "**Linux:**" >> release_notes.md
echo "- 64-bit Linux system" >> release_notes.md
@@ -292,46 +289,52 @@ jobs:
echo "- 50MB free storage" >> release_notes.md
echo "" >> release_notes.md
echo "---" >> release_notes.md
echo "Built with Tauri, SvelteKit, and Rust 🦀" >> release_notes.md
echo "Built with Tauri, SvelteKit, and Rust" >> release_notes.md
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
name: ${{ steps.tag_name.outputs.RELEASE_NAME }}
body_path: release_notes.md
files: |
artifacts/linux/*
artifacts/android/*
draft: false
prerelease: ${{ contains(steps.tag_name.outputs.VERSION, 'rc') || contains(steps.tag_name.outputs.VERSION, 'beta') || contains(steps.tag_name.outputs.VERSION, 'alpha') }}
- name: Publish Gitea release & upload assets
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Upload to Gitea Releases
# GITEA_TOKEN (a PAT) is preferred; falls back to the auto-provided token.
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
AUTO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -e
command -v jq >/dev/null || { echo "❌ jq is required on the runner"; exit 1; }
VERSION="${{ steps.tag_name.outputs.VERSION }}"
API="${GITHUB_SERVER_URL}/api/v1"
REPO="${GITHUB_REPOSITORY}"
TOKEN="${GITEA_TOKEN:-$AUTO_TOKEN}"
case "$VERSION" in *rc*|*beta*|*alpha*) PRE=true;; *) PRE=false;; esac
echo "📦 Release artifacts prepared for $VERSION"
echo ""
echo "Linux:"
ls -lh artifacts/linux/ || echo "No Linux artifacts"
echo ""
echo "Android:"
ls -lh artifacts/android/ || echo "No Android artifacts"
echo ""
echo "✅ Release $VERSION is ready!"
echo "📄 Release notes saved to release_notes.md"
PAYLOAD=$(jq -n \
--arg tag "$VERSION" \
--arg name "JellyTau $VERSION" \
--rawfile body release_notes.md \
--argjson pre "$PRE" \
'{tag_name:$tag, name:$name, body:$body, draft:false, prerelease:$pre}')
- name: Publish release notes
run: |
echo "## 🎉 Release Published"
echo ""
echo "**Version:** ${{ steps.tag_name.outputs.VERSION }}"
echo "**Tag:** ${{ github.ref }}"
echo ""
echo "Artifacts:"
echo "- Linux artifacts in: artifacts/linux/"
echo "- Android artifacts in: artifacts/android/"
echo ""
echo "Visit the Release page to download files."
echo "📦 Creating release $VERSION on $REPO"
# -f drops on HTTP error; capture status so an existing release (409) is handled gracefully.
HTTP=$(curl -sS -o resp.json -w '%{http_code}' -X POST "$API/repos/$REPO/releases" \
-H "Authorization: token $TOKEN" \
-H "Content-Type: application/json" \
-d "$PAYLOAD")
if [ "$HTTP" = "201" ]; then
RELEASE_ID=$(jq -r '.id' resp.json)
elif [ "$HTTP" = "409" ]; then
echo "️ Release $VERSION already exists; fetching its id to upload assets"
RELEASE_ID=$(curl -fsS "$API/repos/$REPO/releases/tags/$VERSION" \
-H "Authorization: token $TOKEN" | jq -r '.id')
else
echo "❌ Failed to create release (HTTP $HTTP):"; cat resp.json; exit 1
fi
echo "Release id=$RELEASE_ID"
for f in artifacts/android/* artifacts/linux/*; do
[ -f "$f" ] || continue
echo "⬆️ Uploading $(basename "$f")"
curl -fsS -X POST \
"$API/repos/$REPO/releases/$RELEASE_ID/assets?name=$(basename "$f")" \
-H "Authorization: token $TOKEN" \
-F "attachment=@$f" >/dev/null
done
echo "✅ Release $VERSION published with assets"
+2
View File
@@ -16,6 +16,8 @@ jobs:
validate-traces:
runs-on: linux/amd64
name: Check Requirement Traces
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest
steps:
- name: Checkout repository
+2
View File
@@ -16,6 +16,8 @@ jobs:
traceability:
name: Validate Requirement Traces
runs-on: linux/amd64
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest
steps:
- name: Checkout code
+11
View File
@@ -9,6 +9,11 @@ yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Use bun (see packageManager in package.json); ignore other package managers' lockfiles
package-lock.json
yarn.lock
pnpm-lock.yaml
# Build output
/build
/dist
@@ -47,3 +52,9 @@ vite.config.ts.timestamp-*
# Logs
logs
*.log
# Android signing keystore (NEVER commit)
android-keystore/
# Local machine-specific Android NDK toolchain paths (do not commit)
src-tauri/.cargo/config.toml
+2
View File
@@ -35,6 +35,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libsoup-3.0-dev \
librsvg2-dev \
libayatana-appindicator3-dev \
# mpv player library (linked via libmpv-sys)
libmpv-dev \
&& rm -rf /var/lib/apt/lists/*
# Install Node.js 20.x from NodeSource
+11 -3
View File
@@ -7,7 +7,8 @@ FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive \
ANDROID_HOME=/opt/android-sdk \
NDK_VERSION=27.0.11902837 \
SDK_VERSION=34 \
SDK_VERSION=36 \
BUILD_TOOLS_VERSION=35.0.0 \
RUST_BACKTRACE=1 \
PATH="/root/.bun/bin:/root/.cargo/bin:$PATH" \
CARGO_HOME=/root/.cargo
@@ -20,6 +21,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
git \
ca-certificates \
unzip \
jq \
openjdk-17-jdk-headless \
pkg-config \
libssl-dev \
@@ -33,6 +35,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libsoup-3.0-dev \
librsvg2-dev \
libayatana-appindicator3-dev \
# mpv player library (linked via libmpv-sys)
libmpv-dev \
&& rm -rf /var/lib/apt/lists/*
# Install Node.js 20.x from NodeSource
@@ -65,10 +69,14 @@ RUN wget -q https://dl.google.com/android/repository/commandlinetools-linux-1107
mkdir -p $ANDROID_HOME/cmdline-tools/latest && \
mv $ANDROID_HOME/cmdline-tools/* $ANDROID_HOME/cmdline-tools/latest/ 2>/dev/null || true
# Install Android SDK components
# Accept all SDK licenses up front so Gradle can install/use components non-interactively
RUN yes | $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --sdk_root=$ANDROID_HOME --licenses > /dev/null
# Install Android SDK components (must match the compileSdk/targetSdk in the generated Gradle project)
RUN $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --sdk_root=$ANDROID_HOME \
"platform-tools" \
"platforms;android-$SDK_VERSION" \
"build-tools;34.0.0" \
"build-tools;$BUILD_TOOLS_VERSION" \
"ndk;$NDK_VERSION" \
--channel=0 2>&1 | grep -v "Warning" || true
+27 -477
View File
@@ -2,335 +2,25 @@
A cross-platform Jellyfin client built with Tauri, SvelteKit, and TypeScript.
## Recommended IDE Setup
Business logic lives in a Rust backend; a UI-rich Svelte frontend handles
presentation and talks to it over Tauri's IPC. Targets Linux (libmpv) and
Android (ExoPlayer).
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer).
## Getting Started
---
# Requirements Specification
## 1. User Requirements
| ID | Requirement | Priority | Status |
|----|-------------|----------|--------|
| UR-001 | Run the app on multiple platforms (Linux, Android) | High | In Progress |
| UR-002 | Access media when online or offline | High | Done |
| UR-003 | Play videos | High | Done |
| UR-004 | Play audio uninterrupted | High | Done |
| UR-005 | Control media playback (pause, play, skip, scrub) | High | Done |
| UR-006 | Control media when device is on lock screen or via BLE headsets | Medium | Done |
| UR-007 | Navigate media in library | High | Done |
| UR-008 | Search media across libraries | High | Done |
| UR-009 | Connect to Jellyfin to access media | High | Done |
| UR-010 | Control playback of Jellyfin remote sessions | Low | Done |
| UR-011 | Download media on demand | Medium | Done |
| UR-012 | Login info shall be stored securely and persistently | High | Done |
| UR-013 | View and manage downloaded media | Medium | Done |
| UR-014 | Make and edit playlists of music that sync back to Jellyfin | Medium | Done |
| UR-015 | View and manage current audio queue (add, reorder tracks) | Medium | Done |
| UR-016 | Change system settings while playing (brightness, volume) | Low | Planned |
| UR-017 | Like or unlike audio, albums, movies, etc. | Medium | Done |
| UR-018 | Choose to download series, albums, songs, artist discography | Medium | Done |
| UR-019 | Resume playback from where you left off (movies, shows, albums) | High | Done |
| UR-020 | Select subtitles for video content | High | Done |
| UR-021 | Select audio track for video content | High | Done |
| UR-022 | Control streaming quality and transcoding settings | Medium | Planned |
| UR-023 | View "Next Up" / Continue Watching on home screen; auto-play next episode with countdown popup and configurable episode limit | Medium | Done |
| UR-024 | View recently added content on server | Medium | Done |
| UR-025 | Sync watch history and progress back to Jellyfin | High | Done |
| UR-026 | Sleep timer for audio and video playback (roller UI, time/track/episode modes) | Low | Done |
| UR-027 | Audio equalizer for sound customization | Low | Planned |
| UR-028 | Navigate to artist/album by tapping names in now playing view | High | Done |
| UR-029 | Toggle between grid and list view in library | Medium | Done |
| UR-030 | Quick genre browsing and filtering | Medium | Done |
| UR-031 | Crossfade between audio tracks | Low | Done (Linux only) |
| UR-032 | Gapless playback for seamless album listening | Medium | Done (Linux only) |
| UR-033 | Volume normalization to prevent volume jumps between tracks | Low | Done (Linux only) |
| UR-034 | Rich home screen with hero banners, carousels, and personalized sections | High | Done |
| UR-035 | View cast/crew (actors, directors) on movie/show detail pages | High | Done |
| UR-036 | Navigate to actor/person page showing their filmography | Medium | Done |
| UR-037 | Visually appealing video library with poster grids and metadata | High | Done |
| UR-038 | Movie/show detail page with backdrop, ratings, and rich metadata | High | Done |
| UR-039 | Navigate between main sections via bottom navigation bar | High | Done |
---
## 2. Software Requirements
### 2.1 Integration Requirements
External system integrations and platform-specific implementations.
| ID | Requirement | Category | Traces To | Status |
|----|-------------|----------|-----------|--------|
| IR-001 | Build system supporting multiple targets (Linux, Android) | Build | UR-001 | Done |
| IR-002 | Build scripts for Android and Linux | Build | UR-001 | Done |
| IR-003 | Integration of libmpv for Linux playback | Playback | UR-003, UR-004 | Done |
| IR-004 | Integration of ExoPlayer for Android playback | Playback | UR-003, UR-004 | In Progress (basic playback works, audio settings missing) |
| IR-005 | MPRIS D-Bus integration for Linux lockscreen/media controls | Platform | UR-006 | Planned |
| IR-006 | Android MediaSession integration for lockscreen controls | Platform | UR-006 | Done |
| IR-007 | Bluetooth AVRCP integration via system media session | Platform | UR-006 | Planned |
| IR-008 | Android audio focus handling (pause on call) | Platform | UR-004, UR-006 | Done |
| IR-009 | Jellyfin API client for authentication | API | UR-009, UR-012 | Done |
| IR-010 | Jellyfin API client for library browsing | API | UR-007, UR-008 | Done |
| IR-011 | Jellyfin API client for playback streaming | API | UR-003, UR-004 | Done |
| IR-012 | Jellyfin Sessions API for remote playback control | API | UR-010 | Done |
| IR-021 | Android MediaRouter integration for remote volume in system panel | Platform | UR-010, UR-016 | Planned |
| IR-013 | SQLite integration for local database | Storage | UR-002, UR-011 | Done |
| IR-014 | Secure credential storage (keyring/keychain) | Security | UR-012 | Done |
| IR-015 | Jellyfin API client for playback progress reporting | API | UR-019, UR-025 | Done |
| IR-016 | Jellyfin API client for subtitle/audio track info | API | UR-020, UR-021 | Done |
| IR-017 | Jellyfin API client for transcoding parameters | API | UR-022 | Planned |
| IR-018 | libmpv subtitle rendering and selection | Playback | UR-020 | Planned |
| IR-019 | libmpv audio track selection | Playback | UR-021 | Planned |
| IR-020 | libmpv/ExoPlayer equalizer integration | Playback | UR-027 | Planned |
| IR-022 | Jellyfin API client for person/cast data | API | UR-035, UR-036 | Done |
| IR-023 | Database schema for person/cast caching | Storage | UR-035, UR-036 | Done |
| IR-024 | Jellyfin API client for home screen data (featured, continue watching) | API | UR-034 | Done |
### 2.2 Jellyfin API Requirements
API endpoints and data contracts required for Jellyfin integration.
| ID | Requirement | Endpoint Category | Traces To | Status |
|----|-------------|-------------------|-----------|--------|
| JA-001 | Server connection and discovery | System | UR-009 | Done |
| JA-002 | User authentication (username/password) | Users | UR-009, UR-012 | Done |
| JA-003 | Get user library views | UserViews | UR-007 | Done |
| JA-004 | Get library items (paginated) | Items | UR-007 | Done |
| JA-005 | Get item details and metadata | Items | UR-007 | Done |
| JA-006 | Search across libraries | Items | UR-008 | Done |
| JA-007 | Get playback info and stream URL | MediaInfo | UR-003, UR-004 | Done |
| JA-008 | Get available subtitles for item | MediaInfo | UR-020 | Done |
| JA-009 | Get available audio tracks for item | MediaInfo | UR-021 | Done |
| JA-010 | Report playback start | Sessions | UR-025 | Done |
| JA-011 | Report playback progress (periodic) | Sessions | UR-025 | Done |
| JA-012 | Report playback stopped | Sessions | UR-025 | Done |
| JA-013 | Get resume position for item | UserData | UR-019 | Done |
| JA-014 | Get "Next Up" items | Shows | UR-023 | Done |
| JA-015 | Get "Continue Watching" items | Items | UR-023 | Done |
| JA-016 | Get recently added items | Items | UR-024 | Done |
| JA-017 | Mark item as favorite | UserData | UR-017 | Done |
| JA-018 | Remove item from favorites | UserData | UR-017 | Done |
| JA-019 | Get/create/update playlists | Playlists | UR-014 | Done |
| JA-020 | Add/remove items from playlist | Playlists | UR-014 | Done |
| JA-021 | Get active sessions list | Sessions | UR-010 | Done |
| JA-022 | Send playback commands to remote session (play/pause/stop) | Sessions | UR-010 | Done |
| JA-023 | Send seek command to remote session | Sessions | UR-010 | Done |
| JA-024 | Send next/previous track commands to remote session | Sessions | UR-010 | Done |
| JA-025 | Play specific item on remote session | Sessions | UR-010 | Done |
| JA-026 | Send volume/mute commands to remote session | Sessions | UR-010 | Done |
| JA-027 | Get transcoding options | MediaInfo | UR-022 | Planned |
| JA-028 | Get image/artwork URLs | Images | UR-007 | Done |
| JA-029 | Get cast/crew for item (actors, directors) | Items | UR-035 | Done |
| JA-030 | Get person details and filmography | Persons | UR-036 | Done |
| JA-031 | Get items by person (actor/director filmography) | Items | UR-036 | Done |
### 2.3 Development Requirements
Internal architecture, components, and application logic.
| ID | Requirement | Category | Traces To | Status |
|----|-------------|----------|-----------|--------|
| DR-001 | Player state machine (idle, loading, playing, paused, seeking, error) | Player | UR-005 | Done |
| DR-002 | MediaItem struct tracking source, location, duration, metadata | Player | UR-003, UR-004 | Done |
| DR-003 | Source-agnostic media abstraction (Remote, Local, DirectUrl) | Player | UR-002, UR-011 | Done |
| DR-004 | PlayerBackend trait for platform-agnostic playback | Player | UR-003, UR-004 | Done |
| DR-005 | Queue manager with shuffle, repeat, history | Player | UR-005, UR-015 | Done |
| DR-006 | Audio pre-caching for seamless track transitions | Player | UR-004 | Planned |
| DR-007 | Library browsing screens (grid view, search, filters) | UI | UR-007, UR-008 | Done |
| DR-008 | Album/Series detail view with track listing | UI | UR-007 | Done |
| DR-009 | Audio player UI (mini player, full screen) | UI | UR-005 | Done |
| DR-010 | Video player UI (fullscreen, controls overlay) | UI | UR-003, UR-005 | Done |
| DR-011 | Search bar with cross-library search | UI | UR-008 | Done |
| DR-012 | Local database for media metadata cache | Storage | UR-002 | Done |
| DR-013 | Repository pattern for online/offline data access | Storage | UR-002 | Done |
| DR-014 | Offline mutation queue for sync-back operations | Storage | UR-002, UR-014, UR-017 | Done |
| DR-015 | Download manager with queue and progress tracking | Storage | UR-011, UR-018 | Done |
| DR-016 | Thumbnail caching and sync with server | Storage | UR-007 | Done |
| DR-017 | "Manage Downloads" screen for local media management | UI | UR-013 | Done |
| DR-018 | Download buttons on library/album/player screens | UI | UR-011, UR-018 | Done |
| DR-019 | Playlist creation and editing UI | UI | UR-014 | Done |
| DR-020 | Queue management UI (add, remove, reorder) | UI | UR-015 | Done |
| DR-021 | Like/favorite functionality on media items | UI | UR-017 | Done |
| DR-022 | Resume position tracking and restoration on play | Player | UR-019 | Done |
| DR-023 | Subtitle selection UI in video player | UI | UR-020 | Done |
| DR-024 | Audio track selection UI in video player | UI | UR-021 | Done |
| DR-025 | Quality/transcoding settings UI | UI | UR-022 | Planned |
| DR-026 | "Continue Watching" / "Next Up" home section | UI | UR-023 | Done |
| DR-027 | "Recently Added" home section | UI | UR-024 | Done |
| DR-028 | Playback progress sync service (periodic reporting) | Player | UR-025 | Done |
| DR-029 | Sleep timer with roller UI, time/track/episode modes, and auto-stop (audio + video players) | Player | UR-026 | Done |
| DR-049 | Auto-play episode limit (configurable max episodes per session) | Player | UR-023 | Done |
| DR-050 | Reusable scroll picker (roller) component | UI | UR-026 | Done |
| DR-030 | Equalizer UI with presets and custom bands | UI | UR-027 | Planned |
| DR-031 | Clickable artist/album links in now playing view | UI | UR-028 | Done |
| DR-032 | List view option for library browsing (albums, artists) | UI | UR-029 | Done |
| DR-033 | Genre browsing screen with quick filters | UI | UR-030 | Done |
| DR-034 | Crossfade engine with configurable duration (0-12s) | Player | UR-031 | Done (Linux only) |
| DR-035 | Gapless playback between sequential tracks | Player | UR-032 | Done (Linux only) |
| DR-036 | Volume normalization with preset levels (Loud/Normal/Quiet) | Player | UR-033 | Done (Linux only) |
| DR-037 | Remote session browser and control UI | UI | UR-010 | Done |
| DR-038 | Home screen with hero banner carousel (featured/continue watching) | UI | UR-034 | Done |
| DR-039 | Home screen horizontal carousels (recently added, recommendations) | UI | UR-034, UR-024 | Done |
| DR-040 | Cast/crew section on movie/show detail pages | UI | UR-035 | Done |
| DR-041 | Person/actor detail page with filmography grid | UI | UR-036 | Done |
| DR-042 | Video library grid with poster cards, year, and rating badges | UI | UR-037 | Done |
| DR-043 | Movie/show detail page with backdrop hero, synopsis, and metadata | UI | UR-038 | Done |
| DR-044 | Horizontal scrolling actor/cast row with profile images | UI | UR-035 | Done |
| DR-045 | Bottom navigation bar with Home, Library, Search buttons | UI | UR-039 | Done |
| DR-046 | Dedicated search page with input and results | UI | UR-039 | Done |
| DR-047 | Next episode auto-play popup with configurable countdown and episode limit | Player | UR-023 | Done |
| DR-048 | Video settings (auto-play toggle, countdown duration, episode limit) | Settings | UR-023, UR-026 | Done |
---
## 3. Traceability Matrix
### User Requirements to Software Requirements
| User Req | Integration Requirements | Development Requirements |
|----------|-------------------------|-------------------------|
| UR-001 | IR-001, IR-002 | - |
| UR-002 | IR-013 | DR-003, DR-012, DR-013, DR-014 |
| UR-003 | IR-003, IR-004, IR-011 | DR-002, DR-004, DR-010 |
| UR-004 | IR-003, IR-004, IR-008, IR-011 | DR-002, DR-004, DR-006 |
| UR-005 | - | DR-001, DR-005, DR-009 |
| UR-006 | IR-005, IR-006, IR-007, IR-008 | - |
| UR-007 | IR-010 | DR-007, DR-008, DR-016 |
| UR-008 | IR-010 | DR-007, DR-011 |
| UR-009 | IR-009, IR-010, IR-011 | - |
| UR-010 | IR-012, IR-021 | DR-037 |
| UR-011 | IR-013 | DR-003, DR-015, DR-018 |
| UR-012 | IR-009, IR-014 | - |
| UR-013 | IR-013 | DR-017 |
| UR-014 | IR-010 | DR-014, DR-019 |
| UR-015 | - | DR-005, DR-020 |
| UR-016 | - | - |
| UR-017 | - | DR-014, DR-021 |
| UR-018 | IR-013 | DR-015, DR-018 |
| UR-019 | IR-015 | DR-022 |
| UR-020 | IR-016, IR-018 | DR-023 |
| UR-021 | IR-016, IR-019 | DR-024 |
| UR-022 | IR-017 | DR-025 |
| UR-023 | IR-010 | DR-026, DR-047, DR-048, DR-049 |
| UR-024 | IR-010 | DR-027 |
| UR-025 | IR-015 | DR-028 |
| UR-026 | - | DR-029, DR-048, DR-050 |
| UR-027 | IR-020 | DR-030 |
| UR-028 | - | DR-031 |
| UR-029 | - | DR-032 |
| UR-030 | IR-010 | DR-033 |
| UR-031 | - | DR-034 |
| UR-032 | - | DR-035 |
| UR-033 | - | DR-036 |
| UR-034 | IR-010, IR-024 | DR-038, DR-039 |
| UR-035 | IR-022, IR-023 | DR-040, DR-044 |
| UR-036 | IR-022, IR-023 | DR-041 |
| UR-037 | IR-010 | DR-042 |
| UR-038 | IR-010 | DR-043 |
| UR-039 | - | DR-045, DR-046 |
---
## 4. Test Traceability
### Unit Tests to Software Requirements
| Test ID | Test Description | Traces To | Status |
|---------|-----------------|-----------|--------|
| UT-001 | Player state transitions | DR-001 | Pending |
| UT-002 | MediaItem source URL resolution | DR-002, DR-003 | Pending |
| UT-003 | Queue next/previous navigation | DR-005 | Pending |
| UT-004 | Queue shuffle order generation | DR-005 | Pending |
| UT-005 | Queue repeat mode behavior | DR-005 | Pending |
| UT-006 | Jellyfin authentication flow | IR-009 | Pending |
| UT-007 | Jellyfin library items parsing | IR-010 | Pending |
| UT-008 | Repository pattern online/offline switching | DR-013 | Pending |
| UT-009 | Offline mutation queue persistence | DR-014 | Pending |
| UT-010 | Download queue management | DR-015 | Done |
| UT-011 | Resume position storage and retrieval | DR-022 | Pending |
| UT-012 | Sleep timer countdown logic | DR-029 | Pending |
| UT-013 | Playback progress reporting throttling | DR-028 | Pending |
| UT-014 | Database open and in-memory mode | IR-013, DR-012 | Done |
| UT-015 | Database migrations run successfully | IR-013, DR-012 | Done |
| UT-016 | All database tables created | IR-013, DR-012 | Done |
| UT-017 | FTS5 search table created | IR-013, DR-012 | Done |
| UT-018 | Server CRUD operations | IR-013, DR-012 | Done |
| UT-019 | User CRUD operations | IR-013, DR-012 | Done |
| UT-020 | Cascade delete server removes users | IR-013, DR-012 | Done |
| UT-021 | Item insert and FTS search | IR-013, DR-012 | Done |
| UT-022 | User data playback position storage | IR-013, DR-012, DR-022 | Done |
| UT-023 | Sync queue operations | IR-013, DR-014 | Done |
| UT-024 | Downloads table operations | IR-013, DR-015 | Done |
| UT-025 | Migrations are idempotent | IR-013, DR-012 | Done |
| UT-026 | NullBackend volume default value | DR-004 | Done |
| UT-027 | NullBackend set volume | DR-004 | Done |
| UT-028 | NullBackend volume clamping (high/low) | DR-004 | Done |
| UT-029 | NullBackend volume boundary values | DR-004 | Done |
| UT-030 | PlayerController volume default | DR-004, DR-009 | Done |
| UT-031 | PlayerController set volume | DR-004, DR-009 | Done |
| UT-032 | PlayerController muted default | DR-004, DR-009 | Done |
| UT-033 | PlayerController volume delegates to backend | DR-004, DR-009 | Done |
| UT-034 | Download event serialization roundtrip | DR-015 | Done |
| UT-035 | Download event completed serialization | DR-015 | Done |
| UT-036 | Download event failed serialization | DR-015 | Done |
| UT-037 | Download worker exponential backoff | DR-015 | Done |
| UT-038 | Download worker error retryable check | DR-015 | Done |
| UT-039 | Download manager creation | DR-015 | Done |
| UT-040 | Download manager set max concurrent | DR-015 | Done |
| UT-041 | Download info serialization | DR-015 | Done |
| UT-042 | Download command filename sanitization | DR-015, DR-018 | Done |
| UT-043 | Download command filename extension preservation | DR-015, DR-018 | Done |
| UT-044 | Offline item serialization | DR-017 | Done |
| UT-045 | Smart cache default config | DR-015 | Done |
| UT-046 | Smart cache album affinity tracking | DR-015 | Done |
| UT-047 | Smart cache queue precache config | DR-015 | Done |
| UT-048 | Smart cache storage limit check | DR-015 | Done |
| UT-049 | Playlist create (offline) | DR-019, JA-019 | Done |
| UT-050 | Playlist delete (offline) | DR-019, JA-019 | Done |
| UT-051 | Playlist rename (offline) | DR-019, JA-019 | Done |
| UT-052 | Playlist get items (offline) | DR-019, JA-019 | Done |
| UT-053 | Playlist add items (offline) | DR-019, JA-020 | Done |
| UT-054 | Playlist remove items (offline) | DR-019, JA-020 | Done |
| UT-055 | Playlist reorder items (offline) | DR-019, JA-020 | Done |
| UT-056 | Playlist entry serialization | DR-019, JA-019 | Done |
| UT-057 | Playlist Tauri command param naming (camelCase) | DR-019, JA-019, JA-020 | Done |
| UT-058 | Playlist repository client methods | DR-019, JA-019, JA-020 | Done |
### Integration Tests
| Test ID | Test Description | Traces To | Status |
|---------|-----------------|-----------|--------|
| IT-001 | End-to-end authentication with Jellyfin server | IR-009, UR-009 | Pending |
| IT-002 | Library browsing and item loading | IR-010, UR-007 | Pending |
| IT-003 | Audio playback via libmpv | IR-003, UR-004 | Pending |
| IT-004 | Video playback via libmpv | IR-003, UR-003 | Pending |
| IT-005 | MPRIS lockscreen controls on Linux | IR-005, UR-006 | Pending |
| IT-006 | Offline mode with local database | IR-013, UR-002 | Pending |
| IT-007 | Media download and local playback | DR-015, UR-011 | Pending |
| IT-008 | Subtitle track selection via libmpv | IR-018, UR-020 | Pending |
| IT-009 | Audio track selection via libmpv | IR-019, UR-021 | Pending |
| IT-010 | Playback progress sync to Jellyfin | IR-015, UR-025 | Pending |
| IT-011 | Resume playback from server position | IR-015, UR-019 | Pending |
| IT-012 | Equalizer bands via libmpv | IR-020, UR-027 | Pending |
---
## 5. Development Commands
This project uses [bun](https://bun.sh) as its package manager.
```bash
# Activate Rust environment (fish shell)
# Activate the Rust environment (fish shell)
source "$HOME/.cargo/env.fish"
# Install dependencies
bun install
# Development
# Run in development
bun run tauri dev
# Type checking
# Type-check the frontend
bun run check
# Build for Linux
@@ -340,168 +30,28 @@ bun run tauri build
bun run tauri android build
```
---
For the full set of build, test, and Android helper scripts, see
[scripts/README.md](scripts/README.md).
## 6. Architecture Overview
## Documentation
```
jellytau/
├── src/ # Svelte frontend
│ ├── lib/
│ │ ├── api/ # Jellyfin API client (repository pattern)
│ │ ├── components/ # UI components (player, library)
│ │ └── stores/ # Svelte stores (auth, library, player, queue)
│ └── routes/ # SvelteKit pages
├── src-tauri/ # Rust backend
│ ├── src/
│ │ ├── commands/ # Tauri commands
│ │ └── player/ # Player architecture
│ │ ├── state.rs # State machine
│ │ ├── media.rs # MediaItem, MediaSource
│ │ ├── queue.rs # Queue management
│ │ └── backend.rs # PlayerBackend trait
│ └── gen/android/ # Android project
└── README.md
```
| Topic | Location |
|-------|----------|
| Architecture overview & subsystem docs | [docs/architecture/](docs/architecture/) |
| Requirements, traceability & technical debt | [docs/requirements.md](docs/requirements.md) |
| Build & release process | [docs/build-release.md](docs/build-release.md) |
| Docker builds | [docs/build/docker.md](docs/build/docker.md) |
| Traceability tooling & CI | [docs/traceability.md](docs/traceability.md), [docs/traceability-ci.md](docs/traceability-ci.md) |
| Release checklist | [docs/release-checklist.md](docs/release-checklist.md) |
| UX flows | [docs/ux-flows.md](docs/ux-flows.md) |
---
## Recommended IDE Setup
## 7. Technical Debt
[VS Code](https://code.visualstudio.com/) +
[Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) +
[Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) +
[rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer).
### Linux Keyring Integration Workaround
## License
**Issue**: The `keyring-rs` crate (v3.x) has issues with retrieving credentials from the Linux Secret Service API, despite successfully saving them.
**Symptoms**:
- Credentials are saved to the system keyring successfully (verified with `secret-tool search`)
- Retrieval via the `keyring-rs` library fails with `NoEntry` error
- Session restoration fails on app restart even though credentials exist
**Root Cause**:
The `keyring-rs` library's Linux backend doesn't correctly retrieve entries from the Secret Service that it previously stored. This appears to be a bug in how the library interfaces with the Secret Service D-Bus API.
**Current Workaround**:
We bypass the `keyring-rs` library on Linux and use direct system calls to `secret-tool`:
- **Save**: `secret-tool store --label <label> service <service> username <username>`
- **Retrieve**: `secret-tool lookup service <service> username <username>`
- **Delete**: `secret-tool clear service <service> username <username>`
**Implementation**:
See [src-tauri/src/credentials.rs](src-tauri/src/credentials.rs):
- Lines 165-209: `save_to_keyring()` - Uses `secret-tool store` on Linux
- Lines 214-248: `get_from_keyring()` - Uses `secret-tool lookup` on Linux
- Lines 254-286: `delete_from_keyring()` - Uses `secret-tool clear` on Linux
**Future Fix**:
- Monitor `keyring-rs` for bug fixes in future versions
- Consider alternative secure storage libraries
- Test if newer versions of `keyring-rs` (v4.x+) resolve the issue
- Once fixed, remove the Linux-specific workaround and use the cross-platform `keyring-rs` API
**Impact**:
- Low - The workaround is functionally equivalent to proper keyring integration
- Credentials are stored securely in the system keyring
- Session restoration works correctly
- Only affects Linux; macOS and Windows use the standard `keyring-rs` implementation
**Dependencies**:
- Requires `secret-tool` to be installed on Linux systems (part of `libsecret-tools` package)
- Already available on most Linux distributions by default
---
### Platform Playback Backend Parity (Linux vs Android)
**Issue**: The Linux (MPV) and Android (ExoPlayer) playback backends have diverged in feature implementation and architecture patterns.
**Symptoms**:
- Audio settings (crossfade, gapless playback, volume normalization) work on Linux but not on Android
- Position update frequency differs between platforms (Linux: 250ms polling, Android: on-demand callbacks)
- Thread safety models differ (Linux: `Arc<Mutex<>>`, Android: global `OnceLock` statics)
**Root Cause**:
The `PlayerBackend` trait defines optional audio settings methods with default empty implementations. The Linux `MpvBackend` overrides these with full MPV property commands, but `ExoPlayerBackend` uses the defaults.
**Affected Files**:
- [src-tauri/src/player/backend.rs:95-103](src-tauri/src/player/backend.rs) - Trait with default empty implementations
- [src-tauri/src/player/mpv/mod.rs](src-tauri/src/player/mpv/mod.rs) - Full audio settings support
- [src-tauri/src/player/android/mod.rs](src-tauri/src/player/android/mod.rs) - Missing audio settings implementation
**Feature Parity Matrix**:
| Feature | Linux (MPV) | Android (ExoPlayer) | Status |
|---------|-------------|---------------------|--------|
| Basic playback | ✅ | ✅ | Parity |
| Volume control | ✅ | ✅ | Parity |
| Seek | ✅ | ✅ | Parity |
| Crossfade | ✅ | ❌ | Gap |
| Gapless playback | ✅ | ❌ | Gap |
| Volume normalization | ✅ | ❌ | Gap |
| Position updates | 250ms | On-demand | Inconsistent |
**Future Fix**:
1. Implement `set_audio_settings()` in `ExoPlayerBackend`
2. Add Kotlin-side ExoPlayer configuration for crossfade (using `ConcatenatingMediaSource` or `DefaultMediaSourceFactory`)
3. Implement gapless via ExoPlayer's built-in gapless support
4. Add volume normalization via ExoPlayer's `LoudnessEnhancer` or audio processor
5. Standardize position update frequency across platforms
**Impact**:
- Medium - Android users lack audio enhancement features advertised in requirements
- User experience differs between platforms
- UR-031 (Crossfade), UR-032 (Gapless), UR-033 (Normalization) only work on Linux
**Traces To**: IR-004, UR-031, UR-032, UR-033, DR-034, DR-035, DR-036
---
### Frontend Playback Code Duplication
**Issue**: Playback control handlers and state derivations are duplicated between `AudioPlayer.svelte` and `MiniPlayer.svelte`.
**Symptoms**:
- Identical try-catch wrapped handler functions in both components (~44 lines duplicated)
- Same `$derived` state merging logic for local/remote playback in both components
- Position conversion (ticks ↔ seconds) scattered across multiple files
**Affected Files**:
- [src/lib/components/player/AudioPlayer.svelte:69-140](src/lib/components/player/AudioPlayer.svelte) - Duplicate handlers
- [src/lib/components/player/MiniPlayer.svelte:74-122](src/lib/components/player/MiniPlayer.svelte) - Duplicate handlers
- [src/lib/services/playbackControl.ts:88](src/lib/services/playbackControl.ts) - Position conversion
- [src/lib/stores/playbackMode.ts](src/lib/stores/playbackMode.ts) - Position conversion
- [src/lib/services/playbackReporting.ts](src/lib/services/playbackReporting.ts) - Position conversion
**Duplicated Code**:
```typescript
// These handlers are identical in both AudioPlayer and MiniPlayer:
handlePlayPause(), handleNext(), handlePrevious(),
handleToggleShuffle(), handleCycleRepeat(), handleVolumeChange()
// These derived states use identical logic:
displayMedia, displayIsPlaying, displayPosition, displayDuration
```
**Future Fix**:
1. Create `src/lib/utils/playbackUnits.ts`:
```typescript
export const TICKS_PER_SECOND = 10_000_000;
export const secondsToTicks = (s: number) => Math.floor(s * TICKS_PER_SECOND);
export const ticksToSeconds = (t: number) => t / TICKS_PER_SECOND;
```
2. Create `src/lib/composables/useMergedPlaybackState.svelte.ts`:
- Export `displayMedia`, `displayIsPlaying`, `displayPosition`, `displayDuration`
- Single source of truth for merged local/remote state
3. Simplify handler wrappers using a utility:
```typescript
export const withErrorHandler = (fn: () => Promise<void>, context: string) =>
async () => { try { await fn(); } catch (e) { console.error(`${context}:`, e); } };
```
**Impact**:
- Low - Code works correctly but violates DRY principle
- Maintenance burden when logic needs to change
- Risk of handlers diverging over time
**Traces To**: DR-009
MIT
+6 -3
View File
@@ -176,7 +176,10 @@ classDiagram
-server_url: String
-user_id: String
-access_token: String
-connectivity: Option~Arc~ConnectivityMonitor~~
+new()
+with_connectivity()
-report_outcome()
}
class OfflineRepository {
@@ -192,10 +195,9 @@ classDiagram
class HybridRepository {
-online: Arc~OnlineRepository~
-offline: Arc~OfflineRepository~
-connectivity: Arc~ConnectivityMonitor~
+new()
-parallel_query()
-has_meaningful_content()
-parallel_race()
-cache_with_timeout()
}
MediaRepository <|.. OnlineRepository
@@ -214,6 +216,7 @@ classDiagram
- Returns cache result if it has meaningful content
- Falls back to server result otherwise
- Background cache updates planned
- **Connectivity feedback**: `OnlineRepository` reports the outcome of every server request to the `ConnectivityMonitor` (classified via `RepoError`). This is the source of truth for the offline/online banner — see [07-connectivity.md](07-connectivity.md). The frontend `connectivity` store is a pure reflection of the resulting events; `navigator.onLine` is only an advisory hint that triggers an immediate recheck.
2. **Handle-Based Resource Management** (`repository.rs` commands):
```rust
+9
View File
@@ -10,6 +10,7 @@ sequenceDiagram
participant Hybrid as HybridRepository
participant Cache as OfflineRepository (SQLite)
participant Server as OnlineRepository (HTTP)
participant Conn as ConnectivityMonitor
UI->>Client: getItems(parentId)
Client->>Rust: invoke("repository_get_items", {handle, parentId})
@@ -20,6 +21,13 @@ sequenceDiagram
Hybrid->>Server: get_items() (no timeout)
end
Note over Server,Conn: Every server request reports its outcome
alt Server succeeds (or answers with 4xx/5xx)
Server->>Conn: mark_reachable() (server is up)
else Network failure / timeout
Server->>Conn: mark_unreachable() (debounced)
end
alt Cache returns with content
Cache-->>Hybrid: Result with items
Hybrid-->>Rust: Return cache result
@@ -39,6 +47,7 @@ sequenceDiagram
- Cache wins if it has meaningful content
- Automatic fallback to server if cache is empty/stale
- Background cache updates (planned)
- **Connectivity side-effect**: each server request feeds the `ConnectivityMonitor`, which is the source of truth for the offline/online banner (see [07-connectivity.md](07-connectivity.md)). A server-answered error (401/404/5xx) still counts as *reachable* — only network failures, sustained past a debounce window, flip the app to offline.
## Playback Initiation Flow
+61 -26
View File
@@ -13,12 +13,13 @@ pub struct HttpClient {
}
pub struct HttpConfig {
pub base_url: String,
pub timeout: Duration, // Default: 10s
pub timeout: Duration, // Default: 30s (large library queries can be slow)
pub max_retries: u32, // Default: 3
}
```
> Note: ordinary requests use the 30s timeout above. The connectivity recovery probe (`ping`) uses a shorter, dedicated 5s timeout so an unreachable server is detected quickly while offline.
**Retry Strategy:**
- Retry delays: 1s, 2s, 4s (exponential backoff)
- Retries on: Network errors, 5xx server errors
@@ -38,39 +39,71 @@ pub enum ErrorKind {
**Location**: `src-tauri/src/connectivity/mod.rs`
The connectivity monitor tracks server reachability with adaptive polling:
The connectivity monitor is the **single source of truth** for server reachability. Its primary signal is the outcome of *real repository traffic* — every server request the user actually makes. A standalone `/System/Info/Public` probe is kept only as an offline recovery detector.
### Source of truth: repository traffic
`OnlineRepository` reports the result of each server request to the monitor, classified via `RepoError`:
| Repository outcome | Meaning | Effect on reachability |
|--------------------|---------|------------------------|
| `Ok(_)` | Server answered successfully | Mark **reachable** (instant recovery) |
| `Err(Authentication)` | Server answered with 401/403 | Mark **reachable** (server is up; request was rejected) |
| `Err(NotFound)` | Server answered with 404 | Mark **reachable** (server is up) |
| `Err(Server)` | Server answered with 5xx / bad body | Mark **reachable** (server is up) |
| `Err(Network)` | Connection failure / timeout / DNS | **Candidate for offline** (see debounce) |
| `Err(Database)` | Local cache error only | No effect (not a server signal) |
This classification fixes the previous bug where a successful `/System/Info/Public` ping reported "online" even while the user's authenticated data calls were failing — and vice versa.
### Time-window debounce (offline) + instant recovery (online)
To stop the banner from flapping on a single dropped request, the transition to **offline** is debounced over a time window:
- On the **first** `Network` failure, the monitor records `first_failure_at`.
- It flips `is_server_reachable = false` only once `Network` failures have persisted continuously for `OFFLINE_CONFIRM_WINDOW` (5s) with no intervening success.
- **Any** success (or server-answered error) clears `first_failure_at` and immediately marks reachable.
Recovery is therefore instant and asymmetric: one good response brings the app back online, but a brief blip never trips the banner.
### Offline-only recovery probe
```mermaid
flowchart TB
Monitor["ConnectivityMonitor"] --> Poller["Background Task"]
Poller --> Check{"Server<br/>Reachable?"}
Check -->|"Yes"| Online["30s Interval"]
Check -->|"No"| Offline["5s Interval"]
Online --> Emit["Emit Events"]
Offline --> Emit
Emit --> Frontend["Frontend Store"]
Repo["OnlineRepository"] -->|"success / RepoError"| Monitor["ConnectivityMonitor"]
Monitor --> State{"is_server_reachable?"}
State -->|"Online"| NoProbe["No background polling<br/>(real traffic is the signal)"]
State -->|"Offline"| Probe["5s /System/Info/Public probe<br/>(recovery detector)"]
Probe -->|"reachable again"| Monitor
Monitor -->|"on change"| Emit["Emit connectivity:changed<br/>+ connectivity:reconnected"]
Emit --> Frontend["Frontend Store → banner"]
```
While **online**, there is no background polling — real requests keep the state fresh. While **offline**, the fast 5s probe runs so an idle app still detects the server returning even when no user traffic is flowing.
**Features:**
- **Adaptive Polling**: 30s when online, 5s when offline (for quick reconnection detection)
- **Event Emission**: Emits `connectivity:changed` and `connectivity:reconnected` events
- **Manual Marking**: Can mark reachable/unreachable based on API call results
- **Thread-Safe**: Uses Arc<RwLock<>> for shared state
- **Traffic-driven**: Reachability follows the requests the user actually makes.
- **Time-window debounce**: Offline declared only after `OFFLINE_CONFIRM_WINDOW` (5s) of sustained network failure; recovery is instant.
- **Offline-only probe**: 5s `/System/Info/Public` probe runs only while offline.
- **Event Emission**: Emits `connectivity:changed` and `connectivity:reconnected` events.
- **Thread-Safe**: Uses `Arc<RwLock<>>` for shared state.
**Tauri Commands:**
| Command | Description |
|---------|-------------|
| `connectivity_check_server` | Manual reachability check |
| `connectivity_check_server` | Manual reachability check (also used by the frontend's advisory `navigator.onLine` hint) |
| `connectivity_set_server_url` | Update monitored server URL |
| `connectivity_get_status` | Get current connectivity status |
| `connectivity_start_monitoring` | Start background monitoring |
| `connectivity_stop_monitoring` | Stop monitoring |
| `connectivity_mark_reachable` | Mark server as reachable (after successful API call) |
| `connectivity_mark_unreachable` | Mark server as unreachable (after failed API call) |
| `connectivity_start_monitoring` | Start the offline recovery probe |
| `connectivity_stop_monitoring` | Stop the probe |
| `connectivity_mark_reachable` | Mark reachable — driven by `OnlineRepository` on every server success |
| `connectivity_mark_unreachable` | Mark unreachable — driven by `OnlineRepository` on `RepoError::Network` (subject to debounce) |
**Frontend Integration:**
```typescript
// TypeScript store listens to Rust events
// The store is a pure reflection of backend events — it no longer decides
// reachability itself. navigator.onLine is advisory: it triggers an immediate
// recheck rather than forcing the offline state.
listen<{ isReachable: boolean }>("connectivity:changed", (event) => {
updateConnectivityState(event.payload.isReachable);
});
@@ -81,12 +114,14 @@ listen<{ isReachable: boolean }>("connectivity:changed", (event) => {
The connectivity system provides resilience through multiple layers:
1. **HTTP Client Layer**: Automatic retry with exponential backoff
2. **Connectivity Monitoring**: Background reachability checks
3. **Frontend Integration**: Offline mode detection and UI updates
2. **Connectivity Monitoring**: Reachability derived from real repository traffic, with an offline-only recovery probe
3. **Frontend Integration**: Offline mode detection and UI updates (a pure reflection of backend events)
4. **Sync Queue**: Offline mutations queued for later (see [06-downloads-and-offline.md](06-downloads-and-offline.md))
**Design Principles:**
- **Fail Fast**: Don't retry 4xx errors (client errors, authentication)
- **Fail Slow**: Retry network and 5xx errors with increasing delays
- **Adaptive Polling**: Reduce polling frequency when online, increase when offline
- **Event-Driven**: Frontend reacts to connectivity changes via events
- **Single source of truth**: Reachability follows the outcome of real requests, classified via `RepoError`; the frontend store and the probe never compete to decide it.
- **Fail Fast**: Don't retry 4xx errors (client errors, authentication).
- **Fail Slow**: Retry network and 5xx errors with increasing delays.
- **Debounced offline, instant online**: Declare offline only after a sustained failure window; recover on the first success.
- **Probe only when needed**: Background polling runs only while offline, as a recovery detector.
- **Event-Driven**: Frontend reacts to connectivity changes via events.
@@ -2,19 +2,22 @@
This document describes the current architecture of JellyTau, a cross-platform Jellyfin client built with Tauri, SvelteKit, and Rust.
**Last Updated:** 2026-03-01
**Last Updated:** 2026-06-20
## Architecture Overview
JellyTau uses a modern client-server architecture with a thin Svelte UI layer and comprehensive Rust backend:
JellyTau uses a client-server architecture: business logic lives in a comprehensive Rust backend, while a UI-rich Svelte frontend handles presentation and interaction.
### Architecture Principles
- **Thin UI Layer**: TypeScript reduced from ~3,300 to ~800 lines
- **Business Logic in Rust**: Performance, reliability, type safety
- **Event-Driven**: Rust emits events, TypeScript listens and updates UI
- **Handle-Based Resources**: UUID handles for stateful Rust objects
- **Cache-First**: Parallel queries with intelligent fallback
- **Business Logic in Rust**: Core logic — playback, repository, sync, downloads, connectivity — lives in Rust for performance, reliability, and type safety.
- **Presentation in Svelte**: The frontend (~20.5k non-test lines) owns UI, layout, navigation, and interaction state and invokes Rust commands. It is intentionally UI-heavy, **not** a thin wrapper. Largest pieces: components + routes (~14.6k lines), stores (~3.4k), api/services/utils (~2.4k); `VideoPlayer.svelte` alone is ~1.6k lines.
- **Events + Polling hybrid**: Rust emits events the frontend listens to, and the UI also polls status on short intervals in a few hot spots (e.g. queue status in `library/+layout.svelte`, playback progress in `VideoPlayer.svelte`).
- **Handle-Based Resources**: UUID handles for stateful Rust objects.
- **Cache-First**: Parallel queries with intelligent fallback.
- **Single source of truth for reachability**: Server reachability is derived from the outcome of *real repository traffic*, not a side-channel poller. The `OnlineRepository` reports each server result to the `ConnectivityMonitor` (classified via `RepoError`), which applies a time-window debounce before declaring the server offline and recovers instantly on the first success. The standalone `/System/Info/Public` probe runs *only while offline*, as a recovery detector for idle sessions.
- **Poison-tolerant locking**: Shared `std::sync` state is accessed via the `MutexSafe`/`RwLockSafe` helpers in `utils/lock.rs`, which recover a poisoned lock instead of cascading a panic across the player.
- **Graceful backend init**: If a native player backend (MPV/ExoPlayer) fails to initialize, the app falls back to a no-op backend and emits a `backend-init-failed` event rather than crashing.
```mermaid
flowchart TB
@@ -77,26 +80,29 @@ flowchart TB
Core --> Storage
Repository --> HttpClient
Repository --> DatabaseService
Repository -->|"reports server outcome<br/>(success / RepoError)"| ConnectivityMonitor
end
```
> The `Repository --> ConnectivityMonitor` edge is the source of truth for the offline/online banner: every server request the user actually makes updates reachability. The monitor's own polling is now an offline-only recovery probe (see [07-connectivity.md](07-connectivity.md)).
---
## Detailed Documentation
Each major subsystem is documented in its own file under [docs/architecture/](docs/architecture/):
Each major subsystem is documented in its own file in this directory:
| Document | Contents |
|----------|----------|
| [01 - Rust Backend](docs/architecture/01-rust-backend.md) | Media session state machine, player state machine, playback mode, media items, queue manager, favorites, player backend trait, player controller, playlist system, Tauri commands |
| [02 - Svelte Frontend](docs/architecture/02-svelte-frontend.md) | Store structure, music library navigation, playback reporting, repository architecture, playback mode system, database service abstraction, component hierarchy, MiniPlayer, sleep timer, auto-play, navigation guard, playlist management UI |
| [03 - Data Flow](docs/architecture/03-data-flow.md) | Repository query flow (cache-first), playback initiation, playback mode transfer, queue navigation, volume control |
| [04 - Type Sync & Threading](docs/architecture/04-type-sync-and-threading.md) | Rust/TypeScript type synchronization, Tauri v2 IPC parameter naming convention, thread safety patterns |
| [05 - Platform Backends](docs/architecture/05-platform-backends.md) | Player events system, MpvBackend (Linux), ExoPlayerBackend (Android), MediaSession & remote volume, album art caching, backend initialization |
| [06 - Downloads & Offline](docs/architecture/06-downloads-and-offline.md) | Download manager, download worker, smart caching engine, download/offline commands, player integration, frontend store, UI components |
| [07 - Connectivity](docs/architecture/07-connectivity.md) | HTTP client with retry logic, connectivity monitor, network resilience architecture |
| [08 - Database Design](docs/architecture/08-database-design.md) | Entity relationships, all table definitions (servers, users, libraries, items, user_data, downloads, media_streams, sync_queue, thumbnails, playlists), key queries, data flow diagrams, storage estimates |
| [09 - Security](docs/architecture/09-security.md) | Authentication token storage, secure storage module, network security, local data protection |
| [01 - Rust Backend](01-rust-backend.md) | Media session state machine, player state machine, playback mode, media items, queue manager, favorites, player backend trait, player controller, playlist system, Tauri commands |
| [02 - Svelte Frontend](02-svelte-frontend.md) | Store structure, music library navigation, playback reporting, repository architecture, playback mode system, database service abstraction, component hierarchy, MiniPlayer, sleep timer, auto-play, navigation guard, playlist management UI |
| [03 - Data Flow](03-data-flow.md) | Repository query flow (cache-first), playback initiation, playback mode transfer, queue navigation, volume control |
| [04 - Type Sync & Threading](04-type-sync-and-threading.md) | Rust/TypeScript type synchronization, Tauri v2 IPC parameter naming convention, thread safety patterns |
| [05 - Platform Backends](05-platform-backends.md) | Player events system, MpvBackend (Linux), ExoPlayerBackend (Android), MediaSession & remote volume, album art caching, backend initialization |
| [06 - Downloads & Offline](06-downloads-and-offline.md) | Download manager, download worker, smart caching engine, download/offline commands, player integration, frontend store, UI components |
| [07 - Connectivity](07-connectivity.md) | HTTP client with retry logic, connectivity monitor, network resilience architecture |
| [08 - Database Design](08-database-design.md) | Entity relationships, all table definitions (servers, users, libraries, items, user_data, downloads, media_streams, sync_queue, thumbnails, playlists), key queries, data flow diagrams, storage estimates |
| [09 - Security](09-security.md) | Authentication token storage, secure storage module, network security, local data protection |
---
@@ -185,16 +191,16 @@ src/lib/
**What moved to Rust (~3,500 lines of business logic):**
1. **HTTP Client** (338 lines) - Retry logic with exponential backoff
2. **Connectivity Monitor** (301 lines) - Adaptive polling, event emission
2. **Connectivity Monitor** (301 lines) - Reachability derived from real repository traffic, time-window debounce, offline-only recovery probe, event emission
3. **Repository Pattern** (1061 lines) - Cache-first hybrid with parallel racing
4. **Database Service** - Async wrapper preventing UI freezing
5. **Playback Mode** (303 lines) - Local/remote transfer coordination
**TypeScript Layer (now ~800 lines, down from ~3,300):**
- Svelte stores (reactive wrappers)
- Type definitions
- UI event handling
- Tauri command invocation
- Event listeners for Rust events
**Svelte/TypeScript frontend (~20.5k non-test lines, plus ~9.6k test lines):**
- Components + routes (~14.6k lines) — UI and presentation
- Stores (~3.4k lines) — reactive state that invokes Rust commands and listens for events
- api / services / utils (~2.4k lines) — typed clients, event listeners, conversion helpers
The frontend is genuinely UI-heavy; business decisions live in Rust, but the UI owns layout, navigation, and interaction state.
**Total Commands:** 90+ Tauri commands across 14 command modules
View File
+454
View File
@@ -0,0 +1,454 @@
# Requirements Specification
This document captures JellyTau's user requirements, software requirements,
traceability matrix, test traceability, and known technical debt.
For a narrative overview of the system design, see
[docs/architecture/](architecture/). For development workflows, see the
[README](../README.md) and [scripts/README.md](../scripts/README.md).
## 1. User Requirements
| ID | Requirement | Priority | Status |
|----|-------------|----------|--------|
| UR-001 | Run the app on multiple platforms (Linux, Android) | High | In Progress |
| UR-002 | Access media when online or offline | High | Done |
| UR-003 | Play videos | High | Done |
| UR-004 | Play audio uninterrupted | High | Done |
| UR-005 | Control media playback (pause, play, skip, scrub) | High | Done |
| UR-006 | Control media when device is on lock screen or via BLE headsets | Medium | Done |
| UR-007 | Navigate media in library | High | Done |
| UR-008 | Search media across libraries | High | Done |
| UR-009 | Connect to Jellyfin to access media | High | Done |
| UR-010 | Control playback of Jellyfin remote sessions | Low | Done |
| UR-011 | Download media on demand | Medium | Done |
| UR-012 | Login info shall be stored securely and persistently | High | Done |
| UR-013 | View and manage downloaded media | Medium | Done |
| UR-014 | Make and edit playlists of music that sync back to Jellyfin | Medium | Done |
| UR-015 | View and manage current audio queue (add, reorder tracks) | Medium | Done |
| UR-016 | Change system settings while playing (brightness, volume) | Low | Planned |
| UR-017 | Like or unlike audio, albums, movies, etc. | Medium | Done |
| UR-018 | Choose to download series, albums, songs, artist discography | Medium | Done |
| UR-019 | Resume playback from where you left off (movies, shows, albums) | High | Done |
| UR-020 | Select subtitles for video content | High | Done |
| UR-021 | Select audio track for video content | High | Done |
| UR-022 | Control streaming quality and transcoding settings | Medium | Planned |
| UR-023 | View "Next Up" / Continue Watching on home screen; auto-play next episode with countdown popup and configurable episode limit | Medium | Done |
| UR-024 | View recently added content on server | Medium | Done |
| UR-025 | Sync watch history and progress back to Jellyfin | High | Done |
| UR-026 | Sleep timer for audio and video playback (roller UI, time/track/episode modes) | Low | Done |
| UR-027 | Audio equalizer for sound customization | Low | Planned |
| UR-028 | Navigate to artist/album by tapping names in now playing view | High | Done |
| UR-029 | Toggle between grid and list view in library | Medium | Done |
| UR-030 | Quick genre browsing and filtering | Medium | Done |
| UR-031 | Crossfade between audio tracks | Low | Done (Linux only) |
| UR-032 | Gapless playback for seamless album listening | Medium | Done (Linux only) |
| UR-033 | Volume normalization to prevent volume jumps between tracks | Low | Done (Linux only) |
| UR-034 | Rich home screen with hero banners, carousels, and personalized sections | High | Done |
| UR-035 | View cast/crew (actors, directors) on movie/show detail pages | High | Done |
| UR-036 | Navigate to actor/person page showing their filmography | Medium | Done |
| UR-037 | Visually appealing video library with poster grids and metadata | High | Done |
| UR-038 | Movie/show detail page with backdrop, ratings, and rich metadata | High | Done |
| UR-039 | Navigate between main sections via bottom navigation bar | High | Done |
---
## 2. Software Requirements
### 2.1 Integration Requirements
External system integrations and platform-specific implementations.
| ID | Requirement | Category | Traces To | Status |
|----|-------------|----------|-----------|--------|
| IR-001 | Build system supporting multiple targets (Linux, Android) | Build | UR-001 | Done |
| IR-002 | Build scripts for Android and Linux | Build | UR-001 | Done |
| IR-003 | Integration of libmpv for Linux playback | Playback | UR-003, UR-004 | Done |
| IR-004 | Integration of ExoPlayer for Android playback | Playback | UR-003, UR-004 | In Progress (basic playback works, audio settings missing) |
| IR-005 | MPRIS D-Bus integration for Linux lockscreen/media controls | Platform | UR-006 | Planned |
| IR-006 | Android MediaSession integration for lockscreen controls | Platform | UR-006 | Done |
| IR-007 | Bluetooth AVRCP integration via system media session | Platform | UR-006 | Planned |
| IR-008 | Android audio focus handling (pause on call) | Platform | UR-004, UR-006 | Done |
| IR-009 | Jellyfin API client for authentication | API | UR-009, UR-012 | Done |
| IR-010 | Jellyfin API client for library browsing | API | UR-007, UR-008 | Done |
| IR-011 | Jellyfin API client for playback streaming | API | UR-003, UR-004 | Done |
| IR-012 | Jellyfin Sessions API for remote playback control | API | UR-010 | Done |
| IR-021 | Android MediaRouter integration for remote volume in system panel | Platform | UR-010, UR-016 | Planned |
| IR-013 | SQLite integration for local database | Storage | UR-002, UR-011 | Done |
| IR-014 | Secure credential storage (keyring/keychain) | Security | UR-012 | Done |
| IR-015 | Jellyfin API client for playback progress reporting | API | UR-019, UR-025 | Done |
| IR-016 | Jellyfin API client for subtitle/audio track info | API | UR-020, UR-021 | Done |
| IR-017 | Jellyfin API client for transcoding parameters | API | UR-022 | Planned |
| IR-018 | libmpv subtitle rendering and selection | Playback | UR-020 | Planned |
| IR-019 | libmpv audio track selection | Playback | UR-021 | Planned |
| IR-020 | libmpv/ExoPlayer equalizer integration | Playback | UR-027 | Planned |
| IR-022 | Jellyfin API client for person/cast data | API | UR-035, UR-036 | Done |
| IR-023 | Database schema for person/cast caching | Storage | UR-035, UR-036 | Done |
| IR-024 | Jellyfin API client for home screen data (featured, continue watching) | API | UR-034 | Done |
### 2.2 Jellyfin API Requirements
API endpoints and data contracts required for Jellyfin integration.
| ID | Requirement | Endpoint Category | Traces To | Status |
|----|-------------|-------------------|-----------|--------|
| JA-001 | Server connection and discovery | System | UR-009 | Done |
| JA-002 | User authentication (username/password) | Users | UR-009, UR-012 | Done |
| JA-003 | Get user library views | UserViews | UR-007 | Done |
| JA-004 | Get library items (paginated) | Items | UR-007 | Done |
| JA-005 | Get item details and metadata | Items | UR-007 | Done |
| JA-006 | Search across libraries | Items | UR-008 | Done |
| JA-007 | Get playback info and stream URL | MediaInfo | UR-003, UR-004 | Done |
| JA-008 | Get available subtitles for item | MediaInfo | UR-020 | Done |
| JA-009 | Get available audio tracks for item | MediaInfo | UR-021 | Done |
| JA-010 | Report playback start | Sessions | UR-025 | Done |
| JA-011 | Report playback progress (periodic) | Sessions | UR-025 | Done |
| JA-012 | Report playback stopped | Sessions | UR-025 | Done |
| JA-013 | Get resume position for item | UserData | UR-019 | Done |
| JA-014 | Get "Next Up" items | Shows | UR-023 | Done |
| JA-015 | Get "Continue Watching" items | Items | UR-023 | Done |
| JA-016 | Get recently added items | Items | UR-024 | Done |
| JA-017 | Mark item as favorite | UserData | UR-017 | Done |
| JA-018 | Remove item from favorites | UserData | UR-017 | Done |
| JA-019 | Get/create/update playlists | Playlists | UR-014 | Done |
| JA-020 | Add/remove items from playlist | Playlists | UR-014 | Done |
| JA-021 | Get active sessions list | Sessions | UR-010 | Done |
| JA-022 | Send playback commands to remote session (play/pause/stop) | Sessions | UR-010 | Done |
| JA-023 | Send seek command to remote session | Sessions | UR-010 | Done |
| JA-024 | Send next/previous track commands to remote session | Sessions | UR-010 | Done |
| JA-025 | Play specific item on remote session | Sessions | UR-010 | Done |
| JA-026 | Send volume/mute commands to remote session | Sessions | UR-010 | Done |
| JA-027 | Get transcoding options | MediaInfo | UR-022 | Planned |
| JA-028 | Get image/artwork URLs | Images | UR-007 | Done |
| JA-029 | Get cast/crew for item (actors, directors) | Items | UR-035 | Done |
| JA-030 | Get person details and filmography | Persons | UR-036 | Done |
| JA-031 | Get items by person (actor/director filmography) | Items | UR-036 | Done |
### 2.3 Development Requirements
Internal architecture, components, and application logic.
| ID | Requirement | Category | Traces To | Status |
|----|-------------|----------|-----------|--------|
| DR-001 | Player state machine (idle, loading, playing, paused, seeking, error) | Player | UR-005 | Done |
| DR-002 | MediaItem struct tracking source, location, duration, metadata | Player | UR-003, UR-004 | Done |
| DR-003 | Source-agnostic media abstraction (Remote, Local, DirectUrl) | Player | UR-002, UR-011 | Done |
| DR-004 | PlayerBackend trait for platform-agnostic playback | Player | UR-003, UR-004 | Done |
| DR-005 | Queue manager with shuffle, repeat, history | Player | UR-005, UR-015 | Done |
| DR-006 | Audio pre-caching for seamless track transitions | Player | UR-004 | Planned |
| DR-007 | Library browsing screens (grid view, search, filters) | UI | UR-007, UR-008 | Done |
| DR-008 | Album/Series detail view with track listing | UI | UR-007 | Done |
| DR-009 | Audio player UI (mini player, full screen) | UI | UR-005 | Done |
| DR-010 | Video player UI (fullscreen, controls overlay) | UI | UR-003, UR-005 | Done |
| DR-011 | Search bar with cross-library search | UI | UR-008 | Done |
| DR-012 | Local database for media metadata cache | Storage | UR-002 | Done |
| DR-013 | Repository pattern for online/offline data access | Storage | UR-002 | Done |
| DR-014 | Offline mutation queue for sync-back operations | Storage | UR-002, UR-014, UR-017 | Done |
| DR-015 | Download manager with queue and progress tracking | Storage | UR-011, UR-018 | Done |
| DR-016 | Thumbnail caching and sync with server | Storage | UR-007 | Done |
| DR-017 | "Manage Downloads" screen for local media management | UI | UR-013 | Done |
| DR-018 | Download buttons on library/album/player screens | UI | UR-011, UR-018 | Done |
| DR-019 | Playlist creation and editing UI | UI | UR-014 | Done |
| DR-020 | Queue management UI (add, remove, reorder) | UI | UR-015 | Done |
| DR-021 | Like/favorite functionality on media items | UI | UR-017 | Done |
| DR-022 | Resume position tracking and restoration on play | Player | UR-019 | Done |
| DR-023 | Subtitle selection UI in video player | UI | UR-020 | Done |
| DR-024 | Audio track selection UI in video player | UI | UR-021 | Done |
| DR-025 | Quality/transcoding settings UI | UI | UR-022 | Planned |
| DR-026 | "Continue Watching" / "Next Up" home section | UI | UR-023 | Done |
| DR-027 | "Recently Added" home section | UI | UR-024 | Done |
| DR-028 | Playback progress sync service (periodic reporting) | Player | UR-025 | Done |
| DR-029 | Sleep timer with roller UI, time/track/episode modes, and auto-stop (audio + video players) | Player | UR-026 | Done |
| DR-049 | Auto-play episode limit (configurable max episodes per session) | Player | UR-023 | Done |
| DR-050 | Reusable scroll picker (roller) component | UI | UR-026 | Done |
| DR-030 | Equalizer UI with presets and custom bands | UI | UR-027 | Planned |
| DR-031 | Clickable artist/album links in now playing view | UI | UR-028 | Done |
| DR-032 | List view option for library browsing (albums, artists) | UI | UR-029 | Done |
| DR-033 | Genre browsing screen with quick filters | UI | UR-030 | Done |
| DR-034 | Crossfade engine with configurable duration (0-12s) | Player | UR-031 | Done (Linux only) |
| DR-035 | Gapless playback between sequential tracks | Player | UR-032 | Done (Linux only) |
| DR-036 | Volume normalization with preset levels (Loud/Normal/Quiet) | Player | UR-033 | Done (Linux only) |
| DR-037 | Remote session browser and control UI | UI | UR-010 | Done |
| DR-038 | Home screen with hero banner carousel (featured/continue watching) | UI | UR-034 | Done |
| DR-039 | Home screen horizontal carousels (recently added, recommendations) | UI | UR-034, UR-024 | Done |
| DR-040 | Cast/crew section on movie/show detail pages | UI | UR-035 | Done |
| DR-041 | Person/actor detail page with filmography grid | UI | UR-036 | Done |
| DR-042 | Video library grid with poster cards, year, and rating badges | UI | UR-037 | Done |
| DR-043 | Movie/show detail page with backdrop hero, synopsis, and metadata | UI | UR-038 | Done |
| DR-044 | Horizontal scrolling actor/cast row with profile images | UI | UR-035 | Done |
| DR-045 | Bottom navigation bar with Home, Library, Search buttons | UI | UR-039 | Done |
| DR-046 | Dedicated search page with input and results | UI | UR-039 | Done |
| DR-047 | Next episode auto-play popup with configurable countdown and episode limit | Player | UR-023 | Done |
| DR-048 | Video settings (auto-play toggle, countdown duration, episode limit) | Settings | UR-023, UR-026 | Done |
---
## 3. Traceability Matrix
### User Requirements to Software Requirements
| User Req | Integration Requirements | Development Requirements |
|----------|-------------------------|-------------------------|
| UR-001 | IR-001, IR-002 | - |
| UR-002 | IR-013 | DR-003, DR-012, DR-013, DR-014 |
| UR-003 | IR-003, IR-004, IR-011 | DR-002, DR-004, DR-010 |
| UR-004 | IR-003, IR-004, IR-008, IR-011 | DR-002, DR-004, DR-006 |
| UR-005 | - | DR-001, DR-005, DR-009 |
| UR-006 | IR-005, IR-006, IR-007, IR-008 | - |
| UR-007 | IR-010 | DR-007, DR-008, DR-016 |
| UR-008 | IR-010 | DR-007, DR-011 |
| UR-009 | IR-009, IR-010, IR-011 | - |
| UR-010 | IR-012, IR-021 | DR-037 |
| UR-011 | IR-013 | DR-003, DR-015, DR-018 |
| UR-012 | IR-009, IR-014 | - |
| UR-013 | IR-013 | DR-017 |
| UR-014 | IR-010 | DR-014, DR-019 |
| UR-015 | - | DR-005, DR-020 |
| UR-016 | - | - |
| UR-017 | - | DR-014, DR-021 |
| UR-018 | IR-013 | DR-015, DR-018 |
| UR-019 | IR-015 | DR-022 |
| UR-020 | IR-016, IR-018 | DR-023 |
| UR-021 | IR-016, IR-019 | DR-024 |
| UR-022 | IR-017 | DR-025 |
| UR-023 | IR-010 | DR-026, DR-047, DR-048, DR-049 |
| UR-024 | IR-010 | DR-027 |
| UR-025 | IR-015 | DR-028 |
| UR-026 | - | DR-029, DR-048, DR-050 |
| UR-027 | IR-020 | DR-030 |
| UR-028 | - | DR-031 |
| UR-029 | - | DR-032 |
| UR-030 | IR-010 | DR-033 |
| UR-031 | - | DR-034 |
| UR-032 | - | DR-035 |
| UR-033 | - | DR-036 |
| UR-034 | IR-010, IR-024 | DR-038, DR-039 |
| UR-035 | IR-022, IR-023 | DR-040, DR-044 |
| UR-036 | IR-022, IR-023 | DR-041 |
| UR-037 | IR-010 | DR-042 |
| UR-038 | IR-010 | DR-043 |
| UR-039 | - | DR-045, DR-046 |
---
## 4. Test Traceability
### Unit Tests to Software Requirements
| Test ID | Test Description | Traces To | Status |
|---------|-----------------|-----------|--------|
| UT-001 | Player state transitions | DR-001 | Pending |
| UT-002 | MediaItem source URL resolution | DR-002, DR-003 | Pending |
| UT-003 | Queue next/previous navigation | DR-005 | Pending |
| UT-004 | Queue shuffle order generation | DR-005 | Pending |
| UT-005 | Queue repeat mode behavior | DR-005 | Pending |
| UT-006 | Jellyfin authentication flow | IR-009 | Pending |
| UT-007 | Jellyfin library items parsing | IR-010 | Pending |
| UT-008 | Repository pattern online/offline switching | DR-013 | Pending |
| UT-009 | Offline mutation queue persistence | DR-014 | Pending |
| UT-010 | Download queue management | DR-015 | Done |
| UT-011 | Resume position storage and retrieval | DR-022 | Pending |
| UT-012 | Sleep timer countdown logic | DR-029 | Pending |
| UT-013 | Playback progress reporting throttling | DR-028 | Pending |
| UT-014 | Database open and in-memory mode | IR-013, DR-012 | Done |
| UT-015 | Database migrations run successfully | IR-013, DR-012 | Done |
| UT-016 | All database tables created | IR-013, DR-012 | Done |
| UT-017 | FTS5 search table created | IR-013, DR-012 | Done |
| UT-018 | Server CRUD operations | IR-013, DR-012 | Done |
| UT-019 | User CRUD operations | IR-013, DR-012 | Done |
| UT-020 | Cascade delete server removes users | IR-013, DR-012 | Done |
| UT-021 | Item insert and FTS search | IR-013, DR-012 | Done |
| UT-022 | User data playback position storage | IR-013, DR-012, DR-022 | Done |
| UT-023 | Sync queue operations | IR-013, DR-014 | Done |
| UT-024 | Downloads table operations | IR-013, DR-015 | Done |
| UT-025 | Migrations are idempotent | IR-013, DR-012 | Done |
| UT-026 | NullBackend volume default value | DR-004 | Done |
| UT-027 | NullBackend set volume | DR-004 | Done |
| UT-028 | NullBackend volume clamping (high/low) | DR-004 | Done |
| UT-029 | NullBackend volume boundary values | DR-004 | Done |
| UT-030 | PlayerController volume default | DR-004, DR-009 | Done |
| UT-031 | PlayerController set volume | DR-004, DR-009 | Done |
| UT-032 | PlayerController muted default | DR-004, DR-009 | Done |
| UT-033 | PlayerController volume delegates to backend | DR-004, DR-009 | Done |
| UT-034 | Download event serialization roundtrip | DR-015 | Done |
| UT-035 | Download event completed serialization | DR-015 | Done |
| UT-036 | Download event failed serialization | DR-015 | Done |
| UT-037 | Download worker exponential backoff | DR-015 | Done |
| UT-038 | Download worker error retryable check | DR-015 | Done |
| UT-039 | Download manager creation | DR-015 | Done |
| UT-040 | Download manager set max concurrent | DR-015 | Done |
| UT-041 | Download info serialization | DR-015 | Done |
| UT-042 | Download command filename sanitization | DR-015, DR-018 | Done |
| UT-043 | Download command filename extension preservation | DR-015, DR-018 | Done |
| UT-044 | Offline item serialization | DR-017 | Done |
| UT-045 | Smart cache default config | DR-015 | Done |
| UT-046 | Smart cache album affinity tracking | DR-015 | Done |
| UT-047 | Smart cache queue precache config | DR-015 | Done |
| UT-048 | Smart cache storage limit check | DR-015 | Done |
| UT-049 | Playlist create (offline) | DR-019, JA-019 | Done |
| UT-050 | Playlist delete (offline) | DR-019, JA-019 | Done |
| UT-051 | Playlist rename (offline) | DR-019, JA-019 | Done |
| UT-052 | Playlist get items (offline) | DR-019, JA-019 | Done |
| UT-053 | Playlist add items (offline) | DR-019, JA-020 | Done |
| UT-054 | Playlist remove items (offline) | DR-019, JA-020 | Done |
| UT-055 | Playlist reorder items (offline) | DR-019, JA-020 | Done |
| UT-056 | Playlist entry serialization | DR-019, JA-019 | Done |
| UT-057 | Playlist Tauri command param naming (camelCase) | DR-019, JA-019, JA-020 | Done |
| UT-058 | Playlist repository client methods | DR-019, JA-019, JA-020 | Done |
### Integration Tests
| Test ID | Test Description | Traces To | Status |
|---------|-----------------|-----------|--------|
| IT-001 | End-to-end authentication with Jellyfin server | IR-009, UR-009 | Pending |
| IT-002 | Library browsing and item loading | IR-010, UR-007 | Pending |
| IT-003 | Audio playback via libmpv | IR-003, UR-004 | Pending |
| IT-004 | Video playback via libmpv | IR-003, UR-003 | Pending |
| IT-005 | MPRIS lockscreen controls on Linux | IR-005, UR-006 | Pending |
| IT-006 | Offline mode with local database | IR-013, UR-002 | Pending |
| IT-007 | Media download and local playback | DR-015, UR-011 | Pending |
| IT-008 | Subtitle track selection via libmpv | IR-018, UR-020 | Pending |
| IT-009 | Audio track selection via libmpv | IR-019, UR-021 | Pending |
| IT-010 | Playback progress sync to Jellyfin | IR-015, UR-025 | Pending |
| IT-011 | Resume playback from server position | IR-015, UR-019 | Pending |
| IT-012 | Equalizer bands via libmpv | IR-020, UR-027 | Pending |
---
## 5. Technical Debt
### Linux Keyring Integration Workaround
**Issue**: The `keyring-rs` crate (v3.x) has issues with retrieving credentials from the Linux Secret Service API, despite successfully saving them.
**Symptoms**:
- Credentials are saved to the system keyring successfully (verified with `secret-tool search`)
- Retrieval via the `keyring-rs` library fails with `NoEntry` error
- Session restoration fails on app restart even though credentials exist
**Root Cause**:
The `keyring-rs` library's Linux backend doesn't correctly retrieve entries from the Secret Service that it previously stored. This appears to be a bug in how the library interfaces with the Secret Service D-Bus API.
**Current Workaround**:
We bypass the `keyring-rs` library on Linux and use direct system calls to `secret-tool`:
- **Save**: `secret-tool store --label <label> service <service> username <username>`
- **Retrieve**: `secret-tool lookup service <service> username <username>`
- **Delete**: `secret-tool clear service <service> username <username>`
**Implementation**:
See [src-tauri/src/credentials.rs](../src-tauri/src/credentials.rs) for the
Linux-specific `secret-tool` save/get/delete paths.
**Future Fix**:
- Monitor `keyring-rs` for bug fixes in future versions
- Consider alternative secure storage libraries
- Test if newer versions of `keyring-rs` (v4.x+) resolve the issue
- Once fixed, remove the Linux-specific workaround and use the cross-platform `keyring-rs` API
**Impact**:
- Low - The workaround is functionally equivalent to proper keyring integration
- Credentials are stored securely in the system keyring
- Session restoration works correctly
- Only affects Linux; macOS and Windows use the standard `keyring-rs` implementation
**Dependencies**:
- Requires `secret-tool` to be installed on Linux systems (part of `libsecret-tools` package)
- Already available on most Linux distributions by default
---
### Platform Playback Backend Parity (Linux vs Android)
**Issue**: The Linux (MPV) and Android (ExoPlayer) playback backends have diverged in feature implementation and architecture patterns.
**Symptoms**:
- Audio settings (crossfade, gapless playback, volume normalization) work on Linux but not on Android
- Position update frequency differs between platforms (Linux: 250ms polling, Android: on-demand callbacks)
- Thread safety models differ (Linux: `Arc<Mutex<>>`, Android: global `OnceLock` statics)
**Root Cause**:
The `PlayerBackend` trait defines optional audio settings methods with default empty implementations. The Linux `MpvBackend` overrides these with full MPV property commands, but `ExoPlayerBackend` uses the defaults.
**Affected Files**:
- [src-tauri/src/player/backend.rs](../src-tauri/src/player/backend.rs) - Trait with default empty implementations
- [src-tauri/src/player/mpv_backend.rs](../src-tauri/src/player/mpv_backend.rs) - Full audio settings support
- [src-tauri/src/player/android/mod.rs](../src-tauri/src/player/android/mod.rs) - Missing audio settings implementation
**Feature Parity Matrix**:
| Feature | Linux (MPV) | Android (ExoPlayer) | Status |
|---------|-------------|---------------------|--------|
| Basic playback | ✅ | ✅ | Parity |
| Volume control | ✅ | ✅ | Parity |
| Seek | ✅ | ✅ | Parity |
| Crossfade | ✅ | ❌ | Gap |
| Gapless playback | ✅ | ❌ | Gap |
| Volume normalization | ✅ | ❌ | Gap |
| Position updates | 250ms | On-demand | Inconsistent |
**Future Fix**:
1. Implement `set_audio_settings()` in `ExoPlayerBackend`
2. Add Kotlin-side ExoPlayer configuration for crossfade (using `ConcatenatingMediaSource` or `DefaultMediaSourceFactory`)
3. Implement gapless via ExoPlayer's built-in gapless support
4. Add volume normalization via ExoPlayer's `LoudnessEnhancer` or audio processor
5. Standardize position update frequency across platforms
**Impact**:
- Medium - Android users lack audio enhancement features advertised in requirements
- User experience differs between platforms
- UR-031 (Crossfade), UR-032 (Gapless), UR-033 (Normalization) only work on Linux
**Traces To**: IR-004, UR-031, UR-032, UR-033, DR-034, DR-035, DR-036
---
### Frontend Playback Code Duplication
**Issue**: Playback control handlers and state derivations are duplicated between `AudioPlayer.svelte` and `MiniPlayer.svelte`.
**Symptoms**:
- Identical try-catch wrapped handler functions in both components (~44 lines duplicated)
- Same `$derived` state merging logic for local/remote playback in both components
- Position conversion (ticks ↔ seconds) scattered across multiple files
**Affected Files**:
- [src/lib/components/player/AudioPlayer.svelte](../src/lib/components/player/AudioPlayer.svelte) - Duplicate handlers
- [src/lib/components/player/MiniPlayer.svelte](../src/lib/components/player/MiniPlayer.svelte) - Duplicate handlers
- [src/lib/services/playbackControl.ts](../src/lib/services/playbackControl.ts) - Position conversion
- [src/lib/stores/playbackMode.ts](../src/lib/stores/playbackMode.ts) - Position conversion
- [src/lib/services/playbackReporting.ts](../src/lib/services/playbackReporting.ts) - Position conversion
**Duplicated Code**:
```typescript
// These handlers are identical in both AudioPlayer and MiniPlayer:
handlePlayPause(), handleNext(), handlePrevious(),
handleToggleShuffle(), handleCycleRepeat(), handleVolumeChange()
// These derived states use identical logic:
displayMedia, displayIsPlaying, displayPosition, displayDuration
```
**Future Fix**:
1. Create `src/lib/utils/playbackUnits.ts`:
```typescript
export const TICKS_PER_SECOND = 10_000_000;
export const secondsToTicks = (s: number) => Math.floor(s * TICKS_PER_SECOND);
export const ticksToSeconds = (t: number) => t / TICKS_PER_SECOND;
```
2. Create `src/lib/composables/useMergedPlaybackState.svelte.ts`:
- Export `displayMedia`, `displayIsPlaying`, `displayPosition`, `displayDuration`
- Single source of truth for merged local/remote state
3. Simplify handler wrappers using a utility:
```typescript
export const withErrorHandler = (fn: () => Promise<void>, context: string) =>
async () => { try { await fn(); } catch (e) { console.error(`${context}:`, e); } };
```
**Impact**:
- Low - Code works correctly but violates DRY principle
- Maintenance burden when logic needs to change
- Risk of handlers diverging over time
**Traces To**: DR-009
View File
-10227
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -3,6 +3,7 @@
"version": "0.1.0",
"description": "",
"type": "module",
"packageManager": "bun@1.3.5",
"scripts": {
"dev": "vite dev",
"build": "vite build",
@@ -18,7 +19,7 @@
"test:rust": "./scripts/test-rust.sh",
"android:build": "./scripts/build-android.sh",
"android:build:release": "./scripts/build-android.sh release",
"android:build:clean": "rm -rf node_modules/.vite dist .svelte-kit .next build target src-tauri/target && npm install && npm run build",
"android:build:clean": "rm -rf node_modules/.vite dist .svelte-kit .next build target src-tauri/target && bun install && bun run build",
"android:deploy": "./scripts/deploy-android.sh",
"android:dev": "./scripts/build-and-deploy.sh",
"android:check": "./scripts/check-android.sh",
+1 -1
View File
@@ -94,7 +94,7 @@ The traceability system is integrated with Gitea Actions CI/CD:
For details, see:
- [Traceability CI Guide](../docs/traceability-ci.md) - Full CI/CD documentation
- [TRACES Quick Reference](../traces-quick-ref.md) - Quick guide for adding TRACES
- [TRACES Quick Reference](../docs/traces-quick-ref.md) - Quick guide for adding TRACES
## Utility Scripts
+6 -2
View File
@@ -36,6 +36,10 @@ interface TracesData {
};
}
// Repo root, derived from this script's location (scripts/ -> repo root).
// Must NOT be hardcoded to a developer's machine, or CI checkouts see no files.
const BASE_DIR = path.resolve(import.meta.dir, "..");
const TRACES_PATTERN = /TRACES:\s*([^\n]+)/gi;
const REQ_ID_PATTERN = /([A-Z]{2})-(\d{3})/g;
@@ -45,7 +49,7 @@ function extractRequirementIds(tracesString: string): string[] {
}
function getAllSourceFiles(): string[] {
const baseDir = "/home/dtourolle/Development/JellyTau";
const baseDir = BASE_DIR;
const patterns = ["src", "src-tauri/src"];
const files: string[] = [];
@@ -101,7 +105,7 @@ function extractTraces(): TracesData {
};
let totalTraces = 0;
const baseDir = "/home/dtourolle/Development/JellyTau";
const baseDir = BASE_DIR;
const files = getAllSourceFiles();
+10
View File
@@ -31,4 +31,14 @@ for kt_file in "$SOURCE_DIR"/*.kt; do
fi
done
# Restore the app module build.gradle.kts (media3 deps + release signing config).
# gen/android is regenerated by `tauri android init`, so this tracked template is
# the source of truth and must be copied back after any (re)generation.
APP_GRADLE_SRC="$PROJECT_ROOT/src-tauri/android/app/build.gradle.kts"
APP_GRADLE_DST="$PROJECT_ROOT/src-tauri/gen/android/app/build.gradle.kts"
if [ -f "$APP_GRADLE_SRC" ]; then
cp "$APP_GRADLE_SRC" "$APP_GRADLE_DST"
echo " Copied: app/build.gradle.kts"
fi
echo "✓ Android sources synced successfully"
-38
View File
@@ -1,38 +0,0 @@
[target.aarch64-linux-android]
linker = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android34-clang"
ar = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar"
[target.armv7-linux-androideabi]
linker = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi34-clang"
ar = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar"
[target.i686-linux-android]
linker = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/i686-linux-android34-clang"
ar = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar"
[target.x86_64-linux-android]
linker = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android34-clang"
ar = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar"
[env]
# Point to the NDK for the cc crate and other build scripts
ANDROID_NDK_HOME = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006"
NDK_HOME = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006"
# Set CC/CXX for each Android target (cc crate looks for these)
CC_aarch64-linux-android = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android34-clang"
CXX_aarch64-linux-android = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android34-clang++"
AR_aarch64-linux-android = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar"
CC_armv7-linux-androideabi = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi34-clang"
CXX_armv7-linux-androideabi = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi34-clang++"
AR_armv7-linux-androideabi = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar"
CC_i686-linux-android = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/i686-linux-android34-clang"
CXX_i686-linux-android = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/i686-linux-android34-clang++"
AR_i686-linux-android = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar"
CC_x86_64-linux-android = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android34-clang"
CXX_x86_64-linux-android = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android34-clang++"
AR_x86_64-linux-android = "/home/dtourolle/Android/Sdk/ndk/27.1.12297006/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar"
+101 -43
View File
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "Inflector"
version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3"
[[package]]
name = "adler2"
version = "2.0.1"
@@ -1745,7 +1751,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.62.2",
"windows-core",
]
[[package]]
@@ -2011,10 +2017,13 @@ dependencies = [
"serde",
"serde_json",
"sha2",
"specta",
"specta-typescript",
"tauri",
"tauri-build",
"tauri-plugin-opener",
"tauri-plugin-os",
"tauri-specta",
"tempfile",
"tokio",
"tokio-rusqlite",
@@ -2795,6 +2804,12 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pathdiff"
version = "0.2.3"
@@ -3933,6 +3948,51 @@ dependencies = [
"system-deps",
]
[[package]]
name = "specta"
version = "2.0.0-rc.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab7f01e9310a820edd31c80fde3cae445295adde21a3f9416517d7d65015b971"
dependencies = [
"chrono",
"paste",
"specta-macros",
"thiserror 1.0.69",
]
[[package]]
name = "specta-macros"
version = "2.0.0-rc.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0074b9e30ed84c6924eb63ad8d2fe71cdc82628525d84b1fcb1f2fd40676517"
dependencies = [
"Inflector",
"proc-macro2",
"quote",
"syn 2.0.112",
]
[[package]]
name = "specta-serde"
version = "0.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77216504061374659e7245eac53d30c7b3e5fe64b88da97c753e7184b0781e63"
dependencies = [
"specta",
"thiserror 1.0.69",
]
[[package]]
name = "specta-typescript"
version = "0.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3220a0c365e51e248ac98eab5a6a32f544ff6f961906f09d3ee10903a4f52b2d"
dependencies = [
"specta",
"specta-serde",
"thiserror 1.0.69",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -4092,7 +4152,7 @@ dependencies = [
"unicode-segmentation",
"url",
"windows",
"windows-core 0.61.2",
"windows-core",
"windows-version",
"x11-dl",
]
@@ -4149,6 +4209,7 @@ dependencies = [
"serde_json",
"serde_repr",
"serialize-to-javascript",
"specta",
"swift-rs",
"tauri-build",
"tauri-macros",
@@ -4337,6 +4398,34 @@ dependencies = [
"wry",
]
[[package]]
name = "tauri-specta"
version = "2.0.0-rc.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b23c0132dd3cf6064e5cd919b82b3f47780e9280e7b5910babfe139829b76655"
dependencies = [
"heck 0.5.0",
"serde",
"serde_json",
"specta",
"specta-typescript",
"tauri",
"tauri-specta-macros",
"thiserror 2.0.17",
]
[[package]]
name = "tauri-specta-macros"
version = "2.0.0-rc.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a4aa93823e07859546aa796b8a5d608190cd8037a3a5dce3eb63d491c34bda8"
dependencies = [
"heck 0.5.0",
"proc-macro2",
"quote",
"syn 2.0.112",
]
[[package]]
name = "tauri-utils"
version = "2.8.1"
@@ -5143,7 +5232,7 @@ dependencies = [
"webview2-com-macros",
"webview2-com-sys",
"windows",
"windows-core 0.61.2",
"windows-core",
"windows-implement",
"windows-interface",
]
@@ -5167,7 +5256,7 @@ checksum = "36695906a1b53a3bf5c4289621efedac12b73eeb0b89e7e1a89b517302d5d75c"
dependencies = [
"thiserror 2.0.17",
"windows",
"windows-core 0.61.2",
"windows-core",
]
[[package]]
@@ -5192,7 +5281,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]
@@ -5223,7 +5312,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
"windows-collections",
"windows-core 0.61.2",
"windows-core",
"windows-future",
"windows-link 0.1.3",
"windows-numerics",
@@ -5235,7 +5324,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
dependencies = [
"windows-core 0.61.2",
"windows-core",
]
[[package]]
@@ -5247,21 +5336,8 @@ dependencies = [
"windows-implement",
"windows-interface",
"windows-link 0.1.3",
"windows-result 0.3.4",
"windows-strings 0.4.2",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
"windows-result",
"windows-strings",
]
[[package]]
@@ -5270,7 +5346,7 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core 0.61.2",
"windows-core",
"windows-link 0.1.3",
"windows-threading",
]
@@ -5315,7 +5391,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
dependencies = [
"windows-core 0.61.2",
"windows-core",
"windows-link 0.1.3",
]
@@ -5328,15 +5404,6 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
@@ -5346,15 +5413,6 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.45.0"
@@ -5750,7 +5808,7 @@ dependencies = [
"webkit2gtk-sys",
"webview2-com",
"windows",
"windows-core 0.61.2",
"windows-core",
"windows-version",
"x11-dl",
]
+8
View File
@@ -14,6 +14,11 @@ edition = "2021"
name = "jellytau_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
# Keep debug info minimal to reduce target/ size in CI (line numbers in
# backtraces are preserved; the bulky full debuginfo is dropped).
[profile.dev]
debug = "line-tables-only"
[build-dependencies]
tauri-build = { version = "2", features = [] }
@@ -45,6 +50,9 @@ sha2 = "0.10"
getrandom = "0.2"
log = "0.4"
env_logger = "0.11"
tauri-specta = { version = "=2.0.0-rc.21", features = ["derive", "typescript"] }
specta-typescript = "=0.0.9"
specta = { version = "=2.0.0-rc.22", features = ["chrono", "derive"] }
# Linux-specific dependencies
[target.'cfg(target_os = "linux")'.dependencies]
+103
View File
@@ -0,0 +1,103 @@
import java.util.Properties
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("rust")
}
val tauriProperties = Properties().apply {
val propFile = file("tauri.properties")
if (propFile.exists()) {
propFile.inputStream().use { load(it) }
}
}
// Release signing: loaded from gen/android/keystore.properties if present.
// Falls back to no signing config (debug-signed) when the file is absent.
val keystoreProperties = Properties().apply {
val propFile = rootProject.file("keystore.properties")
if (propFile.exists()) {
propFile.inputStream().use { load(it) }
}
}
android {
compileSdk = 36
namespace = "com.dtourolle.jellytau"
defaultConfig {
manifestPlaceholders["usesCleartextTraffic"] = "false"
applicationId = "com.dtourolle.jellytau"
minSdk = 24
targetSdk = 36
versionCode = tauriProperties.getProperty("tauri.android.versionCode", "1").toInt()
versionName = tauriProperties.getProperty("tauri.android.versionName", "1.0")
}
signingConfigs {
create("release") {
keystoreProperties.getProperty("storeFile")?.let {
storeFile = file(it)
storePassword = keystoreProperties.getProperty("storePassword")
keyAlias = keystoreProperties.getProperty("keyAlias")
keyPassword = keystoreProperties.getProperty("keyPassword")
}
}
}
buildTypes {
getByName("debug") {
manifestPlaceholders["usesCleartextTraffic"] = "true"
isDebuggable = true
isJniDebuggable = true
isMinifyEnabled = false
packaging { jniLibs.keepDebugSymbols.add("*/arm64-v8a/*.so")
jniLibs.keepDebugSymbols.add("*/armeabi-v7a/*.so")
jniLibs.keepDebugSymbols.add("*/x86/*.so")
jniLibs.keepDebugSymbols.add("*/x86_64/*.so")
}
}
getByName("release") {
if (keystoreProperties.getProperty("storeFile") != null) {
signingConfig = signingConfigs.getByName("release")
}
isMinifyEnabled = true
proguardFiles(
*fileTree(".") { include("**/*.pro") }
.plus(getDefaultProguardFile("proguard-android-optimize.txt"))
.toList().toTypedArray()
)
}
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
buildConfig = true
}
}
rust {
rootDirRel = "../../../"
}
dependencies {
implementation("androidx.webkit:webkit:1.14.0")
implementation("androidx.appcompat:appcompat:1.7.1")
implementation("androidx.activity:activity-ktx:1.10.1")
implementation("com.google.android.material:material:1.12.0")
// Media3 dependencies for audio playback
implementation("androidx.media3:media3-exoplayer:1.5.0")
implementation("androidx.media3:media3-exoplayer-hls:1.5.0")
implementation("androidx.media3:media3-session:1.5.0")
implementation("androidx.media3:media3-common:1.5.0")
implementation("com.google.guava:guava:33.0.0-android")
// Media library for VolumeProviderCompat (remote volume control)
implementation("androidx.media:media:1.7.0")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.4")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.0")
}
apply(from = "tauri.build.gradle.kts")
@@ -0,0 +1,86 @@
package com.dtourolle.jellytau
import android.app.Activity
import android.view.SurfaceView
import android.view.ViewGroup
import android.widget.FrameLayout
import com.dtourolle.jellytau.player.JellyTauPlayer
/**
* Manages the video SurfaceView overlay in the Activity's view hierarchy.
*
* This class handles attaching and detaching the native ExoPlayer SurfaceView
* so that it renders video content behind the WebView.
*/
object VideoOverlayManager {
private var attachedSurfaceView: SurfaceView? = null
/**
* Attach the video SurfaceView to the Activity's content view.
*
* The SurfaceView is added at index 0 (bottom of z-order) so it renders
* behind the Tauri WebView, allowing Svelte controls to overlay on top.
*
* @param activity The Activity to attach the surface to
*/
fun attachVideoSurface(activity: Activity) {
try {
// Get the SurfaceView from JellyTauPlayer
val player = JellyTauPlayer.getInstance()
val surfaceView = player.getSurfaceView()
if (surfaceView == null) {
android.util.Log.w("VideoOverlayManager", "No SurfaceView available to attach")
return
}
// Get the root content view
val contentView = activity.window.decorView.findViewById<ViewGroup>(android.R.id.content)
// Remove from parent if already attached elsewhere
(surfaceView.parent as? ViewGroup)?.removeView(surfaceView)
// Configure layout params to fill the screen
val layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
// Add to content view at index 0 (behind WebView)
contentView.addView(surfaceView, 0, layoutParams)
attachedSurfaceView = surfaceView
android.util.Log.d("VideoOverlayManager", "Video surface attached to view hierarchy")
} catch (e: Exception) {
android.util.Log.e("VideoOverlayManager", "Failed to attach video surface", e)
}
}
/**
* Detach the video SurfaceView from the Activity's view hierarchy.
*
* @param activity The Activity to detach the surface from
*/
fun detachVideoSurface(activity: Activity) {
try {
attachedSurfaceView?.let { surfaceView ->
val contentView = activity.window.decorView.findViewById<ViewGroup>(android.R.id.content)
contentView.removeView(surfaceView)
attachedSurfaceView = null
android.util.Log.d("VideoOverlayManager", "Video surface detached from view hierarchy")
}
} catch (e: Exception) {
android.util.Log.e("VideoOverlayManager", "Failed to detach video surface", e)
}
}
/**
* Check if a video surface is currently attached.
*
* @return true if a surface is attached, false otherwise
*/
fun isVideoSurfaceAttached(): Boolean {
return attachedSurfaceView != null
}
}
+8 -7
View File
@@ -10,8 +10,9 @@ use crate::connectivity::ConnectivityMonitor;
pub use session_verifier::SessionVerifier;
/// Server information returned from Jellyfin
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[specta(rename = "AuthServerInfo")]
pub struct ServerInfo {
pub name: String,
pub version: String,
@@ -21,7 +22,7 @@ pub struct ServerInfo {
}
/// User information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct User {
pub id: String,
@@ -31,7 +32,7 @@ pub struct User {
}
/// Authentication result
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthResult {
pub user: User,
@@ -40,7 +41,7 @@ pub struct AuthResult {
}
/// Active session for restoration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Session {
pub user_id: String,
@@ -55,7 +56,7 @@ pub struct Session {
// Jellyfin API response types (PascalCase from server)
#[derive(Debug, Deserialize)]
#[derive(specta::Type, Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct PublicSystemInfo {
server_name: String,
@@ -63,7 +64,7 @@ struct PublicSystemInfo {
id: String,
}
#[derive(Debug, Deserialize)]
#[derive(specta::Type, Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct AuthenticateByNameResponse {
user: JellyfinUser,
@@ -71,7 +72,7 @@ struct AuthenticateByNameResponse {
server_id: String,
}
#[derive(Debug, Deserialize)]
#[derive(specta::Type, Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct JellyfinUser {
id: String,
+10
View File
@@ -12,6 +12,7 @@ pub struct SessionVerifierWrapper(pub Arc<tokio::sync::Mutex<Option<SessionVerif
/// Initialize the auth manager (call on app startup)
/// Restores session from storage if available
#[tauri::command]
#[specta::specta]
pub async fn auth_initialize(
auth_manager: State<'_, AuthManagerWrapper>,
database: State<'_, crate::commands::DatabaseWrapper>,
@@ -61,6 +62,7 @@ pub async fn auth_initialize(
/// Connect to a Jellyfin server and get server info
#[tauri::command]
#[specta::specta]
pub async fn auth_connect_to_server(
server_url: String,
auth_manager: State<'_, AuthManagerWrapper>,
@@ -70,6 +72,7 @@ pub async fn auth_connect_to_server(
/// Login with username and password
#[tauri::command]
#[specta::specta]
pub async fn auth_login(
server_url: String,
username: String,
@@ -100,6 +103,7 @@ pub async fn auth_login(
/// Verify current session
#[tauri::command]
#[specta::specta]
pub async fn auth_verify_session(
server_url: String,
user_id: String,
@@ -118,6 +122,7 @@ pub async fn auth_verify_session(
/// Logout (clear session and call Jellyfin logout endpoint)
#[tauri::command]
#[specta::specta]
pub async fn auth_logout(
server_url: String,
access_token: String,
@@ -143,6 +148,7 @@ pub async fn auth_logout(
/// Get current session
#[tauri::command]
#[specta::specta]
pub async fn auth_get_session(
auth_manager: State<'_, AuthManagerWrapper>,
) -> Result<Option<Session>, String> {
@@ -151,6 +157,7 @@ pub async fn auth_get_session(
/// Set current session (for restoration from storage)
#[tauri::command]
#[specta::specta]
pub async fn auth_set_session(
session: Option<Session>,
auth_manager: State<'_, AuthManagerWrapper>,
@@ -170,6 +177,7 @@ pub async fn auth_set_session(
/// Start background session verification
#[tauri::command]
#[specta::specta]
pub async fn auth_start_verification(
device_id: String,
app_handle: tauri::AppHandle,
@@ -198,6 +206,7 @@ pub async fn auth_start_verification(
/// Stop background session verification
#[tauri::command]
#[specta::specta]
pub async fn auth_stop_verification(
session_verifier: State<'_, SessionVerifierWrapper>,
) -> Result<(), String> {
@@ -212,6 +221,7 @@ pub async fn auth_stop_verification(
/// Re-authenticate with password (when session expired)
#[tauri::command]
#[specta::specta]
pub async fn auth_reauthenticate(
password: String,
device_id: String,
+7
View File
@@ -7,6 +7,7 @@ pub struct ConnectivityMonitorWrapper(pub Arc<tokio::sync::Mutex<ConnectivityMon
/// Check if the server is currently reachable
#[tauri::command]
#[specta::specta]
pub async fn connectivity_check_server(
state: State<'_, ConnectivityMonitorWrapper>,
) -> Result<bool, String> {
@@ -16,6 +17,7 @@ pub async fn connectivity_check_server(
/// Set the server URL and trigger an immediate check
#[tauri::command]
#[specta::specta]
pub async fn connectivity_set_server_url(
url: String,
state: State<'_, ConnectivityMonitorWrapper>,
@@ -27,6 +29,7 @@ pub async fn connectivity_set_server_url(
/// Get the current connectivity status
#[tauri::command]
#[specta::specta]
pub async fn connectivity_get_status(
state: State<'_, ConnectivityMonitorWrapper>,
) -> Result<ConnectivityStatus, String> {
@@ -36,6 +39,7 @@ pub async fn connectivity_get_status(
/// Start monitoring connectivity with adaptive polling
#[tauri::command]
#[specta::specta]
pub async fn connectivity_start_monitoring(
state: State<'_, ConnectivityMonitorWrapper>,
) -> Result<(), String> {
@@ -46,6 +50,7 @@ pub async fn connectivity_start_monitoring(
/// Stop monitoring connectivity
#[tauri::command]
#[specta::specta]
pub async fn connectivity_stop_monitoring(
state: State<'_, ConnectivityMonitorWrapper>,
) -> Result<(), String> {
@@ -56,6 +61,7 @@ pub async fn connectivity_stop_monitoring(
/// Mark the server as reachable (called after successful API calls)
#[tauri::command]
#[specta::specta]
pub async fn connectivity_mark_reachable(
state: State<'_, ConnectivityMonitorWrapper>,
) -> Result<(), String> {
@@ -66,6 +72,7 @@ pub async fn connectivity_mark_reachable(
/// Mark the server as unreachable (called after failed API calls)
#[tauri::command]
#[specta::specta]
pub async fn connectivity_mark_unreachable(
error: Option<String>,
state: State<'_, ConnectivityMonitorWrapper>,
+5
View File
@@ -16,6 +16,7 @@ use crate::utils::conversions::{
/// # Returns
/// Formatted string like "3:45" or "12:09"
#[tauri::command]
#[specta::specta]
pub fn format_time_seconds(seconds: f64) -> String {
format_time(seconds)
}
@@ -32,6 +33,7 @@ pub fn format_time_seconds(seconds: f64) -> String {
/// # Returns
/// Formatted string like "1:23:45" or "3:45"
#[tauri::command]
#[specta::specta]
pub fn format_time_seconds_long(seconds: f64) -> String {
format_time_long(seconds)
}
@@ -44,6 +46,7 @@ pub fn format_time_seconds_long(seconds: f64) -> String {
/// # Returns
/// Time in seconds
#[tauri::command]
#[specta::specta]
pub fn convert_ticks_to_seconds(ticks: i64) -> f64 {
ticks_to_seconds(ticks)
}
@@ -57,6 +60,7 @@ pub fn convert_ticks_to_seconds(ticks: i64) -> f64 {
/// # Returns
/// Progress as percentage (0.0 to 100.0)
#[tauri::command]
#[specta::specta]
pub fn calc_progress(position: f64, duration: f64) -> f64 {
calculate_progress(position, duration)
}
@@ -69,6 +73,7 @@ pub fn calc_progress(position: f64, duration: f64) -> f64 {
/// # Returns
/// Normalized volume (0.0 to 1.0)
#[tauri::command]
#[specta::specta]
pub fn convert_percent_to_volume(percent: f64) -> f64 {
percent_to_volume(percent)
}
+2
View File
@@ -23,6 +23,7 @@ use crate::storage::db_service::{DatabaseService, Query, QueryParam};
///
/// TRACES: UR-009 | DR-011
#[tauri::command]
#[specta::specta]
pub async fn device_get_id(db: State<'_, DatabaseWrapper>) -> Result<String, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
@@ -79,6 +80,7 @@ pub async fn device_get_id(db: State<'_, DatabaseWrapper>) -> Result<String, Str
///
/// TRACES: UR-009 | DR-011
#[tauri::command]
#[specta::specta]
pub async fn device_set_id(device_id: String, db: State<'_, DatabaseWrapper>) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
@@ -1,5 +1,7 @@
//! Tauri commands for download operations
#[cfg(test)]
use crate::utils::lock::MutexSafe;
use std::sync::{Arc, Mutex};
use tauri::State;
use log::{debug, error, info, warn};
@@ -8,12 +10,19 @@ use crate::download::{DownloadInfo, DownloadManager};
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
use super::{DatabaseWrapper, SmartCacheWrapper};
// Cohesive command clusters in their own submodules, re-exported so the command
// names remain at `commands::download::*` (invoke_handler unchanged).
mod pinning;
mod smart_cache;
pub use pinning::*;
pub use smart_cache::*;
/// Wrapper for DownloadManager to be used as Tauri state
pub struct DownloadManagerWrapper(pub Mutex<DownloadManager>);
/// Download statistics computed server-side
#[allow(dead_code)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadStats {
pub total: usize,
@@ -26,7 +35,7 @@ pub struct DownloadStats {
/// Enhanced response with pre-computed stats
#[allow(dead_code)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadsResponse {
pub downloads: Vec<DownloadInfo>,
@@ -43,22 +52,66 @@ fn sanitize_filename(name: &str) -> String {
.collect()
}
/// Request payload for download_item_and_start (bundled to stay within specta's
/// 10-argument command limit).
#[derive(Debug, specta::Type, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadItemAndStartRequest {
pub item_id: String,
pub user_id: String,
pub stream_url: String,
pub target_dir: String,
pub item_name: Option<String>,
pub artist_name: Option<String>,
pub album_name: Option<String>,
}
/// Request payload for download_item.
#[derive(Debug, specta::Type, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadItemRequest {
pub item_id: String,
pub user_id: String,
pub file_path: String,
pub mime_type: Option<String>,
pub priority: Option<i32>,
pub item_name: Option<String>,
pub artist_name: Option<String>,
pub album_name: Option<String>,
pub expected_size: Option<i64>,
}
/// Request payload for download_video.
#[derive(Debug, specta::Type, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadVideoRequest {
pub item_id: String,
pub user_id: String,
pub file_path: String,
pub mime_type: Option<String>,
pub priority: Option<i32>,
pub item_name: Option<String>,
pub quality_preset: Option<String>,
pub series_name: Option<String>,
pub season_name: Option<String>,
pub episode_number: Option<i32>,
pub season_number: Option<i32>,
}
/// Queue and start a download in a single atomic operation
/// This simplifies the frontend flow by combining multiple steps
#[tauri::command]
#[specta::specta]
pub async fn download_item_and_start(
db: State<'_, DatabaseWrapper>,
smart_cache: State<'_, SmartCacheWrapper>,
download_manager: State<'_, DownloadManagerWrapper>,
app: tauri::AppHandle,
item_id: String,
user_id: String,
stream_url: String,
target_dir: String,
item_name: Option<String>,
artist_name: Option<String>,
album_name: Option<String>,
request: DownloadItemAndStartRequest,
) -> Result<i64, String> {
let DownloadItemAndStartRequest {
item_id, user_id, stream_url, target_dir, item_name, artist_name, album_name,
} = request;
// Sanitize filename
let safe_name = sanitize_filename(item_name.as_deref().unwrap_or(&item_id));
let file_path = format!("downloads/{}.mp3", safe_name);
@@ -67,15 +120,17 @@ pub async fn download_item_and_start(
let download_id = download_item(
db.clone(),
smart_cache.clone(),
item_id,
user_id,
file_path,
None, // mime_type
None, // priority
item_name,
artist_name,
album_name,
None, // expected_size
DownloadItemRequest {
item_id,
user_id,
file_path,
mime_type: None,
priority: None,
item_name,
artist_name,
album_name,
expected_size: None,
},
).await?;
// Start the download immediately
@@ -93,19 +148,15 @@ pub async fn download_item_and_start(
/// Queue a media item for download
#[tauri::command]
#[specta::specta]
pub async fn download_item(
db: State<'_, DatabaseWrapper>,
smart_cache: State<'_, SmartCacheWrapper>,
item_id: String,
user_id: String,
file_path: String,
mime_type: Option<String>,
priority: Option<i32>,
item_name: Option<String>,
artist_name: Option<String>,
album_name: Option<String>,
expected_size: Option<i64>,
request: DownloadItemRequest,
) -> Result<i64, String> {
let DownloadItemRequest {
item_id, user_id, file_path, mime_type, priority, item_name, artist_name, album_name, expected_size,
} = request;
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
@@ -187,6 +238,7 @@ pub async fn download_item(
/// Queue an entire album for download
#[tauri::command]
#[specta::specta]
pub async fn download_album(
db: State<'_, DatabaseWrapper>,
album_id: String,
@@ -258,21 +310,15 @@ pub async fn download_album(
/// Queue a video item (movie or episode) for download with quality preset
#[tauri::command]
#[specta::specta]
pub async fn download_video(
db: State<'_, DatabaseWrapper>,
item_id: String,
user_id: String,
file_path: String,
mime_type: Option<String>,
priority: Option<i32>,
item_name: Option<String>,
quality_preset: Option<String>,
// Video-specific metadata
series_name: Option<String>,
season_name: Option<String>,
episode_number: Option<i32>,
season_number: Option<i32>,
request: DownloadVideoRequest,
) -> Result<i64, String> {
let DownloadVideoRequest {
item_id, user_id, file_path, mime_type, priority, item_name, quality_preset,
series_name, season_name, episode_number, season_number,
} = request;
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
@@ -329,6 +375,7 @@ pub async fn download_video(
/// Queue all episodes of a series for download
#[tauri::command]
#[specta::specta]
pub async fn download_series(
db: State<'_, DatabaseWrapper>,
series_id: String,
@@ -429,6 +476,7 @@ pub async fn download_series(
/// Queue all episodes of a specific season for download
#[tauri::command]
#[specta::specta]
pub async fn download_season(
db: State<'_, DatabaseWrapper>,
season_id: String,
@@ -520,61 +568,6 @@ pub async fn download_season(
Ok(download_ids)
}
/// Pin an item's metadata (protects from cache clear)
#[tauri::command]
pub async fn pin_item(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let query = Query::with_params(
"UPDATE items SET is_pinned = 1 WHERE id = ?",
vec![QueryParam::String(item_id)],
);
db_service.execute(query).await.map_err(|e| e.to_string())?;
Ok(())
}
/// Unpin an item's metadata
#[tauri::command]
pub async fn unpin_item(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let query = Query::with_params(
"UPDATE items SET is_pinned = 0 WHERE id = ?",
vec![QueryParam::String(item_id)],
);
db_service.execute(query).await.map_err(|e| e.to_string())?;
Ok(())
}
/// Check if an item is pinned
#[tauri::command]
pub async fn is_item_pinned(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<bool, 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 COALESCE(is_pinned, 0) FROM items WHERE id = ?",
vec![QueryParam::String(item_id)],
);
let is_pinned: i32 = db_service
.query_optional(query, |row| row.get(0))
.await
.map_err(|e| e.to_string())?
.unwrap_or(0);
Ok(is_pinned == 1)
}
/// Helper to compute download statistics from a list of downloads
#[allow(dead_code)]
@@ -604,6 +597,7 @@ fn compute_download_stats(downloads: &[DownloadInfo]) -> DownloadStats {
/// Get all downloads for a user, optionally filtered by status
#[tauri::command]
#[specta::specta]
pub async fn get_downloads(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -678,6 +672,7 @@ pub async fn get_downloads(
/// Pause a download
#[tauri::command]
#[specta::specta]
pub async fn pause_download(db: State<'_, DatabaseWrapper>, download_id: i64) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
@@ -695,6 +690,7 @@ pub async fn pause_download(db: State<'_, DatabaseWrapper>, download_id: i64) ->
/// Resume a paused download
#[tauri::command]
#[specta::specta]
pub async fn resume_download(db: State<'_, DatabaseWrapper>, download_id: i64) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
@@ -712,6 +708,7 @@ pub async fn resume_download(db: State<'_, DatabaseWrapper>, download_id: i64) -
/// Cancel a download
#[tauri::command]
#[specta::specta]
pub async fn cancel_download(
db: State<'_, DatabaseWrapper>,
download_manager: State<'_, DownloadManagerWrapper>,
@@ -760,6 +757,7 @@ pub async fn cancel_download(
/// Mark a download as completed
#[tauri::command]
#[specta::specta]
pub async fn mark_download_completed(
db: State<'_, DatabaseWrapper>,
download_id: i64,
@@ -788,6 +786,7 @@ pub async fn mark_download_completed(
/// Mark a download as failed
#[tauri::command]
#[specta::specta]
pub async fn mark_download_failed(
db: State<'_, DatabaseWrapper>,
download_id: i64,
@@ -810,6 +809,7 @@ pub async fn mark_download_failed(
/// Start downloading a file immediately
/// This command actually downloads the file using the worker
#[tauri::command]
#[specta::specta]
pub async fn start_download(
db: State<'_, DatabaseWrapper>,
download_manager: State<'_, DownloadManagerWrapper>,
@@ -1027,6 +1027,7 @@ pub async fn start_download(
/// Delete a completed download
#[tauri::command]
#[specta::specta]
pub async fn delete_download(db: State<'_, DatabaseWrapper>, download_id: i64) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
@@ -1094,7 +1095,7 @@ fn map_download_row(row: &rusqlite::Row) -> rusqlite::Result<DownloadInfo> {
}
/// Storage statistics for downloads
#[derive(Debug, Clone, serde::Serialize)]
#[derive(specta::Type, Debug, Clone, serde::Serialize)]
pub struct StorageStats {
pub total_bytes: i64,
pub total_items: i64,
@@ -1102,7 +1103,7 @@ pub struct StorageStats {
}
/// Storage info for a single album
#[derive(Debug, Clone, serde::Serialize)]
#[derive(specta::Type, Debug, Clone, serde::Serialize)]
pub struct AlbumStorageInfo {
pub album_id: String,
pub album_name: String,
@@ -1113,6 +1114,7 @@ pub struct AlbumStorageInfo {
/// Get storage statistics for downloads
#[tauri::command]
#[specta::specta]
pub async fn get_download_storage_stats(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -1173,6 +1175,7 @@ pub async fn get_download_storage_stats(
/// Delete all downloads for a user
#[tauri::command]
#[specta::specta]
pub async fn delete_all_downloads(db: State<'_, DatabaseWrapper>, user_id: String) -> Result<i64, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
@@ -1212,6 +1215,7 @@ pub async fn delete_all_downloads(db: State<'_, DatabaseWrapper>, user_id: Strin
/// Clear all stale pending/failed/paused downloads
#[tauri::command]
#[specta::specta]
pub async fn clear_stale_downloads(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -1254,6 +1258,7 @@ pub async fn clear_stale_downloads(
/// Delete all downloads for a specific album
#[tauri::command]
#[specta::specta]
pub async fn delete_album_downloads(
db: State<'_, DatabaseWrapper>,
album_id: String,
@@ -1298,7 +1303,7 @@ pub async fn delete_album_downloads(
}
/// Download manager statistics
#[derive(Debug, Clone, serde::Serialize)]
#[derive(specta::Type, Debug, Clone, serde::Serialize)]
pub struct DownloadManagerStats {
pub max_concurrent: usize,
pub active_count: usize,
@@ -1307,6 +1312,7 @@ pub struct DownloadManagerStats {
/// Get download manager statistics
#[tauri::command]
#[specta::specta]
pub async fn get_download_manager_stats(
download_manager: State<'_, DownloadManagerWrapper>,
) -> Result<DownloadManagerStats, String> {
@@ -1324,6 +1330,7 @@ pub async fn get_download_manager_stats(
/// Set the maximum concurrent downloads
#[tauri::command]
#[specta::specta]
pub async fn set_max_concurrent_downloads(
download_manager: State<'_, DownloadManagerWrapper>,
max: usize,
@@ -1334,220 +1341,6 @@ pub async fn set_max_concurrent_downloads(
Ok(())
}
/// SmartCache statistics
#[derive(Debug, Clone, serde::Serialize)]
pub struct SmartCacheStats {
pub total_size: u64,
pub storage_limit: u64,
pub available_space: u64,
pub items_count: i64,
pub config: crate::download::cache::CacheConfig,
}
/// Get SmartCache statistics
#[tauri::command]
pub async fn get_smart_cache_stats(
db: State<'_, DatabaseWrapper>,
smart_cache: State<'_, SmartCacheWrapper>,
user_id: String,
) -> Result<SmartCacheStats, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
// Clone cache to avoid holding lock across async operations
let cache = {
let guard = smart_cache.0.lock().map_err(|e| e.to_string())?;
guard.clone()
};
let total_size = cache
.get_total_download_size_async(&db_service, &user_id)
.await?;
let config = cache
.get_config()
.ok_or_else(|| "Failed to get cache config".to_string())?;
let storage_limit = config.storage_limit;
let available_space = storage_limit.saturating_sub(total_size);
// Get item count
let count_query = Query::with_params(
"SELECT COUNT(*) FROM downloads WHERE user_id = ? AND status = 'completed'",
vec![QueryParam::String(user_id)],
);
let items_count: i64 = db_service
.query_one(count_query, |row| row.get(0))
.await
.unwrap_or(0);
Ok(SmartCacheStats {
total_size,
storage_limit,
available_space,
items_count,
config,
})
}
/// Update SmartCache configuration
#[tauri::command]
pub async fn update_smart_cache_config(
smart_cache: State<'_, SmartCacheWrapper>,
config: crate::download::cache::CacheConfig,
) -> Result<(), String> {
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
cache.update_config(config);
info!("Updated SmartCache configuration");
Ok(())
}
/// Get SmartCache configuration
#[tauri::command]
pub async fn get_smart_cache_config(
smart_cache: State<'_, SmartCacheWrapper>,
) -> Result<crate::download::cache::CacheConfig, String> {
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
cache
.get_config()
.ok_or_else(|| "Failed to get cache config".to_string())
}
/// Album recommendation info
#[derive(Debug, Clone, serde::Serialize)]
pub struct AlbumRecommendation {
pub album_id: String,
pub album_name: String,
pub tracks_played: usize,
pub total_tracks: usize,
pub should_download: bool,
}
/// Album affinity status info
#[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AlbumAffinityStatus {
pub album_id: String,
pub unique_tracks_played: usize,
pub threshold: usize,
pub threshold_reached: bool,
}
/// Get album recommendations based on play history
#[tauri::command]
pub async fn get_album_recommendations(
db: State<'_, DatabaseWrapper>,
smart_cache: State<'_, SmartCacheWrapper>,
user_id: String,
) -> Result<Vec<AlbumRecommendation>, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
// Clone cache to avoid holding lock across async operations
let cache = {
let guard = smart_cache.0.lock().map_err(|e| e.to_string())?;
guard.clone()
};
// Get all albums that user has played tracks from
let query = Query::with_params(
"SELECT DISTINCT i.album_id, a.name
FROM user_data ud
JOIN items i ON ud.item_id = i.id
JOIN items a ON i.album_id = a.id
WHERE ud.user_id = ?
AND ud.play_count > 0
AND i.item_type = 'Audio'
AND i.album_id IS NOT NULL",
vec![QueryParam::String(user_id.clone())],
);
let albums: Vec<(String, String)> = db_service
.query_many(query, |row| Ok((row.get(0)?, row.get(1)?)))
.await
.unwrap_or_default();
let mut recommendations = Vec::new();
for (album_id, album_name) in albums {
// Check if should cache
let should_download = cache.should_cache_album(&album_id).unwrap_or(false);
// Get track counts
let tracks_query = Query::with_params(
"SELECT
COUNT(*) as total,
COUNT(ud.id) as played
FROM items i
LEFT JOIN user_data ud ON i.id = ud.item_id AND ud.user_id = ?
WHERE i.album_id = ? AND i.item_type = 'Audio'",
vec![
QueryParam::String(user_id.clone()),
QueryParam::String(album_id.clone()),
],
);
let (total_tracks, tracks_played): (i64, i64) = db_service
.query_one(tracks_query, |row| Ok((row.get(0)?, row.get(1)?)))
.await
.unwrap_or((0, 0));
if tracks_played > 0 {
recommendations.push(AlbumRecommendation {
album_id,
album_name,
tracks_played: tracks_played as usize,
total_tracks: total_tracks as usize,
should_download,
});
}
}
// Sort by tracks played (descending)
recommendations.sort_by(|a, b| b.tracks_played.cmp(&a.tracks_played));
Ok(recommendations)
}
/// Get album affinity status for all tracked albums
/// This shows the SmartCache's internal play history and threshold status
#[tauri::command]
pub fn get_album_affinity_status(
smart_cache: State<'_, SmartCacheWrapper>,
) -> Result<Vec<AlbumAffinityStatus>, String> {
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
// Get the threshold from config
let threshold = cache
.get_config()
.map(|c| c.album_affinity_threshold)
.unwrap_or(3);
// Get all tracked albums with their play counts
let play_history = cache.get_album_play_history();
let mut statuses: Vec<AlbumAffinityStatus> = play_history
.into_iter()
.map(|(album_id, unique_tracks_played)| {
let threshold_reached = unique_tracks_played >= threshold;
AlbumAffinityStatus {
album_id,
unique_tracks_played,
threshold,
threshold_reached,
}
})
.collect();
// Sort by play count (descending)
statuses.sort_by(|a, b| b.unique_tracks_played.cmp(&a.unique_tracks_played));
Ok(statuses)
}
// TRACES: UR-011, UR-018 | DR-015, DR-018 | UT-042, UT-043
#[cfg(test)]
@@ -1577,7 +1370,7 @@ mod tests {
fn setup_test_db() -> Database {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Create server
conn.execute(
@@ -1620,7 +1413,7 @@ mod tests {
fn test_download_item_returns_correct_id_on_insert() {
let db = setup_test_db();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Insert a new download
conn.execute(
@@ -1658,7 +1451,7 @@ mod tests {
fn test_download_item_upsert_returns_correct_id() {
let db = setup_test_db();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// First insert
conn.execute(
@@ -1733,7 +1526,7 @@ mod tests {
// to get the correct download ID, regardless of whether INSERT or UPDATE occurred.
let db = setup_test_db();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// First insert
conn.execute(
@@ -1781,7 +1574,7 @@ mod tests {
fn test_download_album_returns_correct_ids() {
let db = setup_test_db();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Insert downloads for multiple items (simulating album download)
let track_ids = vec!["item1", "item2", "item3"];
@@ -1827,7 +1620,7 @@ mod tests {
fn test_download_album_upsert_returns_correct_ids() {
let db = setup_test_db();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// First download attempt - insert all
let track_ids = vec!["item1", "item2", "item3"];
@@ -1887,7 +1680,7 @@ mod tests {
fn test_get_downloads_returns_correct_metadata() {
let db = setup_test_db();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Insert a download
conn.execute(
@@ -1932,7 +1725,7 @@ mod tests {
fn test_download_status_transitions() {
let db = setup_test_db();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Insert pending download
conn.execute(
@@ -1978,7 +1771,7 @@ mod tests {
fn test_download_progress_updates() {
let db = setup_test_db();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
conn.execute(
"INSERT INTO downloads (item_id, user_id, file_path, status, progress, bytes_downloaded, file_size)
@@ -0,0 +1,66 @@
//! Pinning commands - protect an item's cached metadata from cache clearing.
use std::sync::Arc;
use tauri::State;
use crate::commands::DatabaseWrapper;
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
/// Pin an item's metadata (protects from cache clear)
#[tauri::command]
#[specta::specta]
pub async fn pin_item(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let query = Query::with_params(
"UPDATE items SET is_pinned = 1 WHERE id = ?",
vec![QueryParam::String(item_id)],
);
db_service.execute(query).await.map_err(|e| e.to_string())?;
Ok(())
}
/// Unpin an item's metadata
#[tauri::command]
#[specta::specta]
pub async fn unpin_item(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let query = Query::with_params(
"UPDATE items SET is_pinned = 0 WHERE id = ?",
vec![QueryParam::String(item_id)],
);
db_service.execute(query).await.map_err(|e| e.to_string())?;
Ok(())
}
/// Check if an item is pinned
#[tauri::command]
#[specta::specta]
pub async fn is_item_pinned(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<bool, 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 COALESCE(is_pinned, 0) FROM items WHERE id = ?",
vec![QueryParam::String(item_id)],
);
let is_pinned: i32 = db_service
.query_optional(query, |row| row.get(0))
.await
.map_err(|e| e.to_string())?
.unwrap_or(0);
Ok(is_pinned == 1)
}
@@ -0,0 +1,228 @@
//! Smart-cache statistics/config and album recommendation commands.
use std::sync::Arc;
use log::info;
use tauri::State;
use crate::commands::{DatabaseWrapper, SmartCacheWrapper};
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
/// SmartCache statistics
#[derive(specta::Type, Debug, Clone, serde::Serialize)]
pub struct SmartCacheStats {
pub total_size: u64,
pub storage_limit: u64,
pub available_space: u64,
pub items_count: i64,
pub config: crate::download::cache::CacheConfig,
}
/// Get SmartCache statistics
#[tauri::command]
#[specta::specta]
pub async fn get_smart_cache_stats(
db: State<'_, DatabaseWrapper>,
smart_cache: State<'_, SmartCacheWrapper>,
user_id: String,
) -> Result<SmartCacheStats, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
// Clone cache to avoid holding lock across async operations
let cache = {
let guard = smart_cache.0.lock().map_err(|e| e.to_string())?;
guard.clone()
};
let total_size = cache
.get_total_download_size_async(&db_service, &user_id)
.await?;
let config = cache
.get_config()
.ok_or_else(|| "Failed to get cache config".to_string())?;
let storage_limit = config.storage_limit;
let available_space = storage_limit.saturating_sub(total_size);
// Get item count
let count_query = Query::with_params(
"SELECT COUNT(*) FROM downloads WHERE user_id = ? AND status = 'completed'",
vec![QueryParam::String(user_id)],
);
let items_count: i64 = db_service
.query_one(count_query, |row| row.get(0))
.await
.unwrap_or(0);
Ok(SmartCacheStats {
total_size,
storage_limit,
available_space,
items_count,
config,
})
}
/// Update SmartCache configuration
#[tauri::command]
#[specta::specta]
pub async fn update_smart_cache_config(
smart_cache: State<'_, SmartCacheWrapper>,
config: crate::download::cache::CacheConfig,
) -> Result<(), String> {
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
cache.update_config(config);
info!("Updated SmartCache configuration");
Ok(())
}
/// Get SmartCache configuration
#[tauri::command]
#[specta::specta]
pub async fn get_smart_cache_config(
smart_cache: State<'_, SmartCacheWrapper>,
) -> Result<crate::download::cache::CacheConfig, String> {
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
cache
.get_config()
.ok_or_else(|| "Failed to get cache config".to_string())
}
/// Album recommendation info
#[derive(specta::Type, Debug, Clone, serde::Serialize)]
pub struct AlbumRecommendation {
pub album_id: String,
pub album_name: String,
pub tracks_played: usize,
pub total_tracks: usize,
pub should_download: bool,
}
/// Album affinity status info
#[derive(specta::Type, Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AlbumAffinityStatus {
pub album_id: String,
pub unique_tracks_played: usize,
pub threshold: usize,
pub threshold_reached: bool,
}
/// Get album recommendations based on play history
#[tauri::command]
#[specta::specta]
pub async fn get_album_recommendations(
db: State<'_, DatabaseWrapper>,
smart_cache: State<'_, SmartCacheWrapper>,
user_id: String,
) -> Result<Vec<AlbumRecommendation>, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
// Clone cache to avoid holding lock across async operations
let cache = {
let guard = smart_cache.0.lock().map_err(|e| e.to_string())?;
guard.clone()
};
// Get all albums that user has played tracks from
let query = Query::with_params(
"SELECT DISTINCT i.album_id, a.name
FROM user_data ud
JOIN items i ON ud.item_id = i.id
JOIN items a ON i.album_id = a.id
WHERE ud.user_id = ?
AND ud.play_count > 0
AND i.item_type = 'Audio'
AND i.album_id IS NOT NULL",
vec![QueryParam::String(user_id.clone())],
);
let albums: Vec<(String, String)> = db_service
.query_many(query, |row| Ok((row.get(0)?, row.get(1)?)))
.await
.unwrap_or_default();
let mut recommendations = Vec::new();
for (album_id, album_name) in albums {
// Check if should cache
let should_download = cache.should_cache_album(&album_id).unwrap_or(false);
// Get track counts
let tracks_query = Query::with_params(
"SELECT
COUNT(*) as total,
COUNT(ud.id) as played
FROM items i
LEFT JOIN user_data ud ON i.id = ud.item_id AND ud.user_id = ?
WHERE i.album_id = ? AND i.item_type = 'Audio'",
vec![
QueryParam::String(user_id.clone()),
QueryParam::String(album_id.clone()),
],
);
let (total_tracks, tracks_played): (i64, i64) = db_service
.query_one(tracks_query, |row| Ok((row.get(0)?, row.get(1)?)))
.await
.unwrap_or((0, 0));
if tracks_played > 0 {
recommendations.push(AlbumRecommendation {
album_id,
album_name,
tracks_played: tracks_played as usize,
total_tracks: total_tracks as usize,
should_download,
});
}
}
// Sort by tracks played (descending)
recommendations.sort_by(|a, b| b.tracks_played.cmp(&a.tracks_played));
Ok(recommendations)
}
/// Get album affinity status for all tracked albums
/// This shows the SmartCache's internal play history and threshold status
#[tauri::command]
#[specta::specta]
pub fn get_album_affinity_status(
smart_cache: State<'_, SmartCacheWrapper>,
) -> Result<Vec<AlbumAffinityStatus>, String> {
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
// Get the threshold from config
let threshold = cache
.get_config()
.map(|c| c.album_affinity_threshold)
.unwrap_or(3);
// Get all tracked albums with their play counts
let play_history = cache.get_album_play_history();
let mut statuses: Vec<AlbumAffinityStatus> = play_history
.into_iter()
.map(|(album_id, unique_tracks_played)| {
let threshold_reached = unique_tracks_played >= threshold;
AlbumAffinityStatus {
album_id,
unique_tracks_played,
threshold,
threshold_reached,
}
})
.collect();
// Sort by play count (descending)
statuses.sort_by(|a, b| b.unique_tracks_played.cmp(&a.unique_tracks_played));
Ok(statuses)
}
+4 -1
View File
@@ -7,7 +7,7 @@ use tauri::State;
use super::DatabaseWrapper;
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
#[derive(Debug, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OfflineItem {
pub id: String,
@@ -22,6 +22,7 @@ pub struct OfflineItem {
/// Check if an item is available offline
#[tauri::command]
#[specta::specta]
pub async fn offline_is_available(
db: State<'_, DatabaseWrapper>,
item_id: String,
@@ -46,6 +47,7 @@ pub async fn offline_is_available(
/// Get all offline items for a user
#[tauri::command]
#[specta::specta]
pub async fn offline_get_items(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -84,6 +86,7 @@ pub async fn offline_get_items(
/// Search offline items
#[tauri::command]
#[specta::specta]
pub async fn offline_search(
db: State<'_, DatabaseWrapper>,
user_id: String,
+7 -1
View File
@@ -8,6 +8,7 @@ pub struct PlaybackModeManagerWrapper(pub Arc<PlaybackModeManager>);
/// Get the current playback mode
#[tauri::command]
#[specta::specta]
pub fn playback_mode_get_current(
manager: State<'_, PlaybackModeManagerWrapper>,
) -> Result<PlaybackMode, String> {
@@ -16,6 +17,7 @@ pub fn playback_mode_get_current(
/// Set the playback mode (internal/testing use)
#[tauri::command]
#[specta::specta]
pub fn playback_mode_set(
manager: State<'_, PlaybackModeManagerWrapper>,
mode: PlaybackMode,
@@ -26,6 +28,7 @@ pub fn playback_mode_set(
/// Check if currently transferring between playback modes
#[tauri::command]
#[specta::specta]
pub fn playback_mode_is_transferring(
manager: State<'_, PlaybackModeManagerWrapper>,
) -> Result<bool, String> {
@@ -34,6 +37,7 @@ pub fn playback_mode_is_transferring(
/// Transfer playback from local device to a remote Jellyfin session
#[tauri::command]
#[specta::specta]
pub async fn playback_mode_transfer_to_remote(
manager: State<'_, PlaybackModeManagerWrapper>,
session_id: String,
@@ -51,6 +55,7 @@ pub async fn playback_mode_transfer_to_remote(
/// - current_item_id: The Jellyfin item ID currently playing on remote
/// - position_ticks: Current playback position in ticks (10,000 ticks = 1ms)
#[tauri::command]
#[specta::specta]
pub async fn playback_mode_transfer_to_local(
manager: State<'_, PlaybackModeManagerWrapper>,
current_item_id: String,
@@ -69,6 +74,7 @@ pub async fn playback_mode_transfer_to_local(
/// Get remote session status (for polling position/duration)
#[tauri::command]
#[specta::specta]
pub async fn playback_mode_get_remote_status(
manager: State<'_, PlaybackModeManagerWrapper>,
player: State<'_, crate::commands::PlayerStateWrapper>,
@@ -119,7 +125,7 @@ pub async fn playback_mode_get_remote_status(
}
/// Remote session status for UI updates
#[derive(serde::Serialize)]
#[derive(specta::Type, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoteSessionStatus {
pub position: f64,
@@ -24,6 +24,7 @@ pub struct PlaybackReporterWrapper(pub Arc<TokioMutex<Option<PlaybackReporter>>>
/// Initialize playback reporter (called after login)
#[tauri::command]
#[specta::specta]
pub async fn playback_reporter_init(
reporter_wrapper: State<'_, PlaybackReporterWrapper>,
db: State<'_, DatabaseWrapper>,
@@ -66,6 +67,7 @@ pub async fn playback_reporter_init(
/// Destroy playback reporter (called on logout)
#[tauri::command]
#[specta::specta]
pub async fn playback_reporter_destroy(
reporter_wrapper: State<'_, PlaybackReporterWrapper>,
) -> Result<(), String> {
@@ -76,6 +78,7 @@ pub async fn playback_reporter_destroy(
/// Report playback start
#[tauri::command]
#[specta::specta]
pub async fn playback_report_start(
reporter: State<'_, PlaybackReporterWrapper>,
connectivity: State<'_, ConnectivityMonitorWrapper>,
@@ -110,6 +113,7 @@ pub async fn playback_report_start(
/// Report playback progress
#[tauri::command]
#[specta::specta]
pub async fn playback_report_progress(
reporter: State<'_, PlaybackReporterWrapper>,
connectivity: State<'_, ConnectivityMonitorWrapper>,
@@ -138,6 +142,7 @@ pub async fn playback_report_progress(
/// Report playback stopped
#[tauri::command]
#[specta::specta]
pub async fn playback_report_stopped(
reporter: State<'_, PlaybackReporterWrapper>,
connectivity: State<'_, ConnectivityMonitorWrapper>,
@@ -164,6 +169,7 @@ pub async fn playback_report_stopped(
/// Mark item as played
#[tauri::command]
#[specta::specta]
pub async fn playback_mark_played(
reporter: State<'_, PlaybackReporterWrapper>,
connectivity: State<'_, ConnectivityMonitorWrapper>,
File diff suppressed because it is too large Load Diff
+368
View File
@@ -0,0 +1,368 @@
//! Queue manipulation commands (add / remove / move / skip).
use std::path::PathBuf;
use log::info;
use serde::Deserialize;
use tauri::State;
use super::{
check_for_local_download, create_media_item, get_player_status, get_queue_status,
DatabaseWrapper, PlayItemRequest, PlayerStateWrapper, PlayerStatus, QueueStatus,
};
use crate::commands::repository::RepositoryManagerWrapper;
use crate::player::{MediaItem, MediaSource, MediaType};
use crate::repository::types::{ImageOptions, ImageType};
use crate::repository::MediaRepository;
/// Request to add items to queue
#[derive(specta::Type, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddToQueueRequest {
pub items: Vec<PlayItemRequest>,
pub position: String, // "next" or "end"
}
/// Request to add a track by ID - backend fetches metadata
#[derive(specta::Type, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddTrackByIdRequest {
pub track_id: String,
pub position: String, // "next" or "end"
}
/// Request to add multiple tracks by IDs - backend fetches metadata
#[derive(specta::Type, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddTracksByIdsRequest {
pub track_ids: Vec<String>,
pub position: String, // "next" or "end"
}
#[tauri::command]
#[specta::specta]
pub async fn player_add_to_queue(
player: State<'_, PlayerStateWrapper>,
db: State<'_, DatabaseWrapper>,
request: AddToQueueRequest,
) -> Result<QueueStatus, String> {
use crate::player::queue::AddPosition;
let position = match request.position.as_str() {
"next" => AddPosition::Next,
_ => AddPosition::End,
};
// Create media items first (without holding any locks during await)
let mut items: Vec<MediaItem> = Vec::new();
for req in request.items {
items.push(create_media_item(req, Some(&db)).await?);
}
// Now add to queue
let controller = player.0.lock().await;
let queue = controller.queue();
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
queue_lock.add(items, position);
let result = QueueStatus {
items: queue_lock.items().to_vec(),
current_index: queue_lock.current_index(),
shuffle: queue_lock.is_shuffle(),
repeat: queue_lock.repeat_mode(),
has_next: queue_lock.has_next(),
has_previous: queue_lock.has_previous(),
};
drop(queue_lock);
controller.emit_queue_changed();
Ok(result)
}
#[tauri::command]
#[specta::specta]
pub async fn player_remove_from_queue(
player: State<'_, PlayerStateWrapper>,
index: usize,
) -> Result<QueueStatus, String> {
let controller = player.0.lock().await;
let queue = controller.queue();
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
queue_lock.remove(index);
let result = QueueStatus {
items: queue_lock.items().to_vec(),
current_index: queue_lock.current_index(),
shuffle: queue_lock.is_shuffle(),
repeat: queue_lock.repeat_mode(),
has_next: queue_lock.has_next(),
has_previous: queue_lock.has_previous(),
};
drop(queue_lock);
controller.emit_queue_changed();
Ok(result)
}
#[tauri::command]
#[specta::specta]
pub async fn player_move_in_queue(
player: State<'_, PlayerStateWrapper>,
from_index: usize,
to_index: usize,
) -> Result<QueueStatus, String> {
let controller = player.0.lock().await;
let queue = controller.queue();
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
if !queue_lock.move_item(from_index, to_index) {
return Err("Invalid indices for move operation".to_string());
}
let result = QueueStatus {
items: queue_lock.items().to_vec(),
current_index: queue_lock.current_index(),
shuffle: queue_lock.is_shuffle(),
repeat: queue_lock.repeat_mode(),
has_next: queue_lock.has_next(),
has_previous: queue_lock.has_previous(),
};
drop(queue_lock);
controller.emit_queue_changed();
Ok(result)
}
/// Add a track to queue by ID - backend fetches metadata and constructs URLs
#[tauri::command]
#[specta::specta]
pub async fn player_add_track_by_id(
player: State<'_, PlayerStateWrapper>,
db: State<'_, DatabaseWrapper>,
repository_manager: State<'_, RepositoryManagerWrapper>,
repository_handle: String,
request: AddTrackByIdRequest,
) -> Result<QueueStatus, String> {
use crate::player::queue::AddPosition;
info!("player_add_track_by_id called: track_id={}, position={}",
request.track_id, request.position);
// Get repository (hybrid - supports offline/online)
let repository = repository_manager.0.get(&repository_handle)
.ok_or("Repository not found - user may need to log in")?;
// Fetch track metadata via repository
info!("Fetching metadata for track {} via repository", request.track_id);
let track = repository.get_item(&request.track_id).await
.map_err(|e| format!("Failed to fetch track metadata: {}", e))?;
// Check for local download first
let local_path = check_for_local_download(&db, &request.track_id).await?;
let source = if let Some(path) = local_path {
info!("Using local download for track {}", request.track_id);
MediaSource::Local {
file_path: PathBuf::from(path),
jellyfin_item_id: Some(track.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 {
stream_url,
jellyfin_item_id: track.id.clone(),
}
};
// Build MediaItem with artwork URL from repository and frontend-compatible fields
let primary_image_tag_for_url = track.primary_image_tag.clone();
let media_item = MediaItem {
id: track.id.clone(),
title: track.name.clone(),
name: Some(track.name.clone()), // Frontend compatibility
artist: track.album_artist.clone().or_else(|| track.artists.as_ref().and_then(|a| a.first().cloned())),
album: track.album_name.clone(),
album_name: track.album_name.clone(), // Frontend compatibility
album_id: track.album_id.clone(),
artist_items: track.artist_items.clone(), // For clickable artist links
artists: track.artists.clone(), // Fallback artist info
primary_image_tag: track.primary_image_tag.clone(), // For frontend image display
item_type: Some(track.item_type.clone()), // Frontend compatibility
playlist_id: None,
duration: track.runtime_ticks.map(|t| t as f64 / 10_000_000.0),
artwork_url: primary_image_tag_for_url.and_then(|tag| {
track.album_id.as_ref().map(|album_id| {
repository.get_image_url(album_id, ImageType::Primary, Some(ImageOptions {
max_width: Some(300),
tag: Some(tag),
..Default::default()
}))
})
}),
media_type: MediaType::Audio,
source,
video_codec: None,
needs_transcoding: false,
video_width: None,
video_height: None,
subtitles: vec![],
series_id: None,
server_id: None,
};
// Add to queue at specified position
let position = match request.position.as_str() {
"next" => AddPosition::Next,
_ => AddPosition::End,
};
let controller = player.0.lock().await;
let queue = controller.queue();
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
queue_lock.add(vec![media_item], position);
let result = get_queue_status(&controller);
drop(queue_lock);
controller.emit_queue_changed();
info!("Successfully added track {} to queue", request.track_id);
Ok(result)
}
/// Add multiple tracks to queue by IDs - backend fetches metadata and constructs URLs
#[tauri::command]
#[specta::specta]
pub async fn player_add_tracks_by_ids(
player: State<'_, PlayerStateWrapper>,
db: State<'_, DatabaseWrapper>,
repository_manager: State<'_, RepositoryManagerWrapper>,
repository_handle: String,
request: AddTracksByIdsRequest,
) -> Result<QueueStatus, String> {
use crate::player::queue::AddPosition;
info!("player_add_tracks_by_ids called: {} tracks, position={}",
request.track_ids.len(), request.position);
// Get repository (hybrid - supports offline/online)
let repository = repository_manager.0.get(&repository_handle)
.ok_or("Repository not found - user may need to log in")?;
// Fetch metadata and build MediaItems for all tracks
let mut media_items = Vec::new();
for track_id in &request.track_ids {
info!("Fetching metadata for track {} via repository", track_id);
let track = repository.get_item(track_id).await
.map_err(|e| format!("Failed to fetch track metadata for {}: {}", track_id, e))?;
// Check for local download first
let local_path = check_for_local_download(&db, track_id).await?;
let source = if let Some(path) = local_path {
info!("Using local download for track {}", track_id);
MediaSource::Local {
file_path: PathBuf::from(path),
jellyfin_item_id: Some(track.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 {
stream_url,
jellyfin_item_id: track.id.clone(),
}
};
// Build MediaItem with artwork URL from repository and frontend-compatible fields
let primary_image_tag_for_url = track.primary_image_tag.clone();
let media_item = MediaItem {
id: track.id.clone(),
title: track.name.clone(),
name: Some(track.name.clone()), // Frontend compatibility
artist: track.album_artist.clone().or_else(|| track.artists.as_ref().and_then(|a| a.first().cloned())),
album: track.album_name.clone(),
album_name: track.album_name.clone(), // Frontend compatibility
album_id: track.album_id.clone(),
artist_items: track.artist_items.clone(), // For clickable artist links
artists: track.artists.clone(), // Fallback artist info
primary_image_tag: track.primary_image_tag.clone(), // For frontend image display
item_type: Some(track.item_type.clone()), // Frontend compatibility
playlist_id: None,
duration: track.runtime_ticks.map(|t| t as f64 / 10_000_000.0),
artwork_url: primary_image_tag_for_url.and_then(|tag| {
track.album_id.as_ref().map(|album_id| {
repository.get_image_url(album_id, ImageType::Primary, Some(ImageOptions {
max_width: Some(300),
tag: Some(tag),
..Default::default()
}))
})
}),
media_type: MediaType::Audio,
source,
video_codec: None,
needs_transcoding: false,
video_width: None,
video_height: None,
subtitles: vec![],
series_id: None,
server_id: None,
};
media_items.push(media_item);
}
// Add to queue at specified position
let position = match request.position.as_str() {
"next" => AddPosition::Next,
_ => AddPosition::End,
};
let controller = player.0.lock().await;
let queue = controller.queue();
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
queue_lock.add(media_items, position);
let result = get_queue_status(&controller);
drop(queue_lock);
controller.emit_queue_changed();
info!("Successfully added {} tracks to queue", request.track_ids.len());
Ok(result)
}
#[tauri::command]
#[specta::specta]
pub async fn player_skip_to(
player: State<'_, PlayerStateWrapper>,
index: usize,
) -> Result<PlayerStatus, String> {
let controller = player.0.lock().await;
// Skip to the index and get the item to play
let item = {
let queue = controller.queue();
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
queue_lock.skip_to(index).cloned().ok_or("Invalid index")?
};
// Play the item without modifying the queue
controller.load_and_play(&item).map_err(|e| e.to_string())?;
// Emit queue changed event
controller.emit_queue_changed();
Ok(get_player_status(&controller))
}
+131
View File
@@ -0,0 +1,131 @@
//! Remote Jellyfin session control commands (casting to another device).
//!
//! These thin command adapters forward control actions to the active Jellyfin
//! session via the player's configured `JellyfinClient`.
use tauri::State;
use super::PlayerStateWrapper;
/// Play items on a remote Jellyfin session (casting)
#[tauri::command]
#[specta::specta]
pub async fn remote_play_on_session(
player: State<'_, PlayerStateWrapper>,
session_id: String,
item_ids: Vec<String>,
start_index: usize,
) -> Result<(), String> {
log::info!("[RemoteSession] Playing {} items on session {} (start index: {})", item_ids.len(), session_id, start_index);
log::info!("[RemoteSession] Item IDs: {:?}", item_ids);
let client_opt = {
let controller = player.0.lock().await;
controller.jellyfin_client().lock().map_err(|e| e.to_string())?.clone()
};
if let Some(client) = client_opt {
log::info!("[RemoteSession] Jellyfin client IS configured, calling play_on_session");
client.play_on_session(session_id, item_ids, start_index, None).await?;
log::info!("[RemoteSession] Successfully started playback on remote session");
Ok(())
} else {
log::error!("[RemoteSession] Jellyfin client is NOT configured! User needs to log out/in or restart app");
Err("Jellyfin client not configured - please restart the app or log out and log back in".to_string())
}
}
/// Send a playback command to a remote session
#[tauri::command]
#[specta::specta]
pub async fn remote_send_command(
player: State<'_, PlayerStateWrapper>,
session_id: String,
command: String,
) -> Result<(), String> {
log::info!("[RemoteSession] Sending command '{}' to session {}", command, session_id);
let client_opt = {
let controller = player.0.lock().await;
controller.jellyfin_client().lock().map_err(|e| e.to_string())?.clone()
};
if let Some(client) = client_opt {
client.send_session_command(session_id, &command).await?;
log::info!("[RemoteSession] Command sent successfully");
Ok(())
} else {
Err("Jellyfin client not configured".to_string())
}
}
/// Seek on a remote session
#[tauri::command]
#[specta::specta]
pub async fn remote_session_seek(
player: State<'_, PlayerStateWrapper>,
session_id: String,
position_ticks: i64,
) -> Result<(), String> {
log::info!("[RemoteSession] Seeking to {} ticks on session {}", position_ticks, session_id);
let client_opt = {
let controller = player.0.lock().await;
controller.jellyfin_client().lock().map_err(|e| e.to_string())?.clone()
};
if let Some(client) = client_opt {
client.session_seek(session_id, position_ticks).await?;
log::info!("[RemoteSession] Seek successful");
Ok(())
} else {
Err("Jellyfin client not configured".to_string())
}
}
/// Set volume on a remote session
#[tauri::command]
#[specta::specta]
pub async fn remote_session_set_volume(
player: State<'_, PlayerStateWrapper>,
session_id: String,
volume: i32,
) -> Result<(), String> {
log::info!("[RemoteSession] Setting volume to {} on session {}", volume, session_id);
let client_opt = {
let controller = player.0.lock().await;
controller.jellyfin_client().lock().map_err(|e| e.to_string())?.clone()
};
if let Some(client) = client_opt {
client.session_set_volume(session_id, volume).await?;
log::info!("[RemoteSession] Volume set successfully");
Ok(())
} else {
Err("Jellyfin client not configured".to_string())
}
}
/// Toggle mute on a remote session
#[tauri::command]
#[specta::specta]
pub async fn remote_session_toggle_mute(
player: State<'_, PlayerStateWrapper>,
session_id: String,
) -> Result<(), String> {
log::info!("[RemoteSession] Toggling mute on session {}", session_id);
let client_opt = {
let controller = player.0.lock().await;
controller.jellyfin_client().lock().map_err(|e| e.to_string())?.clone()
};
if let Some(client) = client_opt {
client.session_toggle_mute(session_id).await?;
log::info!("[RemoteSession] Mute toggled successfully");
Ok(())
} else {
Err("Jellyfin client not configured".to_string())
}
}
+45
View File
@@ -0,0 +1,45 @@
//! Media session state commands.
//!
//! Read and dismiss the current media session (the Now Playing surface backing
//! lockscreen/notification controls).
use tauri::State;
use super::{MediaSessionManagerWrapper, PlayerStateWrapper};
use crate::player::PlayerStatusEvent;
/// Get the current media session state
#[tauri::command]
#[specta::specta]
pub async fn player_get_session(
session: State<'_, MediaSessionManagerWrapper>,
) -> Result<crate::player::session::MediaSessionType, String> {
let manager = session.0.lock().map_err(|e| e.to_string())?;
Ok(manager.current().clone())
}
/// Dismiss the current media session (returns to Idle)
#[tauri::command]
#[specta::specta]
pub async fn player_dismiss_session(
session: State<'_, MediaSessionManagerWrapper>,
player: State<'_, PlayerStateWrapper>,
) -> Result<(), String> {
log::info!("[Session] Dismissing current media session");
// Dismiss the session
{
let mut manager = session.0.lock().map_err(|e| e.to_string())?;
manager.dismiss();
}
// Emit session changed event
if let Some(emitter) = player.0.lock().await.event_emitter() {
let manager = session.0.lock().map_err(|e| e.to_string())?;
emitter.emit(PlayerStatusEvent::SessionChanged {
session: manager.current().clone(),
});
}
Ok(())
}
+62
View File
@@ -0,0 +1,62 @@
//! Audio and video playback settings commands.
use tauri::State;
use super::{PlayerStateWrapper, VideoSettingsWrapper};
use crate::player::AutoplaySettings;
use crate::settings::{AudioSettings, VideoSettings};
#[tauri::command]
#[specta::specta]
pub async fn player_set_audio_settings(
player: State<'_, PlayerStateWrapper>,
settings: AudioSettings,
) -> Result<AudioSettings, String> {
let mut controller = player.0.lock().await;
controller
.set_audio_settings(&settings)
.map_err(|e| e.to_string())?;
Ok(controller.audio_settings())
}
#[tauri::command]
#[specta::specta]
pub async fn player_get_audio_settings(
player: State<'_, PlayerStateWrapper>,
) -> Result<AudioSettings, String> {
let controller = player.0.lock().await;
Ok(controller.audio_settings())
}
#[tauri::command]
#[specta::specta]
pub async fn player_set_video_settings(
video_settings: State<'_, VideoSettingsWrapper>,
player: State<'_, PlayerStateWrapper>,
settings: VideoSettings,
) -> Result<VideoSettings, String> {
let validated = settings.with_countdown_clamped();
{
let mut current = video_settings.0.lock().map_err(|e| e.to_string())?;
*current = validated.clone();
} // Drop MutexGuard before await
// Sync to PlayerController's autoplay settings so on_playback_ended() uses current values
let controller = player.0.lock().await;
controller.set_autoplay_settings(AutoplaySettings {
enabled: validated.auto_play_next_episode,
countdown_seconds: validated.auto_play_countdown_seconds,
max_episodes: validated.auto_play_max_episodes,
});
Ok(validated)
}
#[tauri::command]
#[specta::specta]
pub async fn player_get_video_settings(
video_settings: State<'_, VideoSettingsWrapper>,
) -> Result<VideoSettings, String> {
let current = video_settings.0.lock().map_err(|e| e.to_string())?;
Ok(current.clone())
}
+237
View File
@@ -0,0 +1,237 @@
//! Sleep-timer and autoplay commands.
//!
//! Thin command adapters over `PlayerController`'s sleep-timer and autoplay
//! logic, plus persistence of autoplay settings to the database.
use std::sync::Arc;
use tauri::State;
use super::{
create_media_item, get_player_status, DatabaseWrapper, PlayItemRequest, PlayerStatus,
PlayerStateWrapper,
};
use crate::player::{AutoplaySettings, SleepTimerMode, SleepTimerState};
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
// ===== Sleep Timer Commands =====
/// Set sleep timer mode
#[tauri::command]
#[specta::specta]
pub async fn player_set_sleep_timer(
player: State<'_, PlayerStateWrapper>,
mode: SleepTimerMode,
) -> Result<SleepTimerState, String> {
let controller = player.0.lock().await;
controller.set_sleep_timer(mode);
Ok(controller.sleep_timer_state())
}
/// Cancel sleep timer
#[tauri::command]
#[specta::specta]
pub async fn player_cancel_sleep_timer(
player: State<'_, PlayerStateWrapper>,
) -> Result<SleepTimerState, String> {
let controller = player.0.lock().await;
controller.cancel_sleep_timer();
Ok(controller.sleep_timer_state())
}
/// Get current sleep timer state
#[tauri::command]
#[specta::specta]
pub async fn player_get_sleep_timer(
player: State<'_, PlayerStateWrapper>,
) -> Result<SleepTimerState, String> {
let controller = player.0.lock().await;
Ok(controller.sleep_timer_state())
}
// ===== Autoplay Commands =====
/// Get autoplay settings
#[tauri::command]
#[specta::specta]
pub async fn player_get_autoplay_settings(
player: State<'_, PlayerStateWrapper>,
) -> Result<AutoplaySettings, String> {
let controller = player.0.lock().await;
Ok(controller.autoplay_settings())
}
/// Set autoplay settings and persist to database
#[tauri::command]
#[specta::specta]
pub async fn player_set_autoplay_settings(
player: State<'_, PlayerStateWrapper>,
db: State<'_, DatabaseWrapper>,
user_id: String,
settings: AutoplaySettings,
) -> Result<AutoplaySettings, String> {
let validated = settings.with_validated_countdown();
// Set in controller
{
let controller = player.0.lock().await;
controller.set_autoplay_settings(validated.clone());
}
// Persist to database
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let query = Query::with_params(
"INSERT INTO user_player_settings (user_id, autoplay_next_episode, autoplay_countdown_seconds, autoplay_max_episodes, updated_at)
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(user_id) DO UPDATE SET
autoplay_next_episode = excluded.autoplay_next_episode,
autoplay_countdown_seconds = excluded.autoplay_countdown_seconds,
autoplay_max_episodes = excluded.autoplay_max_episodes,
updated_at = CURRENT_TIMESTAMP",
vec![
QueryParam::String(user_id),
QueryParam::Int(if validated.enabled { 1 } else { 0 }),
QueryParam::Int(validated.countdown_seconds as i32),
QueryParam::Int(validated.max_episodes as i32),
],
);
db_service.execute(query).await.map_err(|e| e.to_string())?;
Ok(validated)
}
/// Cancel active autoplay countdown
#[tauri::command]
#[specta::specta]
pub async fn player_cancel_autoplay_countdown(
player: State<'_, PlayerStateWrapper>,
) -> Result<(), String> {
let controller = player.0.lock().await;
controller.cancel_autoplay_countdown();
Ok(())
}
/// Play next episode (user confirmed from popup)
#[tauri::command]
#[specta::specta]
pub async fn player_play_next_episode(
player: State<'_, PlayerStateWrapper>,
db: State<'_, DatabaseWrapper>,
item: PlayItemRequest,
) -> Result<PlayerStatus, String> {
// Convert request to MediaItem
let media_item = create_media_item(item, Some(&db)).await?;
let controller = player.0.lock().await;
controller.play_item(media_item).map_err(|e| e.to_string())?;
Ok(get_player_status(&controller))
}
/// Handle playback ended event - triggers autoplay decision logic
/// This is called from:
/// - Frontend when HTML5 video ends (Linux/desktop) - passes itemId + repositoryHandle for the video
/// - Frontend when audio track ends via backend event - no itemId/repositoryHandle needed
/// - Android JNI callback also triggers this logic directly
#[tauri::command]
#[specta::specta]
pub async fn player_on_playback_ended(
player: State<'_, PlayerStateWrapper>,
repository_manager: State<'_, crate::commands::repository::RepositoryManagerWrapper>,
item_id: Option<String>,
repository_handle: Option<String>,
) -> Result<(), String> {
use crate::player::autoplay::AutoplayDecision;
use crate::player::PlayerStatusEvent;
let controller_arc = player.0.clone();
// Run autoplay decision logic
// If item_id is provided (HTML5 video case), use the video-specific path
// that bypasses the backend queue and stale end_reason
let decision = {
let controller = controller_arc.lock().await;
if let Some(ref id) = item_id {
// Video path: need repository to look up episode info
let repo = repository_handle
.as_ref()
.and_then(|handle| repository_manager.0.get(handle));
if let Some(repo) = repo {
controller.on_video_playback_ended(id, repo).await?
} else {
log::warn!("[Autoplay] No repository available for video autoplay (itemId: {})", id);
AutoplayDecision::Stop
}
} else {
controller.on_playback_ended().await?
}
};
// Handle the decision
match decision {
AutoplayDecision::Stop => {
log::debug!("[Autoplay] Decision: Stop playback");
let controller = controller_arc.lock().await;
if let Some(emitter) = controller.event_emitter() {
// Emit StateChanged to idle to clear the current media from mini player
// Note: Do NOT emit PlaybackEnded here - it would cause an infinite loop
// (frontend receives PlaybackEnded → calls player_on_playback_ended → Stop → PlaybackEnded → ...)
emitter.emit(PlayerStatusEvent::StateChanged {
state: "idle".to_string(),
media_id: None,
});
}
}
AutoplayDecision::AdvanceToNext => {
log::debug!("[Autoplay] Decision: Advance to next track");
// Advance to next track in queue
let controller = controller_arc.lock().await;
if let Err(e) = controller.next() {
log::error!("[Autoplay] Failed to advance to next track: {}", e);
// Emit PlaybackEnded event on error
if let Some(emitter) = controller.event_emitter() {
emitter.emit(PlayerStatusEvent::PlaybackEnded);
}
} else {
// Emit queue changed event so frontend updates UI with new current track
controller.emit_queue_changed();
}
}
AutoplayDecision::ShowNextEpisodePopup {
current_episode,
next_episode,
countdown_seconds,
auto_advance,
} => {
log::info!(
"[Autoplay] Decision: Show next episode popup (countdown: {}s, auto: {})",
countdown_seconds,
auto_advance
);
// Emit popup event to frontend
if let Some(emitter) = controller_arc.lock().await.event_emitter() {
emitter.emit(PlayerStatusEvent::ShowNextEpisodePopup {
current_episode: current_episode.clone(),
next_episode: next_episode.clone(),
countdown_seconds,
auto_advance,
});
}
// Start countdown if auto_advance enabled
if auto_advance {
controller_arc
.lock()
.await
.start_autoplay_countdown(next_episode, countdown_seconds);
}
}
}
Ok(())
}
+7
View File
@@ -11,6 +11,7 @@ use super::repository::RepositoryManagerWrapper;
/// Create a new playlist
#[tauri::command]
#[specta::specta]
pub async fn playlist_create(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -27,6 +28,7 @@ pub async fn playlist_create(
/// Delete a playlist
#[tauri::command]
#[specta::specta]
pub async fn playlist_delete(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -41,6 +43,7 @@ pub async fn playlist_delete(
/// Rename a playlist
#[tauri::command]
#[specta::specta]
pub async fn playlist_rename(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -56,6 +59,7 @@ pub async fn playlist_rename(
/// Get playlist items with PlaylistItemId
#[tauri::command]
#[specta::specta]
pub async fn playlist_get_items(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -70,6 +74,7 @@ pub async fn playlist_get_items(
/// Add items to a playlist
#[tauri::command]
#[specta::specta]
pub async fn playlist_add_items(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -85,6 +90,7 @@ pub async fn playlist_add_items(
/// Remove items from a playlist (uses PlaylistItemId entry IDs, NOT media item IDs)
#[tauri::command]
#[specta::specta]
pub async fn playlist_remove_items(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -100,6 +106,7 @@ pub async fn playlist_remove_items(
/// Move a playlist item to a new position
#[tauri::command]
#[specta::specta]
pub async fn playlist_move_item(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
+46 -9
View File
@@ -3,6 +3,7 @@
//!
//! TRACES: UR-007, UR-035, UR-036 | JA-004, JA-005, JA-029, JA-030, JA-031
use crate::utils::lock::MutexSafe;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
@@ -26,17 +27,17 @@ impl RepositoryManager {
}
pub fn create(&self, handle: String, repository: HybridRepository) {
let mut repos = self.repositories.lock().unwrap();
let mut repos = self.repositories.lock_safe();
repos.insert(handle, Arc::new(repository));
}
pub fn get(&self, handle: &str) -> Option<Arc<HybridRepository>> {
let repos = self.repositories.lock().unwrap();
let repos = self.repositories.lock_safe();
repos.get(handle).cloned()
}
pub fn destroy(&self, handle: &str) {
let mut repos = self.repositories.lock().unwrap();
let mut repos = self.repositories.lock_safe();
repos.remove(handle);
}
}
@@ -47,9 +48,11 @@ pub struct RepositoryManagerWrapper(pub RepositoryManager);
/// Create a new repository instance
/// Returns a handle (UUID) for accessing the repository
#[tauri::command]
#[specta::specta]
pub async fn repository_create(
manager: State<'_, RepositoryManagerWrapper>,
db: State<'_, crate::commands::storage::DatabaseWrapper>,
connectivity: State<'_, crate::commands::connectivity::ConnectivityMonitorWrapper>,
server_url: String,
user_id: String,
access_token: String,
@@ -66,9 +69,18 @@ pub async fn repository_create(
})?;
debug!("[REPO] HTTP client created successfully");
// Create online repository
// Grab a connectivity reporter so the online repository's server outcomes
// drive the reachability state the UI observes (source of truth for the
// offline/online banner). See docs/architecture/07-connectivity.md.
let connectivity_reporter = {
let monitor = connectivity.0.lock().await;
monitor.reporter()
};
// Create online repository wired to connectivity reporting
debug!("[REPO] Creating online repository...");
let online = OnlineRepository::new(Arc::new(http_client), server_url, user_id.clone(), access_token);
let online = OnlineRepository::new(Arc::new(http_client), server_url, user_id.clone(), access_token)
.with_connectivity(connectivity_reporter);
debug!("[REPO] Online repository created");
// Create offline repository with async-safe database service
@@ -107,6 +119,7 @@ pub async fn repository_create(
/// Destroy a repository instance
#[tauri::command]
#[specta::specta]
pub async fn repository_destroy(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -117,6 +130,7 @@ pub async fn repository_destroy(
/// Get libraries
#[tauri::command]
#[specta::specta]
pub async fn repository_get_libraries(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -137,6 +151,7 @@ pub async fn repository_get_libraries(
/// Get items in a container (library, folder, album, etc.)
#[tauri::command]
#[specta::specta]
pub async fn repository_get_items(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -151,6 +166,7 @@ pub async fn repository_get_items(
/// Get a single item by ID
#[tauri::command]
#[specta::specta]
pub async fn repository_get_item(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -164,6 +180,7 @@ pub async fn repository_get_item(
/// Get latest items in a library
#[tauri::command]
#[specta::specta]
pub async fn repository_get_latest_items(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -178,6 +195,7 @@ pub async fn repository_get_latest_items(
/// Get resume items (continue watching/listening)
#[tauri::command]
#[specta::specta]
pub async fn repository_get_resume_items(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -200,6 +218,7 @@ pub async fn repository_get_resume_items(
/// Get next up episodes
#[tauri::command]
#[specta::specta]
pub async fn repository_get_next_up_episodes(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -214,6 +233,7 @@ pub async fn repository_get_next_up_episodes(
/// Get recently played audio
#[tauri::command]
#[specta::specta]
pub async fn repository_get_recently_played_audio(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -227,6 +247,7 @@ pub async fn repository_get_recently_played_audio(
/// Get resume movies
#[tauri::command]
#[specta::specta]
pub async fn repository_get_resume_movies(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -240,6 +261,7 @@ pub async fn repository_get_resume_movies(
/// Get genres for a library
#[tauri::command]
#[specta::specta]
pub async fn repository_get_genres(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -253,6 +275,7 @@ pub async fn repository_get_genres(
/// Search for items
#[tauri::command]
#[specta::specta]
pub async fn repository_search(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -267,6 +290,7 @@ pub async fn repository_search(
/// Get playback info for an item
#[tauri::command]
#[specta::specta]
pub async fn repository_get_playback_info(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -280,6 +304,7 @@ pub async fn repository_get_playback_info(
/// Get video stream URL with optional seeking support
#[tauri::command]
#[specta::specta]
pub async fn repository_get_video_stream_url(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -302,6 +327,7 @@ pub async fn repository_get_video_stream_url(
/// Get audio stream URL for a track
#[tauri::command]
#[specta::specta]
pub async fn repository_get_audio_stream_url(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -316,6 +342,7 @@ pub async fn repository_get_audio_stream_url(
/// Report playback start
#[tauri::command]
#[specta::specta]
pub async fn repository_report_playback_start(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -330,6 +357,7 @@ pub async fn repository_report_playback_start(
/// Report playback progress
#[tauri::command]
#[specta::specta]
pub async fn repository_report_playback_progress(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -344,6 +372,7 @@ pub async fn repository_report_playback_progress(
/// Report playback stopped
#[tauri::command]
#[specta::specta]
pub async fn repository_report_playback_stopped(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -358,6 +387,7 @@ pub async fn repository_report_playback_stopped(
/// Get image URL for an item
#[tauri::command]
#[specta::specta]
pub fn repository_get_image_url(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -371,6 +401,7 @@ pub fn repository_get_image_url(
/// Get subtitle URL for a media item
#[tauri::command]
#[specta::specta]
#[allow(dead_code)]
pub fn repository_get_subtitle_url(
manager: State<'_, RepositoryManagerWrapper>,
@@ -386,6 +417,7 @@ pub fn repository_get_subtitle_url(
/// Get video download URL with quality preset
#[tauri::command]
#[specta::specta]
#[allow(dead_code)]
pub fn repository_get_video_download_url(
manager: State<'_, RepositoryManagerWrapper>,
@@ -400,6 +432,7 @@ pub fn repository_get_video_download_url(
/// Mark an item as favorite
#[tauri::command]
#[specta::specta]
pub async fn repository_mark_favorite(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -413,6 +446,7 @@ pub async fn repository_mark_favorite(
/// Unmark an item as favorite
#[tauri::command]
#[specta::specta]
pub async fn repository_unmark_favorite(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -426,6 +460,7 @@ pub async fn repository_unmark_favorite(
/// Get person details
#[tauri::command]
#[specta::specta]
pub async fn repository_get_person(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -439,6 +474,7 @@ pub async fn repository_get_person(
/// Get items by person (actor, director, etc.)
#[tauri::command]
#[specta::specta]
pub async fn repository_get_items_by_person(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -453,6 +489,7 @@ pub async fn repository_get_items_by_person(
/// Get similar/related items for a media item
#[tauri::command]
#[specta::specta]
pub async fn repository_get_similar_items(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
@@ -472,16 +509,16 @@ mod tests {
#[test]
fn test_repository_manager_creation() {
let manager = RepositoryManager::new();
// Should be able to create RepositoryManager without panicking
assert_eq!(std::mem::size_of::<RepositoryManager>() > 0, true);
// A freshly created manager holds no repositories
assert!(manager.get("any-handle").is_none());
}
#[test]
fn test_repository_manager_wrapper_structure() {
let manager = RepositoryManager::new();
let wrapper = RepositoryManagerWrapper(manager);
// Verify wrapper holds the manager
assert_eq!(std::mem::size_of::<RepositoryManagerWrapper>() > 0, true);
// The wrapper exposes the underlying manager, which starts empty
assert!(wrapper.0.get("any-handle").is_none());
}
#[test]
+2
View File
@@ -10,6 +10,7 @@ pub struct SessionPollerWrapper(pub Arc<SessionPollerManager>);
/// Set polling frequency hint based on UI state
#[tauri::command]
#[specta::specta]
pub fn sessions_set_polling_hint(
poller: State<'_, SessionPollerWrapper>,
hint: String,
@@ -27,6 +28,7 @@ pub fn sessions_set_polling_hint(
/// Manually trigger a session poll (for refresh button)
#[tauri::command]
#[specta::specta]
pub async fn sessions_poll_now(
poller: State<'_, SessionPollerWrapper>,
) -> Result<Vec<SessionInfo>, String> {
@@ -1,7 +1,6 @@
//! Tauri commands for database/storage operations
use std::sync::{Arc, Mutex, OnceLock};
use tokio::sync::Semaphore;
use std::sync::{Arc, Mutex};
use log::{debug, error, info, warn};
use serde::{Deserialize, Serialize};
@@ -10,12 +9,19 @@ use tauri::State;
use crate::credentials::CredentialStore;
use crate::storage::Database;
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
use crate::thumbnail::{ThumbnailCache, ThumbnailCacheStats, ThumbnailWorker};
use crate::repository::types::{ImageType, ImageOptions};
use crate::repository::MediaRepository;
use crate::thumbnail::ThumbnailCache;
use super::SmartCacheWrapper;
// Cohesive command clusters in their own submodules, re-exported so the command
// names remain at `commands::storage::*` (invoke_handler unchanged).
mod people;
mod series_prefs;
mod thumbnails;
pub use people::*;
pub use series_prefs::*;
pub use thumbnails::*;
/// Wrapper for thread-safe database access
pub struct DatabaseWrapper(pub Mutex<Database>);
@@ -26,7 +32,7 @@ pub struct CredentialStoreWrapper(pub Mutex<CredentialStore>);
pub struct ThumbnailCacheWrapper(pub Arc<ThumbnailCache>);
/// Server info returned to frontend
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
pub struct ServerInfo {
pub id: String,
pub name: String,
@@ -35,7 +41,7 @@ pub struct ServerInfo {
}
/// User info returned to frontend
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserInfo {
pub id: String,
@@ -45,7 +51,7 @@ pub struct UserInfo {
}
/// Active session info (for session restoration)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActiveSession {
pub user_id: String,
@@ -57,7 +63,7 @@ pub struct ActiveSession {
}
/// Security status info
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SecurityStatus {
pub using_keyring: bool,
@@ -66,6 +72,7 @@ pub struct SecurityStatus {
/// Initialize the database and run migrations
#[tauri::command]
#[specta::specta]
pub fn storage_init(db: State<DatabaseWrapper>) -> Result<String, String> {
let database = db.0.lock().map_err(|e| e.to_string())?;
Ok(database.path().to_string_lossy().to_string())
@@ -73,6 +80,7 @@ pub fn storage_init(db: State<DatabaseWrapper>) -> Result<String, String> {
/// Get storage directory path (parent directory of the database file)
#[tauri::command]
#[specta::specta]
pub fn storage_get_path(db: State<DatabaseWrapper>) -> Result<String, String> {
let database = db.0.lock().map_err(|e| e.to_string())?;
let db_path = database.path();
@@ -86,6 +94,7 @@ pub fn storage_get_path(db: State<DatabaseWrapper>) -> Result<String, String> {
/// Get database file size in bytes
#[tauri::command]
#[specta::specta]
pub fn storage_get_size(db: State<DatabaseWrapper>) -> Result<Option<u64>, String> {
let database = db.0.lock().map_err(|e| e.to_string())?;
Ok(database.file_size())
@@ -93,6 +102,7 @@ pub fn storage_get_size(db: State<DatabaseWrapper>) -> Result<Option<u64>, Strin
/// Get security status (keyring vs encrypted file fallback)
#[tauri::command]
#[specta::specta]
pub fn storage_get_security_status(
creds: State<CredentialStoreWrapper>,
) -> Result<SecurityStatus, String> {
@@ -111,6 +121,7 @@ pub fn storage_get_security_status(
/// Save a server connection
/// Uses INSERT ... ON CONFLICT to avoid triggering CASCADE DELETE on users
#[tauri::command]
#[specta::specta]
pub async fn storage_save_server(
db: State<'_, DatabaseWrapper>,
id: String,
@@ -148,6 +159,7 @@ pub async fn storage_save_server(
/// Get all saved servers
#[tauri::command]
#[specta::specta]
pub async fn storage_get_servers(db: State<'_, DatabaseWrapper>) -> Result<Vec<ServerInfo>, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
@@ -173,6 +185,7 @@ pub async fn storage_get_servers(db: State<'_, DatabaseWrapper>) -> Result<Vec<S
/// Delete a server and all associated data
#[tauri::command]
#[specta::specta]
pub async fn storage_delete_server(
db: State<'_, DatabaseWrapper>,
creds: State<'_, CredentialStoreWrapper>,
@@ -215,6 +228,7 @@ pub async fn storage_delete_server(
/// Save a user account (token stored in secure storage, not database)
#[tauri::command]
#[specta::specta]
pub async fn storage_save_user(
db: State<'_, DatabaseWrapper>,
creds: State<'_, CredentialStoreWrapper>,
@@ -292,6 +306,7 @@ pub async fn storage_save_user(
/// Get users for a server
#[tauri::command]
#[specta::specta]
pub async fn storage_get_users(
db: State<'_, DatabaseWrapper>,
server_id: String,
@@ -324,6 +339,7 @@ pub async fn storage_get_users(
/// Set a user as active (and deactivate all other users globally)
#[tauri::command]
#[specta::specta]
pub async fn storage_set_active_user(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -372,6 +388,7 @@ pub async fn storage_set_active_user(
/// Get the active user for a server
#[tauri::command]
#[specta::specta]
pub async fn storage_get_active_user(
db: State<'_, DatabaseWrapper>,
server_id: String,
@@ -402,6 +419,7 @@ pub async fn storage_get_active_user(
/// Get the active session (user + server + token) for session restoration
#[tauri::command]
#[specta::specta]
pub async fn storage_get_active_session(
db: State<'_, DatabaseWrapper>,
creds: State<'_, CredentialStoreWrapper>,
@@ -477,6 +495,7 @@ pub async fn storage_get_active_session(
/// Get user's access token from secure storage
#[tauri::command]
#[specta::specta]
pub fn storage_get_access_token(
creds: State<CredentialStoreWrapper>,
user_id: String,
@@ -491,6 +510,7 @@ pub fn storage_get_access_token(
/// Delete a user account and their token from secure storage
#[tauri::command]
#[specta::specta]
pub async fn storage_delete_user(
db: State<'_, DatabaseWrapper>,
creds: State<'_, CredentialStoreWrapper>,
@@ -523,7 +543,7 @@ pub async fn storage_delete_user(
}
/// Playback progress info
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlaybackProgress {
pub item_id: String,
@@ -536,6 +556,7 @@ pub struct PlaybackProgress {
/// Update playback progress in local database
/// This stores the progress locally for offline access and "continue watching"
#[tauri::command]
#[specta::specta]
pub async fn storage_update_playback_progress(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -587,6 +608,7 @@ pub async fn storage_update_playback_progress(
/// Update playback progress with context in local database
/// This stores the progress along with playback context (container vs single)
#[tauri::command]
#[specta::specta]
pub async fn storage_update_playback_context(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -636,6 +658,7 @@ pub async fn storage_update_playback_context(
/// Mark item as played in local database
#[tauri::command]
#[specta::specta]
pub async fn storage_mark_played(
db: State<'_, DatabaseWrapper>,
smart_cache: State<'_, SmartCacheWrapper>,
@@ -766,6 +789,7 @@ pub async fn storage_mark_played(
/// Get playback progress for an item
#[tauri::command]
#[specta::specta]
pub async fn storage_get_playback_progress(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -798,6 +822,7 @@ pub async fn storage_get_playback_progress(
/// Mark pending sync as completed for an item
#[tauri::command]
#[specta::specta]
pub async fn storage_mark_synced(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -822,6 +847,7 @@ pub async fn storage_mark_synced(
/// Toggle favorite status for an item in local database
/// This updates the is_favorite field and marks it for sync to Jellyfin
#[tauri::command]
#[specta::specta]
pub async fn storage_toggle_favorite(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -867,7 +893,7 @@ pub async fn storage_toggle_favorite(
// =============================================================================
/// Cached library info returned to frontend
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedLibrary {
pub id: String,
@@ -878,7 +904,7 @@ pub struct CachedLibrary {
}
/// Cached media item returned to frontend
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedItem {
pub id: String,
@@ -909,6 +935,7 @@ pub struct CachedItem {
/// Get cached libraries for a server
#[tauri::command]
#[specta::specta]
pub async fn storage_get_libraries(
db: State<'_, DatabaseWrapper>,
server_id: String,
@@ -971,6 +998,7 @@ fn row_to_cached_item(row: &rusqlite::Row) -> rusqlite::Result<CachedItem> {
/// Get cached items with optional filtering
#[tauri::command]
#[specta::specta]
pub async fn storage_get_items(
db: State<'_, DatabaseWrapper>,
server_id: String,
@@ -1037,6 +1065,7 @@ pub async fn storage_get_items(
/// Get a single cached item by ID
#[tauri::command]
#[specta::specta]
pub async fn storage_get_item(
db: State<'_, DatabaseWrapper>,
item_id: String,
@@ -1064,6 +1093,7 @@ pub async fn storage_get_item(
/// Search cached items using FTS
#[tauri::command]
#[specta::specta]
pub async fn storage_search_items(
db: State<'_, DatabaseWrapper>,
server_id: String,
@@ -1105,6 +1135,7 @@ pub async fn storage_search_items(
/// Save a library to the cache
#[tauri::command]
#[specta::specta]
pub async fn storage_save_library(
db: State<'_, DatabaseWrapper>,
id: String,
@@ -1138,6 +1169,7 @@ pub async fn storage_save_library(
/// Save an item to the cache
#[tauri::command]
#[specta::specta]
pub async fn storage_save_item(
db: State<'_, DatabaseWrapper>,
item: CachedItem,
@@ -1201,6 +1233,7 @@ pub async fn storage_save_item(
/// Get count of pending sync operations for a user
#[tauri::command]
#[specta::specta]
pub async fn storage_get_pending_sync_count(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -1223,491 +1256,6 @@ pub async fn storage_get_pending_sync_count(
Ok(count)
}
// =============================================================================
// Thumbnail Cache Commands
// =============================================================================
/// Get cached thumbnail path, returns None if not cached
/// Also updates last_accessed timestamp for LRU tracking
#[tauri::command]
pub async fn thumbnail_get_cached(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
item_id: String,
image_type: String,
tag: String,
) -> Result<Option<String>, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let result = thumbnail_cache.0
.get_cached_path(db_service, &item_id, &image_type, &tag)
.await
.map(|p| p.to_string_lossy().to_string());
Ok(result)
}
/// Download and save a thumbnail to cache
/// Returns the local file path on success
#[tauri::command]
pub async fn thumbnail_save(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
item_id: String,
image_type: String,
tag: String,
url: String,
) -> Result<String, String> {
// Download the image
let worker = ThumbnailWorker::new();
let data = worker
.download_with_retry(&url, 2)
.await
.map_err(|e| e.to_string())?;
// Save to cache
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let path = thumbnail_cache.0.save_thumbnail(db_service, &item_id, &image_type, &tag, &data, None, None).await?;
Ok(path.to_string_lossy().to_string())
}
/// Get thumbnail cache statistics
#[tauri::command]
pub async fn thumbnail_get_stats(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
) -> Result<ThumbnailCacheStats, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let total_size_bytes = thumbnail_cache.0.get_cache_size(db_service.clone()).await;
let item_count = thumbnail_cache.0.get_item_count(db_service.clone()).await;
let limit_bytes = thumbnail_cache.0.get_limit(db_service).await;
Ok(ThumbnailCacheStats {
total_size_bytes,
item_count,
limit_bytes,
})
}
/// Set thumbnail cache storage limit in bytes
#[tauri::command]
pub async fn thumbnail_set_limit(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
limit_bytes: u64,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
thumbnail_cache.0.set_limit(db_service, limit_bytes).await
}
/// Clear all cached thumbnails
#[tauri::command]
pub async fn thumbnail_clear_cache(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
thumbnail_cache.0.clear_cache(db_service).await
}
/// Delete cached thumbnails for a specific item
#[tauri::command]
pub async fn thumbnail_delete_item(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
item_id: String,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
thumbnail_cache.0.delete_item(db_service, &item_id).await
}
fn mime_from_ext(ext: Option<&str>) -> &'static str {
match ext {
Some("jpg") | Some("jpeg") => "image/jpeg",
Some("png") => "image/png",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
_ => "image/jpeg",
}
}
/// Limit concurrent image downloads to avoid saturating the connection pool.
/// Without this, rendering a page with hundreds of album cards fires hundreds of
/// concurrent HTTP requests, starving API calls and causing timeouts.
static IMAGE_DOWNLOAD_SEMAPHORE: OnceLock<Semaphore> = OnceLock::new();
fn image_semaphore() -> &'static Semaphore {
IMAGE_DOWNLOAD_SEMAPHORE.get_or_init(|| Semaphore::new(6))
}
/// Request to get an image URL (with caching)
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetImageRequest {
pub item_id: String,
pub image_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_width: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_height: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
}
/// Get image as base64 data URL, caching if not already cached
/// This extends the thumbnail system to serve all images through Rust with automatic caching
#[tauri::command]
pub async fn image_get_url(
repository_manager: State<'_, super::repository::RepositoryManagerWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
db: State<'_, DatabaseWrapper>,
repository_handle: String,
request: GetImageRequest,
) -> Result<String, String> {
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use std::fs;
let tag = request.tag.as_deref().unwrap_or("default");
// Get database service
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
// Check cache first
if let Some(cached_path) = thumbnail_cache.0.get_cached_path(
db_service.clone(),
&request.item_id,
&request.image_type,
tag,
).await {
let image_data = fs::read(&cached_path)
.map_err(|e| format!("Failed to read cached image: {}", e))?;
let base64_data = BASE64.encode(&image_data);
let mime_type = mime_from_ext(cached_path.extension().and_then(|s| s.to_str()));
return Ok(format!("data:{};base64,{}", mime_type, base64_data));
}
// Not cached — fetch from server and cache.
// Acquire semaphore to limit concurrent downloads (prevents connection pool starvation).
let _permit = image_semaphore().acquire().await
.map_err(|_| "Image download semaphore closed".to_string())?;
let repository = repository_manager.0.get(&repository_handle)
.ok_or_else(|| "Repository not found - user may need to log in".to_string())?;
let image_type_enum = match request.image_type.as_str() {
"Primary" => ImageType::Primary,
"Backdrop" => ImageType::Backdrop,
"Banner" => ImageType::Banner,
"Thumb" => ImageType::Thumb,
"Logo" => ImageType::Logo,
_ => ImageType::Primary,
};
let options = ImageOptions {
max_width: request.max_width,
max_height: request.max_height,
quality: Some(90),
tag: request.tag.clone(),
};
let server_url = repository.get_image_url(&request.item_id, image_type_enum, Some(options));
let image_data = repository.download_bytes(&server_url).await
.map_err(|e| format!("Failed to download image: {}", e))?;
let cached_path = thumbnail_cache.0.save_thumbnail(
db_service,
&request.item_id,
&request.image_type,
tag,
&image_data,
request.max_width.map(|w| w as i32),
request.max_height.map(|h| h as i32),
).await?;
let base64_data = BASE64.encode(&image_data);
let mime_type = mime_from_ext(cached_path.extension().and_then(|s| s.to_str()));
Ok(format!("data:{};base64,{}", mime_type, base64_data))
}
// =============================================================================
// People/Cast Cache Commands
// =============================================================================
/// Cached person info returned to frontend
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedPerson {
pub id: String,
pub server_id: String,
pub name: String,
pub overview: Option<String>,
pub primary_image_tag: Option<String>,
pub premiere_date: Option<String>,
pub end_date: Option<String>,
}
/// Item-person association for caching
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedItemPerson {
pub item_id: String,
pub person_id: String,
pub server_id: String,
pub person_type: String,
pub role: Option<String>,
pub sort_order: i32,
}
/// Save a person to the cache
#[tauri::command]
pub async fn storage_save_person(
db: State<'_, DatabaseWrapper>,
person: CachedPerson,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let query = Query::with_params(
"INSERT OR REPLACE INTO people (
id, server_id, name, overview, primary_image_tag,
premiere_date, end_date, synced_at
) VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)",
vec![
QueryParam::String(person.id),
QueryParam::String(person.server_id),
QueryParam::String(person.name),
person.overview.map(QueryParam::String).unwrap_or(QueryParam::Null),
person.primary_image_tag.map(QueryParam::String).unwrap_or(QueryParam::Null),
person.premiere_date.map(QueryParam::String).unwrap_or(QueryParam::Null),
person.end_date.map(QueryParam::String).unwrap_or(QueryParam::Null),
],
);
db_service.execute(query).await.map_err(|e| e.to_string())?;
Ok(())
}
/// Get a cached person by ID
#[tauri::command]
pub async fn storage_get_person(
db: State<'_, DatabaseWrapper>,
person_id: String,
) -> Result<Option<CachedPerson>, 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 id, server_id, name, overview, primary_image_tag, premiere_date, end_date
FROM people WHERE id = ?",
vec![QueryParam::String(person_id)],
);
let result = db_service
.query_optional(query, |row| {
Ok(CachedPerson {
id: row.get(0)?,
server_id: row.get(1)?,
name: row.get(2)?,
overview: row.get(3)?,
primary_image_tag: row.get(4)?,
premiere_date: row.get(5)?,
end_date: row.get(6)?,
})
})
.await
.map_err(|e| e.to_string())?;
Ok(result)
}
/// Save item-person associations (batch)
#[tauri::command]
pub async fn storage_save_item_people(
db: State<'_, DatabaseWrapper>,
associations: Vec<CachedItemPerson>,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
// Clone associations for the closure
let associations_clone = associations.clone();
// Use transaction for batch insert
db_service.transaction(move |tx| {
for assoc in &associations_clone {
let query = Query::with_params(
"INSERT OR REPLACE INTO item_people (
item_id, person_id, server_id, person_type, role, sort_order, synced_at
) VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)",
vec![
QueryParam::String(assoc.item_id.clone()),
QueryParam::String(assoc.person_id.clone()),
QueryParam::String(assoc.server_id.clone()),
QueryParam::String(assoc.person_type.clone()),
assoc.role.clone().map(QueryParam::String).unwrap_or(QueryParam::Null),
QueryParam::Int(assoc.sort_order),
],
);
tx.execute(query)?;
}
Ok(())
}).await.map_err(|e| e.to_string())?;
Ok(())
}
/// Get people for an item (with person details joined)
#[tauri::command]
pub async fn storage_get_item_people(
db: State<'_, DatabaseWrapper>,
item_id: String,
) -> Result<Vec<CachedItemPerson>, 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 ip.item_id, ip.person_id, ip.server_id, ip.person_type, ip.role, ip.sort_order
FROM item_people ip
WHERE ip.item_id = ?
ORDER BY ip.sort_order ASC",
vec![QueryParam::String(item_id)],
);
let people = db_service
.query_many(query, |row| {
Ok(CachedItemPerson {
item_id: row.get(0)?,
person_id: row.get(1)?,
server_id: row.get(2)?,
person_type: row.get(3)?,
role: row.get(4)?,
sort_order: row.get(5)?,
})
})
.await
.map_err(|e| e.to_string())?;
Ok(people)
}
// ===== Series Audio Preferences =====
/// Audio track preference for a series
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SeriesAudioPreference {
pub series_id: String,
pub audio_track_display_title: Option<String>,
pub audio_track_language: Option<String>,
pub audio_track_index: Option<i32>,
}
/// Save user's preferred audio track for a series
#[tauri::command]
pub async fn storage_save_series_audio_preference(
db: State<'_, DatabaseWrapper>,
user_id: String,
series_id: String,
server_id: String,
audio_track_display_title: Option<String>,
audio_track_language: Option<String>,
audio_track_index: Option<i32>,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let query = Query::with_params(
"INSERT INTO series_audio_preferences
(user_id, series_id, server_id, audio_track_display_title, audio_track_language, audio_track_index, updated_at)
VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
ON CONFLICT (user_id, series_id, server_id) DO UPDATE SET
audio_track_display_title = excluded.audio_track_display_title,
audio_track_language = excluded.audio_track_language,
audio_track_index = excluded.audio_track_index,
updated_at = datetime('now')",
vec![
QueryParam::String(user_id),
QueryParam::String(series_id),
QueryParam::String(server_id),
audio_track_display_title.map(QueryParam::String).unwrap_or(QueryParam::Null),
audio_track_language.map(QueryParam::String).unwrap_or(QueryParam::Null),
audio_track_index.map(|i| QueryParam::Int64(i as i64)).unwrap_or(QueryParam::Null),
],
);
db_service.execute(query).await.map_err(|e| e.to_string())?;
Ok(())
}
/// Get user's preferred audio track for a series
#[tauri::command]
pub async fn storage_get_series_audio_preference(
db: State<'_, DatabaseWrapper>,
user_id: String,
series_id: String,
) -> Result<Option<SeriesAudioPreference>, 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 series_id, audio_track_display_title, audio_track_language, audio_track_index
FROM series_audio_preferences
WHERE user_id = ? AND series_id = ?",
vec![QueryParam::String(user_id), QueryParam::String(series_id)],
);
let preference = db_service
.query_optional(query, |row| {
Ok(SeriesAudioPreference {
series_id: row.get(0)?,
audio_track_display_title: row.get(1)?,
audio_track_language: row.get(2)?,
audio_track_index: row.get(3)?,
})
})
.await
.map_err(|e| e.to_string())?;
Ok(preference)
}
#[cfg(test)]
mod tests {
+179
View File
@@ -0,0 +1,179 @@
//! Person/cast metadata cache commands.
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use tauri::State;
use super::DatabaseWrapper;
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
/// Cached person info returned to frontend
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedPerson {
pub id: String,
pub server_id: String,
pub name: String,
pub overview: Option<String>,
pub primary_image_tag: Option<String>,
pub premiere_date: Option<String>,
pub end_date: Option<String>,
}
/// Item-person association for caching
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedItemPerson {
pub item_id: String,
pub person_id: String,
pub server_id: String,
pub person_type: String,
pub role: Option<String>,
pub sort_order: i32,
}
/// Save a person to the cache
#[tauri::command]
#[specta::specta]
pub async fn storage_save_person(
db: State<'_, DatabaseWrapper>,
person: CachedPerson,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let query = Query::with_params(
"INSERT OR REPLACE INTO people (
id, server_id, name, overview, primary_image_tag,
premiere_date, end_date, synced_at
) VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)",
vec![
QueryParam::String(person.id),
QueryParam::String(person.server_id),
QueryParam::String(person.name),
person.overview.map(QueryParam::String).unwrap_or(QueryParam::Null),
person.primary_image_tag.map(QueryParam::String).unwrap_or(QueryParam::Null),
person.premiere_date.map(QueryParam::String).unwrap_or(QueryParam::Null),
person.end_date.map(QueryParam::String).unwrap_or(QueryParam::Null),
],
);
db_service.execute(query).await.map_err(|e| e.to_string())?;
Ok(())
}
/// Get a cached person by ID
#[tauri::command]
#[specta::specta]
pub async fn storage_get_person(
db: State<'_, DatabaseWrapper>,
person_id: String,
) -> Result<Option<CachedPerson>, 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 id, server_id, name, overview, primary_image_tag, premiere_date, end_date
FROM people WHERE id = ?",
vec![QueryParam::String(person_id)],
);
let result = db_service
.query_optional(query, |row| {
Ok(CachedPerson {
id: row.get(0)?,
server_id: row.get(1)?,
name: row.get(2)?,
overview: row.get(3)?,
primary_image_tag: row.get(4)?,
premiere_date: row.get(5)?,
end_date: row.get(6)?,
})
})
.await
.map_err(|e| e.to_string())?;
Ok(result)
}
/// Save item-person associations (batch)
#[tauri::command]
#[specta::specta]
pub async fn storage_save_item_people(
db: State<'_, DatabaseWrapper>,
associations: Vec<CachedItemPerson>,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
// Clone associations for the closure
let associations_clone = associations.clone();
// Use transaction for batch insert
db_service.transaction(move |tx| {
for assoc in &associations_clone {
let query = Query::with_params(
"INSERT OR REPLACE INTO item_people (
item_id, person_id, server_id, person_type, role, sort_order, synced_at
) VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)",
vec![
QueryParam::String(assoc.item_id.clone()),
QueryParam::String(assoc.person_id.clone()),
QueryParam::String(assoc.server_id.clone()),
QueryParam::String(assoc.person_type.clone()),
assoc.role.clone().map(QueryParam::String).unwrap_or(QueryParam::Null),
QueryParam::Int(assoc.sort_order),
],
);
tx.execute(query)?;
}
Ok(())
}).await.map_err(|e| e.to_string())?;
Ok(())
}
/// Get people for an item (with person details joined)
#[tauri::command]
#[specta::specta]
pub async fn storage_get_item_people(
db: State<'_, DatabaseWrapper>,
item_id: String,
) -> Result<Vec<CachedItemPerson>, 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 ip.item_id, ip.person_id, ip.server_id, ip.person_type, ip.role, ip.sort_order
FROM item_people ip
WHERE ip.item_id = ?
ORDER BY ip.sort_order ASC",
vec![QueryParam::String(item_id)],
);
let people = db_service
.query_many(query, |row| {
Ok(CachedItemPerson {
item_id: row.get(0)?,
person_id: row.get(1)?,
server_id: row.get(2)?,
person_type: row.get(3)?,
role: row.get(4)?,
sort_order: row.get(5)?,
})
})
.await
.map_err(|e| e.to_string())?;
Ok(people)
}
@@ -0,0 +1,94 @@
//! Per-series preferred audio track commands.
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use tauri::State;
use super::DatabaseWrapper;
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
/// Audio track preference for a series
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SeriesAudioPreference {
pub series_id: String,
pub audio_track_display_title: Option<String>,
pub audio_track_language: Option<String>,
pub audio_track_index: Option<i32>,
}
/// Save user's preferred audio track for a series
#[tauri::command]
#[specta::specta]
pub async fn storage_save_series_audio_preference(
db: State<'_, DatabaseWrapper>,
user_id: String,
series_id: String,
server_id: String,
audio_track_display_title: Option<String>,
audio_track_language: Option<String>,
audio_track_index: Option<i32>,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let query = Query::with_params(
"INSERT INTO series_audio_preferences
(user_id, series_id, server_id, audio_track_display_title, audio_track_language, audio_track_index, updated_at)
VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
ON CONFLICT (user_id, series_id, server_id) DO UPDATE SET
audio_track_display_title = excluded.audio_track_display_title,
audio_track_language = excluded.audio_track_language,
audio_track_index = excluded.audio_track_index,
updated_at = datetime('now')",
vec![
QueryParam::String(user_id),
QueryParam::String(series_id),
QueryParam::String(server_id),
audio_track_display_title.map(QueryParam::String).unwrap_or(QueryParam::Null),
audio_track_language.map(QueryParam::String).unwrap_or(QueryParam::Null),
audio_track_index.map(|i| QueryParam::Int64(i as i64)).unwrap_or(QueryParam::Null),
],
);
db_service.execute(query).await.map_err(|e| e.to_string())?;
Ok(())
}
/// Get user's preferred audio track for a series
#[tauri::command]
#[specta::specta]
pub async fn storage_get_series_audio_preference(
db: State<'_, DatabaseWrapper>,
user_id: String,
series_id: String,
) -> Result<Option<SeriesAudioPreference>, 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 series_id, audio_track_display_title, audio_track_language, audio_track_index
FROM series_audio_preferences
WHERE user_id = ? AND series_id = ?",
vec![QueryParam::String(user_id), QueryParam::String(series_id)],
);
let preference = db_service
.query_optional(query, |row| {
Ok(SeriesAudioPreference {
series_id: row.get(0)?,
audio_track_display_title: row.get(1)?,
audio_track_language: row.get(2)?,
audio_track_index: row.get(3)?,
})
})
.await
.map_err(|e| e.to_string())?;
Ok(preference)
}
@@ -0,0 +1,248 @@
//! Thumbnail cache and image-URL commands.
use std::sync::{Arc, OnceLock};
use tokio::sync::Semaphore;
use serde::Deserialize;
use tauri::State;
use super::{DatabaseWrapper, ThumbnailCacheWrapper};
use crate::commands::repository::RepositoryManagerWrapper;
use crate::repository::types::{ImageOptions, ImageType};
use crate::repository::MediaRepository;
use crate::thumbnail::{ThumbnailCacheStats, ThumbnailWorker};
/// Get cached thumbnail path, returns None if not cached
/// Also updates last_accessed timestamp for LRU tracking
#[tauri::command]
#[specta::specta]
pub async fn thumbnail_get_cached(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
item_id: String,
image_type: String,
tag: String,
) -> Result<Option<String>, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let result = thumbnail_cache.0
.get_cached_path(db_service, &item_id, &image_type, &tag)
.await
.map(|p| p.to_string_lossy().to_string());
Ok(result)
}
/// Download and save a thumbnail to cache
/// Returns the local file path on success
#[tauri::command]
#[specta::specta]
pub async fn thumbnail_save(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
item_id: String,
image_type: String,
tag: String,
url: String,
) -> Result<String, String> {
// Download the image
let worker = ThumbnailWorker::new();
let data = worker
.download_with_retry(&url, 2)
.await
.map_err(|e| e.to_string())?;
// Save to cache
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let path = thumbnail_cache.0.save_thumbnail(db_service, &item_id, &image_type, &tag, &data, None, None).await?;
Ok(path.to_string_lossy().to_string())
}
/// Get thumbnail cache statistics
#[tauri::command]
#[specta::specta]
pub async fn thumbnail_get_stats(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
) -> Result<ThumbnailCacheStats, String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
let total_size_bytes = thumbnail_cache.0.get_cache_size(db_service.clone()).await;
let item_count = thumbnail_cache.0.get_item_count(db_service.clone()).await;
let limit_bytes = thumbnail_cache.0.get_limit(db_service).await;
Ok(ThumbnailCacheStats {
total_size_bytes,
item_count,
limit_bytes,
})
}
/// Set thumbnail cache storage limit in bytes
#[tauri::command]
#[specta::specta]
pub async fn thumbnail_set_limit(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
limit_bytes: u64,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
thumbnail_cache.0.set_limit(db_service, limit_bytes).await
}
/// Clear all cached thumbnails
#[tauri::command]
#[specta::specta]
pub async fn thumbnail_clear_cache(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
thumbnail_cache.0.clear_cache(db_service).await
}
/// Delete cached thumbnails for a specific item
#[tauri::command]
#[specta::specta]
pub async fn thumbnail_delete_item(
db: State<'_, DatabaseWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
item_id: String,
) -> Result<(), String> {
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
thumbnail_cache.0.delete_item(db_service, &item_id).await
}
fn mime_from_ext(ext: Option<&str>) -> &'static str {
match ext {
Some("jpg") | Some("jpeg") => "image/jpeg",
Some("png") => "image/png",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
_ => "image/jpeg",
}
}
/// Limit concurrent image downloads to avoid saturating the connection pool.
/// Without this, rendering a page with hundreds of album cards fires hundreds of
/// concurrent HTTP requests, starving API calls and causing timeouts.
static IMAGE_DOWNLOAD_SEMAPHORE: OnceLock<Semaphore> = OnceLock::new();
fn image_semaphore() -> &'static Semaphore {
IMAGE_DOWNLOAD_SEMAPHORE.get_or_init(|| Semaphore::new(6))
}
/// Request to get an image URL (with caching)
#[derive(specta::Type, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetImageRequest {
pub item_id: String,
pub image_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_width: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_height: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tag: Option<String>,
}
/// Get image as base64 data URL, caching if not already cached
/// This extends the thumbnail system to serve all images through Rust with automatic caching
#[tauri::command]
#[specta::specta]
pub async fn image_get_url(
repository_manager: State<'_, RepositoryManagerWrapper>,
thumbnail_cache: State<'_, ThumbnailCacheWrapper>,
db: State<'_, DatabaseWrapper>,
repository_handle: String,
request: GetImageRequest,
) -> Result<String, String> {
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use std::fs;
let tag = request.tag.as_deref().unwrap_or("default");
// Get database service
let db_service = {
let database = db.0.lock().map_err(|e| e.to_string())?;
Arc::new(database.service())
};
// Check cache first
if let Some(cached_path) = thumbnail_cache.0.get_cached_path(
db_service.clone(),
&request.item_id,
&request.image_type,
tag,
).await {
let image_data = fs::read(&cached_path)
.map_err(|e| format!("Failed to read cached image: {}", e))?;
let base64_data = BASE64.encode(&image_data);
let mime_type = mime_from_ext(cached_path.extension().and_then(|s| s.to_str()));
return Ok(format!("data:{};base64,{}", mime_type, base64_data));
}
// Not cached — fetch from server and cache.
// Acquire semaphore to limit concurrent downloads (prevents connection pool starvation).
let _permit = image_semaphore().acquire().await
.map_err(|_| "Image download semaphore closed".to_string())?;
let repository = repository_manager.0.get(&repository_handle)
.ok_or_else(|| "Repository not found - user may need to log in".to_string())?;
let image_type_enum = match request.image_type.as_str() {
"Primary" => ImageType::Primary,
"Backdrop" => ImageType::Backdrop,
"Banner" => ImageType::Banner,
"Thumb" => ImageType::Thumb,
"Logo" => ImageType::Logo,
_ => ImageType::Primary,
};
let options = ImageOptions {
max_width: request.max_width,
max_height: request.max_height,
quality: Some(90),
tag: request.tag.clone(),
};
let server_url = repository.get_image_url(&request.item_id, image_type_enum, Some(options));
let image_data = repository.download_bytes(&server_url).await
.map_err(|e| format!("Failed to download image: {}", e))?;
let cached_path = thumbnail_cache.0.save_thumbnail(
db_service,
&request.item_id,
&request.image_type,
tag,
&image_data,
request.max_width.map(|w| w as i32),
request.max_height.map(|h| h as i32),
).await?;
let base64_data = BASE64.encode(&image_data);
let mime_type = mime_from_ext(cached_path.extension().and_then(|s| s.to_str()));
Ok(format!("data:{};base64,{}", mime_type, base64_data))
}
+9 -1
View File
@@ -12,7 +12,7 @@ use super::storage::DatabaseWrapper;
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
/// Sync queue item returned to frontend
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncQueueItem {
pub id: i64,
@@ -28,6 +28,7 @@ pub struct SyncQueueItem {
/// Queue a mutation for sync to server
#[tauri::command]
#[specta::specta]
pub async fn sync_queue_mutation(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -59,6 +60,7 @@ pub async fn sync_queue_mutation(
/// Get all pending sync operations for a user
#[tauri::command]
#[specta::specta]
pub async fn sync_get_pending(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -107,6 +109,7 @@ pub async fn sync_get_pending(
/// Mark a sync operation as in progress
#[tauri::command]
#[specta::specta]
pub async fn sync_mark_processing(
db: State<'_, DatabaseWrapper>,
id: i64,
@@ -127,6 +130,7 @@ pub async fn sync_mark_processing(
/// Mark a sync operation as completed
#[tauri::command]
#[specta::specta]
pub async fn sync_mark_completed(
db: State<'_, DatabaseWrapper>,
id: i64,
@@ -147,6 +151,7 @@ pub async fn sync_mark_completed(
/// Mark a sync operation as failed with error message
#[tauri::command]
#[specta::specta]
pub async fn sync_mark_failed(
db: State<'_, DatabaseWrapper>,
id: i64,
@@ -173,6 +178,7 @@ pub async fn sync_mark_failed(
/// Get count of pending sync operations for a user
#[tauri::command]
#[specta::specta]
pub async fn sync_get_pending_count(
db: State<'_, DatabaseWrapper>,
user_id: String,
@@ -195,6 +201,7 @@ pub async fn sync_get_pending_count(
/// Delete completed sync operations older than specified days
#[tauri::command]
#[specta::specta]
pub async fn sync_cleanup_completed(
db: State<'_, DatabaseWrapper>,
days_old: i32,
@@ -217,6 +224,7 @@ pub async fn sync_cleanup_completed(
/// Delete all sync operations for a user (used during logout)
#[tauri::command]
#[specta::specta]
pub async fn sync_clear_user(
db: State<'_, DatabaseWrapper>,
user_id: String,
+357 -232
View File
@@ -1,18 +1,26 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tauri::{AppHandle, Emitter};
use serde::{Serialize, Deserialize};
use crate::jellyfin::http_client::HttpClient;
// Adaptive polling intervals (matches TypeScript)
const AUTO_CHECK_INTERVAL_MS: u64 = 30000; // 30 seconds when online
const RETRY_CHECK_INTERVAL_MS: u64 = 5000; // 5 seconds when offline
// Offline recovery probe interval.
// Reachability while online is driven by real repository traffic, so there is
// no online polling. While offline we probe quickly to detect the server
// returning even when no user traffic is flowing.
const RETRY_CHECK_INTERVAL_MS: u64 = 5000; // 5 seconds when offline
// Time-window debounce for declaring the server offline.
// A single dropped request must not trip the banner: we only flip to offline
// once network failures have persisted continuously for this window with no
// intervening success. Recovery (online) is instant on the first success.
const OFFLINE_CONFIRM_WINDOW: Duration = Duration::from_secs(5);
/// Connectivity status
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectivityStatus {
/// Whether the Jellyfin server is reachable
@@ -39,216 +47,121 @@ impl Default for ConnectivityStatus {
}
/// Connectivity change event emitted to frontend
#[derive(Debug, Clone, Serialize)]
#[derive(specta::Type, Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct ConnectivityChangeEvent {
is_reachable: bool,
}
/// Connectivity monitor for tracking server reachability
pub struct ConnectivityMonitor {
server_url: Arc<RwLock<Option<String>>>,
http_client: Arc<HttpClient>,
/// Shared reachability state and transition logic.
///
/// This is the single place that mutates reachability and emits events. It is
/// cheap to clone (all fields are `Arc`/`Option`) and is shared by:
/// - the `ConnectivityMonitor` (commands, offline recovery probe), and
/// - `OnlineRepository`, which reports the outcome of every server request.
///
/// Reachability is therefore driven by real traffic; the probe only fills the
/// gap while offline.
#[derive(Clone)]
pub struct ConnectivityReporter {
status: Arc<RwLock<ConnectivityStatus>>,
is_monitoring: Arc<AtomicBool>,
/// Timestamp of the first network failure in the current failure streak.
/// Used to debounce the transition to offline (see `OFFLINE_CONFIRM_WINDOW`).
first_failure_at: Arc<RwLock<Option<Instant>>>,
app_handle: Option<AppHandle>,
}
impl ConnectivityMonitor {
/// Create a new connectivity monitor
pub fn new(http_client: HttpClient) -> Self {
impl ConnectivityReporter {
fn new(status: Arc<RwLock<ConnectivityStatus>>, app_handle: Option<AppHandle>) -> Self {
Self {
server_url: Arc::new(RwLock::new(None)),
http_client: Arc::new(http_client),
status: Arc::new(RwLock::new(ConnectivityStatus::default())),
is_monitoring: Arc::new(AtomicBool::new(false)),
app_handle: None,
status,
first_failure_at: Arc::new(RwLock::new(None)),
app_handle,
}
}
/// Set the Tauri app handle for event emission
pub fn set_app_handle(&mut self, app_handle: AppHandle) {
self.app_handle = Some(app_handle);
/// Current reachability as seen by this reporter (shared with the monitor
/// and the UI). Useful for callers that want to branch on connectivity.
pub async fn is_reachable(&self) -> bool {
self.status.read().await.is_server_reachable
}
/// Update the server URL
pub async fn set_server_url(&self, url: String) {
log::info!("[ConnectivityMonitor] Setting server URL: {}", url);
let mut server_url = self.server_url.write().await;
*server_url = Some(url.clone());
drop(server_url);
// Check new server immediately
log::info!("[ConnectivityMonitor] Checking reachability of new server...");
let is_reachable = self.check_reachability().await;
log::info!("[ConnectivityMonitor] New server is {}", if is_reachable { "REACHABLE" } else { "UNREACHABLE" });
/// Test-only: force the reporter into the offline state without going through
/// the debounce, so other modules' tests can set up an "offline" precondition.
#[cfg(test)]
pub async fn mark_unreachable_for_test(&self) {
self.apply_probe_result(false, Some("forced offline (test)".to_string()))
.await;
}
/// Get current connectivity status
pub async fn get_status(&self) -> ConnectivityStatus {
self.status.read().await.clone()
/// Report that a real server request succeeded (or that the server answered
/// at all, e.g. with 401/404/5xx). The server is up — recover instantly.
pub async fn report_success(&self) {
*self.first_failure_at.write().await = None;
self.set_reachable(true, None).await;
}
/// Check if the Jellyfin server is reachable
pub async fn check_reachability(&self) -> bool {
// Mark as checking
{
let mut status = self.status.write().await;
status.is_checking = true;
/// Report that a real server request failed with a network-level error
/// (connection refused, timeout, DNS). Subject to the time-window debounce:
/// we only flip to offline once failures have persisted for
/// `OFFLINE_CONFIRM_WINDOW` with no intervening success.
pub async fn report_network_failure(&self, error: Option<String>) {
// If already offline, nothing to debounce.
if !self.status.read().await.is_server_reachable {
return;
}
let server_url = self.server_url.read().await.clone();
if server_url.is_none() {
log::warn!("[ConnectivityMonitor] Cannot check reachability: No server URL configured");
let mut status = self.status.write().await;
status.is_server_reachable = false;
status.connection_error = Some("No server URL configured".to_string());
status.is_checking = false;
return false;
}
let url = server_url.unwrap();
let ping_url = format!("{}/System/Info/Public", url);
// Store previous reachability state
let was_reachable = {
let status = self.status.read().await;
status.is_server_reachable
let now = Instant::now();
let streak_start = {
let mut first = self.first_failure_at.write().await;
*first.get_or_insert(now)
};
log::debug!("[ConnectivityMonitor] Pinging server: {}", ping_url);
if now.duration_since(streak_start) >= OFFLINE_CONFIRM_WINDOW {
log::warn!(
"[ConnectivityMonitor] Network failures sustained for {:?}; declaring offline",
OFFLINE_CONFIRM_WINDOW
);
self.set_reachable(false, error).await;
} else {
log::debug!(
"[ConnectivityMonitor] Network failure within debounce window; not yet offline"
);
}
}
// Attempt to ping the server
let is_reachable = self.http_client.ping(&ping_url).await;
/// Apply a deliberate reachability probe result (offline recovery probe or a
/// manual check). Unlike `report_network_failure`, a probe is an explicit
/// reachability test, so its result is applied immediately without debounce.
async fn apply_probe_result(&self, is_reachable: bool, error: Option<String>) {
if is_reachable {
*self.first_failure_at.write().await = None;
}
self.set_reachable(is_reachable, error).await;
}
log::debug!(
"[ConnectivityMonitor] Ping result: {} (was: {})",
if is_reachable { "SUCCESS" } else { "FAILED" },
if was_reachable { "reachable" } else { "unreachable" }
);
// Update status
{
/// Core transition: update status and emit events only on an actual change.
async fn set_reachable(&self, is_reachable: bool, error: Option<String>) {
let was_reachable = {
let mut status = self.status.write().await;
let was = status.is_server_reachable;
status.is_server_reachable = is_reachable;
status.last_checked = Some(chrono::Utc::now().to_rfc3339());
status.connection_error = if is_reachable {
None
} else {
Some("Server unreachable".to_string())
Some(error.unwrap_or_else(|| "Server unreachable".to_string()))
};
status.is_checking = false;
}
was
};
// Emit events if reachability changed
if is_reachable != was_reachable {
self.emit_connectivity_change(is_reachable).await;
}
// Emit reconnection event
if is_reachable && !was_reachable {
self.emit_server_reconnected().await;
}
is_reachable
}
/// Mark server as reachable (called after successful API call)
pub async fn mark_reachable(&self) {
let mut status = self.status.write().await;
let was_reachable = status.is_server_reachable;
status.is_server_reachable = true;
status.last_checked = Some(chrono::Utc::now().to_rfc3339());
status.connection_error = None;
drop(status);
if !was_reachable {
log::info!("[ConnectivityMonitor] Server marked as reachable (was unreachable)");
self.emit_connectivity_change(true).await;
self.emit_server_reconnected().await;
}
}
/// Mark server as unreachable (called after failed API call)
pub async fn mark_unreachable(&self, error: Option<String>) {
let mut status = self.status.write().await;
let was_reachable = status.is_server_reachable;
status.is_server_reachable = false;
status.last_checked = Some(chrono::Utc::now().to_rfc3339());
status.connection_error = error.or_else(|| Some("Server unreachable".to_string()));
let error_msg = status.connection_error.clone().unwrap_or_default();
drop(status);
if was_reachable {
log::warn!("[ConnectivityMonitor] Server marked as unreachable (was reachable): {}", error_msg);
self.emit_connectivity_change(false).await;
}
}
/// Start monitoring connectivity with adaptive polling
pub async fn start_monitoring(&self) {
if self.is_monitoring.swap(true, Ordering::SeqCst) {
log::info!("[ConnectivityMonitor] Already monitoring");
return;
}
log::info!("[ConnectivityMonitor] Starting connectivity monitoring");
// Perform immediate check before starting background task
// This ensures we get an accurate state right away instead of assuming offline
let is_reachable = self.check_reachability().await;
log::info!("[ConnectivityMonitor] Initial connectivity check: {}", if is_reachable { "ONLINE" } else { "OFFLINE" });
// Clone Arc references for the background task
let status = Arc::clone(&self.status);
let is_monitoring = Arc::clone(&self.is_monitoring);
let server_url = Arc::clone(&self.server_url);
let http_client = Arc::clone(&self.http_client);
let self_clone = Arc::new(ConnectivityMonitorHandle {
server_url,
http_client,
status,
app_handle: self.app_handle.clone(),
});
// Spawn background monitoring task
tokio::spawn(async move {
while is_monitoring.load(Ordering::SeqCst) {
// Determine interval based on current reachability
let interval_ms = {
let status = self_clone.status.read().await;
if status.is_server_reachable {
AUTO_CHECK_INTERVAL_MS
} else {
RETRY_CHECK_INTERVAL_MS
}
};
// Wait for the interval
tokio::time::sleep(Duration::from_millis(interval_ms)).await;
// Check if still monitoring
if !is_monitoring.load(Ordering::SeqCst) {
break;
}
// Perform connectivity check
let _ = self_clone.check_reachability().await;
if is_reachable {
self.emit_server_reconnected().await;
}
log::info!("[ConnectivityMonitor] Stopped monitoring");
});
}
/// Stop monitoring connectivity
pub fn stop_monitoring(&self) {
log::info!("[ConnectivityMonitor] Stopping connectivity monitoring");
self.is_monitoring.store(false, Ordering::SeqCst);
}
}
/// Emit connectivity change event to frontend
@@ -275,87 +188,183 @@ impl ConnectivityMonitor {
}
}
/// Handle for the background monitoring task
struct ConnectivityMonitorHandle {
/// Connectivity monitor for tracking server reachability.
///
/// Reachability is driven primarily by real repository traffic via the shared
/// [`ConnectivityReporter`]. The monitor itself only runs an offline recovery
/// probe (see `start_monitoring`) and serves the connectivity Tauri commands.
pub struct ConnectivityMonitor {
server_url: Arc<RwLock<Option<String>>>,
http_client: Arc<HttpClient>,
status: Arc<RwLock<ConnectivityStatus>>,
app_handle: Option<AppHandle>,
reporter: ConnectivityReporter,
is_monitoring: Arc<AtomicBool>,
}
impl ConnectivityMonitorHandle {
async fn check_reachability(&self) -> bool {
impl ConnectivityMonitor {
/// Create a new connectivity monitor
pub fn new(http_client: HttpClient) -> Self {
let status = Arc::new(RwLock::new(ConnectivityStatus::default()));
Self {
server_url: Arc::new(RwLock::new(None)),
http_client: Arc::new(http_client),
reporter: ConnectivityReporter::new(status, None),
is_monitoring: Arc::new(AtomicBool::new(false)),
}
}
/// Set the Tauri app handle for event emission.
/// Must be called before the reporter is shared with the repository.
pub fn set_app_handle(&mut self, app_handle: AppHandle) {
self.reporter.app_handle = Some(app_handle);
}
/// Get a cheap, cloneable reporter so the repository can feed server
/// outcomes into the same reachability state the UI observes.
pub fn reporter(&self) -> ConnectivityReporter {
self.reporter.clone()
}
/// Update the server URL
pub async fn set_server_url(&self, url: String) {
log::info!("[ConnectivityMonitor] Setting server URL: {}", url);
*self.server_url.write().await = Some(url);
// Check new server immediately
log::info!("[ConnectivityMonitor] Checking reachability of new server...");
let is_reachable = self.check_reachability().await;
log::info!("[ConnectivityMonitor] New server is {}", if is_reachable { "REACHABLE" } else { "UNREACHABLE" });
}
/// Get current connectivity status
pub async fn get_status(&self) -> ConnectivityStatus {
self.reporter.status.read().await.clone()
}
/// Deliberately probe the server's reachability (manual check / recovery probe).
/// The result is applied immediately (no debounce) since this is an explicit test.
pub async fn check_reachability(&self) -> bool {
{
let mut status = self.reporter.status.write().await;
status.is_checking = true;
}
let server_url = self.server_url.read().await.clone();
if server_url.is_none() {
let Some(url) = server_url else {
log::warn!("[ConnectivityMonitor] Cannot check reachability: No server URL configured");
self.reporter
.apply_probe_result(false, Some("No server URL configured".to_string()))
.await;
return false;
}
let url = server_url.unwrap();
let ping_url = format!("{}/System/Info/Public", url);
// Store previous reachability state
let was_reachable = {
let status = self.status.read().await;
status.is_server_reachable
};
// Attempt to ping the server
let ping_url = format!("{}/System/Info/Public", url);
log::debug!("[ConnectivityMonitor] Pinging server: {}", ping_url);
let is_reachable = self.http_client.ping(&ping_url).await;
log::debug!(
"[ConnectivityMonitor] Ping result: {}",
if is_reachable { "SUCCESS" } else { "FAILED" }
);
// Update status
{
let mut status = self.status.write().await;
status.is_server_reachable = is_reachable;
status.last_checked = Some(chrono::Utc::now().to_rfc3339());
status.connection_error = if is_reachable {
None
} else {
Some("Server unreachable".to_string())
};
}
// Emit events if reachability changed
if is_reachable != was_reachable {
self.emit_connectivity_change(is_reachable).await;
}
// Emit reconnection event
if is_reachable && !was_reachable {
self.emit_server_reconnected().await;
}
self.reporter.apply_probe_result(is_reachable, None).await;
is_reachable
}
async fn emit_connectivity_change(&self, is_reachable: bool) {
if let Some(app_handle) = &self.app_handle {
let event = ConnectivityChangeEvent { is_reachable };
if let Err(e) = app_handle.emit("connectivity:changed", event) {
log::error!("[ConnectivityMonitor] Failed to emit connectivity change event: {}", e);
}
}
/// Mark server as reachable (called after successful API call / login)
pub async fn mark_reachable(&self) {
self.reporter.report_success().await;
}
async fn emit_server_reconnected(&self) {
if let Some(app_handle) = &self.app_handle {
if let Err(e) = app_handle.emit("connectivity:reconnected", ()) {
log::error!("[ConnectivityMonitor] Failed to emit reconnection event: {}", e);
}
/// Mark server as unreachable directly.
///
/// Used by deliberate signals (e.g. a failed login/connect) where the caller
/// knows the server is unreachable now. Repository traffic should prefer
/// `reporter().report_network_failure()` so the debounce applies.
pub async fn mark_unreachable(&self, error: Option<String>) {
self.reporter.apply_probe_result(false, error).await;
}
/// Start the offline recovery probe.
///
/// While **online**, reachability is kept fresh by real traffic, so the probe
/// idles. While **offline**, it polls `/System/Info/Public` every
/// `RETRY_CHECK_INTERVAL_MS` to detect the server returning even when no user
/// traffic is flowing.
pub async fn start_monitoring(&self) {
if self.is_monitoring.swap(true, Ordering::SeqCst) {
log::info!("[ConnectivityMonitor] Already monitoring");
return;
}
log::info!("[ConnectivityMonitor] Starting connectivity monitoring (offline recovery probe)");
// Perform an immediate check so startup reflects reality quickly.
let is_reachable = self.check_reachability().await;
log::info!("[ConnectivityMonitor] Initial connectivity check: {}", if is_reachable { "ONLINE" } else { "OFFLINE" });
let is_monitoring = Arc::clone(&self.is_monitoring);
let server_url = Arc::clone(&self.server_url);
let http_client = Arc::clone(&self.http_client);
let reporter = self.reporter.clone();
tokio::spawn(async move {
while is_monitoring.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(RETRY_CHECK_INTERVAL_MS)).await;
if !is_monitoring.load(Ordering::SeqCst) {
break;
}
// Only probe while offline — real traffic is the signal when online.
if reporter.status.read().await.is_server_reachable {
continue;
}
let Some(url) = server_url.read().await.clone() else {
continue;
};
let ping_url = format!("{}/System/Info/Public", url);
let is_reachable = http_client.ping(&ping_url).await;
// Probe only ever recovers us to online; a failed probe leaves us
// offline without re-emitting (no change).
if is_reachable {
reporter.apply_probe_result(true, None).await;
}
}
log::info!("[ConnectivityMonitor] Stopped monitoring");
});
}
/// Stop monitoring connectivity
pub fn stop_monitoring(&self) {
log::info!("[ConnectivityMonitor] Stopping connectivity monitoring");
self.is_monitoring.store(false, Ordering::SeqCst);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::jellyfin::http_client::HttpConfig;
/// Build a reporter backed by a fresh (optimistic) status, with no app handle.
/// Event emission is a no-op without a handle, which is exactly what we want
/// for unit-testing the reachability state transitions.
fn test_reporter() -> ConnectivityReporter {
ConnectivityReporter::new(Arc::new(RwLock::new(ConnectivityStatus::default())), None)
}
async fn is_reachable(reporter: &ConnectivityReporter) -> bool {
reporter.status.read().await.is_server_reachable
}
#[test]
fn test_intervals() {
// Verify intervals match TypeScript
assert_eq!(AUTO_CHECK_INTERVAL_MS, 30000);
// Offline recovery probe interval (online has no polling).
assert_eq!(RETRY_CHECK_INTERVAL_MS, 5000);
assert_eq!(OFFLINE_CONFIRM_WINDOW, Duration::from_secs(5));
}
#[tokio::test]
@@ -367,4 +376,120 @@ mod tests {
assert!(status.connection_error.is_none());
assert!(!status.is_checking);
}
/// A single (or brief) network failure must NOT flip the app offline:
/// the time-window debounce keeps us online until the failure persists.
///
/// @req-test: UR-002 - Access media when online or offline
#[tokio::test]
async fn test_single_network_failure_does_not_go_offline() {
let reporter = test_reporter();
assert!(is_reachable(&reporter).await, "starts online");
reporter
.report_network_failure(Some("timeout".to_string()))
.await;
assert!(
is_reachable(&reporter).await,
"one network failure within the debounce window stays online"
);
// But the failure streak is now being tracked.
assert!(reporter.first_failure_at.read().await.is_some());
}
/// Once failures persist past OFFLINE_CONFIRM_WINDOW, we flip offline.
/// We simulate elapsed time by backdating the streak start.
///
/// @req-test: UR-002 - Access media when online or offline
#[tokio::test]
async fn test_sustained_network_failure_goes_offline() {
let reporter = test_reporter();
// First failure starts the streak.
reporter.report_network_failure(None).await;
assert!(is_reachable(&reporter).await);
// Backdate the streak start to before the window.
{
let mut first = reporter.first_failure_at.write().await;
*first = Some(Instant::now() - OFFLINE_CONFIRM_WINDOW - Duration::from_secs(1));
}
// Next failure now exceeds the window → offline.
reporter
.report_network_failure(Some("connection refused".to_string()))
.await;
assert!(
!is_reachable(&reporter).await,
"sustained network failure flips to offline"
);
}
/// A success during a failure streak clears the streak and keeps us online —
/// recovery is instant and never trips the banner.
#[tokio::test]
async fn test_success_clears_failure_streak() {
let reporter = test_reporter();
reporter.report_network_failure(None).await;
assert!(reporter.first_failure_at.read().await.is_some());
reporter.report_success().await;
assert!(is_reachable(&reporter).await);
assert!(
reporter.first_failure_at.read().await.is_none(),
"success resets the debounce streak"
);
}
/// First success after being offline recovers instantly (no debounce on the
/// way back up).
#[tokio::test]
async fn test_recovery_is_instant() {
let reporter = test_reporter();
// Force offline.
reporter.apply_probe_result(false, Some("down".to_string())).await;
assert!(!is_reachable(&reporter).await);
// A single success brings us straight back online.
reporter.report_success().await;
assert!(is_reachable(&reporter).await);
let status = reporter.status.read().await;
assert!(status.connection_error.is_none());
}
/// Server-answered errors (401/404/5xx) are reported via report_success
/// by the repository, because the server is demonstrably reachable. This
/// test documents that contract: report_success means "server is up".
#[tokio::test]
async fn test_server_answered_error_counts_as_reachable() {
let reporter = test_reporter();
// Simulate being offline, then the server answers (even with an error).
reporter.apply_probe_result(false, None).await;
assert!(!is_reachable(&reporter).await);
// Repository maps Authentication/NotFound/Server errors to report_success.
reporter.report_success().await;
assert!(
is_reachable(&reporter).await,
"a server that answers (even with 4xx/5xx) is reachable"
);
}
/// report_network_failure is a no-op once already offline (nothing to debounce,
/// no duplicate events).
#[tokio::test]
async fn test_network_failure_noop_when_already_offline() {
let reporter = test_reporter();
reporter.apply_probe_result(false, None).await;
assert!(!is_reachable(&reporter).await);
// Should not panic or change state.
reporter.report_network_failure(Some("still down".to_string())).await;
assert!(!is_reachable(&reporter).await);
}
}
+4 -2
View File
@@ -1,5 +1,7 @@
//! Smart caching engine for predictive downloads
#[cfg(test)]
use crate::utils::lock::MutexSafe;
use log::{debug, info};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
@@ -9,7 +11,7 @@ use serde::{Deserialize, Serialize};
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
/// Smart caching configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CacheConfig {
/// Enable queue pre-caching
@@ -309,7 +311,7 @@ mod tests {
// Add some downloads
{
let conn_guard = conn_arc.lock().unwrap();
let conn_guard = conn_arc.lock_safe();
conn_guard.execute(
"INSERT INTO downloads (user_id, status, file_size) VALUES ('user1', 'completed', 600)",
[],
+6 -6
View File
@@ -10,6 +10,7 @@ pub mod cache;
pub mod events;
pub mod worker;
use crate::utils::lock::MutexSafe;
use std::path::PathBuf;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
@@ -45,18 +46,18 @@ impl DownloadManager {
/// Check if a new download can be started based on concurrent limit
pub fn can_start_download(&self) -> bool {
let active = self.active_downloads.lock().unwrap();
let active = self.active_downloads.lock_safe();
active.len() < self.max_concurrent
}
/// Get the number of currently active downloads
pub fn active_count(&self) -> usize {
self.active_downloads.lock().unwrap().len()
self.active_downloads.lock_safe().len()
}
/// Register a download as active
pub fn register_download(&self, download_id: i64) -> bool {
let mut active = self.active_downloads.lock().unwrap();
let mut active = self.active_downloads.lock_safe();
if active.len() >= self.max_concurrent {
return false;
}
@@ -65,7 +66,7 @@ impl DownloadManager {
/// Unregister a download when it completes or fails
pub fn unregister_download(&self, download_id: i64) {
let mut active = self.active_downloads.lock().unwrap();
let mut active = self.active_downloads.lock_safe();
active.remove(&download_id);
}
@@ -76,7 +77,7 @@ impl DownloadManager {
}
/// Information about a download
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadInfo {
pub id: i64,
@@ -119,7 +120,6 @@ pub struct DownloadTask {
#[cfg(test)]
mod tests {
use super::*;
use crate::player::MediaType;
#[test]
fn test_download_manager_set_max_concurrent() {
+37 -6
View File
@@ -381,72 +381,103 @@ fn default_true() -> bool {
}
/// Session information from Jellyfin
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
#[serde(rename_all(deserialize = "PascalCase", serialize = "camelCase"))]
#[derive(specta::Type, Debug, Clone, Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionInfo {
#[serde(default)]
#[serde(alias = "Id")]
pub id: Option<String>,
#[serde(default)]
#[serde(alias = "UserId")]
pub user_id: Option<String>,
#[serde(default)]
#[serde(alias = "UserName")]
pub user_name: Option<String>,
#[serde(default)]
#[serde(alias = "Client")]
pub client: Option<String>,
#[serde(default)]
#[serde(alias = "DeviceName")]
pub device_name: Option<String>,
#[serde(default)]
#[serde(alias = "DeviceId")]
pub device_id: Option<String>,
#[serde(default)]
#[serde(alias = "ApplicationVersion")]
pub application_version: Option<String>,
#[serde(default)]
#[serde(alias = "IsActive")]
pub is_active: Option<bool>,
#[serde(default)]
#[serde(alias = "SupportsMediaControl")]
pub supports_media_control: Option<bool>,
#[serde(default = "default_true")]
#[serde(alias = "SupportsRemoteControl")]
pub supports_remote_control: bool,
#[serde(default)]
#[serde(alias = "NowPlayingItem")]
pub now_playing_item: Option<NowPlayingItem>,
#[serde(default)]
#[serde(alias = "PlayState")]
pub play_state: Option<PlayState>,
#[serde(default)]
#[serde(alias = "PlayableMediaTypes")]
pub playable_media_types: Option<Vec<String>>,
#[serde(default)]
#[serde(alias = "SupportedCommands")]
pub supported_commands: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
#[serde(rename_all(deserialize = "PascalCase", serialize = "camelCase"))]
#[derive(specta::Type, Debug, Clone, Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NowPlayingItem {
#[serde(alias = "Id")]
pub id: Option<String>,
#[serde(alias = "Name")]
pub name: Option<String>,
#[serde(alias = "RunTimeTicks")]
pub run_time_ticks: Option<i64>,
#[serde(alias = "Album")]
pub album: Option<String>,
#[serde(alias = "AlbumId")]
pub album_id: Option<String>,
#[serde(alias = "AlbumArtist")]
pub album_artist: Option<String>,
#[serde(alias = "Artists")]
pub artists: Option<Vec<String>>,
#[serde(alias = "ImageTags")]
pub image_tags: Option<std::collections::HashMap<String, String>>,
#[serde(alias = "PrimaryImageTag")]
pub primary_image_tag: Option<String>,
#[serde(alias = "AlbumPrimaryImageTag")]
pub album_primary_image_tag: Option<String>,
#[serde(rename = "Type")]
pub item_type: Option<String>,
}
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
#[serde(rename_all(deserialize = "PascalCase", serialize = "camelCase"))]
#[derive(specta::Type, Debug, Clone, Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlayState {
#[serde(default)]
#[serde(alias = "PositionTicks")]
pub position_ticks: Option<i64>,
#[serde(default)]
#[serde(alias = "CanSeek")]
pub can_seek: Option<bool>,
#[serde(default)]
#[serde(alias = "IsPaused")]
pub is_paused: Option<bool>,
#[serde(default)]
#[serde(alias = "IsMuted")]
pub is_muted: Option<bool>,
#[serde(default)]
#[serde(alias = "VolumeLevel")]
pub volume_level: Option<i32>,
#[serde(default)]
#[serde(alias = "RepeatMode")]
pub repeat_mode: Option<String>,
#[serde(default)]
#[serde(alias = "ShuffleMode")]
pub shuffle_mode: Option<String>,
}
+305 -235
View File
@@ -12,11 +12,12 @@ mod session_poller;
pub mod settings;
mod storage;
mod thumbnail;
mod utils;
pub mod utils;
use std::sync::{Arc, Mutex};
use tokio::sync::Mutex as TokioMutex;
use tauri::Manager;
use tauri::{Emitter, Manager};
use tauri_specta::Builder;
use log::{error, info};
#[cfg(target_os = "android")]
use log::warn;
@@ -100,6 +101,7 @@ use commands::{
repository_report_playback_start, repository_report_playback_progress, repository_report_playback_stopped,
repository_get_image_url, repository_mark_favorite, repository_unmark_favorite,
repository_get_person, repository_get_items_by_person, repository_get_similar_items,
repository_get_subtitle_url, repository_get_video_download_url,
// Playlist commands
playlist_create, playlist_delete, playlist_rename, playlist_get_items,
playlist_add_items, playlist_remove_items, playlist_move_item,
@@ -120,8 +122,9 @@ use download::cache::{CacheConfig as SmartCacheConfig, SmartCache};
use download::DownloadManager;
use jellyfin::{HttpClient, HttpConfig};
use player::{MediaSessionManager, PlayerBackend, PlayerController, TauriEventEmitter};
// NullBackend fallback for platforms without native backends (not Linux or Android)
#[cfg(not(any(target_os = "linux", target_os = "android")))]
// NullBackend is used both for platforms without a native backend AND as a graceful
// fallback when a native backend (MPV/ExoPlayer) fails to initialize, so the app can
// still launch (browse library, manage downloads, see an error) instead of crashing.
use player::NullBackend;
#[cfg(target_os = "linux")]
@@ -225,13 +228,39 @@ impl RemoteVolumeHandler for RemoteVolumeSessionHandler {
}
}
/// Payload emitted to the frontend when a native player backend fails to
/// initialize and the app falls back to a no-op backend.
#[derive(Clone, serde::Serialize)]
struct BackendInitError {
platform: &'static str,
backend: &'static str,
message: String,
}
/// Log a backend-initialization failure and notify the frontend, so the UI can
/// surface "playback unavailable" instead of the app hard-crashing.
fn emit_backend_init_failed(app_handle: &tauri::AppHandle, backend: &'static str, message: String) {
error!(
"[INIT] Player backend '{}' failed to initialize: {}. Falling back to NullBackend (playback disabled).",
backend, message
);
let _ = app_handle.emit(
"backend-init-failed",
BackendInitError {
platform: std::env::consts::OS,
backend,
message,
},
);
}
/// Create the appropriate player backend for the current platform.
fn create_player_backend(
app_handle: tauri::AppHandle,
playback_reporter: Arc<tokio::sync::Mutex<Option<playback_reporting::PlaybackReporter>>>,
position_throttler: Arc<playback_reporting::EventThrottler>,
) -> Box<dyn PlayerBackend> {
let _event_emitter = Arc::new(TauriEventEmitter::new(app_handle));
let _event_emitter = Arc::new(TauriEventEmitter::new(app_handle.clone()));
#[cfg(target_os = "android")]
{
@@ -255,17 +284,21 @@ fn create_player_backend(
return Box::new(backend);
}
Err(e) => {
panic!("FATAL: Failed to initialize ExoPlayer backend on Android: {}. This is a critical error - playback will not work.", e);
// Degrade gracefully instead of crashing the app.
emit_backend_init_failed(&app_handle, "exoplayer", e.to_string());
return Box::new(NullBackend::new());
}
}
}
Err(e) => {
panic!("FATAL: Failed to attach JNI thread on Android: {}. This is a critical error - playback will not work.", e);
emit_backend_init_failed(&app_handle, "exoplayer", format!("attach JNI thread failed: {}", e));
return Box::new(NullBackend::new());
}
}
}
Err(e) => {
panic!("FATAL: Failed to create JavaVM on Android: {}. This is a critical error - playback will not work.", e);
emit_backend_init_failed(&app_handle, "exoplayer", format!("create JavaVM failed: {}", e));
return Box::new(NullBackend::new());
}
}
}
@@ -298,7 +331,11 @@ fn create_player_backend(
error!("\nAudio playback will NOT work until this is fixed.");
error!("========================================\n");
panic!("Cannot start application: MPV backend initialization failed. See error message above.");
// Degrade gracefully: launch with a no-op backend so the user can
// still browse the library and manage downloads, and the frontend
// can show a "playback unavailable" notice via this event.
emit_backend_init_failed(&app_handle, "mpv", e.to_string());
return Box::new(NullBackend::new());
}
}
}
@@ -311,6 +348,243 @@ fn create_player_backend(
}
}
/// Construct the tauri-specta command builder. Shared by `run()` and the
/// bindings-export test so the TypeScript bindings always match the handler.
fn specta_builder() -> Builder<tauri::Wry> {
Builder::<tauri::Wry>::new()
// Throw on error so generated `commands.*` return Promise<T> and throw,
// matching the existing frontend's invoke() try/catch convention.
.error_handling(tauri_specta::ErrorHandlingMode::Throw)
.commands(tauri_specta::collect_commands![
// Player commands
player_play_item,
player_play_queue,
player_play_album_track,
player_play_tracks,
player_play,
player_pause,
player_toggle,
player_stop,
player_next,
player_previous,
player_seek,
player_seek_video,
player_set_volume,
player_toggle_mute,
player_set_audio_track,
player_switch_audio_track,
player_set_subtitle_track,
player_toggle_shuffle,
player_cycle_repeat,
player_get_status,
player_get_queue,
player_add_to_queue,
player_add_track_by_id,
player_add_tracks_by_ids,
player_remove_from_queue,
player_move_in_queue,
player_skip_to,
player_set_audio_settings,
player_get_audio_settings,
player_set_video_settings,
player_get_video_settings,
// Sleep timer and autoplay commands
player_set_sleep_timer,
player_cancel_sleep_timer,
player_get_sleep_timer,
player_get_autoplay_settings,
player_set_autoplay_settings,
player_cancel_autoplay_countdown,
player_play_next_episode,
player_on_playback_ended,
// Preload commands
player_preload_upcoming,
player_set_cache_config,
player_get_cache_config,
// Jellyfin reporting commands
player_configure_jellyfin,
player_disable_jellyfin,
// Session management commands
player_get_session,
player_dismiss_session,
// Remote session control commands
remote_play_on_session,
remote_send_command,
remote_session_seek,
remote_session_set_volume,
remote_session_toggle_mute,
// Session polling commands
sessions_set_polling_hint,
sessions_poll_now,
// Playback mode commands
playback_mode_get_current,
playback_mode_set,
playback_mode_is_transferring,
playback_mode_transfer_to_remote,
playback_mode_get_remote_status,
playback_mode_transfer_to_local,
// Playback reporting commands
playback_reporter_init,
playback_reporter_destroy,
playback_report_start,
playback_report_progress,
playback_report_stopped,
playback_mark_played,
// Auth commands
auth_initialize,
auth_connect_to_server,
auth_login,
auth_verify_session,
auth_logout,
auth_get_session,
auth_set_session,
auth_start_verification,
auth_stop_verification,
auth_reauthenticate,
// Device commands
device_get_id,
device_set_id,
// Connectivity commands
connectivity_check_server,
connectivity_set_server_url,
connectivity_get_status,
connectivity_start_monitoring,
connectivity_stop_monitoring,
connectivity_mark_reachable,
connectivity_mark_unreachable,
// Storage commands
storage_init,
storage_get_path,
storage_get_size,
storage_get_security_status,
storage_save_server,
storage_get_servers,
storage_delete_server,
storage_save_user,
storage_get_users,
storage_set_active_user,
storage_get_active_user,
storage_get_active_session,
storage_get_access_token,
storage_delete_user,
// Playback progress commands
storage_update_playback_progress,
storage_update_playback_context,
storage_mark_played,
storage_get_playback_progress,
storage_mark_synced,
storage_toggle_favorite,
// Download commands
download_item,
download_item_and_start,
download_album,
download_video,
download_series,
download_season,
get_downloads,
pause_download,
resume_download,
cancel_download,
delete_download,
delete_all_downloads,
delete_album_downloads,
clear_stale_downloads,
get_download_storage_stats,
mark_download_completed,
mark_download_failed,
start_download,
get_download_manager_stats,
set_max_concurrent_downloads,
get_smart_cache_stats,
update_smart_cache_config,
get_smart_cache_config,
get_album_recommendations,
get_album_affinity_status,
// Pinning commands
pin_item,
unpin_item,
is_item_pinned,
// Offline commands
offline_is_available,
offline_get_items,
offline_search,
// Offline cache commands
storage_get_libraries,
storage_get_items,
storage_get_item,
storage_search_items,
storage_save_library,
storage_save_item,
storage_get_pending_sync_count,
// Sync queue commands
sync_queue_mutation,
sync_get_pending,
sync_mark_processing,
sync_mark_completed,
sync_mark_failed,
sync_get_pending_count,
sync_cleanup_completed,
sync_clear_user,
// Thumbnail cache and image commands
thumbnail_get_cached,
thumbnail_save,
thumbnail_get_stats,
thumbnail_set_limit,
thumbnail_clear_cache,
thumbnail_delete_item,
image_get_url,
// People cache commands
storage_save_person,
storage_get_person,
storage_save_item_people,
storage_get_item_people,
// Series audio preferences
storage_save_series_audio_preference,
storage_get_series_audio_preference,
// Repository commands
repository_create,
repository_destroy,
repository_get_libraries,
repository_get_items,
repository_get_item,
repository_get_latest_items,
repository_get_resume_items,
repository_get_next_up_episodes,
repository_get_recently_played_audio,
repository_get_resume_movies,
repository_get_genres,
repository_search,
repository_get_playback_info,
repository_get_video_stream_url,
repository_get_audio_stream_url,
repository_report_playback_start,
repository_report_playback_progress,
repository_report_playback_stopped,
repository_get_image_url,
repository_mark_favorite,
repository_unmark_favorite,
repository_get_person,
repository_get_items_by_person,
repository_get_similar_items,
repository_get_subtitle_url,
repository_get_video_download_url,
// Playlist commands
playlist_create,
playlist_delete,
playlist_rename,
playlist_get_items,
playlist_add_items,
playlist_remove_items,
playlist_move_item,
// Conversion commands
format_time_seconds,
format_time_seconds_long,
convert_ticks_to_seconds,
calc_progress,
convert_percent_to_volume,
])
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
// Initialize logger
@@ -318,6 +592,12 @@ pub fn run() {
.filter_level(log::LevelFilter::Info)
.init();
// NOTE: TypeScript bindings are generated by the `export_typescript_bindings`
// test (`cargo test export_typescript_bindings`), NOT at runtime. Calling
// `.export()` here would try to write `../src/lib/api/bindings.ts` at app
// startup, which panics on devices (e.g. Android) where that path doesn't exist.
let builder = specta_builder();
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_os::init())
@@ -561,232 +841,22 @@ pub fn run() {
info!("[INIT] Application setup completed successfully");
Ok(())
})
.invoke_handler(tauri::generate_handler![
// Player commands
player_play_item,
player_play_queue,
player_play_album_track,
player_play_tracks,
player_play,
player_pause,
player_toggle,
player_stop,
player_next,
player_previous,
player_seek,
player_seek_video,
player_set_volume,
player_toggle_mute,
player_set_audio_track,
player_switch_audio_track,
player_set_subtitle_track,
player_toggle_shuffle,
player_cycle_repeat,
player_get_status,
player_get_queue,
player_add_to_queue,
player_add_track_by_id,
player_add_tracks_by_ids,
player_remove_from_queue,
player_move_in_queue,
player_skip_to,
player_set_audio_settings,
player_get_audio_settings,
player_set_video_settings,
player_get_video_settings,
// Sleep timer and autoplay commands
player_set_sleep_timer,
player_cancel_sleep_timer,
player_get_sleep_timer,
player_get_autoplay_settings,
player_set_autoplay_settings,
player_cancel_autoplay_countdown,
player_play_next_episode,
player_on_playback_ended,
// Preload commands
player_preload_upcoming,
player_set_cache_config,
player_get_cache_config,
// Jellyfin reporting commands
player_configure_jellyfin,
player_disable_jellyfin,
// Session management commands
player_get_session,
player_dismiss_session,
// Remote session control commands
remote_play_on_session,
remote_send_command,
remote_session_seek,
remote_session_set_volume,
remote_session_toggle_mute,
// Session polling commands
sessions_set_polling_hint,
sessions_poll_now,
// Playback mode commands
playback_mode_get_current,
playback_mode_set,
playback_mode_is_transferring,
playback_mode_transfer_to_remote,
playback_mode_get_remote_status,
playback_mode_transfer_to_local,
// Playback reporting commands
playback_reporter_init,
playback_reporter_destroy,
playback_report_start,
playback_report_progress,
playback_report_stopped,
playback_mark_played,
// Auth commands
auth_initialize,
auth_connect_to_server,
auth_login,
auth_verify_session,
auth_logout,
auth_get_session,
auth_set_session,
auth_start_verification,
auth_stop_verification,
auth_reauthenticate,
// Device commands
device_get_id,
device_set_id,
// Connectivity commands
connectivity_check_server,
connectivity_set_server_url,
connectivity_get_status,
connectivity_start_monitoring,
connectivity_stop_monitoring,
connectivity_mark_reachable,
connectivity_mark_unreachable,
// Storage commands
storage_init,
storage_get_path,
storage_get_size,
storage_get_security_status,
storage_save_server,
storage_get_servers,
storage_delete_server,
storage_save_user,
storage_get_users,
storage_set_active_user,
storage_get_active_user,
storage_get_active_session,
storage_get_access_token,
storage_delete_user,
// Playback progress commands
storage_update_playback_progress,
storage_update_playback_context,
storage_mark_played,
storage_get_playback_progress,
storage_mark_synced,
storage_toggle_favorite,
// Download commands
download_item,
download_item_and_start,
download_album,
download_video,
download_series,
download_season,
get_downloads,
pause_download,
resume_download,
cancel_download,
delete_download,
delete_all_downloads,
delete_album_downloads,
clear_stale_downloads,
get_download_storage_stats,
mark_download_completed,
mark_download_failed,
start_download,
get_download_manager_stats,
set_max_concurrent_downloads,
get_smart_cache_stats,
update_smart_cache_config,
get_smart_cache_config,
get_album_recommendations,
get_album_affinity_status,
// Pinning commands
pin_item,
unpin_item,
is_item_pinned,
// Offline commands
offline_is_available,
offline_get_items,
offline_search,
// Offline cache commands
storage_get_libraries,
storage_get_items,
storage_get_item,
storage_search_items,
storage_save_library,
storage_save_item,
storage_get_pending_sync_count,
// Sync queue commands
sync_queue_mutation,
sync_get_pending,
sync_mark_processing,
sync_mark_completed,
sync_mark_failed,
sync_get_pending_count,
sync_cleanup_completed,
sync_clear_user,
// Thumbnail cache and image commands
thumbnail_get_cached,
thumbnail_save,
thumbnail_get_stats,
thumbnail_set_limit,
thumbnail_clear_cache,
thumbnail_delete_item,
image_get_url,
// People cache commands
storage_save_person,
storage_get_person,
storage_save_item_people,
storage_get_item_people,
// Series audio preferences
storage_save_series_audio_preference,
storage_get_series_audio_preference,
// Repository commands
repository_create,
repository_destroy,
repository_get_libraries,
repository_get_items,
repository_get_item,
repository_get_latest_items,
repository_get_resume_items,
repository_get_next_up_episodes,
repository_get_recently_played_audio,
repository_get_resume_movies,
repository_get_genres,
repository_search,
repository_get_playback_info,
repository_get_video_stream_url,
repository_get_audio_stream_url,
repository_report_playback_start,
repository_report_playback_progress,
repository_report_playback_stopped,
repository_get_image_url,
repository_mark_favorite,
repository_unmark_favorite,
repository_get_person,
repository_get_items_by_person,
repository_get_similar_items,
// Playlist commands
playlist_create,
playlist_delete,
playlist_rename,
playlist_get_items,
playlist_add_items,
playlist_remove_items,
playlist_move_item,
// Conversion commands
format_time_seconds,
format_time_seconds_long,
convert_ticks_to_seconds,
calc_progress,
convert_percent_to_volume,
])
.invoke_handler(builder.invoke_handler())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
#[cfg(test)]
mod specta_bindings {
/// Generates `src/lib/api/bindings.ts`. Run with `cargo test export_typescript_bindings`.
#[test]
fn export_typescript_bindings() {
super::specta_builder()
.export(
specta_typescript::Typescript::default().bigint(specta_typescript::BigIntExportBehavior::Number),
"../src/lib/api/bindings.ts",
)
.expect("failed to export typescript bindings");
}
}
+7 -6
View File
@@ -1,3 +1,4 @@
use crate::utils::lock::{MutexSafe, RwLockSafe};
use log::{debug, error, info};
use serde::{Deserialize, Serialize};
use std::sync::{
@@ -11,7 +12,7 @@ use crate::jellyfin::JellyfinClient;
use crate::player::{PlayerController, QueueContext};
/// Playback mode - local device, remote session, or idle
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum PlaybackMode {
Local,
@@ -43,13 +44,13 @@ impl PlaybackModeManager {
/// Get current playback mode
pub fn get_mode(&self) -> PlaybackMode {
self.current_mode.read().unwrap().clone()
self.current_mode.read_safe().clone()
}
/// Set playback mode (internal use)
pub fn set_mode(&self, mode: PlaybackMode) {
log::info!("[PlaybackMode] Setting mode to: {:?}", mode);
let mut current = self.current_mode.write().unwrap();
let mut current = self.current_mode.write_safe();
*current = mode;
}
@@ -193,7 +194,7 @@ impl PlaybackModeManager {
debug!("[PlaybackMode] Player controller lock acquired");
let queue_arc = player.queue();
let queue = queue_arc.lock().unwrap();
let queue = queue_arc.lock_safe();
let state = player.state();
let original_index = queue.current_index().unwrap_or(0);
@@ -399,7 +400,7 @@ impl PlaybackModeManager {
// Log queue state BEFORE stop
{
let queue_arc = player.queue();
let queue = queue_arc.lock().unwrap();
let queue = queue_arc.lock_safe();
info!(
"[PlaybackMode] BEFORE STOP: Queue has {} items, current_index={:?}",
queue.items().len(),
@@ -412,7 +413,7 @@ impl PlaybackModeManager {
// Log queue state AFTER stop (should be unchanged)
{
let queue_arc = player.queue();
let queue = queue_arc.lock().unwrap();
let queue = queue_arc.lock_safe();
info!(
"[PlaybackMode] AFTER STOP: Queue has {} items, current_index={:?}",
queue.items().len(),
+5 -4
View File
@@ -5,6 +5,7 @@
#![allow(dead_code)]
use crate::utils::lock::MutexSafe;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
@@ -34,7 +35,7 @@ impl EventThrottler {
/// Checks if enough time has elapsed since the last report for this item
pub fn should_report(&self, item_id: &str) -> bool {
let last_times = self.last_report_time.lock().unwrap();
let last_times = self.last_report_time.lock_safe();
if let Some(last_time) = last_times.get(item_id) {
let elapsed = last_time.elapsed();
@@ -54,7 +55,7 @@ impl EventThrottler {
/// Marks the item as reported at the current time
pub fn mark_reported(&self, item_id: &str) {
let mut last_times = self.last_report_time.lock().unwrap();
let mut last_times = self.last_report_time.lock_safe();
last_times.insert(item_id.to_string(), Instant::now());
log::debug!(
@@ -66,14 +67,14 @@ impl EventThrottler {
/// Clears all tracked report times
pub fn clear(&self) {
let mut last_times = self.last_report_time.lock().unwrap();
let mut last_times = self.last_report_time.lock_safe();
last_times.clear();
log::debug!("[EventThrottler] Cleared all tracked report times");
}
/// Removes a specific item from tracking
pub fn clear_item(&self, item_id: &str) {
let mut last_times = self.last_report_time.lock().unwrap();
let mut last_times = self.last_report_time.lock_safe();
last_times.remove(item_id);
log::debug!("[EventThrottler] Cleared tracking for {}", item_id);
}
+14 -13
View File
@@ -3,6 +3,7 @@
//! This module provides a `PlayerBackend` implementation using Android's ExoPlayer
//! through JNI calls to Kotlin code.
use crate::utils::lock::MutexSafe;
use std::sync::{Arc, Mutex, OnceLock};
use tokio::sync::Mutex as TokioMutex;
use log::debug;
@@ -303,7 +304,7 @@ impl PlayerBackend for ExoPlayerBackend {
// Update local state
{
let mut state = self.shared_state.lock().unwrap();
let mut state = self.shared_state.lock_safe();
state.current_media = Some(media.clone());
state.state = PlayerState::Loading {
media: media.clone(),
@@ -430,7 +431,7 @@ impl PlayerBackend for ExoPlayerBackend {
fn stop(&mut self) -> Result<(), PlayerError> {
{
let mut state = self.shared_state.lock().unwrap();
let mut state = self.shared_state.lock_safe();
state.state = PlayerState::Idle;
state.is_loaded = false;
state.current_media = None;
@@ -479,24 +480,24 @@ impl PlayerBackend for ExoPlayerBackend {
)
.map_err(|e| PlayerError::playback_failed(format!("Failed to call setVolume: {}", e)))?;
self.shared_state.lock().unwrap().volume = clamped;
self.shared_state.lock_safe().volume = clamped;
Ok(())
}
fn position(&self) -> f64 {
self.shared_state.lock().unwrap().position
self.shared_state.lock_safe().position
}
fn duration(&self) -> Option<f64> {
self.shared_state.lock().unwrap().duration
self.shared_state.lock_safe().duration
}
fn state(&self) -> PlayerState {
self.shared_state.lock().unwrap().state.clone()
self.shared_state.lock_safe().state.clone()
}
fn volume(&self) -> f32 {
self.shared_state.lock().unwrap().volume
self.shared_state.lock_safe().volume
}
fn set_audio_track(&mut self, stream_index: i32) -> Result<(), PlayerError> {
@@ -564,7 +565,7 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
// Update state and get the preserved duration to emit
let duration_to_emit = if let Some(state) = SHARED_STATE.get() {
let mut state = state.lock().unwrap();
let mut state = state.lock_safe();
state.position = position;
if duration > 0.0 {
state.duration = Some(duration);
@@ -606,7 +607,7 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
// Update shared state
if let Some(shared) = SHARED_STATE.get() {
let mut shared = shared.lock().unwrap();
let mut shared = shared.lock_safe();
if let Some(media) = shared.current_media.clone() {
let duration = shared.duration.unwrap_or(0.0);
let position = shared.position;
@@ -651,7 +652,7 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
duration: jdouble,
) {
if let Some(state) = SHARED_STATE.get() {
let mut state = state.lock().unwrap();
let mut state = state.lock_safe();
state.duration = Some(duration);
state.is_loaded = true;
}
@@ -692,7 +693,7 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
// Log queue state before advancing
let queue_info = {
let queue = ctrl.queue.lock().unwrap();
let queue = ctrl.queue.lock_safe();
format!("current_index={:?}, len={}", queue.current_index(), queue.items().len())
};
log::debug!("[Autoplay] Queue state before next(): {}", queue_info);
@@ -702,7 +703,7 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
log::info!("[Autoplay] Successfully advanced to next track");
// Log queue state after advancing
let queue_info = {
let queue = ctrl.queue.lock().unwrap();
let queue = ctrl.queue.lock_safe();
format!("current_index={:?}, len={}", queue.current_index(), queue.items().len())
};
log::debug!("[Autoplay] Queue state after next(): {}", queue_info);
@@ -811,7 +812,7 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
muted: jboolean,
) {
if let Some(state) = SHARED_STATE.get() {
state.lock().unwrap().volume = volume;
state.lock_safe().volume = volume;
}
if let Some(emitter) = EVENT_EMITTER.get() {
+2 -2
View File
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use crate::repository::types::MediaItem;
/// Autoplay decision result - determines what happens after playback ends
#[derive(Debug, Clone, Serialize)]
#[derive(specta::Type, Debug, Clone, Serialize)]
#[serde(tag = "action", rename_all = "camelCase")]
pub enum AutoplayDecision {
/// Stop playback (no next item or timer expired)
@@ -21,7 +21,7 @@ pub enum AutoplayDecision {
}
/// Autoplay settings (controls next episode behavior)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AutoplaySettings {
/// Whether autoplay is enabled for next episodes
+4 -6
View File
@@ -5,6 +5,8 @@
//!
//! TRACES: UR-005, UR-019, UR-023, UR-026 | DR-001, DR-028, DR-047
#[cfg(test)]
use crate::utils::lock::MutexSafe;
use log::error;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
@@ -168,17 +170,13 @@ mod tests {
}
pub fn events(&self) -> Vec<PlayerStatusEvent> {
self.events.lock().unwrap().clone()
}
pub fn clear(&self) {
self.events.lock().unwrap().clear();
self.events.lock_safe().clone()
}
}
impl PlayerEventEmitter for TestEventEmitter {
fn emit(&self, event: PlayerStatusEvent) {
self.events.lock().unwrap().push(event);
self.events.lock_safe().push(event);
}
}
+7 -5
View File
@@ -3,7 +3,7 @@ use std::path::PathBuf;
/// Context for the current queue - where did the queue items come from?
/// This is used for remote playback transfer to send album/playlist context.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum QueueContext {
/// Playing from a specific album
@@ -23,7 +23,7 @@ pub enum QueueContext {
}
/// Represents a subtitle track
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SubtitleTrack {
/// Stream index in the media source
pub index: i32,
@@ -40,8 +40,9 @@ pub struct SubtitleTrack {
/// Represents a media item that can be played
///
/// TRACES: UR-003, UR-004 | DR-002
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[specta(rename = "PlayerMediaItem")]
pub struct MediaItem {
/// Unique identifier
pub id: String,
@@ -106,7 +107,7 @@ pub struct MediaItem {
pub server_id: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MediaType {
Audio,
@@ -114,8 +115,9 @@ pub enum MediaType {
}
/// TRACES: UR-002, UR-003, UR-004, UR-011 | DR-003
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "lowercase")]
#[specta(rename = "PlayerMediaSource")]
pub enum MediaSource {
/// Streaming from Jellyfin server
Remote {
+96 -76
View File
@@ -7,6 +7,7 @@ pub mod backend;
pub mod events;
pub mod media;
pub mod queue;
pub mod seek;
pub mod session;
pub mod sleep_timer;
pub mod state;
@@ -27,6 +28,7 @@ pub use backend::{NullBackend, PlayerBackend, PlayerError};
pub use events::{PlayerEventEmitter, PlayerStatusEvent, TauriEventEmitter};
pub use media::{MediaItem, MediaSource, MediaType, QueueContext};
pub use queue::{QueueManager, RepeatMode};
pub use seek::{determine_video_seek_strategy, VideoSeekStrategy};
pub use session::{MediaSessionManager, MediaSessionType};
pub use sleep_timer::{SleepTimerMode, SleepTimerState};
pub use state::{EndReason, PlayerState};
@@ -44,6 +46,7 @@ pub use android::{
set_media_command_handler, set_remote_volume_handler, get_detected_codecs,
};
use crate::utils::lock::MutexSafe;
use log::{debug, error, warn};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -121,7 +124,7 @@ impl PlayerController {
/// Configure the Jellyfin API client for automatic playback reporting
pub fn set_jellyfin_client(&self, client: Option<JellyfinClient>) {
let mut jellyfin = self.jellyfin_client.lock().unwrap();
let mut jellyfin = self.jellyfin_client.lock_safe();
*jellyfin = client;
log::info!("[PlayerController] Jellyfin client configured: {}", jellyfin.is_some());
}
@@ -157,24 +160,24 @@ impl PlayerController {
/// Set the end reason for the next playback end event
fn set_end_reason(&self, reason: EndReason) {
log::debug!("[PlayerController] Setting end reason: {:?}", reason);
*self.end_reason.lock().unwrap() = Some(reason);
*self.end_reason.lock_safe() = Some(reason);
}
/// Get and clear the current end reason
fn take_end_reason(&self) -> Option<EndReason> {
self.end_reason.lock().unwrap().take()
self.end_reason.lock_safe().take()
}
/// Increment autoplay episode counter. Returns true if limit is reached.
fn increment_autoplay_count(&self) -> bool {
let max = self.autoplay_settings.lock().unwrap().max_episodes;
let max = self.autoplay_settings.lock_safe().max_episodes;
if max == 0 {
// Unlimited
return false;
}
let mut count = self.autoplay_episode_count.lock().unwrap();
let mut count = self.autoplay_episode_count.lock_safe();
*count += 1;
debug!("[PlayerController] Autoplay episode count: {}/{}", *count, max);
@@ -183,7 +186,7 @@ impl PlayerController {
/// Reset autoplay episode counter (called on manual play actions)
fn reset_autoplay_count(&self) {
let mut count = self.autoplay_episode_count.lock().unwrap();
let mut count = self.autoplay_episode_count.lock_safe();
if *count > 0 {
debug!("[PlayerController] Resetting autoplay episode counter (was {})", *count);
}
@@ -199,7 +202,7 @@ impl PlayerController {
// Update queue with this single item
{
let mut queue = self.queue.lock().unwrap();
let mut queue = self.queue.lock_safe();
queue.set_queue(vec![item.clone()], 0);
}
@@ -209,6 +212,23 @@ impl PlayerController {
Ok(())
}
/// Set the current queue item without loading it into the playback backend.
///
/// Used on platforms where video is rendered outside the native backend
/// (Linux WebKitGTK HTML5 <video>): the queue/UI state must reflect the
/// item, but MPV must not start a redundant decode for it.
#[cfg(target_os = "linux")]
pub fn set_current_item(&self, item: MediaItem) -> Result<(), PlayerError> {
debug!("[PlayerController] set_current_item (no backend load): {}", item.title);
self.reset_autoplay_count();
let mut queue = self.queue.lock_safe();
queue.set_queue(vec![item], 0);
Ok(())
}
/// Load and play an item without modifying the queue
/// Use this when the queue is already set up and you just want to play a specific item from it
pub fn load_and_play(&self, item: &MediaItem) -> Result<(), PlayerError> {
@@ -217,7 +237,7 @@ impl PlayerController {
// Set end reason to NewTrackLoaded to prevent autoplay when MPV ends current track
self.set_end_reason(EndReason::NewTrackLoaded);
let mut backend = self.backend.lock().unwrap();
let mut backend = self.backend.lock_safe();
backend.load(item)?;
backend.play()?;
drop(backend);
@@ -297,12 +317,12 @@ impl PlayerController {
self.reset_autoplay_count();
{
let mut queue = self.queue.lock().unwrap();
let mut queue = self.queue.lock_safe();
queue.set_queue(items, start_index);
}
// Play the current item (without modifying the queue we just set)
if let Some(item) = self.queue.lock().unwrap().current().cloned() {
if let Some(item) = self.queue.lock_safe().current().cloned() {
self.load_and_play(&item)?;
}
@@ -312,19 +332,19 @@ impl PlayerController {
/// Play/resume playback
pub fn play(&self) -> Result<(), PlayerError> {
debug!("[PlayerController] play");
let mut backend = self.backend.lock().unwrap();
let mut backend = self.backend.lock_safe();
backend.play()
}
/// Pause playback
pub fn pause(&self) -> Result<(), PlayerError> {
let mut backend = self.backend.lock().unwrap();
let mut backend = self.backend.lock_safe();
backend.pause()
}
/// Toggle play/pause
pub fn toggle_playback(&self) -> Result<(), PlayerError> {
let mut backend = self.backend.lock().unwrap();
let mut backend = self.backend.lock_safe();
if backend.state().is_playing() {
backend.pause()
} else {
@@ -339,16 +359,16 @@ impl PlayerController {
// Get current playback info before stopping
let jellyfin_id = {
let queue = self.queue.lock().unwrap();
let queue = self.queue.lock_safe();
queue.current().and_then(|item| item.jellyfin_id().map(|s| s.to_string()))
};
let position_ticks = {
let backend = self.backend.lock().unwrap();
let backend = self.backend.lock_safe();
(backend.position() * 10_000_000.0) as i64
};
let mut backend = self.backend.lock().unwrap();
let mut backend = self.backend.lock_safe();
backend.stop()?;
drop(backend);
@@ -412,7 +432,7 @@ impl PlayerController {
self.reset_autoplay_count();
let next_item = {
let mut queue = self.queue.lock().unwrap();
let mut queue = self.queue.lock_safe();
queue.next().cloned()
};
@@ -435,7 +455,7 @@ impl PlayerController {
self.reset_autoplay_count();
// If we're more than 3 seconds in, restart current track
{
let backend = self.backend.lock().unwrap();
let backend = self.backend.lock_safe();
if backend.position() > 3.0 {
debug!("[PlayerController] previous: restarting current track (position > 3s)");
drop(backend);
@@ -444,7 +464,7 @@ impl PlayerController {
}
let prev_item = {
let mut queue = self.queue.lock().unwrap();
let mut queue = self.queue.lock_safe();
queue.previous().cloned()
};
@@ -459,40 +479,40 @@ impl PlayerController {
/// Seek to a position in seconds
pub fn seek(&self, position: f64) -> Result<(), PlayerError> {
let mut backend = self.backend.lock().unwrap();
let mut backend = self.backend.lock_safe();
backend.seek(position)
}
/// Set volume (0.0 - 1.0)
pub fn set_volume(&self, volume: f32) -> Result<(), PlayerError> {
self.backend.lock().unwrap().set_volume(volume)
self.backend.lock_safe().set_volume(volume)
}
/// Set the active audio track by stream index
pub fn set_audio_track(&self, stream_index: i32) -> Result<(), PlayerError> {
let mut backend = self.backend.lock().unwrap();
let mut backend = self.backend.lock_safe();
backend.set_audio_track(stream_index)
}
/// Set the active subtitle track by stream index (None to disable subtitles)
pub fn set_subtitle_track(&self, stream_index: Option<i32>) -> Result<(), PlayerError> {
let mut backend = self.backend.lock().unwrap();
let mut backend = self.backend.lock_safe();
backend.set_subtitle_track(stream_index)
}
/// Get current state
pub fn state(&self) -> PlayerState {
self.backend.lock().unwrap().state()
self.backend.lock_safe().state()
}
/// Get current position
pub fn position(&self) -> f64 {
self.backend.lock().unwrap().position()
self.backend.lock_safe().position()
}
/// Get duration
pub fn duration(&self) -> Option<f64> {
self.backend.lock().unwrap().duration()
self.backend.lock_safe().duration()
}
/// Get queue reference
@@ -502,27 +522,27 @@ impl PlayerController {
/// Toggle shuffle
pub fn toggle_shuffle(&self) {
self.queue.lock().unwrap().toggle_shuffle();
self.queue.lock_safe().toggle_shuffle();
}
/// Cycle repeat mode
pub fn cycle_repeat(&self) {
self.queue.lock().unwrap().cycle_repeat();
self.queue.lock_safe().cycle_repeat();
}
/// Check if shuffle is enabled
pub fn is_shuffle(&self) -> bool {
self.queue.lock().unwrap().is_shuffle()
self.queue.lock_safe().is_shuffle()
}
/// Get repeat mode
pub fn repeat_mode(&self) -> RepeatMode {
self.queue.lock().unwrap().repeat_mode()
self.queue.lock_safe().repeat_mode()
}
/// Get current volume (0.0 - 1.0)
pub fn volume(&self) -> f32 {
self.backend.lock().unwrap().volume()
self.backend.lock_safe().volume()
}
/// Check if muted
@@ -532,35 +552,35 @@ impl PlayerController {
/// Set audio settings (crossfade, gapless, normalization)
pub fn set_audio_settings(&mut self, settings: &AudioSettings) -> Result<(), PlayerError> {
self.backend.lock().unwrap().set_audio_settings(settings)
self.backend.lock_safe().set_audio_settings(settings)
}
/// Get current audio settings
pub fn audio_settings(&self) -> AudioSettings {
self.backend.lock().unwrap().audio_settings()
self.backend.lock_safe().audio_settings()
}
// ===== Sleep Timer Methods =====
/// Set the event emitter for notifications
pub fn set_event_emitter(&self, emitter: Arc<dyn PlayerEventEmitter>) {
let mut event_emitter = self.event_emitter.lock().unwrap();
let mut event_emitter = self.event_emitter.lock_safe();
*event_emitter = Some(emitter);
}
/// Get the event emitter
pub fn event_emitter(&self) -> Option<Arc<dyn PlayerEventEmitter>> {
self.event_emitter.lock().unwrap().clone()
self.event_emitter.lock_safe().clone()
}
/// Get sleep timer state
pub fn sleep_timer_state(&self) -> SleepTimerState {
self.sleep_timer.lock().unwrap().clone()
self.sleep_timer.lock_safe().clone()
}
/// Set sleep timer mode (in-memory only, not persisted)
pub fn set_sleep_timer(&self, mode: SleepTimerMode) {
let mut timer = self.sleep_timer.lock().unwrap();
let mut timer = self.sleep_timer.lock_safe();
timer.mode = mode.clone();
if let SleepTimerMode::Time { end_time } = mode {
let now = chrono::Utc::now().timestamp_millis();
@@ -589,7 +609,7 @@ impl PlayerController {
loop {
std::thread::sleep(Duration::from_secs(1));
let mut timer = sleep_timer.lock().unwrap();
let mut timer = sleep_timer.lock_safe();
if timer.is_active() {
timer.update_remaining_seconds();
@@ -599,7 +619,7 @@ impl PlayerController {
timer.cancel();
// Emit cancelled state
if let Some(emitter) = event_emitter.lock().unwrap().as_ref() {
if let Some(emitter) = event_emitter.lock_safe().as_ref() {
emitter.emit(PlayerStatusEvent::SleepTimerChanged {
mode: SleepTimerMode::Off,
remaining_seconds: 0,
@@ -608,14 +628,14 @@ impl PlayerController {
drop(timer);
// Stop the backend
if let Err(e) = backend.lock().unwrap().stop() {
if let Err(e) = backend.lock_safe().stop() {
error!("[SleepTimer] Failed to stop playback: {}", e);
}
continue;
}
// Emit update event
if let Some(emitter) = event_emitter.lock().unwrap().as_ref() {
if let Some(emitter) = event_emitter.lock_safe().as_ref() {
emitter.emit(PlayerStatusEvent::SleepTimerChanged {
mode: timer.mode.clone(),
remaining_seconds: timer.remaining_seconds,
@@ -629,9 +649,9 @@ impl PlayerController {
/// Emit sleep timer changed event to frontend
fn emit_sleep_timer_changed(&self) {
let timer = self.sleep_timer.lock().unwrap().clone();
let timer = self.sleep_timer.lock_safe().clone();
if let Some(emitter) = self.event_emitter.lock().unwrap().as_ref() {
if let Some(emitter) = self.event_emitter.lock_safe().as_ref() {
emitter.emit(PlayerStatusEvent::SleepTimerChanged {
mode: timer.mode,
remaining_seconds: timer.remaining_seconds,
@@ -641,12 +661,12 @@ impl PlayerController {
/// Emit queue changed event to frontend
pub fn emit_queue_changed(&self) {
let queue = self.queue.lock().unwrap();
let queue = self.queue.lock_safe();
debug!("PlayerController::emit_queue_changed() - Emitting queue with {} items, current_index: {:?}",
queue.items().len(), queue.current_index());
if let Some(emitter) = self.event_emitter.lock().unwrap().as_ref() {
if let Some(emitter) = self.event_emitter.lock_safe().as_ref() {
emitter.emit(PlayerStatusEvent::QueueChanged {
items: queue.items().to_vec(),
current_index: queue.current_index(),
@@ -664,19 +684,19 @@ impl PlayerController {
/// Get autoplay settings
pub fn autoplay_settings(&self) -> AutoplaySettings {
self.autoplay_settings.lock().unwrap().clone()
self.autoplay_settings.lock_safe().clone()
}
/// Set autoplay settings (in-memory only, persistence handled by command layer)
pub fn set_autoplay_settings(&self, settings: AutoplaySettings) {
let validated = settings.with_validated_countdown();
*self.autoplay_settings.lock().unwrap() = validated;
*self.autoplay_settings.lock_safe() = validated;
}
/// Cancel active autoplay countdown
pub fn cancel_autoplay_countdown(&self) {
if let Some(cancel_flag) = self.countdown_cancel.lock().unwrap().as_ref() {
*cancel_flag.lock().unwrap() = true;
if let Some(cancel_flag) = self.countdown_cancel.lock_safe().as_ref() {
*cancel_flag.lock_safe() = true;
}
}
@@ -719,7 +739,7 @@ impl PlayerController {
}
let current_item = {
let queue = self.queue.lock().unwrap();
let queue = self.queue.lock_safe();
queue.current().cloned()
};
@@ -729,7 +749,7 @@ impl PlayerController {
// Check sleep timer state
let timer_mode = {
let timer = self.sleep_timer.lock().unwrap();
let timer = self.sleep_timer.lock_safe();
timer.mode.clone()
};
@@ -739,14 +759,14 @@ impl PlayerController {
let now = chrono::Utc::now().timestamp_millis();
if now >= *end_time {
debug!("[PlayerController] Time-based sleep timer expired at track boundary");
self.sleep_timer.lock().unwrap().cancel();
self.sleep_timer.lock_safe().cancel();
self.emit_sleep_timer_changed();
return Ok(AutoplayDecision::Stop);
}
}
SleepTimerMode::EndOfTrack => {
// Stop at end of track
self.sleep_timer.lock().unwrap().cancel();
self.sleep_timer.lock_safe().cancel();
self.emit_sleep_timer_changed();
return Ok(AutoplayDecision::Stop);
}
@@ -756,7 +776,7 @@ impl PlayerController {
&& self.is_episode_item(&current).await;
if is_episode {
let should_stop = self.sleep_timer.lock().unwrap().decrement_episode();
let should_stop = self.sleep_timer.lock_safe().decrement_episode();
self.emit_sleep_timer_changed();
if should_stop {
@@ -773,7 +793,7 @@ impl PlayerController {
// Note: This path is typically not hit for HTML5 video (which uses on_video_playback_ended).
// It's here for the Android ExoPlayer path where video items may be in the backend queue.
if current.media_type == MediaType::Video && self.is_episode_item(&current).await {
let repo = self.repository.lock().unwrap().clone();
let repo = self.repository.lock_safe().clone();
let jellyfin_id = current.jellyfin_id().unwrap_or(&current.id);
let next_ep_result = if let Some(repo) = &repo {
self.fetch_next_episode_for_item(jellyfin_id, repo).await?
@@ -782,7 +802,7 @@ impl PlayerController {
None
};
if let Some(next_ep) = next_ep_result {
let settings = self.autoplay_settings.lock().unwrap().clone();
let settings = self.autoplay_settings.lock_safe().clone();
// Check if auto-play episode limit is reached
let limit_reached = self.increment_autoplay_count();
@@ -803,7 +823,7 @@ impl PlayerController {
// For audio/movies, check if there's a next track in the queue
let has_next = {
let queue = self.queue.lock().unwrap();
let queue = self.queue.lock_safe();
queue.has_next()
};
@@ -837,7 +857,7 @@ impl PlayerController {
// Check sleep timer state
let timer_mode = {
let timer = self.sleep_timer.lock().unwrap();
let timer = self.sleep_timer.lock_safe();
timer.mode.clone()
};
@@ -846,18 +866,18 @@ impl PlayerController {
let now = chrono::Utc::now().timestamp_millis();
if now >= *end_time {
debug!("[PlayerController] Time-based sleep timer expired at video end");
self.sleep_timer.lock().unwrap().cancel();
self.sleep_timer.lock_safe().cancel();
self.emit_sleep_timer_changed();
return Ok(AutoplayDecision::Stop);
}
}
SleepTimerMode::EndOfTrack => {
self.sleep_timer.lock().unwrap().cancel();
self.sleep_timer.lock_safe().cancel();
self.emit_sleep_timer_changed();
return Ok(AutoplayDecision::Stop);
}
SleepTimerMode::Episodes { .. } => {
let should_stop = self.sleep_timer.lock().unwrap().decrement_episode();
let should_stop = self.sleep_timer.lock_safe().decrement_episode();
self.emit_sleep_timer_changed();
if should_stop {
return Ok(AutoplayDecision::Stop);
@@ -868,7 +888,7 @@ impl PlayerController {
// Fetch next episode for the video that just ended
if let Some(next_ep) = self.fetch_next_episode_for_item(item_id, &repo).await? {
let settings = self.autoplay_settings.lock().unwrap().clone();
let settings = self.autoplay_settings.lock_safe().clone();
let limit_reached = self.increment_autoplay_count();
if limit_reached {
@@ -961,7 +981,7 @@ impl PlayerController {
pub fn start_autoplay_countdown(&self, _next_item: crate::repository::types::MediaItem, countdown_seconds: u32) {
// Create cancellation flag
let cancel_flag = Arc::new(Mutex::new(false));
*self.countdown_cancel.lock().unwrap() = Some(cancel_flag.clone());
*self.countdown_cancel.lock_safe() = Some(cancel_flag.clone());
let event_emitter = self.event_emitter.clone();
@@ -972,7 +992,7 @@ impl PlayerController {
std::thread::sleep(Duration::from_secs(1));
// Check cancellation
if *cancel_flag.lock().unwrap() {
if *cancel_flag.lock_safe() {
log::info!("[PlayerController] Autoplay countdown cancelled");
return;
}
@@ -980,7 +1000,7 @@ impl PlayerController {
remaining -= 1;
// Emit countdown tick event
if let Some(emitter) = event_emitter.lock().unwrap().as_ref() {
if let Some(emitter) = event_emitter.lock_safe().as_ref() {
emitter.emit(PlayerStatusEvent::CountdownTick {
remaining_seconds: remaining,
});
@@ -1081,7 +1101,7 @@ mod tests {
// Verify initial state
{
let queue = controller.queue();
let queue_lock = queue.lock().unwrap();
let queue_lock = queue.lock_safe();
assert_eq!(queue_lock.items().len(), 5, "Queue should have 5 items");
assert_eq!(queue_lock.current_index(), Some(0), "Should start at index 0");
assert_eq!(queue_lock.current().unwrap().id, "item_0", "Current item should be item_0");
@@ -1093,7 +1113,7 @@ mod tests {
// Verify queue is intact and index advanced
{
let queue = controller.queue();
let queue_lock = queue.lock().unwrap();
let queue_lock = queue.lock_safe();
assert_eq!(queue_lock.items().len(), 5, "Queue should still have 5 items after skip");
assert_eq!(queue_lock.current_index(), Some(1), "Index should advance to 1");
assert_eq!(queue_lock.current().unwrap().id, "item_1", "Current item should be item_1");
@@ -1112,7 +1132,7 @@ mod tests {
// Verify queue still intact and index advanced again
{
let queue = controller.queue();
let queue_lock = queue.lock().unwrap();
let queue_lock = queue.lock_safe();
assert_eq!(queue_lock.items().len(), 5, "Queue should still have 5 items after second skip");
assert_eq!(queue_lock.current_index(), Some(2), "Index should advance to 2");
assert_eq!(queue_lock.current().unwrap().id, "item_2", "Current item should be item_2");
@@ -1125,7 +1145,7 @@ mod tests {
// Verify we're at the last item
{
let queue = controller.queue();
let queue_lock = queue.lock().unwrap();
let queue_lock = queue.lock_safe();
assert_eq!(queue_lock.items().len(), 5, "Queue should still have 5 items at end");
assert_eq!(queue_lock.current_index(), Some(4), "Index should be at last item (4)");
assert_eq!(queue_lock.current().unwrap().id, "item_4", "Current item should be item_4");
@@ -1147,7 +1167,7 @@ mod tests {
// Verify we're at the last item
{
let queue = controller.queue();
let queue_lock = queue.lock().unwrap();
let queue_lock = queue.lock_safe();
assert_eq!(queue_lock.current_index(), Some(2), "Should be at last item");
}
@@ -1158,7 +1178,7 @@ mod tests {
// Verify queue is still intact
{
let queue = controller.queue();
let queue_lock = queue.lock().unwrap();
let queue_lock = queue.lock_safe();
assert_eq!(queue_lock.items().len(), 3, "Queue should still have 3 items after skip at end");
// When we skip past the end, the queue index should stay at the last item
// or become None (depending on implementation)
@@ -1187,7 +1207,7 @@ mod tests {
// Verify we wrapped to the first item
{
let queue = controller.queue();
let queue_lock = queue.lock().unwrap();
let queue_lock = queue.lock_safe();
assert_eq!(queue_lock.items().len(), 3, "Queue should still have 3 items");
assert_eq!(queue_lock.current_index(), Some(0), "Should wrap to index 0");
assert_eq!(queue_lock.current().unwrap().id, "item_0", "Should be back at item_0");
@@ -1206,7 +1226,7 @@ mod tests {
// Verify starting position
{
let queue = controller.queue();
let queue_lock = queue.lock().unwrap();
let queue_lock = queue.lock_safe();
assert_eq!(queue_lock.current_index(), Some(3), "Should start at index 3");
}
@@ -1216,7 +1236,7 @@ mod tests {
// Verify queue is intact and index moved back
{
let queue = controller.queue();
let queue_lock = queue.lock().unwrap();
let queue_lock = queue.lock_safe();
assert_eq!(queue_lock.items().len(), 5, "Queue should still have 5 items after previous");
assert_eq!(queue_lock.current_index(), Some(2), "Index should move to 2");
assert_eq!(queue_lock.current().unwrap().id, "item_2", "Current item should be item_2");
@@ -1385,7 +1405,7 @@ mod tests {
// Set sleep timer to end of track
{
let mut timer = controller.sleep_timer.lock().unwrap();
let mut timer = controller.sleep_timer.lock_safe();
timer.mode = SleepTimerMode::EndOfTrack;
}
@@ -1400,7 +1420,7 @@ mod tests {
// Verify timer was cancelled
{
let timer = controller.sleep_timer.lock().unwrap();
let timer = controller.sleep_timer.lock_safe();
assert!(
matches!(timer.mode, SleepTimerMode::Off),
"Sleep timer should be cancelled after EndOfTrack"
+9 -8
View File
@@ -1,3 +1,4 @@
use crate::utils::lock::MutexSafe;
use log::{debug, error, info, warn};
use super::backend::{PlayerBackend, PlayerError};
use super::events::{PlayerEventEmitter, PlayerStatusEvent};
@@ -190,7 +191,7 @@ impl MpvBackend {
libmpv::events::Event::PlaybackRestart => {
debug!("[MpvBackend] Playback started/resumed");
let media_id = state.lock().unwrap().current_media.as_ref().map(|m| m.id.clone());
let media_id = state.lock_safe().current_media.as_ref().map(|m| m.id.clone());
if let Some(emitter) = &event_emitter {
emitter.emit(PlayerStatusEvent::StateChanged {
@@ -202,7 +203,7 @@ impl MpvBackend {
libmpv::events::Event::PropertyChange { name, .. } if name == "pause" => {
// Handle pause state changes
if let Ok(is_paused) = mpv.get_property::<bool>("pause") {
let media_id = state.lock().unwrap().current_media.as_ref().map(|m| m.id.clone());
let media_id = state.lock_safe().current_media.as_ref().map(|m| m.id.clone());
if let Some(emitter) = &event_emitter {
emitter.emit(PlayerStatusEvent::StateChanged {
@@ -308,7 +309,7 @@ impl MpvBackend {
if !is_paused {
// Throttled progress reporting (every 30s)
let jellyfin_id = {
let state = state_for_position.lock().unwrap();
let state = state_for_position.lock_safe();
state.current_media.as_ref()
.and_then(|m| m.jellyfin_id().map(|s| s.to_string()))
};
@@ -376,7 +377,7 @@ impl PlayerBackend for MpvBackend {
// Update state
{
let mut state = self.state.lock().unwrap();
let mut state = self.state.lock_safe();
state.current_media = Some(media.clone());
}
@@ -422,7 +423,7 @@ impl PlayerBackend for MpvBackend {
message: format!("Failed to stop: {:?}", e),
})?;
let mut state = self.state.lock().unwrap();
let mut state = self.state.lock_safe();
state.current_media = None;
Ok(())
@@ -460,7 +461,7 @@ impl PlayerBackend for MpvBackend {
message: format!("Failed to set volume: {:?}", e),
})?;
let mut state = self.state.lock().unwrap();
let mut state = self.state.lock_safe();
state.volume = clamped;
Ok(())
@@ -480,7 +481,7 @@ impl PlayerBackend for MpvBackend {
}
fn state(&self) -> PlayerState {
let state = self.state.lock().unwrap();
let state = self.state.lock_safe();
if let Some(ref media) = state.current_media {
let is_paused = self.mpv.get_property::<bool>("pause").unwrap_or(true);
@@ -506,7 +507,7 @@ impl PlayerBackend for MpvBackend {
}
fn volume(&self) -> f32 {
let state = self.state.lock().unwrap();
let state = self.state.lock_safe();
state.volume
}
+2 -2
View File
@@ -6,7 +6,7 @@ use super::media::{MediaItem, MediaSource, QueueContext};
/// Repeat mode for the queue
///
/// TRACES: UR-005 | DR-005
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[derive(specta::Type, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum RepeatMode {
#[default]
@@ -18,7 +18,7 @@ pub enum RepeatMode {
/// Queue manager for playlist functionality
///
/// TRACES: UR-005, UR-015 | DR-005, DR-020
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
pub struct QueueManager {
/// All items in the queue
items: Vec<MediaItem>,
+143
View File
@@ -0,0 +1,143 @@
//! Video seek strategy decision logic.
//!
//! This is pure logic, extracted from the command layer so it can be unit-tested
//! in the player core. The `player_seek_video` command translates the resulting
//! [`VideoSeekStrategy`] into a concrete backend/frontend action.
/// Seek strategy for video playback, derived from a stream's characteristics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VideoSeekStrategy {
/// Local file - always use native seek on backend
LocalNativeSeek,
/// HLS or direct stream with HTML5 - frontend handles seek, skip backend
Html5NativeSeek,
/// HLS or direct stream with native backend - backend handles seek
BackendNativeSeek,
/// Transcoded non-HLS with HTML5 - reload stream, frontend handles
Html5ReloadStream,
/// Transcoded non-HLS with native backend - reload stream, backend handles
BackendReloadStream,
}
/// Determine the video seek strategy based on stream characteristics.
///
/// This is a pure function extracted for testability.
///
/// # Arguments
/// * `is_local` - Whether the file is a local download
/// * `is_hls` - Whether the stream URL contains ".m3u8" (HLS stream)
/// * `needs_transcoding` - Whether the content needs transcoding
/// * `use_html5` - Whether frontend is using HTML5 video element
pub fn determine_video_seek_strategy(
is_local: bool,
is_hls: bool,
needs_transcoding: bool,
use_html5: bool,
) -> VideoSeekStrategy {
// Local files always support native seeking via backend
if is_local {
return VideoSeekStrategy::LocalNativeSeek;
}
// HLS streams and direct play (non-transcoded) support native seeking
if is_hls || !needs_transcoding {
if use_html5 {
// HTML5 backend - frontend handles seeking via videoElement.currentTime
// We don't call backend.seek() because video is in HTML5 element, not in MPV
VideoSeekStrategy::Html5NativeSeek
} else {
// Native backend (MPV) - backend handles seeking
VideoSeekStrategy::BackendNativeSeek
}
} else {
// Transcoded non-HLS streams need server-side seek (reload from new position)
if use_html5 {
VideoSeekStrategy::Html5ReloadStream
} else {
VideoSeekStrategy::BackendReloadStream
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Test video seek strategy for local files
#[test]
fn test_seek_strategy_local_file() {
// Local files always use native backend seek regardless of other flags
assert_eq!(
determine_video_seek_strategy(true, false, false, false),
VideoSeekStrategy::LocalNativeSeek
);
assert_eq!(
determine_video_seek_strategy(true, false, false, true),
VideoSeekStrategy::LocalNativeSeek
);
assert_eq!(
determine_video_seek_strategy(true, true, true, true),
VideoSeekStrategy::LocalNativeSeek
);
}
/// Test video seek strategy for HLS streams
#[test]
fn test_seek_strategy_hls_stream() {
// HLS with HTML5 - frontend handles seek, don't call backend
assert_eq!(
determine_video_seek_strategy(false, true, false, true),
VideoSeekStrategy::Html5NativeSeek
);
// HLS with native backend - backend handles seek
assert_eq!(
determine_video_seek_strategy(false, true, false, false),
VideoSeekStrategy::BackendNativeSeek
);
// HLS even with needs_transcoding flag - still native seek (HLS supports it)
assert_eq!(
determine_video_seek_strategy(false, true, true, true),
VideoSeekStrategy::Html5NativeSeek
);
}
/// Test video seek strategy for direct play (non-transcoded) streams
#[test]
fn test_seek_strategy_direct_play() {
// Direct play with HTML5 - frontend handles seek
assert_eq!(
determine_video_seek_strategy(false, false, false, true),
VideoSeekStrategy::Html5NativeSeek
);
// Direct play with native backend - backend handles seek
assert_eq!(
determine_video_seek_strategy(false, false, false, false),
VideoSeekStrategy::BackendNativeSeek
);
}
/// Test video seek strategy for transcoded non-HLS streams
#[test]
fn test_seek_strategy_transcoded_non_hls() {
// Transcoded non-HLS with HTML5 - need to reload stream, frontend handles
assert_eq!(
determine_video_seek_strategy(false, false, true, true),
VideoSeekStrategy::Html5ReloadStream
);
// Transcoded non-HLS with native backend - need to reload stream, backend handles
assert_eq!(
determine_video_seek_strategy(false, false, true, false),
VideoSeekStrategy::BackendReloadStream
);
}
/// Test the specific bug fix: HLS + HTML5 should NOT call backend seek
/// This was the bug causing "Raw(-10)" errors
#[test]
fn test_hls_html5_does_not_use_backend_seek() {
let strategy = determine_video_seek_strategy(false, true, false, true);
// Should be Html5NativeSeek, NOT BackendNativeSeek
assert_eq!(strategy, VideoSeekStrategy::Html5NativeSeek);
assert_ne!(strategy, VideoSeekStrategy::BackendNativeSeek);
}
}
+2 -2
View File
@@ -5,7 +5,7 @@
* beyond individual playback states. Enables persistent UI (miniplayer) and
* proper transitions between content types.
*
* See software-architecture.md Section 2.1 for state machine diagram.
* See docs/architecture/01-rust-backend.md for the state machine diagram.
*/
use log::info;
@@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize};
use super::media::MediaItem;
/// Media session type tracking the high-level playback context
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum MediaSessionType {
/// No active session - browsing library
+2 -2
View File
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
/// Sleep timer mode - determines when playback should stop
/// TRACES: UR-026 | DR-029
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum SleepTimerMode {
/// Timer is off
@@ -19,7 +19,7 @@ pub enum SleepTimerMode {
}
/// Sleep timer state
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SleepTimerState {
pub mode: SleepTimerMode,
+2 -2
View File
@@ -5,7 +5,7 @@ use super::media::MediaItem;
/// Tracks why playback ended to determine autoplay behavior
///
/// TRACES: UR-005 | DR-001
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EndReason {
/// Track played to completion (natural end) - trigger autoplay
@@ -23,7 +23,7 @@ pub enum EndReason {
/// Player state machine (6 states: Idle, Loading, Playing, Paused, Seeking, Error)
///
/// TRACES: UR-005 | DR-001
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum PlayerState {
#[default]
+10 -8
View File
@@ -5,6 +5,8 @@
// @req: DR-012 - Local database for media metadata cache
// @req: DR-013 - Repository pattern for online/offline data access
#[cfg(test)]
use crate::utils::lock::MutexSafe;
use std::sync::Arc;
use async_trait::async_trait;
@@ -546,16 +548,16 @@ mod tests {
}
fn get_query_count(&self) -> usize {
*self.query_count.lock().unwrap()
*self.query_count.lock_safe()
}
fn get_save_count(&self) -> usize {
*self.save_count.lock().unwrap()
*self.save_count.lock_safe()
}
async fn save_to_cache(&self, _parent_id: &str, items: &[MediaItem]) -> Result<usize, RepoError> {
*self.save_count.lock().unwrap() += 1;
*self.items.lock().unwrap() = items.to_vec();
*self.save_count.lock_safe() += 1;
*self.items.lock_safe() = items.to_vec();
Ok(items.len())
}
}
@@ -567,8 +569,8 @@ mod tests {
}
async fn get_items(&self, _parent_id: &str, _options: Option<GetItemsOptions>) -> Result<SearchResult, RepoError> {
*self.query_count.lock().unwrap() += 1;
let items = self.items.lock().unwrap().clone();
*self.query_count.lock_safe() += 1;
let items = self.items.lock_safe().clone();
let count = items.len();
Ok(SearchResult {
items,
@@ -715,7 +717,7 @@ mod tests {
}
fn get_query_count(&self) -> usize {
*self.query_count.lock().unwrap()
*self.query_count.lock_safe()
}
}
@@ -726,7 +728,7 @@ mod tests {
}
async fn get_items(&self, _parent_id: &str, _options: Option<GetItemsOptions>) -> Result<SearchResult, RepoError> {
*self.query_count.lock().unwrap() += 1;
*self.query_count.lock_safe() += 1;
Ok(SearchResult {
items: self.items.clone(),
total_record_count: self.items.len(),
+237 -21
View File
@@ -7,6 +7,7 @@ use log::{debug, error, info};
use log::warn;
use serde::{Deserialize, Serialize};
use crate::connectivity::ConnectivityReporter;
use crate::jellyfin::HttpClient;
use super::{MediaRepository, types::*};
@@ -16,6 +17,10 @@ pub struct OnlineRepository {
server_url: String,
user_id: String,
access_token: String,
/// Reports the outcome of every server request to the connectivity monitor.
/// This is the source of truth for the offline/online banner. `None` in
/// tests / contexts where connectivity tracking isn't wired up.
connectivity: Option<ConnectivityReporter>,
}
impl OnlineRepository {
@@ -30,6 +35,44 @@ impl OnlineRepository {
server_url,
user_id,
access_token,
connectivity: None,
}
}
/// Attach a connectivity reporter so server outcomes drive the reachability
/// state observed by the UI. See `report_outcome`.
pub fn with_connectivity(mut self, reporter: ConnectivityReporter) -> Self {
self.connectivity = Some(reporter);
self
}
/// Feed a request outcome into the connectivity monitor.
///
/// Classification (matches docs/architecture/07-connectivity.md):
/// - `Ok` / `Authentication` / `NotFound` / `Server` → the server answered,
/// so it is reachable → `report_success` (instant recovery).
/// - `Network` → connection-level failure → `report_network_failure`
/// (subject to the time-window debounce before going offline).
/// - `Database` → not a server signal → ignored.
async fn report_outcome<T>(&self, result: &Result<T, RepoError>) {
let Some(reporter) = &self.connectivity else {
return;
};
match result {
Ok(_)
| Err(RepoError::Authentication { .. })
| Err(RepoError::NotFound { .. })
| Err(RepoError::Server { .. }) => {
reporter.report_success().await;
}
Err(RepoError::Network { message }) => {
reporter.report_network_failure(Some(message.clone())).await;
}
Err(RepoError::Database { .. }) | Err(RepoError::Offline) => {
// Local-side errors (cache failure / already-offline) — not a
// statement about the server's reachability, so ignore them.
}
}
}
@@ -63,6 +106,12 @@ impl OnlineRepository {
/// Make authenticated GET request
async fn get_json<T: for<'de> Deserialize<'de>>(&self, endpoint: &str) -> Result<T, RepoError> {
let result = self.get_json_inner(endpoint).await;
self.report_outcome(&result).await;
result
}
async fn get_json_inner<T: for<'de> Deserialize<'de>>(&self, endpoint: &str) -> Result<T, RepoError> {
let url = format!("{}{}", self.server_url, endpoint);
let request = self.http_client.client.get(&url)
@@ -110,6 +159,12 @@ impl OnlineRepository {
/// Make authenticated POST request
async fn post_json<T: Serialize>(&self, endpoint: &str, body: &T) -> Result<(), RepoError> {
let result = self.post_json_inner(endpoint, body).await;
self.report_outcome(&result).await;
result
}
async fn post_json_inner<T: Serialize>(&self, endpoint: &str, body: &T) -> Result<(), RepoError> {
let url = format!("{}{}", self.server_url, endpoint);
let request = self.http_client.client.post(&url)
@@ -145,6 +200,16 @@ impl OnlineRepository {
&self,
endpoint: &str,
body: &T,
) -> Result<R, RepoError> {
let result = self.post_json_response_inner(endpoint, body).await;
self.report_outcome(&result).await;
result
}
async fn post_json_response_inner<T: Serialize, R: for<'de> Deserialize<'de>>(
&self,
endpoint: &str,
body: &T,
) -> Result<R, RepoError> {
let url = format!("{}{}", self.server_url, endpoint);
@@ -193,9 +258,16 @@ impl OnlineRepository {
})
}
/// Get a video stream URL for playback with optional seeking support.
/// For direct streams, uses /Videos/{id}/stream.mp4 with transcoding to support seeking.
/// For transcoded streams (HEVC/10-bit), includes StartTimeTicks parameter.
/// Get a video stream URL for playback at an arbitrary position (resume,
/// transcoded seeking, audio-track switching).
///
/// Returns an HLS master playlist (`/Videos/{id}/master.m3u8`) transcoded to
/// h264/aac. HLS is used rather than a progressive `stream.mp4` because the
/// HTML5 `<video>` element (via HLS.js) starts playing within seconds and can
/// seek within the stream, whereas a progressive MP4 transcode of HEVC source
/// forces the server to transcode the whole file before playback can begin —
/// which manifests as playback never starting. `StartTimeTicks` makes the
/// server begin the transcode at the requested position.
pub async fn get_video_stream_url(
&self,
item_id: &str,
@@ -210,12 +282,11 @@ impl OnlineRepository {
// Use provided audio stream index, or default to 0
let audio_index = audio_stream_index.unwrap_or(0).to_string();
// Build URL with progressive MP4 transcoding for seeking support
// This works for both direct streams and HEVC content
// Build an HLS transcode URL. VideoCodec lists h264 first so the server
// transcodes HEVC/10-bit/unsupported sources to h264 the WebView can decode.
let mut params = vec![
("api_key", self.access_token.clone()),
("DeviceId", "jellytau-tauri".to_string()),
("Container", "mp4".to_string()),
("VideoCodec", "h264".to_string()),
("AudioCodec", "aac".to_string()),
("AudioStreamIndex", audio_index),
@@ -223,6 +294,9 @@ impl OnlineRepository {
("VideoBitrate", "18000000".to_string()),
("AudioBitrate", "384000".to_string()),
("TranscodingMaxAudioChannels", "2".to_string()),
("SegmentContainer", "ts".to_string()),
("TranscodingContainer", "ts".to_string()),
("TranscodingProtocol", "hls".to_string()),
];
if let Some(source_id) = media_source_id {
@@ -241,7 +315,7 @@ impl OnlineRepository {
.join("&");
let url = format!(
"{}/Videos/{}/stream.mp4?{}",
"{}/Videos/{}/master.m3u8?{}",
self.server_url, item_id, query
);
@@ -859,7 +933,18 @@ impl MediaRepository for OnlineRepository {
("h264,hevc".to_string(), "aac,mp3".to_string())
});
#[cfg(not(target_os = "android"))]
// Linux desktop plays video through the WebKitGTK HTML5 <video> element,
// which cannot reliably decode HEVC/AV1/VP9. Advertise only codecs the
// WebView can decode so Jellyfin transcodes anything else to h264 HLS.
// (Audio-only files still direct-play via MPV, but the PlaybackInfo
// profile is shared, so we keep the broadly-supported audio codecs.)
#[cfg(all(not(target_os = "android"), target_os = "linux"))]
let (video_codecs, audio_codecs) = (
"h264".to_string(),
"aac,mp3,opus,vorbis,flac".to_string(),
);
#[cfg(all(not(target_os = "android"), not(target_os = "linux")))]
let (video_codecs, audio_codecs) = (
"h264,hevc,vp8,vp9,av1,mpeg4".to_string(),
"aac,mp3,opus,vorbis,flac".to_string(),
@@ -1136,23 +1221,29 @@ impl MediaRepository for OnlineRepository {
let endpoint = format!("/Users/{}/FavoriteItems/{}", self.user_id, item_id);
let url = format!("{}{}", self.server_url, endpoint);
let request = self.http_client.client.delete(&url)
.header("X-Emby-Authorization", self.auth_header())
.build()
.map_err(|e| RepoError::Network {
message: format!("Failed to build request: {}", e),
})?;
let result = async {
let request = self.http_client.client.delete(&url)
.header("X-Emby-Authorization", self.auth_header())
.build()
.map_err(|e| RepoError::Network {
message: format!("Failed to build request: {}", e),
})?;
let response = self.http_client.request_with_retry(request).await
.map_err(|e| RepoError::Network { message: e.to_string() })?;
let response = self.http_client.request_with_retry(request).await
.map_err(|e| RepoError::Network { message: e.to_string() })?;
if !response.status().is_success() {
return Err(RepoError::Server {
message: format!("HTTP {}", response.status()),
});
if !response.status().is_success() {
return Err(RepoError::Server {
message: format!("HTTP {}", response.status()),
});
}
Ok(())
}
.await;
Ok(())
self.report_outcome(&result).await;
result
}
async fn get_person(&self, person_id: &str) -> Result<MediaItem, RepoError> {
@@ -1377,6 +1468,91 @@ mod tests {
)
}
/// Build a repository wired to a real ConnectivityReporter so we can assert
/// how `report_outcome` classifies each `RepoError` into reachability.
/// (No app handle → event emission is a harmless no-op.)
fn create_test_repository_with_connectivity(
) -> (OnlineRepository, crate::connectivity::ConnectivityReporter) {
let monitor_http = HttpClient::new(crate::jellyfin::HttpConfig::default())
.expect("Failed to create HTTP client for monitor");
let monitor = crate::connectivity::ConnectivityMonitor::new(monitor_http);
let reporter = monitor.reporter();
let repo = create_test_repository().with_connectivity(reporter.clone());
(repo, reporter)
}
/// `report_outcome` is the seam between repository traffic and the
/// connectivity monitor. Verify each `RepoError` variant routes correctly:
/// - the server answering at all (Ok / 401 / 404 / 5xx) ⇒ reachable
/// - a network-level failure ⇒ marked unreachable (debounce reduced for test)
/// - local-side errors (Database / Offline) ⇒ no effect on reachability
///
/// @req-test: UR-002 - Access media when online or offline
/// @req-test: DR-013 - Repository pattern for online/offline data access
#[tokio::test]
async fn test_report_outcome_classifies_server_answered_as_reachable() {
let (repo, reporter) = create_test_repository_with_connectivity();
// Drive offline first so we can observe "recover to reachable".
for err in [
RepoError::Authentication { message: "401".into() },
RepoError::NotFound { message: "404".into() },
RepoError::Server { message: "500".into() },
] {
reporter.mark_unreachable_for_test().await;
assert!(!reporter.is_reachable().await, "precondition: offline");
let result: Result<(), RepoError> = Err(err);
repo.report_outcome(&result).await;
assert!(
reporter.is_reachable().await,
"a server that answers should be reported reachable"
);
}
// Ok should also report reachable.
reporter.mark_unreachable_for_test().await;
let ok: Result<(), RepoError> = Ok(());
repo.report_outcome(&ok).await;
assert!(reporter.is_reachable().await, "Ok ⇒ reachable");
}
/// Local-side errors must NOT flip reachability — they say nothing about the
/// server.
#[tokio::test]
async fn test_report_outcome_ignores_local_errors() {
let (repo, reporter) = create_test_repository_with_connectivity();
// Force offline, then a Database/Offline error must leave it offline
// (not falsely report reachable).
reporter.mark_unreachable_for_test().await;
for err in [RepoError::Database { message: "cache".into() }, RepoError::Offline] {
let result: Result<(), RepoError> = Err(err);
repo.report_outcome(&result).await;
assert!(
!reporter.is_reachable().await,
"local-side error must not change reachability"
);
}
}
/// A network error routes through the debounced path. A single failure stays
/// online (debounce window not yet elapsed).
#[tokio::test]
async fn test_report_outcome_network_error_is_debounced() {
let (repo, reporter) = create_test_repository_with_connectivity();
assert!(reporter.is_reachable().await, "starts online");
let result: Result<(), RepoError> = Err(RepoError::Network { message: "timeout".into() });
repo.report_outcome(&result).await;
assert!(
reporter.is_reachable().await,
"a single network failure stays online (debounced)"
);
}
#[tokio::test]
async fn test_get_audio_stream_url_formats_correctly() {
let repo = create_test_repository();
@@ -1392,6 +1568,46 @@ mod tests {
);
}
#[tokio::test]
async fn test_get_video_stream_url_returns_hls_with_position() {
// Transcoded video resume/seek must produce an HLS master playlist with
// StartTimeTicks, not a progressive stream.mp4 (which never starts playing
// for HEVC sources). See get_video_stream_url docs.
let repo = create_test_repository();
let url = repo
.get_video_stream_url("vid-1", Some("source-1"), Some(193.0), Some(1))
.await
.unwrap();
assert!(
url.starts_with("https://test.server.com/Videos/vid-1/master.m3u8?"),
"expected HLS master playlist, got: {url}"
);
assert!(url.contains("VideoCodec=h264"));
assert!(url.contains("MediaSourceId=source-1"));
assert!(url.contains("AudioStreamIndex=1"));
// 193.0 seconds * 10_000_000 ticks/sec
assert!(url.contains("StartTimeTicks=1930000000"), "url: {url}");
assert!(!url.contains("stream.mp4"));
}
#[tokio::test]
async fn test_get_video_stream_url_omits_position_when_absent() {
let repo = create_test_repository();
let url = repo
.get_video_stream_url("vid-1", None, None, None)
.await
.unwrap();
assert!(url.starts_with("https://test.server.com/Videos/vid-1/master.m3u8?"));
assert!(!url.contains("StartTimeTicks"));
assert!(!url.contains("MediaSourceId"));
// Defaults to first audio stream
assert!(url.contains("AudioStreamIndex=0"));
}
#[tokio::test]
async fn test_get_audio_stream_url_with_special_characters() {
let repo = create_test_repository();
+30 -21
View File
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
/// Error types for repository operations
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum RepoError {
Network { message: String },
@@ -28,7 +28,7 @@ impl std::fmt::Display for RepoError {
impl std::error::Error for RepoError {}
/// Library (media collection)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Library {
pub id: String,
@@ -39,7 +39,7 @@ pub struct Library {
}
/// User-specific data for an item (playback state, favorites, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserData {
#[serde(skip_serializing_if = "Option::is_none")]
@@ -59,15 +59,17 @@ pub struct UserData {
}
/// Artist item with ID and name (for clickable artist links)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "PascalCase")]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ArtistItem {
#[serde(alias = "Id")]
pub id: String,
#[serde(alias = "Name")]
pub name: String,
}
/// Person (cast/crew member) - for movies, series, and episodes
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Person {
/// Deserializes from API's "Id" field (PascalCase), serializes as "id" (camelCase to frontend)
@@ -95,7 +97,7 @@ pub struct Person {
}
/// Media item
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaItem {
pub id: String,
@@ -118,6 +120,7 @@ pub struct MediaItem {
#[serde(skip_serializing_if = "Option::is_none")]
pub official_rating: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "runTimeTicks")]
pub runtime_ticks: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub primary_image_tag: Option<String>,
@@ -158,7 +161,7 @@ pub struct MediaItem {
}
/// Media stream information (audio, video, subtitle tracks)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaStream {
#[serde(rename = "type")]
@@ -175,7 +178,7 @@ pub struct MediaStream {
}
/// Media source information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaSource {
pub id: String,
@@ -194,7 +197,7 @@ pub struct MediaSource {
}
/// Search result with pagination
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchResult {
pub items: Vec<MediaItem>,
@@ -202,7 +205,7 @@ pub struct SearchResult {
}
/// Options for querying items
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct GetItemsOptions {
#[serde(skip_serializing_if = "Option::is_none")]
@@ -224,7 +227,7 @@ pub struct GetItemsOptions {
}
/// Options for search queries
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SearchOptions {
#[serde(skip_serializing_if = "Option::is_none")]
@@ -236,7 +239,7 @@ pub struct SearchOptions {
}
/// Playback information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlaybackInfo {
pub media_source_id: String,
@@ -247,7 +250,7 @@ pub struct PlaybackInfo {
}
/// Genre
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Genre {
pub id: String,
@@ -255,7 +258,7 @@ pub struct Genre {
}
/// Image type
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
pub enum ImageType {
Primary,
Backdrop,
@@ -277,7 +280,7 @@ impl ImageType {
}
/// Image options
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ImageOptions {
#[serde(skip_serializing_if = "Option::is_none")]
@@ -335,7 +338,7 @@ impl MeaningfulContent for PlaybackInfo {
/// needed for remove/reorder operations (distinct from the media item's ID)
///
/// @req: UR-014 - Make and edit playlists of music that sync back to Jellyfin
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlaylistEntry {
/// The playlist-scoped entry ID (Jellyfin's PlaylistItemId)
@@ -348,7 +351,7 @@ pub struct PlaylistEntry {
/// Result of creating a playlist
///
/// @req: JA-019 - Get/create/update playlists
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlaylistCreatedResult {
pub id: String,
@@ -402,15 +405,21 @@ mod tests {
#[test]
fn test_artist_item_serialize() {
// Test that ArtistItem serializes to PascalCase for consistency
// ArtistItem serializes to camelCase for the frontend; it still accepts
// Jellyfin's PascalCase on deserialize via #[serde(alias = ...)].
let artist = ArtistItem {
id: "test-id".to_string(),
name: "Test Artist".to_string(),
};
let json = serde_json::to_string(&artist).expect("Failed to serialize");
assert!(json.contains(r#""Id":"test-id""#));
assert!(json.contains(r#""Name":"Test Artist""#));
assert!(json.contains(r#""id":"test-id""#));
assert!(json.contains(r#""name":"Test Artist""#));
let from_pascal: ArtistItem =
serde_json::from_str(r#"{"Id":"x","Name":"Y"}"#).expect("Failed to deserialize");
assert_eq!(from_pascal.id, "x");
assert_eq!(from_pascal.name, "Y");
}
#[test]
+9 -8
View File
@@ -5,6 +5,7 @@
//!
//! TRACES: UR-010 | JA-021
use crate::utils::lock::{MutexSafe, RwLockSafe};
use log::{debug, info, warn};
use std::sync::{Arc, Mutex, RwLock};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -60,7 +61,7 @@ impl SessionPollerManager {
/// Set event emitter for broadcasting session updates
pub fn set_event_emitter(&self, emitter: Arc<dyn PlayerEventEmitter>) {
*self.event_emitter.lock().unwrap() = Some(emitter);
*self.event_emitter.lock_safe() = Some(emitter);
}
/// Start the background polling thread
@@ -88,7 +89,7 @@ impl SessionPollerManager {
// Calculate poll interval based on mode and hint
let new_interval = Self::calculate_interval(
&mode_manager.get_mode(),
*hint.read().unwrap(),
*hint.read_safe(),
);
interval_ms.store(new_interval, Ordering::Relaxed);
@@ -97,7 +98,7 @@ impl SessionPollerManager {
// Fetch sessions
let sessions_result = rt.block_on(async {
let client_opt = client.lock().unwrap().clone();
let client_opt = client.lock_safe().clone();
match client_opt {
Some(c) => c.get_sessions().await,
None => {
@@ -111,7 +112,7 @@ impl SessionPollerManager {
match sessions_result {
Ok(sessions) => {
debug!("[SessionPoller] Fetched {} sessions", sessions.len());
if let Some(em) = emitter.lock().unwrap().as_ref() {
if let Some(em) = emitter.lock_safe().as_ref() {
em.emit(crate::player::PlayerStatusEvent::SessionsUpdated {
sessions,
});
@@ -129,7 +130,7 @@ impl SessionPollerManager {
info!("[SessionPoller] Polling thread stopped");
});
*self.thread_handle.lock().unwrap() = Some(handle);
*self.thread_handle.lock_safe() = Some(handle);
}
/// Stop the polling thread
@@ -138,7 +139,7 @@ impl SessionPollerManager {
self.is_running.store(false, Ordering::Relaxed);
// Join the thread if possible (don't block indefinitely)
if let Some(handle) = self.thread_handle.lock().unwrap().take() {
if let Some(handle) = self.thread_handle.lock_safe().take() {
let _ = handle.join();
}
}
@@ -146,7 +147,7 @@ impl SessionPollerManager {
/// Set UI hint for polling frequency adjustment
pub fn set_polling_hint(&self, hint: PollingHint) {
debug!("[SessionPoller] Setting polling hint: {:?}", hint);
*self.current_hint.write().unwrap() = hint;
*self.current_hint.write_safe() = hint;
}
/// Calculate polling interval based on mode and hint
@@ -165,7 +166,7 @@ impl SessionPollerManager {
/// Manually trigger a poll (for frontend refresh button)
pub async fn poll_now(&self) -> Result<Vec<crate::jellyfin::client::SessionInfo>, String> {
let client = self.jellyfin_client.lock().unwrap().clone()
let client = self.jellyfin_client.lock_safe().clone()
.ok_or("Jellyfin client not configured")?;
client.get_sessions().await
+3 -3
View File
@@ -3,7 +3,7 @@
use serde::{Deserialize, Serialize};
/// Volume normalization levels matching Spotify's presets
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
#[derive(specta::Type, Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum VolumeLevel {
/// Louder output (-11 LUFS)
@@ -27,7 +27,7 @@ impl VolumeLevel {
}
/// Audio playback settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AudioSettings {
/// Crossfade duration in seconds (0 = disabled, max 12)
@@ -60,7 +60,7 @@ impl AudioSettings {
}
/// Video playback settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VideoSettings {
/// Enable auto-play of next episode (with countdown)
+15 -14
View File
@@ -7,6 +7,7 @@ pub mod db_service;
pub mod models;
pub mod schema;
use crate::utils::lock::MutexSafe;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
@@ -77,7 +78,7 @@ impl Database {
/// Run all pending migrations
pub fn migrate(&self) -> SqliteResult<()> {
info!("Starting database migrations...");
let conn = self.conn.lock().unwrap();
let conn = self.conn.lock_safe();
// Create migrations table if it doesn't exist
debug!("Creating _migrations table if it doesn't exist...");
@@ -172,7 +173,7 @@ mod tests {
fn test_migrations_run() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Check that tables exist
let mut stmt = conn
@@ -186,7 +187,7 @@ mod tests {
fn test_all_tables_created() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
let expected_tables = [
"servers",
@@ -218,7 +219,7 @@ mod tests {
fn test_fts_table_created() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
let exists: Option<String> = conn
.query_row(
@@ -234,7 +235,7 @@ mod tests {
fn test_server_crud() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Insert a server
conn.execute(
@@ -282,7 +283,7 @@ mod tests {
fn test_user_crud() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Create a server first (foreign key)
conn.execute(
@@ -329,7 +330,7 @@ mod tests {
fn test_cascade_delete_server_removes_users() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Create server and user
conn.execute(
@@ -367,7 +368,7 @@ mod tests {
fn test_item_insert_and_fts_search() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Create server first
conn.execute(
@@ -424,7 +425,7 @@ mod tests {
fn test_user_data_playback_position() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Setup: server, user, item
conn.execute(
@@ -487,7 +488,7 @@ mod tests {
fn test_sync_queue_operations() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Setup
conn.execute(
@@ -552,7 +553,7 @@ mod tests {
fn test_downloads_table() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Setup
conn.execute(
@@ -627,7 +628,7 @@ mod tests {
// Tables should still exist
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
let count: i32 = conn
.query_row(
@@ -643,7 +644,7 @@ mod tests {
fn test_global_active_user_deactivation() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Create two servers
conn.execute(
@@ -713,7 +714,7 @@ mod tests {
fn test_active_session_query_ordering() {
let db = Database::open_in_memory().unwrap();
let conn = db.connection();
let conn = conn.lock().unwrap();
let conn = conn.lock_safe();
// Create server
conn.execute(
-1
View File
@@ -344,7 +344,6 @@ mod tests {
use super::*;
use crate::storage::db_service::RusqliteService;
use rusqlite::Connection;
use std::io::Write;
use std::sync::{Arc, Mutex};
use tempfile::TempDir;
+1 -1
View File
@@ -13,7 +13,7 @@ pub use cache::{CacheConfig, ThumbnailCache};
pub use worker::ThumbnailWorker;
/// Statistics about the thumbnail cache
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThumbnailCacheStats {
pub total_size_bytes: u64,
+7
View File
@@ -24,6 +24,7 @@ pub const TICKS_PER_SECOND: i64 = 10_000_000;
///
/// # Example
/// ```
/// # use jellytau_lib::utils::conversions::*;
/// let ticks = seconds_to_ticks(1.5); // 15,000,000 ticks
/// ```
#[inline]
@@ -41,6 +42,7 @@ pub fn seconds_to_ticks(seconds: f64) -> i64 {
///
/// # Example
/// ```
/// # use jellytau_lib::utils::conversions::*;
/// let seconds = ticks_to_seconds(15_000_000); // 1.5 seconds
/// ```
#[inline]
@@ -61,6 +63,7 @@ pub fn ticks_to_seconds(ticks: i64) -> f64 {
///
/// # Example
/// ```
/// # use jellytau_lib::utils::conversions::*;
/// let normalized = percent_to_volume(75.0); // 0.75
/// ```
#[inline]
@@ -81,6 +84,7 @@ pub fn percent_to_volume(percent: f64) -> f64 {
///
/// # Example
/// ```
/// # use jellytau_lib::utils::conversions::*;
/// let percent = volume_to_percent(0.75); // 75.0
/// ```
#[inline]
@@ -99,6 +103,7 @@ pub fn volume_to_percent(volume: f64) -> f64 {
///
/// # Example
/// ```
/// # use jellytau_lib::utils::conversions::*;
/// let formatted = format_time(225.0); // "3:45"
/// ```
pub fn format_time(seconds: f64) -> String {
@@ -121,6 +126,7 @@ pub fn format_time(seconds: f64) -> String {
///
/// # Example
/// ```
/// # use jellytau_lib::utils::conversions::*;
/// let short = format_time_long(225.0); // "3:45"
/// let long = format_time_long(5025.0); // "1:23:45"
/// ```
@@ -147,6 +153,7 @@ pub fn format_time_long(seconds: f64) -> String {
///
/// # Example
/// ```
/// # use jellytau_lib::utils::conversions::*;
/// let progress = calculate_progress(45.0, 180.0); // 25.0
/// ```
pub fn calculate_progress(position: f64, duration: f64) -> f64 {
+111
View File
@@ -0,0 +1,111 @@
//! Poison-tolerant locking helpers.
//!
//! `std::sync::Mutex` and `RwLock` become *poisoned* if a thread panics while
//! holding the guard. After that, every `.lock().unwrap()` / `.read().unwrap()`
//! / `.write().unwrap()` panics as well — so a single failure can cascade into
//! an unrecoverable crash. That is a real risk for stateful subsystems like the
//! player, whose locks are touched from many background threads (the MPV event
//! loop, sleep/autoplay timers, JNI callbacks, the session poller).
//!
//! These extension traits recover the guard from a poisoned lock instead of
//! panicking. The data behind a poisoned lock may be in an unexpected state,
//! but for this application's state (queues, settings, flags) recovering and
//! continuing is far preferable to taking down playback entirely.
//!
//! Use `lock_safe()` / `read_safe()` / `write_safe()` in place of
//! `.lock().unwrap()` / `.read().unwrap()` / `.write().unwrap()`.
//!
//! Note: these apply only to `std::sync` primitives. `tokio::sync::Mutex` does
//! not poison, so async code keeps using `.lock().await` unchanged.
use std::sync::{Mutex, MutexGuard, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
/// Poison-tolerant locking for [`std::sync::Mutex`].
pub trait MutexSafe<T: ?Sized> {
/// Lock the mutex, recovering the inner guard if the lock was poisoned.
fn lock_safe(&self) -> MutexGuard<'_, T>;
}
impl<T: ?Sized> MutexSafe<T> for Mutex<T> {
fn lock_safe(&self) -> MutexGuard<'_, T> {
self.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// Poison-tolerant locking for [`std::sync::RwLock`].
pub trait RwLockSafe<T: ?Sized> {
/// Acquire a read guard, recovering it if the lock was poisoned.
fn read_safe(&self) -> RwLockReadGuard<'_, T>;
/// Acquire a write guard, recovering it if the lock was poisoned.
fn write_safe(&self) -> RwLockWriteGuard<'_, T>;
}
impl<T: ?Sized> RwLockSafe<T> for RwLock<T> {
fn read_safe(&self) -> RwLockReadGuard<'_, T> {
self.read().unwrap_or_else(PoisonError::into_inner)
}
fn write_safe(&self) -> RwLockWriteGuard<'_, T> {
self.write().unwrap_or_else(PoisonError::into_inner)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::thread;
/// Run `f` with the panic hook suppressed so deliberately-poisoning panics
/// don't spam the test output.
fn without_panic_noise<R>(f: impl FnOnce() -> R) -> R {
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let result = f();
std::panic::set_hook(prev);
result
}
#[test]
fn lock_safe_recovers_from_poison() {
let mutex = Arc::new(Mutex::new(0u32));
let poisoner = Arc::clone(&mutex);
without_panic_noise(|| {
let _ = thread::spawn(move || {
let mut guard = poisoner.lock().unwrap();
*guard = 42;
panic!("poison the mutex while holding the guard");
})
.join();
});
// The mutex is now poisoned: the normal path would panic.
assert!(mutex.lock().is_err());
// lock_safe recovers the guard with the last written value intact.
let guard = mutex.lock_safe();
assert_eq!(*guard, 42);
}
#[test]
fn rwlock_safe_recovers_from_poison() {
let lock = Arc::new(RwLock::new(0u32));
let poisoner = Arc::clone(&lock);
without_panic_noise(|| {
let _ = thread::spawn(move || {
let mut guard = poisoner.write().unwrap();
*guard = 7;
panic!("poison the rwlock while holding the write guard");
})
.join();
});
assert!(lock.write().is_err());
assert_eq!(*lock.read_safe(), 7);
*lock.write_safe() = 9;
assert_eq!(*lock.read_safe(), 9);
}
}
+1
View File
@@ -1 +1,2 @@
pub mod conversions;
pub mod lock;
+5
View File
@@ -1,5 +1,10 @@
@import "tailwindcss";
/* Exclude the generated tauri-specta bindings from Tailwind's content scan.
It contains no CSS classes (only TS types/command wrappers), and scanning a
large generated file can confuse Tailwind v4's automatic class detection. */
@source not "./lib/api/bindings.ts";
/* Custom theme variables for JellyTau */
@theme {
--color-jellyfin: #00a4dc;
+23 -9
View File
@@ -10,6 +10,7 @@ import {
playNextEpisode,
type AutoplaySettings,
} from "./autoplay";
import type { PlayItemRequest } from "./bindings";
vi.mock("@tauri-apps/api/core", () => ({
invoke: vi.fn(async (command: string, args?: any) => {
@@ -33,6 +34,23 @@ vi.mock("@tauri-apps/api/core", () => ({
}),
}));
// setAutoplaySettings sources the user id from the auth store
vi.mock("$lib/stores/auth", () => ({
auth: { getUserId: () => "user-1" },
}));
// Minimal valid PlayItemRequest for playNextEpisode tests
function makeItem(overrides: Partial<PlayItemRequest> = {}): PlayItemRequest {
return {
id: "item-123",
title: "Episode 1",
streamUrl: "http://example/stream",
videoCodec: "h264",
needsTranscoding: false,
...overrides,
};
}
describe("autoplay API", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -98,7 +116,7 @@ describe("autoplay API", () => {
(c) => c[0] === "player_set_autoplay_settings"
);
expect(call).toBeDefined();
expect(call![1]).toEqual({ settings });
expect(call![1]).toEqual({ userId: "user-1", settings });
});
it("should support different countdown values", async () => {
@@ -130,11 +148,7 @@ describe("autoplay API", () => {
describe("playNextEpisode", () => {
it("should play next episode with item", async () => {
const mockItem = {
id: "item-123",
name: "Episode 1",
seriesId: "series-456",
};
const mockItem = makeItem();
await playNextEpisode(mockItem);
@@ -150,9 +164,9 @@ describe("autoplay API", () => {
it("should handle different item types", async () => {
const items = [
{ id: "1", name: "Episode 1" },
{ id: "2", name: "Episode 2", seasonNumber: 1 },
{ id: "3", name: "Episode 3", episodeNumber: 5 },
makeItem({ id: "1", title: "Episode 1" }),
makeItem({ id: "2", title: "Episode 2" }),
makeItem({ id: "3", title: "Episode 3" }),
];
for (const item of items) {
+9 -11
View File
@@ -4,28 +4,26 @@
* Functions to control autoplay in the backend.
*/
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import type { PlayItemRequest, AutoplaySettings } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
export interface AutoplaySettings {
enabled: boolean;
countdownSeconds: number;
maxEpisodes: number;
}
export type { AutoplaySettings };
export async function getAutoplaySettings(): Promise<AutoplaySettings> {
return invoke("player_get_autoplay_settings");
return commands.playerGetAutoplaySettings();
}
export async function setAutoplaySettings(
settings: AutoplaySettings
): Promise<AutoplaySettings> {
return invoke("player_set_autoplay_settings", { settings });
return commands.playerSetAutoplaySettings(auth.getUserId() ?? "", settings);
}
export async function cancelAutoplayCountdown(): Promise<void> {
return invoke("player_cancel_autoplay_countdown");
await commands.playerCancelAutoplayCountdown();
}
export async function playNextEpisode(item: any): Promise<void> {
return invoke("player_play_next_episode", { item });
export async function playNextEpisode(item: PlayItemRequest): Promise<void> {
await commands.playerPlayNextEpisode(item);
}
File diff suppressed because it is too large Load Diff
+39 -157
View File
@@ -2,9 +2,8 @@
// All API calls go through Tauri commands in src-tauri/src/commands/repository.rs
// NO direct HTTP calls - everything routes through Rust backend
import { invoke } from "@tauri-apps/api/core";
import { commands } from "./bindings";
import type { QualityPreset } from "./quality-presets";
import { QUALITY_PRESETS } from "./quality-presets";
import type {
Library,
MediaItem,
@@ -39,12 +38,7 @@ export class RepositoryClient {
serverId: string
): Promise<string> {
console.log("[RepositoryClient] Creating Rust repository...");
this.handle = await invoke<string>("repository_create", {
serverUrl,
userId,
accessToken,
serverId,
});
this.handle = await commands.repositoryCreate(serverUrl, userId, accessToken, serverId);
// Store for URL construction
this._serverUrl = serverUrl;
@@ -60,7 +54,7 @@ export class RepositoryClient {
*/
async destroy(): Promise<void> {
if (this.handle) {
await invoke("repository_destroy", { handle: this.handle });
await commands.repositoryDestroy(this.handle);
this.handle = null;
this._serverUrl = null;
this._accessToken = null;
@@ -84,119 +78,67 @@ export class RepositoryClient {
// ===== Library Methods (all via Rust) =====
async getLibraries(): Promise<Library[]> {
return invoke<Library[]>("repository_get_libraries", {
handle: this.ensureHandle(),
});
return commands.repositoryGetLibraries(this.ensureHandle());
}
async getItems(parentId: string, options?: GetItemsOptions): Promise<SearchResult> {
return invoke<SearchResult>("repository_get_items", {
handle: this.ensureHandle(),
parentId,
options: options ?? null,
});
return commands.repositoryGetItems(this.ensureHandle(), parentId, options ?? null);
}
async getItem(itemId: string): Promise<MediaItem> {
return invoke<MediaItem>("repository_get_item", {
handle: this.ensureHandle(),
itemId,
});
return commands.repositoryGetItem(this.ensureHandle(), itemId);
}
async getLatestItems(parentId: string, limit?: number): Promise<MediaItem[]> {
return invoke<MediaItem[]>("repository_get_latest_items", {
handle: this.ensureHandle(),
parentId,
limit: limit ?? null,
});
return commands.repositoryGetLatestItems(this.ensureHandle(), parentId, limit ?? null);
}
async getResumeItems(parentId?: string, limit?: number): Promise<MediaItem[]> {
return invoke<MediaItem[]>("repository_get_resume_items", {
handle: this.ensureHandle(),
parentId: parentId ?? null,
limit: limit ?? null,
});
return commands.repositoryGetResumeItems(this.ensureHandle(), parentId ?? null, limit ?? null);
}
async getNextUpEpisodes(seriesId?: string, limit?: number): Promise<MediaItem[]> {
return invoke<MediaItem[]>("repository_get_next_up_episodes", {
handle: this.ensureHandle(),
seriesId: seriesId ?? null,
limit: limit ?? null,
});
return commands.repositoryGetNextUpEpisodes(this.ensureHandle(), seriesId ?? null, limit ?? null);
}
async getRecentlyPlayedAudio(limit?: number): Promise<MediaItem[]> {
return invoke<MediaItem[]>("repository_get_recently_played_audio", {
handle: this.ensureHandle(),
limit: limit ?? null,
});
return commands.repositoryGetRecentlyPlayedAudio(this.ensureHandle(), limit ?? null);
}
async getResumeMovies(limit?: number): Promise<MediaItem[]> {
return invoke<MediaItem[]>("repository_get_resume_movies", {
handle: this.ensureHandle(),
limit: limit ?? null,
});
return commands.repositoryGetResumeMovies(this.ensureHandle(), limit ?? null);
}
async getGenres(parentId?: string): Promise<Genre[]> {
return invoke<Genre[]>("repository_get_genres", {
handle: this.ensureHandle(),
parentId: parentId ?? null,
});
return commands.repositoryGetGenres(this.ensureHandle(), parentId ?? null);
}
async search(query: string, options?: SearchOptions): Promise<SearchResult> {
return invoke<SearchResult>("repository_search", {
handle: this.ensureHandle(),
query,
options: options ?? null,
});
return commands.repositorySearch(this.ensureHandle(), query, options ?? null);
}
// ===== Playback Methods (all via Rust) =====
async getPlaybackInfo(itemId: string): Promise<PlaybackInfo> {
return invoke<PlaybackInfo>("repository_get_playback_info", {
handle: this.ensureHandle(),
itemId,
});
return commands.repositoryGetPlaybackInfo(this.ensureHandle(), itemId);
}
async reportPlaybackStart(itemId: string, positionTicks: number): Promise<void> {
return invoke("repository_report_playback_start", {
handle: this.ensureHandle(),
itemId,
positionTicks,
});
await commands.repositoryReportPlaybackStart(this.ensureHandle(), itemId, positionTicks);
}
async reportPlaybackProgress(itemId: string, positionTicks: number): Promise<void> {
return invoke("repository_report_playback_progress", {
handle: this.ensureHandle(),
itemId,
positionTicks,
});
await commands.repositoryReportPlaybackProgress(this.ensureHandle(), itemId, positionTicks);
}
async reportPlaybackStopped(itemId: string, positionTicks: number): Promise<void> {
return invoke("repository_report_playback_stopped", {
handle: this.ensureHandle(),
itemId,
positionTicks,
});
await commands.repositoryReportPlaybackStopped(this.ensureHandle(), itemId, positionTicks);
}
// ===== Stream URL Methods (via Rust) =====
async getAudioStreamUrl(itemId: string): Promise<string> {
return invoke<string>("repository_get_audio_stream_url", {
handle: this.ensureHandle(),
itemId,
});
return commands.repositoryGetAudioStreamUrl(this.ensureHandle(), itemId);
}
async getVideoStreamUrl(
@@ -205,13 +147,13 @@ export class RepositoryClient {
startTimeSeconds?: number,
audioStreamIndex?: number
): Promise<string> {
return invoke<string>("repository_get_video_stream_url", {
handle: this.ensureHandle(),
return commands.repositoryGetVideoStreamUrl(
this.ensureHandle(),
itemId,
mediaSourceId: mediaSourceId ?? null,
startTimeSeconds: startTimeSeconds ?? null,
audioStreamIndex: audioStreamIndex ?? null,
});
mediaSourceId ?? null,
startTimeSeconds ?? null,
audioStreamIndex ?? null
);
}
// ===== URL Construction Methods (sync, no server call) =====
@@ -221,12 +163,7 @@ export class RepositoryClient {
* The Rust backend constructs and returns the URL with proper credentials handling
*/
async getImageUrl(itemId: string, imageType: ImageType = "Primary", options?: ImageOptions): Promise<string> {
return invoke<string>("repository_get_image_url", {
handle: this.ensureHandle(),
itemId,
imageType,
options: options ?? null,
});
return commands.repositoryGetImageUrl(this.ensureHandle(), itemId, imageType, options ?? null);
}
/**
@@ -239,13 +176,7 @@ export class RepositoryClient {
streamIndex: number,
format: string = "vtt"
): Promise<string> {
return invoke<string>("repository_get_subtitle_url", {
handle: this.ensureHandle(),
itemId,
mediaSourceId,
streamIndex,
format,
});
return commands.repositoryGetSubtitleUrl(this.ensureHandle(), itemId, mediaSourceId, streamIndex, format);
}
/**
@@ -258,110 +189,61 @@ export class RepositoryClient {
quality: QualityPreset = "original",
mediaSourceId?: string
): Promise<string> {
return invoke<string>("repository_get_video_download_url", {
handle: this.ensureHandle(),
itemId,
quality,
mediaSourceId: mediaSourceId ?? null,
});
return commands.repositoryGetVideoDownloadUrl(this.ensureHandle(), itemId, quality, mediaSourceId ?? null);
}
// ===== Favorite Methods (via Rust) =====
async markFavorite(itemId: string): Promise<void> {
return invoke("repository_mark_favorite", {
handle: this.ensureHandle(),
itemId,
});
await commands.repositoryMarkFavorite(this.ensureHandle(), itemId);
}
async unmarkFavorite(itemId: string): Promise<void> {
return invoke("repository_unmark_favorite", {
handle: this.ensureHandle(),
itemId,
});
await commands.repositoryUnmarkFavorite(this.ensureHandle(), itemId);
}
// ===== Person Methods (via Rust) =====
async getPerson(personId: string): Promise<MediaItem> {
return invoke<MediaItem>("repository_get_person", {
handle: this.ensureHandle(),
personId,
});
return commands.repositoryGetPerson(this.ensureHandle(), personId);
}
async getItemsByPerson(personId: string, options?: GetItemsOptions): Promise<SearchResult> {
return invoke<SearchResult>("repository_get_items_by_person", {
handle: this.ensureHandle(),
personId,
options: options ?? null,
});
return commands.repositoryGetItemsByPerson(this.ensureHandle(), personId, options ?? null);
}
async getSimilarItems(itemId: string, limit?: number): Promise<SearchResult> {
return invoke<SearchResult>("repository_get_similar_items", {
handle: this.ensureHandle(),
itemId,
limit: limit ?? null,
});
return commands.repositoryGetSimilarItems(this.ensureHandle(), itemId, limit ?? null);
}
// ===== Playlist Methods (via Rust) =====
async createPlaylist(name: string, itemIds?: string[]): Promise<PlaylistCreatedResult> {
return invoke<PlaylistCreatedResult>("playlist_create", {
handle: this.ensureHandle(),
name,
itemIds: itemIds ?? null,
});
return commands.playlistCreate(this.ensureHandle(), name, itemIds ?? null);
}
async deletePlaylist(playlistId: string): Promise<void> {
return invoke("playlist_delete", {
handle: this.ensureHandle(),
playlistId,
});
await commands.playlistDelete(this.ensureHandle(), playlistId);
}
async renamePlaylist(playlistId: string, name: string): Promise<void> {
return invoke("playlist_rename", {
handle: this.ensureHandle(),
playlistId,
name,
});
await commands.playlistRename(this.ensureHandle(), playlistId, name);
}
async getPlaylistItems(playlistId: string): Promise<PlaylistEntry[]> {
return invoke<PlaylistEntry[]>("playlist_get_items", {
handle: this.ensureHandle(),
playlistId,
});
return commands.playlistGetItems(this.ensureHandle(), playlistId);
}
async addToPlaylist(playlistId: string, itemIds: string[]): Promise<void> {
return invoke("playlist_add_items", {
handle: this.ensureHandle(),
playlistId,
itemIds,
});
await commands.playlistAddItems(this.ensureHandle(), playlistId, itemIds);
}
async removeFromPlaylist(playlistId: string, entryIds: string[]): Promise<void> {
return invoke("playlist_remove_items", {
handle: this.ensureHandle(),
playlistId,
entryIds,
});
await commands.playlistRemoveItems(this.ensureHandle(), playlistId, entryIds);
}
async movePlaylistItem(playlistId: string, itemId: string, newIndex: number): Promise<void> {
return invoke("playlist_move_item", {
handle: this.ensureHandle(),
playlistId,
itemId,
newIndex,
});
await commands.playlistMoveItem(this.ensureHandle(), playlistId, itemId, newIndex);
}
// ===== Getters =====
+46 -236
View File
@@ -1,76 +1,41 @@
// Jellyfin API Types
// Frontend type layer.
//
// Wire types are the single source of truth, generated from Rust by tauri-specta
// in ./bindings.ts. This module re-exports them under the names the frontend uses
// and adds frontend-only unions/helpers that have no backend equivalent.
export interface ServerInfo {
id: string;
name: string;
url: string;
}
export type {
AuthResult,
Genre,
GetItemsOptions,
ImageOptions,
ImageType,
Library,
MediaItem,
MediaSource,
MediaStream,
Person,
PlaybackInfo,
PlaylistCreatedResult,
PlaylistEntry,
PlayState,
SearchOptions,
SearchResult,
ServerInfo,
User,
UserData,
} from "./bindings";
export interface User {
id: string;
name: string;
serverId: string;
primaryImageTag?: string;
}
import type { SessionInfo } from "./bindings";
export interface AuthResult {
user: User;
accessToken: string;
serverId: string;
}
// The frontend's "Session" is the backend remote-control session (SessionInfo).
// (Note: bindings also has a `Session` type — that's the auth/login session, a
// different concept — so we alias explicitly here rather than re-export it.)
export type Session = SessionInfo;
export interface Library {
id: string;
name: string;
collectionType: LibraryType;
imageTag?: string;
}
export type LibraryType = "movies" | "tvshows" | "music" | "books" | "photos" | "homevideos" | "boxsets" | "playlists" | "channels" | "unknown";
export interface MediaItem {
id: string;
name: string;
type: ItemType;
serverId: string;
// Common fields
overview?: string;
productionYear?: number;
communityRating?: number;
officialRating?: string;
runTimeTicks?: number;
// Images
primaryImageTag?: string;
backdropImageTags?: string[];
parentBackdropImageTags?: string[];
// For audio
albumId?: string;
albumName?: string;
artists?: string[];
artistItems?: { id: string; name: string }[];
indexNumber?: number; // Track number
parentIndexNumber?: number; // Disc number
// For video
seriesId?: string;
seriesName?: string;
seasonId?: string;
seasonName?: string;
// Playback
userData?: UserData;
mediaStreams?: MediaStream[];
mediaSources?: MediaSource[];
// Cast & Crew
people?: Person[];
// Genres
genres?: string[];
}
// ---------------------------------------------------------------------------
// Frontend-only types (not part of the Rust command surface)
// ---------------------------------------------------------------------------
export type ItemType =
| "Movie"
@@ -87,7 +52,18 @@ export type ItemType =
| "ChannelFolderItem"
| "Person";
// Person/Cast types
export type LibraryType =
| "movies"
| "tvshows"
| "music"
| "books"
| "photos"
| "homevideos"
| "boxsets"
| "playlists"
| "channels"
| "unknown";
export type PersonType =
| "Actor"
| "Director"
@@ -99,81 +75,6 @@ export type PersonType =
| "Conductor"
| "Lyricist";
export interface Person {
id: string;
name: string;
role?: string; // Character name for actors
type: PersonType;
primaryImageTag?: string;
}
export interface UserData {
playbackPositionTicks: number;
playCount: number;
isFavorite: boolean;
played: boolean;
lastPlayedDate?: string;
}
export interface MediaStream {
type: "Video" | "Audio" | "Subtitle";
codec?: string;
language?: string;
displayTitle?: string;
index: number;
isDefault: boolean;
isForced: boolean;
}
export interface MediaSource {
id: string;
name: string;
container?: string;
size?: number;
bitrate?: number;
supportsDirectPlay: boolean;
supportsDirectStream: boolean;
supportsTranscoding: boolean;
directStreamUrl?: string;
}
export interface PlaybackInfo {
mediaSourceId: string;
playSessionId: string;
streamUrl: string;
directPlay: boolean;
/** True if content requires transcoding (HEVC, 10-bit) - seeking requires server-side StartTimeTicks */
needsTranscoding: boolean;
}
// Remote session control types
export interface Session {
id: string;
userId: string;
userName: string;
client: string;
deviceName: string;
deviceId: string;
applicationVersion: string;
isActive: boolean;
supportsMediaControl: boolean;
supportsRemoteControl: boolean;
playState: PlayState | null;
nowPlayingItem: MediaItem | null;
playableMediaTypes: string[];
supportedCommands: string[];
}
export interface PlayState {
positionTicks: number;
canSeek: boolean;
isPaused: boolean;
isMuted: boolean;
volumeLevel: number;
repeatMode: string;
shuffleMode: string;
}
export type SessionCommand =
| "PlayPause"
| "Stop"
@@ -183,94 +84,3 @@ export type SessionCommand =
| "PreviousTrack"
| "Mute"
| "Unmute";
export interface SearchResult {
items: MediaItem[];
totalRecordCount: number;
}
// Repository pattern for offline support
export interface MediaRepository {
// Libraries
getLibraries(): Promise<Library[]>;
// Items
getItems(parentId: string, options?: GetItemsOptions): Promise<SearchResult>;
getItem(itemId: string): Promise<MediaItem>;
getLatestItems(parentId: string, limit?: number): Promise<MediaItem[]>;
// Home screen
getResumeItems(parentId?: string, limit?: number): Promise<MediaItem[]>;
getNextUpEpisodes(seriesId?: string, limit?: number): Promise<MediaItem[]>;
getRecentlyPlayedAudio(limit?: number): Promise<MediaItem[]>;
getResumeMovies(limit?: number): Promise<MediaItem[]>;
// Genres
getGenres(parentId?: string): Promise<Genre[]>;
// Search
search(query: string, options?: SearchOptions): Promise<SearchResult>;
// Playback
getPlaybackInfo(itemId: string): Promise<PlaybackInfo>;
reportPlaybackStart(itemId: string, positionTicks: number): Promise<void>;
reportPlaybackProgress(itemId: string, positionTicks: number): Promise<void>;
reportPlaybackStopped(itemId: string, positionTicks: number): Promise<void>;
// Images
getImageUrl(itemId: string, imageType: ImageType, options?: ImageOptions): string;
// Subtitles
getSubtitleUrl(itemId: string, mediaSourceId: string, streamIndex: number, format?: string): string;
// Favorites
markFavorite(itemId: string): Promise<void>;
unmarkFavorite(itemId: string): Promise<void>;
// People/Cast
getPerson(personId: string): Promise<MediaItem>;
getItemsByPerson(personId: string, options?: GetItemsOptions): Promise<SearchResult>;
// Related Content
getSimilarItems(itemId: string, limit?: number): Promise<SearchResult>;
}
export interface Genre {
id: string;
name: string;
}
// Playlist types
export interface PlaylistEntry extends MediaItem {
playlistItemId: string;
}
export interface PlaylistCreatedResult {
id: string;
}
export interface GetItemsOptions {
startIndex?: number;
limit?: number;
sortBy?: string;
sortOrder?: "Ascending" | "Descending";
includeItemTypes?: ItemType[];
recursive?: boolean;
fields?: string[];
genres?: string[];
}
export interface SearchOptions {
limit?: number;
includeItemTypes?: ItemType[];
searchTerm?: string;
}
export type ImageType = "Primary" | "Backdrop" | "Banner" | "Thumb" | "Logo";
export interface ImageOptions {
maxWidth?: number;
maxHeight?: number;
quality?: number;
tag?: string;
}
+8 -11
View File
@@ -1,12 +1,12 @@
<script lang="ts">
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
import { get } from "svelte/store";
interface Props {
itemId: string;
imageType?: string;
tag?: string;
tag?: string | null;
maxWidth?: number;
maxHeight?: number;
class?: string;
@@ -47,15 +47,12 @@
const repositoryHandle = repository.getHandle();
// Call Rust to get image as base64 data URL
const dataUrl = await invoke<string>("image_get_url", {
repositoryHandle,
request: {
itemId,
imageType,
maxWidth,
maxHeight,
tag,
},
const dataUrl = await commands.imageGetUrl(repositoryHandle, {
itemId,
imageType,
maxWidth,
maxHeight,
tag,
});
// Use data URL directly
@@ -1,5 +1,5 @@
<script lang="ts">
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import { auth } from "$lib/stores/auth";
import { downloads } from "$lib/stores/downloads";
import { goto } from "$app/navigation";
@@ -34,7 +34,7 @@
loading = true;
const userId = $auth.user?.id;
if (userId) {
stats = await invoke<StorageStats>("get_download_storage_stats", { userId });
stats = await commands.getDownloadStorageStats(userId);
}
} catch (error) {
console.error("Failed to load storage stats:", error);
@@ -56,7 +56,7 @@
deleting = true;
const userId = $auth.user?.id;
if (userId) {
await invoke("delete_all_downloads", { userId });
await commands.deleteAllDownloads(userId);
await downloads.refresh(userId);
await loadStats();
}
@@ -73,7 +73,7 @@
deletingAlbum = albumId;
const userId = $auth.user?.id;
if (userId) {
await invoke("delete_album_downloads", { albumId, userId });
await commands.deleteAlbumDownloads(albumId, userId);
await downloads.refresh(userId);
await loadStats();
}
@@ -1,7 +1,7 @@
<script lang="ts">
import { downloads } from "$lib/stores/downloads";
import { auth } from "$lib/stores/auth";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import type { MediaItem } from "$lib/api/types";
interface Props {
@@ -89,18 +89,14 @@
const downloadIds = await downloads.downloadAlbum(albumId, userId, basePath);
// Get target directory for downloads
const targetDir = await invoke<string>("storage_get_path");
const targetDir = await commands.storageGetPath();
// Start each queued track download
for (let i = 0; i < tracks.length && i < downloadIds.length; i++) {
try {
const streamUrl = await repo.getAudioStreamUrl(tracks[i].id);
if (streamUrl) {
await invoke("start_download", {
downloadId: downloadIds[i],
streamUrl,
targetDir,
});
await commands.startDownload(downloadIds[i], streamUrl, targetDir);
}
} catch (e) {
console.error(`Failed to start download for track ${tracks[i].id}:`, e);
@@ -28,6 +28,7 @@
continue;
}
const type = person.type;
if (!type) continue;
if (type in groups) {
groups[type].push(person);
} else {
@@ -84,7 +85,7 @@
<!-- Person image -->
<div class="w-24 h-24 rounded-full overflow-hidden bg-[var(--color-surface)] mb-2">
<CachedImage
itemId={person.id}
itemId={person.id ?? ""}
imageType="Primary"
tag={person.primaryImageTag}
maxWidth={200}
+1 -1
View File
@@ -55,7 +55,7 @@
<div class="flex flex-wrap gap-1">
{#each filteredPeople as person, index (person.id)}
<button
onclick={(e) => handlePersonClick(person.id, e)}
onclick={(e) => handlePersonClick(person.id ?? "", e)}
class="text-[var(--color-jellyfin)] hover:underline"
>
{person.name}
@@ -1,7 +1,7 @@
<script lang="ts">
import { downloads } from "$lib/stores/downloads";
import { auth } from "$lib/stores/auth";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import DownloadButtonCore from "./DownloadButtonCore.svelte";
import type { DownloadState } from "./DownloadButtonCore.svelte";
@@ -80,18 +80,18 @@
}
// Get target directory
const targetDir = await invoke<string>("storage_get_path");
const targetDir = await commands.storageGetPath();
console.log(" Target directory:", targetDir);
// Queue and start download in single atomic operation
const downloadId = await invoke<number>("download_item_and_start", {
const downloadId = await commands.downloadItemAndStart({
itemId,
userId,
streamUrl,
targetDir,
itemName: itemName || undefined,
artistName: artistName || undefined,
albumName: albumName || undefined,
itemName: itemName || null,
artistName: artistName || null,
albumName: albumName || null,
});
console.log(" Download queued and started with ID:", downloadId);
@@ -84,7 +84,7 @@
return null;
});
function formatDuration(ticks?: number): string {
function formatDuration(ticks?: number | null): string {
if (!ticks) return "";
const seconds = Math.floor(ticks / 10000000);
const hours = Math.floor(seconds / 3600);
@@ -100,7 +100,7 @@
if (!ep.userData || !ep.runTimeTicks) {
return 0;
}
return (ep.userData.playbackPositionTicks / ep.runTimeTicks) * 100;
return ((ep.userData.playbackPositionTicks ?? 0) / ep.runTimeTicks) * 100;
}
function handlePlay() {
@@ -178,7 +178,7 @@
{episode.communityRating.toFixed(1)}
</span>
{/if}
{#if episode.userData?.played}
{#if episode.userData?.isPlayed}
<span class="flex items-center gap-1 text-[var(--color-jellyfin)]">
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
@@ -281,7 +281,7 @@
{/if}
<!-- Played indicator -->
{#if ep.userData?.played}
{#if ep.userData?.isPlayed}
<div class="absolute top-2 right-2">
<svg class="w-5 h-5 text-[var(--color-jellyfin)]" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
+6 -6
View File
@@ -40,7 +40,7 @@
if (!episode.userData || !episode.runTimeTicks) {
return 0;
}
return (episode.userData.playbackPositionTicks / episode.runTimeTicks) * 100;
return ((episode.userData.playbackPositionTicks ?? 0) / episode.runTimeTicks) * 100;
});
const duration = $derived(formatDuration(episode.runTimeTicks));
@@ -137,7 +137,7 @@
{episode.name}
</h3>
<!-- Played indicator -->
{#if episode.userData?.played}
{#if episode.userData?.isPlayed}
<svg class="w-4 h-4 flex-shrink-0 text-[var(--color-jellyfin)]" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
@@ -164,10 +164,10 @@
<VideoDownloadButton
itemId={episode.id}
itemName={episode.name}
seriesName={episode.seriesName}
seasonName={episode.seasonName}
episodeNumber={episode.indexNumber}
seasonNumber={episode.parentIndexNumber}
seriesName={episode.seriesName ?? undefined}
seasonName={episode.seasonName ?? undefined}
episodeNumber={episode.indexNumber ?? undefined}
seasonNumber={episode.parentIndexNumber ?? undefined}
size="sm"
/>
</div>
@@ -18,7 +18,7 @@
}
function getImageTag(item: MediaItem | Library): string | undefined {
return "primaryImageTag" in item ? item.primaryImageTag : ("imageTag" in item ? item.imageTag : undefined);
return "primaryImageTag" in item ? (item.primaryImageTag ?? undefined) : ("imageTag" in item ? (item.imageTag ?? undefined) : undefined);
}
function getSubtitle(item: MediaItem | Library): string {
@@ -44,7 +44,7 @@
if (!showProgress || !("userData" in item) || !item.userData || !("runTimeTicks" in item) || !item.runTimeTicks) {
return 0;
}
return (item.userData.playbackPositionTicks / item.runTimeTicks) * 100;
return ((item.userData.playbackPositionTicks ?? 0) / item.runTimeTicks) * 100;
}
function getTrackNumber(item: MediaItem | Library): string {
@@ -61,7 +61,7 @@
{@const duration = "runTimeTicks" in item ? formatDuration(item.runTimeTicks) : ""}
{@const progress = getProgress(item)}
{@const trackNum = getTrackNumber(item)}
{@const isPlayed = "userData" in item && item.userData?.played}
{@const isPlayed = "userData" in item && item.userData?.isPlayed}
{@const downloadInfo = getDownloadInfo(item.id)}
{@const isDownloaded = downloadInfo?.status === "completed"}
{@const isDownloading = downloadInfo?.status === "downloading" || downloadInfo?.status === "pending"}
+2 -2
View File
@@ -52,7 +52,7 @@
if (!showProgress || !("userData" in item) || !item.userData || !item.runTimeTicks) {
return 0;
}
return (item.userData.playbackPositionTicks / item.runTimeTicks) * 100;
return ((item.userData.playbackPositionTicks ?? 0) / item.runTimeTicks) * 100;
});
const subtitle = $derived(() => {
@@ -112,7 +112,7 @@
{/if}
<!-- Played indicator -->
{#if "userData" in item && item.userData?.played}
{#if "userData" in item && item.userData?.isPlayed}
<div class="absolute top-2 right-2">
<svg class="w-5 h-5 text-[var(--color-jellyfin)]" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
@@ -1,7 +1,7 @@
<script lang="ts">
import { onMount } from "svelte";
import { goto } from "$app/navigation";
import { invoke } from "@tauri-apps/api/core";
import { commands } from "$lib/api/bindings";
import type { MediaItem, PlaylistEntry } from "$lib/api/types";
import { auth } from "$lib/stores/auth";
import { toast } from "$lib/stores/toast";
@@ -51,17 +51,14 @@
const repo = auth.getRepository();
const repositoryHandle = repo.getHandle();
const trackIds = entries.map(e => e.id);
await invoke("player_play_tracks", {
repositoryHandle,
request: {
trackIds,
startIndex: 0,
shuffle: false,
context: {
type: "playlist",
playlistId: playlist.id,
playlistName: playlist.name,
},
await commands.playerPlayTracks(repositoryHandle, {
trackIds,
startIndex: 0,
shuffle: false,
context: {
type: "playlist",
playlistId: playlist.id,
playlistName: playlist.name,
},
});
} catch (e) {
@@ -76,17 +73,14 @@
const repo = auth.getRepository();
const repositoryHandle = repo.getHandle();
const trackIds = entries.map(e => e.id);
await invoke("player_play_tracks", {
repositoryHandle,
request: {
trackIds,
startIndex: 0,
shuffle: true,
context: {
type: "playlist",
playlistId: playlist.id,
playlistName: playlist.name,
},
await commands.playerPlayTracks(repositoryHandle, {
trackIds,
startIndex: 0,
shuffle: true,
context: {
type: "playlist",
playlistId: playlist.id,
playlistName: playlist.name,
},
});
} catch (e) {

Some files were not shown because too many files have changed in this diff Show More