//! Which pictures make an album — the ONE decision behind //! `cotton_media_albums`, stated as pure functions. //! The port of `packages/core/src/engine/media/albums.ts`. //! //! **Eligibility first (D1).** A picture the person took themselves — a //! `library`/`apple_library` sighting, or camera metadata on the row — at a //! time that is its TAKEN time. A picture that only ever arrived in a chat or //! an email carries the SENT time, and forty forwarded pictures received one //! evening are not an event the person attended. Screenshots and utility //! images never enter, and a confirmed duplicate copy is stood for by its keep. //! //! **Home is inferred (D2):** the modal 10 km cell over the trailing year's //! located pictures, named on every trip it judged. Nothing marks home today; //! a set home (the spec names `cotton_locations.is_home`) replaces the //! inference when it exists. //! //! **Time gap, then place, then people (D3).** Clusters break on a 3-hour gap //! or a 2 km jump; a same-day cluster whose two halves share no linked person //! across an hour's gap is two events. An event is ≥ 8 members on one local //! day; a trip is ≥ 2 consecutive days ≥ 50 km from home (one unlocated day //! bridged) with ≥ 10 members, and it subsumes the events inside it. //! //! **The anchor is the id (D4)** — first local hour for an event, first local //! day for a trip — and DRIFT IS CAUGHT BY OVERLAP: a proposal sharing half of //! either member set with an album the person already decided is not made. //! //! **An opinion, never an act.** The output is proposals; the person keeps. //! //! ## What the Rust port changes, and why //! //! * **No process clock and no process zone.** [`zone_offset_seconds`] takes //! the instant as milliseconds instead of a `Date`, [`infer_home`] takes //! `now_ms`, and the zone is what it always was in this module — an explicit //! argument. `Intl` is replaced by [`crate::transforms::zoned_clock`], the //! crate's one zone reader. //! * **[`derive_albums`] takes its two callbacks as generic parameters** //! rather than as fields of an input struct, because Rust has no //! structurally-typed closure field that reads as well at a call site as //! `Fn(i64) -> i64` does. //! * **It returns a `Result`.** Three places in the TypeScript can throw a //! `RangeError` on an instant a calendar cannot render; none of them is //! reachable through the eligibility filter, and a pure library may not //! panic on rows a caller handed it. use serde::{Deserialize, Serialize}; use cotton_store::protocol::js::{parse_date_ms, to_iso_string}; use crate::constants::MediaAlbumKind; use crate::rules::media::stable_sort_by; use crate::rules::media_items::MediaFamily; use crate::transforms::zoned_clock::{zone_offset_ms, ZoneError}; use crate::js_number::math_round; /// Consecutive pictures further apart than this are different clusters. pub const ALBUM_EVENT_GAP_MS: i64 = 3 * 60 * 60 * 1000; /// A jump between consecutive located pictures beyond this splits a cluster. pub const ALBUM_PLACE_JUMP_KM: f64 = 2.0; /// Fewer members than this on one day is a burst, not an event. pub const ALBUM_EVENT_MIN_MEMBERS: usize = 8; /// A gap at or beyond this, with disjoint linked people either side, splits. pub const ALBUM_PEOPLE_SPLIT_GAP_MS: i64 = 60 * 60 * 1000; /// A located picture at least this far from home is "away". pub const ALBUM_TRIP_DISTANCE_KM: f64 = 50.0; pub const ALBUM_TRIP_MIN_DAYS: usize = 2; pub const ALBUM_TRIP_MIN_MEMBERS: usize = 10; /// Consecutive away days may be separated by this many days with no located /// picture. pub const ALBUM_TRIP_BRIDGE_DAYS: i64 = 1; /// A proposal sharing this share of either member set with a decided album is /// suppressed. pub const ALBUM_OVERLAP_SUPPRESS: f64 = 0.5; pub const ALBUM_HOME_WINDOW_DAYS: i64 = 365; /// Fewer located pictures than this in the window ⇒ no home, no trips. pub const ALBUM_HOME_MIN_LOCATED: usize = 30; /// The cell home is judged in: 0.1° ≈ 10 km at the equator. pub const ALBUM_HOME_CELL_DEGREES: f64 = 0.1; /// A linked person on at least this share of members is named in the title. pub const ALBUM_TITLE_PEOPLE_SHARE: f64 = 0.5; pub const ALBUM_TITLE_MAX_PEOPLE: usize = 2; /// A trip's title names at most this many places. pub const ALBUM_TITLE_MAX_PLACES: usize = 2; const DAY_MS: i64 = 24 * 60 * 60 * 1000; /// The failures the TypeScript raises as a `RangeError`, plus the arithmetic /// one Rust has to name. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum AlbumsError { /// `new Date(NaN).toISOString()` — an unparseable `taken_at`, or a shifted /// instant outside what a calendar can render. The TypeScript's sentence /// here is V8's, because the throw comes from `Date` rather than from the /// module. #[error("Invalid time value")] InvalidTimeValue, } // ── eligibility ───────────────────────────────────────────────────────────── /// What the derivation reads about one photo or video. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AlbumCandidate { pub id: String, /// `MEDIA_RECORD_KINDS` — the same two strings as /// [`MediaFamily`], reused rather than redeclared. pub kind: MediaFamily, pub taken_at: String, /// Seconds east of UTC at capture, as the row stores it; `None` = unknown. pub taken_offset: Option, pub latitude: Option, pub longitude: Option, pub place_name: Option, pub place_city: Option, pub place_country: Option, /// `cotton_photos.is_utility` (v40); videos carry none. An INTEGER column /// with three meanings, so the test is `== Some(1)` and not truthiness: /// `2` is not "utility". pub is_utility: Option, pub subtypes: Vec, /// A `library` or `apple_library` sighting exists. pub own_library: bool, pub camera_make: Option, /// The `copy_id` of a confirmed `cotton_media_duplicates` row. pub confirmed_copy: bool, /// Linked person ids from `cotton_media_faces.person_id`. pub people: Vec, pub aesthetic_score: Option, pub favourite: bool, } /// Why a picture is not album material. The strings are the reported ones. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AlbumIneligibleReason { NotOwn, Utility, Screenshot, DuplicateCopy, } impl AlbumIneligibleReason { pub const fn as_str(self) -> &'static str { match self { AlbumIneligibleReason::NotOwn => "not_own", AlbumIneligibleReason::Utility => "utility", AlbumIneligibleReason::Screenshot => "screenshot", AlbumIneligibleReason::DuplicateCopy => "duplicate_copy", } } } /// The TypeScript's `{ eligible: true } | { eligible: false; reason }`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AlbumEligibility { Eligible, Ineligible(AlbumIneligibleReason), } impl AlbumEligibility { pub const fn is_eligible(self) -> bool { matches!(self, AlbumEligibility::Eligible) } pub const fn reason(self) -> Option { match self { AlbumEligibility::Eligible => None, AlbumEligibility::Ineligible(reason) => Some(reason), } } } /// D1, clause by clause, IN THE ORDER THE REASONS ARE REPORTED. /// /// The order is part of the answer, not an implementation accident: a picture /// that is both a utility image and not the person's own is reported as /// `utility`, because the reason names the rule that bit first and that is the /// rule the owner would have to change. pub fn album_eligibility(candidate: &AlbumCandidate) -> AlbumEligibility { if candidate.is_utility == Some(1) { return AlbumEligibility::Ineligible(AlbumIneligibleReason::Utility); } // Case-sensitive, as `Array.prototype.includes` is: the subtype vocabulary // is Apple's own lowercase one. if candidate.subtypes.iter().any(|s| s == "screenshot") { return AlbumEligibility::Ineligible(AlbumIneligibleReason::Screenshot); } if candidate.confirmed_copy { return AlbumEligibility::Ineligible(AlbumIneligibleReason::DuplicateCopy); } let own = candidate.own_library || candidate.camera_make.is_some() || candidate.latitude.is_some(); if !own { return AlbumEligibility::Ineligible(AlbumIneligibleReason::NotOwn); } AlbumEligibility::Eligible } /// May the person put this picture in an album by hand? /// /// The same rule, minus ownership — the person's own album may hold a picture /// someone sent. Two arguments rather than the TypeScript's /// `Pick`, which Rust has no /// structural spelling for and which no caller builds a whole row for anyway. pub fn album_admits_by_hand(is_utility: Option, subtypes: &[String]) -> bool { is_utility != Some(1) && !subtypes.iter().any(|s| s == "screenshot") } // ── clocks ────────────────────────────────────────────────────────────────── /// A picture's own local reading of its instant. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct LocalInstant { /// The instant shifted by its offset — comparable across pictures, NOT a /// real epoch. Nothing may hand this to a formatter as an instant. pub ms: i64, /// `YYYY-MM-DD` in the picture's own local day. pub date: String, /// `YYYY-MM-DDTHH` — the event anchor. pub hour: String, } /// The first `n` characters of an ASCII ISO string, the way /// `String.prototype.slice(0, n)` cuts one — clamping rather than panicking on /// a short string. fn slice_prefix(text: &str, n: usize) -> String { text.chars().take(n).collect() } /// Shift an instant into its own local day and hour. /// /// The shifted value is fed straight back to `toISOString` and the date and /// hour are read off the front, which is the trick the whole module runs on: a /// picture is compared to its neighbours in ITS OWN wall clock without anyone /// having to know which zone that was. pub fn local_instant(taken_at: &str, offset_seconds: i64) -> Result { let parsed = parse_date_ms(taken_at).ok_or(AlbumsError::InvalidTimeValue)?; let shifted = offset_seconds .checked_mul(1000) .and_then(|offset| parsed.checked_add(offset)) .ok_or(AlbumsError::InvalidTimeValue)?; let iso = to_iso_string(shifted).ok_or(AlbumsError::InvalidTimeValue)?; Ok(LocalInstant { ms: shifted, date: slice_prefix(&iso, 10), hour: slice_prefix(&iso, 13), }) } /// Seconds east of UTC that `zone` keeps at `at_ms` — the fallback for a row /// with no offset of its own. /// /// **An unknown zone is UTC**, as the TypeScript's `try`/`catch` around the /// `Intl.DateTimeFormat` constructor makes it: a workspace with a nonsense /// zone string still gets albums, judged in UTC, rather than none. /// /// The one case the two implementations cannot both answer is an instant /// beyond what `chrono` can render (roughly year ±262143) but inside what /// `Date` can (±275760). JavaScript answers there and this returns 0. No /// picture reaches it, and every caller in this module has already refused an /// instant it could not parse. pub fn zone_offset_seconds(zone: &str, at_ms: i64) -> i64 { match zone_offset_ms(at_ms, zone) { Ok(offset_ms) => math_round(offset_ms as f64 / 1000.0) as i64, Err(ZoneError::UnknownTimeZone(_)) | Err(ZoneError::UnreadableInstant(_)) => 0, } } // ── geography ─────────────────────────────────────────────────────────────── /// The great-circle distance in kilometres (haversine, R = 6371 km). pub fn distance_km(a_lat: f64, a_lng: f64, b_lat: f64, b_lng: f64) -> f64 { let rad = std::f64::consts::PI / 180.0; let d_lat = (b_lat - a_lat) * rad; let d_lng = (b_lng - a_lng) * rad; let h = (d_lat / 2.0).sin().powi(2) + (a_lat * rad).cos() * (b_lat * rad).cos() * (d_lng / 2.0).sin().powi(2); let root = h.sqrt(); // `Math.min(1, x)` — floating-point slop can put the root a hair over 1 at // the antipode, and `asin` of that is NaN. let clamped = if root.is_nan() || root < 1.0 { root } else { 1.0 }; 2.0 * 6371.0 * clamped.asin() } /// Where the person lives, as the pictures say it. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AlbumHome { pub latitude: f64, pub longitude: f64, /// The cell's majority city and country, e.g. "Bengaluru, India"; `None` /// when unnamed. pub label: Option, pub country: Option, /// Located candidates the inference had in its window. pub located: usize, } /// The most frequent non-empty value, first past the post. /// /// The `!== ""` is the TypeScript's own and it matters: an empty `place_city` /// is a column that was written but says nothing, and letting it win the mode /// would label home `", India"`. fn mode(values: &[Option]) -> Option { let mut order: Vec<&str> = Vec::new(); let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); for value in values.iter().flatten() { if value.is_empty() { continue; } if !counts.contains_key(value.as_str()) { order.push(value.as_str()); } *counts.entry(value.as_str()).or_insert(0) += 1; } let mut best: Option<&str> = None; let mut best_count = 0usize; for value in order { let count = counts.get(value).copied().unwrap_or(0); if count > best_count { best = Some(value); best_count = count; } } best.map(str::to_string) } /// The `max` most frequent non-empty values, ties broken by the value itself. fn modes(values: &[Option], max: usize) -> Vec { let mut order: Vec<&str> = Vec::new(); let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); for value in values.iter().flatten() { if value.is_empty() { continue; } if !counts.contains_key(value.as_str()) { order.push(value.as_str()); } *counts.entry(value.as_str()).or_insert(0) += 1; } let mut entries: Vec<(&str, usize)> = order .into_iter() .map(|value| (value, counts.get(value).copied().unwrap_or(0))) .collect(); // `b[1] - a[1] || (a[0] < b[0] ? -1 : 1)` — count descending, then the // value ascending, and never `Equal`. stable_sort_by(&mut entries, |a, b| { if a.1 != b.1 { b.1.cmp(&a.1) } else if a.0 < b.0 { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } }); entries .into_iter() .take(max) .map(|(value, _)| value.to_string()) .collect() } /// D2: the modal cell over the trailing year's located, eligible pictures. /// Ties go to the cell whose latest picture is more recent. /// /// A picture with no readable `taken_at` is stepped over rather than counted: /// `!(NaN >= since)` is true in JavaScript, so the `continue` fires there for /// exactly the same reason it fires here. pub fn infer_home(candidates: &[AlbumCandidate], now_ms: i64) -> Option { let since = now_ms - ALBUM_HOME_WINDOW_DAYS * DAY_MS; let mut cell_order: Vec = Vec::new(); let mut cells: std::collections::HashMap, i64)> = std::collections::HashMap::new(); let mut located = 0usize; for candidate in candidates { let (Some(latitude), Some(longitude)) = (candidate.latitude, candidate.longitude) else { continue; }; if !album_eligibility(candidate).is_eligible() { continue; } let Some(at) = parse_date_ms(&candidate.taken_at) else { continue; }; if !(at >= since) || at > now_ms { continue; } located += 1; // `Math.round`, not Rust's `round`: they disagree at every negative // half, and a southern or western cell boundary is exactly where a // half lands. let key = format!( "{}:{}", cotton_store::protocol::js::number_to_string(math_round( latitude / ALBUM_HOME_CELL_DEGREES )), cotton_store::protocol::js::number_to_string(math_round( longitude / ALBUM_HOME_CELL_DEGREES )) ); if !cells.contains_key(&key) { cell_order.push(key.clone()); } let cell = cells.entry(key).or_insert_with(|| (Vec::new(), 0)); cell.0.push(candidate); cell.1 = cell.1.max(at); } if located < ALBUM_HOME_MIN_LOCATED { return None; } let mut best: Option<&(Vec<&AlbumCandidate>, i64)> = None; for key in &cell_order { let Some(cell) = cells.get(key) else { continue; }; let take = match best { None => true, Some(current) => { cell.0.len() > current.0.len() || (cell.0.len() == current.0.len() && cell.1 > current.1) } }; if take { best = Some(cell); } } let best = best?; let count = best.0.len() as f64; let latitude = best .0 .iter() .fold(0.0f64, |sum, c| sum + c.latitude.unwrap_or(0.0)) / count; let longitude = best .0 .iter() .fold(0.0f64, |sum, c| sum + c.longitude.unwrap_or(0.0)) / count; let city = mode( &best .0 .iter() .map(|c| c.place_city.clone()) .collect::>(), ); let country = mode( &best .0 .iter() .map(|c| c.place_country.clone()) .collect::>(), ); // `[city, country].filter(non-null).join(", ") || null` — an empty join is // falsy in JavaScript, which is the only way `label` comes back null. let label_parts: Vec = [city, country.clone()].into_iter().flatten().collect(); let label = if label_parts.is_empty() { None } else { Some(label_parts.join(", ")) }; Some(AlbumHome { latitude, longitude, label, country, located, }) } // ── derivation ────────────────────────────────────────────────────────────── #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AlbumMember { pub id: String, pub kind: MediaFamily, /// The picture's `taken_at`, the members' order. pub sort_at: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AlbumProposal { pub kind: MediaAlbumKind, /// First local hour (event) or first local day (trip). pub anchor: String, pub title: AlbumTitle, /// Local days, `YYYY-MM-DD`. pub starts_at: String, pub ends_at: String, pub home_label: Option, pub cover_id: String, /// Linked person ids named in the title, most frequent first. pub people: Vec, pub members: Vec, } /// The TypeScript's `Record`, as a struct so a /// new reason fails the BUILD rather than reading as a silent zero. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct AlbumIneligibleCounts { pub not_own: usize, pub utility: usize, pub screenshot: usize, pub duplicate_copy: usize, } impl AlbumIneligibleCounts { fn bump(&mut self, reason: AlbumIneligibleReason) { match reason { AlbumIneligibleReason::NotOwn => self.not_own += 1, AlbumIneligibleReason::Utility => self.utility += 1, AlbumIneligibleReason::Screenshot => self.screenshot += 1, AlbumIneligibleReason::DuplicateCopy => self.duplicate_copy += 1, } } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DeriveAlbumsResult { pub proposals: Vec, pub eligible: usize, pub ineligible: AlbumIneligibleCounts, } /// One eligible candidate with its own local reading. #[derive(Debug, Clone)] struct Placed<'a> { candidate: &'a AlbumCandidate, at: LocalInstant, } impl Placed<'_> { /// `latitude !== null && longitude !== null` — the TypeScript's type guard. fn point(&self) -> Option<(f64, f64)> { match (self.candidate.latitude, self.candidate.longitude) { (Some(latitude), Some(longitude)) => Some((latitude, longitude)), _ => None, } } } /// D3, first two rules: the 3-hour gap and the 2 km jump. /// /// `last_located` is reset at every split, so the jump is measured inside a /// cluster and never across one — and an unlocated run in the middle of a /// cluster never splits anything, because the last KNOWN point is what the /// next located picture is compared against. fn cluster_by_time_and_place<'a>(items: &[Placed<'a>]) -> Vec>> { let mut clusters: Vec>> = Vec::new(); let mut current: Vec> = Vec::new(); let mut last_located: Option<(f64, f64)> = None; for item in items { let mut split = false; if let Some(previous) = current.last() { if item.at.ms - previous.at.ms > ALBUM_EVENT_GAP_MS { split = true; } else if let (Some(here), Some(there)) = (item.point(), last_located) { split = distance_km(there.0, there.1, here.0, here.1) > ALBUM_PLACE_JUMP_KM; } } if split { clusters.push(std::mem::take(&mut current)); last_located = None; } if let Some(point) = item.point() { last_located = Some(point); } current.push(item.clone()); } if !current.is_empty() { clusters.push(current); } clusters } fn people_of(items: &[Placed<'_>]) -> std::collections::HashSet { items .iter() .flat_map(|p| p.candidate.people.iter().cloned()) .collect() } /// Two non-empty companies with nobody in common. fn disjoint(a: &std::collections::HashSet, b: &std::collections::HashSet) -> bool { !a.is_empty() && !b.is_empty() && a.iter().all(|x| !b.contains(x)) } /// D3, third rule: two disjoint companies across an hour's gap are two events. /// /// Nobody linked on one side is NOT a split — there is nothing to be disjoint /// from, and an unlabelled stretch of an evening is still that evening. fn split_by_people<'a>(cluster: &[Placed<'a>]) -> Vec>> { for i in 0..cluster.len().saturating_sub(1) { if cluster[i + 1].at.ms - cluster[i].at.ms < ALBUM_PEOPLE_SPLIT_GAP_MS { continue; } let (left, right) = cluster.split_at(i + 1); if disjoint(&people_of(left), &people_of(right)) { let mut out = vec![left.to_vec()]; out.extend(split_by_people(right)); return out; } } vec![cluster.to_vec()] } /// The best-looking member, a favourite breaking a tie. /// /// An unscored picture counts as −1, so any scored one beats it and a library /// the analyser has not reached yet still gets its first picture as the cover. fn choose_cover<'a>(items: &'a [Placed<'a>]) -> Option<&'a Placed<'a>> { let mut best = items.first()?; for item in items { let a = item.candidate.aesthetic_score.unwrap_or(-1.0); let b = best.candidate.aesthetic_score.unwrap_or(-1.0); if a > b || (a == b && item.candidate.favourite && !best.candidate.favourite) { best = item; } } Some(best) } /// D3's people rule on its own: the linked people on at least half the /// members, at most two, most frequent first — what a title names and what a /// list row shows. `per_member` is each member's linked person ids. /// /// A person whose name the caller cannot resolve is SKIPPED, not counted /// against the two: an unnamed person still holds their place in the count, so /// the second-most-frequent named person is named. An EMPTY name is treated as /// no name, because `if (!name)` is falsy for `""`. pub fn album_people(per_member: &[Vec], person_name: F) -> (Vec, Vec) where F: Fn(&str) -> Option, { let mut order: Vec<&str> = Vec::new(); let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); for people in per_member { let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new(); for id in people { // `new Set(people)` — a person linked twice on one picture counts // once. if !seen.insert(id.as_str()) { continue; } if !counts.contains_key(id.as_str()) { order.push(id.as_str()); } *counts.entry(id.as_str()).or_insert(0) += 1; } } let floor = (per_member.len() as f64 * ALBUM_TITLE_PEOPLE_SHARE).ceil(); let mut entries: Vec<(&str, usize)> = order .into_iter() .map(|id| (id, counts.get(id).copied().unwrap_or(0))) .collect(); stable_sort_by(&mut entries, |a, b| { if a.1 != b.1 { b.1.cmp(&a.1) } else if a.0 < b.0 { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } }); let mut ids = Vec::new(); let mut names = Vec::new(); for (id, count) in entries { if (count as f64) < floor || ids.len() >= ALBUM_TITLE_MAX_PEOPLE { break; } let Some(name) = person_name(id).filter(|name| !name.is_empty()) else { continue; }; ids.push(id.to_string()); names.push(name); } (ids, names) } fn named_people(items: &[Placed<'_>], person_name: F) -> (Vec, Vec) where F: Fn(&str) -> Option, { let per_member: Vec> = items .iter() .map(|item| item.candidate.people.clone()) .collect(); album_people(&per_member, person_name) } /// The set an album's title is said in (`kits/shell/lines/albums.json`). pub const LINES: &str = "albums"; /// What a derived album is called, as a typed fact: the place (or places) /// and the people named on at least half its members. Said in the /// database's line rows by [`AlbumTitle::say`] where the title is written. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", tag = "form")] pub enum AlbumTitle { /// A place, or a trip's places, with whoever is named. Place { places: Vec, names: Vec }, /// An event with no place: who it was with, or "a day out". DayOut { names: Vec }, /// A trip with no place. Trip { names: Vec }, } impl AlbumTitle { /// The title in `rows`' words (the kit's for a line they have none of). /// A list of names or places is joined by the `join` line, pairwise. pub fn say(&self, rows: &[crate::rules::shell_lines::LineRow]) -> String { let line = |path: &str, fills: &[(&str, &str)]| { crate::rules::shell_lines::resolve(LINES, path, rows, fills).unwrap_or_default() }; let joined = |items: &[String]| { items .iter() .cloned() .reduce(|a, b| line("join", &[("a", &a), ("b", &b)])) .unwrap_or_default() }; let (bare, with, names) = match self { AlbumTitle::Place { places, names } => { let place = joined(places); if names.is_empty() { return line("title.place", &[("place", &place)]); } return line("title.place_with", &[("place", &place), ("names", &joined(names))]); } AlbumTitle::DayOut { names } => ("title.day_out", "title.day_out_with", names), AlbumTitle::Trip { names } => ("title.trip", "title.trip_with", names), }; if names.is_empty() { line(bare, &[]) } else { line(with, &[("names", &joined(names))]) } } } /// D3: the place, then up to two linked people on at least half the members. /// /// An EMPTY first place falls through to the people, because `if (place)` is /// falsy for `""` — a place column that was written and says nothing must not /// title an album "". pub fn album_title(kind: MediaAlbumKind, places: &[String], names: &[String]) -> AlbumTitle { let names = names.to_vec(); if kind == MediaAlbumKind::Event { if let Some(place) = places.first().filter(|place| !place.is_empty()) { return AlbumTitle::Place { places: vec![place.clone()], names }; } return AlbumTitle::DayOut { names }; } if !places.is_empty() { return AlbumTitle::Place { places: places.to_vec(), names }; } AlbumTitle::Trip { names } } fn to_members(items: &[Placed<'_>]) -> Vec { items .iter() .map(|item| AlbumMember { id: item.candidate.id.clone(), kind: item.candidate.kind, sort_at: item.candidate.taken_at.clone(), }) .collect() } /// Away from home: far enough, OR in a different country whatever the /// distance. A weekend across a border is a trip even when the border is /// twenty kilometres away. fn is_away(placed: &Placed<'_>, home: &AlbumHome) -> bool { let Some((latitude, longitude)) = placed.point() else { return false; }; if distance_km(home.latitude, home.longitude, latitude, longitude) >= ALBUM_TRIP_DISTANCE_KM { return true; } match (&home.country, &placed.candidate.place_country) { (Some(home_country), Some(country)) => country != home_country, _ => false, } } /// Days since the epoch for a `YYYY-MM-DD` key. /// /// `None` where the TypeScript answers `NaN`, and both mean the same thing to /// the one caller: a day whose number cannot be read is never BRIDGED to its /// neighbour, so it starts a run of its own rather than silently joining one. fn day_number(date: &str) -> Option { let ms = parse_date_ms(&format!("{date}T00:00:00.000Z"))?; Some(math_round(ms as f64 / DAY_MS as f64) as i64) } /// D3: runs of away days, one unlocated day bridged, ≥ 2 days and ≥ 10 /// members. fn derive_trips( items: &[Placed<'_>], home: &AlbumHome, person_name: &G, ) -> Result, AlbumsError> where G: Fn(&str) -> Option, { let mut day_order: Vec = Vec::new(); let mut away_by_day: std::collections::HashMap>> = std::collections::HashMap::new(); let mut located_days: std::collections::HashSet = std::collections::HashSet::new(); for placed in items { if placed.point().is_some() { located_days.insert(placed.at.date.clone()); } if is_away(placed, home) { if !away_by_day.contains_key(&placed.at.date) { day_order.push(placed.at.date.clone()); } away_by_day .entry(placed.at.date.clone()) .or_default() .push(placed.clone()); } } // `[...map.keys()].sort()` — no comparator, so a UTF-16 code-unit sort. // Every key is `YYYY-MM-DD` off `toISOString`, i.e. ASCII, where a // code-unit sort and a byte sort are the same order. let mut days = day_order; days.sort(); let mut runs: Vec> = Vec::new(); for day in days { let mut appended = false; if let Some(run) = runs.last_mut() { if let Some(previous) = run.last().cloned() { if let (Some(this_number), Some(previous_number)) = (day_number(&day), day_number(&previous)) { let gap = this_number - previous_number; let mut bridged = gap == 1; if !bridged && gap - 1 <= ALBUM_TRIP_BRIDGE_DAYS { bridged = true; for n in (previous_number + 1)..this_number { let between = n .checked_mul(DAY_MS) .and_then(to_iso_string) .ok_or(AlbumsError::InvalidTimeValue)?; if located_days.contains(&slice_prefix(&between, 10)) { bridged = false; } } } if bridged { run.push(day.clone()); appended = true; } } } } if !appended { runs.push(vec![day]); } } let mut trips = Vec::new(); for run in runs { if run.len() < ALBUM_TRIP_MIN_DAYS { continue; } let members: Vec> = run .iter() .flat_map(|day| away_by_day.get(day).cloned().unwrap_or_default()) .collect(); if members.len() < ALBUM_TRIP_MIN_MEMBERS { continue; } let places = modes( &members .iter() .map(|p| { p.candidate .place_city .clone() .or_else(|| p.candidate.place_country.clone()) }) .collect::>(), ALBUM_TITLE_MAX_PLACES, ); let (ids, names) = named_people(&members, person_name); let Some(cover) = choose_cover(&members) else { continue; }; let Some(first) = run.first() else { continue }; let Some(last) = run.last() else { continue }; trips.push(AlbumProposal { kind: MediaAlbumKind::Trip, anchor: first.clone(), title: album_title(MediaAlbumKind::Trip, &places, &names), starts_at: first.clone(), ends_at: last.clone(), home_label: home.label.clone(), cover_id: cover.candidate.id.clone(), people: ids, members: to_members(&members), }); } Ok(trips) } fn derive_events(items: &[Placed<'_>], person_name: &G) -> Vec where G: Fn(&str) -> Option, { let mut events = Vec::new(); for cluster in cluster_by_time_and_place(items) { for part in split_by_people(&cluster) { if part.len() < ALBUM_EVENT_MIN_MEMBERS { continue; } let (Some(first), Some(last)) = (part.first(), part.last()) else { continue; }; let date = first.at.date.clone(); // A cluster that crosses local midnight is not an event: an event // is a DAY, and its id is a day. if last.at.date != date { continue; } let places = modes( &part .iter() .map(|p| { p.candidate .place_name .clone() .or_else(|| p.candidate.place_city.clone()) }) .collect::>(), 1, ); let (ids, names) = named_people(&part, person_name); let Some(cover) = choose_cover(&part) else { continue; }; events.push(AlbumProposal { kind: MediaAlbumKind::Event, anchor: first.at.hour.clone(), title: album_title(MediaAlbumKind::Event, &places, &names), starts_at: date.clone(), ends_at: date, home_label: None, cover_id: cover.candidate.id.clone(), people: ids, members: to_members(&part), }); } } events } /// The whole rule, oldest proposal first. /// /// `fallback_offset` is the workspace zone's offset at an instant, for a row /// with no offset of its own; `person_name` resolves a linked person's display /// name, and `None` leaves them out of the title. `home` of `None` means no /// trips are derived this pass — events still are. pub fn derive_albums( candidates: &[AlbumCandidate], home: Option<&AlbumHome>, fallback_offset: F, person_name: G, ) -> Result where F: Fn(i64) -> i64, G: Fn(&str) -> Option, { let mut ineligible = AlbumIneligibleCounts::default(); let mut items: Vec> = Vec::new(); for candidate in candidates { if let Some(reason) = album_eligibility(candidate).reason() { ineligible.bump(reason); continue; } // A `taken_at` nothing can parse is stepped over WITHOUT a count: it // is not a reason the owner could act on, it is a broken row. let Some(at) = parse_date_ms(&candidate.taken_at) else { continue; }; let offset = candidate .taken_offset .unwrap_or_else(|| fallback_offset(at)); items.push(Placed { candidate, at: local_instant(&candidate.taken_at, offset)?, }); } // `a.at.ms - b.at.ms || (a.c.id < b.c.id ? -1 : 1)` — never `Equal`. stable_sort_by(&mut items, |a, b| { if a.at.ms != b.at.ms { a.at.ms.cmp(&b.at.ms) } else if a.candidate.id < b.candidate.id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } }); let trips = match home { Some(home) => derive_trips(&items, home, &person_name)?, None => Vec::new(), }; let in_trip = |date: &str| { trips .iter() .any(|trip| trip.starts_at.as_str() <= date && date <= trip.ends_at.as_str()) }; let events: Vec = derive_events(&items, &person_name) .into_iter() .filter(|event| !in_trip(&event.starts_at)) .collect(); let mut proposals: Vec = trips.into_iter().chain(events).collect(); stable_sort_by(&mut proposals, |a, b| { if a.starts_at != b.starts_at { if a.starts_at < b.starts_at { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } } else if a.anchor < b.anchor { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } }); Ok(DeriveAlbumsResult { proposals, eligible: items.len(), ineligible, }) } // ── convergence ───────────────────────────────────────────────────────────── /// |a ∩ b| / min(|a|, |b|); 0 when either is empty. /// /// Against the SMALLER set on purpose: a fresh cluster of six that contains /// all four of a decided album's pictures is the same event grown, not a new /// one, and dividing by the union would have called it 0.67 and let it through /// at the wrong threshold. pub fn overlap_share(a: &[String], b: &[String]) -> f64 { let set_a: std::collections::HashSet<&str> = a.iter().map(String::as_str).collect(); let set_b: std::collections::HashSet<&str> = b.iter().map(String::as_str).collect(); if set_a.is_empty() || set_b.is_empty() { return 0.0; } let shared = set_a.iter().filter(|x| set_b.contains(*x)).count(); shared as f64 / set_a.len().min(set_b.len()) as f64 } /// An album the person has already decided on. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DecidedAlbum { pub id: String, pub members: Vec, } /// D4: a fresh proposal that shares half of either member set with an album /// the person already decided is not written — a dismissal is for ever, and a /// kept album's new pictures are the person's to add. pub fn suppressed_by(members: &[String], decided: &[DecidedAlbum]) -> Option { for album in decided { if overlap_share(members, &album.members) >= ALBUM_OVERLAP_SUPPRESS { return Some(album.id.clone()); } } None } #[cfg(test)] #[path = "albums_tests.rs"] mod tests;