Compare commits

...
9 Commits
Author SHA1 Message Date
dtourolle 345bd0730c Merge pull request 'feat/plugin-channel-support' (#6) from feat/plugin-channel-support into master
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 4m40s
Traceability Validation / Check Requirement Traces (push) Successful in 23s
🏗️ Build and Test JellyTau / Build Android APK (push) Successful in 18m27s
Build & Release / Run Tests (push) Successful in 4m6s
Build & Release / Build Linux (push) Successful in 16m11s
Build & Release / Build Android (push) Successful in 18m47s
Build & Release / Create Release (push) Successful in 13s
Reviewed-on: #6
2026-06-27 15:52:39 +00:00
dtourolle e1e50d51e0 Use different app logo
🏗️ Build and Test JellyTau / Run Tests (pull_request) Successful in 4m1s
Traceability Validation / Check Requirement Traces (pull_request) Successful in 21s
Build & Release / Run Tests (push) Successful in 4m6s
🏗️ Build and Test JellyTau / Build Android APK (pull_request) Successful in 18m52s
Build & Release / Build Linux (push) Successful in 16m22s
Build & Release / Build Android (push) Successful in 19m13s
Build & Release / Create Release (push) Successful in 10s
2026-06-27 17:43:08 +02:00
dtourolle 7d7f27aa10 feat(library and playback): Support for serverside channel plugins and hls streaming 2026-06-27 17:25:57 +02:00
dtourolle f1d25c4f4d Add support for fusing/unfusing JellyLMS zones into synchronized
multi-room groups, addressed by MAC (derived from the `lms-{mac}` device id).
2026-06-26 19:27:37 +02:00
dtourolle ff8f35084b Merge pull request 'feat(library): genre sliders, artist links, and navigation utils' (#5) from feat/library-genre-sliders-and-nav-utils into master
🏗️ Build and Test JellyTau / Run Tests (push) Successful in 3m54s
Traceability Validation / Check Requirement Traces (push) Successful in 17s
Build & Release / Run Tests (push) Successful in 4m6s
🏗️ Build and Test JellyTau / Build Android APK (push) Successful in 18m38s
Build & Release / Build Linux (push) Successful in 16m2s
Build & Release / Build Android (push) Successful in 18m54s
Build & Release / Create Release (push) Successful in 11s
Reviewed-on: #5
2026-06-25 21:52:13 +00:00
dtourolle 4634ed595c fix(remote playback): Move audio between remote players
🏗️ Build and Test JellyTau / Run Tests (pull_request) Successful in 3m49s
Traceability Validation / Check Requirement Traces (pull_request) Successful in 21s
🏗️ Build and Test JellyTau / Build Android APK (pull_request) Successful in 18m37s
2026-06-25 23:39:01 +02:00
dtourolle 6836ce79c8 fix(Remote playback): kludge to scrub after stream move
🏗️ Build and Test JellyTau / Run Tests (pull_request) Successful in 3m51s
Traceability Validation / Check Requirement Traces (pull_request) Successful in 20s
🏗️ Build and Test JellyTau / Build Android APK (pull_request) Successful in 18m18s
2026-06-25 21:31:39 +02:00
dtourolle 2811e1b7ca fix: several small fixes
🏗️ Build and Test JellyTau / Run Tests (pull_request) Successful in 3m51s
Traceability Validation / Check Requirement Traces (pull_request) Successful in 22s
🏗️ Build and Test JellyTau / Build Android APK (pull_request) Successful in 18m26s
2026-06-25 20:02:01 +02:00
dtourolle 1836615dc0 feat(library): genre sliders, artist links, and navigation utils
🏗️ Build and Test JellyTau / Run Tests (pull_request) Successful in 3m49s
Traceability Validation / Check Requirement Traces (pull_request) Successful in 19s
🏗️ Build and Test JellyTau / Build Android APK (pull_request) Successful in 18m24s
- music landing: diverse per-genre album sliders (online counts /
  offline wide-probe fallback) and home-screen library shortcuts
- add ArtistLinks component and shared navigation/genreDiversity utils
- player/playback-mode refinements across Rust and frontend
2026-06-25 19:18:06 +02:00
91 changed files with 2444 additions and 347 deletions
+4 -1
View File
@@ -1,4 +1,7 @@
# JellyTau <h1 align="center">
<img src="docs/assets/logo.png" alt="JellyTau logo" width="120" /><br />
JellyTau
</h1>
A cross-platform Jellyfin client built with Tauri, SvelteKit, and TypeScript. A cross-platform Jellyfin client built with Tauri, SvelteKit, and TypeScript.
Binary file not shown.

After

Width:  |  Height:  |  Size: 338 KiB

@@ -138,6 +138,15 @@ class JellyTauPlayer(private val appContext: Context) {
/** Current media ID being played */ /** Current media ID being played */
private var currentMediaId: String? = null private var currentMediaId: String? = null
/**
* Guards against nativeOnPlaybackEnded() firing more than once per loaded
* media. ExoPlayer can re-enter STATE_ENDED (e.g. transient buffering near
* end of a transcoded stream), which would otherwise notify the backend
* twice and, for example, decrement the sleep-timer episode counter twice.
* Reset whenever new media is loaded.
*/
private var endedNotified = false
/** Current media metadata for notification updates */ /** Current media metadata for notification updates */
private var currentTitle: String = "" private var currentTitle: String = ""
private var currentArtist: String = "" private var currentArtist: String = ""
@@ -208,7 +217,15 @@ class JellyTauPlayer(private val appContext: Context) {
// Playback completed // Playback completed
android.util.Log.d("JellyTauPlayer", "▶ Playback ended") android.util.Log.d("JellyTauPlayer", "▶ Playback ended")
stopPositionUpdates() stopPositionUpdates()
nativeOnPlaybackEnded() // Only notify the backend once per loaded media. ExoPlayer
// can re-enter STATE_ENDED, which would double-count things
// like the sleep-timer episode counter.
if (!endedNotified) {
endedNotified = true
nativeOnPlaybackEnded()
} else {
android.util.Log.d("JellyTauPlayer", "▶ Playback ended already notified - ignoring")
}
} }
Player.STATE_BUFFERING -> { Player.STATE_BUFFERING -> {
android.util.Log.d("JellyTauPlayer", "▶ Buffering...") android.util.Log.d("JellyTauPlayer", "▶ Buffering...")
@@ -322,6 +339,7 @@ class JellyTauPlayer(private val appContext: Context) {
fun load(url: String, mediaId: String) { fun load(url: String, mediaId: String) {
mainHandler.post { mainHandler.post {
currentMediaId = mediaId currentMediaId = mediaId
endedNotified = false
val mediaItem = MediaItem.fromUri(url) val mediaItem = MediaItem.fromUri(url)
exoPlayer.setMediaItem(mediaItem) exoPlayer.setMediaItem(mediaItem)
exoPlayer.prepare() exoPlayer.prepare()
@@ -552,6 +570,7 @@ class JellyTauPlayer(private val appContext: Context) {
) { ) {
mainHandler.post { mainHandler.post {
currentMediaId = mediaId currentMediaId = mediaId
endedNotified = false
// Store metadata for notification updates // Store metadata for notification updates
currentTitle = title currentTitle = title
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 974 B

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 903 B

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 342 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 998 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 915 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

+21 -3
View File
@@ -41,12 +41,30 @@ pub fn playback_mode_is_transferring(
pub async fn playback_mode_transfer_to_remote( pub async fn playback_mode_transfer_to_remote(
manager: State<'_, PlaybackModeManagerWrapper>, manager: State<'_, PlaybackModeManagerWrapper>,
session_id: String, session_id: String,
position: Option<f64>,
) -> Result<(), String> { ) -> Result<(), String> {
log::info!( log::info!(
"[PlaybackModeCommands] Transferring to remote session: {}", "[PlaybackModeCommands] Transferring to remote session: {} (position override: {:?})",
session_id session_id,
position
); );
manager.0.transfer_to_remote(session_id).await manager.0.transfer_to_remote(session_id, position).await
}
/// Set the transferring flag on the playback mode manager.
///
/// Used by the frontend remote->local flow to mark the whole two-step sequence
/// as a transfer, so `player_play_tracks` starts LOCAL playback instead of
/// casting back to the remote session it's leaving. Always pair `true` with a
/// later `false` (including on error) so the flag can't stick.
#[tauri::command]
#[specta::specta]
pub async fn playback_mode_set_transferring(
manager: State<'_, PlaybackModeManagerWrapper>,
transferring: bool,
) -> Result<(), String> {
manager.0.set_transferring(transferring);
Ok(())
} }
/// Transfer playback from remote session back to local device /// Transfer playback from remote session back to local device
+102 -7
View File
@@ -224,6 +224,10 @@ pub struct PlayTracksRequest {
pub start_index: usize, pub start_index: usize,
pub shuffle: bool, pub shuffle: bool,
pub context: PlayTracksContext, pub context: PlayTracksContext,
/// Position (seconds) to resume the starting track from. Used when taking
/// over playback from a remote session so we don't restart from 0.
#[serde(default)]
pub start_position: Option<f64>,
} }
/// Context information for track playback /// Context information for track playback
@@ -1245,6 +1249,59 @@ pub(super) fn get_queue_status(controller: &PlayerController) -> QueueStatus {
} }
} }
/// Start a freshly-built queue on the active remote session.
///
/// Used by the "play tracks"/"play album track" commands when we're in remote
/// mode: instead of starting local MPV playback, we cast the selected tracks to
/// the remote device. Mirrors PlaybackModeManager::transfer_to_remote's
/// play_on_session call, but for a brand-new selection (so there's no resume
/// position - playback starts from the chosen track's beginning).
///
/// Local-only items (no Jellyfin ID) can't be cast, so they're filtered out and
/// the start index is adjusted to the remaining Jellyfin items. Returns an error
/// if the selected track itself has no Jellyfin ID.
async fn play_selection_on_remote(
controller: &PlayerController,
session_id: &str,
media_items: &[MediaItem],
start_index: usize,
) -> Result<(), String> {
// Collect Jellyfin IDs, tracking where the selected track lands after any
// local-only items are dropped.
let mut jellyfin_ids: Vec<String> = Vec::new();
let mut adjusted_index: Option<usize> = None;
for (i, item) in media_items.iter().enumerate() {
if let Some(id) = item.jellyfin_id() {
if i == start_index {
adjusted_index = Some(jellyfin_ids.len());
}
jellyfin_ids.push(id.to_string());
}
}
let start_index = adjusted_index
.ok_or("Cannot play on remote: selected track is not from Jellyfin")?;
if jellyfin_ids.is_empty() {
return Err("Cannot play on remote: no Jellyfin tracks in selection".to_string());
}
let client = {
let client_arc = controller.jellyfin_client();
let client_opt = client_arc.lock().map_err(|e| e.to_string())?;
client_opt
.as_ref()
.ok_or("Jellyfin client not configured")?
.clone()
};
// Fresh selection: start from the beginning of the chosen track.
client
.play_on_session(session_id.to_string(), jellyfin_ids, start_index, None)
.await
.map_err(|e| format!("Failed to start playback on remote session: {}", e))
}
/// Play a track from an album - backend fetches all album tracks and builds queue /// Play a track from an album - backend fetches all album tracks and builds queue
#[tauri::command] #[tauri::command]
@@ -1254,6 +1311,7 @@ pub async fn player_play_album_track(
session: State<'_, MediaSessionManagerWrapper>, session: State<'_, MediaSessionManagerWrapper>,
db: State<'_, DatabaseWrapper>, db: State<'_, DatabaseWrapper>,
repository_manager: State<'_, super::repository::RepositoryManagerWrapper>, repository_manager: State<'_, super::repository::RepositoryManagerWrapper>,
playback_mode: State<'_, super::playback_mode::PlaybackModeManagerWrapper>,
repository_handle: String, repository_handle: String,
request: PlayAlbumTrackRequest, request: PlayAlbumTrackRequest,
) -> Result<PlayerStatus, String> { ) -> Result<PlayerStatus, String> {
@@ -1376,11 +1434,24 @@ pub async fn player_play_album_track(
session_mgr.start_audio_session(first_item.clone()); session_mgr.start_audio_session(first_item.clone());
} }
// Play the queue
let controller = player.0.lock().await; let controller = player.0.lock().await;
controller
.play_queue(media_items, start_index) // When controlling a remote session, cast the selection there instead of
.map_err(|e| e.to_string())?; // starting local MPV playback. We still load the queue locally (below) so
// the queue/context stay in sync for the UI and for transferring back.
let remote_session = match playback_mode.0.get_mode() {
crate::playback_mode::PlaybackMode::Remote { session_id } => Some(session_id),
_ => None,
};
if let Some(session_id) = &remote_session {
play_selection_on_remote(&controller, session_id, &media_items, start_index).await?;
controller.set_queue(media_items, start_index).map_err(|e| e.to_string())?;
} else {
controller
.play_queue(media_items, start_index)
.map_err(|e| e.to_string())?;
}
// Set the queue context for remote transfer // Set the queue context for remote transfer
{ {
@@ -1422,6 +1493,7 @@ pub async fn player_play_tracks(
session: State<'_, MediaSessionManagerWrapper>, session: State<'_, MediaSessionManagerWrapper>,
db: State<'_, DatabaseWrapper>, db: State<'_, DatabaseWrapper>,
repository_manager: State<'_, super::repository::RepositoryManagerWrapper>, repository_manager: State<'_, super::repository::RepositoryManagerWrapper>,
playback_mode: State<'_, super::playback_mode::PlaybackModeManagerWrapper>,
repository_handle: String, repository_handle: String,
request: PlayTracksRequest, request: PlayTracksRequest,
) -> Result<PlayerStatus, String> { ) -> Result<PlayerStatus, String> {
@@ -1529,10 +1601,33 @@ pub async fn player_play_tracks(
session_mgr.start_audio_session(first_item.clone()); session_mgr.start_audio_session(first_item.clone());
} }
// Play queue
let controller = player.0.lock().await; let controller = player.0.lock().await;
controller.play_queue(media_items, request.start_index)
.map_err(|e| e.to_string())?; // When controlling a remote session, cast the selection there instead of
// starting local MPV playback. Skip this while a transfer is in flight: the
// transfer-to-local path calls this command to load the queue locally and
// the mode is still Remote until the transfer completes - routing it back to
// the remote would undo the transfer.
let remote_session = match playback_mode.0.get_mode() {
crate::playback_mode::PlaybackMode::Remote { session_id }
if !playback_mode.0.is_transferring() =>
{
Some(session_id)
}
_ => None,
};
if let Some(session_id) = &remote_session {
play_selection_on_remote(&controller, session_id, &media_items, request.start_index)
.await?;
controller
.set_queue(media_items, request.start_index)
.map_err(|e| e.to_string())?;
} else {
controller
.play_queue_from(media_items, request.start_index, request.start_position)
.map_err(|e| e.to_string())?;
}
// Set queue context // Set queue context
{ {
+90
View File
@@ -6,6 +6,7 @@
use tauri::State; use tauri::State;
use super::PlayerStateWrapper; use super::PlayerStateWrapper;
use crate::jellyfin::client::LmsSyncGroup;
/// Play items on a remote Jellyfin session (casting) /// Play items on a remote Jellyfin session (casting)
#[tauri::command] #[tauri::command]
@@ -129,3 +130,92 @@ pub async fn remote_session_toggle_mute(
Err("Jellyfin client not configured".to_string()) Err("Jellyfin client not configured".to_string())
} }
} }
// --- JellyLMS multi-room sync groups (fuse / unfuse LMS zones) --------------
//
// The frontend addresses LMS players by MAC address, which it derives from a
// session's device id (`lms-{mac}`). These commands forward to the JellyLMS
// plugin REST API via the configured JellyfinClient.
/// List current LMS sync groups.
#[tauri::command]
#[specta::specta]
pub async fn lms_get_sync_groups(
player: State<'_, PlayerStateWrapper>,
) -> Result<Vec<LmsSyncGroup>, String> {
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.lms_get_sync_groups().await
} else {
Err("Jellyfin client not configured".to_string())
}
}
/// Fuse LMS zones into a sync group. `master_mac` keeps playing and the
/// `slave_macs` zones join it in sync.
#[tauri::command]
#[specta::specta]
pub async fn lms_create_sync_group(
player: State<'_, PlayerStateWrapper>,
master_mac: String,
slave_macs: Vec<String>,
) -> Result<(), String> {
log::info!("[LmsSync] Fusing zones: master={}, slaves={:?}", master_mac, slave_macs);
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.lms_create_sync_group(&master_mac, slave_macs).await
} else {
Err("Jellyfin client not configured".to_string())
}
}
/// Remove a single LMS zone from its sync group (decouple one player).
#[tauri::command]
#[specta::specta]
pub async fn lms_unsync_player(
player: State<'_, PlayerStateWrapper>,
mac: String,
) -> Result<(), String> {
log::info!("[LmsSync] Decoupling zone {}", mac);
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.lms_unsync_player(&mac).await
} else {
Err("Jellyfin client not configured".to_string())
}
}
/// Dissolve an entire LMS sync group, identified by its master's MAC.
#[tauri::command]
#[specta::specta]
pub async fn lms_dissolve_sync_group(
player: State<'_, PlayerStateWrapper>,
master_mac: String,
) -> Result<(), String> {
log::info!("[LmsSync] Dissolving group with master {}", master_mac);
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.lms_dissolve_sync_group(&master_mac).await
} else {
Err("Jellyfin client not configured".to_string())
}
}
+43
View File
@@ -410,6 +410,49 @@ pub async fn repository_get_audio_stream_url(
.map_err(|e| format!("{:?}", e)) .map_err(|e| format!("{:?}", e))
} }
/// Get Live TV channels (broadcast / IPTV) for browsing
#[tauri::command]
#[specta::specta]
pub async fn repository_get_live_tv_channels(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
) -> Result<Vec<MediaItem>, String> {
let repo = manager.0.get(&handle).ok_or("Repository not found")?;
repo.as_ref()
.get_live_tv_channels()
.await
.map_err(|e| format!("{:?}", e))
}
/// Get the root list of plugin "Channels"
#[tauri::command]
#[specta::specta]
pub async fn repository_get_channels(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
) -> Result<SearchResult, String> {
let repo = manager.0.get(&handle).ok_or("Repository not found")?;
repo.as_ref()
.get_channels()
.await
.map_err(|e| format!("{:?}", e))
}
/// Open a live stream for a Live TV channel / live item
#[tauri::command]
#[specta::specta]
pub async fn repository_open_live_stream(
manager: State<'_, RepositoryManagerWrapper>,
handle: String,
item_id: String,
) -> Result<LiveStreamInfo, String> {
let repo = manager.0.get(&handle).ok_or("Repository not found")?;
repo.as_ref()
.open_live_stream(&item_id)
.await
.map_err(|e| format!("{:?}", e))
}
/// Report playback start /// Report playback start
#[tauri::command] #[tauri::command]
#[specta::specta] #[specta::specta]
+1
View File
@@ -82,6 +82,7 @@ impl ConnectivityReporter {
/// Current reachability as seen by this reporter (shared with the monitor /// Current reachability as seen by this reporter (shared with the monitor
/// and the UI). Useful for callers that want to branch on connectivity. /// and the UI). Useful for callers that want to branch on connectivity.
#[allow(dead_code)] // public API; currently only exercised by cross-module tests
pub async fn is_reachable(&self) -> bool { pub async fn is_reachable(&self) -> bool {
self.status.read().await.is_server_reachable self.status.read().await.is_server_reachable
} }
+98 -9
View File
@@ -284,22 +284,35 @@ impl JellyfinClient {
} }
/// Seek on a remote session /// Seek on a remote session
///
/// Jellyfin's `/Sessions/{id}/Playing/Seek` endpoint takes the target as the
/// `SeekPositionTicks` *query parameter*, not a JSON body. Sending it in the
/// body (as we used to) is silently ignored and the remote never seeks.
pub async fn session_seek( pub async fn session_seek(
&self, &self,
session_id: String, session_id: String,
position_ticks: i64, position_ticks: i64,
) -> Result<(), String> { ) -> Result<(), String> {
#[derive(serde::Serialize)] let url = format!(
#[serde(rename_all = "PascalCase")] "{}/Sessions/{}/Playing/Seek?SeekPositionTicks={}",
struct SeekRequest { self.config.server_url, session_id, position_ticks
seek_position_ticks: i64, );
let response = self.http_client
.post(&url)
.header("X-Emby-Authorization", self.get_auth_header())
.send()
.await
.map_err(|e| format!("Network request failed: {}", e))?;
let status = response.status();
if !status.is_success() {
let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
return Err(format!("Jellyfin API error {}: {}", status.as_u16(), error_text));
} }
let request = SeekRequest { log::info!("[JellyfinClient] Seek to {} ticks on session {}", position_ticks, session_id);
seek_position_ticks: position_ticks, Ok(())
};
self.post(&format!("/Sessions/{}/Playing/Seek", session_id), &request).await
} }
/// Send a full GeneralCommand to a remote session. /// Send a full GeneralCommand to a remote session.
@@ -371,6 +384,82 @@ impl JellyfinClient {
let sessions = self.get_sessions().await?; let sessions = self.get_sessions().await?;
Ok(sessions.into_iter().find(|s| s.id.as_deref() == Some(session_id))) Ok(sessions.into_iter().find(|s| s.id.as_deref() == Some(session_id)))
} }
// --- JellyLMS multi-room sync groups -----------------------------------
//
// The JellyLMS plugin exposes a REST API under `/JellyLms` for grouping LMS
// players ("zones") into synchronized multi-room sync groups. Players are
// addressed by MAC address; JellyTau maps a Jellyfin session to a MAC by
// stripping the `lms-` prefix off the session's device id (see
// LmsDeviceDiscoveryService in the jellyLMS repo, which registers each player
// with deviceId = "lms-{MacAddress}").
/// List current LMS sync groups.
pub async fn lms_get_sync_groups(&self) -> Result<Vec<LmsSyncGroup>, String> {
self.get("/JellyLms/SyncGroups").await
}
/// Fuse LMS zones: create a sync group with `master_mac` as the sync master
/// and `slave_macs` joining it. The master keeps playing; slaves follow.
pub async fn lms_create_sync_group(
&self,
master_mac: &str,
slave_macs: Vec<String>,
) -> Result<(), String> {
let payload = serde_json::json!({
"MasterMac": master_mac,
"SlaveMacs": slave_macs,
});
self.post("/JellyLms/SyncGroups", &payload).await
}
/// Remove a single LMS player from whatever sync group it's in.
pub async fn lms_unsync_player(&self, mac: &str) -> Result<(), String> {
self.delete(&format!("/JellyLms/SyncGroups/Players/{}", mac)).await
}
/// Dissolve an entire LMS sync group, identified by its master's MAC.
pub async fn lms_dissolve_sync_group(&self, master_mac: &str) -> Result<(), String> {
self.delete(&format!("/JellyLms/SyncGroups/{}", master_mac)).await
}
/// Make a DELETE request to the Jellyfin API (used by the JellyLMS endpoints).
async fn delete(&self, endpoint: &str) -> Result<(), String> {
let url = format!("{}{}", self.config.server_url, endpoint);
log::debug!("[JellyfinClient] DELETE {}", endpoint);
let response = self.http_client
.delete(&url)
.header("X-Emby-Authorization", self.get_auth_header())
.send()
.await
.map_err(|e| format!("Network request failed: {}", e))?;
let status = response.status();
if !status.is_success() {
let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
return Err(format!("Jellyfin API error {}: {}", status.as_u16(), error_text));
}
Ok(())
}
}
/// An LMS multi-room sync group, as returned by JellyLMS `/JellyLms/SyncGroups`.
///
/// Mirrors the plugin's `SyncGroup` model. The master is the sync source; slaves
/// follow it in lockstep.
#[derive(specta::Type, Debug, Clone, Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LmsSyncGroup {
#[serde(alias = "MasterMac")]
pub master_mac: String,
#[serde(default, alias = "MasterName")]
pub master_name: String,
#[serde(default, alias = "SlaveMacs")]
pub slave_macs: Vec<String>,
#[serde(default, alias = "SlaveNames")]
pub slave_names: Vec<String>,
} }
/// Default value for supports_remote_control when missing from API /// Default value for supports_remote_control when missing from API
+23 -3
View File
@@ -52,11 +52,13 @@ use commands::{
// Remote session control commands // Remote session control commands
remote_play_on_session, remote_send_command, remote_session_seek, remote_session_set_volume, remote_play_on_session, remote_send_command, remote_session_seek, remote_session_set_volume,
remote_session_toggle_mute, remote_session_toggle_mute,
// LMS multi-room sync group commands
lms_get_sync_groups, lms_create_sync_group, lms_unsync_player, lms_dissolve_sync_group,
// Session polling commands // Session polling commands
sessions_set_polling_hint, sessions_poll_now, SessionPollerWrapper, sessions_set_polling_hint, sessions_poll_now, SessionPollerWrapper,
// Playback mode commands // Playback mode commands
playback_mode_get_current, playback_mode_set, playback_mode_is_transferring, playback_mode_get_current, playback_mode_set, playback_mode_is_transferring,
playback_mode_transfer_to_remote, playback_mode_transfer_to_local, playback_mode_transfer_to_remote, playback_mode_transfer_to_local, playback_mode_set_transferring,
playback_mode_get_remote_status, playback_mode_get_remote_status,
// Playback reporting commands // Playback reporting commands
playback_reporter_init, playback_reporter_destroy, playback_reporter_init, playback_reporter_destroy,
@@ -99,6 +101,7 @@ use commands::{
repository_get_rediscover_albums, repository_get_rediscover_albums,
repository_get_genres, repository_search, repository_get_playback_info, repository_get_genres, repository_search, repository_get_playback_info,
repository_get_video_stream_url, repository_get_audio_stream_url, repository_get_video_stream_url, repository_get_audio_stream_url,
repository_get_live_tv_channels, repository_get_channels, repository_open_live_stream,
repository_report_playback_start, repository_report_playback_progress, repository_report_playback_stopped, repository_report_playback_start, repository_report_playback_progress, repository_report_playback_stopped,
repository_get_image_url, repository_mark_favorite, repository_unmark_favorite, repository_get_image_url, repository_mark_favorite, repository_unmark_favorite,
repository_get_person, repository_get_items_by_person, repository_get_similar_items, repository_get_person, repository_get_items_by_person, repository_get_similar_items,
@@ -356,6 +359,9 @@ fn specta_builder() -> Builder<tauri::Wry> {
// Throw on error so generated `commands.*` return Promise<T> and throw, // Throw on error so generated `commands.*` return Promise<T> and throw,
// matching the existing frontend's invoke() try/catch convention. // matching the existing frontend's invoke() try/catch convention.
.error_handling(tauri_specta::ErrorHandlingMode::Throw) .error_handling(tauri_specta::ErrorHandlingMode::Throw)
.events(tauri_specta::collect_events![
crate::player::events::PlayerStatusEvent
])
.commands(tauri_specta::collect_commands![ .commands(tauri_specta::collect_commands![
// Player commands // Player commands
player_play_item, player_play_item,
@@ -414,6 +420,11 @@ fn specta_builder() -> Builder<tauri::Wry> {
remote_session_seek, remote_session_seek,
remote_session_set_volume, remote_session_set_volume,
remote_session_toggle_mute, remote_session_toggle_mute,
// LMS multi-room sync group commands
lms_get_sync_groups,
lms_create_sync_group,
lms_unsync_player,
lms_dissolve_sync_group,
// Session polling commands // Session polling commands
sessions_set_polling_hint, sessions_set_polling_hint,
sessions_poll_now, sessions_poll_now,
@@ -424,6 +435,7 @@ fn specta_builder() -> Builder<tauri::Wry> {
playback_mode_transfer_to_remote, playback_mode_transfer_to_remote,
playback_mode_get_remote_status, playback_mode_get_remote_status,
playback_mode_transfer_to_local, playback_mode_transfer_to_local,
playback_mode_set_transferring,
// Playback reporting commands // Playback reporting commands
playback_reporter_init, playback_reporter_init,
playback_reporter_destroy, playback_reporter_destroy,
@@ -561,6 +573,9 @@ fn specta_builder() -> Builder<tauri::Wry> {
repository_get_playback_info, repository_get_playback_info,
repository_get_video_stream_url, repository_get_video_stream_url,
repository_get_audio_stream_url, repository_get_audio_stream_url,
repository_get_live_tv_channels,
repository_get_channels,
repository_open_live_stream,
repository_report_playback_start, repository_report_playback_start,
repository_report_playback_progress, repository_report_playback_progress,
repository_report_playback_stopped, repository_report_playback_stopped,
@@ -601,11 +616,17 @@ pub fn run() {
// `.export()` here would try to write `../src/lib/api/bindings.ts` at app // `.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. // startup, which panics on devices (e.g. Android) where that path doesn't exist.
let builder = specta_builder(); let builder = specta_builder();
let invoke_handler = builder.invoke_handler();
tauri::Builder::default() tauri::Builder::default()
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_os::init()) .plugin(tauri_plugin_os::init())
.setup(|app| { .invoke_handler(invoke_handler)
.setup(move |app| {
// Mount tauri-specta events so PlayerStatusEvent can be emitted to and
// listened for on the frontend via the generated bindings.
builder.mount_events(app);
// Initialize database with proper app data directory // Initialize database with proper app data directory
// Check for test mode environment variable first // Check for test mode environment variable first
let db_path = if let Ok(test_data_dir) = std::env::var("JELLYTAU_DATA_DIR") { let db_path = if let Ok(test_data_dir) = std::env::var("JELLYTAU_DATA_DIR") {
@@ -845,7 +866,6 @@ pub fn run() {
info!("[INIT] Application setup completed successfully"); info!("[INIT] Application setup completed successfully");
Ok(()) Ok(())
}) })
.invoke_handler(builder.invoke_handler())
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
} }
+154 -12
View File
@@ -20,6 +20,28 @@ pub enum PlaybackMode {
Idle, Idle,
} }
/// Number of Jellyfin ticks per second (100ns units).
const TICKS_PER_SECOND: f64 = 10_000_000.0;
/// Below this many seconds we treat the position as "at the start" and don't
/// send a resume position, so a fresh track casts from 0 rather than ~0.
const RESUME_THRESHOLD_SECONDS: f64 = 0.5;
/// Convert a live playback position (seconds) into the `StartPositionTicks` to
/// hand to a remote session, or `None` if we're effectively at the start.
///
/// Pure helper so the resume-position math is unit-testable without a remote
/// session or HTTP. The *source* of `position_seconds` matters too: callers
/// must pass the live backend position (`PlayerController::position()`), not the
/// snapshot embedded in `PlayerState`, which is stale mid-track on Android.
fn start_position_ticks_from_seconds(position_seconds: f64) -> Option<i64> {
if position_seconds > RESUME_THRESHOLD_SECONDS {
Some((position_seconds * TICKS_PER_SECOND) as i64)
} else {
None
}
}
/// Manages playback mode transfers between local and remote sessions /// Manages playback mode transfers between local and remote sessions
pub struct PlaybackModeManager { pub struct PlaybackModeManager {
jellyfin_client: Arc<Mutex<Option<JellyfinClient>>>, jellyfin_client: Arc<Mutex<Option<JellyfinClient>>>,
@@ -59,6 +81,19 @@ impl PlaybackModeManager {
self.is_transferring.load(Ordering::Relaxed) self.is_transferring.load(Ordering::Relaxed)
} }
/// Set the transferring flag directly.
///
/// The remote->local transfer is driven from the frontend in two steps
/// (`player_play_tracks` to start local playback, then
/// `playback_mode_transfer_to_local` to stop the remote). The first step's
/// routing depends on this flag: while it's set, `player_play_tracks` plays
/// locally instead of casting back to the remote session. The frontend must
/// raise the flag *before* that first call and lower it when the sequence is
/// done (or aborts), so it can't be left stuck on.
pub fn set_transferring(&self, transferring: bool) {
self.is_transferring.store(transferring, Ordering::Relaxed);
}
/// Send volume command to remote session /// Send volume command to remote session
/// Commands: "SetVolume", "VolumeUp", "VolumeDown" /// Commands: "SetVolume", "VolumeUp", "VolumeDown"
#[allow(dead_code)] // Called from Android JNI callback #[allow(dead_code)] // Called from Android JNI callback
@@ -159,7 +194,11 @@ impl PlaybackModeManager {
} }
/// Transfer playback from local device to remote Jellyfin session /// Transfer playback from local device to remote Jellyfin session
pub async fn transfer_to_remote(&self, session_id: String) -> Result<(), String> { pub async fn transfer_to_remote(
&self,
session_id: String,
position_override: Option<f64>,
) -> Result<(), String> {
debug!("[PlaybackMode] transfer_to_remote ENTERED"); debug!("[PlaybackMode] transfer_to_remote ENTERED");
debug!("[PlaybackMode] session_id: {}", session_id); debug!("[PlaybackMode] session_id: {}", session_id);
log::info!( log::info!(
@@ -173,7 +212,7 @@ impl PlaybackModeManager {
debug!("[PlaybackMode] Flag set, calling transfer_to_remote_inner"); debug!("[PlaybackMode] Flag set, calling transfer_to_remote_inner");
// Perform the transfer // Perform the transfer
let result = self.transfer_to_remote_inner(&session_id).await; let result = self.transfer_to_remote_inner(&session_id, position_override).await;
// Clear transferring flag // Clear transferring flag
self.is_transferring.store(false, Ordering::Relaxed); self.is_transferring.store(false, Ordering::Relaxed);
@@ -181,12 +220,24 @@ impl PlaybackModeManager {
result result
} }
async fn transfer_to_remote_inner(&self, session_id: &str) -> Result<(), String> { async fn transfer_to_remote_inner(
&self,
session_id: &str,
position_override: Option<f64>,
) -> Result<(), String> {
log::info!("[PlaybackMode] transfer_to_remote_inner ENTERED"); log::info!("[PlaybackMode] transfer_to_remote_inner ENTERED");
debug!("[PlaybackMode] transfer_to_remote_inner: session_id={}", session_id); debug!("[PlaybackMode] transfer_to_remote_inner: session_id={}", session_id);
// If we're already controlling a remote session, that *old* session — not
// the idle local player — is the source of truth for the current track and
// position. Capture it so we can resume there and stop it afterwards.
let previous_remote_session = match self.get_mode() {
PlaybackMode::Remote { session_id: prev } if prev != session_id => Some(prev),
_ => None,
};
// Get current player state and queue context // Get current player state and queue context
let (queue_ids, current_index, position_seconds, queue_context) = { let (queue_ids, mut current_index, mut position_seconds, queue_context) = {
log::info!("[PlaybackMode] Acquiring player controller lock..."); log::info!("[PlaybackMode] Acquiring player controller lock...");
debug!("[PlaybackMode] Acquiring player controller lock..."); debug!("[PlaybackMode] Acquiring player controller lock...");
let player = self.player_controller.lock().await; let player = self.player_controller.lock().await;
@@ -195,7 +246,6 @@ impl PlaybackModeManager {
let queue_arc = player.queue(); let queue_arc = player.queue();
let queue = queue_arc.lock_safe(); let queue = queue_arc.lock_safe();
let state = player.state();
let original_index = queue.current_index().unwrap_or(0); let original_index = queue.current_index().unwrap_or(0);
let items = queue.items(); let items = queue.items();
@@ -210,7 +260,19 @@ impl PlaybackModeManager {
} }
let (ids, adjusted_index) = self.extract_jellyfin_ids(items, original_index)?; let (ids, adjusted_index) = self.extract_jellyfin_ids(items, original_index)?;
let position = state.position().unwrap_or(0.0); // Prefer the frontend-supplied position when available. The backend
// position is unreliable as a transfer source: on Linux, *video* plays
// in the HTML5 <video> element and the MPV backend is never loaded, so
// PlayerController::position() is always 0; only the frontend knows the
// true position. We fall back to the live backend position (correct for
// Linux audio via MPV) when the frontend doesn't pass one.
let position = match position_override {
Some(p) => {
log::info!("[PlaybackMode] Using frontend position override: {:.2}s", p);
p
}
None => player.position(),
};
let context = queue.context().clone(); let context = queue.context().clone();
log::info!( log::info!(
@@ -272,12 +334,48 @@ impl PlaybackModeManager {
} }
}; };
// Calculate position in ticks // Remote -> remote switch: take the current track and position from the
let start_position_ticks = if position_seconds > 0.5 { // session we're leaving, since the local player is idle and reports 0.
Some((position_seconds * 10_000_000.0) as i64) if let Some(ref prev_session_id) = previous_remote_session {
} else { log::info!(
None "[PlaybackMode] Remote->remote switch; reading state from previous session {}",
}; prev_session_id
);
match client.get_session(prev_session_id).await {
Ok(Some(session)) => {
// Resume at the previous session's position.
if let Some(ticks) = session.play_state.as_ref().and_then(|ps| ps.position_ticks) {
position_seconds = ticks as f64 / TICKS_PER_SECOND;
log::info!(
"[PlaybackMode] Using previous remote position: {:.2}s",
position_seconds
);
}
// Resume on whichever track the previous session reached.
if let Some(now_id) = session.now_playing_item.as_ref().and_then(|i| i.id.as_deref()) {
if let Some(idx) = queue_ids.iter().position(|id| id == now_id) {
log::info!(
"[PlaybackMode] Previous session is on track {} (queue index {})",
now_id,
idx
);
current_index = idx;
} else {
log::warn!(
"[PlaybackMode] Previous session's track {} not found in queue; keeping index {}",
now_id,
current_index
);
}
}
}
Ok(None) => log::warn!("[PlaybackMode] Previous remote session not found while reading state"),
Err(e) => log::warn!("[PlaybackMode] Failed to read previous remote session: {}", e),
}
}
// Calculate position in ticks (from the live position read above)
let start_position_ticks = start_position_ticks_from_seconds(position_seconds);
// Log queue context for debugging (context is tracked but we always send track IDs) // Log queue context for debugging (context is tracked but we always send track IDs)
match &queue_context { match &queue_context {
@@ -392,6 +490,33 @@ impl PlaybackModeManager {
return Err("Remote session did not load track in time".to_string()); return Err("Remote session did not load track in time".to_string());
} }
// Resume at the right position. We send StartPositionTicks in the play
// command above, but some Jellyfin client/server combinations ignore it
// and start from 0. Now that the track is confirmed loaded, issue an
// explicit seek as well (mirrors how the local resume path works). This
// is the reliable mechanism; StartPositionTicks is best-effort.
if let Some(ticks) = start_position_ticks {
log::info!(
"[PlaybackMode] Seeking remote session to resume position: {} ticks",
ticks
);
if let Err(e) = client.session_seek(session_id.to_string(), ticks).await {
// Non-fatal: the track is already playing, just not at the
// resume point. Log and continue rather than failing the transfer.
log::warn!("[PlaybackMode] Resume seek on remote failed: {}", e);
}
}
// Remote -> remote switch: stop the session we just left so we don't end
// up with two devices playing at once. Do this only after the new session
// is confirmed playing, so a failure here doesn't leave us with silence.
if let Some(prev_session_id) = previous_remote_session {
log::info!("[PlaybackMode] Stopping previous remote session {}", prev_session_id);
if let Err(e) = client.send_session_command(prev_session_id, "Stop").await {
log::warn!("[PlaybackMode] Failed to stop previous remote session: {}", e);
}
}
// Stop local playback (queue should remain intact for remote session) // Stop local playback (queue should remain intact for remote session)
log::info!("[PlaybackMode] Stopping local playback - queue should NOT be cleared"); log::info!("[PlaybackMode] Stopping local playback - queue should NOT be cleared");
{ {
@@ -577,6 +702,23 @@ mod tests {
); );
} }
/// The resume position handed to a remote session is derived from a live
/// playback position. Guards the seconds->ticks conversion and the
/// at-the-start threshold (Bug: casting restarted the track from 0).
#[test]
fn test_start_position_ticks_from_seconds() {
// Mid-track positions convert to ticks (10M ticks per second).
assert_eq!(start_position_ticks_from_seconds(5.0), Some(50_000_000));
assert_eq!(start_position_ticks_from_seconds(123.45), Some(1_234_500_000));
// At/near the start, send no resume position so the track casts from 0.
assert_eq!(start_position_ticks_from_seconds(0.0), None);
assert_eq!(start_position_ticks_from_seconds(0.5), None);
// Just past the threshold resumes rather than restarting.
assert!(start_position_ticks_from_seconds(0.6).is_some());
}
// Tests for extract_jellyfin_ids - verify all track IDs are sent to remote, not just album/playlist ID // Tests for extract_jellyfin_ids - verify all track IDs are sent to remote, not just album/playlist ID
mod extract_jellyfin_ids_tests { mod extract_jellyfin_ids_tests {
use crate::player::{MediaItem, MediaSource, MediaType}; use crate::player::{MediaItem, MediaSource, MediaType};
+6 -1
View File
@@ -678,7 +678,12 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
// Use tauri::async_runtime::spawn instead of tokio::spawn // Use tauri::async_runtime::spawn instead of tokio::spawn
// JNI callbacks happen on arbitrary threads without a Tokio runtime // JNI callbacks happen on arbitrary threads without a Tokio runtime
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
match controller.lock().await.on_playback_ended().await { // Compute the autoplay decision and release the lock before matching.
// Holding the guard across the match would deadlock the AdvanceToNext
// arm, which re-locks the controller to call next() — leaving playback
// stopped (paused at position 0) instead of advancing.
let decision = controller.lock().await.on_playback_ended().await;
match decision {
Ok(AutoplayDecision::Stop) => { Ok(AutoplayDecision::Stop) => {
log::debug!("[Autoplay] Decision: Stop playback"); log::debug!("[Autoplay] Decision: Stop playback");
// Emit PlaybackEnded event to frontend // Emit PlaybackEnded event to frontend
+13 -6
View File
@@ -10,7 +10,8 @@ use crate::utils::lock::MutexSafe;
use log::error; use log::error;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use tauri::{AppHandle, Emitter}; use tauri::AppHandle;
use tauri_specta::Event;
use super::{MediaSessionType, SleepTimerMode}; use super::{MediaSessionType, SleepTimerMode};
@@ -20,7 +21,14 @@ use super::{MediaSessionType, SleepTimerMode};
/// state machine transitions. /// state machine transitions.
/// ///
/// TRACES: UR-005, UR-019, UR-023, UR-026 | DR-001, DR-028, DR-047 /// TRACES: UR-005, UR-019, UR-023, UR-026 | DR-001, DR-028, DR-047
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize, specta::Type, tauri_specta::Event)]
// NOTE: fields are intentionally snake_case on the wire. specta generates the
// TypeScript bindings with snake_case field names (it does not apply serde's
// `rename_all_fields`), so adding `rename_all_fields = "camelCase"` here makes
// serde emit camelCase payloads that no longer match the generated schema —
// tauri-specta then silently drops those events (e.g. state_changed,
// queue_changed never reach the frontend, so the mini player never appears).
// Keep serde and specta agreeing: snake_case fields, snake_case variant tags.
#[serde(tag = "type", rename_all = "snake_case")] #[serde(tag = "type", rename_all = "snake_case")]
pub enum PlayerStatusEvent { pub enum PlayerStatusEvent {
/// Playback position updated (emitted periodically during playback) /// Playback position updated (emitted periodically during playback)
@@ -113,9 +121,6 @@ pub enum PlayerStatusEvent {
}, },
} }
/// Tauri event name for player status events
pub const PLAYER_EVENT_NAME: &str = "player-event";
/// Trait for emitting player events to the frontend. /// Trait for emitting player events to the frontend.
/// ///
/// This abstraction allows backends to emit events without depending /// This abstraction allows backends to emit events without depending
@@ -141,7 +146,9 @@ impl TauriEventEmitter {
impl PlayerEventEmitter for TauriEventEmitter { impl PlayerEventEmitter for TauriEventEmitter {
fn emit(&self, event: PlayerStatusEvent) { fn emit(&self, event: PlayerStatusEvent) {
if let Err(e) = self.app_handle.emit(PLAYER_EVENT_NAME, &event) { // Emitted via the tauri-specta Event trait so the payload shape and event
// name match the generated TypeScript bindings (events.playerStatusEvent).
if let Err(e) = Event::emit(&event, &self.app_handle) {
error!("Failed to emit player event: {}", e); error!("Failed to emit player event: {}", e);
} }
} }
+85 -1
View File
@@ -311,7 +311,27 @@ impl PlayerController {
/// Set the queue and start playing from the specified index /// Set the queue and start playing from the specified index
pub fn play_queue(&self, items: Vec<MediaItem>, start_index: usize) -> Result<(), PlayerError> { pub fn play_queue(&self, items: Vec<MediaItem>, start_index: usize) -> Result<(), PlayerError> {
debug!("[PlayerController] play_queue: {} items, starting at index {}", items.len(), start_index); self.play_queue_from(items, start_index, None)
}
/// Set the queue and start playing from the specified index, optionally
/// resuming the starting track at `start_position` (seconds).
///
/// The seek happens immediately after load so the backend never audibly
/// starts at 0 and there's no race against a fixed delay. Used when taking
/// over playback from a remote session.
pub fn play_queue_from(
&self,
items: Vec<MediaItem>,
start_index: usize,
start_position: Option<f64>,
) -> Result<(), PlayerError> {
debug!(
"[PlayerController] play_queue: {} items, starting at index {} (resume: {:?})",
items.len(),
start_index,
start_position
);
// Reset autoplay counter on manual queue start // Reset autoplay counter on manual queue start
self.reset_autoplay_count(); self.reset_autoplay_count();
@@ -324,11 +344,37 @@ impl PlayerController {
// Play the current item (without modifying the queue we just set) // Play the current item (without modifying the queue we just set)
if let Some(item) = self.queue.lock_safe().current().cloned() { if let Some(item) = self.queue.lock_safe().current().cloned() {
self.load_and_play(&item)?; self.load_and_play(&item)?;
// Resume from the requested position. Seeking right after load (while
// the backend lock is no longer held) avoids the start-at-0-then-jump
// race that a delayed frontend seek suffers from.
if let Some(position) = start_position {
if position > 0.5 {
self.seek(position)?;
}
}
} }
Ok(()) Ok(())
} }
/// Replace the queue without starting local playback.
///
/// Used when we're controlling a remote session: the tracks play on the
/// remote device, but we keep the local queue in sync so the UI reflects
/// what's playing and a later transfer-to-local has the queue to resume.
pub fn set_queue(&self, items: Vec<MediaItem>, start_index: usize) -> Result<(), PlayerError> {
debug!(
"[PlayerController] set_queue (no local playback): {} items, index {}",
items.len(),
start_index
);
self.reset_autoplay_count();
let mut queue = self.queue.lock_safe();
queue.set_queue(items, start_index);
Ok(())
}
/// Play/resume playback /// Play/resume playback
pub fn play(&self) -> Result<(), PlayerError> { pub fn play(&self) -> Result<(), PlayerError> {
debug!("[PlayerController] play"); debug!("[PlayerController] play");
@@ -1333,6 +1379,44 @@ mod tests {
} }
} }
/// Resuming a queue at a position seeks the starting track immediately.
/// Regression guard for taking over a remote session: the local player must
/// pick up where the remote left off, not restart from 0.
#[test]
fn test_play_queue_from_resumes_at_position() {
let controller = PlayerController::default();
let items = create_test_items(3);
controller.play_queue_from(items, 1, Some(42.5)).unwrap();
{
let queue = controller.queue();
let queue_lock = queue.lock_safe();
assert_eq!(queue_lock.current_index(), Some(1), "Should start at index 1");
}
assert_eq!(controller.position(), 42.5, "Should resume at the requested position");
}
/// A None / near-zero start position starts the track from the beginning.
#[test]
fn test_play_queue_from_without_position_starts_at_zero() {
let controller = PlayerController::default();
controller
.play_queue_from(create_test_items(2), 0, None)
.unwrap();
assert_eq!(controller.position(), 0.0, "No resume position starts at 0");
controller
.play_queue_from(create_test_items(2), 0, Some(0.2))
.unwrap();
assert_eq!(
controller.position(),
0.0,
"Sub-threshold resume position is ignored (starts at 0)"
);
}
#[test] #[test]
fn test_seek_to_zero() { fn test_seek_to_zero() {
let controller = PlayerController::default(); let controller = PlayerController::default();
+6 -1
View File
@@ -61,7 +61,12 @@ pub enum PlayerState {
} }
impl PlayerState { impl PlayerState {
/// Get the current playback position if available /// Get the current playback position if available.
///
/// Note: this is the position snapshot embedded in the state at the last
/// state transition, not the live backend position. For an up-to-date
/// value use `PlayerController::position()`.
#[allow(dead_code)]
pub fn position(&self) -> Option<f64> { pub fn position(&self) -> Option<f64> {
match self { match self {
PlayerState::Playing { position, .. } => Some(*position), PlayerState::Playing { position, .. } => Some(*position),
+40
View File
@@ -415,6 +415,21 @@ impl MediaRepository for HybridRepository {
self.online.get_audio_stream_url(item_id).await self.online.get_audio_stream_url(item_id).await
} }
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError> {
// Live TV requires server communication - delegate to online repository
self.online.get_live_tv_channels().await
}
async fn get_channels(&self) -> Result<SearchResult, RepoError> {
// Plugin channels require server communication - delegate to online repository
self.online.get_channels().await
}
async fn open_live_stream(&self, item_id: &str) -> Result<LiveStreamInfo, RepoError> {
// Opening a live stream requires server communication - delegate to online
self.online.open_live_stream(item_id).await
}
async fn report_playback_start(&self, item_id: &str, position_ticks: i64) -> Result<(), RepoError> { async fn report_playback_start(&self, item_id: &str, position_ticks: i64) -> Result<(), RepoError> {
// Playback reporting goes directly to server // Playback reporting goes directly to server
self.online.report_playback_start(item_id, position_ticks).await self.online.report_playback_start(item_id, position_ticks).await
@@ -722,6 +737,18 @@ mod tests {
unimplemented!() unimplemented!()
} }
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError> {
unimplemented!()
}
async fn get_channels(&self) -> Result<SearchResult, RepoError> {
unimplemented!()
}
async fn open_live_stream(&self, _item_id: &str) -> Result<LiveStreamInfo, RepoError> {
unimplemented!()
}
async fn report_playback_start(&self, _item_id: &str, _position_ticks: i64) -> Result<(), RepoError> { async fn report_playback_start(&self, _item_id: &str, _position_ticks: i64) -> Result<(), RepoError> {
unimplemented!() unimplemented!()
} }
@@ -887,6 +914,18 @@ mod tests {
unimplemented!() unimplemented!()
} }
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError> {
unimplemented!()
}
async fn get_channels(&self) -> Result<SearchResult, RepoError> {
unimplemented!()
}
async fn open_live_stream(&self, _item_id: &str) -> Result<LiveStreamInfo, RepoError> {
unimplemented!()
}
async fn report_playback_start(&self, _item_id: &str, _position_ticks: i64) -> Result<(), RepoError> { async fn report_playback_start(&self, _item_id: &str, _position_ticks: i64) -> Result<(), RepoError> {
unimplemented!() unimplemented!()
} }
@@ -976,6 +1015,7 @@ mod tests {
id: id.to_string(), id: id.to_string(),
name: name.to_string(), name: name.to_string(),
item_type: "Movie".to_string(), item_type: "Movie".to_string(),
is_folder: false,
server_id: "test-server".to_string(), server_id: "test-server".to_string(),
parent_id: Some("parent-123".to_string()), parent_id: Some("parent-123".to_string()),
library_id: Some("library-456".to_string()), library_id: Some("library-456".to_string()),
+13
View File
@@ -117,6 +117,19 @@ pub trait MediaRepository: Send + Sync {
/// @req: JA-007 - Get playback info and stream URL /// @req: JA-007 - Get playback info and stream URL
async fn get_audio_stream_url(&self, item_id: &str) -> Result<String, RepoError>; async fn get_audio_stream_url(&self, item_id: &str) -> Result<String, RepoError>;
/// Get Live TV channels (broadcast / IPTV) for browsing.
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError>;
/// Get the root list of plugin "Channels" (Jellyfin Channels feature).
/// Drill-down into a channel reuses `get_items(channel_id, ...)`.
async fn get_channels(&self) -> Result<SearchResult, RepoError>;
/// Open a live stream (Live TV channel or live channel item) for playback.
///
/// Returns the server transcoding URL plus identifiers needed to manage the
/// stream. Required before a live channel can be played over HLS.
async fn open_live_stream(&self, item_id: &str) -> Result<LiveStreamInfo, RepoError>;
/// Report playback start /// Report playback start
/// ///
/// @req: UR-025 - Sync watch history and progress back to Jellyfin /// @req: UR-025 - Sync watch history and progress back to Jellyfin
+70 -30
View File
@@ -29,6 +29,7 @@ impl OfflineRepository {
id: item.id.clone(), id: item.id.clone(),
name: item.name, name: item.name,
item_type: item.item_type, item_type: item.item_type,
is_folder: item.is_folder,
server_id: item.server_id, server_id: item.server_id,
parent_id: item.parent_id, parent_id: item.parent_id,
library_id: item.library_id, library_id: item.library_id,
@@ -92,6 +93,7 @@ struct CachedItem {
id: String, id: String,
name: String, name: String,
item_type: String, item_type: String,
is_folder: bool,
server_id: String, server_id: String,
parent_id: Option<String>, parent_id: Option<String>,
library_id: Option<String>, library_id: Option<String>,
@@ -143,6 +145,8 @@ fn row_to_cached_item(row: &rusqlite::Row) -> rusqlite::Result<CachedItem> {
season_id: row.get(20)?, season_id: row.get(20)?,
season_name: row.get(21)?, season_name: row.get(21)?,
parent_index_number: row.get(22)?, parent_index_number: row.get(22)?,
// Appended as the final column in every SELECT that maps through this fn.
is_folder: row.get::<_, Option<i64>>(23)?.unwrap_or(0) != 0,
}) })
} }
@@ -230,7 +234,7 @@ impl OfflineRepository {
let query = Query::with_params( let query = Query::with_params(
"INSERT OR REPLACE INTO items ( "INSERT OR REPLACE INTO items (
id, server_id, library_id, parent_id, id, server_id, library_id, parent_id,
name, item_type, overview, name, item_type, is_folder, overview,
genres, series_id, series_name, genres, series_id, series_name,
season_id, season_name, index_number, parent_index_number, season_id, season_name, index_number, parent_index_number,
album_id, album_name, album_artist, artists, album_id, album_name, album_artist, artists,
@@ -240,14 +244,14 @@ impl OfflineRepository {
synced_at synced_at
) VALUES ( ) VALUES (
?1, ?2, ?3, ?4, ?1, ?2, ?3, ?4,
?5, ?6, ?7, ?5, ?6, ?7, ?8,
?8, ?9, ?10, ?9, ?10, ?11,
?11, ?12, ?13, ?14, ?12, ?13, ?14, ?15,
?15, ?16, ?17, ?18, ?16, ?17, ?18, ?19,
?19, ?20, ?20, ?21,
?21, ?22, ?22, ?23,
?23, ?24, ?24, ?25,
?25 ?26
)", )",
vec![ vec![
QueryParam::String(item.id.clone()), QueryParam::String(item.id.clone()),
@@ -261,6 +265,7 @@ impl OfflineRepository {
}, },
QueryParam::String(item.name.clone()), QueryParam::String(item.name.clone()),
QueryParam::String(item.item_type.clone()), QueryParam::String(item.item_type.clone()),
QueryParam::Int(if item.is_folder { 1 } else { 0 }),
match &item.overview { match &item.overview {
Some(o) => QueryParam::String(o.clone()), Some(o) => QueryParam::String(o.clone()),
None => QueryParam::Null, None => QueryParam::Null,
@@ -491,7 +496,7 @@ impl MediaRepository for OfflineRepository {
i.runtime_ticks, i.production_year, i.community_rating, i.official_rating, i.runtime_ticks, i.production_year, i.community_rating, i.official_rating,
i.primary_image_tag, i.album_id, i.album_name, i.album_artist, i.artists, i.primary_image_tag, i.album_id, i.album_name, i.album_artist, i.artists,
i.index_number, i.series_id, i.series_name, i.season_id, i.season_name, i.index_number, i.series_id, i.series_name, i.season_id, i.season_name,
i.parent_index_number i.parent_index_number, i.is_folder
FROM items i FROM items i
INNER JOIN available_items ai ON i.id = ai.id INNER JOIN available_items ai ON i.id = ai.id
WHERE i.server_id = ? AND i.parent_id = ?{} WHERE i.server_id = ? AND i.parent_id = ?{}
@@ -556,7 +561,7 @@ impl MediaRepository for OfflineRepository {
i.runtime_ticks, i.production_year, i.community_rating, i.official_rating, i.runtime_ticks, i.production_year, i.community_rating, i.official_rating,
i.primary_image_tag, i.album_id, i.album_name, i.album_artist, i.artists, i.primary_image_tag, i.album_id, i.album_name, i.album_artist, i.artists,
i.index_number, i.series_id, i.series_name, i.season_id, i.season_name, i.index_number, i.series_id, i.series_name, i.season_id, i.season_name,
i.parent_index_number i.parent_index_number, i.is_folder
FROM items i FROM items i
INNER JOIN downloaded_items di ON i.id = di.id INNER JOIN downloaded_items di ON i.id = di.id
WHERE i.id = ?", WHERE i.id = ?",
@@ -601,7 +606,7 @@ impl MediaRepository for OfflineRepository {
i.runtime_ticks, i.production_year, i.community_rating, i.official_rating, i.runtime_ticks, i.production_year, i.community_rating, i.official_rating,
i.primary_image_tag, i.album_id, i.album_name, i.album_artist, i.artists, i.primary_image_tag, i.album_id, i.album_name, i.album_artist, i.artists,
i.index_number, i.series_id, i.series_name, i.season_id, i.season_name, i.index_number, i.series_id, i.series_name, i.season_id, i.season_name,
i.parent_index_number i.parent_index_number, i.is_folder
FROM items i FROM items i
INNER JOIN downloaded_items di ON i.id = di.id INNER JOIN downloaded_items di ON i.id = di.id
WHERE i.server_id = ? AND i.library_id = ? WHERE i.server_id = ? AND i.library_id = ?
@@ -639,7 +644,7 @@ impl MediaRepository for OfflineRepository {
i.community_rating, i.official_rating, i.primary_image_tag, i.community_rating, i.official_rating, i.primary_image_tag,
i.album_id, i.album_name, i.album_artist, i.artists, i.album_id, i.album_name, i.album_artist, i.artists,
i.index_number, i.series_id, i.series_name, i.season_id, i.index_number, i.series_id, i.series_name, i.season_id,
i.season_name, i.parent_index_number i.season_name, i.parent_index_number, i.is_folder
FROM items i FROM items i
JOIN user_data ud ON i.id = ud.item_id JOIN user_data ud ON i.id = ud.item_id
INNER JOIN downloads d ON i.id = d.item_id INNER JOIN downloads d ON i.id = d.item_id
@@ -664,7 +669,7 @@ impl MediaRepository for OfflineRepository {
i.community_rating, i.official_rating, i.primary_image_tag, i.community_rating, i.official_rating, i.primary_image_tag,
i.album_id, i.album_name, i.album_artist, i.artists, i.album_id, i.album_name, i.album_artist, i.artists,
i.index_number, i.series_id, i.series_name, i.season_id, i.index_number, i.series_id, i.series_name, i.season_id,
i.season_name, i.parent_index_number i.season_name, i.parent_index_number, i.is_folder
FROM items i FROM items i
JOIN user_data ud ON i.id = ud.item_id JOIN user_data ud ON i.id = ud.item_id
INNER JOIN downloads d ON i.id = d.item_id INNER JOIN downloads d ON i.id = d.item_id
@@ -752,7 +757,7 @@ impl MediaRepository for OfflineRepository {
i.community_rating, i.official_rating, i.primary_image_tag, i.community_rating, i.official_rating, i.primary_image_tag,
i.album_id, i.album_name, i.album_artist, i.artists, i.album_id, i.album_name, i.album_artist, i.artists,
i.index_number, i.series_id, i.series_name, i.season_id, i.index_number, i.series_id, i.series_name, i.season_id,
i.season_name, i.parent_index_number i.season_name, i.parent_index_number, i.is_folder
FROM ranked_plays rp FROM ranked_plays rp
JOIN items i ON rp.display_id = i.id JOIN items i ON rp.display_id = i.id
INNER JOIN downloaded_items di ON i.id = di.id INNER JOIN downloaded_items di ON i.id = di.id
@@ -800,7 +805,7 @@ impl MediaRepository for OfflineRepository {
i.community_rating, i.official_rating, i.primary_image_tag, i.community_rating, i.official_rating, i.primary_image_tag,
i.album_id, i.album_name, i.album_artist, i.artists, i.album_id, i.album_name, i.album_artist, i.artists,
i.index_number, i.series_id, i.series_name, i.season_id, i.index_number, i.series_id, i.series_name, i.season_id,
i.season_name, i.parent_index_number i.season_name, i.parent_index_number, i.is_folder
FROM items i FROM items i
JOIN user_data ud ON i.id = ud.item_id JOIN user_data ud ON i.id = ud.item_id
INNER JOIN downloads d ON i.id = d.item_id INNER JOIN downloads d ON i.id = d.item_id
@@ -830,41 +835,57 @@ impl MediaRepository for OfflineRepository {
} }
async fn get_genres(&self, parent_id: Option<&str>) -> Result<Vec<Genre>, RepoError> { async fn get_genres(&self, parent_id: Option<&str>) -> Result<Vec<Genre>, RepoError> {
// Extract unique genres from cached items // Derive genres from cached albums, tallying how many albums carry each
let mut genre_set = std::collections::HashSet::new(); // so the frontend can rank by popularity. We scope to MusicAlbum (genres
// power the music landing) and read every matching row — NOT DISTINCT —
// so the per-genre counts are real. Genres are stored as a JSON array
// string per item.
let (sql, params) = if let Some(pid) = parent_id { let (sql, params) = if let Some(pid) = parent_id {
( (
"SELECT DISTINCT genres FROM items WHERE server_id = ? AND library_id = ? AND genres IS NOT NULL", "SELECT genres FROM items WHERE server_id = ? AND library_id = ? \
AND item_type = 'MusicAlbum' AND genres IS NOT NULL",
vec![ vec![
QueryParam::String(self.server_id.clone()), QueryParam::String(self.server_id.clone()),
QueryParam::String(pid.to_string()), QueryParam::String(pid.to_string()),
] ],
) )
} else { } else {
( (
"SELECT DISTINCT genres FROM items WHERE server_id = ? AND genres IS NOT NULL", "SELECT genres FROM items WHERE server_id = ? \
vec![QueryParam::String(self.server_id.clone())] AND item_type = 'MusicAlbum' AND genres IS NOT NULL",
vec![QueryParam::String(self.server_id.clone())],
) )
}; };
let query = Query::with_params(sql, params); let query = Query::with_params(sql, params);
let genres_rows: Vec<String> = self.db_service.query_many(query, |row| row.get(0)) let genres_rows: Vec<String> = self
.db_service
.query_many(query, |row| row.get(0))
.await .await
.map_err(|e| RepoError::Database { message: e })?; .map_err(|e| RepoError::Database { message: e })?;
// genre name -> album count
let mut counts: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
for genres_json in genres_rows { for genres_json in genres_rows {
if let Ok(genres_vec) = serde_json::from_str::<Vec<String>>(&genres_json) { if let Ok(genres_vec) = serde_json::from_str::<Vec<String>>(&genres_json) {
// De-dupe within one album so a genre listed twice counts once.
let mut seen = std::collections::HashSet::new();
for genre in genres_vec { for genre in genres_vec {
genre_set.insert(genre); if seen.insert(genre.clone()) {
*counts.entry(genre).or_insert(0) += 1;
}
} }
} }
} }
let genres = genre_set let genres = counts
.into_iter() .into_iter()
.map(|name| Genre { id: name.clone(), name }) .map(|(name, count)| Genre {
id: name.clone(),
name,
album_count: Some(count),
})
.collect(); .collect();
Ok(genres) Ok(genres)
@@ -918,7 +939,7 @@ impl MediaRepository for OfflineRepository {
i.community_rating, i.official_rating, i.primary_image_tag, i.community_rating, i.official_rating, i.primary_image_tag,
i.album_id, i.album_name, i.album_artist, i.artists, i.album_id, i.album_name, i.album_artist, i.artists,
i.index_number, i.series_id, i.series_name, i.season_id, i.index_number, i.series_id, i.series_name, i.season_id,
i.season_name, i.parent_index_number i.season_name, i.parent_index_number, i.is_folder
FROM items i FROM items i
JOIN items_fts fts ON fts.rowid = i.rowid JOIN items_fts fts ON fts.rowid = i.rowid
INNER JOIN downloaded_items di ON i.id = di.id INNER JOIN downloaded_items di ON i.id = di.id
@@ -964,6 +985,21 @@ impl MediaRepository for OfflineRepository {
Err(RepoError::Offline) Err(RepoError::Offline)
} }
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError> {
// Live TV is inherently online-only.
Err(RepoError::Offline)
}
async fn get_channels(&self) -> Result<SearchResult, RepoError> {
// Plugin channels are inherently online-only.
Err(RepoError::Offline)
}
async fn open_live_stream(&self, _item_id: &str) -> Result<LiveStreamInfo, RepoError> {
// Live streams cannot be opened offline.
Err(RepoError::Offline)
}
async fn report_playback_start(&self, _item_id: &str, _position_ticks: i64) -> Result<(), RepoError> { async fn report_playback_start(&self, _item_id: &str, _position_ticks: i64) -> Result<(), RepoError> {
// Cannot report to server while offline // Cannot report to server while offline
Err(RepoError::Offline) Err(RepoError::Offline)
@@ -1055,6 +1091,7 @@ impl MediaRepository for OfflineRepository {
id: person_data.0, id: person_data.0,
name: person_data.1, name: person_data.1,
item_type: "Person".to_string(), item_type: "Person".to_string(),
is_folder: false,
server_id: self.server_id.clone(), server_id: self.server_id.clone(),
parent_id: None, parent_id: None,
library_id: None, library_id: None,
@@ -1115,7 +1152,7 @@ impl MediaRepository for OfflineRepository {
i.community_rating, i.official_rating, i.primary_image_tag, i.community_rating, i.official_rating, i.primary_image_tag,
i.album_id, i.album_name, i.album_artist, i.artists, i.album_id, i.album_name, i.album_artist, i.artists,
i.index_number, i.series_id, i.series_name, i.season_id, i.index_number, i.series_id, i.series_name, i.season_id,
i.season_name, i.parent_index_number i.season_name, i.parent_index_number, i.is_folder
FROM items i FROM items i
JOIN item_people ip ON i.id = ip.item_id JOIN item_people ip ON i.id = ip.item_id
INNER JOIN downloaded_items di ON i.id = di.id INNER JOIN downloaded_items di ON i.id = di.id
@@ -1226,7 +1263,7 @@ impl MediaRepository for OfflineRepository {
i.runtime_ticks, i.production_year, i.community_rating, i.official_rating, \ i.runtime_ticks, i.production_year, i.community_rating, i.official_rating, \
i.primary_image_tag, i.album_id, i.album_name, i.album_artist, i.artists, \ i.primary_image_tag, i.album_id, i.album_name, i.album_artist, i.artists, \
i.index_number, i.series_id, i.series_name, i.season_id, i.season_name, \ i.index_number, i.series_id, i.series_name, i.season_id, i.season_name, \
i.parent_index_number \ i.parent_index_number, i.is_folder \
FROM playlist_items pi \ FROM playlist_items pi \
JOIN items i ON pi.item_id = i.id \ JOIN items i ON pi.item_id = i.id \
WHERE pi.playlist_id = ? \ WHERE pi.playlist_id = ? \
@@ -1264,6 +1301,7 @@ impl MediaRepository for OfflineRepository {
season_id: row.get(21)?, season_id: row.get(21)?,
season_name: row.get(22)?, season_name: row.get(22)?,
parent_index_number: row.get(23)?, parent_index_number: row.get(23)?,
is_folder: row.get::<_, Option<i64>>(24)?.unwrap_or(0) != 0,
}; };
Ok((entry_id.to_string(), cached)) Ok((entry_id.to_string(), cached))
}) })
@@ -1430,6 +1468,7 @@ mod tests {
parent_id TEXT REFERENCES items(id) ON DELETE CASCADE, parent_id TEXT REFERENCES items(id) ON DELETE CASCADE,
name TEXT NOT NULL, name TEXT NOT NULL,
item_type TEXT NOT NULL, item_type TEXT NOT NULL,
is_folder INTEGER DEFAULT 0,
overview TEXT, overview TEXT,
genres TEXT, genres TEXT,
runtime_ticks INTEGER, runtime_ticks INTEGER,
@@ -1502,6 +1541,7 @@ mod tests {
id: id.to_string(), id: id.to_string(),
name: name.to_string(), name: name.to_string(),
item_type: "Audio".to_string(), item_type: "Audio".to_string(),
is_folder: false,
server_id: "test-server".to_string(), server_id: "test-server".to_string(),
parent_id: parent_id.map(|s| s.to_string()), parent_id: parent_id.map(|s| s.to_string()),
library_id: None, library_id: None,
+142 -7
View File
@@ -363,6 +363,8 @@ struct JellyfinItem {
name: String, name: String,
#[serde(rename = "Type")] #[serde(rename = "Type")]
item_type: String, item_type: String,
#[serde(default)]
is_folder: bool,
parent_id: Option<String>, parent_id: Option<String>,
overview: Option<String>, overview: Option<String>,
genres: Option<Vec<String>>, genres: Option<Vec<String>>,
@@ -450,6 +452,7 @@ impl JellyfinItem {
id: self.id, id: self.id,
name: self.name, name: self.name,
item_type: self.item_type, item_type: self.item_type,
is_folder: self.is_folder,
server_id, server_id,
parent_id: self.parent_id, parent_id: self.parent_id,
library_id: None, // Not provided by Jellyfin API directly library_id: None, // Not provided by Jellyfin API directly
@@ -580,8 +583,10 @@ impl MediaRepository for OnlineRepository {
} }
} }
// Request image fields for list views (People only needed in get_item detail view) // Request image fields for list views (People only needed in get_item
endpoint.push_str("&Fields=BackdropImageTags,ParentBackdropImageTags"); // detail view). Genres is needed so cached items carry their genres,
// which lets the offline store derive genre lists + per-genre counts.
endpoint.push_str("&Fields=BackdropImageTags,ParentBackdropImageTags,Genres");
let response: ItemsResponse = self.get_json(&endpoint).await?; let response: ItemsResponse = self.get_json(&endpoint).await?;
@@ -726,6 +731,7 @@ impl MediaRepository for OnlineRepository {
id: album_id, id: album_id,
name: first_track.album_name.clone().unwrap_or_else(|| "Unknown Album".to_string()), name: first_track.album_name.clone().unwrap_or_else(|| "Unknown Album".to_string()),
item_type: "MusicAlbum".to_string(), item_type: "MusicAlbum".to_string(),
is_folder: true,
server_id: first_track.server_id.clone(), server_id: first_track.server_id.clone(),
parent_id: None, parent_id: None,
library_id: None, library_id: None,
@@ -811,7 +817,12 @@ impl MediaRepository for OnlineRepository {
} }
async fn get_genres(&self, parent_id: Option<&str>) -> Result<Vec<Genre>, RepoError> { async fn get_genres(&self, parent_id: Option<&str>) -> Result<Vec<Genre>, RepoError> {
let mut endpoint = format!("/Genres?UserId={}", self.user_id); // Ask Jellyfin to scope counts to albums and include them, so the
// frontend can rank genres by popularity without probing each one.
let mut endpoint = format!(
"/Genres?UserId={}&IncludeItemTypes=MusicAlbum&Recursive=true&Fields=ItemCounts",
self.user_id
);
if let Some(pid) = parent_id { if let Some(pid) = parent_id {
endpoint.push_str(&format!("&ParentId={}", pid)); endpoint.push_str(&format!("&ParentId={}", pid));
@@ -828,17 +839,41 @@ impl MediaRepository for OnlineRepository {
struct JellyfinGenre { struct JellyfinGenre {
id: String, id: String,
name: String, name: String,
// Which count field Jellyfin populates for a genre under
// Fields=ItemCounts varies by server/version: scoped queries may
// fill AlbumCount, others only ChildCount. Read whichever is
// present so ranking still works. Absent on servers that ignore
// Fields=ItemCounts entirely, so all stay optional.
album_count: Option<u32>,
child_count: Option<u32>,
} }
let response: GenresResponse = self.get_json(&endpoint).await?; let response: GenresResponse = self.get_json(&endpoint).await?;
Ok(response let genres: Vec<Genre> = response
.items .items
.into_iter() .into_iter()
.map(|g| Genre { .map(|g| Genre {
id: g.id, id: g.id,
name: g.name, name: g.name,
album_count: g.album_count.or(g.child_count),
}) })
.collect()) .collect();
let with_counts = genres.iter().filter(|g| g.album_count.is_some()).count();
// TEMP DIAGNOSTIC: dump the first few genres with their counts so we can
// see whether the server populates any count field. Remove once known.
log::warn!(
"get_genres: {} genres, {} carry counts. sample: {:?}",
genres.len(),
with_counts,
genres
.iter()
.take(8)
.map(|g| (g.name.as_str(), g.album_count))
.collect::<Vec<_>>()
);
Ok(genres)
} }
async fn search( async fn search(
@@ -868,8 +903,9 @@ impl MediaRepository for OnlineRepository {
} }
} }
// Request image fields for list views (People only needed in get_item detail view) // Request image fields for list views (plus Genres so cached items
endpoint.push_str("&Fields=BackdropImageTags,ParentBackdropImageTags"); // carry genres for offline genre lists/counts).
endpoint.push_str("&Fields=BackdropImageTags,ParentBackdropImageTags,Genres");
let response: ItemsResponse = self.get_json(&endpoint).await?; let response: ItemsResponse = self.get_json(&endpoint).await?;
Ok(SearchResult { Ok(SearchResult {
@@ -1107,6 +1143,105 @@ impl MediaRepository for OnlineRepository {
Ok(url) Ok(url)
} }
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError> {
// Live TV channels (broadcast tuners / IPTV M3U). Returned as items with
// type "TvChannel" — playable via open_live_stream.
let endpoint = format!(
"/LiveTv/Channels?UserId={}&Fields=PrimaryImageAspectRatio,Overview&EnableImageTypes=Primary",
self.user_id
);
let response: ItemsResponse = self.get_json(&endpoint).await?;
Ok(response
.items
.into_iter()
.map(|item| item.to_media_item(self.server_url.clone()))
.collect())
}
async fn get_channels(&self) -> Result<SearchResult, RepoError> {
// Root list of plugin "Channels". Drill-down into a channel folder reuses
// get_items(channel_id, ...).
let endpoint = format!("/Channels?UserId={}", self.user_id);
let response: ItemsResponse = self.get_json(&endpoint).await?;
let total = response.total_record_count;
let items = response
.items
.into_iter()
.map(|item| item.to_media_item(self.server_url.clone()))
.collect();
Ok(SearchResult {
items,
total_record_count: total,
})
}
async fn open_live_stream(&self, item_id: &str) -> Result<LiveStreamInfo, RepoError> {
// Live channels require a PlaybackInfo call with AutoOpenLiveStream so the
// server opens the live stream and returns a ready-to-play transcoding URL.
// We send a minimal request; the server applies its own defaults for live.
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
struct OpenLiveStreamRequest {
user_id: String,
#[serde(rename = "AutoOpenLiveStream")]
auto_open_live_stream: bool,
is_playback: bool,
max_streaming_bitrate: u64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct OpenLiveStreamResponse {
#[serde(default)]
media_sources: Vec<LiveMediaSource>,
play_session_id: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct LiveMediaSource {
id: String,
transcoding_url: Option<String>,
live_stream_id: Option<String>,
}
let endpoint = format!("/Items/{}/PlaybackInfo", item_id);
let request = OpenLiveStreamRequest {
user_id: self.user_id.clone(),
auto_open_live_stream: true,
is_playback: true,
max_streaming_bitrate: 20_000_000,
};
let response: OpenLiveStreamResponse =
self.post_json_response(&endpoint, &request).await?;
let source = response.media_sources.into_iter().next().ok_or(RepoError::NotFound {
message: "No live media source returned".to_string(),
})?;
// The transcoding URL is server-relative; make it absolute. If the server
// did not provide one (rare for live), fall back to the HLS master endpoint.
let stream_url = match source.transcoding_url {
Some(url) => format!("{}{}", self.server_url, url),
None => format!(
"{}/Videos/{}/master.m3u8?api_key={}&MediaSourceId={}&LiveStreamId={}&VideoCodec=h264&AudioCodec=aac&TranscodingProtocol=hls&TranscodingContainer=ts",
self.server_url,
item_id,
self.access_token,
source.id,
source.live_stream_id.clone().unwrap_or_default(),
),
};
Ok(LiveStreamInfo {
stream_url,
play_session_id: response.play_session_id,
live_stream_id: source.live_stream_id,
media_source_id: Some(source.id),
})
}
async fn report_playback_start( async fn report_playback_start(
&self, &self,
item_id: &str, item_id: &str,
+25
View File
@@ -104,6 +104,10 @@ pub struct MediaItem {
pub name: String, pub name: String,
#[serde(rename = "type")] #[serde(rename = "type")]
pub item_type: String, pub item_type: String,
/// Whether this item is a folder/container (vs a playable leaf). Used to
/// decide whether a channel item drills into a list or plays directly.
#[serde(default)]
pub is_folder: bool,
pub server_id: String, pub server_id: String,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub parent_id: Option<String>, pub parent_id: Option<String>,
@@ -249,12 +253,30 @@ pub struct PlaybackInfo {
pub needs_transcoding: bool, pub needs_transcoding: bool,
} }
/// Live stream information returned from opening a Live TV / channel stream.
///
/// Unlike on-demand video, a live channel must be "opened" before it can be
/// streamed; the server returns a transcoding URL (already absolute) plus a
/// `live_stream_id` that can later be used to close the stream.
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LiveStreamInfo {
pub stream_url: String,
pub play_session_id: Option<String>,
pub live_stream_id: Option<String>,
pub media_source_id: Option<String>,
}
/// Genre /// Genre
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)] #[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct Genre { pub struct Genre {
pub id: String, pub id: String,
pub name: String, pub name: String,
/// Number of albums tagged with this genre, when the backend can supply it
/// (online only). Lets the frontend rank/pick genres without probing each
/// one. `None` when unknown (e.g. offline).
pub album_count: Option<u32>,
} }
/// Image type /// Image type
@@ -477,6 +499,7 @@ mod tests {
id: "1".to_string(), id: "1".to_string(),
name: "Test".to_string(), name: "Test".to_string(),
item_type: "Audio".to_string(), item_type: "Audio".to_string(),
is_folder: false,
server_id: "server1".to_string(), server_id: "server1".to_string(),
parent_id: None, parent_id: None,
library_id: None, library_id: None,
@@ -616,6 +639,7 @@ mod tests {
id: "track1".to_string(), id: "track1".to_string(),
name: "Test Track".to_string(), name: "Test Track".to_string(),
item_type: "Audio".to_string(), item_type: "Audio".to_string(),
is_folder: false,
server_id: "server1".to_string(), server_id: "server1".to_string(),
parent_id: None, parent_id: None,
library_id: None, library_id: None,
@@ -675,6 +699,7 @@ mod tests {
id: "1".to_string(), id: "1".to_string(),
name: "Track".to_string(), name: "Track".to_string(),
item_type: "Audio".to_string(), item_type: "Audio".to_string(),
is_folder: false,
server_id: "s1".to_string(), server_id: "s1".to_string(),
parent_id: None, parent_id: None,
library_id: None, library_id: None,
+13
View File
@@ -22,6 +22,7 @@ pub const MIGRATIONS: &[(&str, &str)] = &[
("015_device_id", MIGRATION_015), ("015_device_id", MIGRATION_015),
("016_autoplay_max_episodes", MIGRATION_016), ("016_autoplay_max_episodes", MIGRATION_016),
("017_downloads_resume_url", MIGRATION_017), ("017_downloads_resume_url", MIGRATION_017),
("018_items_is_folder", MIGRATION_018),
]; ];
/// Initial schema migration /// Initial schema migration
@@ -680,3 +681,15 @@ const MIGRATION_017: &str = r#"
ALTER TABLE downloads ADD COLUMN stream_url TEXT; ALTER TABLE downloads ADD COLUMN stream_url TEXT;
ALTER TABLE downloads ADD COLUMN target_dir TEXT; ALTER TABLE downloads ADD COLUMN target_dir TEXT;
"#; "#;
/// Migration to record whether a cached item is a folder/container vs a playable
/// leaf. Needed so channel items (which can be either) route to the player or to
/// a browse list correctly. Existing cached rows predate the column and have an
/// unknown folder flag, so we force a refresh by clearing their `synced_at`,
/// causing the hybrid repository to re-fetch them from the server on next browse.
const MIGRATION_018: &str = r#"
ALTER TABLE items ADD COLUMN is_folder INTEGER DEFAULT 0;
-- Force re-fetch of all cached items so is_folder is populated from the server.
UPDATE items SET synced_at = NULL;
"#;
+162 -6
View File
@@ -270,6 +270,31 @@ async remoteSessionSetVolume(sessionId: string, volume: number) : Promise<null>
async remoteSessionToggleMute(sessionId: string) : Promise<null> { async remoteSessionToggleMute(sessionId: string) : Promise<null> {
return await TAURI_INVOKE("remote_session_toggle_mute", { sessionId }); return await TAURI_INVOKE("remote_session_toggle_mute", { sessionId });
}, },
/**
* List current LMS sync groups.
*/
async lmsGetSyncGroups() : Promise<LmsSyncGroup[]> {
return await TAURI_INVOKE("lms_get_sync_groups");
},
/**
* Fuse LMS zones into a sync group. `master_mac` keeps playing and the
* `slave_macs` zones join it in sync.
*/
async lmsCreateSyncGroup(masterMac: string, slaveMacs: string[]) : Promise<null> {
return await TAURI_INVOKE("lms_create_sync_group", { masterMac, slaveMacs });
},
/**
* Remove a single LMS zone from its sync group (decouple one player).
*/
async lmsUnsyncPlayer(mac: string) : Promise<null> {
return await TAURI_INVOKE("lms_unsync_player", { mac });
},
/**
* Dissolve an entire LMS sync group, identified by its master's MAC.
*/
async lmsDissolveSyncGroup(masterMac: string) : Promise<null> {
return await TAURI_INVOKE("lms_dissolve_sync_group", { masterMac });
},
/** /**
* Set polling frequency hint based on UI state * Set polling frequency hint based on UI state
*/ */
@@ -303,8 +328,8 @@ async playbackModeIsTransferring() : Promise<boolean> {
/** /**
* Transfer playback from local device to a remote Jellyfin session * Transfer playback from local device to a remote Jellyfin session
*/ */
async playbackModeTransferToRemote(sessionId: string) : Promise<null> { async playbackModeTransferToRemote(sessionId: string, position: number | null) : Promise<null> {
return await TAURI_INVOKE("playback_mode_transfer_to_remote", { sessionId }); return await TAURI_INVOKE("playback_mode_transfer_to_remote", { sessionId, position });
}, },
/** /**
* Get remote session status (for polling position/duration) * Get remote session status (for polling position/duration)
@@ -322,6 +347,17 @@ async playbackModeGetRemoteStatus() : Promise<RemoteSessionStatus> {
async playbackModeTransferToLocal(currentItemId: string, positionTicks: number) : Promise<null> { async playbackModeTransferToLocal(currentItemId: string, positionTicks: number) : Promise<null> {
return await TAURI_INVOKE("playback_mode_transfer_to_local", { currentItemId, positionTicks }); return await TAURI_INVOKE("playback_mode_transfer_to_local", { currentItemId, positionTicks });
}, },
/**
* Set the transferring flag on the playback mode manager.
*
* Used by the frontend remote->local flow to mark the whole two-step sequence
* as a transfer, so `player_play_tracks` starts LOCAL playback instead of
* casting back to the remote session it's leaving. Always pair `true` with a
* later `false` (including on error) so the flag can't stick.
*/
async playbackModeSetTransferring(transferring: boolean) : Promise<null> {
return await TAURI_INVOKE("playback_mode_set_transferring", { transferring });
},
/** /**
* Initialize playback reporter (called after login) * Initialize playback reporter (called after login)
*/ */
@@ -1098,6 +1134,24 @@ async repositoryGetVideoStreamUrl(handle: string, itemId: string, mediaSourceId:
async repositoryGetAudioStreamUrl(handle: string, itemId: string) : Promise<string> { async repositoryGetAudioStreamUrl(handle: string, itemId: string) : Promise<string> {
return await TAURI_INVOKE("repository_get_audio_stream_url", { handle, itemId }); return await TAURI_INVOKE("repository_get_audio_stream_url", { handle, itemId });
}, },
/**
* Get Live TV channels (broadcast / IPTV) for browsing
*/
async repositoryGetLiveTvChannels(handle: string) : Promise<MediaItem[]> {
return await TAURI_INVOKE("repository_get_live_tv_channels", { handle });
},
/**
* Get the root list of plugin "Channels"
*/
async repositoryGetChannels(handle: string) : Promise<SearchResult> {
return await TAURI_INVOKE("repository_get_channels", { handle });
},
/**
* Open a live stream for a Live TV channel / live item
*/
async repositoryOpenLiveStream(handle: string, itemId: string) : Promise<LiveStreamInfo> {
return await TAURI_INVOKE("repository_open_live_stream", { handle, itemId });
},
/** /**
* Report playback start * Report playback start
*/ */
@@ -1276,6 +1330,11 @@ async convertPercentToVolume(percent: number) : Promise<number> {
/** user-defined events **/ /** user-defined events **/
export const events = __makeEvents__<{
playerStatusEvent: PlayerStatusEvent
}>({
playerStatusEvent: "player-status-event"
})
/** user-defined constants **/ /** user-defined constants **/
@@ -1471,7 +1530,13 @@ export type DownloadsResponse = { downloads: DownloadInfo[]; stats: DownloadStat
/** /**
* Genre * Genre
*/ */
export type Genre = { id: string; name: string } export type Genre = { id: string; name: string;
/**
* Number of albums tagged with this genre, when the backend can supply it
* (online only). Lets the frontend rank/pick genres without probing each
* one. `None` when unknown (e.g. offline).
*/
albumCount: number | null }
/** /**
* Request to get an image URL (with caching) * Request to get an image URL (with caching)
*/ */
@@ -1492,10 +1557,30 @@ export type ImageType = "Primary" | "Backdrop" | "Banner" | "Thumb" | "Logo"
* Library (media collection) * Library (media collection)
*/ */
export type Library = { id: string; name: string; collectionType: string; imageTag?: string | null } export type Library = { id: string; name: string; collectionType: string; imageTag?: string | null }
/**
* Live stream information returned from opening a Live TV / channel stream.
*
* Unlike on-demand video, a live channel must be "opened" before it can be
* streamed; the server returns a transcoding URL (already absolute) plus a
* `live_stream_id` that can later be used to close the stream.
*/
export type LiveStreamInfo = { streamUrl: string; playSessionId: string | null; liveStreamId: string | null; mediaSourceId: string | null }
/**
* An LMS multi-room sync group, as returned by JellyLMS `/JellyLms/SyncGroups`.
*
* Mirrors the plugin's `SyncGroup` model. The master is the sync source; slaves
* follow it in lockstep.
*/
export type LmsSyncGroup = { masterMac: string; masterName?: string; slaveMacs?: string[]; slaveNames?: string[] }
/** /**
* Media item * Media item
*/ */
export type MediaItem = { id: string; name: string; type: string; serverId: string; parentId?: string | null; libraryId?: string | null; overview?: string | null; genres?: string[] | null; productionYear?: number | null; communityRating?: number | null; officialRating?: string | null; runTimeTicks?: number | null; primaryImageTag?: string | null; backdropImageTags?: string[] | null; parentBackdropImageTags?: string[] | null; albumId?: string | null; albumName?: string | null; albumArtist?: string | null; artists?: string[] | null; artistItems?: ArtistItem[] | null; indexNumber?: number | null; parentIndexNumber?: number | null; seriesId?: string | null; seriesName?: string | null; seasonId?: string | null; seasonName?: string | null; userData?: UserData | null; mediaStreams?: MediaStream[] | null; mediaSources?: MediaSource[] | null; people?: Person[] | null } export type MediaItem = { id: string; name: string; type: string;
/**
* Whether this item is a folder/container (vs a playable leaf). Used to
* decide whether a channel item drills into a list or plays directly.
*/
isFolder?: boolean; serverId: string; parentId?: string | null; libraryId?: string | null; overview?: string | null; genres?: string[] | null; productionYear?: number | null; communityRating?: number | null; officialRating?: string | null; runTimeTicks?: number | null; primaryImageTag?: string | null; backdropImageTags?: string[] | null; parentBackdropImageTags?: string[] | null; albumId?: string | null; albumName?: string | null; albumArtist?: string | null; artists?: string[] | null; artistItems?: ArtistItem[] | null; indexNumber?: number | null; parentIndexNumber?: number | null; seriesId?: string | null; seriesName?: string | null; seasonId?: string | null; seasonName?: string | null; userData?: UserData | null; mediaStreams?: MediaStream[] | null; mediaSources?: MediaSource[] | null; people?: Person[] | null }
/** /**
* Media session type tracking the high-level playback context * Media session type tracking the high-level playback context
*/ */
@@ -1610,7 +1695,12 @@ export type PlayTracksContext = { type: "playlist"; playlistId: string; playlist
/** /**
* Request to play tracks by ID (backend fetches metadata) * Request to play tracks by ID (backend fetches metadata)
*/ */
export type PlayTracksRequest = { trackIds: string[]; startIndex: number; shuffle: boolean; context: PlayTracksContext } export type PlayTracksRequest = { trackIds: string[]; startIndex: number; shuffle: boolean; context: PlayTracksContext;
/**
* Position (seconds) to resume the starting track from. Used when taking
* over playback from a remote session so we don't restart from 0.
*/
startPosition?: number | null }
/** /**
* Playback information * Playback information
*/ */
@@ -1791,6 +1881,67 @@ mergedIsPlaying: boolean;
* Volume from either local player or remote session (0-1 normalized) * Volume from either local player or remote session (0-1 normalized)
*/ */
mergedVolume: number } mergedVolume: number }
/**
* Events emitted by the player backend to the frontend via Tauri events.
*
* These are distinct from `PlayerEvent` in state.rs, which handles internal
* state machine transitions.
*
* TRACES: UR-005, UR-019, UR-023, UR-026 | DR-001, DR-028, DR-047
*/
export type PlayerStatusEvent =
/**
* Playback position updated (emitted periodically during playback)
*/
{ type: "position_update"; position: number; duration: number } |
/**
* Player state changed
*/
{ type: "state_changed"; state: string; media_id: string | null } |
/**
* Media has finished loading and is ready to play
*/
{ type: "media_loaded"; duration: number } |
/**
* Playback has ended naturally (reached end of media)
*/
{ type: "playback_ended" } |
/**
* Buffering state changed
*/
{ type: "buffering"; percent: number } |
/**
* An error occurred during playback
*/
{ type: "error"; message: string; recoverable: boolean } |
/**
* Volume changed
*/
{ type: "volume_changed"; volume: number; muted: boolean } |
/**
* Sleep timer state changed
*/
{ type: "sleep_timer_changed"; mode: SleepTimerMode; remaining_seconds: number } |
/**
* Show next episode popup with countdown
*/
{ type: "show_next_episode_popup"; current_episode: MediaItem; next_episode: MediaItem; countdown_seconds: number; auto_advance: boolean } |
/**
* Countdown tick (emitted every second during autoplay countdown)
*/
{ type: "countdown_tick"; remaining_seconds: number } |
/**
* Queue changed (items added, removed, reordered, or playback mode changed)
*/
{ type: "queue_changed"; items: PlayerMediaItem[]; current_index: number | null; shuffle: boolean; repeat: RepeatMode; has_next: boolean; has_previous: boolean } |
/**
* Media session changed (activity context changed: Audio/Movie/TvShow/Idle)
*/
{ type: "session_changed"; session: MediaSessionType } |
/**
* Remote sessions updated (for cast/remote control UI)
*/
{ type: "sessions_updated"; sessions: SessionInfo[] }
/** /**
* Result of creating a playlist * Result of creating a playlist
* *
@@ -1807,7 +1958,12 @@ export type PlaylistEntry =
/** /**
* The underlying media item * The underlying media item
*/ */
({ id: string; name: string; type: string; serverId: string; parentId?: string | null; libraryId?: string | null; overview?: string | null; genres?: string[] | null; productionYear?: number | null; communityRating?: number | null; officialRating?: string | null; runTimeTicks?: number | null; primaryImageTag?: string | null; backdropImageTags?: string[] | null; parentBackdropImageTags?: string[] | null; albumId?: string | null; albumName?: string | null; albumArtist?: string | null; artists?: string[] | null; artistItems?: ArtistItem[] | null; indexNumber?: number | null; parentIndexNumber?: number | null; seriesId?: string | null; seriesName?: string | null; seasonId?: string | null; seasonName?: string | null; userData?: UserData | null; mediaStreams?: MediaStream[] | null; mediaSources?: MediaSource[] | null; people?: Person[] | null }) & { ({ id: string; name: string; type: string;
/**
* Whether this item is a folder/container (vs a playable leaf). Used to
* decide whether a channel item drills into a list or plays directly.
*/
isFolder?: boolean; serverId: string; parentId?: string | null; libraryId?: string | null; overview?: string | null; genres?: string[] | null; productionYear?: number | null; communityRating?: number | null; officialRating?: string | null; runTimeTicks?: number | null; primaryImageTag?: string | null; backdropImageTags?: string[] | null; parentBackdropImageTags?: string[] | null; albumId?: string | null; albumName?: string | null; albumArtist?: string | null; artists?: string[] | null; artistItems?: ArtistItem[] | null; indexNumber?: number | null; parentIndexNumber?: number | null; seriesId?: string | null; seriesName?: string | null; seasonId?: string | null; seasonName?: string | null; userData?: UserData | null; mediaStreams?: MediaStream[] | null; mediaSources?: MediaSource[] | null; people?: Person[] | null }) & {
/** /**
* The playlist-scoped entry ID (Jellyfin's PlaylistItemId) * The playlist-scoped entry ID (Jellyfin's PlaylistItemId)
*/ */
+18
View File
@@ -11,6 +11,7 @@ import type {
GetItemsOptions, GetItemsOptions,
SearchOptions, SearchOptions,
PlaybackInfo, PlaybackInfo,
LiveStreamInfo,
ImageType, ImageType,
ImageOptions, ImageOptions,
Genre, Genre,
@@ -161,6 +162,23 @@ export class RepositoryClient {
); );
} }
// ===== Live TV / Channels =====
/** Browse Live TV channels (broadcast / IPTV). */
async getLiveTvChannels(): Promise<MediaItem[]> {
return commands.repositoryGetLiveTvChannels(this.ensureHandle());
}
/** Browse the root list of plugin "Channels". Drill-down uses getItems(channelId). */
async getChannels(): Promise<SearchResult> {
return commands.repositoryGetChannels(this.ensureHandle());
}
/** Open a live stream for a Live TV channel / live item before HLS playback. */
async openLiveStream(itemId: string): Promise<LiveStreamInfo> {
return commands.repositoryOpenLiveStream(this.ensureHandle(), itemId);
}
// ===== URL Construction Methods (sync, no server call) ===== // ===== URL Construction Methods (sync, no server call) =====
/** /**
+4
View File
@@ -5,12 +5,14 @@
// and adds frontend-only unions/helpers that have no backend equivalent. // and adds frontend-only unions/helpers that have no backend equivalent.
export type { export type {
ArtistItem,
AuthResult, AuthResult,
Genre, Genre,
GetItemsOptions, GetItemsOptions,
ImageOptions, ImageOptions,
ImageType, ImageType,
Library, Library,
LiveStreamInfo,
MediaItem, MediaItem,
MediaSource, MediaSource,
MediaStream, MediaStream,
@@ -50,6 +52,7 @@ export type ItemType =
| "CollectionFolder" | "CollectionFolder"
| "Channel" | "Channel"
| "ChannelFolderItem" | "ChannelFolderItem"
| "TvChannel"
| "Person"; | "Person";
export type LibraryType = export type LibraryType =
@@ -62,6 +65,7 @@ export type LibraryType =
| "boxsets" | "boxsets"
| "playlists" | "playlists"
| "channels" | "channels"
| "livetv"
| "unknown"; | "unknown";
export type PersonType = export type PersonType =
@@ -26,17 +26,28 @@
let { availableLetters, onJump, bottomGap = "5rem" }: Props = $props(); let { availableLetters, onJump, bottomGap = "5rem" }: Props = $props();
// The strip stretches to fill the height of its scroll container (the page's // The strip stretches from where it sits down to just above the bottom nav /
// <main>, which sits below the sticky header) from the sticky top offset down // mini-player bars. Those bars are pinned to the bottom of the screen, so the
// to the bottom gap reserved for the nav / mini-player bars. We measure the // hard floor is `window.innerHeight - bottomGap`. We measure the strip's own
// container's visible height live so it stays correct regardless of header // top against that floor (clamped to non-negative) and update on scroll/resize
// size, platform, or window resizes. // so it never slides under the bars regardless of header or platform.
let container = $state<HTMLDivElement | null>(null); let container = $state<HTMLDivElement | null>(null);
let viewportHeight = $state(0); let stripHeight = $state(0);
function measure() { function measure() {
const scroller = container?.closest("main") ?? document.documentElement; if (!container) return;
viewportHeight = scroller.clientHeight; const top = container.getBoundingClientRect().top;
const floor = window.innerHeight - remToPx(bottomGap);
stripHeight = Math.max(0, floor - top);
}
function remToPx(len: string): number {
const n = parseFloat(len);
if (len.trim().endsWith("rem")) {
const root = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
return n * root;
}
return n; // assume px otherwise
} }
$effect(() => { $effect(() => {
@@ -44,13 +55,21 @@
const scroller = container?.closest("main"); const scroller = container?.closest("main");
const ro = new ResizeObserver(measure); const ro = new ResizeObserver(measure);
if (scroller) ro.observe(scroller); if (scroller) ro.observe(scroller);
scroller?.addEventListener("scroll", measure, { passive: true });
window.addEventListener("resize", measure); window.addEventListener("resize", measure);
return () => { return () => {
ro.disconnect(); ro.disconnect();
scroller?.removeEventListener("scroll", measure);
window.removeEventListener("resize", measure); window.removeEventListener("resize", measure);
}; };
}); });
// Recompute when the reserved bottom gap changes (mini-player shows/hides).
$effect(() => {
bottomGap;
measure();
});
const letters = $derived([HASH, ...ALPHABET]); const letters = $derived([HASH, ...ALPHABET]);
let activeLetter = $state<string | null>(null); let activeLetter = $state<string | null>(null);
@@ -99,7 +118,7 @@
<div <div
bind:this={container} bind:this={container}
class="flex flex-col items-center justify-between select-none touch-none py-1" class="flex flex-col items-center justify-between select-none touch-none py-1"
style="height: calc({viewportHeight}px - 1.5rem - {bottomGap})" style="height: {stripHeight}px"
onpointerdown={handlePointerDown} onpointerdown={handlePointerDown}
onpointermove={handlePointerMove} onpointermove={handlePointerMove}
role="navigation" role="navigation"
@@ -0,0 +1,54 @@
<script lang="ts">
import { goto } from "$app/navigation";
import type { ArtistItem } from "$lib/api/types";
/**
* Renders a comma-separated list of artist names. When the artists carry
* ids (artistItems) each name links to that artist's detail page; otherwise
* it falls back to plain text from the names-only `artists` array.
*
* Consolidates the artist-linking markup used on the player and detail
* screens so every surface behaves the same way.
*/
interface Props {
artistItems?: ArtistItem[] | null;
artists?: string[] | null;
/** Tailwind classes for the link colour/state. */
linkClass?: string;
/** Tailwind classes for the non-linkable fallback text. */
textClass?: string;
/** Called before navigating (e.g. to close a full-screen player). */
onNavigate?: () => void;
}
let {
artistItems = null,
artists = null,
linkClass = "text-[var(--color-jellyfin)] hover:underline",
textClass = "text-gray-400",
onNavigate,
}: Props = $props();
const linkable = $derived(
(artistItems ?? []).filter((a) => a.id && a.id.trim() !== "")
);
function handleClick(artistId: string, e: MouseEvent) {
e.preventDefault();
e.stopPropagation();
onNavigate?.();
goto(`/library/${artistId}`);
}
</script>
{#if linkable.length > 0}
<span class="inline-flex flex-wrap items-baseline gap-1">
{#each linkable as artist, i (artist.id)}
<button onclick={(e) => handleClick(artist.id, e)} class={linkClass}>
{artist.name}
</button>{#if i < linkable.length - 1}<span class={textClass}>,</span>{/if}
{/each}
</span>
{:else if artists && artists.length > 0}
<span class={textClass}>{artists.join(", ")}</span>
{/if}
@@ -0,0 +1,57 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/svelte";
import ArtistLinks from "./ArtistLinks.svelte";
const goto = vi.fn();
vi.mock("$app/navigation", () => ({
goto: (...args: unknown[]) => goto(...args),
}));
describe("ArtistLinks", () => {
beforeEach(() => goto.mockClear());
it("renders a clickable link per artist that navigates to its detail page", async () => {
render(ArtistLinks, {
artistItems: [
{ id: "a1", name: "Radiohead" },
{ id: "a2", name: "Thom Yorke" },
],
});
const link = screen.getByRole("button", { name: "Radiohead" });
await fireEvent.click(link);
expect(goto).toHaveBeenCalledWith("/library/a1");
expect(screen.getByRole("button", { name: "Thom Yorke" })).toBeTruthy();
});
it("falls back to plain text when only names (no ids) are available", () => {
render(ArtistLinks, { artists: ["Unknown Artist"] });
expect(screen.queryByRole("button")).toBeNull();
expect(screen.getByText("Unknown Artist")).toBeTruthy();
});
it("ignores artistItems with blank ids and uses the names fallback", () => {
render(ArtistLinks, {
artistItems: [{ id: " ", name: "No Id Artist" }],
artists: ["No Id Artist"],
});
expect(screen.queryByRole("button")).toBeNull();
expect(screen.getByText("No Id Artist")).toBeTruthy();
});
it("calls onNavigate before navigating (e.g. to close a player)", async () => {
const onNavigate = vi.fn();
render(ArtistLinks, {
artistItems: [{ id: "a1", name: "Radiohead" }],
onNavigate,
});
await fireEvent.click(screen.getByRole("button", { name: "Radiohead" }));
expect(onNavigate).toHaveBeenCalledOnce();
expect(goto).toHaveBeenCalledWith("/library/a1");
});
});
@@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte"; import { onMount } from "svelte";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { navigateBack } from "$lib/utils/navigation";
import { currentLibrary } from "$lib/stores/library"; import { currentLibrary } from "$lib/stores/library";
import { auth } from "$lib/stores/auth"; import { auth } from "$lib/stores/auth";
import SearchBar from "$lib/components/common/SearchBar.svelte"; import SearchBar from "$lib/components/common/SearchBar.svelte";
@@ -125,7 +126,7 @@
selectedGenre = null; selectedGenre = null;
genreItems = []; genreItems = [];
} else { } else {
goto(config.backPath); navigateBack(config.backPath);
} }
} }
@@ -2,6 +2,7 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte"; import { onMount } from "svelte";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { navigateBack } from "$lib/utils/navigation";
import { currentLibrary } from "$lib/stores/library"; import { currentLibrary } from "$lib/stores/library";
import { auth } from "$lib/stores/auth"; import { auth } from "$lib/stores/auth";
import { shouldShowAudioMiniPlayer } from "$lib/stores/player"; import { shouldShowAudioMiniPlayer } from "$lib/stores/player";
@@ -130,7 +131,7 @@
} }
function goBack() { function goBack() {
goto(config.backPath); navigateBack(config.backPath);
} }
const searchPlaceholder = $derived(config.searchPlaceholder || `Search ${config.title.toLowerCase()}...`); const searchPlaceholder = $derived(config.searchPlaceholder || `Search ${config.title.toLowerCase()}...`);
@@ -28,6 +28,7 @@ vi.mock("$lib/stores/queue", () => ({
setQueue: vi.fn(), setQueue: vi.fn(),
addToQueue: vi.fn(), addToQueue: vi.fn(),
}, },
currentQueueItem: { subscribe: vi.fn((fn: any) => { fn(null); return () => {}; }) },
})); }));
vi.mock("./DownloadButton.svelte", () => ({ vi.mock("./DownloadButton.svelte", () => ({
+61 -39
View File
@@ -30,9 +30,10 @@
onEnded?: () => void; // Called when video playback ends naturally onEnded?: () => void; // Called when video playback ends naturally
onNext?: () => void; // Called when user clicks next episode button onNext?: () => void; // Called when user clicks next episode button
hasNext?: boolean; // Whether there is a next episode available hasNext?: boolean; // Whether there is a next episode available
isLive?: boolean; // Live stream (Live TV) - no seek bar, no resume, no progress reporting
} }
let { media, streamUrl, mediaSourceId, initialPosition, needsTranscoding = false, onClose, onSeek, onReportProgress, onReportStart, onReportStop, onEnded, onNext, hasNext = false }: Props = $props(); let { media, streamUrl, mediaSourceId, initialPosition, needsTranscoding = false, onClose, onSeek, onReportProgress, onReportStart, onReportStop, onEnded, onNext, hasNext = false, isLive = false }: Props = $props();
// The id this player instance reports progress against. Snapshotted from the // The id this player instance reports progress against. Snapshotted from the
// media prop so a late reportStop (e.g. from onDestroy during autoplay // media prop so a late reportStop (e.g. from onDestroy during autoplay
@@ -43,6 +44,18 @@
let videoElement: HTMLVideoElement | null = $state(null); let videoElement: HTMLVideoElement | null = $state(null);
let isPlaying = $state(false); let isPlaying = $state(false);
let currentTime = $state(0); let currentTime = $state(0);
// Guards against onEnded() firing more than once per loaded stream. For
// transcoded HLS, both the native `ended` event and the "fatal network error
// near end of stream" recovery path can fire for the same playback, which
// would otherwise call playerOnPlaybackEnded twice (e.g. decrementing the
// sleep-timer episode counter twice). Reset when the stream URL changes.
let endedFired = $state(false);
function notifyEnded() {
if (endedFired) return;
endedFired = true;
onEnded?.();
}
let isFullscreen = $state(false); let isFullscreen = $state(false);
let showControls = $state(true); let showControls = $state(true);
let showSleepTimerModal = $state(false); let showSleepTimerModal = $state(false);
@@ -188,6 +201,7 @@
seekOffset = 0; seekOffset = 0;
isMediaReady = false; // Reset to loading state when stream URL changes isMediaReady = false; // Reset to loading state when stream URL changes
hasPerformedInitialSeek = false; // Reset so new video can seek to initial position hasPerformedInitialSeek = false; // Reset so new video can seek to initial position
endedFired = false; // New stream loaded - allow onEnded to fire again
} }
}); });
@@ -285,9 +299,7 @@
if (isNearEnd) { if (isNearEnd) {
// Near end of stream - treat as natural end, don't restart // Near end of stream - treat as natural end, don't restart
console.log('[VideoPlayer] Fatal network error near end of stream - treating as ended'); console.log('[VideoPlayer] Fatal network error near end of stream - treating as ended');
if (onEnded) { notifyEnded();
onEnded();
}
} else if (hlsFatalRecoveryAttempts <= 3) { } else if (hlsFatalRecoveryAttempts <= 3) {
console.error('[VideoPlayer] Fatal network error, trying to recover (attempt', hlsFatalRecoveryAttempts, ')'); console.error('[VideoPlayer] Fatal network error, trying to recover (attempt', hlsFatalRecoveryAttempts, ')');
hls!.startLoad(); hls!.startLoad();
@@ -477,12 +489,15 @@
// Load series audio preference (for TV shows) // Load series audio preference (for TV shows)
await loadSeriesAudioPreference(); await loadSeriesAudioPreference();
// Report progress every 10 seconds while playing // Report progress every 10 seconds while playing. Live streams have no
progressInterval = setInterval(() => { // meaningful position to report, so skip progress reporting entirely.
if (isPlaying && !isSeeking && onReportProgress) { if (!isLive) {
onReportProgress(currentTime, false, reportMediaId); progressInterval = setInterval(() => {
} if (isPlaying && !isSeeking && onReportProgress) {
}, 10000); onReportProgress(currentTime, false, reportMediaId);
}
}, 10000);
}
// Debug logging every second // Debug logging every second
debugLogInterval = setInterval(() => { debugLogInterval = setInterval(() => {
@@ -544,8 +559,8 @@
} }
} }
// Report stop when component is destroyed // Report stop when component is destroyed (skip for live - no resume tracking)
if (onReportStop && currentTime > 0) { if (!isLive && onReportStop && currentTime > 0) {
onReportStop(currentTime, reportMediaId); onReportStop(currentTime, reportMediaId);
} }
}); });
@@ -738,8 +753,8 @@
function handlePlay() { function handlePlay() {
isPlaying = true; isPlaying = true;
startTimeUpdates(); // Start RAF loop for smooth time updates startTimeUpdates(); // Start RAF loop for smooth time updates
// Report playback start on first play // Report playback start on first play (skip for live - no resume tracking)
if (!hasReportedStart && onReportStart) { if (!isLive && !hasReportedStart && onReportStart) {
onReportStart(currentTime, reportMediaId); onReportStart(currentTime, reportMediaId);
hasReportedStart = true; hasReportedStart = true;
} }
@@ -757,14 +772,12 @@
function handleEnded() { function handleEnded() {
isPlaying = false; isPlaying = false;
stopTimeUpdates(); // Stop RAF loop when ended stopTimeUpdates(); // Stop RAF loop when ended
// Report stop when video ends // Report stop when video ends (skip for live - no resume tracking)
if (onReportStop) { if (!isLive && onReportStop) {
onReportStop(currentTime, reportMediaId); onReportStop(currentTime, reportMediaId);
} }
// Notify parent that video has ended (for next episode popup) // Notify parent that video has ended (for next episode popup)
if (onEnded) { notifyEnded();
onEnded();
}
} }
async function togglePlayPause() { async function togglePlayPause() {
@@ -1404,26 +1417,35 @@
<h2 class="text-white text-lg font-semibold">{media?.name || "Video"}</h2> <h2 class="text-white text-lg font-semibold">{media?.name || "Video"}</h2>
</div> </div>
<!-- Progress bar --> <!-- Progress bar (hidden for live streams - no fixed timeline) -->
<div class="flex items-center gap-2 mb-2"> {#if isLive}
<span class="text-white text-sm w-12">{formatTime(currentTime)}</span> <div class="flex items-center gap-2 mb-2">
<input <span class="flex items-center gap-1.5 text-white text-sm font-semibold">
type="range" <span class="inline-block w-2 h-2 rounded-full bg-red-500"></span>
min="0" LIVE
max={duration || 100} </span>
value={currentTime} </div>
oninput={handleSeekBarInput} {:else}
onchange={handleSeekBarChange} <div class="flex items-center gap-2 mb-2">
onmousedown={() => isDraggingSeekBar = true} <span class="text-white text-sm w-12">{formatTime(currentTime)}</span>
onmouseup={() => isDraggingSeekBar = false} <input
ontouchstart={() => isDraggingSeekBar = true} type="range"
ontouchend={() => isDraggingSeekBar = false} min="0"
class="flex-1 h-1 bg-white/30 rounded-full appearance-none cursor-pointer max={duration || 100}
[&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 value={currentTime}
[&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full" oninput={handleSeekBarInput}
/> onchange={handleSeekBarChange}
<span class="text-white text-sm w-12 text-right">{formatTime(duration)}</span> onmousedown={() => isDraggingSeekBar = true}
</div> onmouseup={() => isDraggingSeekBar = false}
ontouchstart={() => isDraggingSeekBar = true}
ontouchend={() => isDraggingSeekBar = false}
class="flex-1 h-1 bg-white/30 rounded-full appearance-none cursor-pointer
[&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
[&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full"
/>
<span class="text-white text-sm w-12 text-right">{formatTime(duration)}</span>
</div>
{/if}
<!-- Control buttons --> <!-- Control buttons -->
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
@@ -1,7 +1,10 @@
<!-- TRACES: UR-010 | JA-021, JA-025 | DR-037 --> <!-- TRACES: UR-010 | JA-021, JA-025 | DR-037 -->
<script lang="ts"> <script lang="ts">
import { get } from "svelte/store";
import { sessions, controllableSessions, selectedSession } from "$lib/stores"; import { sessions, controllableSessions, selectedSession } from "$lib/stores";
import { playbackMode, isTransferring, transferError } from "$lib/stores/playbackMode"; import { playbackMode, isTransferring, transferError } from "$lib/stores/playbackMode";
import { playbackPosition } from "$lib/stores/player";
import { lmsSync, isLmsSession, macForSession } from "$lib/stores/lmsSync";
import type { Session } from "$lib/api/types"; import type { Session } from "$lib/api/types";
interface Props { interface Props {
@@ -12,10 +15,24 @@
let { isOpen = false, onClose, onSelectSession }: Props = $props(); let { isOpen = false, onClose, onSelectSession }: Props = $props();
// MACs currently part of any sync group, for rendering toggle state.
const groupedMacs = $derived(new Set(($lmsSync.groups ?? []).flatMap(
(g) => [g.masterMac, ...(g.slaveMacs ?? [])]
)));
// The sync master is the LMS zone we're currently controlling. Zones can only
// be fused once we have a master to fuse them into.
const masterMac = $derived(isLmsSession($selectedSession) ? macForSession($selectedSession) : null);
function isZoneFused(session: Session): boolean {
const mac = macForSession(session);
return mac !== null && groupedMacs.has(mac);
}
async function handleSessionSelect(session: Session) { async function handleSessionSelect(session: Session) {
try { try {
// Transfer playback to remote session // Transfer playback to remote session, resuming at our current position
await playbackMode.transferToRemote(session.id); await playbackMode.transferToRemote(session.id, get(playbackPosition));
if (onSelectSession) { if (onSelectSession) {
onSelectSession(session); onSelectSession(session);
@@ -29,6 +46,32 @@
} }
} }
// Toggle an LMS zone in/out of the current master's sync group. If there's no
// master yet (we're not controlling an LMS zone), the click falls back to a
// normal transfer so the user can start playing on a zone first.
async function handleLmsZoneToggle(session: Session) {
const zoneMac = macForSession(session);
if (!zoneMac) return;
if (!masterMac) {
// No master yet — start playback on this zone; it becomes the master.
await handleSessionSelect(session);
await lmsSync.refresh();
return;
}
try {
if (isZoneFused(session)) {
await lmsSync.decoupleZone(zoneMac);
} else {
await lmsSync.fuseZone(masterMac, zoneMac);
}
} catch (error) {
console.error("Failed to toggle LMS zone:", error);
// Error is surfaced via the lmsSync store
}
}
async function handleTransferToLocal() { async function handleTransferToLocal() {
try { try {
await playbackMode.transferToLocal(); await playbackMode.transferToLocal();
@@ -78,6 +121,7 @@
$effect(() => { $effect(() => {
if (isOpen) { if (isOpen) {
sessions.refresh(); sessions.refresh();
lmsSync.refresh();
} }
}); });
</script> </script>
@@ -165,14 +209,24 @@
<!-- Available sessions --> <!-- Available sessions -->
{#each $controllableSessions as session (session.id)} {#each $controllableSessions as session (session.id)}
{#if session.id !== $selectedSession?.id} {#if session.id !== $selectedSession?.id}
{@const lmsZone = isLmsSession(session)}
{@const fused = lmsZone && isZoneFused(session)}
<button <button
onclick={() => handleSessionSelect(session)} onclick={() => (lmsZone ? handleLmsZoneToggle(session) : handleSessionSelect(session))}
class="w-full p-4 rounded-lg border border-gray-800 hover:border-[var(--color-jellyfin)]/50 hover:bg-[var(--color-jellyfin)]/5 transition-all text-left" disabled={$lmsSync.isBusy}
aria-pressed={lmsZone ? fused : undefined}
class="w-full p-4 rounded-lg border transition-all text-left disabled:opacity-60
{fused
? 'border-[var(--color-jellyfin)] bg-[var(--color-jellyfin)]/10'
: 'border-gray-800 hover:border-[var(--color-jellyfin)]/50 hover:bg-[var(--color-jellyfin)]/5'}"
> >
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-lg bg-gray-800 flex items-center justify-center flex-shrink-0"> <div class="w-10 h-10 rounded-lg bg-gray-800 flex items-center justify-center flex-shrink-0">
<svg class="w-5 h-5 text-gray-400" fill="currentColor" viewBox="0 0 24 24"> <svg class="w-5 h-5 text-gray-400" fill="currentColor" viewBox="0 0 24 24">
{#if getSessionIcon(session.client) === "tv"} {#if lmsZone}
<!-- speaker icon for LMS zones -->
<path d="M12 2a1 1 0 011 1v18a1 1 0 01-1 1H6a2 2 0 01-2-2V4a2 2 0 012-2h6zm0 2H6v16h6V4zm-3 9a2 2 0 110 4 2 2 0 010-4zm0-2a4 4 0 100 8 4 4 0 000-8zm0-4a1 1 0 110 2 1 1 0 010-2zm9 0h2v2h-2V7zm0 4h2v2h-2v-2z" />
{:else if getSessionIcon(session.client) === "tv"}
<path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z" /> <path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z" />
{:else if getSessionIcon(session.client) === "web"} {:else if getSessionIcon(session.client) === "web"}
<path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 14H4v-4h11v4zm0-5H4V9h11v4zm5 5h-4V9h4v9z" /> <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 14H4v-4h11v4zm0-5H4V9h11v4zm5 5h-4V9h4v9z" />
@@ -185,14 +239,33 @@
</div> </div>
<div class="flex-1 min-w-0"> <div class="flex-1 min-w-0">
<h3 class="font-medium text-white truncate">{session.deviceName}</h3> <h3 class="font-medium text-white truncate">{session.deviceName}</h3>
<p class="text-sm text-gray-400 truncate">{session.client}</p> <p class="text-sm text-gray-400 truncate">
{#if lmsZone}
{fused ? "In sync group — tap to remove" : masterMac ? "Tap to add to group" : "Speaker zone"}
{:else}
{session.client}
{/if}
</p>
{#if session.nowPlayingItem} {#if session.nowPlayingItem}
<p class="text-xs text-gray-500 truncate mt-1"> <p class="text-xs text-gray-500 truncate mt-1">
Playing: {session.nowPlayingItem.name} Playing: {session.nowPlayingItem.name}
</p> </p>
{/if} {/if}
</div> </div>
{#if session.playState} {#if lmsZone}
<!-- Fuse toggle indicator -->
<div class="flex-shrink-0">
{#if fused}
<svg class="w-5 h-5 text-[var(--color-jellyfin)]" fill="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
</svg>
{:else}
<svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="9" stroke-width="2" />
</svg>
{/if}
</div>
{:else if session.playState}
<div class="flex-shrink-0"> <div class="flex-shrink-0">
{#if session.playState.isPaused} {#if session.playState.isPaused}
<svg class="w-4 h-4 text-gray-500" fill="currentColor" viewBox="0 0 24 24"> <svg class="w-4 h-4 text-gray-500" fill="currentColor" viewBox="0 0 24 24">
@@ -293,6 +366,27 @@
</div> </div>
{/if} {/if}
<!-- LMS sync error -->
{#if $lmsSync.error}
<div class="absolute bottom-0 left-0 right-0 bg-red-500/90 text-white px-6 py-3 flex items-center justify-between z-10 rounded-b-2xl">
<div class="flex items-center gap-2">
<svg class="w-5 h-5 flex-shrink-0" fill="currentColor" viewBox="0 0 24 24">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z" />
</svg>
<span class="text-sm">{$lmsSync.error}</span>
</div>
<button
onclick={() => lmsSync.clearError()}
class="text-white hover:text-gray-200 transition-colors"
aria-label="Dismiss error"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/if}
<!-- Error Display --> <!-- Error Display -->
{#if $transferError} {#if $transferError}
<div class="absolute bottom-0 left-0 right-0 bg-red-500/90 text-white px-6 py-3 flex items-center justify-between z-10 rounded-b-2xl"> <div class="absolute bottom-0 left-0 right-0 bg-red-500/90 text-white px-6 py-3 flex items-center justify-between z-10 rounded-b-2xl">
+22 -61
View File
@@ -8,9 +8,9 @@
* TRACES: UR-005, UR-019, UR-023, UR-026 | DR-001, DR-028, DR-047 * TRACES: UR-005, UR-019, UR-023, UR-026 | DR-001, DR-028, DR-047
*/ */
import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import { type UnlistenFn } from "@tauri-apps/api/event";
import { commands } from "$lib/api/bindings"; import { commands, events, type PlayerStatusEvent, type SleepTimerMode } from "$lib/api/bindings";
import { player, playbackPosition } from "$lib/stores/player"; import { player, playbackPosition, currentMedia } from "$lib/stores/player";
import { queue, currentQueueItem } from "$lib/stores/queue"; import { queue, currentQueueItem } from "$lib/stores/queue";
import { playbackMode } from "$lib/stores/playbackMode"; import { playbackMode } from "$lib/stores/playbackMode";
import { sleepTimer } from "$lib/stores/sleepTimer"; import { sleepTimer } from "$lib/stores/sleepTimer";
@@ -20,33 +20,9 @@ import { preloadUpcomingTracks } from "$lib/services/preload";
import type { MediaItem } from "$lib/api/types"; import type { MediaItem } from "$lib/api/types";
import { get } from "svelte/store"; import { get } from "svelte/store";
/** // PlayerStatusEvent and SleepTimerMode are generated by tauri-specta and
* Event types emitted by the player backend. // imported from $lib/api/bindings — they are the authoritative shapes emitted
* Must match PlayerStatusEvent in src-tauri/src/player/events.rs // by src-tauri/src/player/events.rs.
*
* TRACES: UR-005, UR-019, UR-023, UR-026 | DR-001, DR-028, DR-047
*/
export type PlayerStatusEvent =
| { type: "position_update"; position: number; duration: number }
| { type: "state_changed"; state: string; media_id: string | null }
| { type: "media_loaded"; duration: number }
| { type: "playback_ended" }
| { type: "buffering"; percent: number }
| { type: "error"; message: string; recoverable: boolean }
| { type: "volume_changed"; volume: number; muted: boolean }
| { type: "sleep_timer_changed"; mode: SleepTimerMode; remaining_seconds: number }
| { type: "show_next_episode_popup"; current_episode: MediaItem; next_episode: MediaItem; countdown_seconds: number; auto_advance: boolean }
| { type: "countdown_tick"; remaining_seconds: number };
// Sleep timer mode type
export type SleepTimerMode =
| { kind: "off" }
| { kind: "time"; endTime: number }
| { kind: "endOfTrack" }
| { kind: "episodes"; remaining: number };
/** Event name for player status events from backend */
const PLAYER_EVENT_NAME = "player-event";
let unlistenFn: UnlistenFn | null = null; let unlistenFn: UnlistenFn | null = null;
let isInitialized = false; let isInitialized = false;
@@ -62,12 +38,9 @@ export async function initPlayerEvents(): Promise<void> {
} }
try { try {
unlistenFn = await listen<PlayerStatusEvent>( unlistenFn = await events.playerStatusEvent.listen((event) => {
PLAYER_EVENT_NAME, handlePlayerEvent(event.payload);
(event) => { });
handlePlayerEvent(event.payload);
}
);
isInitialized = true; isInitialized = true;
console.log("Player event listener initialized"); console.log("Player event listener initialized");
} catch (e) { } catch (e) {
@@ -152,6 +125,10 @@ function handlePlayerEvent(event: PlayerStatusEvent): void {
case "countdown_tick": case "countdown_tick":
handleCountdownTick(event.remaining_seconds); handleCountdownTick(event.remaining_seconds);
break; break;
// queue_changed is handled by the queue store's own listener
// ($lib/stores/queue), which is the single source of truth for
// shuffle/repeat/next/previous. No action needed here.
} }
} }
@@ -186,9 +163,16 @@ async function handleStateChanged(state: string, _mediaId: string | null): Promi
} }
if (state === "playing" && currentItem) { if (state === "playing" && currentItem) {
// Use 0 for position/duration - will be updated by position_update events // Preserve the current position when the same track is already loaded
// (e.g. resuming from pause, or a spurious PlaybackRestart). Only reset
// to 0 when switching to a different track. position_update events keep
// it fresh either way, but resetting unconditionally caused the time to
// flash to 0:00 on pause/resume.
const previous = get(currentMedia);
const isSameTrack = previous?.id === currentItem.id;
const startPosition = isSameTrack ? get(playbackPosition) : 0;
const initialDuration = currentItem.runTimeTicks ? currentItem.runTimeTicks / 10000000 : 0; const initialDuration = currentItem.runTimeTicks ? currentItem.runTimeTicks / 10000000 : 0;
player.setPlaying(currentItem, 0, initialDuration); player.setPlaying(currentItem, startPosition, initialDuration);
// Trigger preloading of upcoming tracks in the background // Trigger preloading of upcoming tracks in the background
preloadUpcomingTracks().catch((e) => { preloadUpcomingTracks().catch((e) => {
@@ -204,8 +188,6 @@ async function handleStateChanged(state: string, _mediaId: string | null): Promi
player.setLoading(currentItem); player.setLoading(currentItem);
} }
// Update queue status on state change
await updateQueueStatus();
break; break;
case "idle": case "idle":
@@ -218,31 +200,10 @@ async function handleStateChanged(state: string, _mediaId: string | null): Promi
playbackMode.setMode("idle"); playbackMode.setMode("idle");
} }
// Update queue status on state change
await updateQueueStatus();
break; break;
} }
} }
/**
* Update queue status from backend.
* Called on state changes instead of polling.
*/
async function updateQueueStatus(): Promise<void> {
try {
const queueStatus = await commands.playerGetQueue();
// Import appState stores dynamically to avoid circular imports
const { hasNext, hasPrevious, shuffle, repeat } = await import("$lib/stores/appState");
hasNext.set(queueStatus.hasNext);
hasPrevious.set(queueStatus.hasPrevious);
shuffle.set(queueStatus.shuffle);
repeat.set(queueStatus.repeat as "off" | "all" | "one");
} catch (e) {
console.error("[playerEvents] Failed to update queue status:", e);
}
}
/** /**
* Handle media loaded event. * Handle media loaded event.
*/ */
+2 -4
View File
@@ -6,10 +6,8 @@ import { writable } from 'svelte/store';
export const isInitialized = writable(false); export const isInitialized = writable(false);
export const pendingSyncCount = writable(0); export const pendingSyncCount = writable(0);
export const isAndroid = writable(false); export const isAndroid = writable(false);
export const shuffle = writable(false); // Shuffle/repeat/next/previous state now lives in the event-driven queue store
export const repeat = writable<'off' | 'all' | 'one'>('off'); // ($lib/stores/queue), the single source of truth.
export const hasNext = writable(false);
export const hasPrevious = writable(false);
export const showSleepTimerModal = writable(false); export const showSleepTimerModal = writable(false);
// Library-specific state // Library-specific state
+43
View File
@@ -152,6 +152,47 @@ function createLibraryStore() {
} }
} }
// Load Live TV channels (broadcast / IPTV) into the items list. Live TV uses a
// dedicated Jellyfin endpoint rather than the generic /Items browse.
async function loadLiveTvChannels() {
update((s) => ({ ...s, loadingCount: s.loadingCount + 1, error: null }));
try {
const repo = auth.getRepository();
const channels = await repo.getLiveTvChannels();
update((s) => ({
...s,
items: channels,
totalItems: channels.length,
loadingCount: Math.max(0, s.loadingCount - 1),
}));
return channels;
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to load Live TV channels";
update((s) => ({ ...s, loadingCount: Math.max(0, s.loadingCount - 1), error: message }));
throw error;
}
}
// Load the root list of plugin "Channels" into the items list.
async function loadChannels() {
update((s) => ({ ...s, loadingCount: s.loadingCount + 1, error: null }));
try {
const repo = auth.getRepository();
const result = await repo.getChannels();
update((s) => ({
...s,
items: result.items,
totalItems: result.totalRecordCount,
loadingCount: Math.max(0, s.loadingCount - 1),
}));
return result;
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to load channels";
update((s) => ({ ...s, loadingCount: Math.max(0, s.loadingCount - 1), error: message }));
throw error;
}
}
async function loadItem(itemId: string) { async function loadItem(itemId: string) {
update((s) => ({ ...s, loadingCount: s.loadingCount + 1, error: null })); update((s) => ({ ...s, loadingCount: s.loadingCount + 1, error: null }));
@@ -297,6 +338,8 @@ function createLibraryStore() {
subscribe, subscribe,
loadLibraries, loadLibraries,
loadItems, loadItems,
loadLiveTvChannels,
loadChannels,
loadItem, loadItem,
search, search,
setCurrentLibrary, setCurrentLibrary,
+91
View File
@@ -0,0 +1,91 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { get } from "svelte/store";
import type { Session } from "$lib/api/types";
const mockInvoke = vi.fn();
vi.mock("$lib/api/bindings", () => ({
commands: {
lmsGetSyncGroups: () => mockInvoke("lms_get_sync_groups"),
lmsCreateSyncGroup: (masterMac: string, slaveMacs: string[]) =>
mockInvoke("lms_create_sync_group", { masterMac, slaveMacs }),
lmsUnsyncPlayer: (mac: string) => mockInvoke("lms_unsync_player", { mac }),
lmsDissolveSyncGroup: (masterMac: string) =>
mockInvoke("lms_dissolve_sync_group", { masterMac }),
},
}));
import { lmsSync, isLmsSession, macForSession } from "./lmsSync";
function session(deviceId: string | null): Session {
return { id: "s", deviceId } as unknown as Session;
}
describe("LMS session detection", () => {
it("detects LMS zones by the lms- device-id prefix", () => {
expect(isLmsSession(session("lms-aa:bb:cc:dd:ee:ff"))).toBe(true);
expect(isLmsSession(session("chromecast-123"))).toBe(false);
expect(isLmsSession(session(null))).toBe(false);
expect(isLmsSession(null)).toBe(false);
});
it("recovers the MAC from an LMS session, null otherwise", () => {
expect(macForSession(session("lms-aa:bb:cc:dd:ee:ff"))).toBe("aa:bb:cc:dd:ee:ff");
expect(macForSession(session("web-xyz"))).toBeNull();
expect(macForSession(null)).toBeNull();
});
});
describe("lmsSync store", () => {
beforeEach(() => {
mockInvoke.mockReset();
lmsSync.reset();
});
it("fusing preserves existing slaves and adds the new zone", async () => {
// Initial group: master M with slave A.
mockInvoke.mockResolvedValueOnce([{ masterMac: "M", masterName: "M", slaveMacs: ["A"], slaveNames: [] }]);
await lmsSync.refresh();
// create returns void; refresh after returns the updated group.
mockInvoke.mockResolvedValueOnce(undefined);
mockInvoke.mockResolvedValueOnce([{ masterMac: "M", masterName: "M", slaveMacs: ["A", "B"], slaveNames: [] }]);
await lmsSync.fuseZone("M", "B");
expect(mockInvoke).toHaveBeenCalledWith("lms_create_sync_group", {
masterMac: "M",
slaveMacs: ["A", "B"],
});
expect(get(lmsSync).groups[0].slaveMacs).toEqual(["A", "B"]);
});
it("decoupling a slave unsyncs just that player", async () => {
mockInvoke.mockResolvedValueOnce([{ masterMac: "M", masterName: "M", slaveMacs: ["A"], slaveNames: [] }]);
await lmsSync.refresh();
mockInvoke.mockResolvedValueOnce(undefined); // unsync
mockInvoke.mockResolvedValueOnce([{ masterMac: "M", masterName: "M", slaveMacs: [], slaveNames: [] }]);
await lmsSync.decoupleZone("A");
expect(mockInvoke).toHaveBeenCalledWith("lms_unsync_player", { mac: "A" });
});
it("decoupling the master dissolves the whole group", async () => {
mockInvoke.mockResolvedValueOnce([{ masterMac: "M", masterName: "M", slaveMacs: ["A"], slaveNames: [] }]);
await lmsSync.refresh();
mockInvoke.mockResolvedValueOnce(undefined); // dissolve
mockInvoke.mockResolvedValueOnce([]);
await lmsSync.decoupleZone("M");
expect(mockInvoke).toHaveBeenCalledWith("lms_dissolve_sync_group", { masterMac: "M" });
});
it("treats a missing plugin (refresh error) as no groups, not fatal", async () => {
mockInvoke.mockRejectedValueOnce(new Error("404"));
await lmsSync.refresh();
expect(get(lmsSync).groups).toEqual([]);
});
});
+133
View File
@@ -0,0 +1,133 @@
/**
* LMS multi-room sync ("fuse zones") store.
*
* The JellyLMS plugin registers each LMS player as a Jellyfin session whose
* device id is `lms-{MacAddress}`. We use that prefix both to detect which cast
* targets are fuseable LMS zones and to recover the MAC the SyncGroups API needs.
*
* Fusing model (per product decision): the currently-controlled zone is the sync
* master; other selected zones join it. Toggling an already-grouped zone off
* decouples just that zone; toggling the master off dissolves the group.
*
* TRACES: UR-010 | JA-021, JA-025 | DR-037
*/
import { writable, get } from "svelte/store";
import { commands } from "$lib/api/bindings";
import type { Session } from "$lib/api/types";
import type { LmsSyncGroup } from "$lib/api/bindings";
const LMS_DEVICE_PREFIX = "lms-";
/** Is this cast target an LMS zone (and therefore fuseable)? */
export function isLmsSession(session: Session | null | undefined): boolean {
return !!session?.deviceId?.startsWith(LMS_DEVICE_PREFIX);
}
/** Recover the LMS player MAC from a session, or null if it isn't an LMS zone. */
export function macForSession(session: Session | null | undefined): string | null {
const deviceId = session?.deviceId;
if (!deviceId?.startsWith(LMS_DEVICE_PREFIX)) return null;
return deviceId.slice(LMS_DEVICE_PREFIX.length);
}
interface LmsSyncState {
groups: LmsSyncGroup[];
isBusy: boolean;
error: string | null;
}
function createLmsSyncStore() {
const { subscribe, update, set } = writable<LmsSyncState>({
groups: [],
isBusy: false,
error: null,
});
/** Refresh the list of current sync groups from the server. */
async function refresh(): Promise<void> {
try {
const groups = await commands.lmsGetSyncGroups();
update((s) => ({ ...s, groups, error: null }));
} catch (error) {
// The plugin may not be installed; treat as "no groups" rather than fatal.
console.warn("[LmsSync] Failed to load sync groups:", error);
update((s) => ({ ...s, groups: [] }));
}
}
/** All MACs that are part of any sync group (master or slave). */
function groupedMacs(): Set<string> {
const macs = new Set<string>();
for (const g of get({ subscribe }).groups) {
macs.add(g.masterMac);
for (const slave of g.slaveMacs ?? []) macs.add(slave);
}
return macs;
}
/**
* Add an LMS zone to the master's sync group (fuse it in).
* Preserves any zones already grouped with the master.
*/
async function fuseZone(masterMac: string, zoneMac: string): Promise<void> {
if (masterMac === zoneMac) return;
update((s) => ({ ...s, isBusy: true, error: null }));
try {
const existing = get({ subscribe }).groups.find((g) => g.masterMac === masterMac);
const slaves = new Set(existing?.slaveMacs ?? []);
slaves.add(zoneMac);
await commands.lmsCreateSyncGroup(masterMac, [...slaves]);
await refresh();
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to fuse zone";
update((s) => ({ ...s, error: message }));
throw error;
} finally {
update((s) => ({ ...s, isBusy: false }));
}
}
/**
* Remove a single zone from its group. If the zone is a group's master, the
* whole group is dissolved (a group can't outlive its master).
*/
async function decoupleZone(zoneMac: string): Promise<void> {
update((s) => ({ ...s, isBusy: true, error: null }));
try {
const asMaster = get({ subscribe }).groups.find((g) => g.masterMac === zoneMac);
if (asMaster) {
await commands.lmsDissolveSyncGroup(zoneMac);
} else {
await commands.lmsUnsyncPlayer(zoneMac);
}
await refresh();
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to decouple zone";
update((s) => ({ ...s, error: message }));
throw error;
} finally {
update((s) => ({ ...s, isBusy: false }));
}
}
function clearError(): void {
update((s) => ({ ...s, error: null }));
}
function reset(): void {
set({ groups: [], isBusy: false, error: null });
}
return {
subscribe,
refresh,
groupedMacs,
fuseZone,
decoupleZone,
clearError,
reset,
};
}
export const lmsSync = createLmsSyncStore();
+102 -1
View File
@@ -2,9 +2,17 @@
// Powers the focused music landing: hero + horizontal sliders. // Powers the focused music landing: hero + horizontal sliders.
// TRACES: UR-007, UR-034 | DR-007, DR-038, DR-039 // TRACES: UR-007, UR-034 | DR-007, DR-038, DR-039
import { writable, derived } from "svelte/store"; import { writable, derived } from "svelte/store";
import type { MediaItem } from "$lib/api/types"; import type { MediaItem, Genre } from "$lib/api/types";
import { auth } from "./auth"; import { auth } from "./auth";
import { excludePodcasts } from "$lib/utils/podcastFilter"; import { excludePodcasts } from "$lib/utils/podcastFilter";
import { selectDiverseGenres, sampleAcross } from "$lib/utils/genreDiversity";
/** A single "by genre" row: the genre name plus the albums in it. */
export interface GenreRow {
id: string;
name: string;
items: MediaItem[];
}
interface MusicState { interface MusicState {
// Albums grouped from recently played tracks (backend handles grouping). // Albums grouped from recently played tracks (backend handles grouping).
@@ -15,6 +23,8 @@ interface MusicState {
playlists: MediaItem[]; playlists: MediaItem[];
// Albums the user has played but hasn't returned to in a while. // Albums the user has played but hasn't returned to in a while.
rediscover: MediaItem[]; rediscover: MediaItem[];
// One slider per genre (top genres by album count).
genreRows: GenreRow[];
// Mix of recently played + rediscover, used for the hero banner. // Mix of recently played + rediscover, used for the hero banner.
heroItems: MediaItem[]; heroItems: MediaItem[];
isLoading: boolean; isLoading: boolean;
@@ -22,6 +32,11 @@ interface MusicState {
} }
const SECTION_LIMIT = 16; const SECTION_LIMIT = 16;
// How many genre sliders to show, and how many genres to probe to find them.
const MAX_GENRE_ROWS = 8;
// Probe a wide pool so the diverse-selection step has genres from across the
// whole (alphabetical) list to choose between, not just the first handful.
const MAX_GENRES_PROBED = 40;
function createMusicStore() { function createMusicStore() {
const initialState: MusicState = { const initialState: MusicState = {
@@ -29,6 +44,7 @@ function createMusicStore() {
newlyAdded: [], newlyAdded: [],
playlists: [], playlists: [],
rediscover: [], rediscover: [],
genreRows: [],
heroItems: [], heroItems: [],
isLoading: false, isLoading: false,
error: null, error: null,
@@ -110,6 +126,10 @@ function createMusicStore() {
heroItems, heroItems,
isLoading: false, isLoading: false,
})); }));
// Genre rows are secondary — load them after the main sections paint so
// the page isn't blocked on N per-genre queries.
loadGenreRows(libraryId);
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : "Failed to load music sections"; const message = error instanceof Error ? error.message : "Failed to load music sections";
update(s => ({ ...s, isLoading: false, error: message })); update(s => ({ ...s, isLoading: false, error: message }));
@@ -117,6 +137,87 @@ function createMusicStore() {
} }
} }
/** Fetch up to SECTION_LIMIT albums for one genre as a slider row. */
async function loadGenreRow(libraryId: string, genre: Genre): Promise<GenreRow> {
const repo = auth.getRepository();
try {
const result = await repo.getItems(libraryId, {
includeItemTypes: ["MusicAlbum"],
genres: [genre.name],
sortBy: "SortName",
sortOrder: "Ascending",
recursive: true,
limit: SECTION_LIMIT,
});
// HACK: drop the "Podcasts" folder that lives in the music library.
return { id: genre.id, name: genre.name, items: excludePodcasts(result.items) };
} catch (e) {
console.warn(`Failed to load genre row "${genre.name}":`, e);
return { id: genre.id, name: genre.name, items: [] };
}
}
/**
* Build one slider per genre, showing albums in each. We pick a *diverse* set
* rather than just the most populous otherwise a cluster of near-synonyms
* ("Rock", "Hard Rock", "Classic Rock", ...) crowds out musically distinct
* genres. See selectDiverseGenres. Album genres rarely carry community
* ratings, so we order each row by name.
*
* When the backend reports per-genre album counts (online), we rank and pick
* before fetching, so we only query albums for the genres we'll actually
* show. When counts are missing (offline), we fall back to probing a wide
* pool, dropping empties, then ranking by what came back.
*/
async function loadGenreRows(libraryId: string) {
try {
const repo = auth.getRepository();
const genres = await repo.getGenres(libraryId);
if (genres.length === 0) return;
// Counts are only *useful* if they actually differentiate genres. Some
// servers return Fields=ItemCounts but populate every genre with the same
// value (or 0), which leaves the list in its original alphabetical order
// after "ranking" — so diversity selection seeds on the first genre and we
// get a wall of A-genres ("avangard", "avan-gard", ...) with no Rock.
// Treat that as "no usable counts" and fall through to the probe path,
// which ranks by genres' real album counts instead.
const positiveCounts = genres
.map(g => g.albumCount)
.filter((c): c is number => c != null && c > 0);
const hasUsefulCounts = new Set(positiveCounts).size > 1;
let genreRows: GenreRow[];
if (hasUsefulCounts) {
// Rank by reported count, pick a diverse subset, then fetch only those.
const ranked = [...genres].sort(
(a, b) => (b.albumCount ?? 0) - (a.albumCount ?? 0)
);
const chosen = selectDiverseGenres(ranked, MAX_GENRE_ROWS);
genreRows = (await Promise.all(chosen.map(g => loadGenreRow(libraryId, g)))).filter(
row => row.items.length > 0
);
} else {
// No usable counts (offline, a server that ignores Fields=ItemCounts,
// or one that returns uniform/zero counts — see hasUsefulCounts above).
// The genre list is alphabetical, so probing the first N would only
// ever surface A-genres. Sample at an even stride across the whole
// list instead, so the probe pool spans A→Z; then drop empties, rank
// by what came back, and pick a diverse subset.
const probed = sampleAcross(genres, MAX_GENRES_PROBED);
const rows = await Promise.all(probed.map(g => loadGenreRow(libraryId, g)));
const populated = rows
.filter(row => row.items.length > 0)
.sort((a, b) => b.items.length - a.items.length);
genreRows = selectDiverseGenres(populated, MAX_GENRE_ROWS);
}
update(s => ({ ...s, genreRows }));
} catch (e) {
console.warn("Failed to load music genre rows:", e);
}
}
function reset() { function reset() {
set(initialState); set(initialState);
} }
+94 -3
View File
@@ -9,26 +9,31 @@ vi.mock("@tauri-apps/api/core", () => ({
invoke: (...args: unknown[]) => mockInvoke(...args), invoke: (...args: unknown[]) => mockInvoke(...args),
})); }));
// Mock the sessions store // Mock the sessions store. `selectedSession` is read via svelte's `get()`, which
// calls subscribe and synchronously receives the current value; tests set
// `currentSelectedSession` to control what the store yields.
const mockSelectSession = vi.fn(); const mockSelectSession = vi.fn();
let currentSelectedSession: unknown = null;
vi.mock("./sessions", () => ({ vi.mock("./sessions", () => ({
sessions: { sessions: {
selectSession: (...args: unknown[]) => mockSelectSession(...args), selectSession: (...args: unknown[]) => mockSelectSession(...args),
}, },
selectedSession: { selectedSession: {
subscribe: vi.fn((callback: (value: null) => void) => { subscribe: vi.fn((callback: (value: unknown) => void) => {
callback(null); callback(currentSelectedSession);
return () => {}; return () => {};
}), }),
}, },
})); }));
// Mock auth store // Mock auth store
const mockGetHandle = vi.fn(() => "repo-handle-1");
vi.mock("./auth", () => ({ vi.mock("./auth", () => ({
auth: { auth: {
getRepository: vi.fn(() => ({ getRepository: vi.fn(() => ({
getPlaybackInfo: vi.fn().mockResolvedValue({ streamUrl: "http://test.com/stream" }), getPlaybackInfo: vi.fn().mockResolvedValue({ streamUrl: "http://test.com/stream" }),
getImageUrl: vi.fn().mockReturnValue("http://test.com/image"), getImageUrl: vi.fn().mockReturnValue("http://test.com/image"),
getHandle: () => mockGetHandle(),
})), })),
}, },
})); }));
@@ -36,6 +41,7 @@ vi.mock("./auth", () => ({
describe("playbackMode store", () => { describe("playbackMode store", () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
currentSelectedSession = null;
}); });
afterEach(() => { afterEach(() => {
@@ -161,6 +167,7 @@ describe("playbackMode store", () => {
expect(mockInvoke).toHaveBeenCalledWith("playback_mode_transfer_to_remote", { expect(mockInvoke).toHaveBeenCalledWith("playback_mode_transfer_to_remote", {
sessionId: "session-456", sessionId: "session-456",
position: null,
}); });
}); });
@@ -204,6 +211,90 @@ describe("playbackMode store", () => {
}); });
}); });
describe("transferToLocal", () => {
// 50,000,000 ticks = 5 seconds (10M ticks per second).
const REMOTE_POSITION_TICKS = 50_000_000;
const REMOTE_POSITION_SECONDS = 5;
function setRemoteSessionPlaying() {
currentSelectedSession = {
id: "session-123",
nowPlayingItem: { id: "item-abc", name: "Test Track", runTimeTicks: 1_800_000_000 },
playState: { positionTicks: REMOTE_POSITION_TICKS },
};
}
it("resumes local playback at the remote position, not from 0", async () => {
const { playbackMode } = await import("./playbackMode");
playbackMode.setMode("remote", "session-123");
setRemoteSessionPlaying();
mockInvoke.mockResolvedValue(undefined);
await playbackMode.transferToLocal();
// Bug 2 guard: the resume position must be passed to play_tracks so the
// backend seeks at load time. Restarting from 0 means startPosition is missing.
const playTracksCall = mockInvoke.mock.calls.find((c) => c[0] === "player_play_tracks");
expect(playTracksCall).toBeDefined();
expect(playTracksCall![1]).toMatchObject({
repositoryHandle: "repo-handle-1",
request: {
trackIds: ["item-abc"],
startIndex: 0,
startPosition: REMOTE_POSITION_SECONDS,
},
});
});
it("does not issue a separate player_seek (no start-at-0-then-jump race)", async () => {
const { playbackMode } = await import("./playbackMode");
playbackMode.setMode("remote", "session-123");
setRemoteSessionPlaying();
mockInvoke.mockResolvedValue(undefined);
await playbackMode.transferToLocal();
const seekCall = mockInvoke.mock.calls.find((c) => c[0] === "player_seek");
expect(seekCall).toBeUndefined();
});
it("tells Rust to stop the remote session with the current item and position", async () => {
const { playbackMode } = await import("./playbackMode");
playbackMode.setMode("remote", "session-123");
setRemoteSessionPlaying();
mockInvoke.mockResolvedValue(undefined);
await playbackMode.transferToLocal();
expect(mockInvoke).toHaveBeenCalledWith("playback_mode_transfer_to_local", {
currentItemId: "item-abc",
positionTicks: REMOTE_POSITION_TICKS,
});
const state = get(playbackMode);
expect(state.mode).toBe("local");
expect(state.remoteSessionId).toBeNull();
expect(state.isTransferring).toBe(false);
});
it("switches to local without playing media when remote has nothing playing", async () => {
const { playbackMode } = await import("./playbackMode");
playbackMode.setMode("remote", "session-123");
currentSelectedSession = { id: "session-123", nowPlayingItem: null, playState: null };
await playbackMode.transferToLocal();
expect(mockInvoke).not.toHaveBeenCalledWith("player_play_tracks", expect.anything());
const state = get(playbackMode);
expect(state.mode).toBe("local");
expect(state.remoteSessionId).toBeNull();
});
});
describe("clearError", () => { describe("clearError", () => {
it("should clear transfer error", async () => { it("should clear transfer error", async () => {
const { playbackMode } = await import("./playbackMode"); const { playbackMode } = await import("./playbackMode");
+31 -13
View File
@@ -73,7 +73,10 @@ function createPlaybackModeStore() {
* - Polls remote session until track loads * - Polls remote session until track loads
* - Stops local playback * - Stops local playback
*/ */
async function transferToRemote(sessionId: string | null | undefined): Promise<void> { async function transferToRemote(
sessionId: string | null | undefined,
currentPosition?: number,
): Promise<void> {
console.log("[PlaybackMode] Transferring to remote session:", sessionId); console.log("[PlaybackMode] Transferring to remote session:", sessionId);
update((s) => ({ ...s, isTransferring: true, transferError: null })); update((s) => ({ ...s, isTransferring: true, transferError: null }));
@@ -88,10 +91,17 @@ function createPlaybackModeStore() {
}; };
try { try {
// Pass the caller's current local position so the remote resumes where we
// are. The backend can't reliably read this itself: on Linux video plays in
// the HTML5 <video> element and the MPV backend reports 0. A null override
// falls back to the backend position (correct for Linux audio via MPV).
const positionOverride =
currentPosition !== undefined && currentPosition > 0 ? currentPosition : null;
// Rust handles everything - just wait for it to complete // Rust handles everything - just wait for it to complete
// It includes its own 5-second timeout for track loading // It includes its own 5-second timeout for track loading
console.log("[PlaybackMode] About to invoke playback_mode_transfer_to_remote with sessionId:", sessionId); console.log("[PlaybackMode] About to invoke playback_mode_transfer_to_remote with sessionId:", sessionId, "position:", positionOverride);
await commands.playbackModeTransferToRemote(sessionId ?? ""); await commands.playbackModeTransferToRemote(sessionId ?? "", positionOverride);
console.log("[PlaybackMode] Invoke completed successfully"); console.log("[PlaybackMode] Invoke completed successfully");
if (aborted) { if (aborted) {
@@ -188,14 +198,24 @@ function createPlaybackModeStore() {
// Get repository for handle (backend will fetch playback info via player_play_tracks) // Get repository for handle (backend will fetch playback info via player_play_tracks)
const repository = auth.getRepository(); const repository = auth.getRepository();
// Mark the whole sequence as a transfer in the *Rust* manager too. Without
// this, player_play_tracks sees mode=Remote and casts the track back to the
// remote session instead of playing it locally (the frontend's own
// isTransferring flag is invisible to Rust). Cleared in `finally`.
await commands.playbackModeSetTransferring(true);
// Start local playback (events allowed through because isTransferring=true) // Start local playback (events allowed through because isTransferring=true)
// Use player_play_tracks - backend fetches all metadata from single ID // Use player_play_tracks - backend fetches all metadata from single ID
const repositoryHandle = repository.getHandle(); const repositoryHandle = repository.getHandle();
// Pass the resume position so the backend seeks at load time. Doing the
// seek here (rather than a delayed playerSeek) avoids the race where the
// media isn't loaded yet and the seek is lost, restarting from 0.
await commands.playerPlayTracks(repositoryHandle, { await commands.playerPlayTracks(repositoryHandle, {
trackIds: [itemId], trackIds: [itemId],
startIndex: 0, startIndex: 0,
shuffle: false, shuffle: false,
startPosition: positionSeconds,
context: { context: {
type: "search", type: "search",
searchQuery: "", searchQuery: "",
@@ -204,16 +224,6 @@ function createPlaybackModeStore() {
if (aborted) return; if (aborted) return;
// Wait briefly for media to load
await new Promise((resolve) => setTimeout(resolve, 500));
// Seek to position if not at the very start
if (positionSeconds > 0.5) {
await commands.playerSeek(positionSeconds);
}
if (aborted) return;
// Let Rust handle stopping remote playback // Let Rust handle stopping remote playback
await commands.playbackModeTransferToLocal(itemId, positionTicks); await commands.playbackModeTransferToLocal(itemId, positionTicks);
@@ -244,6 +254,14 @@ function createPlaybackModeStore() {
console.error("Transfer to local failed:", error); console.error("Transfer to local failed:", error);
throw error; throw error;
} finally { } finally {
// Always lower the Rust transferring flag so it can't stick on if any step
// above threw (transfer_to_local lowers it on success, but not if we never
// reached it). Safe to call unconditionally.
try {
await commands.playbackModeSetTransferring(false);
} catch (e) {
console.warn("[PlaybackMode] Failed to clear transferring flag:", e);
}
currentTransferAbort = null; currentTransferAbort = null;
} }
} }
+10 -6
View File
@@ -13,6 +13,7 @@ import type { MediaItem, ItemType } from "$lib/api/types";
import type { NowPlayingItem } from "$lib/api/bindings"; import type { NowPlayingItem } from "$lib/api/bindings";
import { isRemoteMode } from "./playbackMode"; import { isRemoteMode } from "./playbackMode";
import { selectedSession } from "./sessions"; import { selectedSession } from "./sessions";
import { currentQueueItem } from "./queue";
import { ticksToSeconds } from "$lib/utils/playbackUnits"; import { ticksToSeconds } from "$lib/utils/playbackUnits";
// Merged media item from backend (matches Rust MergedMediaItem) // Merged media item from backend (matches Rust MergedMediaItem)
@@ -257,21 +258,24 @@ export const mergedVolume = derived(
* AND current media is audio (not video: Movie or Episode) * AND current media is audio (not video: Movie or Episode)
*/ */
export const shouldShowAudioMiniPlayer = derived( export const shouldShowAudioMiniPlayer = derived(
[player, currentMedia, isRemoteMode, selectedSession], [player, currentMedia, currentQueueItem, isRemoteMode, selectedSession],
([$player, $media, $isRemote, $session]) => { ([$player, $media, $queueItem, $isRemote, $session]) => {
// In remote mode, show if the remote session has a now-playing item // In remote mode, show if the remote session has a now-playing item
if ($isRemote && $session?.nowPlayingItem) { if ($isRemote && $session?.nowPlayingItem) {
return true; return true;
} }
// Local mode: only show when actively playing or paused // Local mode: hide only when there is genuinely nothing loaded
// (idle/stopped/error). Keep showing through loading/seeking transitions
// so the mini player doesn't blink out when advancing between tracks.
const state = $player.state; const state = $player.state;
if (state.kind !== "playing" && state.kind !== "paused") { if (state.kind === "idle" || state.kind === "error") {
return false; return false;
} }
// Don't show for video content // Determine media type from the player state, falling back to the queue
const mediaType = $media?.type; // item (the player store can momentarily lack media during transitions).
const mediaType = $media?.type ?? $queueItem?.type;
if (mediaType === "Movie" || mediaType === "Episode") { if (mediaType === "Movie" || mediaType === "Episode") {
return false; return false;
} }
+6 -7
View File
@@ -7,8 +7,7 @@
// TRACES: UR-005, UR-015 | DR-005, DR-020 // TRACES: UR-005, UR-015 | DR-005, DR-020
import { writable, derived, get } from "svelte/store"; import { writable, derived, get } from "svelte/store";
import { listen } from "@tauri-apps/api/event"; import { commands, events } from "$lib/api/bindings";
import { commands } from "$lib/api/bindings";
import type { MediaItem } from "$lib/api/types"; import type { MediaItem } from "$lib/api/types";
import { auth } from "$lib/stores/auth"; import { auth } from "$lib/stores/auth";
@@ -51,12 +50,12 @@ function createQueueStore() {
// Initial sync from backend // Initial sync from backend
await syncFromRust(); await syncFromRust();
// Listen for queue changed events // Listen for queue changed events (generated tauri-specta event)
unlisten = await listen<QueueChangedEvent>("player-event", (event) => { unlisten = await events.playerStatusEvent.listen((event) => {
if ((event.payload as any).type === "queue_changed") { if (event.payload.type === "queue_changed") {
const queueEvent = event.payload as any; const queueEvent = event.payload;
set({ set({
items: queueEvent.items, items: queueEvent.items as unknown as MediaItem[],
currentIndex: queueEvent.current_index, currentIndex: queueEvent.current_index,
shuffle: queueEvent.shuffle, shuffle: queueEvent.shuffle,
repeat: queueEvent.repeat, repeat: queueEvent.repeat,
+8 -13
View File
@@ -2,8 +2,7 @@
// TRACES: UR-010 | DR-037 // TRACES: UR-010 | DR-037
import { writable, derived } from "svelte/store"; import { writable, derived } from "svelte/store";
import { listen } from "@tauri-apps/api/event"; import { commands, events } from "$lib/api/bindings";
import { commands } from "$lib/api/bindings";
import type { Session } from "$lib/api/types"; import type { Session } from "$lib/api/types";
interface SessionsState { interface SessionsState {
@@ -14,11 +13,6 @@ interface SessionsState {
lastUpdated: Date | null; lastUpdated: Date | null;
} }
interface PlayerStatusEvent {
type: string;
sessions?: Session[];
}
function createSessionsStore() { function createSessionsStore() {
const initialState: SessionsState = { const initialState: SessionsState = {
sessions: [], sessions: [],
@@ -30,16 +24,17 @@ function createSessionsStore() {
const { subscribe, update } = writable<SessionsState>(initialState); const { subscribe, update } = writable<SessionsState>(initialState);
// Listen for session updates from Rust backend // Listen for session updates from Rust backend (generated tauri-specta event)
listen<PlayerStatusEvent>("player-event", (event) => { events.playerStatusEvent.listen((event) => {
if (event.payload.type === "sessions_updated" && event.payload.sessions) { if (event.payload.type === "sessions_updated") {
console.log(`[Sessions] Received ${event.payload.sessions.length} sessions from backend`); const sessions = event.payload.sessions as unknown as Session[];
event.payload.sessions.forEach((s, i) => { console.log(`[Sessions] Received ${sessions.length} sessions from backend`);
sessions.forEach((s, i) => {
console.log(`[Sessions] Session ${i}: id=${s.id}, device=${s.deviceName}, supportsRemoteControl=${s.supportsRemoteControl}`); console.log(`[Sessions] Session ${i}: id=${s.id}, device=${s.deviceName}, supportsRemoteControl=${s.supportsRemoteControl}`);
}); });
update((s) => ({ update((s) => ({
...s, ...s,
sessions: event.payload.sessions!, sessions,
lastUpdated: new Date(), lastUpdated: new Date(),
error: null, error: null,
})); }));
+79
View File
@@ -0,0 +1,79 @@
import { describe, it, expect } from "vitest";
import { selectDiverseGenres, sampleAcross } from "./genreDiversity";
const g = (...names: string[]) => names.map(name => ({ name }));
describe("sampleAcross", () => {
it("returns input unchanged when at or under the count", () => {
expect(sampleAcross([1, 2, 3], 5)).toEqual([1, 2, 3]);
});
it("spreads the sample across the whole list rather than taking a prefix", () => {
// 26 letters, want ~7: a prefix would be AG; striding spans A→Z.
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
const picked = sampleAcross(letters, 7);
expect(picked[0]).toBe("A");
// Reaches deep into the alphabet, not stuck near the front.
expect(picked[picked.length - 1] >= "S").toBe(true);
expect(picked.length).toBeLessThanOrEqual(7);
});
it("never exceeds the requested count", () => {
const items = Array.from({ length: 100 }, (_, i) => i);
expect(sampleAcross(items, 8).length).toBeLessThanOrEqual(8);
});
});
describe("selectDiverseGenres", () => {
it("returns input unchanged when at or under the limit", () => {
const input = g("Rock", "Jazz");
expect(selectDiverseGenres(input, 5)).toEqual(input);
});
it("seeds with the most populous genre (first in input)", () => {
const out = selectDiverseGenres(g("Rock", "Jazz", "Hip Hop"), 1);
expect(out.map(x => x.name)).toEqual(["Rock"]);
});
it("spreads the family instead of stacking near-synonyms", () => {
// Count ranking puts all the Rock variants first; a naive top-N would
// return four flavours of Rock. Diversity should pull in distinct genres.
const input = g(
"Rock",
"Hard Rock",
"Classic Rock",
"Pop Rock",
"Jazz",
"Hip Hop",
"Classical"
);
const names = selectDiverseGenres(input, 4).map(x => x.name);
expect(names[0]).toBe("Rock"); // seeded by count
expect(names).toContain("Jazz");
expect(names).toContain("Hip Hop");
expect(names).toContain("Classical");
// Only the seed represents the Rock cluster.
expect(names.filter(n => n.includes("Rock"))).toEqual(["Rock"]);
});
it("preserves count order as the tie-breaker among equally-distinct genres", () => {
// All four are mutually distinct (no shared tokens), so every pick after
// the seed is a distance tie and should follow input (count) order.
const input = g("Rock", "Jazz", "Blues", "Folk");
expect(selectDiverseGenres(input, 3).map(x => x.name)).toEqual([
"Rock",
"Jazz",
"Blues",
]);
});
it("is case- and separator-insensitive when comparing", () => {
const input = g("Hip Hop", "hip-hop", "Reggae");
// "Hip Hop" and "hip-hop" share all tokens → the second is redundant.
expect(selectDiverseGenres(input, 2).map(x => x.name)).toEqual([
"Hip Hop",
"Reggae",
]);
});
});
+95
View File
@@ -0,0 +1,95 @@
// Selecting a *diverse* set of genres for the music landing page.
//
// The naive approach ("keep the genres with the most albums") tends to surface
// a cluster of near-synonyms — "Rock", "Hard Rock", "Classic Rock", "Pop Rock"
// — because big umbrella genres and their sub-genres are all populous. The
// result reads as one genre repeated, not a tour of the library.
//
// Instead we pick greedily for *spread*: start from the most populous genre,
// then repeatedly add whichever remaining genre is least similar to everything
// already chosen (a max-min / farthest-point selection). Similarity is word-
// token overlap (Jaccard), so "Hard Rock" stays close to "Rock" but far from
// "Jazz" or "Hip Hop". Count still acts as a gentle tie-breaker so we don't
// promote a one-album novelty genre over a healthy distinct one.
/** Anything with a name and a relative weight (album count) we can rank by. */
export interface DiversityCandidate {
name: string;
}
/**
* Sample up to `count` items at an even stride across `items`. Genre lists come
* back alphabetical, so taking the first N would only ever surface A-genres;
* striding spreads the sample AZ. Always includes the first item.
*/
export function sampleAcross<T>(items: T[], count: number): T[] {
if (items.length <= count) return items.slice();
const stride = Math.max(1, Math.floor(items.length / count));
return items.filter((_, i) => i % stride === 0).slice(0, count);
}
/** Split a genre name into a set of lowercased word tokens. */
function tokenize(name: string): Set<string> {
return new Set(
name
.toLowerCase()
.split(/[^a-z0-9]+/)
.filter(Boolean)
);
}
/** Jaccard similarity of two token sets: |A∩B| / |AB|, in [0, 1]. */
function jaccard(a: Set<string>, b: Set<string>): number {
if (a.size === 0 && b.size === 0) return 1;
let intersection = 0;
for (const t of a) if (b.has(t)) intersection++;
const union = a.size + b.size - intersection;
return union === 0 ? 0 : intersection / union;
}
/**
* Pick up to `limit` genres that are textually distinct from one another,
* preferring more populous genres. Input order is treated as the count ranking
* (most albums first); ties in distance fall back to that order.
*/
export function selectDiverseGenres<T extends DiversityCandidate>(
candidates: T[],
limit: number
): T[] {
if (candidates.length <= limit) return candidates.slice();
const tokens = candidates.map(c => tokenize(c.name));
const chosen: number[] = [];
const remaining = new Set(candidates.map((_, i) => i));
// Seed with the most populous genre (candidates[0]).
chosen.push(0);
remaining.delete(0);
while (chosen.length < limit && remaining.size > 0) {
let best = -1;
// The best candidate is the one *least* similar to its most-similar chosen
// member. We track that max-similarity and minimise it: a genre is only
// "diverse" if it resembles *nothing* already chosen, so looking at the
// single nearest neighbour (as plain farthest-point does) isn't enough —
// "Hard Rock" must stay close to "Rock" even after unrelated "Jazz" is in.
let bestMaxSim = Infinity;
for (const i of remaining) {
let maxSim = 0;
for (const c of chosen) {
const sim = jaccard(tokens[i], tokens[c]);
if (sim > maxSim) maxSim = sim;
}
// Lower max-similarity wins; on a tie keep the earlier (more populous)
// one, guaranteed because `remaining` iterates in insertion order.
if (maxSim < bestMaxSim) {
bestMaxSim = maxSim;
best = i;
}
}
chosen.push(best);
remaining.delete(best);
}
return chosen.map(i => candidates[i]);
}
+35
View File
@@ -0,0 +1,35 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { navigateBack } from "./navigation";
const goto = vi.fn();
vi.mock("$app/navigation", () => ({
goto: (...args: unknown[]) => goto(...args),
}));
describe("navigateBack", () => {
beforeEach(() => {
goto.mockClear();
});
it("pops real history when there is in-app history to go back to", () => {
const back = vi.fn();
vi.spyOn(history, "back").mockImplementation(back);
vi.spyOn(history, "length", "get").mockReturnValue(3);
navigateBack("/library");
expect(back).toHaveBeenCalledOnce();
expect(goto).not.toHaveBeenCalled();
});
it("falls back to the given path on a fresh deep-link (no history)", () => {
const back = vi.fn();
vi.spyOn(history, "back").mockImplementation(back);
vi.spyOn(history, "length", "get").mockReturnValue(1);
navigateBack("/library/music");
expect(goto).toHaveBeenCalledWith("/library/music");
expect(back).not.toHaveBeenCalled();
});
});
+33
View File
@@ -0,0 +1,33 @@
import { goto } from "$app/navigation";
/**
* Navigate "back" using real browser/Android history when possible, falling
* back to an explicit path otherwise.
*
* Hardcoded `goto(backPath)` always sends the user to a fixed screen, which
* loses track of where they actually came from (e.g. reaching the genres list
* from different entry points). Preferring `history.back()` keeps the back
* affordance consistent with the platform back gesture and the browser/Android
* hardware back button.
*
* We only use history when there is somewhere to go back to *within the app*.
* On a fresh deep-link (history length 1, or an external referrer) we fall back
* to `fallbackPath` so the user never gets stranded or bounced out of the app.
*/
export function navigateBack(fallbackPath: string): void {
if (canGoBack()) {
history.back();
} else {
goto(fallbackPath);
}
}
/**
* True when there is in-app history to pop. `history.length > 1` means the user
* navigated here from another page in this session rather than landing here
* directly (deep link, refresh, or first load).
*/
function canGoBack(): boolean {
if (typeof history === "undefined") return false;
return history.length > 1;
}
+17 -10
View File
@@ -17,23 +17,30 @@
import MiniPlayer from "$lib/components/player/MiniPlayer.svelte"; import MiniPlayer from "$lib/components/player/MiniPlayer.svelte";
import SleepTimerModal from "$lib/components/player/SleepTimerModal.svelte"; import SleepTimerModal from "$lib/components/player/SleepTimerModal.svelte";
import BottomNav from "$lib/components/BottomNav.svelte"; import BottomNav from "$lib/components/BottomNav.svelte";
import { isInitialized, pendingSyncCount, isAndroid, shuffle, repeat, hasNext, hasPrevious, showSleepTimerModal } from "$lib/stores/appState"; import { isInitialized, pendingSyncCount, isAndroid, showSleepTimerModal } from "$lib/stores/appState";
// Shuffle/repeat/next/previous come from the event-driven queue store, the
// single source of truth (updated instantly on queue_changed).
import { isShuffle as shuffle, repeatMode as repeat, hasNext, hasPrevious } from "$lib/stores/queue";
let { children } = $props(); let { children } = $props();
onMount(async () => { onMount(async () => {
// Initialize auth state (restore session from secure storage) // Detect platform first (synchronously, before any await) so the global
await auth.initialize(); // mini player's Android visibility gate is correct from the first render.
isInitialized.set(true); // Android needs the global mini player because the library layout hides its
// own; if this ran after `await auth.initialize()` the store stayed false
// Detect platform (Android needs global mini player) // long enough that the mini player never appeared on library routes.
try { try {
const platformName = await platform(); const platformName = platform();
isAndroid.set(platformName === "android"); isAndroid.set(platformName === "android");
} catch (err) { } catch (err) {
console.error("Platform detection failed:", err); console.error("Platform detection failed:", err);
} }
// Initialize auth state (restore session from secure storage)
await auth.initialize();
isInitialized.set(true);
// Initialize player event listener for push-based updates // Initialize player event listener for push-based updates
await initPlayerEvents(); await initPlayerEvents();
@@ -129,10 +136,10 @@
<BottomNav /> <BottomNav />
{/if} {/if}
<!-- Mini Player - show everywhere except on full player page and login --> <!-- Mini Player - show everywhere except on full player page, login and settings -->
<!-- Android: Show on all routes (except player/login) --> <!-- Android: Show on all routes (except player/login/settings) -->
<!-- Desktop: Show on non-library routes (library layout has its own MiniPlayer) --> <!-- Desktop: Show on non-library routes (library layout has its own MiniPlayer) -->
{#if !$page.url.pathname.startsWith('/player/') && !$page.url.pathname.startsWith('/login')} {#if !$page.url.pathname.startsWith('/player/') && !$page.url.pathname.startsWith('/login') && !$page.url.pathname.startsWith('/settings')}
{#if $isAndroid || !$page.url.pathname.startsWith('/library')} {#if $isAndroid || !$page.url.pathname.startsWith('/library')}
<MiniPlayer <MiniPlayer
media={$currentMedia} media={$currentMedia}
+49 -1
View File
@@ -4,11 +4,13 @@
import { platform } from "@tauri-apps/plugin-os"; import { platform } from "@tauri-apps/plugin-os";
import { auth, isAuthenticated } from "$lib/stores/auth"; import { auth, isAuthenticated } from "$lib/stores/auth";
import { home } from "$lib/stores/home"; import { home } from "$lib/stores/home";
import { library, libraries } from "$lib/stores/library";
import { isServerReachable } from "$lib/stores/connectivity"; import { isServerReachable } from "$lib/stores/connectivity";
import { currentMedia } from "$lib/stores/player"; import { currentMedia } from "$lib/stores/player";
import HeroBanner from "$lib/components/home/HeroBanner.svelte"; import HeroBanner from "$lib/components/home/HeroBanner.svelte";
import Carousel from "$lib/components/home/Carousel.svelte"; import Carousel from "$lib/components/home/Carousel.svelte";
import type { MediaItem } from "$lib/api/types"; import MediaCard from "$lib/components/library/MediaCard.svelte";
import type { MediaItem, Library } from "$lib/api/types";
// Track if we've done an initial load (plain variable, not reactive) // Track if we've done an initial load (plain variable, not reactive)
let hasLoadedOnce = false; let hasLoadedOnce = false;
@@ -34,6 +36,9 @@
if ($isAuthenticated) { if ($isAuthenticated) {
await home.loadHomeSections(); await home.loadHomeSections();
if ($libraries.length === 0) {
await library.loadLibraries();
}
hasLoadedOnce = true; hasLoadedOnce = true;
} }
}); });
@@ -68,6 +73,31 @@
} }
} }
// Playlist libraries live inside the Music landing page, not as top-level shortcuts.
const shortcutLibraries = $derived(
$libraries.filter((lib) => lib.collectionType !== "playlists")
);
function handleLibraryClick(lib: Library) {
// Mirror /library routing: dedicated landing pages need currentLibrary set.
library.setCurrentLibrary(lib);
switch (lib.collectionType) {
case "music":
goto("/library/music");
break;
case "tvshows":
goto("/library/tv");
break;
case "movies":
goto("/library/movies");
break;
default:
library.clearGenres();
goto("/library");
break;
}
}
const heroItems = $derived($home.heroItems); const heroItems = $derived($home.heroItems);
const resumeItems = $derived($home.resumeItems.filter( const resumeItems = $derived($home.resumeItems.filter(
i => i.type === "Movie" || i.type === "Episode" i => i.type === "Movie" || i.type === "Episode"
@@ -92,6 +122,24 @@
<HeroBanner items={heroItems} /> <HeroBanner items={heroItems} />
{/if} {/if}
<!-- Your Libraries: quick jump into each dedicated landing page -->
{#if shortcutLibraries.length > 0}
<div>
<h2 class="text-xl font-bold text-white mb-4 px-4">Your Libraries</h2>
<div class="flex gap-4 overflow-x-auto px-4 pb-2">
{#each shortcutLibraries as lib (lib.id)}
<div class="flex-shrink-0">
<MediaCard
item={lib}
size="medium"
onclick={() => handleLibraryClick(lib)}
/>
</div>
{/each}
</div>
</div>
{/if}
<!-- Next Movie --> <!-- Next Movie -->
{#if resumeMovies.length > 0} {#if resumeMovies.length > 0}
<Carousel <Carousel
+14 -50
View File
@@ -3,10 +3,11 @@
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { page } from "$app/stores"; import { page } from "$app/stores";
import { commands } from "$lib/api/bindings"; import { commands } from "$lib/api/bindings";
import { platform } from "@tauri-apps/plugin-os";
import { auth, isAuthenticated, isLoading as isAuthLoading, currentUser } from "$lib/stores/auth"; import { auth, isAuthenticated, isLoading as isAuthLoading, currentUser } from "$lib/stores/auth";
import { library } from "$lib/stores/library"; import { library } from "$lib/stores/library";
import { currentMedia, isPlaying, playbackPosition, playbackDuration, shouldShowAudioMiniPlayer } from "$lib/stores/player"; import { currentMedia, isPlaying, playbackPosition, playbackDuration, shouldShowAudioMiniPlayer } from "$lib/stores/player";
import { isShuffle, repeatMode, hasNext as hasNextStore, hasPrevious as hasPreviousStore } from "$lib/stores/queue";
import { isAndroid } from "$lib/stores/appState";
import { useScrollGuard } from "$lib/composables/useScrollGuard"; import { useScrollGuard } from "$lib/composables/useScrollGuard";
import Search from "$lib/components/Search.svelte"; import Search from "$lib/components/Search.svelte";
import MiniPlayer from "$lib/components/player/MiniPlayer.svelte"; import MiniPlayer from "$lib/components/player/MiniPlayer.svelte";
@@ -23,36 +24,19 @@
let showFullPlayer = $state(false); let showFullPlayer = $state(false);
let showOverflowMenu = $state(false); let showOverflowMenu = $state(false);
let showSleepTimerModal = $state(false); let showSleepTimerModal = $state(false);
let shuffle = $state(false); // Queue status (shuffle, repeat, hasNext, hasPrevious) is event-driven via the
let repeat = $state<"off" | "all" | "one">("off"); // queue store, which listens for queue_changed events from the backend. This
let hasNext = $state(false); // updates instantly when toggling shuffle/repeat (no polling lag).
let hasPrevious = $state(false); const shuffle = $derived($isShuffle);
let isAndroid = $state(false); const repeat = $derived($repeatMode);
const hasNext = $derived($hasNextStore);
let pollInterval: ReturnType<typeof setInterval> | null = null; const hasPrevious = $derived($hasPreviousStore);
let failedAttempts = 0; // Platform comes from the shared appState store (set once in the root layout),
const MAX_SILENT_FAILURES = 3; // Don't log errors for first 3 attempts // so this layout and the root layout never disagree about Android — otherwise
// both can suppress their mini players and none appears. See $lib/stores/appState.
onMount(() => { onMount(() => {
// Detect platform
try {
const platformName = platform();
isAndroid = platformName === "android";
} catch (err) {
console.error("Platform detection failed:", err);
}
// Poll for queue status (shuffle, repeat, hasNext, hasPrevious)
// Position/duration come from player events (pushed every 250ms)
// Add a small delay before starting polling to ensure player is ready on Android
const timeoutId = setTimeout(() => {
updateQueueStatus(); // Initial update
pollInterval = setInterval(updateQueueStatus, 1000);
}, 100);
return () => { return () => {
clearTimeout(timeoutId);
if (pollInterval) clearInterval(pollInterval);
scrollGuard.cleanup(); scrollGuard.cleanup();
}; };
}); });
@@ -64,26 +48,6 @@
} }
}); });
async function updateQueueStatus() {
try {
const queue = await commands.playerGetQueue();
// Reset failure counter on success
failedAttempts = 0;
hasNext = queue.hasNext;
hasPrevious = queue.hasPrevious;
shuffle = queue.shuffle;
repeat = queue.repeat as "off" | "all" | "one";
} catch (e) {
failedAttempts++;
// Only log errors after initial attempts (player may still be initializing)
if (failedAttempts > MAX_SILENT_FAILURES) {
console.error("[Queue Status] Error:", e);
}
}
}
async function handleLogout() { async function handleLogout() {
await auth.logout(); await auth.logout();
library.reset(); library.reset();
@@ -243,7 +207,7 @@
<!-- Main content (with padding for bottom nav bar and mini player) --> <!-- Main content (with padding for bottom nav bar and mini player) -->
<main <main
class="flex-1 overflow-y-auto p-4" class="flex-1 overflow-y-auto p-4"
style="padding-bottom: {$shouldShowAudioMiniPlayer ? (isAndroid ? '11rem' : '7rem') : '5rem'}; overscroll-behavior: contain" style="padding-bottom: {$shouldShowAudioMiniPlayer ? ($isAndroid ? '11rem' : '7rem') : '5rem'}; overscroll-behavior: contain"
onscroll={scrollGuard.onScroll} onscroll={scrollGuard.onScroll}
> >
{@render children()} {@render children()}
@@ -251,7 +215,7 @@
<!-- Mini Player (only show on non-Android platforms - Android uses global mini player) --> <!-- Mini Player (only show on non-Android platforms - Android uses global mini player) -->
<!-- Hide on player page since full player is already there --> <!-- Hide on player page since full player is already there -->
{#if !isAndroid && !$page.url.pathname.startsWith('/player/')} {#if !$isAndroid && !$page.url.pathname.startsWith('/player/')}
<MiniPlayer <MiniPlayer
media={$currentMedia} media={$currentMedia}
isPlaying={$isPlaying} isPlaying={$isPlaying}
+23 -1
View File
@@ -76,6 +76,22 @@
return; return;
} }
// Live TV channels use a dedicated endpoint
if (lib.collectionType === "livetv") {
library.setCurrentLibrary(lib);
library.clearGenres();
await library.loadLiveTvChannels();
return;
}
// Plugin "Channels" root list uses a dedicated endpoint
if (lib.collectionType === "channels") {
library.setCurrentLibrary(lib);
library.clearGenres();
await library.loadChannels();
return;
}
// For other library types, load items normally // For other library types, load items normally
library.setCurrentLibrary(lib); library.setCurrentLibrary(lib);
library.clearGenres(); library.clearGenres();
@@ -97,6 +113,11 @@
if ("type" in item) { if ("type" in item) {
// It's a MediaItem // It's a MediaItem
const mediaItem = item as MediaItem; const mediaItem = item as MediaItem;
// A ChannelFolderItem can be a folder (drill in) or a playable leaf.
if (mediaItem.type === "ChannelFolderItem" && !mediaItem.isFolder) {
goto(`/player/${mediaItem.id}`);
return;
}
switch (mediaItem.type) { switch (mediaItem.type) {
case "Series": case "Series":
case "Movie": case "Movie":
@@ -111,7 +132,8 @@
goto(`/library/${mediaItem.id}`); goto(`/library/${mediaItem.id}`);
break; break;
case "Episode": case "Episode":
// Episodes play directly case "TvChannel":
// Episodes and live TV channels play directly
goto(`/player/${mediaItem.id}`); goto(`/player/${mediaItem.id}`);
break; break;
default: default:
+34 -3
View File
@@ -2,6 +2,7 @@
import { onMount, untrack } from "svelte"; import { onMount, untrack } from "svelte";
import { page } from "$app/stores"; import { page } from "$app/stores";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { navigateBack } from "$lib/utils/navigation";
import { commands } from "$lib/api/bindings"; import { commands } from "$lib/api/bindings";
import type { MediaItem, Library } from "$lib/api/types"; import type { MediaItem, Library } from "$lib/api/types";
import { library, libraryItems, isLibraryLoading, currentLibrary, libraries } from "$lib/stores/library"; import { library, libraryItems, isLibraryLoading, currentLibrary, libraries } from "$lib/stores/library";
@@ -23,6 +24,8 @@
import CrewLinks from "$lib/components/library/CrewLinks.svelte"; import CrewLinks from "$lib/components/library/CrewLinks.svelte";
import GenreTags from "$lib/components/library/GenreTags.svelte"; import GenreTags from "$lib/components/library/GenreTags.svelte";
import CachedImage from "$lib/components/common/CachedImage.svelte"; import CachedImage from "$lib/components/common/CachedImage.svelte";
import BackButton from "$lib/components/common/BackButton.svelte";
import ArtistLinks from "$lib/components/library/ArtistLinks.svelte";
interface SeasonData { interface SeasonData {
season: MediaItem; season: MediaItem;
@@ -184,6 +187,12 @@
goto(`/library/${clickedItem.id}`); goto(`/library/${clickedItem.id}`);
return; return;
} }
// A ChannelFolderItem can be either a folder (drill in) or a playable leaf.
// Route non-folder channel items straight to the player.
if (clickedItem.type === "ChannelFolderItem" && !clickedItem.isFolder) {
goto(`/player/${clickedItem.id}`);
return;
}
switch (clickedItem.type) { switch (clickedItem.type) {
case "Series": case "Series":
case "Season": case "Season":
@@ -281,6 +290,13 @@
// Navigate to series page without the episode param // Navigate to series page without the episode param
goto(`/library/${itemId}`); goto(`/library/${itemId}`);
} }
function goBack() {
// Prefer real history so the user returns to wherever they came from
// (libraries grid, a list page, a parent album/artist, search, etc.),
// falling back to the libraries overview on a fresh deep-link.
navigateBack("/library");
}
</script> </script>
<div class="relative"> <div class="relative">
@@ -315,6 +331,9 @@
{:else if item} {:else if item}
<!-- Person Detail View - shown for Person items --> <!-- Person Detail View - shown for Person items -->
{#if item.type === "Person"} {#if item.type === "Person"}
<div class="pt-4">
<BackButton onClick={goBack} label="Back" />
</div>
<PersonDetailView person={item} /> <PersonDetailView person={item} />
<!-- Episode Focus View - shown when navigating with ?episode param --> <!-- Episode Focus View - shown when navigating with ?episode param -->
{:else if item.type === "Series" && focusedEpisode} {:else if item.type === "Series" && focusedEpisode}
@@ -326,8 +345,13 @@
/> />
{:else} {:else}
<div class="space-y-8"> <div class="space-y-8">
<!-- Back navigation -->
<div class="pt-4">
<BackButton onClick={goBack} label="Back" />
</div>
<!-- Header with item info --> <!-- Header with item info -->
<div class="flex gap-6 pt-4"> <div class="flex gap-6">
<!-- Poster --> <!-- Poster -->
<div class="flex-shrink-0 w-48"> <div class="flex-shrink-0 w-48">
{#if item.primaryImageTag} {#if item.primaryImageTag}
@@ -362,10 +386,17 @@
{#if item.parentIndexNumber && item.indexNumber}, {/if} {#if item.parentIndexNumber && item.indexNumber}, {/if}
{#if item.indexNumber}Episode {item.indexNumber}{/if} {#if item.indexNumber}Episode {item.indexNumber}{/if}
</p> </p>
{:else if item.productionYear || item.artists?.length} {:else if item.artistItems?.length || item.artists?.length}
<p class="text-lg text-gray-400 mt-1"> <p class="text-lg text-gray-400 mt-1">
{item.artists?.join(", ") || item.productionYear} <ArtistLinks
artistItems={item.artistItems}
artists={item.artists}
linkClass="text-lg text-[var(--color-jellyfin)] hover:underline"
textClass="text-gray-400"
/>
</p> </p>
{:else if item.productionYear}
<p class="text-lg text-gray-400 mt-1">{item.productionYear}</p>
{/if} {/if}
</div> </div>
+2 -1
View File
@@ -2,6 +2,7 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte"; import { onMount } from "svelte";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { navigateBack } from "$lib/utils/navigation";
import { currentLibrary } from "$lib/stores/library"; import { currentLibrary } from "$lib/stores/library";
import { movies } from "$lib/stores/movies"; import { movies } from "$lib/stores/movies";
import { isServerReachable } from "$lib/stores/connectivity"; import { isServerReachable } from "$lib/stores/connectivity";
@@ -85,7 +86,7 @@
<div class="flex items-center justify-between px-4"> <div class="flex items-center justify-between px-4">
<h1 class="text-3xl font-bold text-white">{$currentLibrary?.name ?? "Movies"}</h1> <h1 class="text-3xl font-bold text-white">{$currentLibrary?.name ?? "Movies"}</h1>
<button <button
onclick={() => goto("/library")} onclick={() => navigateBack("/library")}
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white" class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
title="Back to libraries" title="Back to libraries"
aria-label="Back to libraries" aria-label="Back to libraries"
+13 -1
View File
@@ -2,6 +2,7 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte"; import { onMount } from "svelte";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { navigateBack } from "$lib/utils/navigation";
import { auth } from "$lib/stores/auth"; import { auth } from "$lib/stores/auth";
import { currentLibrary } from "$lib/stores/library"; import { currentLibrary } from "$lib/stores/library";
import { music } from "$lib/stores/music"; import { music } from "$lib/stores/music";
@@ -86,6 +87,7 @@
const newlyAdded = $derived($music.newlyAdded); const newlyAdded = $derived($music.newlyAdded);
const playlists = $derived($music.playlists); const playlists = $derived($music.playlists);
const rediscover = $derived($music.rediscover); const rediscover = $derived($music.rediscover);
const genreRows = $derived($music.genreRows);
const isLoading = $derived($music.isLoading); const isLoading = $derived($music.isLoading);
const hasContent = $derived( const hasContent = $derived(
heroItems.length > 0 || heroItems.length > 0 ||
@@ -106,7 +108,7 @@
<div class="flex items-center justify-between px-4"> <div class="flex items-center justify-between px-4">
<h1 class="text-3xl font-bold text-white">Music</h1> <h1 class="text-3xl font-bold text-white">Music</h1>
<button <button
onclick={() => goto("/library")} onclick={() => navigateBack("/library")}
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white" class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
title="Back to libraries" title="Back to libraries"
aria-label="Back to libraries" aria-label="Back to libraries"
@@ -160,6 +162,16 @@
/> />
{/if} {/if}
<!-- One slider per genre -->
{#each genreRows as row (row.id)}
<Carousel
title={row.name}
items={row.items}
onItemClick={handleItemClick}
showAll={() => goto("/library/music/genres")}
/>
{/each}
{#if !hasContent} {#if !hasContent}
<p class="px-4 text-gray-400">Nothing here yet. Start playing some music to fill this page.</p> <p class="px-4 text-gray-400">Nothing here yet. Start playing some music to fill this page.</p>
{/if} {/if}
+2 -1
View File
@@ -2,6 +2,7 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte"; import { onMount } from "svelte";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { navigateBack } from "$lib/utils/navigation";
import { currentLibrary } from "$lib/stores/library"; import { currentLibrary } from "$lib/stores/library";
import { tv } from "$lib/stores/tv"; import { tv } from "$lib/stores/tv";
import { isServerReachable } from "$lib/stores/connectivity"; import { isServerReachable } from "$lib/stores/connectivity";
@@ -92,7 +93,7 @@
<div class="flex items-center justify-between px-4"> <div class="flex items-center justify-between px-4">
<h1 class="text-3xl font-bold text-white">{$currentLibrary?.name ?? "TV Shows"}</h1> <h1 class="text-3xl font-bold text-white">{$currentLibrary?.name ?? "TV Shows"}</h1>
<button <button
onclick={() => goto("/library")} onclick={() => navigateBack("/library")}
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white" class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
title="Back to libraries" title="Back to libraries"
aria-label="Back to libraries" aria-label="Back to libraries"
+47 -26
View File
@@ -8,7 +8,7 @@
import type { MediaItem } from "$lib/api/types"; import type { MediaItem } from "$lib/api/types";
import { auth } from "$lib/stores/auth"; import { auth } from "$lib/stores/auth";
import { library } from "$lib/stores/library"; import { library } from "$lib/stores/library";
import { queue, currentQueueItem } from "$lib/stores/queue"; import { queue, currentQueueItem, isShuffle, repeatMode, hasNext as hasNextStore, hasPrevious as hasPreviousStore } from "$lib/stores/queue";
import { downloads, type DownloadInfo } from "$lib/stores/downloads"; import { downloads, type DownloadInfo } from "$lib/stores/downloads";
import { playbackPosition, playbackDuration, currentMedia as storeCurrentMedia } from "$lib/stores/player"; import { playbackPosition, playbackDuration, currentMedia as storeCurrentMedia } from "$lib/stores/player";
import { get } from "svelte/store"; import { get } from "svelte/store";
@@ -47,14 +47,17 @@
const position = $derived($playbackPosition); const position = $derived($playbackPosition);
const duration = $derived($playbackDuration); const duration = $derived($playbackDuration);
let isPlaying = $state(false); let isPlaying = $state(false);
let shuffle = $state(false); // Shuffle/repeat/next/previous are event-driven via the queue store (instant
let repeat = $state<"off" | "all" | "one">("off"); // update on queue_changed), not polled.
let hasNext = $state(false); const shuffle = $derived($isShuffle);
let hasPrevious = $state(false); const repeat = $derived($repeatMode);
const hasNext = $derived($hasNextStore);
const hasPrevious = $derived($hasPreviousStore);
let currentMedia = $state<MediaItem | null>(null); let currentMedia = $state<MediaItem | null>(null);
let streamUrl = $state<string | null>(null); let streamUrl = $state<string | null>(null);
let mediaSourceId = $state<string | null>(null); let mediaSourceId = $state<string | null>(null);
let isVideo = $state(false); let isVideo = $state(false);
let isLive = $state(false); // Whether this is a live stream (Live TV channel) - no seek/resume
let videoInitialPosition = $state(0); // Position in seconds to seek to after video loads let videoInitialPosition = $state(0); // Position in seconds to seek to after video loads
let videoNeedsTranscoding = $state(false); // Whether video needs transcoding (HEVC/10-bit) let videoNeedsTranscoding = $state(false); // Whether video needs transcoding (HEVC/10-bit)
let isOfflinePlayback = $state(false); // Whether playing from local file let isOfflinePlayback = $state(false); // Whether playing from local file
@@ -102,6 +105,15 @@
} }
}); });
// A playable channel leaf (ChannelFolderItem) has no dedicated item type, so
// treat it as video when it carries a video media stream.
function isVideoChannelItem(item: MediaItem): boolean {
return (
item.type === "ChannelFolderItem" &&
(item.mediaStreams?.some((s) => s.type === "Video") ?? false)
);
}
async function loadAndPlay(id: string, startPosition?: number, forceRestart = false) { async function loadAndPlay(id: string, startPosition?: number, forceRestart = false) {
loading = true; loading = true;
error = null; error = null;
@@ -116,8 +128,9 @@
currentMedia = item; currentMedia = item;
// Check if this is a non-playable collection type that should be viewed in library instead // Check if this is a non-playable collection type that should be viewed in library instead
const collectionTypes = ["MusicAlbum", "MusicArtist", "Series", "Season", "Folder", "CollectionFolder", "Playlist"]; const collectionTypes = ["MusicAlbum", "MusicArtist", "Series", "Season", "Folder", "CollectionFolder", "Playlist", "Channel"];
if (collectionTypes.includes(item.type)) { // A ChannelFolderItem that is itself a folder is a container, not playable.
if (collectionTypes.includes(item.type) || (item.type === "ChannelFolderItem" && item.isFolder)) {
console.log("loadAndPlay: Redirecting collection type to library:", item.type); console.log("loadAndPlay: Redirecting collection type to library:", item.type);
goto(`/library/${id}`); goto(`/library/${id}`);
return; return;
@@ -130,17 +143,11 @@
const alreadyPlayingMedia = get(storeCurrentMedia); const alreadyPlayingMedia = get(storeCurrentMedia);
if (alreadyPlayingMedia?.id === id && !startPosition && !forceRestart) { if (alreadyPlayingMedia?.id === id && !startPosition && !forceRestart) {
console.log("loadAndPlay: Track already playing, showing UI without restarting"); console.log("loadAndPlay: Track already playing, showing UI without restarting");
isVideo = item.type === "Movie" || item.type === "Episode"; isLive = item.type === "TvChannel";
isVideo = item.type === "Movie" || item.type === "Episode" || isLive || isVideoChannelItem(item);
isPlaying = true; isPlaying = true;
loading = false; loading = false;
// Sync queue status // hasNext/hasPrevious come from the event-driven queue store.
try {
const queueStatus = await commands.playerGetQueue();
hasNext = queueStatus.hasNext;
hasPrevious = queueStatus.hasPrevious;
} catch (e) {
// Ignore - queue status will update via polling
}
// Fetch next episode for video skip button // Fetch next episode for video skip button
if (isVideo) { if (isVideo) {
fetchNextEpisode(item); fetchNextEpisode(item);
@@ -148,8 +155,10 @@
return; return;
} }
// Determine if this is video content (Movie and Episode are video types) // Determine if this is video content (Movie, Episode, live TV channels, and
isVideo = item.type === "Movie" || item.type === "Episode"; // channel leaf items that carry a video stream).
isLive = item.type === "TvChannel";
isVideo = item.type === "Movie" || item.type === "Episode" || isLive || isVideoChannelItem(item);
// When switching to video, stop audio playback and clear the queue // When switching to video, stop audio playback and clear the queue
// This prevents audio from continuing in the background and clears stale state // This prevents audio from continuing in the background and clears stale state
@@ -169,7 +178,8 @@
const userId = auth.getUserId(); const userId = auth.getUserId();
console.log("Resume check - userId:", userId, "itemId:", id, "startPosition:", startPosition, "forceRestart:", forceRestart); console.log("Resume check - userId:", userId, "itemId:", id, "startPosition:", startPosition, "forceRestart:", forceRestart);
if (!startPosition && !forceRestart && userId) { // Live streams have no fixed position - never resume.
if (!startPosition && !forceRestart && userId && !isLive) {
try { try {
const progress = await commands.storageGetPlaybackProgress(userId, id); const progress = await commands.storageGetPlaybackProgress(userId, id);
console.log("Resume check - retrieved progress:", progress); console.log("Resume check - retrieved progress:", progress);
@@ -256,6 +266,22 @@
// Online playback - get playback info from server // Online playback - get playback info from server
isOfflinePlayback = false; isOfflinePlayback = false;
const repo = auth.getRepository(); const repo = auth.getRepository();
if (isLive) {
// Live TV channels must be "opened" before streaming; the server returns
// a ready-to-play HLS transcoding URL. No resume, no seek, no progress.
console.log("loadAndPlay: Opening live stream for channel:", id);
const liveInfo = await repo.openLiveStream(id);
console.log("loadAndPlay: Live stream URL:", liveInfo.streamUrl);
mediaSourceId = liveInfo.mediaSourceId;
streamUrl = liveInfo.streamUrl;
videoNeedsTranscoding = true;
videoInitialPosition = 0;
isPlaying = true;
loading = false;
return;
}
console.log("loadAndPlay: Getting playback info"); console.log("loadAndPlay: Getting playback info");
const playbackInfo = await repo.getPlaybackInfo(id); const playbackInfo = await repo.getPlaybackInfo(id);
console.log("loadAndPlay: Got playback info, mediaSourceId:", playbackInfo.mediaSourceId); console.log("loadAndPlay: Got playback info, mediaSourceId:", playbackInfo.mediaSourceId);
@@ -446,13 +472,7 @@
isPlaying = status.state.kind === "playing"; isPlaying = status.state.kind === "playing";
// Note: position/duration are now derived from player store (updated by events) // Note: position/duration are now derived from player store (updated by events)
} }
shuffle = status.shuffle; // shuffle/repeat/hasNext/hasPrevious come from the queue store (event-driven).
repeat = status.repeat;
// Update queue status
const queue = await commands.playerGetQueue();
hasNext = queue.hasNext;
hasPrevious = queue.hasPrevious;
} catch (e) { } catch (e) {
// Ignore polling errors // Ignore polling errors
} }
@@ -624,6 +644,7 @@
mediaSourceId={mediaSourceId ?? undefined} mediaSourceId={mediaSourceId ?? undefined}
initialPosition={videoInitialPosition} initialPosition={videoInitialPosition}
needsTranscoding={videoNeedsTranscoding} needsTranscoding={videoNeedsTranscoding}
{isLive}
onClose={handleClose} onClose={handleClose}
onSeek={handleVideoSeek} onSeek={handleVideoSeek}
onReportStart={handleReportStart} onReportStart={handleReportStart}