From c0ea039476dc8d326d0b67babed9793b4efe97fe Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Fri, 16 Jan 2026 04:40:06 -0600 Subject: [PATCH] Add network folder detection and folder settings - Add network folder detection module using /proc/self/mountinfo - Detect CIFS/SMB, NFS, SSHFS, rclone, WebDAV, GlusterFS, CephFS - Classify mount types (local, network, virtual, FUSE unknown) - Check mount accessibility - Add library folder metadata - Alias for friendly naming (e.g., "NAS Music", "External Drive") - Network folder flag with auto-detection - User override for manual network folder marking - Network filesystem type (detected or user-defined) - Enabled toggle to disable folders without removing - Add FolderSettingsModal component - Edit folder alias, enabled state, network settings - Show accessibility status for network folders - Scan single folder button - Update LocalLibraryView folder list - Show network icon with connected/disconnected states - Display alias with path below if set - Edit button (enabled for single selection) - Visual badges for disabled/unavailable folders - Add Tauri commands - library_get_folders_with_metadata - library_update_folder_settings - library_scan_folder (scan single folder) - check_network_path, check_mount_accessible --- src-tauri/src/lib.rs | 12 + src-tauri/src/library/commands.rs | 311 ++++++++- src-tauri/src/library/database.rs | 155 ++++- src-tauri/src/library/mod.rs | 2 +- src-tauri/src/network/mod.rs | 441 ++++++++++++ src/lib/components/FolderSettingsModal.svelte | 628 ++++++++++++++++++ .../components/views/LocalLibraryView.svelte | 258 ++++++- src/lib/i18n/locales/en.json | 34 +- src/lib/i18n/locales/es.json | 34 +- static/nas_settings.svg | 7 + static/network_folder.svg | 7 + 11 files changed, 1848 insertions(+), 41 deletions(-) create mode 100644 src-tauri/src/network/mod.rs create mode 100644 src/lib/components/FolderSettingsModal.svelte create mode 100644 static/nas_settings.svg create mode 100644 static/network_folder.svg diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 3a2032cf7..05f7b97fb 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -17,6 +17,7 @@ pub mod lastfm; pub mod library; pub mod lyrics; pub mod media_controls; +pub mod network; pub mod offline; pub mod player; pub mod playlist_import; @@ -360,7 +361,13 @@ pub fn run() { library::commands::library_add_folder, library::commands::library_remove_folder, library::commands::library_get_folders, + library::commands::library_get_folders_with_metadata, + library::commands::library_get_folder, + library::commands::library_update_folder_settings, + library::commands::library_set_folder_enabled, + library::commands::library_check_folder_accessible, library::commands::library_scan, + library::commands::library_scan_folder, library::commands::library_get_scan_progress, library::commands::library_stop_scan, library::commands::library_get_albums, @@ -529,6 +536,11 @@ pub fn run() { offline::commands::mark_scrobbles_sent, offline::commands::get_queued_scrobble_count, offline::commands::cleanup_sent_scrobbles, + // Network folder detection commands + network::commands::check_network_path, + network::commands::get_network_mounts_cmd, + network::commands::check_mount_accessible, + network::commands::check_network_paths_batch, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/src-tauri/src/library/commands.rs b/src-tauri/src/library/commands.rs index 753580363..16b1d64dd 100644 --- a/src-tauri/src/library/commands.rs +++ b/src-tauri/src/library/commands.rs @@ -10,9 +10,10 @@ use tokio::sync::Mutex; use crate::api_keys::ApiKeysState; use crate::discogs::DiscogsClient; use crate::library::{ - cue_to_tracks, get_artwork_cache_dir, CueParser, LibraryDatabase, LibraryScanner, LibraryStats, + cue_to_tracks, get_artwork_cache_dir, CueParser, LibraryDatabase, LibraryFolder, LibraryScanner, LibraryStats, LocalAlbum, LocalArtist, LocalTrack, MetadataExtractor, ScanError, ScanProgress, ScanStatus, }; +use crate::network::{is_network_path, MountKind, NetworkFs}; /// Library state shared across commands pub struct LibraryState { @@ -31,7 +32,7 @@ fn normalize_library_path(path: &Path) -> PathBuf { pub async fn library_add_folder( path: String, state: State<'_, LibraryState>, -) -> Result<(), String> { +) -> Result { log::info!("Command: library_add_folder {}", path); // Validate path exists and is a directory @@ -43,8 +44,39 @@ pub async fn library_add_folder( return Err(format!("Path is not a directory: {}", path)); } + // Detect if this is a network folder + let network_info = is_network_path(path_ref); + let (is_network, fs_type) = if network_info.is_network { + let fs_type = network_info.mount_info.as_ref().and_then(|m| { + match &m.kind { + MountKind::Network(nfs) => Some(match nfs { + NetworkFs::Cifs => "cifs".to_string(), + NetworkFs::Nfs => "nfs".to_string(), + NetworkFs::Sshfs => "sshfs".to_string(), + NetworkFs::Rclone => "rclone".to_string(), + NetworkFs::Webdav => "webdav".to_string(), + NetworkFs::Gluster => "glusterfs".to_string(), + NetworkFs::Ceph => "ceph".to_string(), + NetworkFs::Other(s) => s.clone(), + }), + _ => None, + } + }); + (true, fs_type) + } else { + (false, None) + }; + + log::info!("Folder network info: is_network={}, fs_type={:?}", is_network, fs_type); + let db = state.db.lock().await; - db.add_folder(&path).map_err(|e| e.to_string()) + let id = db.add_folder_with_network_info(&path, is_network, fs_type.as_deref()) + .map_err(|e| e.to_string())?; + + // Return the full folder info + db.get_folder_by_id(id) + .map_err(|e| e.to_string())? + .ok_or_else(|| "Failed to retrieve folder after insert".to_string()) } #[tauri::command] @@ -68,6 +100,87 @@ pub async fn library_get_folders(state: State<'_, LibraryState>) -> Result, +) -> Result, String> { + 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()) +} + +/// Get a single folder by ID +#[tauri::command] +pub async fn library_get_folder( + id: i64, + state: State<'_, LibraryState>, +) -> Result, String> { + log::info!("Command: library_get_folder {}", id); + + let db = state.db.lock().await; + db.get_folder_by_id(id).map_err(|e| e.to_string()) +} + +/// Update folder settings (alias, enabled, network info) +#[tauri::command] +pub async fn library_update_folder_settings( + id: i64, + alias: Option, + enabled: bool, + is_network: bool, + network_fs_type: Option, + user_override_network: bool, + state: State<'_, LibraryState>, +) -> Result { + log::info!("Command: library_update_folder_settings {} alias={:?} enabled={}", id, alias, enabled); + + let db = state.db.lock().await; + db.update_folder_settings( + id, + alias.as_deref(), + enabled, + is_network, + network_fs_type.as_deref(), + user_override_network, + ).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()) +} + +/// Enable or disable a folder +#[tauri::command] +pub async fn library_set_folder_enabled( + id: i64, + enabled: bool, + state: State<'_, LibraryState>, +) -> Result<(), String> { + log::info!("Command: library_set_folder_enabled {} enabled={}", id, enabled); + + let db = state.db.lock().await; + db.set_folder_enabled(id, enabled).map_err(|e| e.to_string()) +} + +/// Check network accessibility for a folder +#[tauri::command] +pub async fn library_check_folder_accessible(path: String) -> Result { + log::info!("Command: library_check_folder_accessible {}", path); + + let path_ref = Path::new(&path); + if !path_ref.exists() { + return Ok(false); + } + + // Try to read the directory + match std::fs::read_dir(path_ref) { + Ok(_) => Ok(true), + Err(_) => Ok(false), + } +} + // === Scanning === #[tauri::command] @@ -328,6 +441,198 @@ pub async fn library_stop_scan(state: State<'_, LibraryState>) -> Result<(), Str Ok(()) } +/// Scan a single folder (by ID) +#[tauri::command] +pub async fn library_scan_folder( + folder_id: i64, + state: State<'_, LibraryState>, +) -> Result<(), String> { + log::info!("Command: library_scan_folder {}", folder_id); + + // Get folder info + let folder = { + let db = state.db.lock().await; + db.get_folder_by_id(folder_id) + .map_err(|e| e.to_string())? + .ok_or_else(|| format!("Folder with ID {} not found", folder_id))? + }; + + if !folder.enabled { + return Err("Cannot scan disabled folder".to_string()); + } + + // Reset cancel flag and progress + state.scan_cancel.store(false, Ordering::Relaxed); + { + let mut progress = state.scan_progress.lock().await; + *progress = ScanProgress { + status: ScanStatus::Scanning, + total_files: 0, + processed_files: 0, + current_file: None, + errors: Vec::new(), + }; + } + + let scanner = LibraryScanner::new(); + let mut all_errors: Vec = Vec::new(); + + log::info!("Scanning single folder: {}", folder.path); + + // Scan for files + let scan_result = match scanner.scan_directory(Path::new(&folder.path)) { + Ok(result) => result, + Err(e) => { + let mut progress = state.scan_progress.lock().await; + progress.status = ScanStatus::Complete; + progress.errors = vec![ScanError { + file_path: folder.path.clone(), + error: e.to_string(), + }]; + return Err(e.to_string()); + } + }; + + let total_files = scan_result.audio_files.len() + scan_result.cue_files.len(); + + // Update total count + { + let mut progress = state.scan_progress.lock().await; + progress.total_files = total_files as u32; + } + + // Process CUE files first + for cue_path in &scan_result.cue_files { + if state.scan_cancel.load(Ordering::Relaxed) { + let mut progress = state.scan_progress.lock().await; + progress.status = ScanStatus::Cancelled; + progress.current_file = None; + log::info!("Library scan cancelled by user"); + return Ok(()); + } + + { + let mut progress = state.scan_progress.lock().await; + progress.current_file = Some(cue_path.to_string_lossy().to_string()); + } + + match process_cue_file(cue_path, &state).await { + Ok(_) => {} + Err(e) => { + all_errors.push(ScanError { + file_path: cue_path.to_string_lossy().to_string(), + error: e, + }); + } + } + + { + let mut progress = state.scan_progress.lock().await; + progress.processed_files += 1; + } + } + + // Process regular audio files + let cue_audio_files: std::collections::HashSet = scan_result + .cue_files + .iter() + .filter_map(|p| { + CueParser::parse(p).ok().map(|cue| { + normalize_library_path(Path::new(&cue.audio_file)) + .to_string_lossy() + .to_string() + }) + }) + .collect(); + + for audio_path in &scan_result.audio_files { + if state.scan_cancel.load(Ordering::Relaxed) { + let mut progress = state.scan_progress.lock().await; + progress.status = ScanStatus::Cancelled; + progress.current_file = None; + log::info!("Library scan cancelled by user"); + return Ok(()); + } + + let canonical_path = normalize_library_path(audio_path); + let path_str = canonical_path.to_string_lossy().to_string(); + if cue_audio_files.contains(&path_str) { + let mut progress = state.scan_progress.lock().await; + progress.processed_files += 1; + continue; + } + + { + let mut progress = state.scan_progress.lock().await; + progress.current_file = Some(path_str.clone()); + } + + match MetadataExtractor::extract(&canonical_path) { + Ok(mut track) => { + let artwork_cache = get_artwork_cache_dir(); + let mut artwork_path = MetadataExtractor::extract_artwork(&canonical_path, &artwork_cache); + if artwork_path.is_none() { + if let Some(folder_art) = MetadataExtractor::find_folder_artwork( + canonical_path.as_path(), + Some(&track.album), + ) { + artwork_path = MetadataExtractor::cache_artwork_file( + Path::new(&folder_art), + &artwork_cache, + ); + } + } + track.artwork_path = artwork_path.clone(); + + let db = state.db.lock().await; + let group_key = track.album_group_key.clone(); + if let Err(e) = db.insert_track(&track) { + all_errors.push(ScanError { + file_path: path_str, + error: e.to_string(), + }); + } else if let Some(path) = artwork_path.as_ref() { + if !group_key.is_empty() { + let _ = db.update_album_group_artwork(&group_key, path); + } + } + } + Err(e) => { + all_errors.push(ScanError { + file_path: path_str, + error: e.to_string(), + }); + } + } + + { + let mut progress = state.scan_progress.lock().await; + progress.processed_files += 1; + } + } + + // Update folder scan time + { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0); + let db = state.db.lock().await; + let _ = db.update_folder_scan_time(&folder.path, now); + } + + // Update final status + { + let mut progress = state.scan_progress.lock().await; + progress.status = ScanStatus::Complete; + progress.current_file = None; + progress.errors = all_errors; + } + + log::info!("Single folder scan complete"); + Ok(()) +} + // === Queries === #[tauri::command] diff --git a/src-tauri/src/library/database.rs b/src-tauri/src/library/database.rs index 32cd0cca8..1a2b9aaa6 100644 --- a/src-tauri/src/library/database.rs +++ b/src-tauri/src/library/database.rs @@ -289,12 +289,32 @@ impl LibraryDatabase { .map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; } + // Migration: Add folder metadata columns (alias, network info) + let has_folder_alias: bool = self.conn + .query_row( + "SELECT COUNT(*) FROM pragma_table_info('library_folders') WHERE name = 'alias'", + [], + |row| row.get::<_, i32>(0), + ) + .map(|count| count > 0) + .unwrap_or(false); + + if !has_folder_alias { + log::info!("Running migration: adding folder metadata columns (alias, network info)"); + self.conn.execute_batch( + "ALTER TABLE library_folders ADD COLUMN alias TEXT; + ALTER TABLE library_folders ADD COLUMN is_network INTEGER DEFAULT 0; + ALTER TABLE library_folders ADD COLUMN network_fs_type TEXT; + ALTER TABLE library_folders ADD COLUMN user_override_network INTEGER DEFAULT 0;" + ).map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; + } + Ok(()) } // === Folder Management === - /// Add a folder to the library + /// Add a folder to the library with optional network info pub fn add_folder(&self, path: &str) -> Result<(), LibraryError> { self.conn .execute( @@ -305,6 +325,32 @@ impl LibraryDatabase { Ok(()) } + /// Add a folder with network detection info + pub fn add_folder_with_network_info( + &self, + path: &str, + is_network: bool, + network_fs_type: Option<&str>, + ) -> Result { + self.conn + .execute( + "INSERT OR IGNORE INTO library_folders (path, is_network, network_fs_type) VALUES (?, ?, ?)", + params![path, is_network as i32, network_fs_type], + ) + .map_err(|e| LibraryError::Database(e.to_string()))?; + + // Get the folder ID (either newly inserted or existing) + let id: i64 = self.conn + .query_row( + "SELECT id FROM library_folders WHERE path = ?", + params![path], + |row| row.get(0), + ) + .map_err(|e| LibraryError::Database(e.to_string()))?; + + Ok(id) + } + /// Remove a folder from the library pub fn remove_folder(&self, path: &str) -> Result<(), LibraryError> { self.conn @@ -313,7 +359,7 @@ impl LibraryDatabase { Ok(()) } - /// Get all enabled library folders + /// Get all enabled library folders (paths only, for scanning) pub fn get_folders(&self) -> Result, LibraryError> { let mut stmt = self .conn @@ -331,6 +377,97 @@ impl LibraryDatabase { Ok(folders) } + /// Get all library folders with full metadata + pub fn get_folders_with_metadata(&self) -> Result, LibraryError> { + let mut stmt = self + .conn + .prepare( + "SELECT id, path, alias, enabled, is_network, network_fs_type, user_override_network, last_scan + FROM library_folders ORDER BY path" + ) + .map_err(|e| LibraryError::Database(e.to_string()))?; + + let rows = stmt + .query_map([], |row| { + Ok(LibraryFolder { + id: row.get(0)?, + path: row.get(1)?, + alias: row.get(2)?, + enabled: row.get::<_, i32>(3)? != 0, + is_network: row.get::<_, i32>(4).unwrap_or(0) != 0, + network_fs_type: row.get(5)?, + user_override_network: row.get::<_, i32>(6).unwrap_or(0) != 0, + last_scan: row.get(7)?, + }) + }) + .map_err(|e| LibraryError::Database(e.to_string()))?; + + let mut folders = Vec::new(); + for folder in rows { + folders.push(folder.map_err(|e| LibraryError::Database(e.to_string()))?); + } + Ok(folders) + } + + /// Get a single folder by ID + pub fn get_folder_by_id(&self, id: i64) -> Result, LibraryError> { + let result = self + .conn + .query_row( + "SELECT id, path, alias, enabled, is_network, network_fs_type, user_override_network, last_scan + FROM library_folders WHERE id = ?", + params![id], + |row| { + Ok(LibraryFolder { + id: row.get(0)?, + path: row.get(1)?, + alias: row.get(2)?, + enabled: row.get::<_, i32>(3)? != 0, + is_network: row.get::<_, i32>(4).unwrap_or(0) != 0, + network_fs_type: row.get(5)?, + user_override_network: row.get::<_, i32>(6).unwrap_or(0) != 0, + last_scan: row.get(7)?, + }) + }, + ) + .optional() + .map_err(|e| LibraryError::Database(e.to_string()))?; + + Ok(result) + } + + /// Update folder settings + pub fn update_folder_settings( + &self, + id: i64, + alias: Option<&str>, + enabled: bool, + is_network: bool, + network_fs_type: Option<&str>, + user_override_network: bool, + ) -> Result<(), LibraryError> { + self.conn + .execute( + "UPDATE library_folders + SET alias = ?, enabled = ?, is_network = ?, network_fs_type = ?, user_override_network = ? + WHERE id = ?", + params![alias, enabled as i32, is_network as i32, network_fs_type, user_override_network as i32, id], + ) + .map_err(|e| LibraryError::Database(e.to_string()))?; + Ok(()) + } + + /// Set folder enabled state + pub fn set_folder_enabled(&self, id: i64, enabled: bool) -> Result<(), LibraryError> { + self.conn + .execute( + "UPDATE library_folders SET enabled = ? WHERE id = ?", + params![enabled as i32, id], + ) + .map_err(|e| LibraryError::Database(e.to_string()))?; + Ok(()) + } + /// Update last scan time for a folder pub fn update_folder_scan_time(&self, path: &str, timestamp: i64) -> Result<(), LibraryError> { self.conn @@ -846,6 +983,20 @@ pub struct LibraryStats { pub total_size_bytes: u64, } +/// Library folder with metadata +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LibraryFolder { + pub id: i64, + pub path: String, + pub alias: Option, + pub enabled: bool, + pub is_network: bool, + pub network_fs_type: Option, + pub user_override_network: bool, + pub last_scan: Option, +} + /// Playlist local settings (enhances remote Qobuz playlists) #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PlaylistSettings { diff --git a/src-tauri/src/library/mod.rs b/src-tauri/src/library/mod.rs index 5f4f7042f..bcfff207d 100644 --- a/src-tauri/src/library/mod.rs +++ b/src-tauri/src/library/mod.rs @@ -13,7 +13,7 @@ pub mod scanner; pub use commands::LibraryState; pub use cue_parser::{cue_to_tracks, CueParser, CueSheet, CueTrack}; -pub use database::{LibraryDatabase, LibraryStats, PlaylistSettings, PlaylistStats}; +pub use database::{LibraryDatabase, LibraryFolder, LibraryStats, PlaylistSettings, PlaylistStats}; pub use errors::LibraryError; pub use metadata::MetadataExtractor; pub use models::*; diff --git a/src-tauri/src/network/mod.rs b/src-tauri/src/network/mod.rs new file mode 100644 index 000000000..3a9bf3896 --- /dev/null +++ b/src-tauri/src/network/mod.rs @@ -0,0 +1,441 @@ +//! Network folder detection module +//! +//! Detects if a path is on a network-mounted filesystem (NAS, DAS, Samba, NFS, etc.) +//! by parsing /proc/self/mountinfo on Linux. +//! +//! Used by: +//! - Download folder selection (warning for network folders) +//! - Library folder management (network folder indicator) +//! - Offline mode (accessibility of network content) + +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::fs; +use std::path::Path; + +/// Type of mount point +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MountKind { + /// Local storage (ext4, btrfs, xfs, ntfs, vfat, etc.) + Local, + /// Network filesystem (SMB, NFS, SSHFS, etc.) + Network(NetworkFs), + /// Virtual/pseudo filesystem (/proc, /sys, tmpfs, etc.) + Virtual, + /// FUSE filesystem of unknown type + FuseUnknown, +} + +/// Specific network filesystem types +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NetworkFs { + /// SMB/CIFS (Samba, Windows shares) + Cifs, + /// NFS (Network File System) + Nfs, + /// SSHFS (SSH Filesystem) + Sshfs, + /// rclone mount (cloud storage) + Rclone, + /// WebDAV + Webdav, + /// GlusterFS + Gluster, + /// CephFS + Ceph, + /// Other network filesystem + Other(String), +} + +/// Information about a mount point +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MountInfo { + /// Filesystem type (e.g., "ext4", "cifs", "nfs") + pub fs_type: String, + /// Mount point path + pub mount_point: String, + /// Mount source (device or remote path) + pub source: String, + /// Classified mount kind + pub kind: MountKind, + /// Whether the mount is currently accessible + pub accessible: bool, +} + +/// Result of checking if a path is on a network mount +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NetworkPathInfo { + /// Whether the path is on a network filesystem + pub is_network: bool, + /// Mount information if found + pub mount_info: Option, + /// The path that was checked + pub path: String, +} + +/// Cached mount information for performance +#[derive(Debug)] +pub struct MountCache { + mounts: Vec, + last_refresh: std::time::Instant, +} + +impl MountCache { + /// Create a new mount cache + pub fn new() -> Self { + Self { + mounts: Vec::new(), + last_refresh: std::time::Instant::now() - std::time::Duration::from_secs(3600), + } + } + + /// Refresh mount information from /proc/self/mountinfo + pub fn refresh(&mut self) { + self.mounts = parse_mount_info().unwrap_or_default(); + self.last_refresh = std::time::Instant::now(); + } + + /// Get mounts, refreshing if stale (older than 30 seconds) + pub fn get_mounts(&mut self) -> &[MountInfo] { + if self.last_refresh.elapsed() > std::time::Duration::from_secs(30) { + self.refresh(); + } + &self.mounts + } + + /// Force refresh and return mounts + pub fn get_mounts_fresh(&mut self) -> &[MountInfo] { + self.refresh(); + &self.mounts + } +} + +/// Classify a filesystem type into MountKind +fn classify_fs_type(fs_type: &str, source: &str) -> MountKind { + let fs_lower = fs_type.to_lowercase(); + + // Network filesystems + match fs_lower.as_str() { + "cifs" | "smb" | "smb3" | "smbfs" => { + return MountKind::Network(NetworkFs::Cifs); + } + "nfs" | "nfs4" | "nfsd" => { + return MountKind::Network(NetworkFs::Nfs); + } + "sshfs" => { + return MountKind::Network(NetworkFs::Sshfs); + } + "rclone" => { + return MountKind::Network(NetworkFs::Rclone); + } + "davfs" | "davfs2" | "webdav" => { + return MountKind::Network(NetworkFs::Webdav); + } + "glusterfs" => { + return MountKind::Network(NetworkFs::Gluster); + } + "ceph" => { + return MountKind::Network(NetworkFs::Ceph); + } + // FUSE types that might be network + "fuse.sshfs" => { + return MountKind::Network(NetworkFs::Sshfs); + } + "fuse.rclone" => { + return MountKind::Network(NetworkFs::Rclone); + } + "fuse.cifs" => { + return MountKind::Network(NetworkFs::Cifs); + } + _ => {} + } + + // Check for FUSE with network-like source patterns + if fs_lower.starts_with("fuse") { + // Check source for network patterns + if source.contains("@") || source.contains("://") { + // Likely SSHFS (user@host:path) or URL-based mount + if source.contains("@") && source.contains(":") { + return MountKind::Network(NetworkFs::Sshfs); + } + return MountKind::Network(NetworkFs::Other(fs_type.to_string())); + } + return MountKind::FuseUnknown; + } + + // Virtual/pseudo filesystems + match fs_lower.as_str() { + "proc" | "sysfs" | "devtmpfs" | "devpts" | "tmpfs" | "ramfs" + | "securityfs" | "debugfs" | "tracefs" | "configfs" | "cgroup" + | "cgroup2" | "pstore" | "efivarfs" | "bpf" | "autofs" + | "mqueue" | "hugetlbfs" | "fusectl" | "overlay" | "squashfs" => { + return MountKind::Virtual; + } + _ => {} + } + + // Local filesystems + match fs_lower.as_str() { + "ext2" | "ext3" | "ext4" | "xfs" | "btrfs" | "zfs" + | "ntfs" | "ntfs3" | "vfat" | "fat32" | "exfat" | "hfs" + | "hfsplus" | "apfs" | "f2fs" | "jfs" | "reiserfs" | "udf" + | "iso9660" | "ufs" => { + return MountKind::Local; + } + _ => {} + } + + // Default to local for unknown types (conservative approach) + MountKind::Local +} + +/// Parse /proc/self/mountinfo and return mount information +fn parse_mount_info() -> Result, String> { + let content = fs::read_to_string("/proc/self/mountinfo") + .map_err(|e| format!("Failed to read /proc/self/mountinfo: {}", e))?; + + let mut mounts = Vec::new(); + + for line in content.lines() { + if let Some(mount) = parse_mount_line(line) { + mounts.push(mount); + } + } + + Ok(mounts) +} + +/// Parse a single line from /proc/self/mountinfo +/// Format: mount_id parent_id major:minor root mount_point mount_options ... - fs_type mount_source super_options +fn parse_mount_line(line: &str) -> Option { + let parts: Vec<&str> = line.split_whitespace().collect(); + + // Need at least the basic fields plus separator + if parts.len() < 7 { + return None; + } + + // Find the separator "-" to split fixed and optional parts + let separator_idx = parts.iter().position(|&s| s == "-")?; + + // mount_point is at index 4 + let mount_point = parts.get(4)?.to_string(); + + // After separator: fs_type, mount_source, super_options + let fs_type = parts.get(separator_idx + 1)?.to_string(); + let source = parts.get(separator_idx + 2).unwrap_or(&"").to_string(); + + // Unescape mount point (replaces \040 with space, etc.) + let mount_point = unescape_mount_path(&mount_point); + + let kind = classify_fs_type(&fs_type, &source); + + // Check accessibility with a quick stat + let accessible = Path::new(&mount_point).exists() + && std::fs::metadata(&mount_point).is_ok(); + + Some(MountInfo { + fs_type, + mount_point, + source, + kind, + accessible, + }) +} + +/// Unescape mount path (handles \040 for space, etc.) +fn unescape_mount_path(path: &str) -> String { + let mut result = String::with_capacity(path.len()); + let mut chars = path.chars().peekable(); + + while let Some(c) = chars.next() { + if c == '\\' { + // Read up to 3 octal digits + let mut octal = String::new(); + for _ in 0..3 { + if let Some(&next) = chars.peek() { + if next.is_ascii_digit() && next < '8' { + octal.push(chars.next().unwrap()); + } else { + break; + } + } + } + if !octal.is_empty() { + if let Ok(code) = u8::from_str_radix(&octal, 8) { + result.push(code as char); + } else { + result.push('\\'); + result.push_str(&octal); + } + } else { + result.push('\\'); + } + } else { + result.push(c); + } + } + + result +} + +/// Find the mount point for a given path +pub fn find_mount_for_path(path: &Path, mounts: &[MountInfo]) -> Option { + // Canonicalize path to resolve symlinks + let canonical = match path.canonicalize() { + Ok(p) => p, + Err(_) => path.to_path_buf(), + }; + + let path_str = canonical.to_string_lossy(); + + // Find the longest matching mount point (most specific) + let mut best_match: Option<&MountInfo> = None; + let mut best_len = 0; + + for mount in mounts { + if path_str.starts_with(&mount.mount_point) || path_str == mount.mount_point { + let mount_len = mount.mount_point.len(); + // Make sure it's a proper path prefix (ends at directory boundary) + let is_valid_prefix = path_str.len() == mount_len + || path_str.chars().nth(mount_len) == Some('/') + || mount.mount_point == "/"; + + if is_valid_prefix && mount_len > best_len { + best_match = Some(mount); + best_len = mount_len; + } + } + } + + best_match.cloned() +} + +/// Check if a path is on a network filesystem +pub fn is_network_path(path: &Path) -> NetworkPathInfo { + let mounts = parse_mount_info().unwrap_or_default(); + + if let Some(mount) = find_mount_for_path(path, &mounts) { + let is_network = matches!(mount.kind, MountKind::Network(_)); + NetworkPathInfo { + is_network, + mount_info: Some(mount), + path: path.to_string_lossy().to_string(), + } + } else { + NetworkPathInfo { + is_network: false, + mount_info: None, + path: path.to_string_lossy().to_string(), + } + } +} + +/// Check accessibility of a network mount with timeout +pub fn check_mount_accessibility(mount_point: &str) -> bool { + // Use a quick readdir operation + let path = Path::new(mount_point); + + // First check if path exists + if !path.exists() { + return false; + } + + // Try to read directory to verify access + match fs::read_dir(path) { + Ok(mut entries) => { + // Try to read at least one entry + entries.next().is_some() || true // Empty dir is still accessible + } + Err(_) => false, + } +} + +/// Get all network mounts +pub fn get_network_mounts() -> Vec { + parse_mount_info() + .unwrap_or_default() + .into_iter() + .filter(|m| matches!(m.kind, MountKind::Network(_))) + .collect() +} + +/// Get all mounts with their classifications +pub fn get_all_mounts() -> Vec { + parse_mount_info().unwrap_or_default() +} + +// Tauri commands +pub mod commands { + use super::*; + + /// Check if a path is on a network filesystem + #[tauri::command] + pub fn check_network_path(path: String) -> NetworkPathInfo { + is_network_path(Path::new(&path)) + } + + /// Get all network mounts currently visible + #[tauri::command] + pub fn get_network_mounts_cmd() -> Vec { + get_network_mounts() + } + + /// Check if a network mount is currently accessible + #[tauri::command] + pub fn check_mount_accessible(mount_point: String) -> bool { + check_mount_accessibility(&mount_point) + } + + /// Batch check multiple paths for network status + #[tauri::command] + pub fn check_network_paths_batch(paths: Vec) -> HashMap { + let mounts = parse_mount_info().unwrap_or_default(); + + paths + .into_iter() + .map(|p| { + let path = Path::new(&p); + let info = if let Some(mount) = find_mount_for_path(path, &mounts) { + let is_network = matches!(mount.kind, MountKind::Network(_)); + NetworkPathInfo { + is_network, + mount_info: Some(mount), + path: p.clone(), + } + } else { + NetworkPathInfo { + is_network: false, + mount_info: None, + path: p.clone(), + } + }; + (p, info) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_classify_fs_type() { + assert!(matches!(classify_fs_type("ext4", ""), MountKind::Local)); + assert!(matches!(classify_fs_type("cifs", "//server/share"), MountKind::Network(NetworkFs::Cifs))); + assert!(matches!(classify_fs_type("nfs", "server:/export"), MountKind::Network(NetworkFs::Nfs))); + assert!(matches!(classify_fs_type("tmpfs", "tmpfs"), MountKind::Virtual)); + assert!(matches!(classify_fs_type("fuse.sshfs", "user@host:/path"), MountKind::Network(NetworkFs::Sshfs))); + } + + #[test] + fn test_unescape_mount_path() { + assert_eq!(unescape_mount_path("/mnt/My\\040Drive"), "/mnt/My Drive"); + assert_eq!(unescape_mount_path("/normal/path"), "/normal/path"); + } +} diff --git a/src/lib/components/FolderSettingsModal.svelte b/src/lib/components/FolderSettingsModal.svelte new file mode 100644 index 000000000..f60f881ba --- /dev/null +++ b/src/lib/components/FolderSettingsModal.svelte @@ -0,0 +1,628 @@ + + +{#if isOpen && folder} + +{/if} + + diff --git a/src/lib/components/views/LocalLibraryView.svelte b/src/lib/components/views/LocalLibraryView.svelte index 9e29080bf..c9ace2e14 100644 --- a/src/lib/components/views/LocalLibraryView.svelte +++ b/src/lib/components/views/LocalLibraryView.svelte @@ -4,8 +4,11 @@ import { onMount, onDestroy } from 'svelte'; import { HardDrive, Music, Disc3, Mic2, FolderPlus, Trash2, RefreshCw, - Settings, ArrowLeft, X, Play, AlertCircle, ImageDown, Upload, Search, LayoutGrid, List, Edit3 + Settings, ArrowLeft, X, Play, AlertCircle, ImageDown, Upload, Search, LayoutGrid, List, Edit3, + Network, Power, PowerOff } from 'lucide-svelte'; + import FolderSettingsModal from '../FolderSettingsModal.svelte'; + import { t } from '$lib/i18n'; import AlbumCard from '../AlbumCard.svelte'; import TrackRow from '../TrackRow.svelte'; import { @@ -99,6 +102,17 @@ errors: { file_path: string; error: string }[]; } + interface LibraryFolder { + id: number; + path: string; + alias: string | null; + enabled: boolean; + isNetwork: boolean; + networkFsType: string | null; + userOverrideNetwork: boolean; + lastScan: number | null; + } + interface Props { onAlbumClick?: (album: LocalAlbum) => void; onQobuzArtistClick?: (artistId: number) => void; @@ -144,7 +158,7 @@ let artists = $state([]); let tracks = $state([]); let stats = $state(null); - let folders = $state([]); + let folders = $state([]); let scanProgress = $state(null); // Loading state @@ -168,8 +182,15 @@ let editingAlbumTitle = $state(''); let editingAlbumHidden = $state(false); - // Folder selection state - let selectedFolders = $state>(new Set()); + // Folder selection state (by folder ID) + let selectedFolders = $state>(new Set()); + + // Folder settings modal state + let showFolderSettingsModal = $state(false); + let editingFolder = $state(null); + + // Folder accessibility cache + let folderAccessibility = $state>(new Map()); let unsubscribeNav: (() => void) | null = null; let unsubscribeOffline: (() => void) | null = null; @@ -272,12 +293,33 @@ async function loadFolders() { try { - folders = await invoke('library_get_folders'); + folders = await invoke('library_get_folders_with_metadata'); + // Check accessibility for network folders + for (const folder of folders) { + if (folder.isNetwork) { + checkFolderAccessibility(folder); + } else { + folderAccessibility.set(folder.id, true); + } + } + folderAccessibility = new Map(folderAccessibility); } catch (err) { console.error('Failed to load folders:', err); } } + async function checkFolderAccessibility(folder: LibraryFolder) { + try { + const accessible = await invoke('library_check_folder_accessible', { path: folder.path }); + folderAccessibility.set(folder.id, accessible); + folderAccessibility = new Map(folderAccessibility); + } catch (err) { + console.error('Failed to check folder accessibility:', err); + folderAccessibility.set(folder.id, false); + folderAccessibility = new Map(folderAccessibility); + } + } + async function loadArtists() { loading = true; try { @@ -340,21 +382,27 @@ if (!selected || typeof selected !== 'string') return; - await invoke('library_add_folder', { path: selected }); + const newFolder = await invoke('library_add_folder', { path: selected }); await loadFolders(); + + // Show warning if network folder detected + if (newFolder.isNetwork) { + alert($t('library.networkFolderDetected')); + } } catch (err) { console.error('Failed to add folder:', err); } } - async function handleRemoveFolder(path: string) { - if (!confirm(`Remove "${path}" from library? This will remove all indexed tracks from this folder.`)) { + async function handleRemoveFolder(folder: LibraryFolder) { + const displayName = folder.alias || folder.path; + if (!confirm(`Remove "${displayName}" from library? This will remove all indexed tracks from this folder.`)) { return; } try { - await invoke('library_remove_folder', { path }); - selectedFolders.delete(path); + await invoke('library_remove_folder', { path: folder.path }); + selectedFolders.delete(folder.id); selectedFolders = new Set(selectedFolders); await loadFolders(); await loadLibraryData(); @@ -364,24 +412,67 @@ } } - function toggleFolderSelection(folder: string) { - if (selectedFolders.has(folder)) { - selectedFolders.delete(folder); + function toggleFolderSelection(folderId: number) { + if (selectedFolders.has(folderId)) { + selectedFolders.delete(folderId); } else { - selectedFolders.add(folder); + selectedFolders.add(folderId); } selectedFolders = new Set(selectedFolders); } + function handleEditFolder() { + if (selectedFolders.size !== 1) return; + const folderId = Array.from(selectedFolders)[0]; + editingFolder = folders.find(f => f.id === folderId) || null; + if (editingFolder) { + showFolderSettingsModal = true; + } + } + + function handleFolderSettingsSave(updatedFolder: LibraryFolder) { + // Update folder in list + const index = folders.findIndex(f => f.id === updatedFolder.id); + if (index !== -1) { + folders[index] = updatedFolder; + folders = [...folders]; + } + editingFolder = null; + } + + async function handleScanSingleFolder(folderId: number) { + try { + scanning = true; + await invoke('library_scan_folder', { folderId }); + // Start polling for progress + const progressInterval = setInterval(async () => { + scanProgress = await invoke('library_get_scan_progress'); + if (scanProgress.status === 'Complete' || scanProgress.status === 'Cancelled' || scanProgress.status === 'Error') { + clearInterval(progressInterval); + scanning = false; + await loadLibraryData(); + await loadFolders(); + } + }, 500); + } catch (err) { + console.error('Failed to scan folder:', err); + scanning = false; + alert(`Failed to scan folder: ${err}`); + } + } + async function handleRemoveSelectedFolders() { if (selectedFolders.size === 0) return; - + const count = selectedFolders.size; if (!confirm(`Remove ${count} selected folder${count > 1 ? 's' : ''}? This will remove all indexed tracks from these folders.`)) return; try { - for (const folder of selectedFolders) { - await invoke('library_remove_folder', { path: folder }); + for (const folderId of selectedFolders) { + const folder = folders.find(f => f.id === folderId); + if (folder) { + await invoke('library_remove_folder', { path: folder.path }); + } } selectedFolders.clear(); selectedFolders = new Set(selectedFolders); @@ -1368,16 +1459,24 @@ {#if showSettings}
-

Library Folders

+

{$t('library.folders')}

- - + @@ -1386,20 +1485,45 @@ {#if folders.length === 0}
-

No folders added yet. Add a folder to start building your library.

+

{$t('library.noFolders')}

{:else}
- {#each folders as folder} -
+ {#each folders as folder (folder.id)} + {@const accessible = folderAccessibility.get(folder.id) ?? true} +
- {folder} +
+ {#if folder.isNetwork} + + {:else} + + {/if} +
+
+ {#if folder.alias} + {folder.alias} + {folder.path} + {:else} + {folder.path} + {/if} +
+ {#if !folder.enabled} + {$t('library.disabled')} + {:else if folder.isNetwork && !accessible} + {$t('library.unavailable')} + {/if}
{/each}
@@ -2014,6 +2138,15 @@
{/if} + + { showFolderSettingsModal = false; editingFolder = null; }} + onSave={handleFolderSettingsSave} + onScanFolder={handleScanSingleFolder} +/> +