1use crate::services::story;
7use std::collections::{HashMap, HashSet};
8use std::hash::{DefaultHasher, Hash, Hasher};
9use std::sync::atomic::{AtomicBool, Ordering};
10
11use chrono::NaiveDate;
12use rusqlite::{params, Connection};
13
14use crate::db::album_suggestion_repo::AlbumSuggestionRepo;
15
16#[derive(Debug, Clone)]
18pub struct DetectedSuggestion {
19 pub kind: String,
20 pub title: String,
21 pub photo_ids: Vec<i64>,
22 pub cover_photo_id: Option<i64>,
23 pub fingerprint: String,
24}
25
26#[allow(dead_code)]
27#[derive(Debug, Clone, Default)]
28pub struct SuggestionDiagnostics {
29 pub total_photos_with_date: i64,
30 pub photos_with_city: i64,
31 pub photos_with_gps: i64,
36 pub home_city: Option<String>,
37 pub trip_rows: usize,
38 pub trip_gate_duration_rejected: usize,
39 pub trip_gate_photo_count_rejected: usize,
40 pub trip_gate_rarity_rejected: usize,
41 pub trip_gate_home_distance_rejected: usize,
42 pub trip_gate_album_overlap_rejected: usize,
43 pub trip_candidates_passed: usize,
44 pub event_windows: usize,
45 pub event_gate_photo_count_rejected: usize,
46 pub event_gate_trip_overlap_rejected: usize,
47 pub event_gate_signal_rejected: usize,
48 pub event_gate_album_overlap_rejected: usize,
49 pub event_candidates_passed: usize,
50 pub persisted_new: usize,
51 pub skipped_existing_fingerprint: usize,
52}
53
54pub fn haversine_km(lat1: f64, lng1: f64, lat2: f64, lng2: f64) -> f64 {
60 let r = 6371.0; let dlat = (lat2 - lat1).to_radians();
62 let dlng = ((lng2 - lng1 + 540.0).rem_euclid(360.0) - 180.0).to_radians();
63 let a = (dlat / 2.0).sin().powi(2)
64 + lat1.to_radians().cos() * lat2.to_radians().cos() * (dlng / 2.0).sin().powi(2);
65 let c = 2.0 * a.sqrt().asin();
66 r * c
67}
68
69fn parse_date_prefix(date_str: &str) -> Option<NaiveDate> {
70 NaiveDate::parse_from_str(date_str.get(..10)?, "%Y-%m-%d").ok()
71}
72
73pub(crate) const KNOWN_PEOPLE_CTE: &str = "known AS MATERIALIZED (
77 SELECT f.cluster_id FROM faces f
78 JOIN photos p ON p.id = f.photo_id
79 JOIN face_clusters c ON c.id = f.cluster_id
80 WHERE p.is_trashed = FALSE AND f.user_confirmed >= 0
81 GROUP BY f.cluster_id
82 HAVING MAX(COALESCE(TRIM(c.name), '') != '') = 1
83 OR COUNT(DISTINCT substr(p.date_taken, 1, 10)) >= 3)";
84
85const SAME_MOMENT_OVERLAP: f64 = 0.5;
88
89fn overlaps(a: &HashSet<i64>, b: &[i64]) -> bool {
90 let shared = b.iter().filter(|id| a.contains(id)).count();
91 let smaller = a.len().min(b.len()).max(1);
92 shared as f64 / smaller as f64 >= SAME_MOMENT_OVERLAP
93}
94
95pub fn compute_fingerprint(photo_ids: &[i64]) -> String {
98 let mut sorted = photo_ids.to_vec();
99 sorted.sort_unstable();
100 let mut hasher = DefaultHasher::new();
101 sorted.hash(&mut hasher);
102 format!("{:016x}", hasher.finish())
103}
104
105pub fn pick_cover(conn: &Connection, photo_ids: &[i64]) -> Option<i64> {
109 if photo_ids.is_empty() {
110 return None;
111 }
112
113 let placeholders: Vec<String> = photo_ids.iter().map(|_| "?".to_string()).collect();
115 let in_clause = placeholders.join(",");
116
117 let sql = format!(
118 r#"SELECT p.id FROM photos p
119 LEFT JOIN faces f ON p.id = f.photo_id
120 WHERE p.id IN ({})
121 AND p.is_trashed = FALSE
122 GROUP BY p.id
123 ORDER BY
124 p.media_type = 'photo' DESC,
125 p.is_favorite DESC,
126 COALESCE((
127 SELECT MAX(psm.quality_score)
128 FROM photo_stack_members psm
129 WHERE psm.photo_id = p.id
130 ), 0) DESC,
131 COUNT(f.id) > 0 DESC,
132 p.width > p.height DESC,
133 p.date_taken DESC
134 LIMIT 1"#,
135 in_clause,
136 );
137
138 let mut stmt = conn.prepare(&sql).ok()?;
139 let params: Vec<rusqlite::types::Value> = photo_ids
140 .iter()
141 .map(|id| rusqlite::types::Value::Integer(*id))
142 .collect();
143 let param_refs: Vec<&dyn rusqlite::types::ToSql> = params
144 .iter()
145 .map(|v| v as &dyn rusqlite::types::ToSql)
146 .collect();
147 stmt.query_row(&*param_refs, |row| row.get::<_, i64>(0))
148 .ok()
149}
150
151static HOME_OVERRIDE: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
160
161pub fn set_home_override(city: Option<String>) {
162 *HOME_OVERRIDE.write().unwrap_or_else(|e| e.into_inner()) =
163 city.filter(|c| !c.trim().is_empty());
164}
165
166pub fn home_override() -> Option<String> {
167 HOME_OVERRIDE
168 .read()
169 .unwrap_or_else(|e| e.into_inner())
170 .clone()
171}
172
173pub fn home(conn: &Connection) -> Option<(String, String, f64, f64)> {
176 detect_home_city(conn, home_override().as_deref())
177}
178
179pub fn detect_home_city(
180 conn: &Connection,
181 override_city: Option<&str>,
182) -> Option<(String, String, f64, f64)> {
183 if let Some(city_name) = override_city {
185 if !city_name.trim().is_empty() {
186 let result: Option<(String, String, f64, f64)> = conn
187 .query_row(
188 r#"SELECT location_city, COALESCE(location_country,''),
189 AVG(gps_latitude), AVG(gps_longitude)
190 FROM photos
191 WHERE location_city = ?1
192 AND gps_latitude IS NOT NULL
193 AND is_trashed = FALSE
194 GROUP BY location_city, COALESCE(location_country,'')
195 ORDER BY COUNT(DISTINCT strftime('%Y-%W', date_taken)) DESC
196 LIMIT 1"#,
197 params![city_name.trim()],
198 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
199 )
200 .ok();
201 if result.is_some() {
202 return result;
203 }
204 }
205 }
206
207 conn.query_row(
209 r#"SELECT location_city, COALESCE(location_country,''),
210 AVG(gps_latitude), AVG(gps_longitude)
211 FROM photos
212 WHERE location_city IS NOT NULL
213 AND gps_latitude IS NOT NULL
214 AND is_trashed = FALSE
215 GROUP BY location_city, COALESCE(location_country,'')
216 ORDER BY COUNT(DISTINCT strftime('%Y-%W', date_taken)) DESC
217 LIMIT 1"#,
218 [],
219 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
220 )
221 .ok()
222}
223
224#[derive(Debug, Clone)]
229struct TripPhoto {
230 id: i64,
231 city: String,
232 country: String,
233 date: NaiveDate,
234 people: HashSet<i64>,
235}
236
237#[derive(Debug, Default)]
238struct TripSpan {
239 start: Option<NaiveDate>,
240 end: Option<NaiveDate>,
241 located_photo_ids: Vec<i64>,
242 stops: Vec<(String, String)>,
243 people: HashSet<i64>,
244}
245
246impl TripSpan {
247 fn push(&mut self, photo: &TripPhoto) {
248 self.start.get_or_insert(photo.date);
249 self.end = Some(photo.date);
250 self.located_photo_ids.push(photo.id);
251 self.people.extend(photo.people.iter().copied());
252 let stop = (photo.city.clone(), photo.country.clone());
253 if self.stops.last() != Some(&stop) {
254 self.stops.push(stop);
255 }
256 }
257
258 fn is_empty(&self) -> bool {
259 self.located_photo_ids.is_empty()
260 }
261}
262
263pub fn detect_trips(
272 conn: &Connection,
273 home: Option<&(String, String, f64, f64)>,
274) -> Vec<DetectedSuggestion> {
275 let rows: Vec<TripPhoto> = {
276 let mut stmt = match conn.prepare(
277 r#"SELECT p.id, p.location_city, COALESCE(p.location_country,''), p.date_taken,
278 (SELECT GROUP_CONCAT(DISTINCT f.cluster_id)
279 FROM faces f
280 WHERE f.photo_id = p.id AND f.cluster_id IS NOT NULL)
281 FROM photos p
282 WHERE p.location_city IS NOT NULL AND p.location_city != ''
283 AND p.date_taken IS NOT NULL
284 AND p.is_trashed = FALSE
285 ORDER BY p.date_taken, p.id"#,
286 ) {
287 Ok(s) => s,
288 Err(_) => return Vec::new(),
289 };
290 stmt.query_map([], |row| {
291 Ok((
292 row.get::<_, i64>(0)?,
293 row.get::<_, String>(1)?,
294 row.get::<_, String>(2)?,
295 row.get::<_, String>(3)?,
296 row.get::<_, Option<String>>(4)?,
297 ))
298 })
299 .and_then(|iter| iter.collect::<rusqlite::Result<Vec<_>>>())
300 .unwrap_or_else(|e| {
301 tracing::warn!("album trip detection skipped: failed reading city rows: {e}");
302 Vec::new()
303 })
304 .into_iter()
305 .filter_map(|(id, city, country, raw_date, people_csv)| {
306 Some(TripPhoto {
307 id,
308 city,
309 country,
310 date: parse_date_prefix(&raw_date)?,
311 people: people_csv
312 .as_deref()
313 .unwrap_or_default()
314 .split(',')
315 .filter_map(|value| value.parse().ok())
316 .collect(),
317 })
318 })
319 .collect()
320 };
321
322 if rows.is_empty() {
323 return Vec::new();
324 }
325
326 let city_centroids: HashMap<(String, String), (f64, f64)> = {
327 let mut stmt = match conn.prepare(
328 r#"SELECT location_city, COALESCE(location_country,''), AVG(gps_latitude), AVG(gps_longitude)
329 FROM photos
330 WHERE location_city IS NOT NULL AND gps_latitude IS NOT NULL AND is_trashed = FALSE
331 GROUP BY location_city, COALESCE(location_country,'')"#,
332 ) {
333 Ok(stmt) => stmt,
334 Err(_) => return Vec::new(),
335 };
336 stmt.query_map([], |row| {
337 Ok((
338 (row.get::<_, String>(0)?, row.get::<_, String>(1)?),
339 (row.get::<_, f64>(2)?, row.get::<_, f64>(3)?),
340 ))
341 })
342 .and_then(|iter| iter.collect::<rusqlite::Result<HashMap<_, _>>>())
343 .unwrap_or_else(|e| {
344 tracing::warn!("album trip detection skipped: failed reading city centroid rows: {e}");
345 HashMap::new()
346 })
347 };
348
349 let album_photo_set: HashSet<i64> = {
350 match conn.prepare("SELECT DISTINCT photo_id FROM album_photos") {
351 Ok(mut stmt) => stmt
352 .query_map([], |row| row.get::<_, i64>(0))
353 .and_then(|iter| iter.collect::<rusqlite::Result<HashSet<_>>>())
354 .unwrap_or_else(|e| {
355 tracing::warn!(
356 "album trip detection continuing without album membership filter: {e}"
357 );
358 HashSet::new()
359 }),
360 Err(_) => HashSet::new(),
361 }
362 };
363
364 let inferred_home: Option<(String, String)> = if home.is_none() {
365 conn.query_row(
366 r#"SELECT location_city, COALESCE(location_country, '')
367 FROM photos
368 WHERE is_trashed = FALSE
369 AND location_city IS NOT NULL AND location_city != ''
370 AND date_taken IS NOT NULL
371 GROUP BY location_city, COALESCE(location_country, '')
372 ORDER BY COUNT(DISTINCT strftime('%Y-%W', date_taken)) DESC
373 LIMIT 1"#,
374 [],
375 |row| Ok((row.get(0)?, row.get(1)?)),
376 )
377 .ok()
378 } else {
379 None
380 };
381 let home_place = home.map(|h| (h.0.as_str(), h.1.as_str())).or_else(|| {
382 inferred_home
383 .as_ref()
384 .map(|(city, country)| (city.as_str(), country.as_str()))
385 });
386 let home_coords = home.map(|h| (h.2, h.3));
387 let is_home = |photo: &TripPhoto| {
388 if home_place == Some((photo.city.as_str(), photo.country.as_str())) {
389 return true;
390 }
391 let place = (photo.city.clone(), photo.country.clone());
392 matches!(
393 (home_coords, city_centroids.get(&place)),
394 (Some((hlat, hlng)), Some((clat, clng)))
395 if haversine_km(hlat, hlng, *clat, *clng) < 50.0
396 )
397 };
398
399 let mut spans = Vec::new();
400 let mut current = TripSpan::default();
401 for photo in &rows {
402 if is_home(photo) {
403 if !current.is_empty() {
404 spans.push(std::mem::take(&mut current));
405 }
406 continue;
407 }
408 if let Some(end) = current.end {
409 let gap = (photo.date - end).num_days();
410 let people_continue = !photo.people.is_disjoint(¤t.people);
411 if gap > 10 || (gap > 4 && !people_continue) {
412 spans.push(std::mem::take(&mut current));
413 }
414 }
415 current.push(photo);
416 }
417 if !current.is_empty() {
418 spans.push(current);
419 }
420
421 let mut suggestions = Vec::new();
422 for span in spans {
423 let (Some(start), Some(end)) = (span.start, span.end) else {
424 continue;
425 };
426 let duration_days = (end - start).num_days() + 1;
427 if duration_days < 3 {
428 continue;
429 }
430
431 let mut photo_ids = photos_in_date_envelope(conn, start, end);
432 if photo_ids.is_empty() {
433 photo_ids = span.located_photo_ids;
434 }
435 photo_ids.sort_unstable();
436 photo_ids.dedup();
437 if photo_ids.len() < 15 {
438 continue;
439 }
440
441 let in_album = photo_ids
442 .iter()
443 .filter(|id| album_photo_set.contains(id))
444 .count();
445 if in_album as f64 / photo_ids.len() as f64 > 0.60 {
446 continue;
447 }
448
449 let facts = story::Facts::gather_with_home(
450 conn,
451 &photo_ids,
452 home_place.map(|(city, country)| (city.to_string(), country.to_string())),
453 );
454 let title = story::trip(conn, &facts).joined();
455
456 let fp = compute_fingerprint(&photo_ids);
457 let cover = pick_cover(conn, &photo_ids);
458
459 suggestions.push(DetectedSuggestion {
460 kind: "trip".to_string(),
461 title,
462 photo_ids,
463 cover_photo_id: cover,
464 fingerprint: fp,
465 });
466 }
467
468 suggestions
469}
470
471fn photos_in_date_envelope(conn: &Connection, start: NaiveDate, end: NaiveDate) -> Vec<i64> {
472 let end_exclusive = end.succ_opt().unwrap_or(end).format("%Y-%m-%d").to_string();
473 let mut stmt = match conn.prepare(
474 r#"SELECT id
475 FROM photos
476 WHERE is_trashed = FALSE
477 AND date_taken >= ?1 AND date_taken < ?2
478 ORDER BY date_taken, id"#,
479 ) {
480 Ok(stmt) => stmt,
481 Err(_) => return Vec::new(),
482 };
483 stmt.query_map(
484 params![start.format("%Y-%m-%d").to_string(), end_exclusive],
485 |row| row.get(0),
486 )
487 .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
488 .unwrap_or_default()
489}
490
491fn curate_story_photos(conn: &Connection, photo_ids: &[i64]) -> Vec<i64> {
492 if photo_ids.is_empty() {
493 return Vec::new();
494 }
495 let mut out = Vec::new();
496 for chunk in photo_ids.chunks(900) {
497 let placeholders = (0..chunk.len()).map(|_| "?").collect::<Vec<_>>().join(",");
498 let sql = format!(
499 r#"SELECT p.id
500 FROM photos p
501 WHERE p.id IN ({placeholders})
502 AND p.is_trashed = FALSE
503 AND NOT EXISTS (
504 SELECT 1
505 FROM photo_stack_members psm
506 JOIN photo_stacks ps ON ps.id = psm.stack_id
507 WHERE psm.photo_id = p.id
508 AND ps.dismissed = FALSE
509 AND psm.is_cover = FALSE
510 )
511 ORDER BY p.date_taken, p.id"#
512 );
513 let Ok(mut stmt) = conn.prepare(&sql) else {
514 return photo_ids.to_vec();
515 };
516 let Ok(rows) = stmt.query_map(rusqlite::params_from_iter(chunk.iter().copied()), |row| {
517 row.get::<_, i64>(0)
518 }) else {
519 return photo_ids.to_vec();
520 };
521 out.extend(rows.flatten());
522 }
523 out
524}
525
526pub fn detect_events(conn: &Connection, trip_photo_ids: &HashSet<i64>) -> Vec<DetectedSuggestion> {
534 let rows: Vec<(i64, String, Option<String>, Option<i64>)> = {
536 let mut stmt = match conn.prepare(&format!(
537 r#"WITH {KNOWN_PEOPLE_CTE}
538 SELECT p.id, p.date_taken, p.location_city,
539 (SELECT f.cluster_id FROM faces f
540 WHERE f.photo_id = p.id AND f.cluster_id IN (SELECT cluster_id FROM known)
541 LIMIT 1)
542 FROM photos p
543 WHERE p.date_taken IS NOT NULL AND p.is_trashed = FALSE
544 ORDER BY p.date_taken"#,
545 )) {
546 Ok(s) => s,
547 Err(_) => return Vec::new(),
548 };
549 stmt.query_map([], |row| {
550 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
551 })
552 .and_then(|iter| iter.collect::<rusqlite::Result<Vec<_>>>())
553 .unwrap_or_else(|e| {
554 tracing::warn!("album event detection skipped: failed reading event rows: {e}");
555 Vec::new()
556 })
557 };
558
559 if rows.is_empty() {
560 return Vec::new();
561 }
562
563 let album_photo_set: HashSet<i64> = {
565 match conn.prepare("SELECT DISTINCT photo_id FROM album_photos") {
566 Ok(mut stmt) => stmt
567 .query_map([], |row| row.get::<_, i64>(0))
568 .and_then(|iter| iter.collect::<rusqlite::Result<HashSet<_>>>())
569 .unwrap_or_else(|e| {
570 tracing::warn!(
571 "album event detection continuing without album membership filter: {e}"
572 );
573 HashSet::new()
574 }),
575 Err(_) => HashSet::new(),
576 }
577 };
578
579 struct EventPhoto {
581 id: i64,
582 ts: i64, city: Option<String>,
584 cluster_id: Option<i64>,
585 }
586
587 let parsed: Vec<EventPhoto> = rows
588 .into_iter()
589 .filter_map(|(id, dt, city, cluster)| {
590 let normalized = if dt.contains('T') {
591 dt.replace('T', " ")
592 } else {
593 dt.clone()
594 };
595 let ts = chrono::NaiveDateTime::parse_from_str(
596 &normalized[..normalized.len().min(19)],
597 "%Y-%m-%d %H:%M:%S",
598 )
599 .ok()
600 .map(|ndt| ndt.and_utc().timestamp())
601 .or_else(|| {
602 parse_date_prefix(&normalized)
603 .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc().timestamp())
604 })?;
605 Some(EventPhoto {
606 id,
607 ts,
608 city,
609 cluster_id: cluster,
610 })
611 })
612 .collect();
613
614 let four_hours = 4 * 3600;
616 let mut windows: Vec<Vec<&EventPhoto>> = Vec::new();
617 let mut current_window: Vec<&EventPhoto> = Vec::new();
618
619 for photo in &parsed {
620 if let Some(last) = current_window.last() {
621 if photo.ts - last.ts > four_hours && !current_window.is_empty() {
622 windows.push(std::mem::take(&mut current_window));
623 }
624 }
625 current_window.push(photo);
626 }
627 if !current_window.is_empty() {
628 windows.push(current_window);
629 }
630
631 let mut suggestions = Vec::new();
632
633 for window in &windows {
634 if window.len() < 15 {
637 continue;
638 }
639
640 let ids: Vec<i64> = window.iter().map(|p| p.id).collect();
641
642 let in_trip = ids.iter().filter(|id| trip_photo_ids.contains(id)).count();
644 if !ids.is_empty() && in_trip as f64 / ids.len() as f64 > 0.70 {
645 continue;
646 }
647
648 let cluster_ids: HashSet<i64> = window.iter().filter_map(|p| p.cluster_id).collect();
650 let distinct_days: HashSet<i64> = window.iter().map(|p| p.ts / 86400).collect();
651 let location_days: HashSet<String> = window.iter().filter_map(|p| p.city.clone()).collect();
652
653 let has_face_signal = cluster_ids.len() >= 2;
654 let has_location_signal = !location_days.is_empty() && distinct_days.len() <= 3;
655
656 if !has_face_signal && !has_location_signal {
657 continue;
658 }
659
660 let in_album = ids.iter().filter(|id| album_photo_set.contains(id)).count();
662 if !ids.is_empty() && in_album as f64 / ids.len() as f64 > 0.60 {
663 continue;
664 }
665
666 let title = story::moment(&story::Facts::gather(conn, &ids)).joined();
667
668 let fp = compute_fingerprint(&ids);
669 let cover = pick_cover(conn, &ids);
670
671 suggestions.push(DetectedSuggestion {
672 kind: "event".to_string(),
673 title,
674 photo_ids: ids,
675 cover_photo_id: cover,
676 fingerprint: fp,
677 });
678 }
679
680 suggestions
681}
682
683pub fn detect_gatherings(
695 conn: &Connection,
696 excluded_photo_ids: &HashSet<i64>,
697) -> Vec<DetectedSuggestion> {
698 let mut stmt = match conn.prepare(&format!(
701 r#"
702 WITH {KNOWN_PEOPLE_CTE}
703 SELECT DISTINCT
704 p.id,
705 CAST(strftime('%s', p.date_taken) AS INTEGER) AS ts,
706 f.cluster_id
707 FROM photos p
708 JOIN faces f ON f.photo_id = p.id
709 WHERE p.is_trashed = FALSE
710 AND p.date_taken IS NOT NULL
711 AND f.cluster_id IN (SELECT cluster_id FROM known)
712 ORDER BY p.date_taken
713 "#,
714 )) {
715 Ok(s) => s,
716 Err(_) => return Vec::new(),
717 };
718
719 type Row = (i64, i64, i64); let rows: Vec<Row> = stmt
721 .query_map([], |row| {
722 Ok((
723 row.get::<_, i64>(0)?,
724 row.get::<_, i64>(1)?,
725 row.get::<_, i64>(2)?,
726 ))
727 })
728 .and_then(|iter| iter.collect::<rusqlite::Result<Vec<_>>>())
729 .unwrap_or_else(|e| {
730 tracing::warn!("album people-gathering detection skipped: failed reading rows: {e}");
731 Vec::new()
732 });
733
734 if rows.is_empty() {
735 return Vec::new();
736 }
737
738 let secs_per_day: i64 = 86_400;
741 let max_span_days: i64 = 2;
742
743 struct Window {
744 start_ts: i64,
745 end_ts: i64,
746 photo_ids: Vec<i64>,
747 cluster_ids: HashSet<i64>,
748 }
749
750 let mut windows: Vec<Window> = Vec::new();
751 let mut cur: Option<Window> = None;
752 let mut last_seen_photo: HashMap<i64, i64> = HashMap::new(); for (photo_id, ts, cluster_id) in &rows {
755 let ts = *ts;
756 let pid = *photo_id;
757 let cid = *cluster_id;
758 let mut new_window = false;
759 if let Some(c) = &cur {
760 if (ts - c.start_ts) <= max_span_days * secs_per_day {
762 } else {
764 new_window = true;
765 }
766 } else {
767 new_window = true;
768 }
769 if new_window {
770 if let Some(w) = cur.take() {
771 if !w.photo_ids.is_empty() {
772 windows.push(w);
773 }
774 }
775 cur = Some(Window {
776 start_ts: ts,
777 end_ts: ts,
778 photo_ids: Vec::new(),
779 cluster_ids: HashSet::new(),
780 });
781 }
782 let Some(w) = cur.as_mut() else {
783 continue;
784 };
785 w.cluster_ids.insert(cid);
786 w.end_ts = w.end_ts.max(ts);
787 let prev_ts = last_seen_photo.get(&pid).copied();
790 if prev_ts.is_none() {
791 w.photo_ids.push(pid);
792 }
793 last_seen_photo.insert(pid, ts);
794 }
795 if let Some(w) = cur.take() {
796 if !w.photo_ids.is_empty() {
797 windows.push(w);
798 }
799 }
800
801 let mut out = Vec::new();
802 for mut w in windows {
803 w.photo_ids.retain(|p| !excluded_photo_ids.contains(p));
805 if w.photo_ids.len() < 8 || w.cluster_ids.len() < 2 {
806 continue;
807 }
808
809 let title = story::gathering(&story::Facts::gather(conn, &w.photo_ids)).joined();
810
811 let cover_photo_id = pick_cover(conn, &w.photo_ids);
812 let fingerprint = compute_fingerprint(&w.photo_ids);
813
814 out.push(DetectedSuggestion {
815 kind: "gathering".to_string(),
816 title,
817 photo_ids: w.photo_ids,
818 cover_photo_id,
819 fingerprint,
820 });
821 }
822
823 out
824}
825
826pub fn detect_suggestions_with_diagnostics_cancel(
831 conn: &Connection,
832 home_city_override: Option<&str>,
833 cancel: Option<&AtomicBool>,
834) -> (Vec<DetectedSuggestion>, SuggestionDiagnostics) {
835 let mut diag = SuggestionDiagnostics {
836 total_photos_with_date: conn
837 .query_row(
838 "SELECT COUNT(*) FROM photos WHERE is_trashed = FALSE AND date_taken IS NOT NULL",
839 [],
840 |row| row.get(0),
841 )
842 .unwrap_or(0),
843 photos_with_city: conn
844 .query_row(
845 "SELECT COUNT(*) FROM photos WHERE is_trashed = FALSE AND location_city IS NOT NULL AND location_city != ''",
846 [],
847 |row| row.get(0),
848 )
849 .unwrap_or(0),
850 photos_with_gps: conn
851 .query_row(
852 "SELECT COUNT(*) FROM photos WHERE is_trashed = FALSE AND gps_latitude IS NOT NULL AND gps_longitude IS NOT NULL",
853 [],
854 |row| row.get(0),
855 )
856 .unwrap_or(0),
857 ..SuggestionDiagnostics::default()
858 };
859
860 if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
861 return (Vec::new(), diag);
862 }
863
864 let repo = AlbumSuggestionRepo::new(conn);
865 let existing_fps: HashSet<String> = repo
866 .get_all_fingerprints()
867 .unwrap_or_default()
868 .into_iter()
869 .collect();
870 let earlier = repo.photo_sets_by_kind().unwrap_or_default();
874
875 if diag.total_photos_with_date < 20 {
876 tracing::info!(
877 "suggestions: insufficient dated photos ({})",
878 diag.total_photos_with_date
879 );
880 return (Vec::new(), diag);
881 }
882
883 let home = detect_home_city(conn, home_city_override);
884 diag.home_city = home.as_ref().map(|h| h.0.clone());
885 let trips = detect_trips(conn, home.as_ref());
886 diag.trip_candidates_passed = trips.len();
887
888 if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
889 return (Vec::new(), diag);
890 }
891
892 {
894 let mut stmt = conn
895 .prepare(
896 r#"SELECT p.id, p.location_city, COALESCE(p.location_country,''), p.date_taken
897 FROM photos p
898 WHERE p.location_city IS NOT NULL
899 AND p.date_taken IS NOT NULL
900 AND p.is_trashed = FALSE
901 ORDER BY p.location_city, COALESCE(p.location_country,''), p.date_taken"#,
902 )
903 .ok();
904 if let Some(ref mut stmt) = stmt {
905 let rows: Vec<(i64, String, String, String)> = stmt
906 .query_map([], |row| {
907 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
908 })
909 .and_then(|iter| iter.collect::<rusqlite::Result<Vec<_>>>())
910 .unwrap_or_default();
911 diag.trip_rows = rows.len();
912
913 let total_weeks: i64 = conn
914 .query_row(
915 "SELECT COUNT(DISTINCT strftime('%Y-%W', date_taken)) FROM photos WHERE date_taken IS NOT NULL AND is_trashed = FALSE",
916 [],
917 |row| row.get(0),
918 )
919 .unwrap_or(1)
920 .max(1);
921 let city_weeks: HashMap<(String, String), i64> = {
922 match conn.prepare(
923 r#"SELECT location_city, COALESCE(location_country,''), COUNT(DISTINCT strftime('%Y-%W', date_taken))
924 FROM photos
925 WHERE location_city IS NOT NULL AND date_taken IS NOT NULL AND is_trashed = FALSE
926 GROUP BY location_city, COALESCE(location_country,'')"#,
927 ) {
928 Ok(mut stmt) => stmt
929 .query_map([], |row| {
930 Ok((
931 (row.get::<_, String>(0)?, row.get::<_, String>(1)?),
932 row.get::<_, i64>(2)?,
933 ))
934 })
935 .and_then(|iter| iter.collect::<rusqlite::Result<HashMap<_, _>>>())
936 .unwrap_or_default(),
937 Err(_) => HashMap::new(),
938 }
939 };
940
941 let mut spans: Vec<(String, String, NaiveDate, NaiveDate, usize)> = Vec::new();
942 let mut city = String::new();
943 let mut country = String::new();
944 let mut dates: Vec<NaiveDate> = Vec::new();
945 let mut flush = |city: &str, country: &str, dates: &mut Vec<NaiveDate>| {
946 if city.is_empty() || dates.is_empty() {
947 dates.clear();
948 return;
949 }
950 dates.sort();
951 let mut start = dates[0];
952 let mut end = dates[0];
953 let mut count = 1usize;
954 for d in dates.iter().skip(1).copied() {
955 if (d - end).num_days() > 3 {
956 spans.push((city.to_string(), country.to_string(), start, end, count));
957 start = d;
958 count = 0;
959 }
960 end = d;
961 count += 1;
962 }
963 spans.push((city.to_string(), country.to_string(), start, end, count));
964 dates.clear();
965 };
966 for (_, c, co, ds) in rows {
967 let Some(d) = parse_date_prefix(&ds) else {
968 continue;
969 };
970 if c != city || co != country {
971 flush(&city, &country, &mut dates);
972 city = c;
973 country = co;
974 }
975 dates.push(d);
976 }
977 flush(&city, &country, &mut dates);
978
979 for (city, country, start, end, count) in spans {
980 let duration_days = (end - start).num_days() + 1;
981 if duration_days < 3 {
982 diag.trip_gate_duration_rejected += 1;
983 continue;
984 }
985 if count < 15 {
986 diag.trip_gate_photo_count_rejected += 1;
987 continue;
988 }
989 let cw = city_weeks.get(&(city, country)).copied().unwrap_or(0);
990 if cw as f64 / total_weeks as f64 >= 0.10 {
991 diag.trip_gate_rarity_rejected += 1;
992 continue;
993 }
994 }
995 }
996 }
997
998 let trip_photo_ids: HashSet<i64> = trips
1000 .iter()
1001 .flat_map(|t| t.photo_ids.iter().copied())
1002 .collect();
1003
1004 let events = detect_events(conn, &trip_photo_ids);
1005 diag.event_candidates_passed = events.len();
1006
1007 if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
1008 return (Vec::new(), diag);
1009 }
1010
1011 let already_used: HashSet<i64> = trips
1015 .iter()
1016 .chain(events.iter())
1017 .flat_map(|s| s.photo_ids.iter().copied())
1018 .collect();
1019 let gatherings = detect_gatherings(conn, &already_used);
1020
1021 let mut all: Vec<DetectedSuggestion> = Vec::new();
1022 all.extend(trips);
1023 all.extend(events);
1024 all.extend(gatherings);
1025 for suggestion in &mut all {
1026 suggestion.photo_ids = curate_story_photos(conn, &suggestion.photo_ids);
1027 suggestion.cover_photo_id = pick_cover(conn, &suggestion.photo_ids);
1028 suggestion.fingerprint = compute_fingerprint(&suggestion.photo_ids);
1029 }
1030 all.retain(|suggestion| !suggestion.photo_ids.is_empty());
1031
1032 let mut persisted = Vec::new();
1034 for s in all {
1035 if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
1036 break;
1037 }
1038 let same_moment = earlier
1039 .iter()
1040 .any(|(kind, set)| *kind == s.kind && overlaps(set, &s.photo_ids));
1041 if existing_fps.contains(&s.fingerprint) || same_moment {
1042 diag.skipped_existing_fingerprint += 1;
1043 let _ = repo.retitle_pending(&s.fingerprint, &s.title);
1046 continue;
1047 }
1048 match repo.insert(
1049 &s.kind,
1050 &s.title,
1051 &s.photo_ids,
1052 s.cover_photo_id,
1053 &s.fingerprint,
1054 ) {
1055 Ok(_id) => {
1056 tracing::info!("New {} suggestion: {}", s.kind, s.title);
1057 persisted.push(s);
1058 diag.persisted_new += 1;
1059 }
1060 Err(e) => {
1061 tracing::warn!("Failed to insert suggestion: {}", e);
1062 }
1063 }
1064 }
1065
1066 let _ = repo.cleanup_old(180);
1068
1069 tracing::info!(
1070 "suggestions diagnostics: dated={}, with_city={}, home_city={:?}, trip_passed={}, event_passed={}, persisted={}, skipped_fp={}",
1071 diag.total_photos_with_date,
1072 diag.photos_with_city,
1073 diag.home_city,
1074 diag.trip_candidates_passed,
1075 diag.event_candidates_passed,
1076 diag.persisted_new,
1077 diag.skipped_existing_fingerprint
1078 );
1079
1080 (persisted, diag)
1081}
1082
1083#[cfg(test)]
1084mod tests {
1085 use super::*;
1086 use rusqlite::Connection;
1087 use std::sync::atomic::AtomicBool;
1088
1089 fn create_trip_test_schema(conn: &Connection) {
1090 conn.execute_batch(
1091 r#"
1092 CREATE TABLE photos (
1093 id INTEGER PRIMARY KEY,
1094 location_city TEXT,
1095 location_country TEXT,
1096 date_taken TEXT,
1097 gps_latitude REAL,
1098 gps_longitude REAL,
1099 is_trashed BOOLEAN DEFAULT FALSE
1100 );
1101 "#,
1102 )
1103 .unwrap();
1104 }
1105
1106 #[test]
1107 fn detect_trips_tolerates_missing_album_photos_table() {
1108 let conn = Connection::open_in_memory().unwrap();
1109 create_trip_test_schema(&conn);
1110 conn.execute_batch(
1111 r#"
1112 INSERT INTO photos
1113 (id, location_city, location_country, date_taken, gps_latitude, gps_longitude, is_trashed)
1114 VALUES
1115 (1, 'Goa', 'India', '2024-01-01T10:00:00Z', 15.2993, 74.1240, FALSE),
1116 (2, 'Goa', 'India', '2024-01-02T10:00:00Z', 15.2993, 74.1240, FALSE),
1117 (3, 'Goa', 'India', '2024-01-03T10:00:00Z', 15.2993, 74.1240, FALSE);
1118 "#,
1119 )
1120 .unwrap();
1121
1122 let suggestions = detect_trips(&conn, None);
1123 assert!(suggestions.is_empty());
1124 }
1125
1126 #[test]
1127 fn detect_trips_does_not_merge_same_city_name_across_countries() {
1128 let conn = Connection::open_in_memory().unwrap();
1129 create_trip_test_schema(&conn);
1130 let mut id = 1;
1131 for country in ["Canada", "United Kingdom"] {
1132 for day in 1..=4 {
1133 for shot in 0..2 {
1134 conn.execute(
1135 r#"INSERT INTO photos
1136 (id, location_city, location_country, date_taken, gps_latitude, gps_longitude, is_trashed)
1137 VALUES (?1, 'London', ?2, ?3, 51.5, -0.1, FALSE)"#,
1138 params![
1139 id,
1140 country,
1141 format!("2024-01-{day:02}T10:00:{shot:02}Z")
1142 ],
1143 )
1144 .unwrap();
1145 id += 1;
1146 }
1147 }
1148 }
1149 for week in 1..=20 {
1150 let date = NaiveDate::from_ymd_opt(2023, 1, 1)
1151 .unwrap()
1152 .checked_add_days(chrono::Days::new((week - 1) * 7))
1153 .unwrap();
1154 conn.execute(
1155 "INSERT INTO photos (id, date_taken, is_trashed) VALUES (?1, ?2, FALSE)",
1156 params![id, format!("{date}T00:00:00Z")],
1157 )
1158 .unwrap();
1159 id += 1;
1160 }
1161
1162 let suggestions = detect_trips(&conn, None);
1163 assert!(suggestions.is_empty());
1164 }
1165
1166 #[test]
1167 fn detect_trips_keeps_multiple_stops_and_unlocated_photos_in_one_journey() {
1168 let conn = Connection::open_in_memory().unwrap();
1169 crate::db::schema::create_schema(&conn).unwrap();
1170 let stops = [
1171 ("Jaipur", 1_u32, 4_u32, 26.9124, 75.7873),
1172 ("Jodhpur", 5, 8, 26.2389, 73.0243),
1173 ("Udaipur", 9, 12, 24.5854, 73.7125),
1174 ];
1175 let mut id = 1_i64;
1176 for (city, first_day, last_day, lat, lng) in stops {
1177 for day in first_day..=last_day {
1178 for shot in 0..2 {
1179 conn.execute(
1180 r#"INSERT INTO photos
1181 (id, file_path, file_name, file_hash, file_size, date_taken,
1182 gps_latitude, gps_longitude, location_city, location_country)
1183 VALUES (?1, ?2, ?3, ?4, 1, ?5, ?6, ?7, ?8, 'India')"#,
1184 params![
1185 id,
1186 format!("{id}.jpg"),
1187 format!("{id}.jpg"),
1188 format!("hash-{id}"),
1189 format!("2024-03-{day:02}T10:00:{shot:02}Z"),
1190 lat,
1191 lng,
1192 city,
1193 ],
1194 )
1195 .unwrap();
1196 id += 1;
1197 }
1198 }
1199 }
1200 let unlocated_id = id;
1201 conn.execute(
1202 r#"INSERT INTO photos
1203 (id, file_path, file_name, file_hash, file_size, date_taken)
1204 VALUES (?1, ?2, ?3, ?4, 1, '2024-03-06T20:00:00Z')"#,
1205 params![
1206 unlocated_id,
1207 format!("{unlocated_id}.jpg"),
1208 format!("{unlocated_id}.jpg"),
1209 format!("hash-{unlocated_id}")
1210 ],
1211 )
1212 .unwrap();
1213
1214 let home = ("Delhi".to_string(), "India".to_string(), 28.6139, 77.2090);
1215 let suggestions = detect_trips(&conn, Some(&home));
1216
1217 assert_eq!(suggestions.len(), 1);
1218 let trip = &suggestions[0];
1219 assert!(trip
1220 .title
1221 .starts_with("Jaipur, Jodhpur and Udaipur · Mar 1 – 12, 2024"));
1222 assert!(trip.photo_ids.contains(&unlocated_id));
1223 assert_eq!(trip.photo_ids.len(), 25);
1224 }
1225
1226 #[test]
1227 fn suggestion_detection_skips_short_malformed_dates() {
1228 let conn = Connection::open_in_memory().unwrap();
1229 conn.execute_batch(
1230 r#"
1231 CREATE TABLE photos (
1232 id INTEGER PRIMARY KEY,
1233 location_city TEXT,
1234 location_country TEXT,
1235 date_taken TEXT,
1236 gps_latitude REAL,
1237 gps_longitude REAL,
1238 is_trashed BOOLEAN DEFAULT FALSE
1239 );
1240 CREATE TABLE album_suggestions (
1241 id INTEGER PRIMARY KEY,
1242 kind TEXT NOT NULL,
1243 title TEXT NOT NULL,
1244 photo_ids_json TEXT NOT NULL,
1245 cover_photo_id INTEGER,
1246 fingerprint TEXT NOT NULL,
1247 status TEXT NOT NULL,
1248 seen_count INTEGER NOT NULL DEFAULT 0,
1249 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
1250 );
1251 "#,
1252 )
1253 .unwrap();
1254 for id in 1..=22 {
1255 conn.execute(
1256 r#"INSERT INTO photos
1257 (id, location_city, location_country, date_taken, gps_latitude, gps_longitude, is_trashed)
1258 VALUES (?1, 'Goa', 'India', 'bad', 15.2993, 74.1240, FALSE)"#,
1259 params![id],
1260 )
1261 .unwrap();
1262 }
1263
1264 let (suggestions, _diag) = detect_suggestions_with_diagnostics_cancel(&conn, None, None);
1265 assert!(suggestions.is_empty());
1266 }
1267
1268 #[test]
1269 fn a_changed_version_of_a_moment_counts_as_the_same_moment() {
1270 let dismissed: HashSet<i64> = (1..=20).collect();
1271 assert!(overlaps(&dismissed, &(1..=21).collect::<Vec<_>>()));
1273 assert!(overlaps(&dismissed, &(2..=20).collect::<Vec<_>>()));
1274 assert!(!overlaps(&dismissed, &(19..=40).collect::<Vec<_>>()));
1276 }
1277
1278 #[test]
1279 fn dismissals_outlive_cleanup() {
1280 let conn = Connection::open_in_memory().unwrap();
1281 crate::db::schema::create_schema(&conn).unwrap();
1282 let repo = AlbumSuggestionRepo::new(&conn);
1283 let dismissed = repo.insert("trip", "Goa", &[1, 2], None, "a").unwrap();
1284 let accepted = repo.insert("trip", "Pune", &[3, 4], None, "b").unwrap();
1285 repo.dismiss(dismissed).unwrap();
1286 repo.accept(accepted).unwrap();
1287 conn.execute("UPDATE album_suggestions SET created_at = '2000-01-01'", [])
1288 .unwrap();
1289 assert_eq!(repo.cleanup_old(180).unwrap(), 1);
1290 assert_eq!(repo.get_all_fingerprints().unwrap(), vec!["a".to_string()]);
1291 }
1292
1293 #[test]
1294 fn haversine_uses_shortest_path_across_date_line() {
1295 assert!(haversine_km(0.0, 179.9, 0.0, -179.9) < 25.0);
1296 }
1297
1298 #[test]
1299 fn cancelled_detection_persists_no_suggestions() {
1300 let conn = Connection::open_in_memory().unwrap();
1301 conn.execute_batch(
1302 r#"
1303 CREATE TABLE photos (
1304 id INTEGER PRIMARY KEY,
1305 location_city TEXT,
1306 location_country TEXT,
1307 date_taken TEXT,
1308 gps_latitude REAL,
1309 gps_longitude REAL,
1310 is_trashed BOOLEAN DEFAULT FALSE
1311 );
1312 CREATE TABLE album_suggestions (
1313 id INTEGER PRIMARY KEY,
1314 kind TEXT NOT NULL,
1315 title TEXT NOT NULL,
1316 photo_ids_json TEXT NOT NULL,
1317 cover_photo_id INTEGER,
1318 fingerprint TEXT NOT NULL,
1319 status TEXT NOT NULL,
1320 seen_count INTEGER NOT NULL DEFAULT 0,
1321 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
1322 );
1323 INSERT INTO photos
1324 (id, location_city, location_country, date_taken, gps_latitude, gps_longitude, is_trashed)
1325 VALUES
1326 (1, 'Goa', 'India', '2024-01-01T10:00:00Z', 15.2993, 74.1240, FALSE),
1327 (2, 'Goa', 'India', '2024-01-02T10:00:00Z', 15.2993, 74.1240, FALSE);
1328 "#,
1329 )
1330 .unwrap();
1331
1332 let cancel = AtomicBool::new(true);
1333 let (suggestions, _diag) =
1334 detect_suggestions_with_diagnostics_cancel(&conn, None, Some(&cancel));
1335 let count: i64 = conn
1336 .query_row("SELECT COUNT(*) FROM album_suggestions", [], |row| {
1337 row.get(0)
1338 })
1339 .unwrap();
1340
1341 assert!(suggestions.is_empty());
1342 assert_eq!(count, 0);
1343 }
1344}