feat(plex): checkpoint plex lan integration and quality sync

cx
This commit is contained in:
vicrodh committed 2026-02-09 01:28:11 -06:00
1 parent d2531ea700
commit 228563454b
28 files changed
+2596 -107

No files matched your search

+19 -5
View File
@@ -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 @@
<!-- Image overlays placeholder when loaded -->
{#if !imageError && artwork}
<img src={artwork} alt={title} loading="lazy" decoding="async" onerror={handleImageError} />
<img class="artwork-image" src={artwork} alt={title} loading="lazy" decoding="async" onerror={handleImageError} />
{/if}
<!-- Action Overlay -->
@@ -262,9 +262,15 @@
<!-- Source Badge (Local Library only) -->
{#if sourceBadge}
<div class="source-badge" class:local-badge={sourceBadge === 'user'} title={sourceBadge === 'user' ? 'Local file' : 'Qobuz offline'}>
<div
class="source-badge"
class:local-badge={sourceBadge === 'user'}
title={sourceBadge === 'user' ? 'Local file' : sourceBadge === 'plex' ? 'Plex library' : 'Qobuz offline'}
>
{#if sourceBadge === 'user'}
<HardDrive size={14} />
{:else if sourceBadge === 'plex'}
<img src="/plex-logo.svg" alt="Plex" class="qobuz-badge-icon plex-logo-icon" />
{:else}
<img src="/qobuz-logo-filled.svg" alt="Qobuz" class="qobuz-badge-icon" />
{/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;
@@ -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}
</div>
+8 -1
View File
@@ -912,7 +912,14 @@
<div class="header-actions">
<GenreFilterButton onFilterChange={handleGenreFilterChange} />
<button class="settings-btn" onclick={() => isSettingsModalOpen = true} title={$t('home.customizeHome')}>
<img src="/home-gear.svg" alt="Settings" class="settings-icon" />
<img
src="/home-gear.svg"
alt="Settings"
class="settings-icon"
width="22"
height="22"
style="width:22px;height:22px;filter:invert(1) opacity(0.8);"
/>
</button>
</div>
</div>
+365 -55
View File
@@ -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<string | null>(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<LocalAlbum[]>('library_get_albums', {
includeHidden: false,
excludeNetworkFolders: shouldExcludeNetworkFolders()
});
const [localAlbums, plexAlbumsRaw] = await Promise.all([
invoke<LocalAlbum[]>('library_get_albums', {
includeHidden: false,
excludeNetworkFolders: shouldExcludeNetworkFolders()
}),
invoke<PlexCachedAlbum[]>('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<LocalTrack[]>('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<boolean> {
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<PlexMusicSection[]>('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<PlexTrack[]>('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<LocalAlbum[]>('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<LibraryStats>('library_get_stats');
const fetchStart = performance.now();
const [albumsResult, statsResult, plexAlbumsRaw] = await Promise.all([
invoke<LocalAlbum[]>('library_get_albums', {
includeHidden: false,
excludeNetworkFolders: excludeNetwork
}),
invoke<LibraryStats>('library_get_stats'),
invoke<PlexCachedAlbum[]>('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<LocalArtist[]>('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<LocalArtist[]>('library_get_artists', {
excludeNetworkFolders: shouldExcludeNetworkFolders()
}),
invoke<PlexCachedAlbum[]>('plex_cache_get_albums').catch(() => [])
]);
const plexArtistMap = new Map<string, { albumCount: number; trackCount: number }>();
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<string, LocalArtist>();
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<LocalTrack[]>('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<LocalTrack[]>('library_search', {
query,
limit: 0, // 0 = no limit, virtualization handles any list size
excludeNetworkFolders: shouldExcludeNetworkFolders()
}),
invoke<PlexCachedTrack[]>('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<LocalTrack[]>('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<LocalTrack[]> {
try {
if (album.source === 'plex') {
const plexTracks = await invoke<PlexCachedTrack[]>('plex_cache_get_album_tracks', {
albumKey: album.id
});
return plexTracks.map(mapPlexTrack);
}
return await invoke<LocalTrack[]>('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 @@
<ArrowLeft size={16} />
<span>{$t('library.backToLibrary')}</span>
</button>
<button class="edit-btn" onclick={openAlbumEditModal} title={$t('actions.edit')}>
<button
class="edit-btn"
onclick={openAlbumEditModal}
title={selectedAlbum?.source === 'plex' && getUserItem(PLEX_METADATA_WRITE_KEY) !== 'true'
? $t('settings.integrations.plexWriteDisabledNotice')
: $t('actions.edit')}
disabled={selectedAlbum?.source === 'plex' && getUserItem(PLEX_METADATA_WRITE_KEY) !== 'true'}
>
<Edit3 size={16} />
</button>
</div>
@@ -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}
</div>
+575 -1
View File
@@ -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<PlexMusicSection[]>([]);
let plexTracks = $state<PlexTrack[]>([]);
let plexSelectedSectionKey = $state('');
let plexStatusKey = $state('settings.integrations.plexStatusIdle');
let plexStatusValues = $state<Record<string, string | number>>({});
let plexBusy = $state(false);
let plexLastError = $state('');
let plexAuthBusy = $state(false);
let plexAuthPinId = $state<number | null>(null);
let plexAuthCode = $state('');
let plexAuthUrl = $state('');
let plexAuthClientId = $state(getUserItem('qbz-plex-poc-client-id') || '');
let plexAuthPollTimer: ReturnType<typeof setInterval> | 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<PlexPinStartResult>('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<PlexPinCheckResult>('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<PlexMusicSection[]>('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<PlexTrack[]>('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<PlexServerInfo>('plex_ping', {
baseUrl: plexBaseUrl.trim(),
token: plexToken.trim()
});
if (info.machineIdentifier) {
setUserItem(PLEX_CACHE_SERVER_ID_KEY, info.machineIdentifier);
}
const sections = await invoke<PlexMusicSection[]>('plex_get_music_sections', {
baseUrl: plexBaseUrl.trim(),
token: plexToken.trim()
});
plexSections = sections;
await invoke<number>('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<PlexTrack[]>('plex_get_section_tracks', {
baseUrl: plexBaseUrl.trim(),
token: plexToken.trim(),
sectionKey: plexSelectedSectionKey
});
plexTracks = tracks;
await invoke<number>('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<PlexServerInfo>('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<PlexMusicSection[]>('plex_get_music_sections', {
baseUrl: plexBaseUrl.trim(),
token: plexToken.trim()
});
plexSections = sections;
await invoke<number>('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<PlexTrack[]>('plex_get_section_tracks', {
baseUrl: plexBaseUrl.trim(),
token: plexToken.trim(),
sectionKey: plexSelectedSectionKey
});
plexTracks = tracks;
await invoke<number>('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<RemoteControlStatus>('remote_control_get_status');
@@ -2851,7 +3247,7 @@
{/if}
<!-- MusicBrainz Integration -->
<div class="setting-row last">
<div class="setting-row">
<div class="setting-info">
<span class="setting-label">{$t('settings.integrations.musicbrainz')}</span>
<small class="setting-note">
@@ -2860,6 +3256,117 @@
</div>
<Toggle enabled={musicbrainzEnabled} onchange={handleMusicBrainzChange} />
</div>
<div class="lastfm-config plex-poc-panel">
<div class="setting-with-description">
<span class="setting-label">{$t('settings.integrations.plexPoc')}</span>
<span class="setting-description">{$t('settings.integrations.plexPocDesc')}</span>
</div>
<small class="setting-note">{$t('settings.integrations.plexLibraryIntegrationNote')}</small>
<small class="setting-note">{$t('settings.integrations.plexLocalOnlyDirectPlayNote')}</small>
<div class="setting-row">
<div class="setting-info">
<span class="setting-label">{$t('settings.integrations.plexMetadataWrite')}</span>
<small class="setting-note">{$t('settings.integrations.plexMetadataWriteDesc')}</small>
</div>
<Toggle enabled={plexMetadataWriteEnabled} onchange={handlePlexMetadataWriteToggle} />
</div>
<div class="plex-connect-wizard">
<div class="plex-wizard-header">
<span class="setting-label">{$t('settings.integrations.plexEasyConnectTitle')}</span>
<small class="setting-note">{$t('settings.integrations.plexEasyConnectDesc')}</small>
</div>
<div class="plex-actions">
<button class="connect-btn" onclick={handlePlexConnectEasy} disabled={plexBusy || plexAuthBusy}>
{plexAuthBusy ? $t('actions.loading') : $t('settings.integrations.plexActionEasyConnect')}
</button>
{#if plexAuthUrl}
<button
class="connect-btn"
onclick={handleOpenPlexAuthUrl}
disabled={plexAuthBusy}
>
{$t('settings.integrations.plexActionOpenAuth')}
</button>
{/if}
<button class="connect-btn danger-btn" onclick={handlePlexDisconnect} disabled={plexBusy || plexAuthBusy}>
{$t('settings.integrations.plexActionDisconnect')}
</button>
<button class="connect-btn danger-btn" onclick={handlePlexClearCache} disabled={plexBusy || plexAuthBusy}>
{$t('settings.integrations.plexActionClearCache')}
</button>
</div>
{#if plexAuthCode}
<div class="plex-code-card">
<small class="setting-note">{$t('settings.integrations.plexCodeLabel')}</small>
<div class="plex-code-value">{plexAuthCode}</div>
<div class="plex-actions">
<button class="connect-btn" onclick={handleCopyPlexCode}>
{$t('settings.integrations.plexActionCopyCode')}
</button>
</div>
</div>
{/if}
</div>
<div class="config-field">
<label for="plex-base-url">{$t('settings.integrations.plexBaseUrl')}</label>
<input
id="plex-base-url"
type="text"
bind:value={plexBaseUrl}
placeholder={$t('settings.integrations.plexBaseUrlPlaceholder')}
/>
</div>
<div class="config-field">
<label for="plex-token">{$t('settings.integrations.plexToken')}</label>
<input
id="plex-token"
type="password"
bind:value={plexToken}
placeholder={$t('settings.integrations.plexTokenPlaceholder')}
/>
</div>
<div class="plex-actions">
<button class="connect-btn" onclick={handlePlexPing} disabled={plexBusy || !plexBaseUrl.trim() || !plexToken.trim()}>
{plexBusy ? $t('actions.loading') : $t('settings.integrations.plexActionPing')}
</button>
<button class="connect-btn" onclick={handlePlexLoadSections} disabled={plexBusy || !plexBaseUrl.trim() || !plexToken.trim()}>
{plexBusy ? $t('actions.loading') : $t('settings.integrations.plexActionLoadSections')}
</button>
</div>
<div class="setting-row plex-inline-row">
<span class="setting-label">{$t('settings.integrations.plexMusicSection')}</span>
<div class="plex-section-controls">
<select
class="remote-control-input plex-section-select"
bind:value={plexSelectedSectionKey}
disabled={plexSections.length === 0 || plexBusy}
>
<option value="" disabled selected={plexSelectedSectionKey === ''}>
{$t('settings.integrations.plexSelectSection')}
</option>
{#each plexSections as plexSection}
<option value={plexSection.key}>{plexSection.title}</option>
{/each}
</select>
<button class="connect-btn" onclick={handlePlexLoadTracks} disabled={plexBusy || !plexSelectedSectionKey}>
{plexBusy ? $t('actions.loading') : $t('settings.integrations.plexActionLoadTracks')}
</button>
</div>
</div>
<small class="setting-note">{$t(plexStatusKey, { values: plexStatusValues })}</small>
{#if plexLastError}
<small class="setting-note plex-error-note">{plexLastError}</small>
{/if}
</div>
</section>
<!-- Updates Section -->
@@ -4390,6 +4897,73 @@ flatpak override --user --filesystem=/home/USUARIO/Música com.blitzfc.qbz</pre>
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;
}
</style>
<MigrationModal