feat(settings): add global autoplay mode preference (backend)

- Create PlaybackPreferences config module with SQLite persistence
- Add AutoplayMode enum (ContinueWithinSource | PlayTrackOnly)
- Register Tauri commands: get_playback_preferences, set_autoplay_mode
- Create playbackPreferencesStore for frontend state management
- Add loadPlaybackPreferences to SettingsView
- Default: Continue within source (creates context on track click)
- Settings UI pending (next commit)

cp
This commit is contained in:
vicrodh committed 2026-01-18 00:49:45 -06:00
1 parent 515632913d
commit dbdd664415
5 files changed
+276

No files matched your search

+10
View File
@@ -4,12 +4,14 @@
//! - User credentials (encrypted) //! - User credentials (encrypted)
//! - Audio preferences //! - Audio preferences
//! - Download preferences //! - Download preferences
//! - Playback preferences
//! - UI preferences //! - UI preferences
//! - Local playlists //! - Local playlists
//! - Cached favorites //! - Cached favorites
pub mod audio_settings; pub mod audio_settings;
pub mod download_settings; pub mod download_settings;
pub mod playback_preferences;
pub use audio_settings::{ pub use audio_settings::{
AudioSettings, AudioSettings,
@@ -29,3 +31,11 @@ pub use download_settings::{
set_show_downloads_in_library, set_show_downloads_in_library,
validate_download_root, validate_download_root,
}; };
pub use playback_preferences::{
AutoplayMode,
PlaybackPreferences,
PlaybackPreferencesState,
get_playback_preferences,
set_autoplay_mode,
};
@@ -0,0 +1,150 @@
//! Playback preferences
//!
//! Stores user preferences for playback behavior (autoplay mode, etc.)
use rusqlite::{Connection, params};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AutoplayMode {
/// Continue playing within the source (album, playlist, etc.)
ContinueWithinSource,
/// Play only the selected track, then stop
PlayTrackOnly,
}
impl Default for AutoplayMode {
fn default() -> Self {
Self::ContinueWithinSource
}
}
impl AutoplayMode {
fn to_db_value(&self) -> &'static str {
match self {
AutoplayMode::ContinueWithinSource => "continue",
AutoplayMode::PlayTrackOnly => "track_only",
}
}
fn from_db_value(s: &str) -> Self {
match s {
"track_only" => AutoplayMode::PlayTrackOnly,
_ => AutoplayMode::ContinueWithinSource,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlaybackPreferences {
pub autoplay_mode: AutoplayMode,
}
impl Default for PlaybackPreferences {
fn default() -> Self {
Self {
autoplay_mode: AutoplayMode::ContinueWithinSource,
}
}
}
pub struct PlaybackPreferencesStore {
conn: Connection,
}
impl PlaybackPreferencesStore {
pub fn new() -> Result<Self, String> {
let data_dir = dirs::data_dir()
.ok_or("Could not determine data directory")?
.join("qbz");
std::fs::create_dir_all(&data_dir)
.map_err(|e| format!("Failed to create data directory: {}", e))?;
let db_path = data_dir.join("playback_preferences.db");
let conn = Connection::open(&db_path)
.map_err(|e| format!("Failed to open playback preferences database: {}", e))?;
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS playback_preferences (
id INTEGER PRIMARY KEY CHECK (id = 1),
autoplay_mode TEXT NOT NULL DEFAULT 'continue'
);
INSERT OR IGNORE INTO playback_preferences (id, autoplay_mode)
VALUES (1, 'continue');"
).map_err(|e| format!("Failed to create playback preferences table: {}", e))?;
Ok(Self { conn })
}
pub fn get_preferences(&self) -> Result<PlaybackPreferences, String> {
self.conn
.query_row(
"SELECT autoplay_mode FROM playback_preferences WHERE id = 1",
[],
|row| {
let autoplay_str: String = row.get(0)?;
Ok(PlaybackPreferences {
autoplay_mode: AutoplayMode::from_db_value(&autoplay_str),
})
},
)
.map_err(|e| format!("Failed to get playback preferences: {}", e))
}
pub fn set_autoplay_mode(&self, mode: AutoplayMode) -> Result<(), String> {
self.conn
.execute(
"UPDATE playback_preferences SET autoplay_mode = ?1 WHERE id = 1",
params![mode.to_db_value()],
)
.map_err(|e| format!("Failed to set autoplay mode: {}", e))?;
Ok(())
}
}
/// Global state wrapper for thread-safe access
pub struct PlaybackPreferencesState {
store: Arc<Mutex<PlaybackPreferencesStore>>,
}
impl PlaybackPreferencesState {
pub fn new() -> Result<Self, String> {
let store = PlaybackPreferencesStore::new()?;
Ok(Self {
store: Arc::new(Mutex::new(store)),
})
}
pub fn get_preferences(&self) -> Result<PlaybackPreferences, String> {
self.store.lock().unwrap().get_preferences()
}
pub fn set_autoplay_mode(&self, mode: AutoplayMode) -> Result<(), String> {
self.store.lock().unwrap().set_autoplay_mode(mode)
}
}
// Tauri commands
#[tauri::command]
pub fn get_playback_preferences(
state: tauri::State<PlaybackPreferencesState>,
) -> Result<PlaybackPreferences, String> {
state.get_preferences()
}
#[tauri::command]
pub fn set_autoplay_mode(
mode: String,
state: tauri::State<PlaybackPreferencesState>,
) -> Result<(), String> {
let autoplay_mode = match mode.as_str() {
"continue" => AutoplayMode::ContinueWithinSource,
"track_only" => AutoplayMode::PlayTrackOnly,
_ => return Err(format!("Invalid autoplay mode: {}", mode)),
};
state.set_autoplay_mode(autoplay_mode)
}
+7
View File
@@ -172,6 +172,9 @@ pub fn run() {
// Initialize offline mode state // Initialize offline mode state
let offline_state = offline::OfflineState::new() let offline_state = offline::OfflineState::new()
.expect("Failed to initialize offline state"); .expect("Failed to initialize offline state");
// Initialize playback preferences state
let playback_prefs_state = config::playback_preferences::PlaybackPreferencesState::new()
.expect("Failed to initialize playback preferences");
// Read saved audio device and settings for player initialization // Read saved audio device and settings for player initialization
let (saved_device, audio_settings) = audio_settings_state let (saved_device, audio_settings) = audio_settings_state
@@ -296,6 +299,7 @@ pub fn run() {
.manage(audio_settings_state) .manage(audio_settings_state)
.manage(download_settings_state) .manage(download_settings_state)
.manage(offline_state) .manage(offline_state)
.manage(playback_prefs_state)
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
// Auth commands // Auth commands
commands::init_client, commands::init_client,
@@ -569,6 +573,9 @@ pub fn run() {
offline::commands::set_manual_offline, offline::commands::set_manual_offline,
offline::commands::set_show_partial_playlists, offline::commands::set_show_partial_playlists,
offline::commands::set_allow_cast_while_offline, offline::commands::set_allow_cast_while_offline,
// Playback preferences commands
config::playback_preferences::get_playback_preferences,
config::playback_preferences::set_autoplay_mode,
offline::commands::set_allow_immediate_scrobbling, offline::commands::set_allow_immediate_scrobbling,
offline::commands::set_allow_accumulated_scrobbling, offline::commands::set_allow_accumulated_scrobbling,
offline::commands::set_show_network_folders_in_manual_offline, offline::commands::set_show_network_folders_in_manual_offline,
@@ -43,6 +43,11 @@
type OfflineSettings type OfflineSettings
} from '$lib/stores/offlineStore'; } from '$lib/stores/offlineStore';
import { showToast } from '$lib/stores/toastStore'; import { showToast } from '$lib/stores/toastStore';
import {
getPlaybackPreferences,
setAutoplayMode,
type AutoplayMode
} from '$lib/stores/playbackPreferencesStore';
interface Props { interface Props {
onBack?: () => void; onBack?: () => void;
@@ -310,6 +315,7 @@
); );
// Playback settings // Playback settings
let autoplayMode = $state<AutoplayMode>('continue');
let gaplessPlayback = $state(true); let gaplessPlayback = $state(true);
let crossfade = $state(0); let crossfade = $state(0);
let normalizeVolume = $state(false); let normalizeVolume = $state(false);
@@ -417,6 +423,9 @@
loadSystemNotificationsPreference(); loadSystemNotificationsPreference();
systemNotificationsEnabled = getSystemNotificationsEnabled(); systemNotificationsEnabled = getSystemNotificationsEnabled();
// Load playback preferences
loadPlaybackPreferences();
// Check for legacy downloads // Check for legacy downloads
checkLegacyDownloads(); checkLegacyDownloads();
@@ -1101,6 +1110,25 @@
} }
} }
async function loadPlaybackPreferences() {
try {
const prefs = await getPlaybackPreferences();
autoplayMode = prefs.autoplay_mode;
} catch (err) {
console.error('Failed to load playback preferences:', err);
}
}
async function handleAutoplayModeChange(mode: AutoplayMode) {
try {
await setAutoplayMode(mode);
autoplayMode = mode;
} catch (err) {
console.error('Failed to set autoplay mode:', err);
showToast('Failed to save autoplay preference', 'error');
}
}
async function checkLegacyDownloads() { async function checkLegacyDownloads() {
try { try {
const result = await invoke<{has_legacy_files: boolean, total_tracks: number}>('detect_legacy_downloads'); const result = await invoke<{has_legacy_files: boolean, total_tracks: number}>('detect_legacy_downloads');
@@ -0,0 +1,81 @@
/**
* Playback Preferences Store
*
* Manages global playback behavior preferences (autoplay mode, etc.)
*/
import { invoke } from '@tauri-apps/api/core';
// ============ Types ============
export type AutoplayMode = 'continue' | 'track_only';
export interface PlaybackPreferences {
autoplay_mode: AutoplayMode;
}
// ============ State ============
let preferences: PlaybackPreferences = {
autoplay_mode: 'continue'
};
const listeners = new Set<() => void>();
function notifyListeners(): void {
for (const listener of listeners) {
listener();
}
}
// ============ Public API ============
/**
* Get current playback preferences
*/
export async function getPlaybackPreferences(): Promise<PlaybackPreferences> {
const prefs = await invoke<PlaybackPreferences>('get_playback_preferences');
preferences = prefs;
notifyListeners();
return prefs;
}
/**
* Set autoplay mode
*/
export async function setAutoplayMode(mode: AutoplayMode): Promise<void> {
await invoke('set_autoplay_mode', { mode });
preferences.autoplay_mode = mode;
notifyListeners();
}
/**
* Get cached preferences (no backend call)
*/
export function getCachedPreferences(): PlaybackPreferences {
return preferences;
}
/**
* Check if autoplay is enabled (continue within source)
*/
export function isAutoplayEnabled(): boolean {
return preferences.autoplay_mode === 'continue';
}
/**
* Subscribe to preference changes
*/
export function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/**
* Initialize preferences store (call on app startup)
*/
export async function initPlaybackPreferences(): Promise<void> {
await getPlaybackPreferences();
}