diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 05f7b97fb..a2a7be606 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -365,6 +365,7 @@ pub fn run() { library::commands::library_get_folder, library::commands::library_update_folder_settings, library::commands::library_set_folder_enabled, + library::commands::library_update_folder_path, library::commands::library_check_folder_accessible, library::commands::library_scan, library::commands::library_scan_folder, @@ -523,6 +524,7 @@ pub fn run() { offline::commands::set_allow_cast_while_offline, offline::commands::set_allow_immediate_scrobbling, offline::commands::set_allow_accumulated_scrobbling, + offline::commands::set_show_network_folders_in_manual_offline, offline::commands::check_network, // Offline playlist sync queue commands offline::commands::create_pending_playlist, diff --git a/src-tauri/src/library/commands.rs b/src-tauri/src/library/commands.rs index 16b1d64dd..a1953161d 100644 --- a/src-tauri/src/library/commands.rs +++ b/src-tauri/src/library/commands.rs @@ -101,6 +101,7 @@ pub async fn library_get_folders(state: State<'_, LibraryState>) -> Result, @@ -108,7 +109,50 @@ pub async fn library_get_folders_with_metadata( log::info!("Command: library_get_folders_with_metadata"); let db = state.db.lock().await; - db.get_folders_with_metadata().map_err(|e| e.to_string()) + let mut folders = db.get_folders_with_metadata().map_err(|e| e.to_string())?; + + // Refresh network detection for folders without user override + for folder in &mut folders { + if !folder.user_override_network { + let path = Path::new(&folder.path); + let network_info = crate::network::is_network_path(path); + + // Update if detection differs from stored value + if network_info.is_network != folder.is_network { + log::info!( + "Updating network status for folder {}: {} -> {}", + folder.path, + folder.is_network, + network_info.is_network + ); + + // Extract network filesystem type + let fs_type = network_info.mount_info.as_ref().and_then(|mi| { + if let crate::network::MountKind::Network(nfs) = &mi.kind { + Some(format!("{:?}", nfs).to_lowercase()) + } else { + None + } + }); + + // Update database + let _ = db.update_folder_settings( + folder.id, + folder.alias.as_deref(), + folder.enabled, + network_info.is_network, + fs_type.as_deref(), + false, // not user override + ); + + // Update the folder struct for return + folder.is_network = network_info.is_network; + folder.network_fs_type = fs_type; + } + } + } + + Ok(folders) } /// Get a single folder by ID @@ -164,6 +208,58 @@ pub async fn library_set_folder_enabled( db.set_folder_enabled(id, enabled).map_err(|e| e.to_string()) } +/// Update folder path (move folder to new location) +#[tauri::command] +pub async fn library_update_folder_path( + id: i64, + new_path: String, + state: State<'_, LibraryState>, +) -> Result { + log::info!("Command: library_update_folder_path {} -> {}", id, new_path); + + // Verify the new path exists and is a directory + let path_ref = Path::new(&new_path); + if !path_ref.exists() { + return Err("The selected folder does not exist".to_string()); + } + if !path_ref.is_dir() { + return Err("The selected path is not a folder".to_string()); + } + + let db = state.db.lock().await; + db.update_folder_path(id, &new_path).map_err(|e| e.to_string())?; + + // Check if it's a network folder and update network info + let network_info = crate::network::is_network_path(path_ref); + if network_info.is_network { + // Extract network filesystem type from mount_info + let fs_type = network_info.mount_info.as_ref().and_then(|mi| { + if let crate::network::MountKind::Network(nfs) = &mi.kind { + Some(format!("{:?}", nfs).to_lowercase()) + } else { + None + } + }); + + // Get current folder settings to preserve enabled state + let current = db.get_folder_by_id(id).map_err(|e| e.to_string())?; + if let Some(folder) = current { + db.update_folder_settings( + id, + folder.alias.as_deref(), + folder.enabled, + true, // is_network + fs_type.as_deref(), + false, // not user override + ).map_err(|e| e.to_string())?; + } + } + + db.get_folder_by_id(id) + .map_err(|e| e.to_string())? + .ok_or_else(|| "Folder not found after update".to_string()) +} + /// Check network accessibility for a folder #[tauri::command] pub async fn library_check_folder_accessible(path: String) -> Result { @@ -461,6 +557,39 @@ pub async fn library_scan_folder( return Err("Cannot scan disabled folder".to_string()); } + // Refresh network detection if not user overridden + if !folder.user_override_network { + let path = Path::new(&folder.path); + let network_info = crate::network::is_network_path(path); + + if network_info.is_network != folder.is_network { + log::info!( + "Updating network status for folder {} during scan: {} -> {}", + folder.path, + folder.is_network, + network_info.is_network + ); + + let fs_type = network_info.mount_info.as_ref().and_then(|mi| { + if let crate::network::MountKind::Network(nfs) = &mi.kind { + Some(format!("{:?}", nfs).to_lowercase()) + } else { + None + } + }); + + let db = state.db.lock().await; + let _ = db.update_folder_settings( + folder.id, + folder.alias.as_deref(), + folder.enabled, + network_info.is_network, + fs_type.as_deref(), + false, + ); + } + } + // Reset cancel flag and progress state.scan_cancel.store(false, Ordering::Relaxed); { diff --git a/src-tauri/src/library/database.rs b/src-tauri/src/library/database.rs index 1a2b9aaa6..db15d5f40 100644 --- a/src-tauri/src/library/database.rs +++ b/src-tauri/src/library/database.rs @@ -479,6 +479,32 @@ impl LibraryDatabase { Ok(()) } + /// Update folder path (moves the folder to a new location) + /// This also clears the last_scan since the new path needs to be scanned + pub fn update_folder_path(&self, id: i64, new_path: &str) -> Result<(), LibraryError> { + // Check if new path already exists as a different folder + let existing: Option = self.conn + .query_row( + "SELECT id FROM library_folders WHERE path = ? AND id != ?", + params![new_path, id], + |row| row.get(0), + ) + .optional() + .map_err(|e| LibraryError::Database(e.to_string()))?; + + if existing.is_some() { + return Err(LibraryError::Database("A folder with this path already exists".to_string())); + } + + self.conn + .execute( + "UPDATE library_folders SET path = ?, last_scan = NULL WHERE id = ?", + params![new_path, id], + ) + .map_err(|e| LibraryError::Database(e.to_string()))?; + Ok(()) + } + // === Track Management === /// Insert or update a track diff --git a/src-tauri/src/offline/mod.rs b/src-tauri/src/offline/mod.rs index a135c4aea..c2ca96d51 100644 --- a/src-tauri/src/offline/mod.rs +++ b/src-tauri/src/offline/mod.rs @@ -43,6 +43,8 @@ pub struct OfflineSettings { pub allow_immediate_scrobbling: bool, /// Queue scrobbles for later submission when back online pub allow_accumulated_scrobbling: bool, + /// Show network folder content in manual offline mode + pub show_network_folders_in_manual_offline: bool, } /// A playlist created offline, pending sync to Qobuz @@ -90,17 +92,15 @@ impl OfflineStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open offline settings database: {}", e))?; + // Create base tables (with original schema for backward compatibility) conn.execute_batch( "CREATE TABLE IF NOT EXISTS offline_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), manual_offline_mode INTEGER NOT NULL DEFAULT 0, - show_partial_playlists INTEGER NOT NULL DEFAULT 1, - allow_cast_while_offline INTEGER NOT NULL DEFAULT 0, - allow_immediate_scrobbling INTEGER NOT NULL DEFAULT 0, - allow_accumulated_scrobbling INTEGER NOT NULL DEFAULT 1 + show_partial_playlists INTEGER NOT NULL DEFAULT 1 ); - INSERT OR IGNORE INTO offline_settings (id, manual_offline_mode, show_partial_playlists, allow_cast_while_offline, allow_immediate_scrobbling, allow_accumulated_scrobbling) - VALUES (1, 0, 1, 0, 0, 1); + INSERT OR IGNORE INTO offline_settings (id, manual_offline_mode, show_partial_playlists) + VALUES (1, 0, 1); CREATE TABLE IF NOT EXISTS pending_playlist_sync ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -126,12 +126,18 @@ impl OfflineStore { CREATE INDEX IF NOT EXISTS idx_scrobble_queue_sent ON scrobble_queue(sent);" ).map_err(|e| format!("Failed to create offline settings table: {}", e))?; - // Migration: Add new columns if they don't exist (for existing databases) - let _ = conn.execute_batch( - "ALTER TABLE offline_settings ADD COLUMN allow_cast_while_offline INTEGER NOT NULL DEFAULT 0; - ALTER TABLE offline_settings ADD COLUMN allow_immediate_scrobbling INTEGER NOT NULL DEFAULT 0; - ALTER TABLE offline_settings ADD COLUMN allow_accumulated_scrobbling INTEGER NOT NULL DEFAULT 1;" - ); + // Migration: Add new columns if they don't exist (run each separately to handle partial migrations) + let migrations = [ + "ALTER TABLE offline_settings ADD COLUMN allow_cast_while_offline INTEGER NOT NULL DEFAULT 0", + "ALTER TABLE offline_settings ADD COLUMN allow_immediate_scrobbling INTEGER NOT NULL DEFAULT 0", + "ALTER TABLE offline_settings ADD COLUMN allow_accumulated_scrobbling INTEGER NOT NULL DEFAULT 1", + "ALTER TABLE offline_settings ADD COLUMN show_network_folders_in_manual_offline INTEGER NOT NULL DEFAULT 0", + ]; + + for migration in migrations { + // Ignore errors (column may already exist) + let _ = conn.execute(migration, []); + } Ok(Self { conn }) } @@ -139,7 +145,7 @@ impl OfflineStore { pub fn get_settings(&self) -> Result { self.conn .query_row( - "SELECT manual_offline_mode, show_partial_playlists, allow_cast_while_offline, allow_immediate_scrobbling, allow_accumulated_scrobbling FROM offline_settings WHERE id = 1", + "SELECT manual_offline_mode, show_partial_playlists, allow_cast_while_offline, allow_immediate_scrobbling, allow_accumulated_scrobbling, COALESCE(show_network_folders_in_manual_offline, 0) FROM offline_settings WHERE id = 1", [], |row| { Ok(OfflineSettings { @@ -148,6 +154,7 @@ impl OfflineStore { allow_cast_while_offline: row.get::<_, i64>(2)? != 0, allow_immediate_scrobbling: row.get::<_, i64>(3)? != 0, allow_accumulated_scrobbling: row.get::<_, i64>(4)? != 0, + show_network_folders_in_manual_offline: row.get::<_, i64>(5)? != 0, }) }, ) @@ -204,6 +211,16 @@ impl OfflineStore { Ok(()) } + pub fn set_show_network_folders_in_manual_offline(&self, enabled: bool) -> Result<(), String> { + self.conn + .execute( + "UPDATE offline_settings SET show_network_folders_in_manual_offline = ?1 WHERE id = 1", + params![enabled as i64], + ) + .map_err(|e| format!("Failed to set show network folders in manual offline: {}", e))?; + Ok(()) + } + // === Pending Playlist Sync Methods === /// Create a new pending playlist (created while offline) @@ -552,6 +569,16 @@ pub mod commands { store.set_allow_accumulated_scrobbling(enabled) } + /// Set whether to show network folder content in manual offline mode + #[tauri::command] + pub fn set_show_network_folders_in_manual_offline( + enabled: bool, + state: State<'_, OfflineState>, + ) -> Result<(), String> { + let store = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + store.set_show_network_folders_in_manual_offline(enabled) + } + /// Check if network connectivity is available #[tauri::command] pub async fn check_network() -> bool { diff --git a/src/lib/components/FolderSettingsModal.svelte b/src/lib/components/FolderSettingsModal.svelte index f60f881ba..f3a948735 100644 --- a/src/lib/components/FolderSettingsModal.svelte +++ b/src/lib/components/FolderSettingsModal.svelte @@ -1,6 +1,7 @@ @@ -190,8 +231,11 @@
{getDisplayName()} - {folder.path} + {currentPath}
+
{#if checkingAccessibility} @@ -415,6 +459,35 @@ white-space: nowrap; } + .folder-path.path-changed { + color: var(--accent-primary); + } + + .change-path-btn { + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + background: var(--bg-tertiary); + border: none; + border-radius: 6px; + color: var(--text-secondary); + cursor: pointer; + transition: all 150ms ease; + flex-shrink: 0; + } + + .change-path-btn:hover:not(:disabled) { + background: var(--bg-hover); + color: var(--text-primary); + } + + .change-path-btn:disabled { + opacity: 0.5; + cursor: not-allowed; + } + .folder-status { display: flex; align-items: center; diff --git a/src/lib/components/views/LocalLibraryView.svelte b/src/lib/components/views/LocalLibraryView.svelte index c9ace2e14..5944a740c 100644 --- a/src/lib/components/views/LocalLibraryView.svelte +++ b/src/lib/components/views/LocalLibraryView.svelte @@ -1511,10 +1511,9 @@ {/if}
-
+
{#if folder.alias} {folder.alias} - {folder.path} {:else} {folder.path} {/if} diff --git a/src/lib/components/views/SettingsView.svelte b/src/lib/components/views/SettingsView.svelte index 847d62a43..9a585a57e 100644 --- a/src/lib/components/views/SettingsView.svelte +++ b/src/lib/components/views/SettingsView.svelte @@ -37,6 +37,7 @@ setAllowCastWhileOffline, setAllowImmediateScrobbling, setAllowAccumulatedScrobbling, + setShowNetworkFoldersInManualOffline, checkNetwork, type OfflineStatus, type OfflineSettings @@ -722,6 +723,14 @@ } } + async function handleShowNetworkFoldersChange(enabled: boolean) { + try { + await setShowNetworkFoldersInManualOffline(enabled); + } catch (error) { + console.error('Failed to set show network folders in manual offline:', error); + } + } + async function handleLanguageChange(lang: string) { language = lang; const localeCode = languageToLocale[lang]; @@ -890,13 +899,13 @@ async function handleChangeDownloadFolder() { try { const { open } = await import('@tauri-apps/plugin-dialog'); - + const result = await open({ title: 'Select Downloads Folder', directory: true, defaultPath: downloadRoot || undefined }); - + if (result) { // Validate the path const valid = await invoke('validate_download_path', { path: result }); @@ -905,6 +914,23 @@ return; } + // Check if this is a network folder and warn user + interface NetworkPathInfo { + isNetwork: boolean; + mountInfo: { fsType: string; kind: string } | null; + path: string; + } + const networkInfo = await invoke('check_network_path', { path: result }); + if (networkInfo.isNetwork) { + const proceed = confirm( + $t('settings.networkDownloadWarning') + '\n\n' + + $t('settings.networkDownloadWarningDetail') + ); + if (!proceed) { + return; + } + } + // Ask if user wants to move existing downloads const hasDownloads = downloadStats && downloadStats.readyTracks > 0; let moveFiles = false; @@ -1187,7 +1213,7 @@
-
+
{$t('offline.allowAccumulatedScrobbling')} {$t('offline.allowAccumulatedScrobblingDesc')} @@ -1195,6 +1221,13 @@
+
+
+ {$t('offline.showNetworkFolders')} + {$t('offline.showNetworkFoldersDesc')} +
+ +
{/if} diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 992f8a513..5a65a5ca0 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -115,6 +115,8 @@ "networkFolderDetected": "This folder appears to be on a network drive. It may be unavailable in offline mode.", "disabled": "Disabled", "unavailable": "Unavailable", + "changeFolder": "Change folder location", + "selectFolder": "Select folder", "networkFs": { "auto": "Auto-detect", "other": "Other" @@ -359,6 +361,8 @@ "clearDownloads": "Clear All", "openFolder": "Open Folder" }, + "networkDownloadWarning": "The selected folder is on a network drive.", + "networkDownloadWarningDetail": "Downloaded tracks may not be available when the network is disconnected or in offline mode. Are you sure you want to use this location?", "lyrics": { "title": "Lyrics", "lyricsCache": "Lyrics Cache", @@ -485,7 +489,9 @@ "allowImmediateScrobblingDesc": "Send scrobbles to Last.fm immediately while in manual offline mode", "allowAccumulatedScrobbling": "Accumulated Scrobbling", "allowAccumulatedScrobblingDesc": "Queue scrobbles for later when back online", - "scrobbleTimeLimit": "Last.fm accepts scrobbles up to 2 weeks old" + "scrobbleTimeLimit": "Last.fm accepts scrobbles up to 2 weeks old", + "showNetworkFolders": "Show Network Folder Content", + "showNetworkFoldersDesc": "Display content from network-mounted folders (NAS, Samba, etc.) while in manual offline mode" }, "filter": { "all": "All" diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index d50122abf..cbe68dded 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -115,6 +115,8 @@ "networkFolderDetected": "Esta carpeta parece estar en una unidad de red. Puede no estar disponible en modo offline.", "disabled": "Deshabilitada", "unavailable": "No disponible", + "changeFolder": "Cambiar ubicacion de carpeta", + "selectFolder": "Seleccionar carpeta", "networkFs": { "auto": "Auto-detectar", "other": "Otro" @@ -359,6 +361,8 @@ "clearDownloads": "Limpiar Todo", "openFolder": "Abrir Carpeta" }, + "networkDownloadWarning": "La carpeta seleccionada está en una unidad de red.", + "networkDownloadWarningDetail": "Las pistas descargadas pueden no estar disponibles cuando la red esté desconectada o en modo offline. ¿Estás seguro de que quieres usar esta ubicación?", "lyrics": { "title": "Letras", "lyricsCache": "Caché de Letras", @@ -485,7 +489,9 @@ "allowImmediateScrobblingDesc": "Enviar scrobbles a Last.fm inmediatamente en modo offline manual", "allowAccumulatedScrobbling": "Scrobbling Acumulado", "allowAccumulatedScrobblingDesc": "Almacenar scrobbles para enviar cuando vuelvas a estar en linea", - "scrobbleTimeLimit": "Last.fm acepta scrobbles de hasta 2 semanas de antiguedad" + "scrobbleTimeLimit": "Last.fm acepta scrobbles de hasta 2 semanas de antiguedad", + "showNetworkFolders": "Mostrar Contenido de Carpetas de Red", + "showNetworkFoldersDesc": "Mostrar contenido de carpetas montadas en red (NAS, Samba, etc.) mientras estas en modo offline manual" }, "filter": { "all": "Todos" diff --git a/src/lib/stores/offlineStore.ts b/src/lib/stores/offlineStore.ts index f8eaaae6d..23b8e048d 100644 --- a/src/lib/stores/offlineStore.ts +++ b/src/lib/stores/offlineStore.ts @@ -36,6 +36,7 @@ export interface OfflineSettings { allowCastWhileOffline: boolean; allowImmediateScrobbling: boolean; allowAccumulatedScrobbling: boolean; + showNetworkFoldersInManualOffline: boolean; } // Store state @@ -51,6 +52,7 @@ let settings: OfflineSettings = { allowCastWhileOffline: false, allowImmediateScrobbling: false, allowAccumulatedScrobbling: true, + showNetworkFoldersInManualOffline: false, }; let initialized = false; @@ -236,6 +238,20 @@ export async function setAllowAccumulatedScrobbling(enabled: boolean): Promise { + try { + await invoke('set_show_network_folders_in_manual_offline', { enabled }); + settings.showNetworkFoldersInManualOffline = enabled; + notifyListeners(); + } catch (error) { + console.error('Failed to set show network folders in manual offline:', error); + throw error; + } +} + /** * Force refresh of offline status */