tuigram-cli 1.10.0

Telegram in your terminal: a fast, vim-style Telegram client built on TDLib
//! `:schedule`: sending the composer's message later, as Telegram's
//! scheduled messages do. The time is typed in the words of the prompt
//! (`18:30`, `2026-12-31 09:00` or `+45`), always in local time.

use chrono::{
    DateTime, Datelike, MappedLocalTime, NaiveDateTime, NaiveTime, Offset, TimeDelta, TimeZone,
};

use crate::lang;

/// The unix time `input` names, counting from `now`: `HH:MM` for the next
/// such time, later today or tomorrow; `YYYY-MM-DD HH:MM` for a moment
/// named in full; or `+N` for N minutes from now. Words in none of these
/// forms, or a time already past, are an error for the status bar.
pub fn parse<Tz: TimeZone>(input: &str, now: DateTime<Tz>) -> Result<i32, String> {
    let wrong = || {
        lang::f(
            "Send times are like 18:30, 2026-12-31 09:00 or +45 minutes, not \"{input}\"",
            &[("input", &input)],
        )
    };
    let past = || lang::t("That time has already passed").to_string();
    let input = input.trim();
    let zone = now.timezone();
    let local = |at: NaiveDateTime| moment(&zone, at).ok_or_else(wrong);
    let when = if let Some(minutes) = input.strip_prefix('+') {
        let minutes: i64 = minutes.trim().parse().map_err(|_| wrong())?;
        if minutes < 1 {
            return Err(wrong());
        }
        // Any number can be typed: one too big for a date is wrong too.
        TimeDelta::try_minutes(minutes)
            .and_then(|later| now.clone().checked_add_signed(later))
            .ok_or_else(wrong)?
    } else if let Ok(time) = NaiveTime::parse_from_str(input, "%H:%M") {
        let today = local(now.date_naive().and_time(time))?;
        if today > now {
            today
        } else {
            local((now.date_naive() + TimeDelta::days(1)).and_time(time))?
        }
    } else {
        let moment = NaiveDateTime::parse_from_str(input, "%Y-%m-%d %H:%M").map_err(|_| wrong())?;
        local(moment)?
    };
    if when <= now {
        return Err(past());
    }
    // Telegram refuses one further ahead, after it has left the composer.
    if when.clone().signed_duration_since(now) > TimeDelta::days(365) {
        return Err(lang::t("Telegram schedules messages at most a year ahead").into());
    }
    i32::try_from(when.timestamp()).map_err(|_| wrong())
}

/// The moment a wall-clock time names in `zone`: the first of two when
/// the clocks going back repeat it; when their going forward skips it,
/// the time as read before they did, as far past the gap as it was into it.
pub fn moment<Tz: TimeZone>(zone: &Tz, at: NaiveDateTime) -> Option<DateTime<Tz>> {
    match zone.from_local_datetime(&at) {
        MappedLocalTime::None => {
            let before = zone
                .from_local_datetime(&(at - TimeDelta::hours(3)))
                .earliest()?;
            let offset = before.offset().fix().local_minus_utc();
            let utc = at.checked_sub_signed(TimeDelta::seconds(offset.into()))?;
            Some(zone.from_utc_datetime(&utc))
        }
        found => found.earliest(),
    }
}

/// How the status bar names the moment `at` a message was scheduled for:
/// its time of day, after its date unless that's today.
pub fn describe<Tz: TimeZone>(at: i32, now: &DateTime<Tz>) -> String {
    let Some(at) = now.timezone().timestamp_opt(at.into(), 0).single() else {
        return String::new();
    };
    let (at, today) = (at.naive_local(), now.naive_local().date());
    let time = at.format("%H:%M");
    if at.date() == today {
        time.to_string()
    } else if at.year() == today.year() {
        format!("{} {time}", lang::day_month(&at))
    } else {
        format!("{} {time}", lang::day_month_year(&at))
    }
}

#[cfg(test)]
mod tests {
    use chrono::{FixedOffset, Local, NaiveDate};

    use super::*;

    #[test]
    fn a_scheduled_time_is_named_by_its_time_of_day_and_its_date_when_not_today() {
        let zone = FixedOffset::east_opt(3600).unwrap();
        let now = zone.with_ymd_and_hms(2026, 12, 4, 10, 0, 0).unwrap();
        let at = |d, h, m| {
            zone.with_ymd_and_hms(2026, 12, d, h, m, 0)
                .unwrap()
                .timestamp() as i32
        };
        assert_eq!(describe(at(4, 18, 30), &now), "18:30");
        assert_eq!(describe(at(5, 9, 5), &now), "5 Dec 09:05");
        let next_year = zone
            .with_ymd_and_hms(2027, 1, 2, 8, 0, 0)
            .unwrap()
            .timestamp() as i32;
        assert_eq!(describe(next_year, &now), "2 Jan 2027 08:00");
    }

    /// A zone whose clocks go forward an hour at 02:00 on 29 March 2026,
    /// from UTC+1 to UTC+2, as Central Europe's do.
    #[derive(Clone, Copy)]
    struct Spring;

