1use std::collections::HashMap;
7
8use chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike, Weekday};
9use rusqlite::Connection;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Story {
14 pub title: String,
15 pub context: String,
16}
17
18pub const SEPARATOR: &str = " · ";
20
21impl Story {
22 pub fn joined(&self) -> String {
23 if self.context.is_empty() {
24 self.title.clone()
25 } else {
26 format!("{}{SEPARATOR}{}", self.title, self.context)
27 }
28 }
29}
30
31pub fn split(stored: &str) -> (&str, &str) {
33 stored.split_once(SEPARATOR).unwrap_or((stored, ""))
34}
35
36#[derive(Debug, Clone)]
37pub struct Place {
38 pub city: String,
39 pub country: String,
40 pub photos: usize,
41 pub first: NaiveDateTime,
42}
43
44#[derive(Debug, Clone, Default)]
46pub struct Facts {
47 pub start: Option<NaiveDateTime>,
48 pub end: Option<NaiveDateTime>,
49 pub places: Vec<Place>,
51 pub people: Vec<(String, usize)>,
53 pub faces: usize,
55 pub photos: usize,
56 pub latitude: Option<f64>,
57 pub home: Option<(String, String)>,
58}
59
60impl Facts {
61 pub fn gather(conn: &Connection, ids: &[i64]) -> Facts {
62 let home = crate::services::album_suggestions::home(conn)
63 .map(|(city, country, _, _)| (city, country));
64 Self::gather_with_home(conn, ids, home)
65 }
66
67 pub fn gather_with_home(
68 conn: &Connection,
69 ids: &[i64],
70 home: Option<(String, String)>,
71 ) -> Facts {
72 let mut facts = Facts {
73 home,
74 ..Facts::default()
75 };
76 let mut places: HashMap<(String, String), Place> = HashMap::new();
77 let mut latitudes = Vec::new();
78 let mut people: HashMap<String, usize> = HashMap::new();
79 for chunk in ids.chunks(900) {
80 let marks = vec!["?"; chunk.len()].join(",");
81 let sql = format!(
82 "SELECT date_taken, location_city, COALESCE(location_country, ''), gps_latitude
83 FROM photos WHERE id IN ({marks}) AND is_trashed = FALSE"
84 );
85 if let Ok(mut stmt) = conn.prepare(&sql) {
86 let rows = stmt.query_map(rusqlite::params_from_iter(chunk), |row| {
87 Ok((
88 row.get::<_, Option<String>>(0)?,
89 row.get::<_, Option<String>>(1)?,
90 row.get::<_, String>(2)?,
91 row.get::<_, Option<f64>>(3)?,
92 ))
93 });
94 for (date, city, country, lat) in rows.into_iter().flatten().flatten() {
95 facts.photos += 1;
96 let when = date.as_deref().and_then(parse_datetime);
97 if let Some(when) = when {
98 facts.start = Some(facts.start.map_or(when, |s| s.min(when)));
99 facts.end = Some(facts.end.map_or(when, |e| e.max(when)));
100 }
101 if let Some(lat) = lat {
102 latitudes.push(lat);
103 }
104 if let Some(city) = city.filter(|c| !c.trim().is_empty()) {
105 let first = when.unwrap_or_default();
106 let place =
107 places
108 .entry((city.clone(), country.clone()))
109 .or_insert(Place {
110 city,
111 country,
112 photos: 0,
113 first,
114 });
115 place.photos += 1;
116 if when.is_some() && first < place.first {
117 place.first = first;
118 }
119 }
120 }
121 }
122 let sql = format!(
125 "WITH {known}
126 SELECT fc.name, COUNT(DISTINCT f.photo_id)
127 FROM faces f JOIN face_clusters fc ON fc.id = f.cluster_id
128 WHERE f.photo_id IN ({marks})
129 AND fc.id IN (SELECT cluster_id FROM known)
130 AND NOT EXISTS (SELECT 1 FROM memory_blocks mb
131 WHERE mb.kind = 'person' AND mb.target_key = CAST(fc.id AS TEXT))
132 GROUP BY fc.id",
133 known = crate::services::album_suggestions::KNOWN_PEOPLE_CTE,
134 );
135 if let Ok(mut stmt) = conn.prepare(&sql) {
136 let rows = stmt.query_map(rusqlite::params_from_iter(chunk), |row| {
137 Ok((
138 row.get::<_, Option<String>>(0)?,
139 row.get::<_, i64>(1)? as usize,
140 ))
141 });
142 for (name, count) in rows.into_iter().flatten().flatten() {
143 facts.faces += 1;
144 if let Some(name) = name.filter(|n| !n.trim().is_empty()) {
145 *people.entry(name.trim().to_string()).or_default() += count;
146 }
147 }
148 }
149 }
150 let mut places: Vec<Place> = places.into_values().collect();
151 places.sort_by(|a, b| a.first.cmp(&b.first).then(b.photos.cmp(&a.photos)));
152 facts.places = places;
153 let mut people: Vec<(String, usize)> = people.into_iter().collect();
154 people.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
155 facts.people = people;
156 if !latitudes.is_empty() {
157 facts.latitude = Some(latitudes.iter().sum::<f64>() / latitudes.len() as f64);
158 }
159 facts
160 }
161
162 fn is_home(&self, place: &Place) -> bool {
163 self.home
164 .as_ref()
165 .is_some_and(|(city, country)| &place.city == city && &place.country == country)
166 }
167
168 pub fn away(&self) -> Vec<&Place> {
170 self.places.iter().filter(|p| !self.is_home(p)).collect()
171 }
172
173 pub fn main_place(&self) -> Option<&Place> {
175 let best = self.places.iter().max_by_key(|p| p.photos)?;
176 (best.photos * 2 >= self.photos.max(1)).then_some(best)
177 }
178
179 pub fn main_away_place(&self) -> Option<&Place> {
181 self.main_place().filter(|p| !self.is_home(p))
182 }
183
184 pub fn regulars(&self, share: f64, limit: usize) -> Vec<&str> {
186 let floor = ((self.photos as f64) * share).ceil().max(1.0) as usize;
187 self.people
188 .iter()
189 .filter(|(_, count)| *count >= floor)
190 .take(limit)
191 .map(|(name, _)| name.as_str())
192 .collect()
193 }
194
195 fn days(&self) -> i64 {
196 match (self.start, self.end) {
197 (Some(s), Some(e)) => (e.date() - s.date()).num_days() + 1,
198 _ => 1,
199 }
200 }
201}
202
203fn parse_datetime(raw: &str) -> Option<NaiveDateTime> {
204 let raw = raw.get(..19).unwrap_or(raw).replace('T', " ");
205 NaiveDateTime::parse_from_str(&raw, "%Y-%m-%d %H:%M:%S")
206 .ok()
207 .or_else(|| {
208 NaiveDate::parse_from_str(raw.get(..10)?, "%Y-%m-%d")
209 .ok()
210 .and_then(|d| d.and_hms_opt(12, 0, 0))
211 })
212}
213
214pub fn trip(conn: &Connection, facts: &Facts) -> Story {
219 let (Some(start), Some(end)) = (facts.start, facts.end) else {
220 return Story {
221 title: "A trip".into(),
222 context: String::new(),
223 };
224 };
225 let away = facts.away();
226 let stops: Vec<&Place> = if away.is_empty() {
227 facts.places.iter().collect()
228 } else {
229 away
230 };
231 let main = stops
232 .iter()
233 .copied()
234 .max_by_key(|p| p.photos)
235 .map(|p| p.city.as_str())
236 .unwrap_or("somewhere new");
237 let people = facts.regulars(0.3, 2);
238 let mut extras: Vec<String> = Vec::new();
239
240 let first_in_country = stops.first().and_then(|p| {
241 let home_country = facts.home.as_ref().map(|h| h.1.as_str());
242 (!p.country.is_empty()
243 && Some(p.country.as_str()) != home_country
244 && earlier_photos_in_country(conn, &p.country, start) == 0)
245 .then(|| p.country.clone())
246 });
247 let earlier_years = stops
248 .iter()
249 .find(|p| p.city == main)
250 .map(|p| earlier_years_in_city(conn, &p.city, &p.country, start))
251 .unwrap_or(0);
252
253 let title = if let Some(holiday) = holiday_span(start.date(), end.date()) {
254 format!("{holiday} in {main}")
255 } else if !people.is_empty() {
256 format!("{main} with {}", join(&people))
257 } else if stops.len() >= 2 {
258 route(&stops)
259 } else if let Some(country) = &first_in_country {
260 format!("First time in {country}")
261 } else if earlier_years > 0 {
262 format!("Back in {main}")
263 } else if is_weekend(start.date(), end.date()) {
264 format!("A weekend in {main}")
265 } else if let Some(season) = season(start.date(), facts.latitude) {
266 format!("{season} in {main}")
267 } else {
268 format!("{} in {main}", capitalise(&duration(facts.days())))
269 };
270
271 if let Some(country) = &first_in_country {
272 if !title.contains("First time") {
273 extras.push(format!("your first time in {country}"));
274 }
275 }
276 if earlier_years > 0 && !title.starts_with("Back in") {
277 extras.push(format!("back in {main} after {}", since(conn, main, start)));
278 }
279 extras.push(duration(facts.days()));
280 Story {
281 title,
282 context: with_extra(date_range(start.date(), end.date()), extras.first()),
283 }
284}
285
286fn route(stops: &[&Place]) -> String {
287 let countries: std::collections::HashSet<&str> = stops
288 .iter()
289 .map(|p| p.country.as_str())
290 .filter(|c| !c.is_empty())
291 .collect();
292 match stops {
293 [a, b] => format!("{} to {}", a.city, b.city),
294 [a, b, c] => format!("{}, {} and {}", a.city, b.city, c.city),
295 _ if countries.len() == 1 => format!("Across {}", countries.iter().next().unwrap()),
296 _ => format!("{} to {}", stops[0].city, stops[stops.len() - 1].city),
297 }
298}
299
300fn earlier_photos_in_country(conn: &Connection, country: &str, before: NaiveDateTime) -> i64 {
301 conn.query_row(
302 "SELECT COUNT(*) FROM photos WHERE location_country = ?1 AND date_taken < ?2 AND is_trashed = FALSE",
303 rusqlite::params![country, before.format("%Y-%m-%d").to_string()],
304 |row| row.get(0),
305 )
306 .unwrap_or(0)
307}
308
309fn earlier_years_in_city(
310 conn: &Connection,
311 city: &str,
312 country: &str,
313 before: NaiveDateTime,
314) -> i64 {
315 let cutoff = (before.date() - chrono::Duration::days(30))
318 .format("%Y-%m-%d")
319 .to_string();
320 conn.query_row(
321 "SELECT COUNT(DISTINCT strftime('%Y', date_taken)) FROM photos
322 WHERE location_city = ?1 AND COALESCE(location_country, '') = ?2
323 AND date_taken < ?3 AND is_trashed = FALSE",
324 rusqlite::params![city, country, cutoff],
325 |row| row.get(0),
326 )
327 .unwrap_or(0)
328}
329
330fn since(conn: &Connection, city: &str, before: NaiveDateTime) -> String {
332 let cutoff = (before.date() - chrono::Duration::days(30))
333 .format("%Y-%m-%d")
334 .to_string();
335 let last: Option<String> = conn
336 .query_row(
337 "SELECT MAX(date_taken) FROM photos WHERE location_city = ?1 AND date_taken < ?2 AND is_trashed = FALSE",
338 rusqlite::params![city, cutoff],
339 |row| row.get(0),
340 )
341 .ok()
342 .flatten();
343 let Some(last) = last.as_deref().and_then(parse_datetime) else {
344 return "a while".into();
345 };
346 let months = (before.year() - last.year()) * 12 + before.month() as i32 - last.month() as i32;
347 match months {
348 ..=1 => "a month".into(),
349 2..=11 => format!("{} months", number(months as i64)),
350 12..=17 => "a year".into(),
351 _ => format!("{} years", number((months / 12) as i64)),
352 }
353}
354
355pub fn moment(facts: &Facts) -> Story {
360 let Some(start) = facts.start else {
361 return Story {
362 title: "A day worth keeping".into(),
363 context: String::new(),
364 };
365 };
366 let end = facts.end.unwrap_or(start);
367 let when = format!("{} {}", weekday(start.weekday()), daypart(start.hour()));
368 let people = facts.regulars(0.25, 2);
369 let away = facts.main_away_place().map(|p| p.city.clone());
370 let at_home = facts.main_place().is_some() && away.is_none();
371
372 let title = if let Some(day) = holiday_day(start.date()) {
373 if !people.is_empty() {
374 format!("{day} with {}", join(&people))
375 } else if let Some(city) = &away {
376 format!("{day} in {city}")
377 } else if at_home {
378 format!("{day} at home")
379 } else {
380 day.to_string()
381 }
382 } else if !people.is_empty() {
383 format!("A {when} with {}", join(&people))
384 } else if let Some(city) = &away {
385 format!("A {when} in {city}")
386 } else if at_home {
387 format!("A {when} at home")
388 } else {
389 format!("A {when} worth keeping")
390 };
391 let span = (end - start).num_minutes();
392 let extra = (facts.photos >= 20 && span <= 6 * 60)
393 .then(|| format!("{} photos in {}", facts.photos, hours(span)));
394 Story {
395 title,
396 context: with_extra(date_range(start.date(), end.date()), extra.as_ref()),
397 }
398}
399
400pub fn gathering(facts: &Facts) -> Story {
403 let Some(start) = facts.start else {
404 return Story {
405 title: "A get-together".into(),
406 context: String::new(),
407 };
408 };
409 let end = facts.end.unwrap_or(start);
410 if holiday_day(start.date()).is_some() {
411 return moment(facts);
412 }
413 let named = facts.regulars(0.2, 2);
414 let others = facts.faces.saturating_sub(named.len());
415 let one_day = if end.date() == start.date() {
416 format!("one {}", weekday(start.weekday()))
417 } else if is_weekend(start.date(), end.date()) {
418 "one weekend".into()
419 } else {
420 format!("{} days", number(facts.days()))
421 };
422 let title = match (named.as_slice(), others) {
423 ([], _) => format!(
424 "{} people, {one_day}",
425 capitalise(&number(facts.faces as i64))
426 ),
427 (names, 0) => format!("{}, {one_day}", join(names)),
428 (names, 1) => format!("{} and one other", names.join(", ")),
429 (names, n) => format!("{} and {} others", names.join(", "), number(n as i64)),
430 };
431 Story {
432 title,
433 context: with_extra(
434 date_range(start.date(), end.date()),
435 Some(&format!("{} photos", facts.photos)),
436 ),
437 }
438}
439
440pub fn looking_back(base: &str, facts: &Facts) -> String {
445 if let Some(place) = facts.main_away_place() {
446 return format!("{base}, in {}", place.city);
447 }
448 match facts.regulars(0.4, 1).first() {
449 Some(name) => format!("{base}, with {name}"),
450 None => base.to_string(),
451 }
452}
453
454pub fn month_back(month: &str, year: i32, facts: &Facts) -> String {
457 if let Some(place) = facts.main_away_place() {
458 return format!("{}, {month} {year}", place.city);
459 }
460 match facts.regulars(0.4, 1).first() {
461 Some(name) => format!("{month} {year} with {name}"),
462 None => format!("{month} {year}, a look back"),
463 }
464}
465
466pub fn year_back(year: i32, facts: &Facts) -> String {
468 let mut away: Vec<&Place> = facts.away();
469 away.sort_by_key(|p| std::cmp::Reverse(p.photos));
470 let names: Vec<&str> = away.iter().take(2).map(|p| p.city.as_str()).collect();
471 match (names.as_slice(), away.len()) {
472 ([], _) => format!("Your {year}"),
473 ([one], _) => format!("{year}: home and {one}"),
474 ([a, b], 2) => format!("{year}: {a} and {b}"),
475 ([a, b], _) => format!("{year}: {a}, {b} and more"),
476 _ => format!("Your {year}"),
477 }
478}
479
480pub fn spelled(label: &str) -> String {
482 let digits: String = label.chars().take_while(|c| c.is_ascii_digit()).collect();
483 let Ok(n) = digits.parse::<i64>() else {
484 return capitalise(label);
485 };
486 let rest = &label[digits.len()..];
487 if n == 1 {
488 format!("A{rest}")
489 } else {
490 format!("{}{rest}", capitalise(&number(n)))
491 }
492}
493
494fn holiday_span(start: NaiveDate, end: NaiveDate) -> Option<&'static str> {
497 let christmas = covers(start, end, 12, 25);
498 let new_year = covers(start, end, 12, 31) || covers(start, end, 1, 1);
499 match (christmas, new_year) {
500 (true, true) => Some("The holidays"),
501 (true, false) => Some("Christmas"),
502 (false, true) => Some("New Year"),
503 _ => None,
504 }
505}
506
507fn covers(start: NaiveDate, end: NaiveDate, month: u32, day: u32) -> bool {
508 (start.year()..=end.year())
509 .any(|y| NaiveDate::from_ymd_opt(y, month, day).is_some_and(|d| d >= start && d <= end))
510}
511
512fn holiday_day(date: NaiveDate) -> Option<&'static str> {
513 match (date.month(), date.day()) {
514 (12, 24) => Some("Christmas Eve"),
515 (12, 25) => Some("Christmas Day"),
516 (12, 31) => Some("New Year's Eve"),
517 (1, 1) => Some("New Year's Day"),
518 _ => None,
519 }
520}
521
522fn is_weekend(start: NaiveDate, end: NaiveDate) -> bool {
523 let days = (end - start).num_days() + 1;
524 (2..=3).contains(&days)
525 && matches!(start.weekday(), Weekday::Fri | Weekday::Sat)
526 && matches!(end.weekday(), Weekday::Sat | Weekday::Sun | Weekday::Mon)
527}
528
529fn season(date: NaiveDate, latitude: Option<f64>) -> Option<String> {
531 let lat = latitude?;
532 if lat.abs() < 23.5 {
533 return Some(month_name(date.month()).to_string());
534 }
535 let north = [
536 "Winter", "Winter", "Spring", "Spring", "Spring", "Summer", "Summer", "Summer", "Autumn",
537 "Autumn", "Autumn", "Winter",
538 ];
539 let south = [
540 "Summer", "Summer", "Autumn", "Autumn", "Autumn", "Winter", "Winter", "Winter", "Spring",
541 "Spring", "Spring", "Summer",
542 ];
543 let table = if lat >= 0.0 { north } else { south };
544 Some(table[date.month0() as usize].to_string())
545}
546
547fn daypart(hour: u32) -> &'static str {
548 match hour {
549 5..=11 => "morning",
550 12..=16 => "afternoon",
551 17..=21 => "evening",
552 _ => "night",
553 }
554}
555
556fn weekday(day: Weekday) -> &'static str {
557 match day {
558 Weekday::Mon => "Monday",
559 Weekday::Tue => "Tuesday",
560 Weekday::Wed => "Wednesday",
561 Weekday::Thu => "Thursday",
562 Weekday::Fri => "Friday",
563 Weekday::Sat => "Saturday",
564 Weekday::Sun => "Sunday",
565 }
566}
567
568pub fn month_name(month: u32) -> &'static str {
569 [
570 "January",
571 "February",
572 "March",
573 "April",
574 "May",
575 "June",
576 "July",
577 "August",
578 "September",
579 "October",
580 "November",
581 "December",
582 ]
583 .get(month.saturating_sub(1) as usize)
584 .copied()
585 .unwrap_or("")
586}
587
588fn duration(days: i64) -> String {
589 match days {
590 ..=1 => "one day".into(),
591 2..=6 => format!("{} days", number(days)),
592 7..=10 => "a week".into(),
593 11..=17 => "two weeks".into(),
594 _ => format!("{} weeks", number((days + 3) / 7)),
595 }
596}
597
598fn hours(minutes: i64) -> String {
599 match minutes {
600 ..=59 => "under an hour".into(),
601 60..=119 => "an hour".into(),
602 _ => format!("{} hours", number(minutes / 60)),
603 }
604}
605
606fn number(n: i64) -> String {
607 const WORDS: [&str; 13] = [
608 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
609 "eleven", "twelve",
610 ];
611 WORDS
612 .get(n as usize)
613 .map(|w| w.to_string())
614 .unwrap_or_else(|| n.to_string())
615}
616
617fn capitalise(text: &str) -> String {
618 let mut chars = text.chars();
619 match chars.next() {
620 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
621 None => String::new(),
622 }
623}
624
625fn join(names: &[&str]) -> String {
626 match names {
627 [] => String::new(),
628 [one] => one.to_string(),
629 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
630 }
631}
632
633fn with_extra(base: String, extra: Option<&String>) -> String {
634 match extra {
635 Some(extra) => format!("{base} · {extra}"),
636 None => base,
637 }
638}
639
640pub fn span_label(conn: &Connection, ids: &[i64]) -> Option<String> {
643 let mut first: Option<NaiveDateTime> = None;
644 let mut last: Option<NaiveDateTime> = None;
645 for chunk in ids.chunks(900) {
646 let marks = vec!["?"; chunk.len()].join(",");
647 let sql = format!(
648 "SELECT MIN(date_taken), MAX(date_taken) FROM photos WHERE id IN ({marks}) AND is_trashed = FALSE"
649 );
650 let (lo, hi): (Option<String>, Option<String>) = conn
651 .query_row(&sql, rusqlite::params_from_iter(chunk), |row| {
652 Ok((row.get(0)?, row.get(1)?))
653 })
654 .ok()?;
655 if let Some(lo) = lo.as_deref().and_then(parse_datetime) {
656 first = Some(first.map_or(lo, |f| f.min(lo)));
657 }
658 if let Some(hi) = hi.as_deref().and_then(parse_datetime) {
659 last = Some(last.map_or(hi, |l| l.max(hi)));
660 }
661 }
662 let (first, last) = (first?, last?);
663 Some(if first.year() != last.year() {
664 format!("{} – {}", first.year(), last.year())
665 } else if first.month() != last.month() {
666 format!("{} – {}", first.format("%b"), last.format("%b %Y"))
667 } else {
668 first.format("%b %Y").to_string()
669 })
670}
671
672pub fn date_range(start: NaiveDate, end: NaiveDate) -> String {
674 if start == end {
675 start.format("%b %-d, %Y").to_string()
676 } else if start.year() == end.year() && start.month() == end.month() {
677 format!(
678 "{} – {}, {}",
679 start.format("%b %-d"),
680 end.format("%-d"),
681 start.year()
682 )
683 } else if start.year() == end.year() {
684 format!("{} – {}", start.format("%b %-d"), end.format("%b %-d, %Y"))
685 } else {
686 format!(
687 "{} – {}",
688 start.format("%b %-d, %Y"),
689 end.format("%b %-d, %Y")
690 )
691 }
692}
693
694#[cfg(test)]
695mod tests {
696 use super::*;
697
698 fn at(y: i32, m: u32, d: u32, h: u32) -> NaiveDateTime {
699 NaiveDate::from_ymd_opt(y, m, d)
700 .unwrap()
701 .and_hms_opt(h, 0, 0)
702 .unwrap()
703 }
704
705 fn place(city: &str, country: &str, photos: usize, first: NaiveDateTime) -> Place {
706 Place {
707 city: city.into(),
708 country: country.into(),
709 photos,
710 first,
711 }
712 }
713
714 fn conn() -> Connection {
715 let conn = Connection::open_in_memory().unwrap();
716 crate::db::create_schema(&conn).unwrap();
717 conn
718 }
719
720 fn trip_facts(places: Vec<Place>, start: NaiveDateTime, end: NaiveDateTime) -> Facts {
721 let photos = places.iter().map(|p| p.photos).sum();
722 Facts {
723 start: Some(start),
724 end: Some(end),
725 places,
726 photos,
727 latitude: Some(46.7),
728 home: Some(("Vizianagaram".into(), "India".into())),
729 ..Facts::default()
730 }
731 }
732
733 #[test]
734 fn trips_lead_with_the_most_specific_true_thing() {
735 let conn = conn();
736 let s = at(2023, 10, 15, 9);
737 let e = at(2023, 10, 19, 18);
738 let swiss = trip(
739 &conn,
740 &trip_facts(vec![place("Bern", "Switzerland", 16, s)], s, e),
741 );
742 assert_eq!(swiss.title, "First time in Switzerland");
743 assert_eq!(swiss.context, "Oct 15 – 19, 2023 · five days");
744
745 let home_country = trip(&conn, &trip_facts(vec![place("Goa", "India", 18, s)], s, e));
746 assert_eq!(home_country.title, "Autumn in Goa");
747
748 let xmas = trip(
749 &conn,
750 &trip_facts(
751 vec![place("Goa", "India", 18, at(2023, 12, 23, 9))],
752 at(2023, 12, 23, 9),
753 at(2023, 12, 27, 9),
754 ),
755 );
756 assert_eq!(xmas.title, "Christmas in Goa");
757
758 let two_stops = trip(
759 &conn,
760 &trip_facts(
761 vec![
762 place("Paris", "France", 4, s),
763 place("Bruges", "Belgium", 3, e),
764 ],
765 s,
766 e,
767 ),
768 );
769 assert_eq!(two_stops.title, "Paris to Bruges");
770
771 let mut with_people = trip_facts(vec![place("Goa", "India", 10, s)], s, e);
772 with_people.people = vec![("Meera".into(), 6), ("Dev".into(), 4)];
773 assert_eq!(trip(&conn, &with_people).title, "Goa with Meera and Dev");
774 }
775
776 #[test]
777 fn days_out_name_the_day_and_who_or_where() {
778 let mut facts = Facts {
779 start: Some(at(2024, 5, 19, 14)),
780 end: Some(at(2024, 5, 19, 17)),
781 places: vec![place("Paris", "France", 30, at(2024, 5, 19, 14))],
782 photos: 30,
783 home: Some(("Vizianagaram".into(), "India".into())),
784 ..Facts::default()
785 };
786 let story = moment(&facts);
787 assert_eq!(story.title, "A Sunday afternoon in Paris");
788 assert_eq!(story.context, "May 19, 2024 · 30 photos in three hours");
789
790 facts.people = vec![("Meera".into(), 20)];
791 assert_eq!(moment(&facts).title, "A Sunday afternoon with Meera");
792
793 facts.start = Some(at(2024, 12, 25, 10));
794 facts.end = Some(at(2024, 12, 25, 12));
795 assert_eq!(moment(&facts).title, "Christmas Day with Meera");
796 }
797
798 #[test]
799 fn gatherings_count_the_people() {
800 let facts = Facts {
801 start: Some(at(2024, 6, 8, 11)),
802 end: Some(at(2024, 6, 8, 16)),
803 photos: 12,
804 faces: 5,
805 ..Facts::default()
806 };
807 assert_eq!(gathering(&facts).title, "Five people, one Saturday");
808 let named = Facts {
809 people: vec![("Meera".into(), 8), ("Dev".into(), 6)],
810 ..facts
811 };
812 assert_eq!(gathering(&named).title, "Meera, Dev and three others");
813 }
814
815 #[test]
816 fn memories_add_a_place_or_person_when_one_stands_out() {
817 let s = at(2023, 10, 17, 9);
818 let facts = trip_facts(vec![place("Bern", "Switzerland", 6, s)], s, s);
819 assert_eq!(spelled("3 years ago today"), "Three years ago today");
820 assert_eq!(spelled("1 year ago this week"), "A year ago this week");
821 assert_eq!(spelled("14 years ago"), "14 years ago");
822 assert_eq!(
823 looking_back("Three years ago today", &facts),
824 "Three years ago today, in Bern"
825 );
826 assert_eq!(month_back("October", 2023, &facts), "Bern, October 2023");
827 let home = trip_facts(vec![place("Vizianagaram", "India", 6, s)], s, s);
828 assert_eq!(
829 month_back("October", 2023, &home),
830 "October 2023, a look back"
831 );
832 assert_eq!(year_back(2023, &home), "Your 2023");
833 }
834
835 #[test]
836 fn stored_titles_split_back_apart() {
837 let story = Story {
838 title: "Back in Goa".into(),
839 context: "Dec 26 – 30, 2023".into(),
840 };
841 assert_eq!(split(&story.joined()), ("Back in Goa", "Dec 26 – 30, 2023"));
842 assert_eq!(split("Old title"), ("Old title", ""));
843 }
844}