From 228563454b70bc2a9975880ebf533a99d741059b Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 9 Feb 2026 01:28:11 -0600 Subject: [PATCH 01/11] feat(plex): checkpoint plex lan integration and quality sync cx --- package-lock.json | 4 +- src-tauri/src/api_server/mod.rs | 1 + src-tauri/src/commands/playback_context.rs | 1 + src-tauri/src/commands/radio.rs | 1 + src-tauri/src/lib.rs | 17 + src-tauri/src/playback_context/mod.rs | 1 + src-tauri/src/plex/mod.rs | 1269 +++++++++++++++++ src-tauri/src/queue/mod.rs | 3 + src-tauri/src/session_store/mod.rs | 29 +- src/lib/components/AlbumCard.svelte | 24 +- .../components/VirtualizedAlbumList.svelte | 4 +- src/lib/components/views/HomeView.svelte | 9 +- .../components/views/LocalLibraryView.svelte | 420 +++++- src/lib/components/views/SettingsView.svelte | 576 +++++++- src/lib/i18n/locales/de.json | 30 +- src/lib/i18n/locales/en.json | 53 +- src/lib/i18n/locales/es.json | 53 +- src/lib/i18n/locales/fr.json | 30 +- src/lib/services/playbackService.ts | 56 +- src/lib/services/trackActions.ts | 25 +- src/lib/stores/playbackContextStore.ts | 2 +- src/lib/stores/playerStore.ts | 50 +- src/lib/stores/queueStore.ts | 2 + src/lib/types/index.ts | 1 + src/routes/+page.svelte | 28 +- static/home-gear.svg | 5 +- static/plex-logo.svg | 7 + static/plex-mono.svg | 2 + 28 files changed, 2596 insertions(+), 107 deletions(-) create mode 100644 src-tauri/src/plex/mod.rs create mode 100644 static/plex-logo.svg create mode 100644 static/plex-mono.svg diff --git a/package-lock.json b/package-lock.json index 69943842d..ecd0d2ae0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "qbz-nix", - "version": "1.1.8-rc-5", + "version": "1.1.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "qbz-nix", - "version": "1.1.8-rc-5", + "version": "1.1.9", "license": "MIT", "dependencies": { "@tauri-apps/api": "^2", diff --git a/src-tauri/src/api_server/mod.rs b/src-tauri/src/api_server/mod.rs index 125e22597..6a328c302 100644 --- a/src-tauri/src/api_server/mod.rs +++ b/src-tauri/src/api_server/mod.rs @@ -936,6 +936,7 @@ async fn play_album( album_id: Some(album.id.clone()), artist_id: t.performer.as_ref().map(|p| p.id), streamable: t.streamable, + source: Some("qobuz".to_string()), } }).collect() } else { diff --git a/src-tauri/src/commands/playback_context.rs b/src-tauri/src/commands/playback_context.rs index 20517858c..0df4b1fe0 100644 --- a/src-tauri/src/commands/playback_context.rs +++ b/src-tauri/src/commands/playback_context.rs @@ -37,6 +37,7 @@ pub fn set_playback_context( let content_source = match source.as_str() { "qobuz" => ContentSource::Qobuz, "local" => ContentSource::Local, + "plex" => ContentSource::Plex, _ => return Err(format!("Invalid source: {}", source)), }; diff --git a/src-tauri/src/commands/radio.rs b/src-tauri/src/commands/radio.rs index 0478e78be..96c4e0040 100644 --- a/src-tauri/src/commands/radio.rs +++ b/src-tauri/src/commands/radio.rs @@ -327,6 +327,7 @@ fn track_to_queue_track(track: &Track) -> QueueTrack { album_id, artist_id, streamable: track.streamable, + source: Some("qobuz".to_string()), } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 707beee85..6492803bd 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -26,6 +26,7 @@ pub mod musicbrainz; pub mod network; pub mod offline; pub mod playback_context; +pub mod plex; pub mod player; pub mod playlist_import; pub mod queue; @@ -672,6 +673,22 @@ pub fn run() { cast::dlna::commands::dlna_stop, cast::dlna::commands::dlna_seek, cast::dlna::commands::dlna_set_volume, + // Plex LAN-only POC commands + plex::plex_ping, + plex::plex_get_music_sections, + plex::plex_get_section_tracks, + plex::plex_play_track, + plex::plex_auth_pin_start, + plex::plex_auth_pin_check, + plex::plex_open_auth_url, + plex::plex_cache_get_sections, + plex::plex_cache_save_sections, + plex::plex_cache_get_tracks, + plex::plex_cache_save_tracks, + plex::plex_cache_get_albums, + plex::plex_cache_get_album_tracks, + plex::plex_cache_search_tracks, + plex::plex_cache_clear, // AirPlay casting commands - DISABLED until RAOP implementation is complete // See docs/AIRPLAY_IMPLEMENTATION_STATUS.md for details // cast::airplay::commands::airplay_start_discovery, diff --git a/src-tauri/src/playback_context/mod.rs b/src-tauri/src/playback_context/mod.rs index d35d3ce83..36cb23cdd 100644 --- a/src-tauri/src/playback_context/mod.rs +++ b/src-tauri/src/playback_context/mod.rs @@ -32,6 +32,7 @@ pub enum ContextType { pub enum ContentSource { Qobuz, Local, + Plex, } /// Playback context - the semantic origin of playback diff --git a/src-tauri/src/plex/mod.rs b/src-tauri/src/plex/mod.rs new file mode 100644 index 000000000..3ef15b8db --- /dev/null +++ b/src-tauri/src/plex/mod.rs @@ -0,0 +1,1269 @@ +//! Plex LAN-only POC integration. +//! +//! This module intentionally avoids transcoding endpoints and uses `/library/parts/.../file...` +//! so playback uses original media bytes served by Plex Media Server. + +use std::collections::hash_map::DefaultHasher; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::time::Duration; + +use reqwest::header::{HeaderMap, HeaderValue}; +use rusqlite::{Connection, params}; +use serde::{Deserialize, Serialize}; +use tauri::State; + +use crate::AppState; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PlexServerInfo { + pub friendly_name: Option, + pub version: Option, + pub machine_identifier: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PlexMusicSection { + pub key: String, + pub title: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PlexTrack { + pub rating_key: String, + pub title: String, + pub artist: Option, + pub album: Option, + pub duration_ms: Option, + pub artwork_path: Option, + pub part_key: Option, + pub container: Option, + pub codec: Option, + pub channels: Option, + pub bitrate_kbps: Option, + pub sampling_rate_hz: Option, + pub bit_depth: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlexPlayResult { + pub rating_key: String, + pub part_key: String, + pub part_url: String, + pub bytes: usize, + pub direct_play_confirmed: bool, + pub content_type: Option, + pub sampling_rate_hz: Option, + pub bit_depth: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlexPinStartResult { + pub pin_id: u64, + pub code: String, + pub auth_url: String, + pub expires_in: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlexPinCheckResult { + pub authorized: bool, + pub expired: bool, + pub auth_token: Option, + pub expires_in: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlexCachedAlbum { + pub id: String, + pub title: String, + pub artist: String, + pub artwork_path: Option, + pub track_count: u32, + pub total_duration_secs: u64, + pub format: String, + pub bit_depth: Option, + pub sample_rate: u32, + pub source: String, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlexCachedTrack { + pub id: u64, + pub rating_key: String, + pub title: String, + pub artist: String, + pub album: String, + pub duration_secs: u64, + pub format: String, + pub bit_depth: Option, + pub sample_rate: u32, + pub artwork_path: Option, + pub source: String, + pub album_key: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +struct PlexPinResponse { + id: u64, + code: String, + #[serde(default)] + auth_token: Option, + #[serde(default)] + expires_in: Option, +} + +#[derive(Debug, Default)] +struct TrackBuilder { + rating_key: Option, + title: Option, + artist: Option, + album: Option, + duration_ms: Option, + artwork_path: Option, + part_key: Option, + container: Option, + codec: Option, + channels: Option, + bitrate_kbps: Option, + sampling_rate_hz: Option, + bit_depth: Option, +} + +fn normalize_base_url(base_url: &str) -> String { + base_url.trim_end_matches('/').to_string() +} + +fn now_epoch_secs() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +fn open_plex_cache_db() -> Result { + let data_dir = dirs::data_dir() + .ok_or("Could not determine data directory")? + .join("qbz"); + std::fs::create_dir_all(&data_dir) + .map_err(|e| format!("Failed to create Plex cache dir: {}", e))?; + + let db_path = data_dir.join("plex_cache.db"); + let conn = Connection::open(db_path) + .map_err(|e| format!("Failed to open Plex cache database: {}", e))?; + + conn.execute_batch( + " + CREATE TABLE IF NOT EXISTS plex_cache_sections ( + section_key TEXT PRIMARY KEY, + title TEXT NOT NULL, + server_id TEXT, + updated_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS plex_cache_tracks ( + rating_key TEXT PRIMARY KEY, + section_key TEXT NOT NULL, + server_id TEXT, + title TEXT NOT NULL, + artist TEXT, + album TEXT, + duration_ms INTEGER, + artwork_path TEXT, + part_key TEXT, + container TEXT, + codec TEXT, + channels INTEGER, + bitrate_kbps INTEGER, + sampling_rate_hz INTEGER, + bit_depth INTEGER, + updated_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_plex_cache_tracks_section ON plex_cache_tracks(section_key); + " + ).map_err(|e| format!("Failed to initialize Plex cache schema: {}", e))?; + + Ok(conn) +} + +fn build_plex_client() -> Result { + let mut headers = HeaderMap::new(); + headers.insert("X-Plex-Product", HeaderValue::from_static("QBZ")); + headers.insert("X-Plex-Version", HeaderValue::from_static("0.1-poc")); + headers.insert("X-Plex-Device", HeaderValue::from_static("QBZ Desktop")); + headers.insert( + "X-Plex-Platform", + HeaderValue::from_static(std::env::consts::OS), + ); + headers.insert( + "X-Plex-Client-Identifier", + HeaderValue::from_static("qbz-plex-lan-poc"), + ); + + reqwest::Client::builder() + .default_headers(headers) + .timeout(Duration::from_secs(120)) + .connect_timeout(Duration::from_secs(8)) + .build() + .map_err(|e| format!("Failed to create Plex HTTP client: {}", e)) +} + +fn build_plex_auth_client(client_identifier: &str) -> Result { + let mut headers = HeaderMap::new(); + headers.insert("X-Plex-Product", HeaderValue::from_static("QBZ")); + headers.insert("X-Plex-Version", HeaderValue::from_static("0.1-poc")); + headers.insert("X-Plex-Device", HeaderValue::from_static("QBZ Desktop")); + headers.insert( + "X-Plex-Platform", + HeaderValue::from_static(std::env::consts::OS), + ); + headers.insert( + "X-Plex-Client-Identifier", + HeaderValue::from_str(client_identifier) + .map_err(|e| format!("Invalid Plex client identifier: {}", e))?, + ); + headers.insert("Accept", HeaderValue::from_static("application/json")); + + reqwest::Client::builder() + .default_headers(headers) + .timeout(Duration::from_secs(20)) + .connect_timeout(Duration::from_secs(8)) + .build() + .map_err(|e| format!("Failed to create Plex auth HTTP client: {}", e)) +} + +fn build_plex_auth_url() -> String { + "https://plex.tv/link".to_string() +} + +fn with_token(url: &str, token: &str) -> String { + let sep = if url.contains('?') { "&" } else { "?" }; + format!("{url}{sep}X-Plex-Token={token}") +} + +fn parse_u64(v: Option) -> Option { + v.and_then(|s| s.parse::().ok()) +} + +fn parse_u32(v: Option) -> Option { + v.and_then(|s| s.parse::().ok()) +} + +fn decode_xml_entities(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + let bytes = input.as_bytes(); + let mut i = 0usize; + + while i < bytes.len() { + if bytes[i] == b'&' { + let mut j = i + 1; + while j < bytes.len() && bytes[j] != b';' && (j - i) <= 12 { + j += 1; + } + + if j < bytes.len() && bytes[j] == b';' { + let entity = &input[i + 1..j]; + let decoded = match entity { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "apos" => Some('\''), + _ if entity.starts_with("#x") || entity.starts_with("#X") => { + u32::from_str_radix(&entity[2..], 16).ok().and_then(char::from_u32) + } + _ if entity.starts_with('#') => { + entity[1..].parse::().ok().and_then(char::from_u32) + } + _ => None, + }; + + if let Some(ch) = decoded { + out.push(ch); + i = j + 1; + continue; + } + } + } + + if let Some(ch) = input[i..].chars().next() { + out.push(ch); + i += ch.len_utf8(); + } else { + break; + } + } + + out +} + +fn normalize_album_title(artist: Option<&str>, album: &str) -> String { + let trimmed_album = album.trim(); + let Some(artist_value) = artist.map(str::trim).filter(|a| !a.is_empty()) else { + return trimmed_album.to_string(); + }; + + for sep in [" - ", " — ", " – ", ": "] { + let prefix = format!("{artist_value}{sep}"); + if trimmed_album.starts_with(&prefix) { + return trimmed_album[prefix.len()..].trim().to_string(); + } + } + + trimmed_album.to_string() +} + +fn get_attr(tag: &str, key: &str) -> Option { + let tag_bytes = tag.as_bytes(); + let key_bytes = key.as_bytes(); + if key_bytes.is_empty() || tag_bytes.len() < key_bytes.len() + 2 { + return None; + } + + let mut i = 0usize; + while i + key_bytes.len() + 2 <= tag_bytes.len() { + if &tag_bytes[i..i + key_bytes.len()] != key_bytes { + i += 1; + continue; + } + + let prev = if i == 0 { b' ' } else { tag_bytes[i - 1] }; + if !prev.is_ascii_whitespace() && prev != b'<' { + i += 1; + continue; + } + + let eq_idx = i + key_bytes.len(); + if eq_idx >= tag_bytes.len() || tag_bytes[eq_idx] != b'=' { + i += 1; + continue; + } + let quote_idx = eq_idx + 1; + if quote_idx >= tag_bytes.len() || tag_bytes[quote_idx] != b'"' { + i += 1; + continue; + } + + let value_start = quote_idx + 1; + let value_rel_end = tag[value_start..].find('"')?; + let value_end = value_start + value_rel_end; + return Some(decode_xml_entities(tag[value_start..value_end].trim())); + } + + None +} + +fn find_first_tag(xml: &str, tag_name: &str) -> Option { + let needle = format!("<{tag_name}"); + let start = xml.find(&needle)?; + let rest = &xml[start..]; + let end = rest.find('>')?; + Some(rest[..=end].to_string()) +} + +fn collect_start_tags(xml: &str, tag_name: &str) -> Vec { + let mut tags = Vec::new(); + let open = format!("<{tag_name}"); + let mut offset = 0usize; + + while let Some(pos) = xml[offset..].find(&open) { + let start = offset + pos; + let rest = &xml[start..]; + let Some(end) = rest.find('>') else { + break; + }; + tags.push(rest[..=end].to_string()); + offset = start + end + 1; + } + + tags +} + +fn collect_tag_blocks(xml: &str, tag_name: &str) -> Vec<(String, String)> { + let mut blocks = Vec::new(); + let open = format!("<{tag_name}"); + let close = format!(""); + let mut offset = 0usize; + + while let Some(pos) = xml[offset..].find(&open) { + let start = offset + pos; + let rest = &xml[start..]; + let Some(open_end_rel) = rest.find('>') else { + break; + }; + let open_end = start + open_end_rel; + let start_tag = &xml[start..=open_end]; + let is_self_closing = start_tag.trim_end().ends_with("/>"); + + if is_self_closing { + blocks.push((start_tag.to_string(), String::new())); + offset = open_end + 1; + continue; + } + + let after_open = open_end + 1; + let Some(close_rel) = xml[after_open..].find(&close) else { + break; + }; + let close_start = after_open + close_rel; + let inner = &xml[after_open..close_start]; + blocks.push((start_tag.to_string(), inner.to_string())); + offset = close_start + close.len(); + } + + blocks +} + +fn parse_server_info(xml: &str) -> PlexServerInfo { + let tag = find_first_tag(xml, "MediaContainer"); + PlexServerInfo { + friendly_name: tag.as_ref().and_then(|t| get_attr(t, "friendlyName")), + version: tag.as_ref().and_then(|t| get_attr(t, "version")), + machine_identifier: tag.as_ref().and_then(|t| get_attr(t, "machineIdentifier")), + } +} + +fn parse_music_sections(xml: &str) -> Vec { + let mut sections = Vec::new(); + for tag in collect_start_tags(xml, "Directory") { + if get_attr(&tag, "type").as_deref() != Some("artist") { + continue; + } + if let (Some(key), Some(title)) = (get_attr(&tag, "key"), get_attr(&tag, "title")) { + sections.push(PlexMusicSection { key, title }); + } + } + sections +} + +fn parse_track_block(start_tag: &str, inner_xml: &str) -> Option { + let mut t = TrackBuilder { + rating_key: get_attr(start_tag, "ratingKey"), + title: get_attr(start_tag, "title"), + artist: get_attr(start_tag, "grandparentTitle") + .or_else(|| get_attr(start_tag, "originalTitle")), + album: get_attr(start_tag, "parentTitle"), + duration_ms: parse_u64(get_attr(start_tag, "duration")), + artwork_path: get_attr(start_tag, "thumb") + .or_else(|| get_attr(start_tag, "parentThumb")) + .or_else(|| get_attr(start_tag, "grandparentThumb")), + ..Default::default() + }; + + if let Some(title) = t.title.as_mut() { + *title = title.trim().to_string(); + } + if let Some(artist) = t.artist.as_mut() { + *artist = artist.trim().to_string(); + } + if let Some(album) = t.album.as_mut() { + let normalized = normalize_album_title(t.artist.as_deref(), album); + *album = normalized; + } + + for media_tag in collect_start_tags(inner_xml, "Media") { + t.container = get_attr(&media_tag, "container"); + t.bitrate_kbps = parse_u32(get_attr(&media_tag, "bitrate")); + t.sampling_rate_hz = parse_u32(get_attr(&media_tag, "samplingRate")); + t.bit_depth = parse_u32(get_attr(&media_tag, "bitDepth")); + break; + } + + // Stream metadata is more accurate for audio details than Media-level fields. + // Prefer selected audio stream when available, otherwise use the first audio stream. + let mut selected_audio_stream: Option = None; + let mut first_audio_stream: Option = None; + for stream_tag in collect_start_tags(inner_xml, "Stream") { + let is_audio = get_attr(&stream_tag, "streamType").as_deref() == Some("2") + || get_attr(&stream_tag, "codecType").as_deref() == Some("audio"); + if !is_audio { + continue; + } + if first_audio_stream.is_none() { + first_audio_stream = Some(stream_tag.clone()); + } + if get_attr(&stream_tag, "selected").as_deref() == Some("1") { + selected_audio_stream = Some(stream_tag); + break; + } + } + + if let Some(stream_tag) = selected_audio_stream.or(first_audio_stream) { + if let Some(codec) = get_attr(&stream_tag, "codec") { + t.codec = Some(codec); + } + if let Some(channels) = parse_u32(get_attr(&stream_tag, "channels")) { + t.channels = Some(channels); + } + if let Some(bitrate) = parse_u32(get_attr(&stream_tag, "bitrate")) { + t.bitrate_kbps = Some(bitrate); + } + if let Some(rate) = parse_u32(get_attr(&stream_tag, "samplingRate")) { + t.sampling_rate_hz = Some(rate); + } + if let Some(depth) = parse_u32(get_attr(&stream_tag, "bitDepth")) { + t.bit_depth = Some(depth); + } + } + + for part_tag in collect_start_tags(inner_xml, "Part") { + t.part_key = get_attr(&part_tag, "key"); + if t.part_key.is_some() { + break; + } + } + + let (Some(rating_key), Some(title)) = (t.rating_key, t.title) else { + return None; + }; + + Some(PlexTrack { + rating_key, + title, + artist: t.artist, + album: t.album, + duration_ms: t.duration_ms, + artwork_path: t.artwork_path, + part_key: t.part_key, + container: t.container, + codec: t.codec, + channels: t.channels, + bitrate_kbps: t.bitrate_kbps, + sampling_rate_hz: t.sampling_rate_hz, + bit_depth: t.bit_depth, + }) +} + +fn parse_tracks(xml: &str, limit: Option) -> Vec { + let mut tracks = Vec::new(); + + for (start_tag, inner_xml) in collect_tag_blocks(xml, "Track") { + if let Some(track) = parse_track_block(&start_tag, &inner_xml) { + tracks.push(track); + if let Some(max) = limit { + if tracks.len() >= max as usize { + break; + } + } + } + } + + tracks +} + +fn synthetic_track_id(rating_key: &str) -> u64 { + let mut hasher = DefaultHasher::new(); + rating_key.hash(&mut hasher); + hasher.finish() +} + +fn playback_track_id(rating_key: &str) -> u64 { + rating_key + .parse::() + .unwrap_or_else(|_| synthetic_track_id(rating_key)) +} + +fn plex_album_key(artist: &str, album: &str) -> String { + let mut hasher = DefaultHasher::new(); + artist.hash(&mut hasher); + "::".hash(&mut hasher); + album.hash(&mut hasher); + format!("plex:{}", hasher.finish()) +} + +fn is_direct_part_key(part_key: &str) -> bool { + part_key.starts_with("/library/parts/") && part_key.contains("/file") +} + +#[tauri::command] +pub async fn plex_ping(base_url: String, token: String) -> Result { + let client = build_plex_client()?; + let base = normalize_base_url(&base_url); + let url = with_token(&format!("{base}/"), &token); + + let xml = client + .get(url) + .send() + .await + .map_err(|e| format!("Plex ping request failed: {}", e))? + .error_for_status() + .map_err(|e| format!("Plex ping status error: {}", e))? + .text() + .await + .map_err(|e| format!("Failed to read Plex ping response: {}", e))?; + + Ok(parse_server_info(&xml)) +} + +#[tauri::command] +pub async fn plex_get_music_sections( + base_url: String, + token: String, +) -> Result, String> { + let client = build_plex_client()?; + let base = normalize_base_url(&base_url); + let url = with_token(&format!("{base}/library/sections"), &token); + + let xml = client + .get(url) + .send() + .await + .map_err(|e| format!("Plex sections request failed: {}", e))? + .error_for_status() + .map_err(|e| format!("Plex sections status error: {}", e))? + .text() + .await + .map_err(|e| format!("Failed to read Plex sections response: {}", e))?; + + Ok(parse_music_sections(&xml)) +} + +#[tauri::command] +pub async fn plex_get_section_tracks( + base_url: String, + token: String, + section_key: String, + limit: Option, +) -> Result, String> { + let client = build_plex_client()?; + let base = normalize_base_url(&base_url); + let list_url = format!("{base}/library/sections/{section_key}/all?type=10"); + let url = with_token(&list_url, &token); + + let xml = client + .get(url) + .send() + .await + .map_err(|e| format!("Plex tracks request failed: {}", e))? + .error_for_status() + .map_err(|e| format!("Plex tracks status error: {}", e))? + .text() + .await + .map_err(|e| format!("Failed to read Plex tracks response: {}", e))?; + + // Treat limit=0 as "no limit" to match frontend semantics. + let effective_limit = limit.filter(|v| *v > 0); + Ok(parse_tracks(&xml, effective_limit)) +} + +#[tauri::command] +pub async fn plex_auth_pin_start(client_identifier: String) -> Result { + let client = build_plex_auth_client(&client_identifier)?; + let pin = client + .post("https://plex.tv/api/v2/pins?strong=false") + .send() + .await + .map_err(|e| format!("Plex auth pin request failed: {}", e))? + .error_for_status() + .map_err(|e| format!("Plex auth pin status error: {}", e))? + .json::() + .await + .map_err(|e| format!("Failed to parse Plex auth pin response: {}", e))?; + + Ok(PlexPinStartResult { + pin_id: pin.id, + code: pin.code.clone(), + auth_url: build_plex_auth_url(), + expires_in: pin.expires_in, + }) +} + +#[tauri::command] +pub async fn plex_auth_pin_check( + client_identifier: String, + pin_id: u64, + code: Option, +) -> Result { + let client = build_plex_auth_client(&client_identifier)?; + let base_url = format!("https://plex.tv/api/v2/pins/{}", pin_id); + let request = if let Some(pin_code) = code { + client.get(format!("{}?code={}", base_url, pin_code)) + } else { + client.get(base_url) + }; + let pin = request + .send() + .await + .map_err(|e| format!("Plex auth pin check request failed: {}", e))? + .error_for_status() + .map_err(|e| format!("Plex auth pin check status error: {}", e))? + .json::() + .await + .map_err(|e| format!("Failed to parse Plex auth pin check response: {}", e))?; + + Ok(PlexPinCheckResult { + authorized: pin.auth_token.is_some(), + expired: pin.expires_in == Some(0), + auth_token: pin.auth_token, + expires_in: pin.expires_in, + }) +} + +#[tauri::command] +pub async fn plex_open_auth_url(url: String) -> Result<(), String> { + open::that(&url).map_err(|e| format!("Failed to open browser: {}", e)) +} + +#[tauri::command] +pub fn plex_cache_get_sections() -> Result, String> { + let conn = open_plex_cache_db()?; + let mut stmt = conn + .prepare( + "SELECT section_key, title + FROM plex_cache_sections + ORDER BY title COLLATE NOCASE", + ) + .map_err(|e| format!("Failed to prepare Plex cache sections query: {}", e))?; + + let rows = stmt + .query_map([], |row| { + Ok(PlexMusicSection { + key: row.get(0)?, + title: row.get(1)?, + }) + }) + .map_err(|e| format!("Failed to query Plex cache sections: {}", e))?; + + let mut sections = Vec::new(); + for row in rows { + sections.push(row.map_err(|e| format!("Failed to read Plex cache section row: {}", e))?); + } + Ok(sections) +} + +#[tauri::command] +pub fn plex_cache_save_sections( + server_id: Option, + sections: Vec, +) -> Result { + let mut conn = open_plex_cache_db()?; + let tx = conn + .transaction() + .map_err(|e| format!("Failed to start Plex cache sections transaction: {}", e))?; + + let now = now_epoch_secs(); + for section in §ions { + tx.execute( + "INSERT INTO plex_cache_sections (section_key, title, server_id, updated_at) + VALUES (?1, ?2, ?3, ?4) + ON CONFLICT(section_key) DO UPDATE SET + title = excluded.title, + server_id = excluded.server_id, + updated_at = excluded.updated_at", + params![section.key, section.title, server_id, now], + ) + .map_err(|e| format!("Failed to upsert Plex cache section: {}", e))?; + } + + tx.commit() + .map_err(|e| format!("Failed to commit Plex cache sections transaction: {}", e))?; + Ok(sections.len()) +} + +#[tauri::command] +pub fn plex_cache_get_tracks( + section_key: Option, + limit: Option, +) -> Result, String> { + let conn = open_plex_cache_db()?; + let max = limit.unwrap_or(200) as i64; + let mut tracks = Vec::new(); + + if let Some(section) = section_key { + let mut stmt = conn + .prepare( + "SELECT rating_key, title, artist, album, duration_ms, artwork_path, part_key, container, + codec, channels, bitrate_kbps, sampling_rate_hz, bit_depth + FROM plex_cache_tracks + WHERE section_key = ?1 + ORDER BY artist COLLATE NOCASE, album COLLATE NOCASE, title COLLATE NOCASE + LIMIT ?2", + ) + .map_err(|e| format!("Failed to prepare Plex cache tracks query: {}", e))?; + let rows = stmt + .query_map(params![section, max], |row| { + Ok(PlexTrack { + rating_key: row.get(0)?, + title: decode_xml_entities(row.get::<_, String>(1)?.trim()), + artist: row + .get::<_, Option>(2)? + .map(|v| decode_xml_entities(v.trim())), + album: row + .get::<_, Option>(3)? + .map(|v| decode_xml_entities(v.trim())), + duration_ms: row.get(4)?, + artwork_path: row.get(5)?, + part_key: row.get(6)?, + container: row.get(7)?, + codec: row.get(8)?, + channels: row.get(9)?, + bitrate_kbps: row.get(10)?, + sampling_rate_hz: row.get(11)?, + bit_depth: row.get(12)?, + }) + }) + .map_err(|e| format!("Failed to query Plex cache tracks: {}", e))?; + for row in rows { + tracks.push(row.map_err(|e| format!("Failed to read Plex cache track row: {}", e))?); + } + } else { + let mut stmt = conn + .prepare( + "SELECT rating_key, title, artist, album, duration_ms, artwork_path, part_key, container, + codec, channels, bitrate_kbps, sampling_rate_hz, bit_depth + FROM plex_cache_tracks + ORDER BY updated_at DESC + LIMIT ?1", + ) + .map_err(|e| format!("Failed to prepare Plex cache tracks query: {}", e))?; + let rows = stmt + .query_map(params![max], |row| { + Ok(PlexTrack { + rating_key: row.get(0)?, + title: decode_xml_entities(row.get::<_, String>(1)?.trim()), + artist: row + .get::<_, Option>(2)? + .map(|v| decode_xml_entities(v.trim())), + album: row + .get::<_, Option>(3)? + .map(|v| decode_xml_entities(v.trim())), + duration_ms: row.get(4)?, + artwork_path: row.get(5)?, + part_key: row.get(6)?, + container: row.get(7)?, + codec: row.get(8)?, + channels: row.get(9)?, + bitrate_kbps: row.get(10)?, + sampling_rate_hz: row.get(11)?, + bit_depth: row.get(12)?, + }) + }) + .map_err(|e| format!("Failed to query Plex cache tracks: {}", e))?; + for row in rows { + tracks.push(row.map_err(|e| format!("Failed to read Plex cache track row: {}", e))?); + } + } + + Ok(tracks) +} + +#[tauri::command] +pub fn plex_cache_get_albums() -> Result, String> { + let conn = open_plex_cache_db()?; + let mut stmt = conn + .prepare( + "SELECT artist, album, duration_ms, artwork_path, container, sampling_rate_hz, bit_depth + FROM plex_cache_tracks", + ) + .map_err(|e| format!("Failed to prepare Plex cache album aggregation query: {}", e))?; + + let rows = stmt + .query_map([], |row| { + Ok(( + row.get::<_, Option>(0)?, + row.get::<_, Option>(1)?, + row.get::<_, Option>(2)?, + row.get::<_, Option>(3)?, + row.get::<_, Option>(4)?, + row.get::<_, Option>(5)?, + row.get::<_, Option>(6)?, + )) + }) + .map_err(|e| format!("Failed to query Plex cache tracks for album aggregation: {}", e))?; + + let mut grouped: HashMap = HashMap::new(); + + for row in rows { + let (artist_opt, album_opt, duration_ms_opt, artwork_path, container, sampling_rate_hz_opt, bit_depth_opt) = + row.map_err(|e| format!("Failed to read Plex cache aggregation row: {}", e))?; + let artist = artist_opt + .map(|v| decode_xml_entities(v.trim())) + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| "Unknown Artist".to_string()); + let album_raw = album_opt + .map(|v| decode_xml_entities(v.trim())) + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| "Unknown Album".to_string()); + let album = normalize_album_title(Some(&artist), &album_raw); + let album_key = plex_album_key(&artist, &album); + + let entry = grouped.entry(album_key.clone()).or_insert_with(|| PlexCachedAlbum { + id: album_key.clone(), + title: album.clone(), + artist: artist.clone(), + artwork_path: artwork_path.clone(), + track_count: 0, + total_duration_secs: 0, + format: container.clone().unwrap_or_else(|| "flac".to_string()), + bit_depth: bit_depth_opt.map(|v| v as u32), + sample_rate: sampling_rate_hz_opt.map(|v| v as u32).unwrap_or(44100), + source: "plex".to_string(), + }); + + entry.track_count += 1; + if let Some(duration_ms) = duration_ms_opt { + entry.total_duration_secs += (duration_ms as u64) / 1000; + } + if entry.artwork_path.is_none() && artwork_path.is_some() { + entry.artwork_path = artwork_path; + } + if let Some(container_value) = container { + if entry.format == "flac" || entry.format.is_empty() { + entry.format = container_value; + } + } + if let Some(rate) = sampling_rate_hz_opt { + let rate_u = rate as u32; + if rate_u > entry.sample_rate { + entry.sample_rate = rate_u; + } + } + if let Some(depth) = bit_depth_opt { + let depth_u = depth as u32; + if depth_u > entry.bit_depth.unwrap_or(0) { + entry.bit_depth = Some(depth_u); + } + } + } + + let mut albums: Vec = grouped.into_values().collect(); + albums.sort_by(|a, b| { + let artist_cmp = a.artist.to_lowercase().cmp(&b.artist.to_lowercase()); + if artist_cmp != std::cmp::Ordering::Equal { + return artist_cmp; + } + a.title.to_lowercase().cmp(&b.title.to_lowercase()) + }); + Ok(albums) +} + +#[tauri::command] +pub fn plex_cache_get_album_tracks(album_key: String) -> Result, String> { + let conn = open_plex_cache_db()?; + let mut stmt = conn + .prepare( + "SELECT rating_key, title, artist, album, duration_ms, container, bit_depth, sampling_rate_hz, artwork_path + FROM plex_cache_tracks + ORDER BY title COLLATE NOCASE", + ) + .map_err(|e| format!("Failed to prepare Plex cache album tracks query: {}", e))?; + + let rows = stmt + .query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, Option>(2)?, + row.get::<_, Option>(3)?, + row.get::<_, Option>(4)?, + row.get::<_, Option>(5)?, + row.get::<_, Option>(6)?, + row.get::<_, Option>(7)?, + row.get::<_, Option>(8)?, + )) + }) + .map_err(|e| format!("Failed to query Plex cache album tracks: {}", e))?; + + let mut tracks = Vec::new(); + for row in rows { + let (rating_key, title, artist_opt, album_opt, duration_ms_opt, container_opt, bit_depth_opt, sampling_rate_opt, artwork_path) = + row.map_err(|e| format!("Failed to read Plex cache album track row: {}", e))?; + let artist = artist_opt + .map(|v| decode_xml_entities(v.trim())) + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| "Unknown Artist".to_string()); + let album_raw = album_opt + .map(|v| decode_xml_entities(v.trim())) + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| "Unknown Album".to_string()); + let album = normalize_album_title(Some(&artist), &album_raw); + if plex_album_key(&artist, &album) != album_key { + continue; + } + tracks.push(PlexCachedTrack { + id: playback_track_id(&rating_key), + rating_key, + title: decode_xml_entities(title.trim()), + artist, + album, + duration_secs: duration_ms_opt.map(|v| (v as u64) / 1000).unwrap_or(0), + format: container_opt.unwrap_or_else(|| "flac".to_string()), + bit_depth: bit_depth_opt.map(|v| v as u32), + sample_rate: sampling_rate_opt.map(|v| v as u32).unwrap_or(44100), + artwork_path, + source: "plex".to_string(), + album_key: album_key.clone(), + }); + } + Ok(tracks) +} + +#[tauri::command] +pub fn plex_cache_search_tracks(query: String, limit: Option) -> Result, String> { + let conn = open_plex_cache_db()?; + let max = limit.unwrap_or(5000) as i64; + let needle = format!("%{}%", query.to_lowercase()); + let mut stmt = conn + .prepare( + "SELECT rating_key, title, artist, album, duration_ms, container, bit_depth, sampling_rate_hz, artwork_path + FROM plex_cache_tracks + WHERE ?1 = '' OR + lower(title) LIKE ?2 OR + lower(COALESCE(artist, '')) LIKE ?2 OR + lower(COALESCE(album, '')) LIKE ?2 + ORDER BY artist COLLATE NOCASE, album COLLATE NOCASE, title COLLATE NOCASE + LIMIT ?3", + ) + .map_err(|e| format!("Failed to prepare Plex cache search query: {}", e))?; + + let rows = stmt + .query_map(params![query.trim(), needle, max], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, Option>(2)?, + row.get::<_, Option>(3)?, + row.get::<_, Option>(4)?, + row.get::<_, Option>(5)?, + row.get::<_, Option>(6)?, + row.get::<_, Option>(7)?, + row.get::<_, Option>(8)?, + )) + }) + .map_err(|e| format!("Failed to query Plex cache search tracks: {}", e))?; + + let mut tracks = Vec::new(); + for row in rows { + let (rating_key, title, artist_opt, album_opt, duration_ms_opt, container_opt, bit_depth_opt, sampling_rate_opt, artwork_path) = + row.map_err(|e| format!("Failed to read Plex cache search row: {}", e))?; + let artist = artist_opt + .map(|v| decode_xml_entities(v.trim())) + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| "Unknown Artist".to_string()); + let album_raw = album_opt + .map(|v| decode_xml_entities(v.trim())) + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| "Unknown Album".to_string()); + let album = normalize_album_title(Some(&artist), &album_raw); + tracks.push(PlexCachedTrack { + id: playback_track_id(&rating_key), + rating_key: rating_key.clone(), + title: decode_xml_entities(title.trim()), + artist: artist.clone(), + album: album.clone(), + duration_secs: duration_ms_opt.map(|v| (v as u64) / 1000).unwrap_or(0), + format: container_opt.unwrap_or_else(|| "flac".to_string()), + bit_depth: bit_depth_opt.map(|v| v as u32), + sample_rate: sampling_rate_opt.map(|v| v as u32).unwrap_or(44100), + artwork_path, + source: "plex".to_string(), + album_key: plex_album_key(&artist, &album), + }); + } + Ok(tracks) +} + +#[tauri::command] +pub fn plex_cache_save_tracks( + server_id: Option, + section_key: String, + tracks: Vec, +) -> Result { + let mut conn = open_plex_cache_db()?; + let tx = conn + .transaction() + .map_err(|e| format!("Failed to start Plex cache tracks transaction: {}", e))?; + + tx.execute( + "DELETE FROM plex_cache_tracks WHERE section_key = ?1", + params![section_key], + ) + .map_err(|e| format!("Failed to clear old Plex cache tracks for section: {}", e))?; + + let now = now_epoch_secs(); + for track in &tracks { + tx.execute( + "INSERT INTO plex_cache_tracks + (rating_key, section_key, server_id, title, artist, album, duration_ms, artwork_path, + part_key, container, codec, channels, bitrate_kbps, sampling_rate_hz, bit_depth, updated_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16) + ON CONFLICT(rating_key) DO UPDATE SET + section_key = excluded.section_key, + server_id = excluded.server_id, + title = excluded.title, + artist = excluded.artist, + album = excluded.album, + duration_ms = excluded.duration_ms, + artwork_path = excluded.artwork_path, + part_key = excluded.part_key, + container = excluded.container, + codec = excluded.codec, + channels = excluded.channels, + bitrate_kbps = excluded.bitrate_kbps, + sampling_rate_hz = excluded.sampling_rate_hz, + bit_depth = excluded.bit_depth, + updated_at = excluded.updated_at", + params![ + track.rating_key, + section_key, + server_id, + track.title, + track.artist, + track.album, + track.duration_ms.map(|v| v as i64), + track.artwork_path, + track.part_key, + track.container, + track.codec, + track.channels.map(|v| v as i64), + track.bitrate_kbps.map(|v| v as i64), + track.sampling_rate_hz.map(|v| v as i64), + track.bit_depth.map(|v| v as i64), + now, + ], + ) + .map_err(|e| format!("Failed to upsert Plex cache track: {}", e))?; + } + + tx.commit() + .map_err(|e| format!("Failed to commit Plex cache tracks transaction: {}", e))?; + Ok(tracks.len()) +} + +#[tauri::command] +pub fn plex_cache_clear() -> Result<(), String> { + let conn = open_plex_cache_db()?; + conn.execute("DELETE FROM plex_cache_tracks", []) + .map_err(|e| format!("Failed to clear Plex cache tracks: {}", e))?; + conn.execute("DELETE FROM plex_cache_sections", []) + .map_err(|e| format!("Failed to clear Plex cache sections: {}", e))?; + Ok(()) +} + +#[tauri::command] +pub async fn plex_play_track( + base_url: String, + token: String, + rating_key: String, + app_state: State<'_, AppState>, +) -> Result { + let client = build_plex_client()?; + let base = normalize_base_url(&base_url); + + let metadata_url = with_token(&format!("{base}/library/metadata/{rating_key}"), &token); + let metadata_xml = client + .get(metadata_url) + .send() + .await + .map_err(|e| format!("Plex metadata request failed: {}", e))? + .error_for_status() + .map_err(|e| format!("Plex metadata status error: {}", e))? + .text() + .await + .map_err(|e| format!("Failed to read Plex metadata response: {}", e))?; + + let mut tracks = parse_tracks(&metadata_xml, Some(1)); + let track = tracks + .pop() + .ok_or_else(|| format!("Track {rating_key} not found in Plex metadata"))?; + + let part_key = track + .part_key + .clone() + .ok_or_else(|| format!("Track {rating_key} does not include a playable Part key"))?; + + let part_url = with_token(&format!("{base}{part_key}"), &token); + let part_response = client + .get(&part_url) + .send() + .await + .map_err(|e| format!("Plex part request failed: {}", e))? + .error_for_status() + .map_err(|e| format!("Plex part status error: {}", e))?; + + let content_type = part_response + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .map(|s| s.to_string()); + + let bytes = part_response + .bytes() + .await + .map_err(|e| format!("Failed to read Plex media bytes: {}", e))?; + + let playback_id = playback_track_id(&rating_key); + app_state + .player + .play_data(bytes.to_vec(), playback_id) + .map_err(|e| format!("Failed to play Plex track: {}", e))?; + + Ok(PlexPlayResult { + rating_key, + part_key: part_key.clone(), + part_url, + bytes: bytes.len(), + direct_play_confirmed: is_direct_part_key(&part_key), + content_type, + sampling_rate_hz: track.sampling_rate_hz, + bit_depth: track.bit_depth, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_music_sections() { + let xml = r#" + + + "#; + let sections = parse_music_sections(xml); + assert_eq!(sections.len(), 1); + assert_eq!(sections[0].key, "1"); + } + + #[test] + fn parses_tracks_with_stream_audio_metadata() { + let xml = r#" + + + + + + + "#; + let tracks = parse_tracks(xml, Some(10)); + assert_eq!(tracks.len(), 1); + assert_eq!(tracks[0].rating_key, "42"); + assert_eq!( + tracks[0].part_key.as_deref(), + Some("/library/parts/999/file.flac") + ); + assert_eq!(tracks[0].artwork_path.as_deref(), Some("/library/metadata/42/thumb/1")); + assert_eq!(tracks[0].sampling_rate_hz, Some(96000)); + assert_eq!(tracks[0].bit_depth, Some(24)); + } + + #[test] + fn direct_part_key_detection() { + assert!(is_direct_part_key("/library/parts/1234/file.flac")); + assert!(!is_direct_part_key("/music/:/transcode/universal/start")); + } + + #[test] + fn playback_track_id_prefers_numeric_rating_key() { + assert_eq!(playback_track_id("48012"), 48012); + } +} diff --git a/src-tauri/src/queue/mod.rs b/src-tauri/src/queue/mod.rs index 147d782af..98d1235c7 100644 --- a/src-tauri/src/queue/mod.rs +++ b/src-tauri/src/queue/mod.rs @@ -33,6 +33,9 @@ pub struct QueueTrack { /// Whether the track is streamable on Qobuz (false = removed/unavailable) #[serde(default = "default_streamable")] pub streamable: bool, + /// Optional origin source (e.g. "qobuz", "local", "plex") + #[serde(default)] + pub source: Option, } fn default_streamable() -> bool { diff --git a/src-tauri/src/session_store/mod.rs b/src-tauri/src/session_store/mod.rs index 903fed019..6798f5f29 100644 --- a/src-tauri/src/session_store/mod.rs +++ b/src-tauri/src/session_store/mod.rs @@ -27,6 +27,8 @@ pub struct PersistedQueueTrack { pub artist_id: Option, #[serde(default = "default_streamable")] pub streamable: bool, + #[serde(default)] + pub source: Option, } /// Represents the full persisted session state @@ -110,7 +112,8 @@ impl SessionStore { artwork_url TEXT, hires INTEGER NOT NULL DEFAULT 0, bit_depth INTEGER, - sample_rate REAL + sample_rate REAL, + source TEXT ); -- Insert default row if not exists @@ -158,6 +161,22 @@ impl SessionStore { ); } + let has_source: bool = conn + .query_row( + "SELECT COUNT(*) FROM pragma_table_info('queue_tracks') WHERE name = 'source'", + [], + |row| row.get(0), + ) + .unwrap_or(0) > 0; + + if !has_source { + let _ = conn.execute_batch( + " + ALTER TABLE queue_tracks ADD COLUMN source TEXT; + " + ); + } + Ok(Self { conn }) } @@ -181,8 +200,8 @@ impl SessionStore { // Insert queue tracks for (pos, track) in session.queue_tracks.iter().enumerate() { if let Err(e) = self.conn.execute( - "INSERT INTO queue_tracks (position, track_id, title, artist, album, duration_secs, artwork_url, hires, bit_depth, sample_rate, is_local, album_id, artist_id) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)", + "INSERT INTO queue_tracks (position, track_id, title, artist, album, duration_secs, artwork_url, hires, bit_depth, sample_rate, is_local, album_id, artist_id, source) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)", params![ pos as i64, track.id as i64, @@ -197,6 +216,7 @@ impl SessionStore { track.is_local as i64, track.album_id, track.artist_id.map(|v| v as i64), + track.source, ], ) { let _ = self.conn.execute("ROLLBACK", []); @@ -258,7 +278,7 @@ impl SessionStore { // Load queue tracks let mut stmt = self.conn - .prepare("SELECT track_id, title, artist, album, duration_secs, artwork_url, hires, bit_depth, sample_rate, is_local, album_id, artist_id FROM queue_tracks ORDER BY position") + .prepare("SELECT track_id, title, artist, album, duration_secs, artwork_url, hires, bit_depth, sample_rate, is_local, album_id, artist_id, source FROM queue_tracks ORDER BY position") .map_err(|e| format!("Failed to prepare queue query: {}", e))?; let tracks: Vec = stmt @@ -277,6 +297,7 @@ impl SessionStore { album_id: row.get(10)?, artist_id: row.get::<_, Option>(11)?.map(|v| v as u64), streamable: true, // Default to true for persisted tracks + source: row.get(12)?, }) }) .map_err(|e| format!("Failed to query queue tracks: {}", e))? diff --git a/src/lib/components/AlbumCard.svelte b/src/lib/components/AlbumCard.svelte index 6c8df70a4..7939d244e 100644 --- a/src/lib/components/AlbumCard.svelte +++ b/src/lib/components/AlbumCard.svelte @@ -35,8 +35,8 @@ onOpenContainingFolder?: () => void; onReDownloadAlbum?: () => void; downloadStateVersion?: number; - /** Source badge for local library: 'user' for local files, 'qobuz_download' for Qobuz offline */ - sourceBadge?: 'user' | 'qobuz_download'; + /** Source badge for local library: 'user' | 'qobuz_download' | 'plex' */ + sourceBadge?: 'user' | 'qobuz_download' | 'plex'; } let { @@ -202,7 +202,7 @@ {#if !imageError && artwork} - {title} + {title} {/if} @@ -262,9 +262,15 @@ {#if sourceBadge} -
+
{#if sourceBadge === 'user'} + {:else if sourceBadge === 'plex'} + Plex {:else} Qobuz {/if} @@ -310,7 +316,7 @@ overflow: hidden; } - .artwork-container img { + .artwork-container .artwork-image { position: absolute; inset: 0; width: 100%; @@ -365,6 +371,7 @@ width: 24px; height: 24px; color: var(--text-secondary); + border-radius: 4px; } .source-badge.local-badge { @@ -378,6 +385,13 @@ height: 24px; } + .source-badge .plex-logo-icon { + width: 18px; + height: 18px; + object-fit: contain; + filter: drop-shadow(0 1px 1px rgba(0, 0, 0, 0.45)); + } + .action-overlay { position: absolute; inset: -1px; diff --git a/src/lib/components/VirtualizedAlbumList.svelte b/src/lib/components/VirtualizedAlbumList.svelte index f06b0ee09..10e005348 100644 --- a/src/lib/components/VirtualizedAlbumList.svelte +++ b/src/lib/components/VirtualizedAlbumList.svelte @@ -17,7 +17,7 @@ bit_depth?: number; sample_rate: number; directory_path: string; - source?: string; // 'user' for local files, 'qobuz_download' for offline cached + source?: string; // 'user' | 'qobuz_download' | 'plex' } interface AlbumGroup { @@ -324,7 +324,7 @@ onPlayNext={() => onAlbumQueueNext(album)} onPlayLater={() => onAlbumQueueLater(album)} onclick={() => onAlbumClick(album)} - sourceBadge={showSourceBadge ? (album.source === 'qobuz_download' ? 'qobuz_download' : 'user') : undefined} + sourceBadge={showSourceBadge ? (album.source === 'plex' ? 'plex' : (album.source === 'qobuz_download' ? 'qobuz_download' : 'user')) : undefined} /> {/each}
diff --git a/src/lib/components/views/HomeView.svelte b/src/lib/components/views/HomeView.svelte index 7a0ffe64a..1fadbfed5 100644 --- a/src/lib/components/views/HomeView.svelte +++ b/src/lib/components/views/HomeView.svelte @@ -912,7 +912,14 @@
diff --git a/src/lib/components/views/LocalLibraryView.svelte b/src/lib/components/views/LocalLibraryView.svelte index 83c96d4c4..18716a624 100644 --- a/src/lib/components/views/LocalLibraryView.svelte +++ b/src/lib/components/views/LocalLibraryView.svelte @@ -72,6 +72,7 @@ artwork_path?: string; last_modified: number; indexed_at: number; + source?: string; // 'user' | 'qobuz_download' | 'plex' } interface LocalAlbum { @@ -88,7 +89,56 @@ bit_depth?: number; sample_rate: number; directory_path: string; - source?: string; // 'user' for local files, 'qobuz_download' for offline cached + source?: string; // 'user' | 'qobuz_download' | 'plex' + } + + interface PlexCachedAlbum { + id: string; + title: string; + artist: string; + artworkPath?: string; + trackCount: number; + totalDurationSecs: number; + format: string; + bitDepth?: number; + sampleRate: number; + source: string; + } + + interface PlexCachedTrack { + id: number; + ratingKey: string; + title: string; + artist: string; + album: string; + durationSecs: number; + format: string; + bitDepth?: number; + sampleRate: number; + artworkPath?: string; + source: string; + albumKey: string; + } + + interface PlexMusicSection { + key: string; + title: string; + } + + interface PlexTrack { + ratingKey: string; + title: string; + artist?: string; + album?: string; + durationMs?: number; + artworkPath?: string; + partKey?: string; + container?: string; + codec?: string; + channels?: number; + bitrateKbps?: number; + samplingRateHz?: number; + bitDepth?: number; } interface LocalArtist { @@ -158,6 +208,8 @@ isPlaybackActive?: boolean; } + const PLEX_METADATA_WRITE_KEY = 'qbz-plex-poc-metadata-write-enabled'; + let { onAlbumClick, onQobuzArtistClick, @@ -319,7 +371,7 @@ if (sourceFiltersActive) { const source = album.source ?? 'user'; - if (filterLocalFiles && source === 'user') passesSource = true; + if (filterLocalFiles && (source === 'user' || source === 'plex')) passesSource = true; if (filterOfflineCache && source === 'qobuz_download') passesSource = true; } @@ -832,6 +884,9 @@ let loading = $state(false); let scanning = $state(false); let error = $state(null); + let plexRepairAttempted = $state(false); + let plexRepairInProgress = $state(false); + let plexRepairQueued = $state(false); let fetchingArtwork = $state(false); let updatingArtwork = $state(false); let hasDiscogsCredentials = $state(false); @@ -971,19 +1026,21 @@ // If not found in loaded albums, we need to fetch album list first if (!album) { - const allAlbums = await invoke('library_get_albums', { - includeHidden: false, - excludeNetworkFolders: shouldExcludeNetworkFolders() - }); + const [localAlbums, plexAlbumsRaw] = await Promise.all([ + invoke('library_get_albums', { + includeHidden: false, + excludeNetworkFolders: shouldExcludeNetworkFolders() + }), + invoke('plex_cache_get_albums').catch(() => []) + ]); + const allAlbums = [...localAlbums, ...plexAlbumsRaw.map(mapPlexAlbum)]; albums = allAlbums; album = allAlbums.find(a => a.id === albumId); } if (album) { selectedAlbum = album; - albumTracks = await invoke('library_get_album_tracks', { - albumGroupKey: album.id - }); + albumTracks = await fetchAlbumTracks(album); } } catch (err) { console.error('Failed to load album:', err); @@ -1035,33 +1092,219 @@ } } - async function loadLibraryData() { - console.log('[LocalLibrary] loadLibraryData START, isOffline:', isOffline); - loading = true; - error = null; + function buildPlexArtworkUrl(path: string): string { + const baseUrl = getUserItem('qbz-plex-poc-base-url') || ''; + const token = getUserItem('qbz-plex-poc-token') || ''; + if (!baseUrl || !token) return path; + const base = baseUrl.replace(/\/+$/, ''); + const separator = path.includes('?') ? '&' : '?'; + return `${base}${path}${separator}X-Plex-Token=${encodeURIComponent(token)}`; + } + + function normalizePlexAlbumTitle(artist: string, album: string): string { + const artistName = artist.trim(); + const albumTitle = album.trim(); + if (!artistName || !albumTitle) return albumTitle; + + for (const sep of [' - ', ' — ', ' – ', ': ']) { + const prefix = `${artistName}${sep}`; + if (albumTitle.startsWith(prefix)) { + return albumTitle.slice(prefix.length).trim(); + } + } + return albumTitle; + } + + function isLikelyLegacyPlexCache(plexAlbums: PlexCachedAlbum[]): boolean { + if (plexAlbums.length < 20) return false; + const suspicious = plexAlbums.filter(album => + album.title.trim().toLowerCase() === album.artist.trim().toLowerCase() + ).length; + return suspicious >= 20 || suspicious / plexAlbums.length >= 0.2; + } + + async function repairLegacyPlexCache(): Promise { + if (plexRepairInProgress) return false; + + const baseUrl = getUserItem('qbz-plex-poc-base-url') || ''; + const token = getUserItem('qbz-plex-poc-token') || ''; + if (!baseUrl || !token) return false; + + plexRepairInProgress = true; + try { + const startedAt = performance.now(); + const sections = await invoke('plex_get_music_sections', { + baseUrl, + token + }); + await invoke('plex_cache_save_sections', { serverId: null, sections }); + + const sectionMetrics = await Promise.all( + sections.map(async (section) => { + const sectionStart = performance.now(); + const sectionTracks = await invoke('plex_get_section_tracks', { + baseUrl, + token, + sectionKey: section.key + }); + await invoke('plex_cache_save_tracks', { + serverId: null, + sectionKey: section.key, + tracks: sectionTracks + }); + return { + key: section.key, + tracks: sectionTracks.length, + ms: performance.now() - sectionStart + }; + }) + ); + + const totalTracks = sectionMetrics.reduce((sum, item) => sum + item.tracks, 0); + const elapsedMs = performance.now() - startedAt; + console.log('[PlexBench] cache repair completed', { + sections: sections.length, + totalTracks, + elapsedMs: Number(elapsedMs.toFixed(1)), + slowestSections: sectionMetrics + .slice() + .sort((a, b) => b.ms - a.ms) + .slice(0, 3) + .map((item) => ({ key: item.key, tracks: item.tracks, ms: Number(item.ms.toFixed(1)) })) + }); + + return true; + } catch (err) { + console.error('[LocalLibrary] Failed to auto-repair Plex cache:', err); + return false; + } finally { + plexRepairInProgress = false; + } + } + + async function queuePlexRepairInBackground() { + if (plexRepairQueued || plexRepairInProgress) return; + plexRepairQueued = true; + try { + const repaired = await repairLegacyPlexCache(); + if (repaired) { + await loadLibraryData({ background: true }); + } + } finally { + plexRepairQueued = false; + } + } + + function mapPlexAlbum(plexAlbum: PlexCachedAlbum): LocalAlbum { + const artist = plexAlbum.artist?.trim() || 'Unknown Artist'; + const title = normalizePlexAlbumTitle(artist, plexAlbum.title || 'Unknown Album'); + return { + id: plexAlbum.id, + title: title || 'Unknown Album', + artist, + artwork_path: plexAlbum.artworkPath, + track_count: plexAlbum.trackCount, + total_duration_secs: plexAlbum.totalDurationSecs, + format: plexAlbum.format, + bit_depth: plexAlbum.bitDepth, + sample_rate: plexAlbum.sampleRate, + directory_path: '', + source: 'plex' + }; + } + + function mapPlexTrack(plexTrack: PlexCachedTrack): LocalTrack { + const artist = plexTrack.artist?.trim() || 'Unknown Artist'; + const album = normalizePlexAlbumTitle(artist, plexTrack.album || 'Unknown Album'); + return { + id: plexTrack.id, + file_path: plexTrack.ratingKey, + title: plexTrack.title, + artist, + album: album || 'Unknown Album', + album_artist: artist, + album_group_key: plexTrack.albumKey, + album_group_title: album || 'Unknown Album', + track_number: undefined, + disc_number: undefined, + duration_secs: plexTrack.durationSecs, + format: plexTrack.format, + bit_depth: plexTrack.bitDepth, + sample_rate: plexTrack.sampleRate, + channels: 2, + file_size_bytes: 0, + artwork_path: plexTrack.artworkPath, + last_modified: 0, + indexed_at: 0, + source: 'plex' + }; + } + + async function loadLibraryData(options: { background?: boolean } = {}) { + const background = options.background === true; + const startedAt = performance.now(); + console.log('[LocalLibrary] loadLibraryData START, isOffline:', isOffline, 'background:', background); + if (!background) { + loading = true; + error = null; + } try { const excludeNetwork = shouldExcludeNetworkFolders(); console.log('[LocalLibrary] Calling library_get_albums with excludeNetwork:', excludeNetwork); - const albumsResult = await invoke('library_get_albums', { - includeHidden: false, - excludeNetworkFolders: excludeNetwork - }); - console.log('[LocalLibrary] Received albums:', albumsResult.length); - - console.log('[LocalLibrary] Calling library_get_stats'); - const statsResult = await invoke('library_get_stats'); + const fetchStart = performance.now(); + const [albumsResult, statsResult, plexAlbumsRaw] = await Promise.all([ + invoke('library_get_albums', { + includeHidden: false, + excludeNetworkFolders: excludeNetwork + }), + invoke('library_get_stats'), + invoke('plex_cache_get_albums').catch(() => []) + ]); + const fetchMs = performance.now() - fetchStart; + let workingPlexAlbumsRaw = plexAlbumsRaw; + const shouldAttemptRepair = + !plexRepairAttempted && + (isLikelyLegacyPlexCache(workingPlexAlbumsRaw) || workingPlexAlbumsRaw.length <= 1); + if (shouldAttemptRepair) { + plexRepairAttempted = true; + void queuePlexRepairInBackground(); + } + const mapStart = performance.now(); + const plexAlbums = workingPlexAlbumsRaw.map(mapPlexAlbum); + const mapMs = performance.now() - mapStart; + console.log('[LocalLibrary] Received albums:', albumsResult.length, 'plex albums:', plexAlbums.length); console.log('[LocalLibrary] Received stats:', statsResult); - albums = albumsResult; - stats = statsResult; - console.log('[LocalLibrary] loadLibraryData COMPLETE'); + const plexTrackCount = plexAlbums.reduce((sum, album) => sum + album.track_count, 0); + const plexDurationSecs = plexAlbums.reduce((sum, album) => sum + album.total_duration_secs, 0); + + albums = [...albumsResult, ...plexAlbums]; + stats = { + ...statsResult, + track_count: statsResult.track_count + plexTrackCount, + album_count: statsResult.album_count + plexAlbums.length, + total_duration_secs: statsResult.total_duration_secs + plexDurationSecs + }; + console.log('[PlexBench] loadLibraryData', { + background, + localAlbums: albumsResult.length, + plexAlbums: plexAlbums.length, + fetchMs: Number(fetchMs.toFixed(1)), + mapMs: Number(mapMs.toFixed(1)), + totalMs: Number((performance.now() - startedAt).toFixed(1)), + repairQueued: shouldAttemptRepair + }); } catch (err) { console.error('[LocalLibrary] Failed to load library:', err); - error = String(err); + if (!background) { + error = String(err); + } } finally { - console.log('[LocalLibrary] Setting loading = false'); - loading = false; + if (!background) { + console.log('[LocalLibrary] Setting loading = false'); + loading = false; + } } } @@ -1122,11 +1365,44 @@ console.log('[LocalLibrary] loadArtists START'); loading = true; try { - console.log('[LocalLibrary] Calling library_get_artists'); - artists = await invoke('library_get_artists', { - excludeNetworkFolders: shouldExcludeNetworkFolders() - }); - console.log('[LocalLibrary] Received artists:', artists.length); + console.log('[LocalLibrary] Calling library_get_artists + plex_cache_get_albums'); + const [localArtists, plexAlbumsRaw] = await Promise.all([ + invoke('library_get_artists', { + excludeNetworkFolders: shouldExcludeNetworkFolders() + }), + invoke('plex_cache_get_albums').catch(() => []) + ]); + + const plexArtistMap = new Map(); + for (const rawAlbum of plexAlbumsRaw) { + const name = (rawAlbum.artist || '').trim(); + if (!name) continue; + const current = plexArtistMap.get(name) ?? { albumCount: 0, trackCount: 0 }; + current.albumCount += 1; + current.trackCount += rawAlbum.trackCount ?? 0; + plexArtistMap.set(name, current); + } + + const mergedArtistMap = new Map(); + for (const localArtist of localArtists) { + mergedArtistMap.set(localArtist.name, { ...localArtist }); + } + for (const [name, metrics] of plexArtistMap) { + const existing = mergedArtistMap.get(name); + if (existing) { + existing.album_count += metrics.albumCount; + existing.track_count += metrics.trackCount; + } else { + mergedArtistMap.set(name, { + name, + album_count: metrics.albumCount, + track_count: metrics.trackCount + }); + } + } + + artists = Array.from(mergedArtistMap.values()).sort((a, b) => a.name.localeCompare(b.name)); + console.log('[LocalLibrary] Received artists:', artists.length, 'local:', localArtists.length, 'plex:', plexArtistMap.size); // Load cached artist images from database await loadCachedArtistImages(); // Fetch missing images in background if enabled @@ -1147,13 +1423,19 @@ console.log('[LocalLibrary] loadTracks START, query:', query); loading = true; try { - console.log('[LocalLibrary] Calling library_search'); - tracks = await invoke('library_search', { - query, - limit: 0, // 0 = no limit, virtualization handles any list size - excludeNetworkFolders: shouldExcludeNetworkFolders() - }); - console.log('[LocalLibrary] Received tracks:', tracks.length); + console.log('[LocalLibrary] Calling library_search + plex_cache_search_tracks'); + const [localTracks, plexTracksRaw] = await Promise.all([ + invoke('library_search', { + query, + limit: 0, // 0 = no limit, virtualization handles any list size + excludeNetworkFolders: shouldExcludeNetworkFolders() + }), + invoke('plex_cache_search_tracks', { + query + }).catch(() => []) + ]); + tracks = [...localTracks, ...plexTracksRaw.map(mapPlexTrack)]; + console.log('[LocalLibrary] Received tracks:', tracks.length, 'local:', localTracks.length, 'plex:', plexTracksRaw.length); } catch (err) { console.error('[LocalLibrary] Failed to load tracks:', err); error = String(err); @@ -1505,9 +1787,7 @@ // Also load album data immediately for responsive UI selectedAlbum = album; try { - albumTracks = await invoke('library_get_album_tracks', { - albumGroupKey: album.id - }); + albumTracks = await fetchAlbumTracks(album); } catch (err) { console.error('Failed to load album tracks:', err); } @@ -1541,6 +1821,7 @@ async function handleTrackPlay(track: LocalTrack) { try { + const trackSource = track.source === 'plex' ? 'plex' : 'local'; if (selectedAlbum && albumTracks.length > 0) { const trackIndex = albumTracks.findIndex(t => t.id === track.id); const trackIds = albumTracks.map(t => t.id); @@ -1550,7 +1831,7 @@ 'local_library', selectedAlbum.id, selectedAlbum.title, - 'local', + selectedAlbum.source === 'plex' ? 'plex' : 'local', trackIds, trackIndex >= 0 ? trackIndex : 0 ); @@ -1558,24 +1839,30 @@ await setQueueForAlbumTracks(albumTracks, trackIndex >= 0 ? trackIndex : 0); } else if (activeTab === 'tracks' && tracks.length > 0) { const orderedTracks = getDisplayedTrackOrder(); - const trackIndex = orderedTracks.findIndex(t => t.id === track.id); - const trackIds = orderedTracks.map(t => t.id); + const sameSourceTracks = orderedTracks.filter(item => (item.source === 'plex') === (trackSource === 'plex')); + const trackIndex = sameSourceTracks.findIndex(item => item.id === track.id); + const trackIds = sameSourceTracks.map(item => item.id); // Set playback context for Local Library tracks view await setPlaybackContext( 'local_library', - 'local-tracks', + trackSource === 'plex' ? 'plex-tracks' : 'local-tracks', 'Local Tracks', - 'local', + trackSource, trackIds, trackIndex >= 0 ? trackIndex : 0 ); - await setQueueForLocalTracks(orderedTracks, trackIndex >= 0 ? trackIndex : 0); + await setQueueForLocalTracks(sameSourceTracks, trackIndex >= 0 ? trackIndex : 0); } - await invoke('library_play_track', { trackId: track.id }); - onTrackPlay?.(track); + if (onTrackPlay) { + await Promise.resolve(onTrackPlay(track)); + } else if (trackSource === 'local') { + await invoke('library_play_track', { trackId: track.id }); + } else { + throw new Error('Plex playback handler not available'); + } } catch (err) { console.error('Failed to play track:', err); alert(`Failed to play: ${err}`); @@ -1616,6 +1903,13 @@ async function fetchAlbumTracks(album: LocalAlbum): Promise { try { + if (album.source === 'plex') { + const plexTracks = await invoke('plex_cache_get_album_tracks', { + albumKey: album.id + }); + return plexTracks.map(mapPlexTrack); + } + return await invoke('library_get_album_tracks', { albumGroupKey: album.id }); @@ -1629,6 +1923,7 @@ console.log('[LocalLibrary Queue] Setting queue with', tracks.length, 'tracks, startIndex:', startIndex); const queueTracks = tracks.map(t => ({ + source: t.source === 'plex' ? 'plex' : 'local', id: t.id, title: t.title, artist: t.artist, @@ -1638,7 +1933,7 @@ hires: (t.bit_depth && t.bit_depth > 16) || t.sample_rate > 44100, bit_depth: t.bit_depth ?? null, sample_rate: t.sample_rate ?? null, - is_local: true, + is_local: t.source !== 'plex', album_id: null, // Local tracks don't have Qobuz IDs artist_id: null, })); @@ -1647,7 +1942,7 @@ console.log('[LocalLibrary Queue] Track IDs:', queueTracks.map(t => t.id)); await invoke('set_queue', { tracks: queueTracks, startIndex }); - onSetLocalQueue?.(tracks.map(t => t.id)); + onSetLocalQueue?.(tracks.filter(t => t.source !== 'plex').map(t => t.id)); console.log('[LocalLibrary Queue] Queue set successfully'); } @@ -1724,6 +2019,10 @@ function openAlbumEditModal() { if (!selectedAlbum) return; + if (selectedAlbum.source === 'plex' && getUserItem(PLEX_METADATA_WRITE_KEY) !== 'true') { + showToast($t('settings.integrations.plexWriteDisabledNotice'), 'info'); + return; + } editingAlbumHidden = false; albumMetadataRefreshed = false; discogsImageOptions = []; @@ -1959,6 +2258,8 @@ function getArtworkUrl(path?: string): string { if (!path) return ''; + if (/^https?:\/\//i.test(path)) return path; + if (path.startsWith('/library/')) return buildPlexArtworkUrl(path); // For grid/list views, prefer thumbnails const cachedThumb = thumbnailUrlCache.get(path); @@ -1991,6 +2292,8 @@ // For album detail view, always use full resolution function getFullArtworkUrl(path?: string): string { if (!path) return ''; + if (/^https?:\/\//i.test(path)) return path; + if (path.startsWith('/library/')) return buildPlexArtworkUrl(path); const cached = artworkUrlCache.get(path); if (cached) return cached; const url = convertFileSrc(path); @@ -2590,7 +2893,14 @@ {$t('library.backToLibrary')} - @@ -2675,7 +2985,7 @@ onPlayNow: () => handleTrackPlay(track), onPlayNext: onTrackPlayNext ? () => onTrackPlayNext(track) : undefined, onPlayLater: onTrackPlayLater ? () => onTrackPlayLater(track) : undefined, - onAddToPlaylist: onTrackAddToPlaylist ? () => onTrackAddToPlaylist(track.id) : undefined + onAddToPlaylist: onTrackAddToPlaylist && track.source !== 'plex' ? () => onTrackAddToPlaylist(track.id) : undefined }} /> {/each} @@ -3364,7 +3674,7 @@ onPlayNext={() => handleAlbumQueueNextFromGrid(album)} onPlayLater={() => handleAlbumQueueLaterFromGrid(album)} onclick={() => handleAlbumClick(album)} - sourceBadge={album.source === 'qobuz_download' ? 'qobuz_download' : 'user'} + sourceBadge={album.source === 'plex' ? 'plex' : (album.source === 'qobuz_download' ? 'qobuz_download' : 'user')} /> {/each} diff --git a/src/lib/components/views/SettingsView.svelte b/src/lib/components/views/SettingsView.svelte index 222074fc8..c72efbd06 100644 --- a/src/lib/components/views/SettingsView.svelte +++ b/src/lib/components/views/SettingsView.svelte @@ -133,6 +133,42 @@ url: string; } + interface PlexServerInfo { + friendlyName?: string | null; + version?: string | null; + machineIdentifier?: string | null; + } + + interface PlexMusicSection { + key: string; + title: string; + } + + interface PlexPinStartResult { + pinId: number; + code: string; + authUrl: string; + expiresIn?: number | null; + } + + interface PlexPinCheckResult { + authorized: boolean; + expired: boolean; + authToken?: string | null; + expiresIn?: number | null; + } + + interface PlexTrack { + ratingKey: string; + title: string; + artist?: string | null; + album?: string | null; + durationMs?: number | null; + artworkPath?: string | null; + bitDepth?: number | null; + samplingRateHz?: number | null; + } + let { onBack, onLogout, @@ -694,6 +730,29 @@ let showRemoteControlGuide = $state(false); let remoteControlCollapsed = $state(true); + // Plex LAN POC state + let plexBaseUrl = $state(getUserItem('qbz-plex-poc-base-url') || 'http://127.0.0.1:32400'); + let plexToken = $state(getUserItem('qbz-plex-poc-token') || ''); + let plexMetadataWriteEnabled = $state(getUserItem('qbz-plex-poc-metadata-write-enabled') === 'true'); + let plexSections = $state([]); + let plexTracks = $state([]); + let plexSelectedSectionKey = $state(''); + let plexStatusKey = $state('settings.integrations.plexStatusIdle'); + let plexStatusValues = $state>({}); + let plexBusy = $state(false); + let plexLastError = $state(''); + let plexAuthBusy = $state(false); + let plexAuthPinId = $state(null); + let plexAuthCode = $state(''); + let plexAuthUrl = $state(''); + let plexAuthClientId = $state(getUserItem('qbz-plex-poc-client-id') || ''); + let plexAuthPollTimer: ReturnType | null = null; + + const PLEX_CACHE_SELECTED_SECTION_KEY = 'qbz-plex-poc-selected-section'; + const PLEX_CACHE_SERVER_ID_KEY = 'qbz-plex-poc-machine-id'; + const PLEX_CLIENT_ID_KEY = 'qbz-plex-poc-client-id'; + const PLEX_METADATA_WRITE_KEY = 'qbz-plex-poc-metadata-write-enabled'; + // Load saved settings on mount onMount(() => { // Load theme @@ -772,6 +831,10 @@ // Load remote control status loadRemoteControlStatus(); + // Warm-start Plex panel from local cache and refresh in background + void loadPlexCachedState(); + void refreshPlexInBackground(); + // Load notification preferences loadToastsPreference(); toastsEnabled = getToastsEnabled(); @@ -839,6 +902,9 @@ settingsViewEl?.addEventListener('scroll', handleScroll); return () => { + if (plexAuthPollTimer) { + clearInterval(plexAuthPollTimer); + } unsubscribeOffline(); unsubscribeZoom(); unsubscribeTitleBar(); @@ -1050,6 +1116,336 @@ } } + function persistPlexConfig() { + setUserItem('qbz-plex-poc-base-url', plexBaseUrl.trim()); + setUserItem('qbz-plex-poc-token', plexToken.trim()); + } + + function handlePlexMetadataWriteToggle(enabled: boolean) { + plexMetadataWriteEnabled = enabled; + setUserItem(PLEX_METADATA_WRITE_KEY, enabled ? 'true' : 'false'); + } + + function ensurePlexClientId(): string { + if (plexAuthClientId) return plexAuthClientId; + const generated = (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') + ? `qbz-${crypto.randomUUID()}` + : `qbz-${Date.now()}-${Math.floor(Math.random() * 1_000_000)}`; + plexAuthClientId = generated; + setUserItem(PLEX_CLIENT_ID_KEY, generated); + return generated; + } + + async function handlePlexConnectEasy() { + if (plexAuthBusy) return; + plexAuthBusy = true; + plexLastError = ''; + try { + const clientIdentifier = ensurePlexClientId(); + const pin = await invoke('plex_auth_pin_start', { + clientIdentifier + }); + plexAuthPinId = pin.pinId; + plexAuthCode = pin.code; + plexAuthUrl = pin.authUrl; + plexStatusKey = 'settings.integrations.plexStatusAuthPending'; + plexStatusValues = { code: pin.code }; + + if (plexAuthPollTimer) { + clearInterval(plexAuthPollTimer); + } + + plexAuthPollTimer = setInterval(async () => { + if (!plexAuthPinId) return; + try { + const check = await invoke('plex_auth_pin_check', { + clientIdentifier, + pinId: plexAuthPinId, + code: plexAuthCode || null + }); + if (check.authorized && check.authToken) { + plexToken = check.authToken; + persistPlexConfig(); + plexStatusKey = 'settings.integrations.plexStatusAuthConnected'; + plexStatusValues = {}; + if (plexAuthPollTimer) { + clearInterval(plexAuthPollTimer); + plexAuthPollTimer = null; + } + plexAuthPinId = null; + plexAuthCode = ''; + void handlePlexPing(); + } else if (check.expired) { + plexStatusKey = 'settings.integrations.plexStatusAuthExpired'; + plexStatusValues = {}; + if (plexAuthPollTimer) { + clearInterval(plexAuthPollTimer); + plexAuthPollTimer = null; + } + plexAuthPinId = null; + plexAuthCode = ''; + } + } catch (error) { + console.warn('Plex auth polling failed:', error); + } + }, 2500); + } catch (error) { + console.error('Failed starting Plex easy connect:', error); + setPlexError(error); + } finally { + plexAuthBusy = false; + } + } + + function handleOpenPlexAuthUrl() { + if (!plexAuthUrl) return; + invoke('plex_open_auth_url', { url: plexAuthUrl }).catch((error) => { + console.error('Failed opening Plex auth URL:', error); + setPlexError(error); + }); + } + + async function handleCopyPlexCode() { + if (!plexAuthCode) return; + try { + await copyToClipboard(plexAuthCode); + showToast(get(t)('settings.integrations.plexCodeCopied'), 'success'); + } catch (error) { + console.error('Failed copying Plex code:', error); + showToast(get(t)('settings.integrations.plexCodeCopyFailed'), 'error'); + } + } + + async function handlePlexDisconnect() { + const confirmed = await ask(get(t)('settings.integrations.plexDisconnectConfirmDesc'), { + title: get(t)('settings.integrations.plexDisconnectConfirmTitle'), + kind: 'warning', + okLabel: get(t)('settings.integrations.plexDisconnectConfirmOk'), + cancelLabel: get(t)('actions.cancel') + }); + if (!confirmed) return; + + if (plexAuthPollTimer) { + clearInterval(plexAuthPollTimer); + plexAuthPollTimer = null; + } + + plexAuthPinId = null; + plexAuthCode = ''; + plexAuthUrl = ''; + plexAuthBusy = false; + plexToken = ''; + plexSections = []; + plexTracks = []; + plexSelectedSectionKey = ''; + plexStatusKey = 'settings.integrations.plexStatusDisconnected'; + plexStatusValues = {}; + plexLastError = ''; + + removeUserItem('qbz-plex-poc-token'); + removeUserItem(PLEX_CACHE_SELECTED_SECTION_KEY); + removeUserItem(PLEX_CACHE_SERVER_ID_KEY); + + try { + await invoke('plex_cache_clear'); + } catch (error) { + console.warn('Failed clearing Plex cache:', error); + } + } + + async function handlePlexClearCache() { + const confirmed = await ask(get(t)('settings.integrations.plexClearCacheConfirmDesc'), { + title: get(t)('settings.integrations.plexClearCacheConfirmTitle'), + kind: 'warning', + okLabel: get(t)('settings.integrations.plexClearCacheConfirmOk'), + cancelLabel: get(t)('actions.cancel') + }); + if (!confirmed) return; + + try { + await invoke('plex_cache_clear'); + plexSections = []; + plexTracks = []; + plexSelectedSectionKey = ''; + plexStatusKey = 'settings.integrations.plexStatusCacheCleared'; + plexStatusValues = {}; + plexLastError = ''; + removeUserItem(PLEX_CACHE_SELECTED_SECTION_KEY); + removeUserItem(PLEX_CACHE_SERVER_ID_KEY); + } catch (error) { + console.error('Failed clearing Plex cache:', error); + setPlexError(error); + } + } + + async function loadPlexCachedState() { + try { + const cachedSections = await invoke('plex_cache_get_sections'); + if (Array.isArray(cachedSections) && cachedSections.length > 0) { + plexSections = cachedSections; + } + + const cachedSelectedSection = getUserItem(PLEX_CACHE_SELECTED_SECTION_KEY); + if (cachedSelectedSection) { + plexSelectedSectionKey = cachedSelectedSection; + } + + const cachedTracks = await invoke('plex_cache_get_tracks', { + sectionKey: plexSelectedSectionKey || null + }); + if (Array.isArray(cachedTracks) && cachedTracks.length > 0) { + plexTracks = cachedTracks; + plexStatusKey = 'settings.integrations.plexStatusCacheLoaded'; + plexStatusValues = { count: cachedTracks.length }; + } + } catch (error) { + console.warn('Failed to load Plex cached state:', error); + } + } + + async function refreshPlexInBackground() { + if (!plexBaseUrl.trim() || !plexToken.trim()) return; + try { + const info = await invoke('plex_ping', { + baseUrl: plexBaseUrl.trim(), + token: plexToken.trim() + }); + if (info.machineIdentifier) { + setUserItem(PLEX_CACHE_SERVER_ID_KEY, info.machineIdentifier); + } + + const sections = await invoke('plex_get_music_sections', { + baseUrl: plexBaseUrl.trim(), + token: plexToken.trim() + }); + plexSections = sections; + await invoke('plex_cache_save_sections', { + serverId: info.machineIdentifier ?? null, + sections + }); + + if (sections.length > 0 && !sections.some((section) => section.key === plexSelectedSectionKey)) { + plexSelectedSectionKey = sections[0].key; + } + if (plexSelectedSectionKey) { + setUserItem(PLEX_CACHE_SELECTED_SECTION_KEY, plexSelectedSectionKey); + } + + if (!plexSelectedSectionKey) return; + + const tracks = await invoke('plex_get_section_tracks', { + baseUrl: plexBaseUrl.trim(), + token: plexToken.trim(), + sectionKey: plexSelectedSectionKey + }); + plexTracks = tracks; + await invoke('plex_cache_save_tracks', { + serverId: info.machineIdentifier ?? (getUserItem(PLEX_CACHE_SERVER_ID_KEY) || null), + sectionKey: plexSelectedSectionKey, + tracks + }); + plexStatusKey = 'settings.integrations.plexStatusTracksLoaded'; + plexStatusValues = { count: tracks.length }; + } catch (error) { + console.warn('Plex background refresh failed:', error); + // Keep cached data visible; only surface error if nothing cached is available. + if (plexTracks.length === 0) { + setPlexError(error); + } + } + } + + function setPlexError(error: unknown) { + const message = String(error); + plexLastError = message; + plexStatusKey = 'settings.integrations.plexStatusError'; + plexStatusValues = { error: message }; + } + + async function handlePlexPing() { + if (!plexBaseUrl.trim() || !plexToken.trim()) return; + plexBusy = true; + plexLastError = ''; + persistPlexConfig(); + try { + const info = await invoke('plex_ping', { + baseUrl: plexBaseUrl.trim(), + token: plexToken.trim() + }); + if (info.machineIdentifier) { + setUserItem(PLEX_CACHE_SERVER_ID_KEY, info.machineIdentifier); + } + plexStatusKey = 'settings.integrations.plexStatusConnected'; + plexStatusValues = { + server: info.friendlyName || info.machineIdentifier || 'Plex', + version: info.version || '?' + }; + } catch (error) { + console.error('Failed Plex ping:', error); + setPlexError(error); + } finally { + plexBusy = false; + } + } + + async function handlePlexLoadSections() { + if (!plexBaseUrl.trim() || !plexToken.trim()) return; + plexBusy = true; + plexLastError = ''; + persistPlexConfig(); + try { + const sections = await invoke('plex_get_music_sections', { + baseUrl: plexBaseUrl.trim(), + token: plexToken.trim() + }); + plexSections = sections; + await invoke('plex_cache_save_sections', { + serverId: getUserItem(PLEX_CACHE_SERVER_ID_KEY) || null, + sections + }); + if (sections.length > 0 && !sections.some((section) => section.key === plexSelectedSectionKey)) { + plexSelectedSectionKey = sections[0].key; + } + if (plexSelectedSectionKey) { + setUserItem(PLEX_CACHE_SELECTED_SECTION_KEY, plexSelectedSectionKey); + } + plexStatusKey = 'settings.integrations.plexStatusSectionsLoaded'; + plexStatusValues = { count: sections.length }; + } catch (error) { + console.error('Failed loading Plex sections:', error); + setPlexError(error); + } finally { + plexBusy = false; + } + } + + async function handlePlexLoadTracks() { + if (!plexBaseUrl.trim() || !plexToken.trim() || !plexSelectedSectionKey) return; + plexBusy = true; + plexLastError = ''; + persistPlexConfig(); + try { + const tracks = await invoke('plex_get_section_tracks', { + baseUrl: plexBaseUrl.trim(), + token: plexToken.trim(), + sectionKey: plexSelectedSectionKey + }); + plexTracks = tracks; + await invoke('plex_cache_save_tracks', { + serverId: getUserItem(PLEX_CACHE_SERVER_ID_KEY) || null, + sectionKey: plexSelectedSectionKey, + tracks + }); + plexStatusKey = 'settings.integrations.plexStatusTracksLoaded'; + plexStatusValues = { count: tracks.length }; + } catch (error) { + console.error('Failed loading Plex tracks:', error); + setPlexError(error); + } finally { + plexBusy = false; + } + } + async function loadRemoteControlStatus() { try { const status = await invoke('remote_control_get_status'); @@ -2851,7 +3247,7 @@ {/if} -
+
{$t('settings.integrations.musicbrainz')} @@ -2860,6 +3256,117 @@
+ +
+
+ {$t('settings.integrations.plexPoc')} + {$t('settings.integrations.plexPocDesc')} +
+ {$t('settings.integrations.plexLibraryIntegrationNote')} + {$t('settings.integrations.plexLocalOnlyDirectPlayNote')} +
+
+ {$t('settings.integrations.plexMetadataWrite')} + {$t('settings.integrations.plexMetadataWriteDesc')} +
+ +
+ +
+
+ {$t('settings.integrations.plexEasyConnectTitle')} + {$t('settings.integrations.plexEasyConnectDesc')} +
+ +
+ + {#if plexAuthUrl} + + {/if} + + +
+ + {#if plexAuthCode} +
+ {$t('settings.integrations.plexCodeLabel')} +
{plexAuthCode}
+
+ +
+
+ {/if} +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ {$t('settings.integrations.plexMusicSection')} +
+ + +
+
+ + {$t(plexStatusKey, { values: plexStatusValues })} + {#if plexLastError} + {plexLastError} + {/if} +
@@ -4390,6 +4897,73 @@ flatpak override --user --filesystem=/home/USUARIO/Música com.blitzfc.qbz word-break: break-all; } + .plex-poc-panel { + margin-top: 10px; + display: grid; + gap: 10px; + } + + .plex-actions { + display: flex; + gap: 8px; + flex-wrap: wrap; + } + + .plex-inline-row { + margin-top: 2px; + margin-bottom: 2px; + padding-top: 0; + padding-bottom: 0; + } + + .plex-connect-wizard { + display: grid; + gap: 10px; + padding: 12px; + border: 1px solid var(--border-subtle); + border-radius: 10px; + background: var(--bg-secondary); + } + + .plex-wizard-header { + display: grid; + gap: 4px; + } + + .plex-code-card { + display: grid; + gap: 10px; + padding: 14px; + border-radius: 10px; + border: 1px solid var(--accent-primary); + background: color-mix(in srgb, var(--accent-primary) 10%, var(--bg-tertiary)); + } + + .plex-code-value { + font-family: 'JetBrains Mono', 'Fira Code', monospace; + font-size: 32px; + line-height: 1; + letter-spacing: 0.16em; + font-weight: 700; + color: var(--text-primary); + } + + .plex-section-controls { + display: flex; + align-items: center; + gap: 8px; + } + + .plex-section-select { + min-width: 240px; + width: 240px; + } + + .plex-error-note { + color: #fca5a5; + word-break: break-word; + } + { const { isLocal = false, + source = isLocal ? 'local' : 'qobuz', showLoadingToast = true, showSuccessToast = true, gaplessTransition = false @@ -154,7 +162,27 @@ export async function playTrack( }); } else { // Use appropriate local playback command - if (isLocal) { + if (source === 'plex') { + const plexBaseUrl = getUserItem('qbz-plex-poc-base-url') || ''; + const plexToken = getUserItem('qbz-plex-poc-token') || ''; + if (!plexBaseUrl || !plexToken) { + throw new Error('Missing Plex base URL or token'); + } + const result = await invoke('plex_play_track', { + baseUrl: plexBaseUrl, + token: plexToken, + ratingKey: String(track.id) + }); + + // Plex metadata endpoint provides stream audio details even when queue list did not. + if (result.sampling_rate_hz && result.sampling_rate_hz > 0) { + track.samplingRate = result.sampling_rate_hz / 1000; + } + if (result.bit_depth && result.bit_depth > 0) { + track.bitDepth = result.bit_depth; + } + setCurrentTrack(track); + } else if (isLocal) { await invoke('library_play_track', { trackId: track.id }); } else { const result = await invoke('play_track', { @@ -181,7 +209,7 @@ export async function playTrack( } // Log play event for recommendations (fire-and-forget) - if (!isLocal) { + if (!isLocal && source !== 'plex') { void logRecoEvent({ eventType: 'play', itemType: 'track', @@ -224,7 +252,7 @@ export async function playTrack( ); // Check favorite status (only for Qobuz tracks) - if (!isLocal) { + if (!isLocal && source !== 'plex') { const isFav = await checkTrackFavorite(track.id); setIsFavorite(isFav); } else { @@ -252,18 +280,34 @@ export async function playTrack( console.log('Auto-skipping to next track:', next.title); // Small delay to let the toast be visible setTimeout(() => { + const nextSource = (next.source === 'plex' || next.source === 'local' || next.source === 'qobuz') + ? next.source + : (next.is_local ? 'local' : 'qobuz'); + const nextSamplingRate = next.sample_rate == null + ? undefined + : (next.is_local || nextSource === 'plex') + ? next.sample_rate / 1000 + : next.sample_rate; playTrack({ id: next.id, title: next.title, artist: next.artist, album: next.album, duration: next.duration_secs, - artwork: next.artwork_url || undefined, + artwork: next.artwork_url || '', + quality: next.hires ? 'Hi-Res' : 'CD Quality', albumId: next.album_id || undefined, artistId: next.artist_id || undefined, bitDepth: next.bit_depth || undefined, - samplingRate: next.sample_rate || undefined - }, { showLoadingToast: true, showSuccessToast: true }); + samplingRate: nextSamplingRate, + source: nextSource, + isLocal: next.is_local + }, { + isLocal: next.is_local ?? false, + source: nextSource, + showLoadingToast: true, + showSuccessToast: true + }); }, 500); } else { setIsPlaying(false); diff --git a/src/lib/services/trackActions.ts b/src/lib/services/trackActions.ts index a82e69ec5..c7a95efd4 100644 --- a/src/lib/services/trackActions.ts +++ b/src/lib/services/trackActions.ts @@ -46,7 +46,8 @@ export function buildQueueTrackFromQobuz(track: QobuzTrack): BackendQueueTrack { is_local: false, album_id: track.album?.id || null, artist_id: track.performer?.id ?? null, - streamable: track.streamable ?? true + streamable: track.streamable ?? true, + source: 'qobuz' }; } @@ -76,7 +77,8 @@ export function buildQueueTrackFromAlbumTrack( is_local: false, album_id: track.albumId || albumId || null, artist_id: track.artistId ?? artistId ?? null, - streamable: track.streamable ?? true + streamable: track.streamable ?? true, + source: 'qobuz' }; } @@ -99,14 +101,18 @@ export function buildQueueTrackFromPlaylistTrack(track: PlaylistTrack): BackendQ is_local: false, album_id: track.albumId || null, artist_id: track.artistId ?? null, - streamable: track.streamable ?? true + streamable: track.streamable ?? true, + source: 'qobuz' }; } export function buildQueueTrackFromLocalTrack(track: LocalLibraryTrack): BackendQueueTrack { - const artwork = track.artwork_path ? convertFileSrc(track.artwork_path) : null; + const artwork = track.artwork_path + ? (/^https?:\/\//i.test(track.artwork_path) ? track.artwork_path : convertFileSrc(track.artwork_path)) + : null; // Local tracks are hi-res if bit_depth > 16 or sample_rate > 44100 const isHires = Boolean((track.bit_depth && track.bit_depth > 16) || (track.sample_rate && track.sample_rate > 44100)); + const isPlexTrack = track.source === 'plex'; return { id: track.id, title: track.title, @@ -117,10 +123,11 @@ export function buildQueueTrackFromLocalTrack(track: LocalLibraryTrack): Backend hires: isHires, bit_depth: track.bit_depth ?? null, sample_rate: track.sample_rate ?? null, - is_local: true, + is_local: !isPlexTrack, album_id: null, // Local tracks don't have Qobuz album IDs artist_id: null, // Local tracks don't have Qobuz artist IDs - streamable: true // Local tracks are always playable + streamable: true, // Local tracks are always playable + source: isPlexTrack ? 'plex' : 'local' }; } @@ -163,11 +170,13 @@ export async function queuePlaylistTrackLater(track: PlaylistTrack): Promise { - await queueTrackNext(buildQueueTrackFromLocalTrack(track), true); + const isPlexTrack = track.source === 'plex'; + await queueTrackNext(buildQueueTrackFromLocalTrack(track), !isPlexTrack); } export async function queueLocalTrackLater(track: LocalLibraryTrack): Promise { - await queueTrackLater(buildQueueTrackFromLocalTrack(track), true); + const isPlexTrack = track.source === 'plex'; + await queueTrackLater(buildQueueTrackFromLocalTrack(track), !isPlexTrack); } // ============ Favorites ============ diff --git a/src/lib/stores/playbackContextStore.ts b/src/lib/stores/playbackContextStore.ts index 4f6fba26a..fa191fa65 100644 --- a/src/lib/stores/playbackContextStore.ts +++ b/src/lib/stores/playbackContextStore.ts @@ -10,7 +10,7 @@ import { invoke } from '@tauri-apps/api/core'; // ============ Types ============ export type ContextType = 'album' | 'playlist' | 'artist_top' | 'home_list' | 'favorites' | 'local_library' | 'radio'; -export type ContentSource = 'qobuz' | 'local'; +export type ContentSource = 'qobuz' | 'local' | 'plex'; export interface PlaybackContext { type: ContextType; diff --git a/src/lib/stores/playerStore.ts b/src/lib/stores/playerStore.ts index 554086140..83d33d4b2 100644 --- a/src/lib/stores/playerStore.ts +++ b/src/lib/stores/playerStore.ts @@ -49,6 +49,7 @@ export interface PlayingTrack { samplingRate?: number; format?: string; isLocal?: boolean; + source?: string; // Optional IDs for recommendation tracking albumId?: string; artistId?: number; @@ -93,10 +94,16 @@ interface QueueTrack { bit_depth: number | null; sample_rate: number | null; is_local?: boolean; + source?: string; album_id?: string | null; artist_id?: number | null; } +interface PlexPlayTrackResult { + sampling_rate_hz?: number | null; + bit_depth?: number | null; +} + // ============ State ============ /** @@ -334,11 +341,27 @@ export async function togglePlay(): Promise { const savedPosition = pendingSessionRestore.position; pendingSessionRestore = null; // Clear before loading - // Check if this is a local track (negative ID) or Qobuz track - if (currentTrack.id < 0) { - // Local track - use library_play_track with positive ID + // Restore source-specific playback + if (currentTrack.source === 'plex') { + const plexBaseUrl = getUserItem('qbz-plex-poc-base-url') || ''; + const plexToken = getUserItem('qbz-plex-poc-token') || ''; + if (!plexBaseUrl || !plexToken) { + throw new Error('Missing Plex configuration for session restore'); + } + const result = await invoke('plex_play_track', { + baseUrl: plexBaseUrl, + token: plexToken, + ratingKey: String(currentTrack.id) + }); + if (result.sampling_rate_hz && result.sampling_rate_hz > 0) { + currentTrack.samplingRate = result.sampling_rate_hz / 1000; + } + if (result.bit_depth && result.bit_depth > 0) { + currentTrack.bitDepth = result.bit_depth; + } + } else if (currentTrack.isLocal || currentTrack.id < 0) { + // Local filesystem track const localTrackId = Math.abs(currentTrack.id); - console.log('[Player] Restoring local track:', localTrackId); await invoke('library_play_track', { trackId: localTrackId }); } else { // Qobuz track - use play_track with duration for seekbar @@ -539,6 +562,12 @@ async function handlePlaybackEvent(event: PlaybackEvent): Promise { try { const queueTrack = await invoke('get_current_queue_track'); if (queueTrack && queueTrack.id === event.track_id) { + const rawRate = queueTrack.sample_rate ?? undefined; + const normalizedRate = rawRate == null + ? undefined + : (queueTrack.is_local || queueTrack.source === 'plex') + ? rawRate / 1000 + : rawRate; currentTrack = { id: queueTrack.id, title: queueTrack.title, @@ -547,11 +576,12 @@ async function handlePlaybackEvent(event: PlaybackEvent): Promise { artwork: queueTrack.artwork_url || '', duration: queueTrack.duration_secs, quality: queueTrack.hires ? 'Hi-Res' : 'CD Quality', - bitDepth: queueTrack.bit_depth, - samplingRate: queueTrack.sample_rate, + bitDepth: queueTrack.bit_depth ?? undefined, + samplingRate: normalizedRate, isLocal: queueTrack.is_local, - albumId: queueTrack.album_id, - artistId: queueTrack.artist_id + source: queueTrack.source ?? undefined, + albumId: queueTrack.album_id ?? undefined, + artistId: queueTrack.artist_id ?? undefined }; duration = queueTrack.duration_secs; // Update playback state from event @@ -587,8 +617,8 @@ async function handlePlaybackEvent(event: PlaybackEvent): Promise { persistVolume(volume); } - // Update track with actual stream quality (issue #34) - // The backend now sends the real sample rate and bit depth from the decoded stream + // Update track with actual stream quality (issue #34). + // For Plex this is needed because cached metadata can be stale/inaccurate. if (event.sample_rate && event.sample_rate > 0) { // Convert Hz to kHz for display (44100 -> 44.1) currentTrack.samplingRate = event.sample_rate / 1000; diff --git a/src/lib/stores/queueStore.ts b/src/lib/stores/queueStore.ts index d530ae1e7..e957be52e 100644 --- a/src/lib/stores/queueStore.ts +++ b/src/lib/stores/queueStore.ts @@ -33,6 +33,8 @@ export interface BackendQueueTrack { artist_id?: number | null; /** Whether the track is streamable on Qobuz (false = removed/unavailable) */ streamable?: boolean; + /** Track source: qobuz | local | plex */ + source?: string; } interface BackendQueueState { diff --git a/src/lib/types/index.ts b/src/lib/types/index.ts index 3d4998283..39bd4090b 100644 --- a/src/lib/types/index.ts +++ b/src/lib/types/index.ts @@ -322,6 +322,7 @@ export interface LocalLibraryTrack { bit_depth?: number; sample_rate: number; artwork_path?: string; + source?: string; } // ============ External API Types ============ diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 1d4909242..0406a0838 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -1473,7 +1473,8 @@ // Helper to play a track from the queue (with offline skip support) async function playQueueTrack(track: BackendQueueTrack, skippedIds = new Set(), gaplessTransition = false) { - const isLocal = isLocalTrack(track.id); + const source = track.source ?? (track.is_local ? 'local' : 'qobuz'); + const isLocal = source !== 'qobuz' || isLocalTrack(track.id); // In offline mode, check if track is available if (offlineStatus.isOffline && !isLocal) { @@ -1524,9 +1525,10 @@ // Only convert Hz to kHz for local tracks. Qobuz tracks are already in kHz. samplingRate: isLocal && track.sample_rate ? track.sample_rate / 1000 : track.sample_rate ?? undefined, isLocal, + source, albumId: track.album_id ?? undefined, artistId: track.artist_id ?? undefined - }, { isLocal, showLoadingToast: false, gaplessTransition }); + }, { isLocal, source: source as 'qobuz' | 'local' | 'plex', showLoadingToast: false, gaplessTransition }); } // Play a specific track from the queue panel @@ -2093,7 +2095,22 @@ // DO NOT clear context - LocalLibraryView already sets it correctly // await clearPlaybackContext(); - const artwork = track.artwork_path ? convertFileSrc(track.artwork_path) : ''; + const source = track.source === 'plex' ? 'plex' : 'local'; + const plexBaseUrl = getUserItem('qbz-plex-poc-base-url') || ''; + const plexToken = getUserItem('qbz-plex-poc-token') || ''; + const resolveArtwork = (path?: string): string => { + if (!path) return ''; + if (/^https?:\/\//i.test(path)) return path; + if (source === 'plex' && path.startsWith('/library/') && plexBaseUrl && plexToken) { + const base = plexBaseUrl.replace(/\/+$/, ''); + const sep = path.includes('?') ? '&' : '?'; + return `${base}${path}${sep}X-Plex-Token=${encodeURIComponent(plexToken)}`; + } + return convertFileSrc(path); + }; + const artwork = track.artwork_path + ? resolveArtwork(track.artwork_path) + : ''; const quality = track.bit_depth && track.sample_rate ? (track.bit_depth >= 24 || track.sample_rate > 48000 ? `${track.bit_depth}bit/${track.sample_rate / 1000}kHz` @@ -2111,8 +2128,9 @@ bitDepth: track.bit_depth, samplingRate: track.sample_rate ? track.sample_rate / 1000 : undefined, // Convert Hz to kHz (44100 → 44.1) - NO ROUNDING format: track.format, - isLocal: true - }, { isLocal: true }); + isLocal: source !== 'plex', + source + }, { isLocal: source !== 'plex', source }); } // Handle setting queue from local library (tracks need different playback command) diff --git a/static/home-gear.svg b/static/home-gear.svg index e8a11350f..60fc53aeb 100644 --- a/static/home-gear.svg +++ b/static/home-gear.svg @@ -1,8 +1,7 @@ - - + - \ No newline at end of file + diff --git a/static/plex-logo.svg b/static/plex-logo.svg new file mode 100644 index 000000000..64d4795fb --- /dev/null +++ b/static/plex-logo.svg @@ -0,0 +1,7 @@ + + \ No newline at end of file diff --git a/static/plex-mono.svg b/static/plex-mono.svg new file mode 100644 index 000000000..32d144bda --- /dev/null +++ b/static/plex-mono.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file From bf99a19eb3c97613152f89ab5e8e73a3ac91fe31 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 9 Feb 2026 01:47:24 -0600 Subject: [PATCH 02/11] fix(plex): hydrate track quality and show plex source indicator cx --- src-tauri/src/lib.rs | 1 + src-tauri/src/plex/mod.rs | 28 +++++++ src/lib/components/TrackRow.svelte | 27 ++++++- .../components/views/LocalLibraryView.svelte | 78 +++++++++++++++++-- src/lib/i18n/locales/de.json | 4 +- src/lib/i18n/locales/en.json | 4 +- src/lib/i18n/locales/es.json | 4 +- src/lib/i18n/locales/fr.json | 4 +- 8 files changed, 138 insertions(+), 12 deletions(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6492803bd..5a7718360 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -677,6 +677,7 @@ pub fn run() { plex::plex_ping, plex::plex_get_music_sections, plex::plex_get_section_tracks, + plex::plex_get_track_metadata, plex::plex_play_track, plex::plex_auth_pin_start, plex::plex_auth_pin_check, diff --git a/src-tauri/src/plex/mod.rs b/src-tauri/src/plex/mod.rs index 3ef15b8db..e4041a368 100644 --- a/src-tauri/src/plex/mod.rs +++ b/src-tauri/src/plex/mod.rs @@ -655,6 +655,34 @@ pub async fn plex_get_section_tracks( Ok(parse_tracks(&xml, effective_limit)) } +#[tauri::command] +pub async fn plex_get_track_metadata( + base_url: String, + token: String, + rating_key: String, +) -> Result { + let client = build_plex_client()?; + let base = normalize_base_url(&base_url); + let detail_url = format!("{base}/library/metadata/{rating_key}"); + let url = with_token(&detail_url, &token); + + let xml = client + .get(url) + .send() + .await + .map_err(|e| format!("Plex track metadata request failed: {}", e))? + .error_for_status() + .map_err(|e| format!("Plex track metadata status error: {}", e))? + .text() + .await + .map_err(|e| format!("Failed to read Plex track metadata response: {}", e))?; + + parse_tracks(&xml, Some(1)) + .into_iter() + .next() + .ok_or_else(|| "Plex track metadata not found".to_string()) +} + #[tauri::command] pub async fn plex_auth_pin_start(client_identifier: String) -> Result { let client = build_plex_auth_client(&client_identifier)?; diff --git a/src/lib/components/TrackRow.svelte b/src/lib/components/TrackRow.svelte index cc76d413d..172dd1a21 100644 --- a/src/lib/components/TrackRow.svelte +++ b/src/lib/components/TrackRow.svelte @@ -1,6 +1,7 @@