    fn spring_change() -> NaiveDateTime {
        NaiveDate::from_ymd_opt(2026, 3, 29)
            .unwrap()
            .and_hms_opt(2, 0, 0)
            .unwrap()
    }

    fn east(hours: i32) -> FixedOffset {
        FixedOffset::east_opt(hours * 3600).unwrap()
    }

    impl TimeZone for Spring {
        type Offset = FixedOffset;
        fn from_offset(_: &FixedOffset) -> Self {
            Spring
        }
        fn offset_from_local_date(&self, _: &NaiveDate) -> MappedLocalTime<FixedOffset> {
            unreachable!("only date-times are asked")
        }
        fn offset_from_local_datetime(
            &self,
            local: &NaiveDateTime,
        ) -> MappedLocalTime<FixedOffset> {
            if *local < spring_change() {
                MappedLocalTime::Single(east(1))
            } else if *local < spring_change() + TimeDelta::hours(1) {
                MappedLocalTime::None
            } else {
                MappedLocalTime::Single(east(2))
            }
        }
        fn offset_from_utc_date(&self, _: &NaiveDate) -> FixedOffset {
            unreachable!("only date-times are asked")
        }
        fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> FixedOffset {
            if *utc < spring_change() - TimeDelta::hours(1) {
                east(1)
            } else {
                east(2)
            }
        }
    }

    #[test]
    fn a_time_the_clocks_skip_is_read_as_before_they_went_forward() {
        let evening = Spring
            .with_ymd_and_hms(2026, 3, 28, 22, 0, 0)
            .single()
            .unwrap();
        // 02:30 at UTC+1, which the clocks call 03:30.
        let meant = Spring
            .with_ymd_and_hms(2026, 3, 29, 3, 30, 0)
            .single()
            .unwrap()
            .timestamp() as i32;
        assert_eq!(parse("02:30", evening), Ok(meant));
        assert_eq!(parse("2026-03-29 02:30", evening), Ok(meant));
        // Either side of the gap, as typed.
        let at = |h| {
            Spring
                .with_ymd_and_hms(2026, 3, 29, h, 0, 0)
                .single()
                .unwrap()
                .timestamp() as i32
        };
        assert_eq!(parse("01:00", evening), Ok(at(1)));
        assert_eq!(parse("03:00", evening), Ok(at(3)));
    }

    /// Noon of a day, wherever the tests run.
    fn now() -> DateTime<Local> {
        Local
            .with_ymd_and_hms(2026, 11, 28, 12, 0, 0)
            .single()
            .unwrap()
    }

    /// The (year, month, day, hour, minute) of a unix time, in local time.
    fn shown(at: i32) -> (i32, u32, u32, u32, u32) {
        use chrono::Datelike;
        use chrono::Timelike;
        let at = Local.timestamp_opt(at as i64, 0).single().unwrap();
        (at.year(), at.month(), at.day(), at.hour(), at.minute())
    }

    #[test]
    fn a_clock_time_later_today_is_today() {
        let at = parse("18:30", now()).unwrap();
        assert_eq!(shown(at), (2026, 11, 28, 18, 30));
    }

    #[test]
    fn a_clock_time_already_past_is_tomorrow() {
        let at = parse("09:00", now()).unwrap();
        assert_eq!(shown(at), (2026, 11, 29, 9, 0));
    }

    #[test]
    fn a_clock_time_of_this_minute_counts_as_past() {
        let at = parse("12:00", now()).unwrap();
        assert_eq!(shown(at), (2026, 11, 29, 12, 0));
    }

    #[test]
    fn a_full_date_and_time_is_that_moment() {
        let at = parse("2026-12-31 09:00", now()).unwrap();
        assert_eq!(shown(at), (2026, 12, 31, 9, 0));
    }

    #[test]
    fn a_full_date_and_time_already_past_is_an_error() {
        assert_eq!(
            parse("2026-11-28 11:59", now()),
            Err(lang::t("That time has already passed").to_string())
        );
        assert!(parse("2020-01-01 00:00", now()).is_err());
    }

    #[test]
    fn telegram_schedules_at_most_a_year_ahead() {
        let too_late = lang::t("Telegram schedules messages at most a year ahead").to_string();
        assert!(parse("+525600", now()).is_ok(), "365 days");
        assert_eq!(parse("+525601", now()), Err(too_late.clone()));
        assert_eq!(parse("2028-01-01 09:00", now()), Err(too_late));
    }

    #[test]
    fn minutes_from_now() {
        assert_eq!(
            parse("+45", now()).unwrap(),
            (now() + TimeDelta::minutes(45)).timestamp() as i32
        );
        assert_eq!(
            parse("+1", now()).unwrap(),
            (now() + TimeDelta::minutes(1)).timestamp() as i32
        );
    }

    #[test]
    fn anything_else_is_an_error() {
        for input in [
            "",
            "+",
            "+0",
            "+-5",
            "+1.5",
            "25:00",
            "12:60",
            "2026-13-01 10:00",
            "soon",
            "18:30:00",
            "+999999999999999",
            "+9223372036854775807",
            "+52560000",
        ] {
            assert!(parse(input, now()).is_err(), "{input:?}");
        }
    }
}