Cotton code
153 lines · 6.5 KB · RustRaw
//! When a recording brought into Comms was made (owner, 24 Nov 2026: "a recording shared in does not keep its date"),//! and the date he sets on one by hand.//!//! RULE: an imported recording is dated by the first of these that is known, never by the moment it was brought in//! while the file says otherwise://! 1. the time the file says it was recorded (its own metadata: an m4a's creation time);//! 2. a date and time written in its name ("Recording 2026-11-20 10.31.12", "Voice 261120_103112");//! 3. the file's own last-changed time, unless it is the copy just made to bring it in (within [`COPY_MS`] of now);//! 4. a date alone in its name ("AUD-20261120-WA0003"): that day, at the file's own time when that falls on it,//!    else at noon;//! 5. now.//!//! A time later than now, or before 2000 (a file's empty date reads as 1904 or 1970), is not one.use chrono::{DateTime, Datelike, LocalResult, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};use chrono_tz::Tz;use regex::Regex;use std::sync::LazyLock;/// A file's last-changed time this close to now is the copy made to bring it in, not the recording's.pub const COPY_MS: i64 = 120_000;/// What the phone knows about a file it brings in.#[derive(Debug, Clone, Default)]pub struct Facts<'a> {    /// Its name, as shared.    pub name: Option<&'a str>,    /// The time its own metadata says it was recorded, as the phone reads it (RFC 3339, or Android's    /// `20261120T103112.000Z`).    pub recorded: Option<&'a str>,    /// Its last-changed time, ms since the epoch.    pub modified_ms: Option<i64>,}/// When the recording was made, as a UTC instant, read in the person's zone (`zone`, IANA) where the file names a/// wall-clock time.pub fn taken_at(facts: &Facts<'_>, zone: &str, now: DateTime<Utc>) -> DateTime<Utc> {    let tz: Tz = zone.parse().unwrap_or(chrono_tz::UTC);    let fits = |at: DateTime<Utc>| at <= now && at.year() >= 2000;    if let Some(at) = facts.recorded.and_then(read_recorded).filter(|at| fits(*at)) {        return at;    }    let named = facts.name.map(named_time).unwrap_or(Named::None);    if let Named::At(local) = named {        if let Some(at) = in_zone(&tz, local).filter(|at| fits(*at)) {            return at;        }    }    let modified = facts.modified_ms.and_then(DateTime::<Utc>::from_timestamp_millis).filter(|at| fits(*at) && (now - *at).num_milliseconds() > COPY_MS);    if let Named::Day(day) = named {        if let Some(at) = modified.filter(|at| at.with_timezone(&tz).date_naive() == day) {            return at;        }        if let Some(at) = in_zone(&tz, day.and_time(NaiveTime::from_hms_opt(12, 0, 0).unwrap_or_default())).filter(|at| fits(*at)) {            return at;        }    }    modified.unwrap_or(now)}/// A date and time he sets by hand (`date` `YYYY-MM-DD`, `time` `HH:MM`, in his zone): the instant, or why not.pub fn set_by_hand(date: &str, time: &str, zone: &str, now: DateTime<Utc>) -> Result<DateTime<Utc>, Refused> {    let tz: Tz = zone.parse().unwrap_or(chrono_tz::UTC);    let day = NaiveDate::parse_from_str(date.trim(), "%Y-%m-%d").map_err(|_| Refused::Unreadable)?;    let clock = NaiveTime::parse_from_str(time.trim(), "%H:%M").map_err(|_| Refused::Unreadable)?;    let at = in_zone(&tz, day.and_time(clock)).ok_or(Refused::Unreadable)?;    if at > now {        return Err(Refused::Later);    }    if at.year() < 2000 {        return Err(Refused::Unreadable);    }    Ok(at)}/// Why a date set by hand is not taken.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Refused {    /// After now.    Later,    /// Not a date and time.    Unreadable,}/// The picker's date and time for an instant, in his zone: (`YYYY-MM-DD`, `HH:MM`).pub fn picker(at: DateTime<Utc>, zone: &str) -> (String, String) {    let tz: Tz = zone.parse().unwrap_or(chrono_tz::UTC);    let local = at.with_timezone(&tz);    (local.format("%Y-%m-%d").to_string(), local.format("%H:%M").to_string())}fn in_zone(tz: &Tz, local: NaiveDateTime) -> Option<DateTime<Utc>> {    match tz.from_local_datetime(&local) {        LocalResult::Single(at) => Some(at.with_timezone(&Utc)),        LocalResult::Ambiguous(first, _) => Some(first.with_timezone(&Utc)),        LocalResult::None => None,    }}fn read_recorded(said: &str) -> Option<DateTime<Utc>> {    let said = said.trim();    if let Ok(at) = DateTime::parse_from_rfc3339(said) {        return Some(at.with_timezone(&Utc));    }    // Android's MediaMetadataRetriever: `20261120T103112.000Z`, UTC.    let plain = said.trim_end_matches('Z');    let plain = plain.split('.').next().unwrap_or(plain);    NaiveDateTime::parse_from_str(plain, "%Y%m%dT%H%M%S").ok().map(|n| n.and_utc())}#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Named {    At(NaiveDateTime),    Day(NaiveDate),    None,}static DATE_TIME: LazyLock<Regex> = LazyLock::new(|| {    Regex::new(r"(?:^|\D)(20\d{2})[-_.]?(\d{2})[-_.]?(\d{2})[ _T-]{0,3}(\d{2})[-_.:h]?(\d{2})(?:[-_.:m]?(\d{2}))?(?:\D|$)").expect("pattern")});static SHORT_DATE_TIME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?:^|\D)(\d{2})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})(?:\D|$)").expect("pattern"));static DATE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?:^|\D)(20\d{2})[-_.]?(\d{2})[-_.]?(\d{2})(?:\D|$)").expect("pattern"));fn named_time(name: &str) -> Named {    let n = |caps: &regex::Captures<'_>, i: usize| caps.get(i).and_then(|m| m.as_str().parse::<u32>().ok());    let at = |y: i32, mo: u32, d: u32, h: u32, mi: u32, s: u32| NaiveDate::from_ymd_opt(y, mo, d).and_then(|day| day.and_hms_opt(h, mi, s));    if let Some(caps) = DATE_TIME.captures(name) {        if let (Some(y), Some(mo), Some(d), Some(h), Some(mi)) = (n(&caps, 1), n(&caps, 2), n(&caps, 3), n(&caps, 4), n(&caps, 5)) {            if let Some(found) = at(y as i32, mo, d, h, mi, n(&caps, 6).unwrap_or(0)) {                return Named::At(found);            }        }    }    if let Some(caps) = SHORT_DATE_TIME.captures(name) {        if let (Some(y), Some(mo), Some(d), Some(h), Some(mi), Some(s)) = (n(&caps, 1), n(&caps, 2), n(&caps, 3), n(&caps, 4), n(&caps, 5), n(&caps, 6)) {            if let Some(found) = at(2000 + y as i32, mo, d, h, mi, s) {                return Named::At(found);            }        }    }    if let Some(caps) = DATE.captures(name) {        if let (Some(y), Some(mo), Some(d)) = (n(&caps, 1), n(&caps, 2), n(&caps, 3)) {            if let Some(day) = NaiveDate::from_ymd_opt(y as i32, mo, d) {                return Named::Day(day);            }        }    }    Named::None}#[cfg(test)]#[path = "recording_time_tests.rs"]mod tests;