Skip to main content

smriti/services/
insights.rs

1//! Insights Dashboard — compute aggregate statistics from the photo library.
2//!
3//! `compute()` runs ~12 SQL queries against the photos/faces/albums tables
4//! and returns an `InsightsData` struct with everything the view needs.
5
6use std::collections::HashMap;
7
8use rusqlite::{params, Connection, Result as SqliteResult};
9
10/// A person stat row for the top-people section.
11#[derive(Debug, Clone)]
12pub struct PersonStat {
13    pub cluster_id: i64,
14    pub name: String,
15    pub photo_count: i64,
16    /// Representative face ID (used to locate the face crop thumbnail).
17    pub face_id: Option<i64>,
18    /// Resolved absolute path to the face crop image (populated post-query).
19    pub face_crop_path: Option<String>,
20}
21
22/// A location stat row for the top-locations section.
23#[derive(Debug, Clone)]
24pub struct LocationStat {
25    pub city: String,
26    pub country: String,
27    pub photo_count: i64,
28}
29
30/// A country stat row for the top-countries section.
31#[derive(Debug, Clone)]
32pub struct CountryStat {
33    pub country: String,
34    pub photo_count: i64,
35}
36
37/// A camera stat row for the camera-breakdown section.
38#[derive(Debug, Clone)]
39pub struct CameraStat {
40    pub camera: String,
41    pub photo_count: i64,
42}
43
44/// All data needed by the Insights dashboard view. Boxed in the message
45/// because it is large.
46#[derive(Debug, Clone)]
47pub struct InsightsData {
48    pub total_photos: i64,
49    pub date_range_start: Option<String>,
50    pub date_range_end: Option<String>,
51    pub people_count: i64,
52    pub album_count: i64,
53    pub country_count: i64,
54    pub city_count: i64,
55    /// How many photos in scope have GPS coordinates. Lets the view tell
56    /// "no GPS data yet" apart from "GPS data but no geocoder result".
57    pub photos_with_gps: i64,
58    pub hero_photo_id: Option<i64>,
59    pub hero_thumbnail_path: Option<String>,
60    /// Day-level photo counts for the heatmap: "YYYY-MM-DD" -> count.
61    pub heatmap: HashMap<String, i64>,
62    /// The year the heatmap covers.
63    pub heatmap_year: i32,
64    /// Month-level counts for every year in the library: "YYYY-MM" -> count.
65    /// Not filtered by `year` — the share card shows the whole library, not
66    /// one year's days, so this is always all-time.
67    pub months_by_year: HashMap<String, i64>,
68    /// Monthly photo counts (index 0 = January, 11 = December).
69    pub monthly_counts: [i64; 12],
70    pub top_people: Vec<PersonStat>,
71    pub top_locations: Vec<LocationStat>,
72    pub top_countries: Vec<CountryStat>,
73    pub top_cameras: Vec<CameraStat>,
74    /// Distinct years present in the library (descending).
75    pub available_years: Vec<i32>,
76}
77
78/// Build a year filter clause. When `year` is Some, returns
79/// `" AND strftime('%Y', date_taken) = 'YYYY'"`. Otherwise empty.
80fn year_clause(year: Option<i32>) -> String {
81    match year {
82        Some(y) => format!(" AND strftime('%Y', date_taken) = '{}'", y),
83        None => String::new(),
84    }
85}
86
87fn normalized_datetime_sql(column: &str) -> String {
88    format!(
89        "CASE WHEN instr({0}, 'T') > 0 THEN replace(substr({0}, 1, 19), 'T', ' ') ELSE substr({0}, 1, 19) END",
90        column
91    )
92}
93
94/// Compute all insights data. Designed to run inside `spawn_blocking`.
95pub fn compute(conn: &Connection, year: Option<i32>) -> SqliteResult<InsightsData> {
96    let _legacy = year_clause(year);
97    let dt = normalized_datetime_sql("date_taken");
98    let yc = match year {
99        Some(y) => format!(" AND strftime('%Y', {}) = '{}'", dt, y),
100        None => String::new(),
101    };
102
103    // 1+2. Total photos + min/max date — collapsed into a single
104    // SELECT. Three round-trips → one. The aggregations all share
105    // the same FROM / WHERE so SQLite can do them in one scan.
106    let (total_photos, date_range_start, date_range_end): (i64, Option<String>, Option<String>) =
107        conn.query_row(
108            &format!(
109                "SELECT COUNT(*),
110                        MIN(CASE WHEN date_taken IS NOT NULL THEN {dt} END),
111                        MAX(CASE WHEN date_taken IS NOT NULL THEN {dt} END)
112                 FROM photos
113                 WHERE is_trashed = FALSE{yc}",
114                dt = dt,
115                yc = yc
116            ),
117            [],
118            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
119        )?;
120
121    // 3. People count — distinct named clusters that have photos in scope
122    let people_count: i64 = conn.query_row(
123        &format!(
124            "SELECT COUNT(DISTINCT fc.id)
125             FROM face_clusters fc
126             JOIN faces f ON f.cluster_id = fc.id
127             JOIN photos p ON p.id = f.photo_id
128             WHERE fc.name IS NOT NULL
129               AND p.is_trashed = FALSE{}",
130            yc.replace(&dt, &normalized_datetime_sql("p.date_taken"))
131        ),
132        [],
133        |row| row.get(0),
134    )?;
135
136    // 4. Album count — distinct albums that have photos in scope
137    let album_count: i64 = conn.query_row(
138        &format!(
139            "SELECT COUNT(DISTINCT a.id)
140             FROM albums a
141             JOIN album_photos ap ON ap.album_id = a.id
142             JOIN photos p ON p.id = ap.photo_id
143             WHERE p.is_trashed = FALSE{}",
144            yc.replace(&dt, &normalized_datetime_sql("p.date_taken"))
145        ),
146        [],
147        |row| row.get(0),
148    )?;
149
150    // 5. Country + city counts + GPS-tagged count (one query, three aggs).
151    let (country_count, city_count, photos_with_gps): (i64, i64, i64) = conn.query_row(
152        &format!(
153            "SELECT
154                COUNT(DISTINCT CASE WHEN location_country IS NOT NULL AND location_country != ''
155                                    THEN location_country END),
156                COUNT(DISTINCT CASE WHEN location_city IS NOT NULL AND location_city != ''
157                                    THEN location_city || char(31) || COALESCE(location_country, '') END),
158                SUM(CASE WHEN gps_latitude IS NOT NULL AND gps_longitude IS NOT NULL THEN 1 ELSE 0 END)
159             FROM photos
160             WHERE is_trashed = FALSE{}",
161            yc
162        ),
163        [],
164        |row| Ok((row.get(0)?, row.get(1)?, row.get::<_, Option<i64>>(2)?.unwrap_or(0))),
165    )?;
166
167    // 6. Hero photo — prefer photos with faces, landscape orientation, newest
168    let hero_photo_id: Option<i64> = conn
169        .query_row(
170            &format!(
171                "SELECT p.id
172                 FROM photos p
173                 LEFT JOIN faces f ON f.photo_id = p.id
174                 WHERE p.is_trashed = FALSE
175                   AND p.thumbnail_path IS NOT NULL{}
176                 GROUP BY p.id
177                 ORDER BY (COUNT(f.id) > 0) DESC,
178                          (COALESCE(p.width, 0) > COALESCE(p.height, 0)) DESC,
179                           CASE WHEN instr(p.date_taken, 'T') > 0 THEN replace(substr(p.date_taken, 1, 19), 'T', ' ') ELSE substr(p.date_taken, 1, 19) END DESC
180                  LIMIT 1",
181                yc
182            ),
183            [],
184            |row| row.get(0),
185        )
186        .ok();
187
188    // Determine heatmap year: if a specific year is selected, use it;
189    // otherwise use the most recent year with photos.
190    let heatmap_year: i32 = if let Some(y) = year {
191        y
192    } else {
193        conn.query_row(
194            "SELECT CAST(strftime('%Y', MAX(CASE WHEN instr(date_taken, 'T') > 0 THEN replace(substr(date_taken, 1, 19), 'T', ' ') ELSE substr(date_taken, 1, 19) END)) AS INTEGER)
195             FROM photos
196             WHERE is_trashed = FALSE AND date_taken IS NOT NULL",
197            [],
198            |row| row.get::<_, Option<i32>>(0),
199        )
200        .ok()
201        .flatten()
202        .unwrap_or(chrono::Local::now().date_naive().year())
203    };
204
205    // 7. Heatmap day counts for the selected year
206    let mut heatmap = HashMap::new();
207    {
208        let mut stmt = conn.prepare(
209            "SELECT DATE(CASE WHEN instr(date_taken, 'T') > 0 THEN replace(substr(date_taken, 1, 19), 'T', ' ') ELSE substr(date_taken, 1, 19) END) AS d, COUNT(*) AS c
210             FROM photos
211             WHERE is_trashed = FALSE
212               AND date_taken IS NOT NULL
213                AND strftime('%Y', CASE WHEN instr(date_taken, 'T') > 0 THEN replace(substr(date_taken, 1, 19), 'T', ' ') ELSE substr(date_taken, 1, 19) END) = ?1
214              GROUP BY d",
215        )?;
216        let rows = stmt.query_map(params![heatmap_year.to_string()], |row| {
217            Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
218        })?;
219        for (day, count) in rows.flatten() {
220            heatmap.insert(day, count);
221        }
222    }
223
224    // 8. Monthly counts (for the selected year if any, otherwise all time)
225    let mut monthly_counts = [0i64; 12];
226    {
227        let mut stmt = conn.prepare(&format!(
228            "SELECT CAST(strftime('%m', CASE WHEN instr(date_taken, 'T') > 0 THEN replace(substr(date_taken, 1, 19), 'T', ' ') ELSE substr(date_taken, 1, 19) END) AS INTEGER) AS m, COUNT(*) AS c
229             FROM photos
230             WHERE is_trashed = FALSE
231               AND date_taken IS NOT NULL{}
232             GROUP BY m",
233            yc
234        ))?;
235        let rows = stmt.query_map([], |row| Ok((row.get::<_, i32>(0)?, row.get::<_, i64>(1)?)))?;
236        for (month, count) in rows.flatten() {
237            if (1..=12).contains(&month) {
238                monthly_counts[(month - 1) as usize] = count;
239            }
240        }
241    }
242
243    // 9. Top 5 people (named clusters only, by photo count)
244    let mut top_people = Vec::new();
245    {
246        let mut stmt = conn.prepare(&format!(
247            "SELECT fc.id, fc.name, COUNT(DISTINCT f.photo_id) AS cnt, fc.representative_face_id
248             FROM face_clusters fc
249             JOIN faces f ON f.cluster_id = fc.id
250             JOIN photos p ON p.id = f.photo_id
251             WHERE fc.name IS NOT NULL
252               AND p.is_trashed = FALSE{}
253             GROUP BY fc.id
254             ORDER BY cnt DESC
255             LIMIT 10",
256            yc.replace(&dt, &normalized_datetime_sql("p.date_taken"))
257        ))?;
258        let rows = stmt.query_map([], |row| {
259            Ok(PersonStat {
260                cluster_id: row.get(0)?,
261                name: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
262                photo_count: row.get(2)?,
263                face_id: row.get(3)?,
264                face_crop_path: None, // resolved later
265            })
266        })?;
267        for stat in rows.flatten() {
268            top_people.push(stat);
269        }
270    }
271
272    // 10. Top cities (by photo count)
273    let mut top_locations = Vec::new();
274    {
275        let mut stmt = conn.prepare(&format!(
276            "SELECT location_city, location_country, COUNT(*) AS cnt
277             FROM photos
278             WHERE is_trashed = FALSE
279               AND location_city IS NOT NULL
280               AND location_city != ''{}
281             GROUP BY location_city, location_country
282             ORDER BY cnt DESC
283             LIMIT 30",
284            yc
285        ))?;
286        let rows = stmt.query_map([], |row| {
287            Ok(LocationStat {
288                city: row.get::<_, Option<String>>(0)?.unwrap_or_default(),
289                country: row.get::<_, Option<String>>(1)?.unwrap_or_default(),
290                photo_count: row.get(2)?,
291            })
292        })?;
293        for stat in rows.flatten() {
294            top_locations.push(stat);
295        }
296    }
297
298    // 10b. Top countries (by photo count). Separate aggregation so a
299    // country with photos spread across many cities still surfaces.
300    let mut top_countries = Vec::new();
301    {
302        let mut stmt = conn.prepare(&format!(
303            "SELECT location_country, COUNT(*) AS cnt
304             FROM photos
305             WHERE is_trashed = FALSE
306               AND location_country IS NOT NULL
307               AND location_country != ''{}
308             GROUP BY location_country
309             ORDER BY cnt DESC
310             LIMIT 20",
311            yc
312        ))?;
313        let rows = stmt.query_map([], |row| {
314            Ok(CountryStat {
315                country: row.get::<_, Option<String>>(0)?.unwrap_or_default(),
316                photo_count: row.get(1)?,
317            })
318        })?;
319        for stat in rows.flatten() {
320            top_countries.push(stat);
321        }
322    }
323
324    // 11. Top cameras. Group raw EXIF make/model first, then collapse
325    // known codenames into user-facing names.
326    let mut top_cameras = Vec::new();
327    {
328        let mut stmt = conn.prepare(&format!(
329            "SELECT NULLIF(TRIM(camera_make), '') AS make,
330                    NULLIF(TRIM(camera_model), '') AS model,
331                    COUNT(*) AS cnt
332             FROM photos
333             WHERE is_trashed = FALSE
334               AND (NULLIF(TRIM(camera_make), '') IS NOT NULL
335                    OR NULLIF(TRIM(camera_model), '') IS NOT NULL){}
336             GROUP BY make, model
337             ORDER BY cnt DESC
338             LIMIT 100",
339            yc
340        ))?;
341        let rows = stmt.query_map([], |row| {
342            Ok((
343                row.get::<_, Option<String>>(0)?,
344                row.get::<_, Option<String>>(1)?,
345                row.get::<_, i64>(2)?,
346            ))
347        })?;
348        let mut grouped: HashMap<String, i64> = HashMap::new();
349        for (make, model, count) in rows.flatten() {
350            if let Some(name) = crate::services::camera_names::friendly_camera_name(
351                make.as_deref(),
352                model.as_deref(),
353            ) {
354                *grouped.entry(name).or_insert(0) += count;
355            }
356        }
357        let mut cameras: Vec<CameraStat> = grouped
358            .into_iter()
359            .map(|(camera, photo_count)| CameraStat {
360                camera,
361                photo_count,
362            })
363            .collect();
364        cameras.sort_by(|a, b| {
365            b.photo_count
366                .cmp(&a.photo_count)
367                .then(a.camera.cmp(&b.camera))
368        });
369        top_cameras.extend(cameras.into_iter().take(3));
370    }
371
372    // 8b. Month counts for every year. One grouped scan; the card needs the
373    // whole library's shape, not a single year.
374    let mut months_by_year = HashMap::new();
375    {
376        let mut stmt = conn.prepare(&format!(
377            "SELECT strftime('%Y-%m', {dt}) AS ym, COUNT(*) AS c
378             FROM photos
379             WHERE is_trashed = FALSE
380               AND date_taken IS NOT NULL
381             GROUP BY ym"
382        ))?;
383        let rows = stmt.query_map([], |row| {
384            Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
385        })?;
386        for (month, count) in rows.flatten() {
387            months_by_year.insert(month, count);
388        }
389    }
390
391    // 12. Available years (descending)
392    let mut available_years = Vec::new();
393    {
394        let mut stmt = conn.prepare(
395            "SELECT DISTINCT CAST(strftime('%Y', CASE WHEN instr(date_taken, 'T') > 0 THEN replace(substr(date_taken, 1, 19), 'T', ' ') ELSE substr(date_taken, 1, 19) END) AS INTEGER) AS y
396             FROM photos
397             WHERE is_trashed = FALSE AND date_taken IS NOT NULL
398             ORDER BY y DESC",
399        )?;
400        let rows = stmt.query_map([], |row| row.get::<_, i32>(0))?;
401        for y in rows.flatten() {
402            available_years.push(y);
403        }
404    }
405
406    Ok(InsightsData {
407        total_photos,
408        date_range_start,
409        date_range_end,
410        people_count,
411        album_count,
412        country_count,
413        city_count,
414        photos_with_gps,
415        hero_photo_id,
416        hero_thumbnail_path: None, // resolved by the loader
417        heatmap,
418        heatmap_year,
419        months_by_year,
420        monthly_counts,
421        top_people,
422        top_locations,
423        top_countries,
424        top_cameras,
425        available_years,
426    })
427}
428
429/// Cheap threshold probe for milestone checks.
430///
431/// `compute` runs roughly a dozen grouped scans; milestones only need
432/// five counters, so the store can probe first and pay for the full
433/// aggregation only when a threshold is actually crossed.
434#[derive(Debug, Clone)]
435pub struct MilestoneProbe {
436    pub total_photos: i64,
437    pub first_year: Option<i64>,
438    pub last_year: Option<i64>,
439    pub people_count: i64,
440    pub city_count: i64,
441}
442
443pub fn compute_milestone_probe(conn: &Connection) -> SqliteResult<MilestoneProbe> {
444    let total_photos: i64 = conn.query_row(
445        "SELECT COUNT(*) FROM photos WHERE is_trashed = FALSE",
446        [],
447        |row| row.get(0),
448    )?;
449    let (first_date, last_date): (Option<String>, Option<String>) = conn.query_row(
450        "SELECT MIN(date_taken), MAX(date_taken)
451         FROM photos
452         WHERE is_trashed = FALSE AND date_taken IS NOT NULL",
453        [],
454        |row| Ok((row.get(0)?, row.get(1)?)),
455    )?;
456    let year_of =
457        |value: Option<String>| -> Option<i64> { value.and_then(|s| s.get(0..4)?.parse().ok()) };
458    let people_count: i64 = conn.query_row(
459        "SELECT COUNT(DISTINCT fc.id)
460         FROM face_clusters fc
461         JOIN faces f ON f.cluster_id = fc.id
462         JOIN photos p ON p.id = f.photo_id
463         WHERE fc.name IS NOT NULL
464           AND p.is_trashed = FALSE",
465        [],
466        |row| row.get(0),
467    )?;
468    let city_count: i64 = conn.query_row(
469        "SELECT COUNT(DISTINCT CASE WHEN location_city IS NOT NULL AND location_city != ''
470                    THEN location_city || char(31) || COALESCE(location_country, '') END)
471         FROM photos
472         WHERE is_trashed = FALSE",
473        [],
474        |row| row.get(0),
475    )?;
476    Ok(MilestoneProbe {
477        total_photos,
478        first_year: year_of(first_date),
479        last_year: year_of(last_date),
480        people_count,
481        city_count,
482    })
483}
484
485use chrono::Datelike;
486
487#[cfg(test)]
488mod tests {
489    use super::compute;
490    use crate::db::create_schema;
491    use rusqlite::Connection;
492
493    #[test]
494    fn top_locations_keep_same_city_in_different_countries_separate() {
495        let conn = Connection::open_in_memory().unwrap();
496        create_schema(&conn).unwrap();
497        conn.execute(
498            "INSERT INTO photos
499                (id, file_path, file_name, file_hash, file_size, date_taken, location_city, location_country, is_trashed)
500             VALUES
501                (1, 'a.jpg', 'a.jpg', 'hash-a', 10, '2026-01-02T00:00:00Z', 'Springfield', 'USA', 0),
502                (2, 'b.jpg', 'b.jpg', 'hash-b', 10, '2026-01-01T00:00:00Z', 'Springfield', 'Canada', 0)",
503            [],
504        )
505        .unwrap();
506
507        let data = compute(&conn, None).unwrap();
508        assert_eq!(data.city_count, 2);
509        let springfields = data
510            .top_locations
511            .iter()
512            .filter(|location| location.city == "Springfield")
513            .collect::<Vec<_>>();
514
515        assert_eq!(springfields.len(), 2);
516        assert!(springfields
517            .iter()
518            .any(|location| location.country == "USA"));
519        assert!(springfields
520            .iter()
521            .any(|location| location.country == "Canada"));
522    }
523}