Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 145 additions & 20 deletions crates/vuio-core/src/lifecycle/media/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,38 @@ pub(in crate::lifecycle) async fn import_changed_playlist<D: DatabaseManager + ?
}
}

async fn remove_indexed_path<D: DatabaseManager + 'static>(
path: &Path,
is_directory: Option<bool>,
app_state: &AppState<D>,
) -> 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<D: DatabaseManager + 'static>(
event: FileSystemEvent,
app_state: &AppState<D>,
Expand Down Expand Up @@ -320,26 +352,7 @@ pub(in crate::lifecycle) async fn handle_file_system_event<D: DatabaseManager +
return Ok(());
}
info!("Path deleted: {}", path.display());
let derived_removed = database.remove_derived_content_by_source(&path).await?;
let summary = database
.remove_media_under_path(&path)
.await
.inspect_err(|_error| {
stats.record_error();
})?;
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()
);
// Publish empty/duplicate directory events because they can retire an
// older browse generation. Known unrelated file deletions do not churn
// the library revision unless they removed indexed/derived content.
if is_directory != Some(false) || summary.removed_files > 0 || derived_removed > 0 {
increment_content_update_id(app_state).await;
}
remove_indexed_path(&path, is_directory, app_state).await?;
}

FileSystemEvent::Renamed { from, to } => {
Expand All @@ -354,6 +367,16 @@ pub(in crate::lifecycle) async fn handle_file_system_event<D: DatabaseManager +
}
info!("Path renamed: {} -> {}", 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 {
Expand Down Expand Up @@ -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("</e:propertyset>") {
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!(
"<SystemUpdateID>{}</SystemUpdateID>",
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.
///
Expand Down
54 changes: 49 additions & 5 deletions crates/vuio-core/src/lifecycle/media/scanning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,10 +252,10 @@ pub(in crate::lifecycle) async fn reconcile_unavailable_media_roots<D: DatabaseM
let indexed_count = previous.as_ref().map_or(0, |state| state.indexed_count);
let probe = tokio::fs::read_dir(root).await;
let reason = match probe {
Ok(mut entries) => {
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(),
Expand All @@ -267,7 +267,8 @@ pub(in crate::lifecycle) async fn reconcile_unavailable_media_roots<D: DatabaseM
.await?;
None
}
}
Err(error) => Some(format!("{}: {error}", error.kind())),
},
Err(error) => Some(format!("{}: {error}", error.kind())),
};
let Some(reason) = reason else {
Expand Down Expand Up @@ -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 —
Expand Down
30 changes: 5 additions & 25 deletions crates/vuio-core/src/media/scanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,18 +195,8 @@ impl<D: DatabaseManager> MediaScanner<D> {
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
}
Expand Down Expand Up @@ -617,22 +607,12 @@ impl<D: DatabaseManager> MediaScanner<D> {
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<PathBuf> = if reconcile_deletions {
existing_files_map
.iter()
Expand All @@ -646,7 +626,7 @@ impl<D: DatabaseManager> MediaScanner<D> {
existing_files_map
.iter()
.filter(|(_, indexed)| !indexed.seen)
.filter(|_| traversal.root_complete && !suspect_empty_root)
.filter(|_| traversal.root_complete)
.filter(|(path, _)| {
!traversal
.uncertain_prefixes
Expand Down
Loading
Loading