Implement session persistence between app restarts
Backend (Rust): - Create session_store module with SQLite database - Store queue tracks, current index, position, volume, shuffle/repeat - Add Tauri commands: save_session_state, load_session_state, etc. - Use WAL mode for better concurrent access Frontend (TypeScript): - Create sessionService.ts with save/load functions - Restore session after login (queue, track info, volume, modes) - Save session on beforeunload and visibility change - Clear session on logout - Debounced position saving during playback Users can now close the app and resume where they left off.
This commit is contained in:
1 parent
e9e82329bd
commit
ddc9497286
4 files changed
+681
-1
No files matched your search
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* Session Persistence Service
|
||||
*
|
||||
* Handles saving and restoring playback state between app sessions.
|
||||
* Saves: queue, current track, position, volume, shuffle/repeat modes
|
||||
*/
|
||||
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
|
||||
export interface PersistedQueueTrack {
|
||||
id: number;
|
||||
title: string;
|
||||
artist: string;
|
||||
album: string;
|
||||
duration_secs: number;
|
||||
artwork_url: string | null;
|
||||
}
|
||||
|
||||
export interface PersistedSession {
|
||||
queue_tracks: PersistedQueueTrack[];
|
||||
current_index: number | null;
|
||||
current_position_secs: number;
|
||||
volume: number;
|
||||
shuffle_enabled: boolean;
|
||||
repeat_mode: string; // "off" | "all" | "one"
|
||||
was_playing: boolean;
|
||||
saved_at: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the complete session state
|
||||
*/
|
||||
export async function saveSessionState(
|
||||
queueTracks: PersistedQueueTrack[],
|
||||
currentIndex: number | null,
|
||||
currentPositionSecs: number,
|
||||
volume: number,
|
||||
shuffleEnabled: boolean,
|
||||
repeatMode: string,
|
||||
wasPlaying: boolean
|
||||
): Promise<void> {
|
||||
try {
|
||||
await invoke('save_session_state', {
|
||||
queueTracks,
|
||||
currentIndex,
|
||||
currentPositionSecs,
|
||||
volume,
|
||||
shuffleEnabled,
|
||||
repeatMode,
|
||||
wasPlaying,
|
||||
});
|
||||
console.log('[Session] State saved successfully');
|
||||
} catch (err) {
|
||||
console.error('[Session] Failed to save state:', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the persisted session state
|
||||
*/
|
||||
export async function loadSessionState(): Promise<PersistedSession | null> {
|
||||
try {
|
||||
const session = await invoke<PersistedSession>('load_session_state');
|
||||
console.log('[Session] State loaded:', {
|
||||
tracks: session.queue_tracks.length,
|
||||
currentIndex: session.current_index,
|
||||
position: session.current_position_secs,
|
||||
volume: session.volume,
|
||||
});
|
||||
return session;
|
||||
} catch (err) {
|
||||
console.error('[Session] Failed to load state:', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick save of just the playback position (debounced during playback)
|
||||
*/
|
||||
export async function saveSessionPosition(positionSecs: number): Promise<void> {
|
||||
try {
|
||||
await invoke('save_session_position', { positionSecs });
|
||||
} catch (err) {
|
||||
console.error('[Session] Failed to save position:', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick save of volume
|
||||
*/
|
||||
export async function saveSessionVolume(volume: number): Promise<void> {
|
||||
try {
|
||||
await invoke('save_session_volume', { volume });
|
||||
} catch (err) {
|
||||
console.error('[Session] Failed to save volume:', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save shuffle and repeat mode
|
||||
*/
|
||||
export async function saveSessionPlaybackMode(
|
||||
shuffle: boolean,
|
||||
repeatMode: string
|
||||
): Promise<void> {
|
||||
try {
|
||||
await invoke('save_session_playback_mode', { shuffle, repeatMode });
|
||||
} catch (err) {
|
||||
console.error('[Session] Failed to save playback mode:', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the session (e.g., on logout)
|
||||
*/
|
||||
export async function clearSession(): Promise<void> {
|
||||
try {
|
||||
await invoke('clear_session');
|
||||
console.log('[Session] Session cleared');
|
||||
} catch (err) {
|
||||
console.error('[Session] Failed to clear session:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// Debounce helper for position saves
|
||||
let positionSaveTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
const POSITION_SAVE_DEBOUNCE_MS = 5000; // Save position every 5 seconds max
|
||||
|
||||
/**
|
||||
* Debounced position save - call frequently, saves every 5 seconds
|
||||
*/
|
||||
export function debouncedSavePosition(positionSecs: number): void {
|
||||
if (positionSaveTimeout) {
|
||||
clearTimeout(positionSaveTimeout);
|
||||
}
|
||||
positionSaveTimeout = setTimeout(() => {
|
||||
saveSessionPosition(positionSecs);
|
||||
positionSaveTimeout = null;
|
||||
}, POSITION_SAVE_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Force save position immediately (e.g., on pause or app close)
|
||||
*/
|
||||
export function flushPositionSave(positionSecs: number): void {
|
||||
if (positionSaveTimeout) {
|
||||
clearTimeout(positionSaveTimeout);
|
||||
positionSaveTimeout = null;
|
||||
}
|
||||
saveSessionPosition(positionSecs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a complete session state from current app state and save it
|
||||
*/
|
||||
export async function saveCurrentSession(
|
||||
getQueueState: () => { tracks: Array<{ id: number; title: string; artist: string; album: string; duration_secs: number; artwork_url: string | null }>; currentIndex: number | null },
|
||||
getPlayerState: () => { currentTime: number; volume: number; isPlaying: boolean },
|
||||
getPlaybackMode: () => { shuffle: boolean; repeat: string }
|
||||
): Promise<void> {
|
||||
const queueState = getQueueState();
|
||||
const playerState = getPlayerState();
|
||||
const playbackMode = getPlaybackMode();
|
||||
|
||||
await saveSessionState(
|
||||
queueState.tracks,
|
||||
queueState.currentIndex,
|
||||
Math.floor(playerState.currentTime),
|
||||
playerState.volume / 100, // Convert 0-100 to 0-1
|
||||
playbackMode.shuffle,
|
||||
playbackMode.repeat,
|
||||
playerState.isPlaying
|
||||
);
|
||||
}
|
||||
+138
-1
@@ -170,6 +170,18 @@
|
||||
// Recommendation scoring
|
||||
import { trainScores } from '$lib/services/recoService';
|
||||
|
||||
// Session persistence
|
||||
import {
|
||||
loadSessionState,
|
||||
saveSessionState,
|
||||
saveSessionVolume,
|
||||
saveSessionPlaybackMode,
|
||||
debouncedSavePosition,
|
||||
flushPositionSave,
|
||||
clearSession,
|
||||
type PersistedQueueTrack
|
||||
} from '$lib/services/sessionService';
|
||||
|
||||
// Lyrics state management
|
||||
import {
|
||||
subscribe as subscribeLyrics,
|
||||
@@ -783,7 +795,7 @@
|
||||
}
|
||||
|
||||
// Auth Handlers
|
||||
function handleLoginSuccess(info: UserInfo) {
|
||||
async function handleLoginSuccess(info: UserInfo) {
|
||||
setLoggedIn(info);
|
||||
showToast(`Welcome, ${info.userName}!`, 'success');
|
||||
|
||||
@@ -793,6 +805,64 @@
|
||||
}).catch(err => {
|
||||
console.debug('[Reco] Score training failed:', err);
|
||||
});
|
||||
|
||||
// Restore previous session if available
|
||||
try {
|
||||
const session = await loadSessionState();
|
||||
if (session && session.queue_tracks.length > 0) {
|
||||
console.log('[Session] Restoring previous session...');
|
||||
|
||||
// Restore queue
|
||||
const tracks: BackendQueueTrack[] = session.queue_tracks.map(t => ({
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
artist: t.artist,
|
||||
album: t.album,
|
||||
duration_secs: t.duration_secs,
|
||||
artwork_url: t.artwork_url
|
||||
}));
|
||||
|
||||
await setQueue(tracks, session.current_index ?? 0, true);
|
||||
|
||||
// Restore shuffle/repeat mode
|
||||
if (session.shuffle_enabled) {
|
||||
await invoke('set_shuffle', { enabled: true });
|
||||
}
|
||||
if (session.repeat_mode !== 'off') {
|
||||
await invoke('set_repeat', { mode: session.repeat_mode });
|
||||
}
|
||||
|
||||
// Restore volume
|
||||
playerSetVolume(Math.round(session.volume * 100));
|
||||
|
||||
// If there was a track playing, restore it (paused)
|
||||
if (session.current_index !== null && tracks[session.current_index]) {
|
||||
const track = tracks[session.current_index];
|
||||
showToast(`Restored: ${track.title}`, 'info');
|
||||
|
||||
// Set the current track info without auto-playing
|
||||
setCurrentTrack({
|
||||
id: track.id,
|
||||
title: track.title,
|
||||
artist: track.artist,
|
||||
album: track.album,
|
||||
artwork: track.artwork_url || '',
|
||||
duration: track.duration_secs,
|
||||
quality: 'Restored',
|
||||
});
|
||||
|
||||
// Seek to saved position if > 0
|
||||
if (session.current_position_secs > 0) {
|
||||
// Note: actual seek will happen when user presses play
|
||||
console.log(`[Session] Will resume at ${session.current_position_secs}s`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[Session] Session restored successfully');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Session] Failed to restore session:', err);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
@@ -806,6 +876,8 @@
|
||||
console.error('Failed to clear credentials:', clearErr);
|
||||
// Don't block logout if clearing fails
|
||||
}
|
||||
// Clear session state
|
||||
await clearSession();
|
||||
setLoggedOut();
|
||||
currentTrack = null;
|
||||
isPlaying = false;
|
||||
@@ -816,6 +888,53 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Save session state before window closes
|
||||
async function saveSessionBeforeClose() {
|
||||
if (!isLoggedIn || !currentTrack) return;
|
||||
|
||||
try {
|
||||
// Get current queue state from backend
|
||||
const queueState = await getBackendQueueState();
|
||||
if (!queueState) return;
|
||||
|
||||
// Build persisted queue tracks
|
||||
const allTracks: PersistedQueueTrack[] = [];
|
||||
if (queueState.current_track) {
|
||||
allTracks.push({
|
||||
id: queueState.current_track.id,
|
||||
title: queueState.current_track.title,
|
||||
artist: queueState.current_track.artist,
|
||||
album: queueState.current_track.album,
|
||||
duration_secs: queueState.current_track.duration_secs,
|
||||
artwork_url: queueState.current_track.artwork_url
|
||||
});
|
||||
}
|
||||
for (const track of queueState.upcoming) {
|
||||
allTracks.push({
|
||||
id: track.id,
|
||||
title: track.title,
|
||||
artist: track.artist,
|
||||
album: track.album,
|
||||
duration_secs: track.duration_secs,
|
||||
artwork_url: track.artwork_url
|
||||
});
|
||||
}
|
||||
|
||||
await saveSessionState(
|
||||
allTracks,
|
||||
queueState.current_index,
|
||||
Math.floor(currentTime),
|
||||
volume / 100,
|
||||
isShuffle,
|
||||
repeatMode,
|
||||
isPlaying
|
||||
);
|
||||
console.log('[Session] Session saved on close');
|
||||
} catch (err) {
|
||||
console.error('[Session] Failed to save session on close:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// Keyboard Shortcuts
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (!isLoggedIn) return;
|
||||
@@ -884,6 +1003,20 @@
|
||||
// Keyboard navigation
|
||||
document.addEventListener('keydown', handleKeydown);
|
||||
|
||||
// Session save on window close/hide
|
||||
const handleBeforeUnload = () => {
|
||||
saveSessionBeforeClose();
|
||||
};
|
||||
window.addEventListener('beforeunload', handleBeforeUnload);
|
||||
|
||||
// Also save when visibility changes (app goes to background)
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
saveSessionBeforeClose();
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
|
||||
// Initialize download states
|
||||
initDownloadStates();
|
||||
startDownloadEventListeners();
|
||||
@@ -977,8 +1110,12 @@
|
||||
});
|
||||
|
||||
return () => {
|
||||
// Save session before cleanup
|
||||
saveSessionBeforeClose();
|
||||
cleanupBootstrap();
|
||||
document.removeEventListener('keydown', handleKeydown);
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload);
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
stopDownloadEventListeners();
|
||||
unsubscribeDownloads();
|
||||
unsubscribeToast();
|
||||
|
||||
Reference in new issue
Block a user