Merge remote-tracking branch 'origin/feature/internal/plex-lan-local-poc' into pre-release
This commit is contained in:
commit
ada4e85606
35 files changed
+3324
-169
No files matched your search
@@ -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';
|
||||
artistId?: number;
|
||||
onArtistClick?: (artistId: number) => void;
|
||||
}
|
||||
@@ -216,7 +216,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 -->
|
||||
@@ -276,9 +276,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}
|
||||
@@ -337,7 +343,7 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.artwork-container img {
|
||||
.artwork-container .artwork-image {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
@@ -392,6 +398,7 @@
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
color: var(--text-secondary);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.source-badge.local-badge {
|
||||
@@ -405,6 +412,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;
|
||||
|
||||
@@ -356,7 +356,7 @@
|
||||
const tracks = await invoke<Array<{ id: number; file_path: string }>>('library_get_tracks_by_ids', {
|
||||
trackIds
|
||||
});
|
||||
localTrackPaths = tracks.map(t => t.file_path);
|
||||
localTrackPaths = tracks.map(track => track.file_path);
|
||||
}
|
||||
|
||||
await invoke('add_tracks_to_pending_playlist', {
|
||||
@@ -419,7 +419,7 @@
|
||||
const tracks = await invoke<Array<{ id: number; file_path: string }>>('library_get_tracks_by_ids', {
|
||||
trackIds
|
||||
});
|
||||
localTrackPaths = tracks.map(t => t.file_path);
|
||||
localTrackPaths = tracks.map(track => track.file_path);
|
||||
}
|
||||
|
||||
// Create pending playlist for sync when back online
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { Play, Pause, Heart, HardDrive, AlertCircle, Ban } from 'lucide-svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import TrackMenu from './TrackMenu.svelte';
|
||||
import DownloadButton from './DownloadButton.svelte';
|
||||
import {
|
||||
@@ -24,6 +25,7 @@
|
||||
quality?: string;
|
||||
isPlaying?: boolean;
|
||||
isLocal?: boolean; // Whether this is a local library track
|
||||
localSource?: 'local' | 'plex';
|
||||
isUnavailable?: boolean; // Track removed from Qobuz or otherwise unavailable
|
||||
unavailableTooltip?: string; // Tooltip for unavailable indicator
|
||||
isBlacklisted?: boolean; // Artist is blacklisted
|
||||
@@ -71,6 +73,7 @@
|
||||
quality,
|
||||
isPlaying = false,
|
||||
isLocal = false,
|
||||
localSource = 'local',
|
||||
isUnavailable = false,
|
||||
unavailableTooltip,
|
||||
isFavoriteOverride,
|
||||
@@ -243,8 +246,16 @@
|
||||
|
||||
<!-- Download Indicator / Local Indicator (placeholder when hidden to maintain column width) -->
|
||||
{#if isLocal}
|
||||
<div class="local-indicator" title="Local track - only available on this device">
|
||||
<HardDrive size={14} />
|
||||
<div
|
||||
class="local-indicator"
|
||||
class:plex-source={localSource === 'plex'}
|
||||
title={localSource === 'plex' ? $t('library.plexTrackIndicator') : $t('library.localTrackIndicator')}
|
||||
>
|
||||
{#if localSource === 'plex'}
|
||||
<span class="plex-indicator-icon" aria-hidden="true"></span>
|
||||
{:else}
|
||||
<HardDrive size={14} />
|
||||
{/if}
|
||||
</div>
|
||||
{:else if hideDownload}
|
||||
<div class="download-placeholder"></div>
|
||||
@@ -520,6 +531,18 @@
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.local-indicator.plex-source {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.plex-indicator-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
background-color: var(--accent-primary);
|
||||
-webkit-mask: url('/plex-mono.svg') center / contain no-repeat;
|
||||
mask: url('/plex-mono.svg') center / contain no-repeat;
|
||||
}
|
||||
|
||||
.download-placeholder {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -218,7 +218,7 @@
|
||||
}
|
||||
|
||||
const albumFullyDownloaded = $derived(
|
||||
isAlbumFullyCached(album.tracks.map(t => t.id))
|
||||
isAlbumFullyCached(album.tracks.map(track => track.id))
|
||||
);
|
||||
|
||||
const isVariousArtists = $derived(
|
||||
|
||||
@@ -594,26 +594,26 @@
|
||||
}
|
||||
|
||||
function buildContinueQueueTracks(tracks: DisplayTrack[]) {
|
||||
return tracks.map(t => ({
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
artist: t.artist || 'Unknown Artist',
|
||||
album: t.album || '',
|
||||
duration_secs: t.durationSeconds,
|
||||
artwork_url: t.albumArt || '',
|
||||
hires: t.hires ?? false,
|
||||
bit_depth: t.bitDepth ?? null,
|
||||
sample_rate: t.samplingRate ?? null,
|
||||
is_local: t.isLocal ?? false,
|
||||
album_id: t.albumId || null,
|
||||
artist_id: t.artistId ?? null,
|
||||
return tracks.map(track => ({
|
||||
id: track.id,
|
||||
title: track.title,
|
||||
artist: track.artist || 'Unknown Artist',
|
||||
album: track.album || '',
|
||||
duration_secs: track.durationSeconds,
|
||||
artwork_url: track.albumArt || '',
|
||||
hires: track.hires ?? false,
|
||||
bit_depth: track.bitDepth ?? null,
|
||||
sample_rate: track.samplingRate ?? null,
|
||||
is_local: track.isLocal ?? false,
|
||||
album_id: track.albumId || null,
|
||||
artist_id: track.artistId ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
async function handleContinueTrackPlay(track: DisplayTrack, trackIndex: number) {
|
||||
// Create continue listening context
|
||||
if (continueTracks.length > 0) {
|
||||
const trackIds = continueTracks.map(t => t.id);
|
||||
const trackIds = continueTracks.map(track => track.id);
|
||||
|
||||
await setPlaybackContext(
|
||||
'home_list',
|
||||
@@ -921,7 +921,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>
|
||||
|
||||
@@ -72,6 +72,7 @@
|
||||
artwork_path?: string;
|
||||
last_modified: number;
|
||||
indexed_at: number;
|
||||
source?: string; // 'user' | 'qobuz_download' | 'plex'
|
||||
}
|
||||
|
||||
interface LocalAlbum {
|
||||
@@ -88,7 +89,71 @@
|
||||
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 PlexTrackMetadata {
|
||||
ratingKey: string;
|
||||
container?: string;
|
||||
codec?: string;
|
||||
samplingRateHz?: number;
|
||||
bitDepth?: number;
|
||||
}
|
||||
|
||||
interface PlexTrackQualityUpdate {
|
||||
ratingKey: string;
|
||||
container?: string;
|
||||
samplingRateHz?: number;
|
||||
bitDepth?: number;
|
||||
}
|
||||
|
||||
interface LocalArtist {
|
||||
@@ -158,6 +223,8 @@
|
||||
isPlaybackActive?: boolean;
|
||||
}
|
||||
|
||||
const PLEX_METADATA_WRITE_KEY = 'qbz-plex-poc-metadata-write-enabled';
|
||||
|
||||
let {
|
||||
onAlbumClick,
|
||||
onQobuzArtistClick,
|
||||
@@ -319,7 +386,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;
|
||||
}
|
||||
|
||||
@@ -419,6 +486,7 @@
|
||||
let artistImageFetchInProgress = false; // Guard against concurrent fetches
|
||||
let artistImageFetchAborted = false; // Flag to abort fetching
|
||||
let trackSearch = $state('');
|
||||
let tracksHydrationRequestId = 0;
|
||||
let searchOpen = $state(false);
|
||||
let searchInputEl: HTMLInputElement | undefined;
|
||||
type TrackGroupMode = 'album' | 'artist' | 'name';
|
||||
@@ -832,6 +900,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 +1042,24 @@
|
||||
|
||||
// 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 includePlex = isPlexLibraryEnabled();
|
||||
const [localAlbums, plexAlbumsRaw] = await Promise.all([
|
||||
invoke<LocalAlbum[]>('library_get_albums', {
|
||||
includeHidden: false,
|
||||
excludeNetworkFolders: shouldExcludeNetworkFolders()
|
||||
}),
|
||||
includePlex
|
||||
? invoke<PlexCachedAlbum[]>('plex_cache_get_albums').catch(() => [])
|
||||
: Promise.resolve([])
|
||||
]);
|
||||
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 +1111,227 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLibraryData() {
|
||||
console.log('[LocalLibrary] loadLibraryData START, isOffline:', isOffline);
|
||||
loading = true;
|
||||
error = null;
|
||||
function isPlexLibraryEnabled(): boolean {
|
||||
return getUserItem('qbz-plex-enabled') === 'true';
|
||||
}
|
||||
|
||||
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 includePlex = isPlexLibraryEnabled();
|
||||
const [albumsResult, statsResult, plexAlbumsRaw] = await Promise.all([
|
||||
invoke<LocalAlbum[]>('library_get_albums', {
|
||||
includeHidden: false,
|
||||
excludeNetworkFolders: excludeNetwork
|
||||
}),
|
||||
invoke<LibraryStats>('library_get_stats'),
|
||||
includePlex
|
||||
? invoke<PlexCachedAlbum[]>('plex_cache_get_albums').catch(() => [])
|
||||
: Promise.resolve([])
|
||||
]);
|
||||
const fetchMs = performance.now() - fetchStart;
|
||||
let workingPlexAlbumsRaw = plexAlbumsRaw;
|
||||
const shouldAttemptRepair =
|
||||
includePlex &&
|
||||
!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 +1392,47 @@
|
||||
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 includePlex = isPlexLibraryEnabled();
|
||||
const [localArtists, plexAlbumsRaw] = await Promise.all([
|
||||
invoke<LocalArtist[]>('library_get_artists', {
|
||||
excludeNetworkFolders: shouldExcludeNetworkFolders()
|
||||
}),
|
||||
includePlex
|
||||
? invoke<PlexCachedAlbum[]>('plex_cache_get_albums').catch(() => [])
|
||||
: Promise.resolve([])
|
||||
]);
|
||||
|
||||
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
|
||||
@@ -1145,15 +1451,37 @@
|
||||
|
||||
async function loadTracks(query = '') {
|
||||
console.log('[LocalLibrary] loadTracks START, query:', query);
|
||||
const requestId = ++tracksHydrationRequestId;
|
||||
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 includePlex = isPlexLibraryEnabled();
|
||||
const [localTracks, plexTracksRaw] = await Promise.all([
|
||||
invoke<LocalTrack[]>('library_search', {
|
||||
query,
|
||||
limit: 0, // 0 = no limit, virtualization handles any list size
|
||||
excludeNetworkFolders: shouldExcludeNetworkFolders()
|
||||
}),
|
||||
includePlex
|
||||
? invoke<PlexCachedTrack[]>('plex_cache_search_tracks', {
|
||||
query
|
||||
}).catch(() => [])
|
||||
: Promise.resolve([])
|
||||
]);
|
||||
const mappedPlexTracks = plexTracksRaw.map(mapPlexTrack);
|
||||
tracks = [...localTracks, ...mappedPlexTracks];
|
||||
console.log('[LocalLibrary] Received tracks:', tracks.length, 'local:', localTracks.length, 'plex:', plexTracksRaw.length);
|
||||
|
||||
// Hydrate Plex quality in the background; don't block rendering track lists.
|
||||
// Guard with requestId to avoid stale updates after a newer search.
|
||||
void hydratePlexTrackQuality(mappedPlexTracks)
|
||||
.then((hydratedPlexTracks) => {
|
||||
if (requestId !== tracksHydrationRequestId) return;
|
||||
tracks = [...localTracks, ...hydratedPlexTracks];
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn('[LocalLibrary] Background Plex quality hydration failed:', error);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[LocalLibrary] Failed to load tracks:', err);
|
||||
error = String(err);
|
||||
@@ -1505,9 +1833,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,16 +1867,17 @@
|
||||
|
||||
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);
|
||||
const trackIds = albumTracks.map(track => track.id);
|
||||
|
||||
// Set playback context for Local Library album
|
||||
await setPlaybackContext(
|
||||
'local_library',
|
||||
selectedAlbum.id,
|
||||
selectedAlbum.title,
|
||||
'local',
|
||||
selectedAlbum.source === 'plex' ? 'plex' : 'local',
|
||||
trackIds,
|
||||
trackIndex >= 0 ? trackIndex : 0
|
||||
);
|
||||
@@ -1558,24 +1885,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 +1949,17 @@
|
||||
|
||||
async function fetchAlbumTracks(album: LocalAlbum): Promise<LocalTrack[]> {
|
||||
try {
|
||||
if (album.source === 'plex') {
|
||||
if (!isPlexLibraryEnabled()) {
|
||||
return [];
|
||||
}
|
||||
const plexTracks = await invoke<PlexCachedTrack[]>('plex_cache_get_album_tracks', {
|
||||
albumKey: album.id
|
||||
});
|
||||
const mappedTracks = plexTracks.map(mapPlexTrack);
|
||||
return await hydratePlexTrackQuality(mappedTracks);
|
||||
}
|
||||
|
||||
return await invoke<LocalTrack[]>('library_get_album_tracks', {
|
||||
albumGroupKey: album.id
|
||||
});
|
||||
@@ -1625,29 +1969,94 @@
|
||||
}
|
||||
}
|
||||
|
||||
function isLikelyFallbackPlexQuality(track: LocalTrack): boolean {
|
||||
if (track.source !== 'plex') return false;
|
||||
const format = (track.format || '').toLowerCase();
|
||||
const bitDepth = track.bit_depth ?? 0;
|
||||
const sampleRate = track.sample_rate ?? 0;
|
||||
return format === 'flac' && bitDepth <= 16 && sampleRate <= 44100;
|
||||
}
|
||||
|
||||
async function hydratePlexTrackQuality(tracks: LocalTrack[]): Promise<LocalTrack[]> {
|
||||
const baseUrl = getUserItem('qbz-plex-poc-base-url') || '';
|
||||
const token = getUserItem('qbz-plex-poc-token') || '';
|
||||
if (!baseUrl || !token || tracks.length === 0) return tracks;
|
||||
|
||||
const candidates = tracks.filter((track) => isLikelyFallbackPlexQuality(track));
|
||||
if (candidates.length === 0) return tracks;
|
||||
|
||||
const metadataEntries = await Promise.all(
|
||||
candidates.map(async (track) => {
|
||||
try {
|
||||
const metadata = await invoke<PlexTrackMetadata>('plex_get_track_metadata', {
|
||||
baseUrl,
|
||||
token,
|
||||
ratingKey: track.file_path
|
||||
});
|
||||
return [track.file_path, metadata] as const;
|
||||
} catch (error) {
|
||||
console.warn('[LocalLibrary] Failed to hydrate Plex track metadata for', track.file_path, error);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
const metadataByRatingKey = new Map<string, PlexTrackMetadata>();
|
||||
const qualityUpdates: PlexTrackQualityUpdate[] = [];
|
||||
for (const entry of metadataEntries) {
|
||||
if (!entry) continue;
|
||||
metadataByRatingKey.set(entry[0], entry[1]);
|
||||
qualityUpdates.push({
|
||||
ratingKey: entry[0],
|
||||
container: entry[1].container ?? entry[1].codec,
|
||||
samplingRateHz: entry[1].samplingRateHz,
|
||||
bitDepth: entry[1].bitDepth
|
||||
});
|
||||
}
|
||||
if (metadataByRatingKey.size === 0) return tracks;
|
||||
|
||||
if (qualityUpdates.length > 0) {
|
||||
invoke<number>('plex_cache_update_track_quality', { updates: qualityUpdates }).catch((error) => {
|
||||
console.warn('[LocalLibrary] Failed to persist Plex track quality updates:', error);
|
||||
});
|
||||
}
|
||||
|
||||
return tracks.map((track) => {
|
||||
const metadata = metadataByRatingKey.get(track.file_path);
|
||||
if (!metadata) return track;
|
||||
return {
|
||||
...track,
|
||||
format: (metadata.container ?? metadata.codec ?? track.format).toLowerCase(),
|
||||
bit_depth: metadata.bitDepth ?? track.bit_depth,
|
||||
sample_rate: metadata.samplingRateHz ?? track.sample_rate
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function setQueueForLocalTracks(tracks: LocalTrack[], startIndex = 0) {
|
||||
console.log('[LocalLibrary Queue] Setting queue with', tracks.length, 'tracks, startIndex:', startIndex);
|
||||
|
||||
const queueTracks = tracks.map(t => ({
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
artist: t.artist,
|
||||
album: t.album,
|
||||
duration_secs: t.duration_secs,
|
||||
artwork_url: t.artwork_path ? getArtworkUrl(t.artwork_path) : null,
|
||||
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,
|
||||
const queueTracks = tracks.map(track => ({
|
||||
source: track.source === 'plex' ? 'plex' : 'local',
|
||||
id: track.id,
|
||||
title: track.title,
|
||||
artist: track.artist,
|
||||
album: track.album,
|
||||
duration_secs: track.duration_secs,
|
||||
artwork_url: track.artwork_path ? getArtworkUrl(track.artwork_path) : null,
|
||||
hires: (track.bit_depth && track.bit_depth > 16) || track.sample_rate > 44100,
|
||||
bit_depth: track.bit_depth ?? null,
|
||||
sample_rate: track.sample_rate ?? null,
|
||||
is_local: track.source !== 'plex',
|
||||
album_id: null, // Local tracks don't have Qobuz IDs
|
||||
artist_id: null,
|
||||
}));
|
||||
|
||||
console.log('[LocalLibrary Queue] Mapped to', queueTracks.length, 'queue tracks');
|
||||
console.log('[LocalLibrary Queue] Track IDs:', queueTracks.map(t => t.id));
|
||||
console.log('[LocalLibrary Queue] Track IDs:', queueTracks.map(track => track.id));
|
||||
|
||||
await invoke('set_queue', { tracks: queueTracks, startIndex });
|
||||
onSetLocalQueue?.(tracks.map(t => t.id));
|
||||
onSetLocalQueue?.(tracks.filter(track => track.source !== 'plex').map(track => track.id));
|
||||
|
||||
console.log('[LocalLibrary Queue] Queue set successfully');
|
||||
}
|
||||
@@ -1724,6 +2133,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 = [];
|
||||
@@ -1879,8 +2292,10 @@
|
||||
|
||||
function getQualityBadge(track: LocalTrack): string {
|
||||
const format = track.format.toUpperCase();
|
||||
const bitDepth = track.bit_depth ?? 16;
|
||||
const sampleRate = track.sample_rate / 1000; // Convert to kHz
|
||||
const bitDepth = track.bit_depth && track.bit_depth > 0 ? String(track.bit_depth) : '--';
|
||||
const sampleRate = track.sample_rate > 0
|
||||
? Number((track.sample_rate / 1000).toFixed(1)).toString()
|
||||
: '--';
|
||||
|
||||
// Format: "FLAC 24/96" style that audiophiles love
|
||||
return `${format} ${bitDepth}/${sampleRate}`;
|
||||
@@ -1891,17 +2306,20 @@
|
||||
}
|
||||
|
||||
function formatSampleRate(hz: number): string {
|
||||
if (hz <= 0) return '-- kHz';
|
||||
return `${(hz / 1000).toFixed(1)} kHz`;
|
||||
}
|
||||
|
||||
function formatBitDepth(bits?: number): string {
|
||||
return bits ? `${bits}-bit` : '16-bit';
|
||||
return bits && bits > 0 ? `${bits}-bit` : '--bit';
|
||||
}
|
||||
|
||||
function getAlbumQualityBadge(album: LocalAlbum): string {
|
||||
const format = album.format.toUpperCase();
|
||||
const bitDepth = album.bit_depth ?? 16;
|
||||
const sampleRate = album.sample_rate / 1000;
|
||||
const bitDepth = album.bit_depth && album.bit_depth > 0 ? String(album.bit_depth) : '--';
|
||||
const sampleRate = album.sample_rate > 0
|
||||
? Number((album.sample_rate / 1000).toFixed(1)).toString()
|
||||
: '--';
|
||||
return `${format} ${bitDepth}/${sampleRate}`;
|
||||
}
|
||||
|
||||
@@ -1959,6 +2377,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 +2411,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 +3012,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>
|
||||
@@ -2665,6 +3094,7 @@
|
||||
quality={getQualityBadge(track)}
|
||||
isPlaying={isPlaybackActive && activeTrackId === track.id}
|
||||
isLocal={true}
|
||||
localSource={track.source === 'plex' ? 'plex' : 'local'}
|
||||
hideDownload={true}
|
||||
hideFavorite={true}
|
||||
onArtistClick={track.artist && track.artist !== selectedAlbum?.artist
|
||||
@@ -2675,7 +3105,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 +3794,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>
|
||||
|
||||
@@ -509,7 +509,7 @@
|
||||
}));
|
||||
|
||||
// Update duration
|
||||
playlist.duration = qobuzTracks.reduce((sum, t) => sum + t.duration, 0);
|
||||
playlist.duration = qobuzTracks.reduce((sum, track) => sum + track.duration, 0);
|
||||
} catch (err) {
|
||||
console.error('Failed to load Qobuz tracks for pending playlist:', err);
|
||||
tracks = [];
|
||||
|
||||
@@ -662,26 +662,26 @@
|
||||
}
|
||||
|
||||
function buildSearchQueueTracks(tracks: Track[]) {
|
||||
return tracks.map(t => ({
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
artist: t.performer?.name || 'Unknown Artist',
|
||||
album: t.album?.title || '',
|
||||
duration_secs: t.duration,
|
||||
artwork_url: t.album?.image?.large || t.album?.image?.thumbnail || t.album?.image?.small || '',
|
||||
hires: t.hires_streamable ?? false,
|
||||
bit_depth: t.maximum_bit_depth ?? null,
|
||||
sample_rate: t.maximum_sampling_rate ?? null,
|
||||
return tracks.map(track => ({
|
||||
id: track.id,
|
||||
title: track.title,
|
||||
artist: track.performer?.name || 'Unknown Artist',
|
||||
album: track.album?.title || '',
|
||||
duration_secs: track.duration,
|
||||
artwork_url: track.album?.image?.large || track.album?.image?.thumbnail || track.album?.image?.small || '',
|
||||
hires: track.hires_streamable ?? false,
|
||||
bit_depth: track.maximum_bit_depth ?? null,
|
||||
sample_rate: track.maximum_sampling_rate ?? null,
|
||||
is_local: false,
|
||||
album_id: t.album?.id || null,
|
||||
artist_id: t.performer?.id ?? null,
|
||||
album_id: track.album?.id || null,
|
||||
artist_id: track.performer?.id ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
async function handleSearchTrackPlay(track: Track, trackIndex: number) {
|
||||
// Create search results context
|
||||
if (trackResults && trackResults.items.length > 0) {
|
||||
const trackIds = trackResults.items.map(t => t.id);
|
||||
const trackIds = trackResults.items.map(track => track.id);
|
||||
|
||||
await setPlaybackContext(
|
||||
'home_list', // Using home_list for search results (search type doesn't exist yet)
|
||||
|
||||
@@ -134,6 +134,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,
|
||||
@@ -704,6 +740,37 @@
|
||||
let showRemoteControlGuide = $state(false);
|
||||
let remoteControlCollapsed = $state(true);
|
||||
|
||||
// Plex LAN POC state
|
||||
let plexEnabled = $state(getUserItem('qbz-plex-enabled') === 'true');
|
||||
let plexUiCollapsed = $state(getUserItem('qbz-plex-ui-collapsed') === 'true');
|
||||
let plexManualTokenMode = $state(false);
|
||||
let plexServerUrl = $state('http://127.0.0.1');
|
||||
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 plexSectionTrackCounts = $state<Record<string, number>>({});
|
||||
let plexSelectedSectionKeys = $state<string[]>([]);
|
||||
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_ENABLED_KEY = 'qbz-plex-enabled';
|
||||
const PLEX_UI_COLLAPSED_KEY = 'qbz-plex-ui-collapsed';
|
||||
const PLEX_CACHE_SELECTED_SECTIONS_KEY = 'qbz-plex-poc-selected-sections';
|
||||
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
|
||||
@@ -782,6 +849,13 @@
|
||||
// Load remote control status
|
||||
loadRemoteControlStatus();
|
||||
|
||||
// Warm-start Plex panel from local cache and refresh in background
|
||||
hydratePlexAddressFieldsFromBaseUrl();
|
||||
if (plexEnabled) {
|
||||
void loadPlexCachedState();
|
||||
void refreshPlexInBackground();
|
||||
}
|
||||
|
||||
// Load notification preferences
|
||||
loadToastsPreference();
|
||||
toastsEnabled = getToastsEnabled();
|
||||
@@ -859,6 +933,9 @@
|
||||
settingsViewEl?.addEventListener('scroll', handleScroll);
|
||||
|
||||
return () => {
|
||||
if (plexAuthPollTimer) {
|
||||
clearInterval(plexAuthPollTimer);
|
||||
}
|
||||
unsubscribeOffline();
|
||||
unsubscribeZoom();
|
||||
unsubscribeTitleBar();
|
||||
@@ -1070,6 +1147,454 @@
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePlexServerUrl(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return '';
|
||||
return /^https?:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
|
||||
}
|
||||
|
||||
function isPrivateIpv4(hostname: string): boolean {
|
||||
if (!/^\d+\.\d+\.\d+\.\d+$/.test(hostname)) return false;
|
||||
const octets = hostname.split('.').map(Number);
|
||||
if (octets.some((octet) => Number.isNaN(octet) || octet < 0 || octet > 255)) return false;
|
||||
if (octets[0] === 10) return true;
|
||||
if (octets[0] === 127) return true;
|
||||
if (octets[0] === 192 && octets[1] === 168) return true;
|
||||
if (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function isLocalPlexAddress(urlInput: string): boolean {
|
||||
const normalized = normalizePlexServerUrl(urlInput);
|
||||
if (!normalized) return false;
|
||||
try {
|
||||
const parsed = new URL(normalized);
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
if (host === 'localhost' || host === '::1') return true;
|
||||
if (host.endsWith('.local') || host.endsWith('.lan')) return true;
|
||||
if (!host.includes('.')) return true;
|
||||
return isPrivateIpv4(host);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePlexBaseUrl(): string {
|
||||
const normalizedUrl = normalizePlexServerUrl(plexServerUrl);
|
||||
if (!normalizedUrl) return '';
|
||||
try {
|
||||
const parsed = new URL(normalizedUrl);
|
||||
if (!['http:', 'https:'].includes(parsed.protocol)) return '';
|
||||
if (!parsed.port) {
|
||||
parsed.port = '32400';
|
||||
}
|
||||
return `${parsed.protocol}//${parsed.host}`;
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function hydratePlexAddressFieldsFromBaseUrl() {
|
||||
try {
|
||||
const parsed = new URL(plexBaseUrl || 'http://127.0.0.1:32400');
|
||||
plexServerUrl = `${parsed.protocol}//${parsed.host}`;
|
||||
} catch {
|
||||
plexServerUrl = 'http://127.0.0.1';
|
||||
}
|
||||
}
|
||||
|
||||
function canUsePlexRequests(): boolean {
|
||||
return plexEnabled && isLocalPlexAddress(plexServerUrl) && !!resolvePlexBaseUrl() && !!plexToken.trim();
|
||||
}
|
||||
|
||||
function persistPlexConfig() {
|
||||
plexBaseUrl = resolvePlexBaseUrl();
|
||||
setUserItem('qbz-plex-poc-base-url', plexBaseUrl);
|
||||
setUserItem('qbz-plex-poc-token', plexToken.trim());
|
||||
}
|
||||
|
||||
function persistPlexSelectedSections() {
|
||||
setUserItem(PLEX_CACHE_SELECTED_SECTIONS_KEY, JSON.stringify(plexSelectedSectionKeys));
|
||||
if (plexSelectedSectionKeys.length === 1) {
|
||||
setUserItem(PLEX_CACHE_SELECTED_SECTION_KEY, plexSelectedSectionKeys[0]);
|
||||
} else {
|
||||
removeUserItem(PLEX_CACHE_SELECTED_SECTION_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
function readPersistedPlexSelectedSections(): string[] {
|
||||
const raw = getUserItem(PLEX_CACHE_SELECTED_SECTIONS_KEY);
|
||||
if (raw) {
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed.filter((item): item is string => typeof item === 'string' && item.trim().length > 0);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed parsing persisted Plex section keys:', error);
|
||||
}
|
||||
}
|
||||
const legacySingle = getUserItem(PLEX_CACHE_SELECTED_SECTION_KEY);
|
||||
return legacySingle ? [legacySingle] : [];
|
||||
}
|
||||
|
||||
function handlePlexEnabledToggle(enabled: boolean) {
|
||||
plexEnabled = enabled;
|
||||
setUserItem(PLEX_ENABLED_KEY, enabled ? 'true' : 'false');
|
||||
if (!enabled) {
|
||||
plexStatusKey = 'settings.integrations.plexStatusDisabled';
|
||||
plexStatusValues = {};
|
||||
return;
|
||||
}
|
||||
plexStatusKey = 'settings.integrations.plexStatusIdle';
|
||||
plexStatusValues = {};
|
||||
void loadPlexCachedState();
|
||||
void refreshPlexInBackground();
|
||||
}
|
||||
|
||||
function togglePlexUiCollapsed() {
|
||||
plexUiCollapsed = !plexUiCollapsed;
|
||||
setUserItem(PLEX_UI_COLLAPSED_KEY, plexUiCollapsed ? 'true' : 'false');
|
||||
}
|
||||
|
||||
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 (!plexEnabled || plexAuthBusy || !isLocalPlexAddress(plexServerUrl) || !resolvePlexBaseUrl()) return;
|
||||
plexAuthBusy = true;
|
||||
plexLastError = '';
|
||||
persistPlexConfig();
|
||||
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 runPlexAutoSetup();
|
||||
} 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 handlePlexTokenBlur() {
|
||||
persistPlexConfig();
|
||||
if (canUsePlexRequests()) {
|
||||
await runPlexAutoSetup();
|
||||
}
|
||||
}
|
||||
|
||||
function setPlexError(error: unknown) {
|
||||
const message = String(error);
|
||||
plexLastError = message;
|
||||
plexStatusKey = 'settings.integrations.plexStatusError';
|
||||
plexStatusValues = { error: message };
|
||||
}
|
||||
|
||||
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 = [];
|
||||
plexSelectedSectionKeys = [];
|
||||
plexStatusKey = 'settings.integrations.plexStatusDisconnected';
|
||||
plexStatusValues = {};
|
||||
plexLastError = '';
|
||||
|
||||
removeUserItem('qbz-plex-poc-token');
|
||||
removeUserItem(PLEX_CACHE_SELECTED_SECTIONS_KEY);
|
||||
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');
|
||||
plexTracks = [];
|
||||
plexStatusKey = 'settings.integrations.plexStatusCacheCleared';
|
||||
plexStatusValues = {};
|
||||
plexLastError = '';
|
||||
removeUserItem(PLEX_CACHE_SERVER_ID_KEY);
|
||||
} catch (error) {
|
||||
console.error('Failed clearing Plex cache:', error);
|
||||
setPlexError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPlexCachedState() {
|
||||
if (!plexEnabled) return;
|
||||
try {
|
||||
const cachedSections = await invoke<PlexMusicSection[]>('plex_cache_get_sections');
|
||||
if (Array.isArray(cachedSections) && cachedSections.length > 0) {
|
||||
plexSections = cachedSections;
|
||||
}
|
||||
|
||||
const persistedSections = readPersistedPlexSelectedSections();
|
||||
if (persistedSections.length > 0) {
|
||||
plexSelectedSectionKeys = persistedSections;
|
||||
}
|
||||
|
||||
const cachedTracks = await invoke<PlexTrack[]>('plex_cache_get_tracks', {
|
||||
sectionKey: 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 (!canUsePlexRequests()) return;
|
||||
await runPlexAutoSetup();
|
||||
}
|
||||
|
||||
async function handlePlexPing(): Promise<boolean> {
|
||||
if (!canUsePlexRequests()) return false;
|
||||
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 || '?'
|
||||
};
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed Plex ping:', error);
|
||||
setPlexError(error);
|
||||
return false;
|
||||
} finally {
|
||||
plexBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function syncSelectedPlexLibraries() {
|
||||
if (!canUsePlexRequests()) return;
|
||||
plexBusy = true;
|
||||
plexLastError = '';
|
||||
try {
|
||||
const serverId = getUserItem(PLEX_CACHE_SERVER_ID_KEY) || null;
|
||||
await invoke('plex_cache_clear');
|
||||
|
||||
if (plexSections.length > 0) {
|
||||
await invoke<number>('plex_cache_save_sections', {
|
||||
serverId,
|
||||
sections: plexSections
|
||||
});
|
||||
}
|
||||
|
||||
if (plexSelectedSectionKeys.length === 0) {
|
||||
plexTracks = [];
|
||||
plexStatusKey = 'settings.integrations.plexStatusTracksLoaded';
|
||||
plexStatusValues = { count: 0 };
|
||||
return;
|
||||
}
|
||||
|
||||
let totalCount = 0;
|
||||
const sectionCounts: Record<string, number> = {};
|
||||
for (const sectionKey of plexSelectedSectionKeys) {
|
||||
const sectionTracks = await invoke<PlexTrack[]>('plex_get_section_tracks', {
|
||||
baseUrl: plexBaseUrl.trim(),
|
||||
token: plexToken.trim(),
|
||||
sectionKey
|
||||
});
|
||||
const count = sectionTracks.length;
|
||||
sectionCounts[sectionKey] = count;
|
||||
totalCount += count;
|
||||
await invoke<number>('plex_cache_save_tracks', {
|
||||
serverId,
|
||||
sectionKey,
|
||||
tracks: sectionTracks
|
||||
});
|
||||
}
|
||||
|
||||
plexSectionTrackCounts = { ...plexSectionTrackCounts, ...sectionCounts };
|
||||
plexTracks = await invoke<PlexTrack[]>('plex_cache_get_tracks', { sectionKey: null });
|
||||
plexStatusKey = 'settings.integrations.plexStatusTracksLoaded';
|
||||
plexStatusValues = { count: totalCount };
|
||||
} catch (error) {
|
||||
console.error('Failed syncing selected Plex libraries:', error);
|
||||
setPlexError(error);
|
||||
} finally {
|
||||
plexBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePlexLoadSections(options: { autoSyncSelected?: boolean } = {}) {
|
||||
if (!canUsePlexRequests()) 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
|
||||
});
|
||||
|
||||
const available = new Set(sections.map((section) => section.key));
|
||||
const persisted = readPersistedPlexSelectedSections().filter((key) => available.has(key));
|
||||
plexSelectedSectionKeys = persisted.length > 0 ? persisted : sections.map((section) => section.key);
|
||||
persistPlexSelectedSections();
|
||||
|
||||
plexStatusKey = 'settings.integrations.plexStatusSectionsLoaded';
|
||||
plexStatusValues = { count: sections.length };
|
||||
|
||||
if (options.autoSyncSelected !== false) {
|
||||
await syncSelectedPlexLibraries();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed loading Plex sections:', error);
|
||||
setPlexError(error);
|
||||
} finally {
|
||||
plexBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function runPlexAutoSetup() {
|
||||
const connected = await handlePlexPing();
|
||||
if (!connected) return;
|
||||
await handlePlexLoadSections({ autoSyncSelected: true });
|
||||
}
|
||||
|
||||
async function handlePlexLibraryToggle(sectionKey: string, checked: boolean) {
|
||||
const current = new Set(plexSelectedSectionKeys);
|
||||
if (checked) {
|
||||
current.add(sectionKey);
|
||||
} else {
|
||||
current.delete(sectionKey);
|
||||
const nextCounts = { ...plexSectionTrackCounts };
|
||||
delete nextCounts[sectionKey];
|
||||
plexSectionTrackCounts = nextCounts;
|
||||
}
|
||||
plexSelectedSectionKeys = plexSections
|
||||
.map((section) => section.key)
|
||||
.filter((key) => current.has(key));
|
||||
persistPlexSelectedSections();
|
||||
await syncSelectedPlexLibraries();
|
||||
}
|
||||
|
||||
async function loadRemoteControlStatus() {
|
||||
try {
|
||||
const status = await invoke<RemoteControlStatus>('remote_control_get_status');
|
||||
@@ -2968,7 +3493,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">
|
||||
@@ -2977,6 +3502,200 @@
|
||||
</div>
|
||||
<Toggle enabled={musicbrainzEnabled} onchange={handleMusicBrainzChange} />
|
||||
</div>
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<span class="setting-label">{$t('settings.integrations.plexConnection')}</span>
|
||||
<small class="setting-note">{$t('settings.integrations.plexConnectionLore')}</small>
|
||||
</div>
|
||||
<div class="setting-row-controls">
|
||||
<Toggle enabled={plexEnabled} onchange={handlePlexEnabledToggle} />
|
||||
<button
|
||||
class="setting-link-button section-collapse-btn"
|
||||
onclick={togglePlexUiCollapsed}
|
||||
title={$t('settings.integrations.plexCollapseHint')}
|
||||
>
|
||||
{#if plexUiCollapsed}
|
||||
<ChevronDown size={16} />
|
||||
{:else}
|
||||
<ChevronUp size={16} />
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if plexEnabled && !plexUiCollapsed}
|
||||
<div class="setting-row plex-two-column-row">
|
||||
<div class="setting-info">
|
||||
<span class="setting-label">{$t('settings.integrations.plexServerUrl')}:</span>
|
||||
<small class="setting-note">{$t('settings.integrations.plexServerUrlHelp')}</small>
|
||||
</div>
|
||||
<input
|
||||
id="plex-server-url"
|
||||
class="remote-control-input plex-server-url-input"
|
||||
type="text"
|
||||
bind:value={plexServerUrl}
|
||||
placeholder={$t('settings.integrations.plexServerUrlPlaceholder')}
|
||||
oninput={() => persistPlexConfig()}
|
||||
onblur={() => persistPlexConfig()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="setting-row plex-two-column-row">
|
||||
<div class="setting-info">
|
||||
<span class="setting-label">{$t('settings.integrations.plexAuthorizeLabel')}</span>
|
||||
<small class="setting-note">{$t('settings.integrations.plexAuthorizeGenerateHelp')}</small>
|
||||
</div>
|
||||
<button
|
||||
class="connect-btn plex-action-btn"
|
||||
onclick={handlePlexConnectEasy}
|
||||
disabled={plexBusy || plexAuthBusy || !isLocalPlexAddress(plexServerUrl) || !resolvePlexBaseUrl()}
|
||||
>
|
||||
{plexAuthBusy ? $t('actions.loading') : $t('settings.integrations.plexActionGenerateCode')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if plexAuthCode}
|
||||
<div class="plex-divider"></div>
|
||||
|
||||
<div class="setting-row plex-two-column-row">
|
||||
<div class="setting-info">
|
||||
<span class="setting-label">{$t('settings.integrations.plexLinkWithPlex')}</span>
|
||||
<small class="setting-note">{$t('settings.integrations.plexLinkWithPlexHelp')}</small>
|
||||
</div>
|
||||
<div class="plex-code-row">
|
||||
<input
|
||||
class="remote-control-input plex-code-input"
|
||||
type="text"
|
||||
readonly
|
||||
value={plexAuthCode}
|
||||
title={$t('settings.integrations.plexCodeTooltip')}
|
||||
/>
|
||||
<button
|
||||
class="connect-btn plex-action-btn"
|
||||
onclick={handleCopyPlexCode}
|
||||
title={$t('settings.integrations.plexCodeTooltip')}
|
||||
>
|
||||
{$t('settings.integrations.plexActionCopyCode')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="setting-row plex-two-column-row">
|
||||
<div class="setting-info">
|
||||
<span class="setting-label">{$t('settings.integrations.plexAuthorizeUsingCode')}</span>
|
||||
<small class="setting-note">{$t('settings.integrations.plexAuthorizeHelp')}</small>
|
||||
</div>
|
||||
<button
|
||||
class="connect-btn plex-action-btn"
|
||||
onclick={handleOpenPlexAuthUrl}
|
||||
disabled={!plexAuthUrl}
|
||||
>
|
||||
{$t('settings.integrations.plexActionOpenAuth')}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<span class="setting-label">{$t('settings.integrations.plexManualTokenToggle')}</span>
|
||||
<small class="setting-note">{$t('settings.integrations.plexManualTokenHelp')}</small>
|
||||
</div>
|
||||
<Toggle enabled={plexManualTokenMode} onchange={(enabled) => plexManualTokenMode = enabled} />
|
||||
</div>
|
||||
|
||||
{#if plexManualTokenMode}
|
||||
<div class="setting-row plex-two-column-row">
|
||||
<span class="setting-label">{$t('settings.integrations.plexToken')}</span>
|
||||
<input
|
||||
class="remote-control-input"
|
||||
type="password"
|
||||
bind:value={plexToken}
|
||||
placeholder={$t('settings.integrations.plexTokenPlaceholder')}
|
||||
onblur={handlePlexTokenBlur}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="setting-row plex-two-column-row">
|
||||
<div class="setting-info">
|
||||
<span class="setting-label">{$t('settings.integrations.plexConnectionCheckLabel')}</span>
|
||||
{#if plexStatusKey === 'settings.integrations.plexStatusConnected'}
|
||||
<small class="setting-note plex-connected-note">{$t(plexStatusKey, { values: plexStatusValues })}</small>
|
||||
{:else}
|
||||
<small class="setting-note">{$t(plexStatusKey, { values: plexStatusValues })}</small>
|
||||
{/if}
|
||||
</div>
|
||||
<button
|
||||
class="connect-btn plex-action-btn"
|
||||
onclick={() => handlePlexPing()}
|
||||
disabled={plexBusy || !canUsePlexRequests()}
|
||||
>
|
||||
{plexBusy ? $t('actions.loading') : $t('settings.integrations.plexActionPing')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="setting-row plex-two-column-row">
|
||||
<div class="setting-info">
|
||||
<span class="setting-label">{$t('settings.integrations.plexGetLibrariesLabel')}</span>
|
||||
<small class="setting-note">{$t('settings.integrations.plexGetLibrariesHelp')}</small>
|
||||
</div>
|
||||
<button
|
||||
class="connect-btn plex-action-btn"
|
||||
onclick={() => handlePlexLoadSections({ autoSyncSelected: true })}
|
||||
disabled={plexBusy || !canUsePlexRequests()}
|
||||
>
|
||||
{plexBusy ? $t('actions.loading') : $t('settings.integrations.plexActionLoadSections')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="setting-row plex-libraries-block">
|
||||
<span class="setting-label">{$t('settings.integrations.plexMusicLibraries')}</span>
|
||||
<div class="plex-libraries-grid">
|
||||
{#each plexSections as plexSection}
|
||||
<label class="plex-library-item">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={plexSelectedSectionKeys.includes(plexSection.key)}
|
||||
disabled={plexBusy || !canUsePlexRequests()}
|
||||
onchange={(event) => handlePlexLibraryToggle(plexSection.key, (event.currentTarget as HTMLInputElement).checked)}
|
||||
/>
|
||||
<span class="plex-library-name">{plexSection.title}</span>
|
||||
{#if plexSectionTrackCounts[plexSection.key] !== undefined}
|
||||
<span class="plex-library-count">({plexSectionTrackCounts[plexSection.key]} {$t('settings.integrations.plexTracksShort')})</span>
|
||||
{/if}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
{#if plexLastError}
|
||||
<small class="setting-note plex-error-note">{plexLastError}</small>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="setting-row plex-two-column-row">
|
||||
<span class="setting-label">{$t('settings.integrations.plexDisconnectRowLabel')}</span>
|
||||
<button
|
||||
class="connect-btn plex-action-btn"
|
||||
onclick={handlePlexDisconnect}
|
||||
disabled={plexBusy || plexAuthBusy || !plexToken.trim()}
|
||||
>
|
||||
{$t('settings.integrations.plexActionDisconnect')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="setting-row last plex-two-column-row">
|
||||
<div class="setting-info">
|
||||
<span class="setting-label">{$t('settings.integrations.plexClearCacheRowLabel')}</span>
|
||||
<small class="setting-note">{$t('settings.integrations.plexClearCacheRowHelp')}</small>
|
||||
</div>
|
||||
<button
|
||||
class="connect-btn plex-action-btn"
|
||||
onclick={handlePlexClearCache}
|
||||
disabled={plexBusy || plexAuthBusy}
|
||||
>
|
||||
{$t('settings.integrations.plexClearButton')}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<!-- Updates Section -->
|
||||
@@ -4648,6 +5367,124 @@ flatpak override --user --filesystem=/home/USUARIO/Música com.blitzfc.qbz</pre>
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.setting-row-controls {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.section-collapse-btn {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.plex-server-url-input {
|
||||
width: 210px;
|
||||
max-width: 210px;
|
||||
}
|
||||
|
||||
.plex-two-column-row {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.plex-divider {
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
background: var(--border-subtle);
|
||||
margin: 2px 0;
|
||||
}
|
||||
|
||||
.plex-code-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.plex-code-input {
|
||||
flex: 1;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.plex-action-btn {
|
||||
min-width: 170px;
|
||||
background: none;
|
||||
border: 1px solid var(--border-subtle);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.plex-action-btn:hover:not(:disabled) {
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border-default);
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.plex-libraries-block {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
align-items: start;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
min-height: unset;
|
||||
}
|
||||
|
||||
.setting-row.plex-libraries-block {
|
||||
height: auto;
|
||||
min-height: 48px;
|
||||
align-items: stretch;
|
||||
padding-bottom: 14px;
|
||||
}
|
||||
|
||||
.plex-libraries-grid {
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-tertiary);
|
||||
padding: 10px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px 16px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
max-height: 130px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.plex-library-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 28px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.plex-library-name {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.plex-library-count {
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.plex-connected-note {
|
||||
color: #86efac;
|
||||
}
|
||||
|
||||
.plex-error-note {
|
||||
color: #fca5a5;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
<MigrationModal
|
||||
|
||||
Reference in new issue
Block a user