//! 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};usecrate::constants::MediaAlbumKind;usecrate::rules::media::stable_sort_by;usecrate::rules::media_items::MediaFamily;usecrate::transforms::zoned_clock::{zone_offset_ms, ZoneError};usecrate::js_number::math_round;/// Consecutive pictures further apart than this are different clusters.pubconst ALBUM_EVENT_GAP_MS: i64 = 3 * 60 * 60 * 1000;/// A jump between consecutive located pictures beyond this splits a cluster.pubconst ALBUM_PLACE_JUMP_KM: f64 = 2.0;/// Fewer members than this on one day is a burst, not an event.pubconst ALBUM_EVENT_MIN_MEMBERS: usize = 8;/// A gap at or beyond this, with disjoint linked people either side, splits.pubconst ALBUM_PEOPLE_SPLIT_GAP_MS: i64 = 60 * 60 * 1000;/// A located picture at least this far from home is "away".pubconst ALBUM_TRIP_DISTANCE_KM: f64 = 50.0;pubconst ALBUM_TRIP_MIN_DAYS: usize = 2;pubconst ALBUM_TRIP_MIN_MEMBERS: usize = 10;/// Consecutive away days may be separated by this many days with no located/// picture.pubconst ALBUM_TRIP_BRIDGE_DAYS: i64 = 1;/// A proposal sharing this share of either member set with a decided album is/// suppressed.pubconst ALBUM_OVERLAP_SUPPRESS: f64 = 0.5;pubconst ALBUM_HOME_WINDOW_DAYS: i64 = 365;/// Fewer located pictures than this in the window ⇒ no home, no trips.pubconst ALBUM_HOME_MIN_LOCATED: usize = 30;/// The cell home is judged in: 0.1° ≈ 10 km at the equator.pubconst ALBUM_HOME_CELL_DEGREES: f64 = 0.1;/// A linked person on at least this share of members is named in the title.pubconst ALBUM_TITLE_PEOPLE_SHARE: f64 = 0.5;pubconst ALBUM_TITLE_MAX_PEOPLE: usize = 2;/// A trip's title names at most this many places.pubconst 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)]pubenumAlbumsError {/// `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")]pubstructAlbumCandidate {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<i64>,pub latitude: Option<f64>,pub longitude: Option<f64>,pub place_name: Option<String>,pub place_city: Option<String>,pub place_country: Option<String>,/// `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<i64>,pub subtypes: Vec<String>,/// A `library` or `apple_library` sighting exists.pub own_library: bool,pub camera_make: Option<String>,/// 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<String>,pub aesthetic_score: Option<f64>,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")]pubenumAlbumIneligibleReason {NotOwn,Utility,Screenshot,DuplicateCopy,}implAlbumIneligibleReason {pubconstfn as_str(self) -> &'static str {matchself {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)]pubenumAlbumEligibility {Eligible,Ineligible(AlbumIneligibleReason),}implAlbumEligibility {pubconstfn is_eligible(self) -> bool { matches!(self, AlbumEligibility::Eligible) }pubconstfn reason(self) -> Option<AlbumIneligibleReason> {matchself {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.pubfn album_eligibility(candidate: &AlbumCandidate) -> AlbumEligibility {if candidate.is_utility == Some(1) {returnAlbumEligibility::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") {returnAlbumEligibility::Ineligible(AlbumIneligibleReason::Screenshot); }if candidate.confirmed_copy {returnAlbumEligibility::Ineligible(AlbumIneligibleReason::DuplicateCopy); }let own = candidate.own_library || candidate.camera_make.is_some() || candidate.latitude.is_some();if !own {returnAlbumEligibility::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<AlbumCandidate, "isUtility" | "subtypes">`, which Rust has no/// structural spelling for and which no caller builds a whole row for anyway.pubfn album_admits_by_hand(is_utility: Option<i64>, 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)]pubstructLocalInstant {/// 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.pubfn local_instant(taken_at: &str, offset_seconds: i64) -> Result<LocalInstant, AlbumsError> {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.pubfn 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).pubfn 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")]pubstructAlbumHome {pub latitude: f64,pub longitude: f64,/// The cell's majority city and country, e.g. "Bengaluru, India"; `None`/// when unnamed.pub label: Option<String>,pub country: Option<String>,/// 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<String>]) -> Option<String> {letmut order: Vec<&str> = Vec::new();letmut 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; }letmut best: Option<&str> = None;letmut 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<String>], max: usize) -> Vec<String> {letmut order: Vec<&str> = Vec::new();letmut 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; }letmut 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) } elseif 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.pubfn infer_home(candidates: &[AlbumCandidate], now_ms: i64) -> Option<AlbumHome> {let since = now_ms - ALBUM_HOME_WINDOW_DAYS * DAY_MS;letmut cell_order: Vec<String> = Vec::new();letmut cells: std::collections::HashMap<String, (Vec<&AlbumCandidate>, i64)> = std::collections::HashMap::new();letmut located = 0usize;for candidate in candidates {let (Some(latitude), Some(longitude)) = (candidate.latitude, candidate.longitude) else {continue; };if !album_eligibility(candidate).is_eligible() {continue; }letSome(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 {returnNone; }letmut best: Option<&(Vec<&AlbumCandidate>, i64)> = None;for key in &cell_order {letSome(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::<Vec<_>>(), );let country = mode( &best .0 .iter() .map(|c| c.place_country.clone()) .collect::<Vec<_>>(), );// `[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<String> = [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")]pubstructAlbumMember {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")]pubstructAlbumProposal {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<String>,pub cover_id: String,/// Linked person ids named in the title, most frequent first.pub people: Vec<String>,pub members: Vec<AlbumMember>,}/// The TypeScript's `Record<AlbumIneligibleReason, number>`, 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)]pubstructAlbumIneligibleCounts {pub not_own: usize,pub utility: usize,pub screenshot: usize,pub duplicate_copy: usize,}implAlbumIneligibleCounts {fn bump(&mutself, 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)]pubstructDeriveAlbumsResult {pub proposals: Vec<AlbumProposal>,pub eligible: usize,pub ineligible: AlbumIneligibleCounts,}/// One eligible candidate with its own local reading.#[derive(Debug, Clone)]structPlaced<'a> { candidate: &'a AlbumCandidate, at: LocalInstant,}implPlaced<'_> {/// `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<Vec<Placed<'a>>> {letmut clusters: Vec<Vec<Placed<'a>>> = Vec::new();letmut current: Vec<Placed<'a>> = Vec::new();letmut last_located: Option<(f64, f64)> = None;for item in items {letmut split = false;ifletSome(previous) = current.last() {if item.at.ms - previous.at.ms > ALBUM_EVENT_GAP_MS { split = true; } elseiflet (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; }ifletSome(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<String> { 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<String>, b: &std::collections::HashSet<String>) -> 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<Vec<Placed<'a>>> {for i in0..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)) {letmut 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>> {letmut 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 `""`.pubfn album_people<F>(per_member: &[Vec<String>], person_name: F) -> (Vec<String>, Vec<String>)where F: Fn(&str) -> Option<String>,{letmut order: Vec<&str> = Vec::new();letmut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();for people in per_member {letmut 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();letmut 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) } elseif a.0 < b.0 { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } });letmut ids = Vec::new();letmut names = Vec::new();for (id, count) in entries {if (count as f64) < floor || ids.len() >= ALBUM_TITLE_MAX_PEOPLE {break; }letSome(name) = person_name(id).filter(|name| !name.is_empty()) else {continue; }; ids.push(id.to_string()); names.push(name); } (ids, names)}fn named_people<F>(items: &[Placed<'_>], person_name: F) -> (Vec<String>, Vec<String>)where F: Fn(&str) -> Option<String>,{let per_member: Vec<Vec<String>> = 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`).pubconst 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")]pubenumAlbumTitle {/// A place, or a trip's places, with whoever is named.Place { places: Vec<String>, names: Vec<String> },/// An event with no place: who it was with, or "a day out".DayOut { names: Vec<String> },/// A trip with no place.Trip { names: Vec<String> },}implAlbumTitle {/// 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.pubfn 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) = matchself {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 "".pubfn album_title(kind: MediaAlbumKind, places: &[String], names: &[String]) -> AlbumTitle {let names = names.to_vec();if kind == MediaAlbumKind::Event {ifletSome(place) = places.first().filter(|place| !place.is_empty()) {returnAlbumTitle::Place { places: vec![place.clone()], names }; }returnAlbumTitle::DayOut { names }; }if !places.is_empty() {returnAlbumTitle::Place { places: places.to_vec(), names }; }AlbumTitle::Trip { names }}fn to_members(items: &[Placed<'_>]) -> Vec<AlbumMember> { 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 {letSome((latitude, longitude)) = placed.point() else {returnfalse; };if distance_km(home.latitude, home.longitude, latitude, longitude) >= ALBUM_TRIP_DISTANCE_KM {returntrue; }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<i64> {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<G>( items: &[Placed<'_>], home: &AlbumHome, person_name: &G,) -> Result<Vec<AlbumProposal>, AlbumsError>where G: Fn(&str) -> Option<String>,{letmut day_order: Vec<String> = Vec::new();letmut away_by_day: std::collections::HashMap<String, Vec<Placed<'_>>> = std::collections::HashMap::new();letmut located_days: std::collections::HashSet<String> = 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.letmut days = day_order; days.sort();letmut runs: Vec<Vec<String>> = Vec::new();for day in days {letmut appended = false;ifletSome(run) = runs.last_mut() {ifletSome(previous) = run.last().cloned() {iflet (Some(this_number), Some(previous_number)) = (day_number(&day), day_number(&previous)) {let gap = this_number - previous_number;letmut 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]); } }letmut trips = Vec::new();for run in runs {if run.len() < ALBUM_TRIP_MIN_DAYS {continue; }let members: Vec<Placed<'_>> = 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::<Vec<_>>(), ALBUM_TITLE_MAX_PLACES, );let (ids, names) = named_people(&members, person_name);letSome(cover) = choose_cover(&members) else {continue; };letSome(first) = run.first() else { continue };letSome(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<G>(items: &[Placed<'_>], person_name: &G) -> Vec<AlbumProposal>where G: Fn(&str) -> Option<String>,{letmut 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::<Vec<_>>(),1, );let (ids, names) = named_people(&part, person_name);letSome(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.pubfn derive_albums<F, G>( candidates: &[AlbumCandidate], home: Option<&AlbumHome>, fallback_offset: F, person_name: G,) -> Result<DeriveAlbumsResult, AlbumsError>where F: Fn(i64) -> i64, G: Fn(&str) -> Option<String>,{letmut ineligible = AlbumIneligibleCounts::default();letmut items: Vec<Placed<'_>> = Vec::new();for candidate in candidates {ifletSome(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.letSome(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) } elseif 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<AlbumProposal> = derive_events(&items, &person_name) .into_iter() .filter(|event| !in_trip(&event.starts_at)) .collect();letmut proposals: Vec<AlbumProposal> = 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 } } elseif 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.pubfn 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() {return0.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)]pubstructDecidedAlbum {pub id: String,pub members: Vec<String>,}/// 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.pubfn suppressed_by(members: &[String], decided: &[DecidedAlbum]) -> Option<String> {for album in decided {if overlap_share(members, &album.members) >= ALBUM_OVERLAP_SUPPRESS {returnSome(album.id.clone()); } }None}#[cfg(test)]#[path = "albums_tests.rs"]mod tests;