diff --git a/crates/vuio-core/src/lifecycle/media/events.rs b/crates/vuio-core/src/lifecycle/media/events.rs index ad2d1a0..db116c9 100644 --- a/crates/vuio-core/src/lifecycle/media/events.rs +++ b/crates/vuio-core/src/lifecycle/media/events.rs @@ -172,6 +172,38 @@ pub(in crate::lifecycle) async fn import_changed_playlist( + path: &Path, + is_directory: Option, + app_state: &AppState, +) -> anyhow::Result<()> { + let derived_removed = app_state + .database + .remove_derived_content_by_source(path) + .await?; + let summary = app_state + .database + .remove_media_under_path(path) + .await + .inspect_err(|_| { + app_state.lifecycle_stats.record_error(); + })?; + app_state + .lifecycle_stats + .record_files_processed(summary.removed_files as u64); + info!( + "Removed {} indexed files and {} derived items below deleted path {}", + summary.removed_files, + derived_removed, + path.display() + ); + // Directory events also retire cached listings when the rows are already gone. + if is_directory != Some(false) || summary.removed_files > 0 || derived_removed > 0 { + increment_content_update_id(app_state).await; + } + Ok(()) +} + pub(in crate::lifecycle) async fn handle_file_system_event( event: FileSystemEvent, app_state: &AppState, @@ -320,26 +352,7 @@ pub(in crate::lifecycle) async fn handle_file_system_event 0 || derived_removed > 0 { - increment_content_update_id(app_state).await; - } + remove_indexed_path(&path, is_directory, app_state).await?; } FileSystemEvent::Renamed { from, to } => { @@ -354,6 +367,16 @@ pub(in crate::lifecycle) async fn handle_file_system_event {}", from.display(), to.display()); + // File managers can report moving a folder to Trash as a paired + // rename. Its destination is outside the library, so the old subtree + // must be retired just like a deletion, including derived playlists. + if media::ScanPolicy::for_path(&policies, &from).is_some() + && media::ScanPolicy::for_path(&policies, &to).is_none() + { + remove_indexed_path(&from, None, app_state).await?; + return Ok(()); + } + // Check if the destination is a directory or file if to.is_dir() { let Some(policy) = media::ScanPolicy::for_path(&policies, &to).cloned() else { @@ -786,6 +809,108 @@ mod tests { } } + #[tokio::test] + async fn moving_a_folder_out_of_the_library_removes_its_index_and_publishes() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("library"); + let folder = root.join("films/series"); + std::fs::create_dir_all(&folder).unwrap(); + let state = state_watching(&root).await; + let file = folder.join("episode.mp4"); + std::fs::write(&file, b"video").unwrap(); + handle_file_system_event(FileSystemEvent::Created(file.clone()), &state) + .await + .unwrap(); + let revision = state.content_update_id.load(Ordering::SeqCst); + let cache_key = crate::state::SoapCacheKey { + object_id: "2".to_owned(), + starting_index: 0, + requested_count: 100, + client_profile: crate::web::client::DlnaClientProfile::Standard, + content_update_id: revision, + browse_epoch: state.browse_cache.lock().await.epoch(), + }; + state.browse_cache.lock().await.insert( + cache_key.clone(), + axum::body::Bytes::from_static(b"old folder listing"), + ); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let now = std::time::Instant::now(); + state.upnp_subscriptions.lock().await.insert( + "uuid:tv".to_owned(), + crate::state::UpnpSubscription { + callback_url: format!("http://{}/events", listener.local_addr().unwrap()), + peer: "127.0.0.1".parse().unwrap(), + generation: uuid::Uuid::new_v4(), + expires_at: now + std::time::Duration::from_secs(60), + next_sequence: 1, + consecutive_failures: 0, + last_notification_at: now.checked_sub(std::time::Duration::from_secs(1)).unwrap(), + pending_notification: false, + notification_worker: None, + }, + ); + + let destination = temp.path().join("trash"); + std::fs::rename(root.join("films"), &destination).unwrap(); + handle_file_system_event( + FileSystemEvent::Renamed { + from: root.join("films"), + to: destination, + }, + &state, + ) + .await + .unwrap(); + + assert!(state + .database + .get_file_by_path(&file) + .await + .unwrap() + .is_none()); + let (directories, files) = state + .database + .get_directory_listing(&root, "video/") + .await + .unwrap(); + assert!( + directories.is_empty(), + "the moved folder must leave the TV browse tree" + ); + assert!(files.is_empty()); + assert_eq!( + state.content_update_id.load(Ordering::SeqCst), + revision.wrapping_add(1) + ); + assert!(state.browse_cache.lock().await.get(&cache_key).is_none()); + + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let notification = tokio::time::timeout(std::time::Duration::from_secs(5), async { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0u8; 4096]; + while !String::from_utf8_lossy(&request).contains("") { + let read = stream.read(&mut buffer).await.unwrap(); + assert!(read > 0, "the UPnP notification must have a complete body"); + request.extend_from_slice(&buffer[..read]); + } + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + String::from_utf8(request).unwrap() + }) + .await + .expect("the subscribed TV must receive the deletion revision"); + assert!(notification.starts_with("NOTIFY ")); + assert!(notification.contains(&format!( + "{}", + revision.wrapping_add(1) + ))); + } + /// An AIFF carrying an ID3v2.3 tag: a title, one tag with no column of its /// own, and `frames` samples at 44.1 kHz. /// diff --git a/crates/vuio-core/src/lifecycle/media/scanning.rs b/crates/vuio-core/src/lifecycle/media/scanning.rs index d90960b..707d71d 100644 --- a/crates/vuio-core/src/lifecycle/media/scanning.rs +++ b/crates/vuio-core/src/lifecycle/media/scanning.rs @@ -252,10 +252,10 @@ pub(in crate::lifecycle) async fn reconcile_unavailable_media_roots { - if indexed_count > 0 && entries.next_entry().await?.is_none() { - Some("previously populated root is unexpectedly empty".to_owned()) - } else { + Ok(mut entries) => match entries.next_entry().await { + Ok(_) => { + // An accessible empty root can be the result of deleting its + // last file. Only a failed read establishes unavailability. database .set_root_availability(&database::RootAvailability { path: root.clone(), @@ -267,7 +267,8 @@ pub(in crate::lifecycle) async fn reconcile_unavailable_media_roots Some(format!("{}: {error}", error.kind())), + }, Err(error) => Some(format!("{}: {error}", error.kind())), }; let Some(reason) = reason else { @@ -593,6 +594,49 @@ mod tests { paths } + #[tokio::test] + async fn a_readable_empty_library_is_available_and_cleans_up() { + let root = tempfile::TempDir::new().unwrap(); + let file = root.path().join("last.mp4"); + std::fs::write(&file, b"video").unwrap(); + let (database, _temp) = database_with(std::slice::from_ref(&file)).await; + database + .set_root_availability(&database::RootAvailability { + path: root.path().to_path_buf(), + last_seen_secs: unix_now_secs(), + unavailable_since_secs: Some(unix_now_secs()), + indexed_count: 1, + reason: "previously populated root is unexpectedly empty".to_owned(), + }) + .await + .unwrap(); + std::fs::remove_file(&file).unwrap(); + + let roots = [root.path().to_path_buf()]; + assert_eq!( + reconcile_unavailable_media_roots(&database, &roots, 168, true) + .await + .unwrap(), + 0 + ); + let availability = database + .get_root_availability(root.path()) + .await + .unwrap() + .unwrap(); + assert!( + availability.unavailable_since_secs.is_none(), + "readable empty roots must recover from the old empty-root state" + ); + assert_eq!( + validate_and_cleanup_deleted_files(database.clone(), &roots, true) + .await + .unwrap(), + 1 + ); + assert!(indexed_paths(&database).await.is_empty()); + } + /// Removing a library through the config watcher drops its content, but a library /// that is simply absent at startup never got that treatment. Its files stayed /// indexed forever — they still exist on disk, which was the only question asked — diff --git a/crates/vuio-core/src/media/scanner.rs b/crates/vuio-core/src/media/scanner.rs index 29eb2c1..88cb2ef 100644 --- a/crates/vuio-core/src/media/scanner.rs +++ b/crates/vuio-core/src/media/scanner.rs @@ -195,18 +195,8 @@ impl MediaScanner { current_files.push(self.create_media_file_from_path(&path).await?); } } - if current_files.is_empty() && !existing_files.is_empty() { - let mut result = ScanResult::new(); - result.complete = false; - result.total_scanned = 0; - result.errors.push(ScanError { - path: canonical_dir, - error: "previously populated root is unexpectedly empty; destructive reconciliation deferred" - .to_owned(), - }); - result.unchanged += existing_files.len(); - return Ok(result); - } + // A successful directory read is authoritative even when the last media + // file was deleted. Read errors above leave the existing index intact. self.perform_incremental_update(&canonical_dir, existing_files, current_files) .await } @@ -617,22 +607,12 @@ impl MediaScanner { let traversal = traversal_task.await?; let total_files = processed; - let suspect_empty_root = total_files == 0 && existing_in_root > 0; result.errors.extend(traversal.errors); - result.complete = traversal.root_complete - && traversal.uncertain_prefixes.is_empty() - && !suspect_empty_root; - if suspect_empty_root { - result.errors.push(ScanError { - path: canonical_root.clone(), - error: "previously populated root is unexpectedly empty; destructive reconciliation deferred" - .to_owned(), - }); - } + result.complete = traversal.root_complete && traversal.uncertain_prefixes.is_empty(); // Whatever the walk never produced is gone from disk. let reconcile_deletions = - traversal.root_complete && !suspect_empty_root && traversal.uncertain_prefixes.is_empty(); + traversal.root_complete && traversal.uncertain_prefixes.is_empty(); let files_to_remove: Vec = if reconcile_deletions { existing_files_map .iter() @@ -646,7 +626,7 @@ impl MediaScanner { existing_files_map .iter() .filter(|(_, indexed)| !indexed.seen) - .filter(|_| traversal.root_complete && !suspect_empty_root) + .filter(|_| traversal.root_complete) .filter(|(path, _)| { !traversal .uncertain_prefixes diff --git a/crates/vuio-core/src/media/tests.rs b/crates/vuio-core/src/media/tests.rs index f4cb731..c350429 100644 --- a/crates/vuio-core/src/media/tests.rs +++ b/crates/vuio-core/src/media/tests.rs @@ -182,6 +182,96 @@ async fn recursive_scan_removes_what_is_gone_from_disk() { assert_eq!(survivors[0].filename, "stays.mp4"); } +#[tokio::test] +async fn scans_remove_the_last_media_from_a_readable_library() { + for recursive in [false, true] { + let temp = tempdir().unwrap(); + let db = Arc::new( + SqliteDatabase::new(temp.path().join("empty.db")) + .await + .unwrap(), + ); + db.initialize().await.unwrap(); + let scanner = MediaScanner::with_database(db.clone()); + let root = temp.path().join("library"); + let parent = if recursive { + root.join("films/series") + } else { + root.clone() + }; + std::fs::create_dir_all(&parent).unwrap(); + let file = parent.join("last.mp4"); + std::fs::write(&file, b"video").unwrap(); + let policy = ScanPolicy::platform_default(&root, recursive); + let first = if recursive { + scanner + .scan_directory_recursive_with_policy(&policy) + .await + .unwrap() + } else { + scanner.scan_directory_with_policy(&policy).await.unwrap() + }; + assert_eq!(first.new, 1); + + if recursive { + std::fs::remove_dir_all(root.join("films")).unwrap(); + } else { + std::fs::remove_file(&file).unwrap(); + } + let rescan = if recursive { + scanner + .scan_directory_recursive_with_policy(&policy) + .await + .unwrap() + } else { + scanner.scan_directory_with_policy(&policy).await.unwrap() + }; + assert!( + rescan.complete, + "an empty, readable library is a complete scan" + ); + assert_eq!(rescan.removed, 1, "the last file must leave the index"); + assert!(db.get_file_by_path(&file).await.unwrap().is_none()); + let (directories, files) = db.get_directory_listing(&root, "video/").await.unwrap(); + assert!( + directories.is_empty(), + "deleted folders must leave TV listings" + ); + assert!(files.is_empty()); + } +} + +#[tokio::test] +async fn scans_keep_media_when_the_library_is_unreadable() { + for recursive in [false, true] { + let temp = tempdir().unwrap(); + let db = Arc::new( + SqliteDatabase::new(temp.path().join("offline.db")) + .await + .unwrap(), + ); + db.initialize().await.unwrap(); + let scanner = MediaScanner::with_database(db.clone()); + let root = temp.path().join("library"); + std::fs::create_dir(&root).unwrap(); + let file = root.join("keep.mp4"); + std::fs::write(&file, b"video").unwrap(); + scanner.scan_directory(&root).await.unwrap(); + + std::fs::rename(&root, temp.path().join("unmounted")).unwrap(); + let result = if recursive { + scanner.scan_directory_recursive(&root).await + } else { + scanner.scan_directory(&root).await + }; + if let Ok(result) = result { + assert!(!result.complete); + assert_eq!(result.removed, 0); + } + assert!(db.get_file_by_path(&file).await.unwrap().is_some()); + } +} + /// A scan compares one root against one root. It loads only that subtree's /// records, and a sibling library — including one whose path is a string prefix /// of this one — must be neither examined nor deleted. diff --git a/crates/vuio-core/src/watcher/mod.rs b/crates/vuio-core/src/watcher/mod.rs index fe703e3..1bfc380 100644 --- a/crates/vuio-core/src/watcher/mod.rs +++ b/crates/vuio-core/src/watcher/mod.rs @@ -238,6 +238,28 @@ fn path_is_relevant(path: &Path, policies: &[ScanPolicy]) -> bool { ScanPolicy::for_path(policies, path).is_some_and(|policy| policy.allows_watched_path(path)) } +fn record_rescan_events( + events: &[DebouncedEvent], + watched_paths: &std::sync::Mutex>, + dirty_roots: &std::sync::Mutex>, +) { + if events.iter().any(|event| event.need_rescan()) { + // Queue overflow is delivered as a successful event with no paths, not + // an error. Record it before path filtering discards that signal. + let watched = watched_paths + .lock() + .unwrap_or_else(|error| error.into_inner()); + dirty_roots + .lock() + .unwrap_or_else(|error| error.into_inner()) + .extend( + watched + .values() + .map(|registration| registration.path.clone()), + ); + } +} + /// Convert notify events to our FileSystemEvent enum (helper) fn convert_watcher_events( events: Vec, @@ -388,6 +410,7 @@ impl CrossPlatformWatcher { move |result: DebounceEventResult| { match result { Ok(events) => { + record_rescan_events(&events, &watched_paths, &dirty_roots); if !events.is_empty() { debug!("Watcher callback triggered with {} events", events.len()); for event in &events { diff --git a/crates/vuio-core/src/watcher/tests.rs b/crates/vuio-core/src/watcher/tests.rs index 098fb6a..bf52c53 100644 --- a/crates/vuio-core/src/watcher/tests.rs +++ b/crates/vuio-core/src/watcher/tests.rs @@ -9,6 +9,41 @@ async fn test_watcher_creation() { assert!(!watcher.is_watching(Path::new("/nonexistent")).await); } +#[test] +fn a_backend_rescan_signal_marks_all_roots_dirty_even_without_paths() { + let watcher = CrossPlatformWatcher::new(); + let roots = [PathBuf::from("/media/films"), PathBuf::from("/media/music")]; + for root in &roots { + watcher.watched_paths.lock().unwrap().insert( + root.clone(), + WatchRegistration { + path: root.clone(), + recursive: true, + }, + ); + } + let rescan = DebouncedEvent::new( + notify::Event::new(notify::EventKind::Other).set_flag(notify::event::Flag::Rescan), + std::time::Instant::now(), + ); + record_rescan_events(&[rescan], &watcher.watched_paths, &watcher.dirty_roots); + let mut dirty = watcher.take_dirty_roots(); + dirty.sort(); + assert_eq!(dirty, roots); + assert!(watcher.take_dirty_roots().is_empty()); + + let ordinary = DebouncedEvent::new( + notify::Event::new(notify::EventKind::Remove(notify::event::RemoveKind::File)) + .add_path(roots[0].join("film.mp4")), + std::time::Instant::now(), + ); + record_rescan_events(&[ordinary], &watcher.watched_paths, &watcher.dirty_roots); + assert!( + watcher.take_dirty_roots().is_empty(), + "ordinary deletions stay incremental" + ); +} + #[tokio::test] async fn test_media_file_detection() { let watcher = CrossPlatformWatcher::new();