diff --git a/src/workers.rs b/src/workers.rs index f33092f..5829396 100644 --- a/src/workers.rs +++ b/src/workers.rs @@ -489,7 +489,34 @@ async fn trigger_pipeline_completion(state: &web::Data, pipeline_id: & let conn = state.db.conn(); tracing::info!(pipeline_id = %pipeline_id, "pipeline complete, running cleanup"); - // Cleanup: remove orphaned tracks, empty albums, unused artists + // Cleanup: remove unwanted tracks (files + DB), orphaned records, empty dirs + let library_path = state.config.read().await.library_path.clone(); + + // Delete files for tracks that went through tagging but aren't wanted + match queries::tracks::get_unwanted(conn).await { + Ok(unwanted) if !unwanted.is_empty() => { + let count = unwanted.len(); + for track in &unwanted { + let path = std::path::Path::new(&track.file_path); + if path.exists() { + if let Err(e) = std::fs::remove_file(path) { + tracing::warn!(path = %track.file_path, error = %e, "failed to delete unwanted file"); + } else { + // Clean up empty parent dirs + if let Some(parent) = path.parent() { + shanty_org::organizer::cleanup_empty_dirs(parent, &library_path); + } + } + } + let _ = queries::tracks::delete(conn, track.id).await; + } + tracing::info!(count, "cleaned up unwanted tracks and files"); + } + Err(e) => tracing::warn!(error = %e, "failed to find unwanted tracks"), + _ => {} + } + + // Remove DB records for files that no longer exist on disk match queries::tracks::delete_orphaned(conn).await { Ok(n) if n > 0 => tracing::info!(count = n, "cleaned up orphaned tracks"), Err(e) => tracing::warn!(error = %e, "failed to clean orphaned tracks"),