1use std::fs;
4use std::io::Write;
5use std::path::Path;
6
7use rusqlite::{params, Connection, OptionalExtension, Result as SqliteResult};
8
9use crate::db::{album_repo::AlbumRepo, FaceRepo, PhotoStackRepo};
10use crate::services::path_util::{safe_existing_path_under_root, safe_join_relative};
11
12#[derive(Debug, Default, Clone)]
14pub struct DeleteResult {
15 pub files_deleted: usize,
16 pub db_records_deleted: usize,
17 pub errors: Vec<String>,
18 pub committed_with_recovery_errors: bool,
19}
20
21#[derive(Debug, Default, Clone)]
23pub struct TrashStats {
24 pub count: usize,
25 pub total_size: u64,
26}
27
28pub struct TrashService;
30
31#[derive(serde::Serialize, serde::Deserialize)]
32struct DeletionIntent {
33 photo_id: i64,
34 relative_path: String,
35}
36
37impl TrashService {
38 pub fn trash_photos(conn: &Connection, photo_ids: &[i64]) -> SqliteResult<usize> {
39 let tx = conn.unchecked_transaction()?;
40 let count = Self::trash_photos_tx(&tx, photo_ids)?;
41 tx.commit()?;
42 Ok(count)
43 }
44
45 pub fn trash_photos_tx(
49 tx: &rusqlite::Transaction<'_>,
50 photo_ids: &[i64],
51 ) -> SqliteResult<usize> {
52 let mut count = 0usize;
53
54 for photo_id in photo_ids {
55 let path: Option<String> = tx
56 .query_row(
57 "SELECT file_path FROM photos WHERE id = ?1 AND is_trashed = FALSE",
58 params![photo_id],
59 |row| row.get(0),
60 )
61 .optional()?;
62
63 if let Some(path) = path {
64 tx.execute(
65 "INSERT OR IGNORE INTO trash (photo_id, original_path) VALUES (?1, ?2)",
66 params![photo_id, path],
67 )?;
68 tx.execute(
69 "UPDATE photos SET is_trashed = TRUE, trashed_at = CURRENT_TIMESTAMP WHERE id = ?1",
70 params![photo_id],
71 )?;
72 count += 1;
73 }
74 }
75
76 PhotoStackRepo::new(tx).reconcile_after_photos_trashed(photo_ids)?;
77 refresh_album_state_for_photos(tx, photo_ids)?;
78 refresh_face_state_for_photos(tx, photo_ids)?;
79 Ok(count)
80 }
81
82 pub fn restore_photos(conn: &Connection, photo_ids: &[i64]) -> SqliteResult<usize> {
83 let tx = conn.unchecked_transaction()?;
84 let mut count = 0usize;
85
86 for photo_id in photo_ids {
87 let removed = tx.execute("DELETE FROM trash WHERE photo_id = ?1", params![photo_id])?;
88 let updated = tx.execute(
89 "UPDATE photos SET is_trashed = FALSE, trashed_at = NULL WHERE id = ?1 AND is_trashed = TRUE",
90 params![photo_id],
91 )?;
92 if removed > 0 || updated > 0 {
93 count += 1;
94 }
95 }
96
97 refresh_album_state_for_photos(&tx, photo_ids)?;
98 refresh_face_state_for_photos(&tx, photo_ids)?;
99 tx.commit()?;
100 Ok(count)
101 }
102
103 pub fn permanent_delete(
104 conn: &Connection,
105 photo_ids: &[i64],
106 drive_root: &Path,
107 ) -> SqliteResult<DeleteResult> {
108 Self::recover_deletions(conn, drive_root)
109 .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
110 let synchronous: i64 = conn.pragma_query_value(None, "synchronous", |row| row.get(0))?;
113 conn.pragma_update(None, "synchronous", "FULL")?;
114 let operation = (|| {
115 let tx = conn.unchecked_transaction()?;
116 let mut result = DeleteResult::default();
117
118 for photo_id in photo_ids {
119 let row: Option<(String, Option<String>)> = tx
120 .query_row(
121 "SELECT file_path, thumbnail_path FROM photos WHERE id = ?1 AND is_trashed = TRUE",
122 params![photo_id],
123 |row| Ok((row.get(0)?, row.get(1)?)),
124 )
125 .optional()?;
126
127 let Some((relative_path, thumbnail_path)) = row else {
128 continue;
129 };
130
131 let full_path = match safe_join_relative(drive_root, &relative_path) {
132 Ok(path) => path,
133 Err(e) => {
134 result.errors.push(format!("{}: {}", relative_path, e));
135 continue;
136 }
137 };
138 if full_path.exists() {
139 let delete_path =
140 match safe_existing_path_under_root(drive_root, &relative_path) {
141 Ok(path) => path,
142 Err(e) => {
143 result.errors.push(format!("{}: {}", relative_path, e));
144 continue;
145 }
146 };
147 if let Err(e) =
148 stage_deletion(drive_root, *photo_id, &relative_path, &delete_path)
149 {
150 result.errors.push(format!("{}: {}", relative_path, e));
151 continue;
152 }
153 result.files_deleted += 1;
154 }
155
156 if let Some(tp) = thumbnail_path {
159 if let Ok(cache_relative) =
160 Path::new(&tp).strip_prefix(".photovault/thumbnails")
161 {
162 if let Ok(cache_root) =
163 safe_existing_path_under_root(drive_root, ".photovault/thumbnails")
164 {
165 if let Ok(thumb_full) = safe_existing_path_under_root(
166 &cache_root,
167 &cache_relative.to_string_lossy(),
168 ) {
169 let _ = fs::remove_file(thumb_full);
170 }
171 }
172 }
173 }
174
175 refresh_album_state_for_photos(&tx, &[*photo_id])?;
176 refresh_face_state_for_photos(&tx, &[*photo_id])?;
177 tx.execute("DELETE FROM trash WHERE photo_id = ?1", params![photo_id])?;
178 tx.execute("DELETE FROM photos WHERE id = ?1", params![photo_id])?;
179 result.db_records_deleted += 1;
180 }
181
182 refresh_album_state_for_photos(&tx, photo_ids)?;
183 refresh_face_state_for_photos(&tx, photo_ids)?;
184 tx.commit()?;
185 Ok(result)
186 })();
187 let recovery = Self::recover_deletions(conn, drive_root);
188 if let Err(error) = conn.pragma_update(None, "synchronous", synchronous) {
189 tracing::warn!("Could not restore SQLite synchronous mode: {error}");
190 }
191 match operation {
192 Err(error) => {
193 if let Err(recovery_error) = recovery {
194 tracing::error!(
195 "Originals retained in .photovault/delete-* for recovery: {recovery_error}"
196 );
197 }
198 Err(error)
199 }
200 Ok(mut result) => {
201 if let Err(error) = recovery {
202 result.committed_with_recovery_errors = true;
203 result
204 .errors
205 .push(format!("Staged deletion retained for recovery: {error}"));
206 }
207 Ok(result)
208 }
209 }
210 }
211
212 pub fn recover_deletions(conn: &Connection, drive_root: &Path) -> std::io::Result<()> {
214 if !drive_root.join(".photovault").exists() {
215 return Ok(());
216 }
217 let metadata = safe_existing_path_under_root(drive_root, ".photovault")
218 .map_err(std::io::Error::other)?;
219 for entry in fs::read_dir(metadata)? {
220 let entry = entry?;
221 if !entry.file_name().to_string_lossy().starts_with("delete-")
222 || !entry.file_type()?.is_dir()
223 {
224 continue;
225 }
226 let directory = entry.path();
227 let manifest = directory.join("intent.json");
228 if !manifest.exists() {
229 continue;
230 }
231 let intent: DeletionIntent = serde_json::from_slice(&fs::read(&manifest)?)?;
232 let staged = directory.join("original");
233 if staged.exists() {
234 let retained: bool = conn
235 .query_row(
236 "SELECT EXISTS(SELECT 1 FROM photos WHERE id = ?1)",
237 [intent.photo_id],
238 |row| row.get(0),
239 )
240 .map_err(std::io::Error::other)?;
241 if retained {
242 let original = safe_join_relative(drive_root, &intent.relative_path)
243 .map_err(std::io::Error::other)?;
244 let parent = original
245 .parent()
246 .ok_or_else(|| std::io::Error::other("missing original parent"))?;
247 if !parent
248 .canonicalize()?
249 .starts_with(drive_root.canonicalize()?)
250 {
251 return Err(std::io::Error::other("original parent escaped library"));
252 }
253 let mut source = tempfile::TempPath::try_from_path(staged.clone())?;
256 source.disable_cleanup(true);
257 source
258 .persist_noclobber(&original)
259 .map_err(|error| error.error)?;
260 sync_directory(parent)?;
261 }
262 if staged.exists() {
263 fs::remove_file(&staged)?;
264 }
265 }
266 fs::remove_file(manifest)?;
267 fs::remove_dir(&directory)?;
268 sync_directory(directory.parent().expect("journal parent"))?;
269 }
270 Ok(())
271 }
272
273 pub fn empty_trash(conn: &Connection, drive_root: &Path) -> SqliteResult<DeleteResult> {
274 let mut stmt = conn.prepare("SELECT photo_id FROM trash")?;
275 let ids: Vec<i64> = stmt
276 .query_map([], |row| row.get(0))?
277 .collect::<SqliteResult<Vec<_>>>()?;
278 drop(stmt);
279 Self::permanent_delete(conn, &ids, drive_root)
280 }
281
282 pub fn get_stats(conn: &Connection) -> SqliteResult<TrashStats> {
283 let count: i64 = conn.query_row(
284 "SELECT COUNT(*) FROM photos WHERE is_trashed = TRUE",
285 [],
286 |row| row.get(0),
287 )?;
288
289 let total: i64 = conn.query_row(
290 "SELECT COALESCE(SUM(file_size), 0) FROM photos WHERE is_trashed = TRUE",
291 [],
292 |row| row.get(0),
293 )?;
294
295 Ok(TrashStats {
296 count: count as usize,
297 total_size: total.max(0) as u64,
298 })
299 }
300}
301
302fn stage_deletion(
303 root: &Path,
304 photo_id: i64,
305 relative_path: &str,
306 original: &Path,
307) -> std::io::Result<()> {
308 fs::create_dir_all(root.join(".photovault"))?;
309 let metadata =
310 safe_existing_path_under_root(root, ".photovault").map_err(std::io::Error::other)?;
311 let directory = tempfile::Builder::new()
312 .prefix("delete-")
313 .tempdir_in(metadata)?;
314 let intent = DeletionIntent {
315 photo_id,
316 relative_path: relative_path.into(),
317 };
318 let mut manifest = fs::File::create(directory.path().join("intent.json"))?;
319 manifest.write_all(&serde_json::to_vec(&intent)?)?;
320 manifest.sync_all()?;
321 sync_directory(directory.path())?;
322 sync_directory(directory.path().parent().expect("journal parent"))?;
323 let directory = directory.keep();
325 fs::rename(original, directory.join("original"))?;
326 sync_directory(&directory)?;
327 sync_directory(original.parent().expect("original parent"))?;
328 Ok(())
329}
330
331fn sync_directory(path: &Path) -> std::io::Result<()> {
332 #[cfg(unix)]
333 {
334 fs::File::open(path)?.sync_all()
335 }
336 #[cfg(not(unix))]
337 {
338 let _ = path;
339 Ok(())
340 }
341}
342
343fn refresh_album_state_for_photos(conn: &Connection, photo_ids: &[i64]) -> SqliteResult<()> {
344 if photo_ids.is_empty() {
345 return Ok(());
346 }
347
348 let mut album_ids = Vec::new();
349 for chunk in photo_ids.chunks(900) {
350 let placeholders = (0..chunk.len()).map(|_| "?").collect::<Vec<_>>().join(",");
351 let sql = format!(
352 "SELECT DISTINCT album_id FROM album_photos WHERE photo_id IN ({})",
353 placeholders
354 );
355 let mut stmt = conn.prepare(&sql)?;
356 let rows = stmt.query_map(rusqlite::params_from_iter(chunk.iter().copied()), |row| {
357 row.get(0)
358 })?;
359 for row in rows {
360 album_ids.push(row?);
361 }
362 }
363 album_ids.sort_unstable();
364 album_ids.dedup();
365
366 let repo = AlbumRepo::new(conn);
367 for album_id in album_ids {
368 repo.refresh_stats(album_id)?;
369 }
370 Ok(())
371}
372
373fn refresh_face_state_for_photos(
374 tx: &rusqlite::Transaction<'_>,
375 photo_ids: &[i64],
376) -> SqliteResult<()> {
377 if photo_ids.is_empty() {
378 return Ok(());
379 }
380
381 let mut cluster_ids = Vec::new();
382 for chunk in photo_ids.chunks(900) {
383 let placeholders = (0..chunk.len()).map(|_| "?").collect::<Vec<_>>().join(",");
384 let sql = format!(
385 "SELECT DISTINCT cluster_id FROM faces
386 WHERE photo_id IN ({0}) AND cluster_id IS NOT NULL
387 UNION
388 SELECT DISTINCT cluster_id FROM photo_inferred_identities
389 WHERE photo_id IN ({0})",
390 placeholders
391 );
392 let mut params = Vec::with_capacity(chunk.len() * 2);
393 params.extend(chunk.iter().copied());
394 params.extend(chunk.iter().copied());
395 let mut stmt = tx.prepare(&sql)?;
396 let rows = stmt.query_map(rusqlite::params_from_iter(params), |row| row.get(0))?;
397 for row in rows {
398 cluster_ids.push(row?);
399 }
400 }
401
402 cluster_ids.sort_unstable();
403 cluster_ids.dedup();
404 for cluster_id in cluster_ids {
405 FaceRepo::refresh_cluster_stats_tx(tx, cluster_id)?;
406 FaceRepo::refresh_gallery_tx(tx, cluster_id)?;
407 }
408 Ok(())
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416 use crate::db::create_schema;
417 use rusqlite::Connection;
418
419 #[test]
420 fn permanent_delete_ignores_photos_not_in_trash() {
421 let temp = tempfile::tempdir().unwrap();
422 let photo_path = temp.path().join("keep.jpg");
423 std::fs::write(&photo_path, b"original").unwrap();
424
425 let conn = Connection::open_in_memory().unwrap();
426 create_schema(&conn).unwrap();
427 conn.execute(
428 "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, is_trashed)
429 VALUES (1, 'keep.jpg', 'keep.jpg', 'hash', 8, FALSE)",
430 [],
431 )
432 .unwrap();
433
434 let result = TrashService::permanent_delete(&conn, &[1], temp.path()).unwrap();
435
436 assert_eq!(result.files_deleted, 0);
437 assert_eq!(result.db_records_deleted, 0);
438 assert!(photo_path.exists());
439 let count: i64 = conn
440 .query_row("SELECT COUNT(*) FROM photos WHERE id = 1", [], |row| {
441 row.get(0)
442 })
443 .unwrap();
444 assert_eq!(count, 1);
445 }
446
447 #[test]
448 fn empty_trash_deletes_collected_rows() {
449 let temp = tempfile::tempdir().unwrap();
450 let photo_path = temp.path().join("gone.jpg");
451 std::fs::write(&photo_path, b"original").unwrap();
452
453 let conn = Connection::open_in_memory().unwrap();
454 create_schema(&conn).unwrap();
455 conn.execute(
456 "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, is_trashed)
457 VALUES (1, 'gone.jpg', 'gone.jpg', 'hash', 8, TRUE)",
458 [],
459 )
460 .unwrap();
461 conn.execute(
462 "INSERT INTO trash (photo_id, original_path) VALUES (1, 'gone.jpg')",
463 [],
464 )
465 .unwrap();
466
467 let result = TrashService::empty_trash(&conn, temp.path()).unwrap();
468
469 assert_eq!(result.files_deleted, 1);
470 assert_eq!(result.db_records_deleted, 1);
471 assert!(!photo_path.exists());
472 let count: i64 = conn
473 .query_row("SELECT COUNT(*) FROM photos", [], |row| row.get(0))
474 .unwrap();
475 assert_eq!(count, 0);
476 }
477
478 #[test]
479 fn permanent_delete_refuses_symlink_escape() {
480 let temp = tempfile::tempdir().unwrap();
481 let outside = tempfile::tempdir().unwrap();
482 let outside_file = outside.path().join("secret.jpg");
483 std::fs::write(&outside_file, b"secret").unwrap();
484
485 #[cfg(unix)]
486 std::os::unix::fs::symlink(outside.path(), temp.path().join("link")).unwrap();
487
488 #[cfg(windows)]
489 if std::os::windows::fs::symlink_dir(outside.path(), temp.path().join("link")).is_err() {
490 return;
491 }
492
493 let conn = Connection::open_in_memory().unwrap();
494 create_schema(&conn).unwrap();
495 conn.execute(
496 "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, is_trashed)
497 VALUES (1, 'link/secret.jpg', 'secret.jpg', 'hash', 6, TRUE)",
498 [],
499 )
500 .unwrap();
501 conn.execute(
502 "INSERT INTO trash (photo_id, original_path) VALUES (1, 'link/secret.jpg')",
503 [],
504 )
505 .unwrap();
506
507 let result = TrashService::permanent_delete(&conn, &[1], temp.path()).unwrap();
508
509 assert_eq!(result.files_deleted, 0);
510 assert_eq!(result.db_records_deleted, 0);
511 assert!(!result.errors.is_empty());
512 assert!(outside_file.exists());
513 let count: i64 = conn
514 .query_row("SELECT COUNT(*) FROM photos WHERE id = 1", [], |row| {
515 row.get(0)
516 })
517 .unwrap();
518 assert_eq!(count, 1);
519 }
520
521 #[test]
522 fn trash_and_restore_refresh_face_cluster_stats() {
523 let conn = Connection::open_in_memory().unwrap();
524 create_schema(&conn).unwrap();
525 conn.execute(
526 "INSERT INTO photos (id, file_path, file_name, file_hash, file_size)
527 VALUES (1, 'one.jpg', 'one.jpg', 'h1', 8),
528 (2, 'two.jpg', 'two.jpg', 'h2', 8)",
529 [],
530 )
531 .unwrap();
532 conn.execute(
533 "INSERT INTO face_clusters (id, face_count, photo_count)
534 VALUES (10, 2, 2)",
535 [],
536 )
537 .unwrap();
538 conn.execute(
539 "INSERT INTO faces
540 (id, photo_id, bbox_x, bbox_y, bbox_width, bbox_height, embedding, cluster_id, confidence)
541 VALUES
542 (1, 1, 0.1, 0.1, 0.2, 0.2, zeroblob(16), 10, 0.5),
543 (2, 2, 0.1, 0.1, 0.2, 0.2, zeroblob(16), 10, 0.9)",
544 [],
545 )
546 .unwrap();
547 conn.execute(
548 "UPDATE face_clusters SET representative_face_id = 2 WHERE id = 10",
549 [],
550 )
551 .unwrap();
552
553 assert_eq!(TrashService::trash_photos(&conn, &[2]).unwrap(), 1);
554 let after_trash: (i64, i64, i64) = conn
555 .query_row(
556 "SELECT face_count, photo_count, representative_face_id FROM face_clusters WHERE id = 10",
557 [],
558 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
559 )
560 .unwrap();
561 assert_eq!(after_trash, (1, 1, 1));
562
563 assert_eq!(TrashService::restore_photos(&conn, &[2]).unwrap(), 1);
564 let after_restore: (i64, i64, i64) = conn
565 .query_row(
566 "SELECT face_count, photo_count, representative_face_id FROM face_clusters WHERE id = 10",
567 [],
568 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
569 )
570 .unwrap();
571 assert_eq!(after_restore, (2, 2, 2));
572 }
573}