Files
qbz/src/lib/components/views/SettingsView.svelte
T
vicrodh 19bad7200b feat(lastfm): improve auth flow with embedded credentials support
- Add support for build-time credentials via LASTFM_API_KEY/LASTFM_API_SECRET env vars
- Add lastfm_has_embedded_credentials command to check for embedded keys
- Add lastfm_open_auth_url command to open browser via native opener
- Simplify UI flow: if embedded credentials exist, just click Connect
- Add cancel button during authorization flow
- Clean up UI when waiting for user to authorize in browser
2026-01-09 13:02:05 -06:00

882 lines
23 KiB
Svelte

<script lang="ts">
import { onMount } from 'svelte';
import { invoke } from '@tauri-apps/api/core';
import { ArrowLeft } from 'lucide-svelte';
import Toggle from '../Toggle.svelte';
import Dropdown from '../Dropdown.svelte';
import VolumeSlider from '../VolumeSlider.svelte';
import Tooltip from '../Tooltip.svelte';
interface Props {
onBack?: () => void;
onLogout?: () => void;
userName?: string;
userEmail?: string;
subscription?: string;
}
interface CacheStats {
cached_tracks: number;
current_size_bytes: number;
max_size_bytes: number;
fetching_count: number;
}
interface AudioDevice {
name: string;
is_default: boolean;
}
let { onBack, onLogout, userName = 'User', userEmail = '', subscription = 'Qobuz' }: Props = $props();
// Cache state
let cacheStats = $state<CacheStats | null>(null);
let isClearing = $state(false);
// Audio device state
let audioDevices = $state<AudioDevice[]>([]);
let audioDeviceOptions = $derived(['System Default', ...audioDevices.map(d => d.name)]);
// Theme mapping: display name -> data-theme value
const themeMap: Record<string, string> = {
'Dark': '',
'Light': 'light',
'OLED Black': 'oled',
'Warm': 'warm'
};
const themeReverseMap: Record<string, string> = {
'': 'Dark',
'light': 'Light',
'oled': 'OLED Black',
'warm': 'Warm'
};
// Audio settings
let streamingQuality = $state('Hi-Res');
let preferHighest = $state(true);
let outputDevice = $state('System Default');
let exclusiveMode = $state(false);
let dacPassthrough = $state(false);
// Playback settings
let gaplessPlayback = $state(true);
let crossfade = $state(0);
let normalizeVolume = $state(false);
// Appearance settings
let theme = $state('Dark');
let compactMode = $state(false);
let language = $state('Auto');
// Last.fm integration state
let lastfmConnected = $state(false);
let lastfmUsername = $state('');
let scrobbling = $state(true);
let lastfmApiKey = $state('');
let lastfmApiSecret = $state('');
let lastfmAuthToken = $state('');
let lastfmConnecting = $state(false);
let showLastfmConfig = $state(false);
let hasEmbeddedCredentials = $state(false);
// Load saved settings on mount
onMount(() => {
// Load theme
const savedTheme = localStorage.getItem('qbz-theme') || '';
theme = themeReverseMap[savedTheme] || 'Dark';
applyTheme(savedTheme);
// Load streaming quality preference
const savedQuality = localStorage.getItem('qbz-streaming-quality');
if (savedQuality) {
streamingQuality = savedQuality;
}
// Load prefer highest setting
const savedPreferHighest = localStorage.getItem('qbz-prefer-highest');
if (savedPreferHighest !== null) {
preferHighest = savedPreferHighest === 'true';
}
// Load language setting
const savedLanguage = localStorage.getItem('qbz-language');
if (savedLanguage) {
language = savedLanguage;
}
// Load cache stats
loadCacheStats();
// Load audio devices
loadAudioDevices();
// Load Last.fm state
loadLastfmState();
});
async function loadLastfmState() {
try {
// Check if embedded (build-time) credentials are available
hasEmbeddedCredentials = await invoke<boolean>('lastfm_has_embedded_credentials');
// Load saved credentials from localStorage (for user-provided keys)
const savedApiKey = localStorage.getItem('qbz-lastfm-api-key');
const savedApiSecret = localStorage.getItem('qbz-lastfm-api-secret');
const savedSessionKey = localStorage.getItem('qbz-lastfm-session-key');
const savedUsername = localStorage.getItem('qbz-lastfm-username');
const savedScrobbling = localStorage.getItem('qbz-lastfm-scrobbling');
// If we have user-provided credentials, set them
if (savedApiKey && savedApiSecret) {
lastfmApiKey = savedApiKey;
lastfmApiSecret = savedApiSecret;
await invoke('lastfm_set_credentials', {
apiKey: savedApiKey,
apiSecret: savedApiSecret
});
}
// Restore session if available
if (savedSessionKey && savedUsername) {
await invoke('lastfm_set_session', { sessionKey: savedSessionKey });
lastfmConnected = true;
lastfmUsername = savedUsername;
}
if (savedScrobbling !== null) {
scrobbling = savedScrobbling === 'true';
}
} catch (err) {
console.error('Failed to load Last.fm state:', err);
}
}
async function handleLastfmConnect() {
// If we don't have credentials (embedded or user-provided), show config
const hasCredentials = hasEmbeddedCredentials || (lastfmApiKey && lastfmApiSecret);
if (!hasCredentials) {
showLastfmConfig = true;
return;
}
lastfmConnecting = true;
try {
// If user provided credentials, save and set them
if (lastfmApiKey && lastfmApiSecret) {
localStorage.setItem('qbz-lastfm-api-key', lastfmApiKey);
localStorage.setItem('qbz-lastfm-api-secret', lastfmApiSecret);
await invoke('lastfm_set_credentials', {
apiKey: lastfmApiKey,
apiSecret: lastfmApiSecret
});
}
// Get auth URL and token
const [token, url] = await invoke<[string, string]>('lastfm_get_auth_url');
lastfmAuthToken = token;
// Open browser for authorization using Tauri's native opener
try {
await invoke('lastfm_open_auth_url', { url });
} catch {
// Fallback to window.open if native opener fails
window.open(url, '_blank');
}
// Show the "I've Authorized" button
showLastfmConfig = true;
} catch (err) {
console.error('Failed to start Last.fm auth:', err);
alert(`Last.fm error: ${err}`);
} finally {
lastfmConnecting = false;
}
}
async function handleLastfmCompleteAuth() {
if (!lastfmAuthToken) {
alert('Please start the authorization first');
return;
}
lastfmConnecting = true;
try {
const session = await invoke<{ name: string; key: string }>('lastfm_authenticate', {
token: lastfmAuthToken
});
lastfmConnected = true;
lastfmUsername = session.name;
showLastfmConfig = false;
lastfmAuthToken = '';
// Save session
localStorage.setItem('qbz-lastfm-session-key', session.key);
localStorage.setItem('qbz-lastfm-username', session.name);
} catch (err) {
console.error('Failed to complete Last.fm auth:', err);
alert(`Authorization failed: ${err}`);
} finally {
lastfmConnecting = false;
}
}
async function handleLastfmDisconnect() {
try {
await invoke('lastfm_disconnect');
lastfmConnected = false;
lastfmUsername = '';
// Clear saved session
localStorage.removeItem('qbz-lastfm-session-key');
localStorage.removeItem('qbz-lastfm-username');
} catch (err) {
console.error('Failed to disconnect Last.fm:', err);
}
}
function handleScrobblingChange(enabled: boolean) {
scrobbling = enabled;
localStorage.setItem('qbz-lastfm-scrobbling', String(enabled));
}
function handleQualityChange(quality: string) {
streamingQuality = quality;
localStorage.setItem('qbz-streaming-quality', quality);
}
function handlePreferHighestChange(enabled: boolean) {
preferHighest = enabled;
localStorage.setItem('qbz-prefer-highest', String(enabled));
}
function handleLanguageChange(lang: string) {
language = lang;
localStorage.setItem('qbz-language', lang);
}
async function loadAudioDevices() {
try {
const devices = await invoke<AudioDevice[]>('get_audio_devices');
audioDevices = devices;
// Set current device to the default one
const defaultDevice = devices.find(d => d.is_default);
if (defaultDevice) {
outputDevice = defaultDevice.name;
}
} catch (err) {
console.error('Failed to load audio devices:', err);
}
}
async function loadCacheStats() {
try {
cacheStats = await invoke<CacheStats>('get_cache_stats');
} catch (err) {
console.error('Failed to load cache stats:', err);
}
}
async function handleClearCache() {
if (isClearing) return;
isClearing = true;
try {
await invoke('clear_cache');
await loadCacheStats();
} catch (err) {
console.error('Failed to clear cache:', err);
} finally {
isClearing = false;
}
}
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
}
function applyTheme(themeValue: string) {
if (themeValue) {
document.documentElement.setAttribute('data-theme', themeValue);
} else {
document.documentElement.removeAttribute('data-theme');
}
}
function handleThemeChange(newTheme: string) {
theme = newTheme;
const themeValue = themeMap[newTheme] || '';
applyTheme(themeValue);
localStorage.setItem('qbz-theme', themeValue);
}
</script>
<div class="settings-view">
<!-- Header -->
<div class="header">
{#if onBack}
<button class="back-btn" onclick={onBack}>
<ArrowLeft size={16} />
<span>Back</span>
</button>
{/if}
<h1 class="title">Settings</h1>
</div>
<!-- Account Section -->
<section class="section">
<h3 class="section-title">Account</h3>
<div class="account-card">
<div class="avatar">{userName.charAt(0).toUpperCase()}</div>
<div class="account-info">
<div class="username">{userName}</div>
{#if userEmail}
<div class="email">{userEmail}</div>
{/if}
<div class="subscription">{subscription}</div>
</div>
<button class="logout-btn" onclick={onLogout}>Logout</button>
</div>
</section>
<!-- Audio Section -->
<section class="section">
<h3 class="section-title">Audio</h3>
<div class="setting-row">
<span class="setting-label">Streaming Quality</span>
<Dropdown
value={streamingQuality}
options={['MP3', 'CD Quality', 'Hi-Res', 'Hi-Res+']}
onchange={handleQualityChange}
/>
</div>
<div class="setting-row">
<span class="setting-label">Prefer highest available</span>
<Toggle enabled={preferHighest} onchange={handlePreferHighestChange} />
</div>
<div class="setting-row">
<span class="setting-label">Output Device</span>
<Dropdown
value={outputDevice}
options={audioDeviceOptions.length > 1 ? audioDeviceOptions : ['System Default']}
onchange={(v) => (outputDevice = v)}
/>
</div>
<div class="setting-row">
<div class="label-with-tooltip">
<span class="setting-label">Exclusive Mode</span>
<Tooltip text="Locks the audio device for exclusive use by QBZ for better quality" />
</div>
<Toggle enabled={exclusiveMode} onchange={(v) => (exclusiveMode = v)} />
</div>
<div class="setting-row">
<div class="label-with-tooltip">
<span class="setting-label">DAC Passthrough</span>
<Tooltip text="Bypass the system audio mixer to send audio directly to your DAC at its native sample rate. Recommended for external DACs." />
</div>
<Toggle enabled={dacPassthrough} onchange={(v) => (dacPassthrough = v)} />
</div>
<div class="setting-row last">
<span class="setting-label">Sample Rate</span>
<span class="setting-value">192 kHz</span>
</div>
</section>
<!-- Playback Section -->
<section class="section">
<h3 class="section-title">Playback</h3>
<div class="setting-row">
<span class="setting-label">Gapless Playback</span>
<Toggle enabled={gaplessPlayback} onchange={(v) => (gaplessPlayback = v)} />
</div>
<div class="setting-row">
<span class="setting-label">Crossfade</span>
<div class="slider-container">
<VolumeSlider value={crossfade} onchange={(v) => (crossfade = v)} max={12} showValue />
</div>
</div>
<div class="setting-row last">
<span class="setting-label">Normalize Volume</span>
<Toggle enabled={normalizeVolume} onchange={(v) => (normalizeVolume = v)} />
</div>
</section>
<!-- Appearance Section -->
<section class="section">
<h3 class="section-title">Appearance</h3>
<div class="setting-row">
<span class="setting-label">Theme</span>
<Dropdown
value={theme}
options={['Dark', 'Light', 'OLED Black', 'Warm']}
onchange={handleThemeChange}
/>
</div>
<div class="setting-row">
<span class="setting-label">Language</span>
<Dropdown
value={language}
options={['Auto', 'English', 'Español', 'Français', 'Deutsch', 'Italiano', 'Português']}
onchange={handleLanguageChange}
/>
</div>
<div class="setting-row last">
<span class="setting-label">Compact Mode</span>
<Toggle enabled={compactMode} onchange={(v) => (compactMode = v)} />
</div>
</section>
<!-- Integrations Section -->
<section class="section">
<h3 class="section-title">Integrations</h3>
{#if lastfmConnected}
<div class="setting-row">
<div class="lastfm-connected">
<span class="setting-label">Last.fm</span>
<span class="lastfm-username">Connected as {lastfmUsername}</span>
</div>
<button
class="connect-btn connected"
onclick={handleLastfmDisconnect}
>
Disconnect
</button>
</div>
<div class="setting-row last">
<span class="setting-label">Scrobbling</span>
<Toggle enabled={scrobbling} onchange={handleScrobblingChange} />
</div>
{:else}
<div class="setting-row" class:last={!showLastfmConfig && !lastfmAuthToken}>
<span class="setting-label">Last.fm</span>
<button
class="connect-btn"
onclick={handleLastfmConnect}
disabled={lastfmConnecting}
>
{lastfmConnecting ? 'Connecting...' : 'Connect'}
</button>
</div>
{#if lastfmAuthToken}
<!-- Waiting for user to authorize in browser -->
<div class="lastfm-config">
<p class="auth-info">
A browser window has been opened. Please authorize QBZ on Last.fm, then click the button below.
</p>
<button
class="auth-complete-btn"
onclick={handleLastfmCompleteAuth}
disabled={lastfmConnecting}
>
{lastfmConnecting ? 'Verifying...' : 'I\'ve Authorized'}
</button>
<button
class="auth-cancel-btn"
onclick={() => { lastfmAuthToken = ''; showLastfmConfig = false; }}
>
Cancel
</button>
</div>
{:else if showLastfmConfig && !hasEmbeddedCredentials}
<!-- No embedded credentials, user needs to provide their own -->
<div class="lastfm-config">
<p class="config-info">
QBZ needs Last.fm API credentials to enable scrobbling.
<a href="https://www.last.fm/api/account/create" target="_blank" rel="noopener">
Create an API account
</a> and enter your credentials below.
</p>
<div class="config-field">
<label for="lastfm-api-key">API Key</label>
<input
id="lastfm-api-key"
type="text"
bind:value={lastfmApiKey}
placeholder="Enter your API key"
/>
</div>
<div class="config-field">
<label for="lastfm-api-secret">Shared Secret</label>
<input
id="lastfm-api-secret"
type="password"
bind:value={lastfmApiSecret}
placeholder="Enter your shared secret"
/>
</div>
<button
class="auth-start-btn"
onclick={handleLastfmConnect}
disabled={!lastfmApiKey || !lastfmApiSecret || lastfmConnecting}
>
{lastfmConnecting ? 'Opening...' : 'Authorize with Last.fm'}
</button>
</div>
{/if}
{/if}
</section>
<!-- Storage Section -->
<section class="section">
<h3 class="section-title">Storage</h3>
<div class="setting-row">
<span class="setting-label">Cache Size</span>
<span class="setting-value">
{#if cacheStats}
{formatBytes(cacheStats.current_size_bytes)} / {formatBytes(cacheStats.max_size_bytes)}
{:else}
Loading...
{/if}
</span>
</div>
<div class="setting-row">
<span class="setting-label">Cached Tracks</span>
<span class="setting-value">
{#if cacheStats}
{cacheStats.cached_tracks} tracks
{:else}
-
{/if}
</span>
</div>
<div class="setting-row last">
<span class="setting-label">Clear Cache</span>
<button
class="clear-btn"
onclick={handleClearCache}
disabled={isClearing || !cacheStats || cacheStats.current_size_bytes === 0}
>
{isClearing ? 'Clearing...' : 'Clear'}
</button>
</div>
</section>
</div>
<style>
.settings-view {
width: 100%;
}
.header {
margin-bottom: 32px;
}
.back-btn {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
color: var(--text-muted);
background: none;
border: none;
cursor: pointer;
margin-bottom: 16px;
transition: color 150ms ease;
}
.back-btn:hover {
color: var(--text-secondary);
}
.title {
font-size: 28px;
font-weight: 700;
color: var(--text-primary);
}
.section {
background-color: var(--bg-secondary);
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
}
.section-title {
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
margin-bottom: 16px;
}
.account-card {
display: flex;
align-items: center;
gap: 16px;
padding: 16px 0;
}
.avatar {
width: 72px;
height: 72px;
border-radius: 50%;
background-color: var(--accent-primary);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 24px;
font-weight: 600;
}
.account-info {
flex: 1;
}
.username {
font-size: 18px;
font-weight: 600;
color: var(--text-primary);
}
.email {
font-size: 14px;
color: var(--text-muted);
}
.subscription {
font-size: 14px;
color: var(--accent-primary);
}
.logout-btn {
padding: 8px 24px;
border-radius: 8px;
border: 1px solid #ff6b6b;
background: none;
color: #ff6b6b;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background-color 150ms ease;
}
.logout-btn:hover {
background-color: rgba(255, 107, 107, 0.1);
}
.setting-row {
display: flex;
align-items: center;
justify-content: space-between;
height: 48px;
border-bottom: 1px solid var(--bg-tertiary);
}
.setting-row.last {
border-bottom: none;
}
.setting-label {
font-size: 14px;
color: var(--text-secondary);
}
.setting-value {
font-size: 14px;
color: var(--text-muted);
}
.label-with-tooltip {
display: flex;
align-items: center;
gap: 8px;
}
.slider-container {
width: 240px;
}
.connect-btn {
padding: 8px 16px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 150ms ease;
background-color: var(--accent-primary);
color: white;
border: none;
}
.connect-btn:hover {
background-color: var(--accent-hover);
}
.connect-btn.connected {
background: none;
border: 1px solid var(--text-muted);
color: var(--text-muted);
}
.connect-btn.connected:hover {
border-color: var(--text-secondary);
color: var(--text-secondary);
}
.clear-btn {
padding: 8px 16px;
border-radius: 8px;
border: 1px solid #ff6b6b;
background: none;
color: #ff6b6b;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background-color 150ms ease;
}
.clear-btn:hover:not(:disabled) {
background-color: rgba(255, 107, 107, 0.1);
}
.clear-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Last.fm styles */
.lastfm-connected {
display: flex;
flex-direction: column;
gap: 4px;
}
.lastfm-username {
font-size: 12px;
color: var(--accent-primary);
}
.lastfm-config {
padding: 16px;
background-color: var(--bg-tertiary);
border-radius: 8px;
margin-top: 8px;
}
.config-info {
font-size: 13px;
color: var(--text-muted);
margin-bottom: 16px;
}
.config-info a {
color: var(--accent-primary);
text-decoration: none;
}
.config-info a:hover {
text-decoration: underline;
}
.config-field {
margin-bottom: 12px;
}
.config-field label {
display: block;
font-size: 12px;
color: var(--text-muted);
margin-bottom: 4px;
}
.config-field input {
width: 100%;
padding: 8px 12px;
background-color: var(--bg-secondary);
border: 1px solid var(--border-subtle);
border-radius: 6px;
color: var(--text-primary);
font-size: 14px;
}
.config-field input:focus {
outline: none;
border-color: var(--accent-primary);
}
.config-field input::placeholder {
color: var(--text-disabled);
}
.auth-info {
font-size: 13px;
color: var(--text-secondary);
margin: 16px 0;
padding: 12px;
background-color: var(--bg-secondary);
border-radius: 6px;
}
.auth-start-btn,
.auth-complete-btn {
width: 100%;
padding: 10px 16px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 150ms ease;
}
.auth-start-btn {
background-color: var(--accent-primary);
color: white;
border: none;
}
.auth-start-btn:hover:not(:disabled) {
background-color: var(--accent-hover);
}
.auth-start-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.auth-complete-btn {
background-color: #1db954;
color: white;
border: none;
}
.auth-complete-btn:hover:not(:disabled) {
background-color: #1ed760;
}
.auth-complete-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.auth-cancel-btn {
width: 100%;
padding: 10px 16px;
margin-top: 8px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 150ms ease;
background: none;
border: 1px solid var(--text-muted);
color: var(--text-muted);
}
.auth-cancel-btn:hover {
border-color: var(--text-secondary);
color: var(--text-secondary);
}
.connect-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>