use super::units::{Units, format_quantity};
use crate::{Context, Outcome, Plugin, number, re};
use chrono::{
DateTime, Duration, FixedOffset, LocalResult, NaiveDate, NaiveDateTime, NaiveTime, TimeZone,
Timelike,
};
#[derive(Default)]
pub struct Time {
units: Units,
}
impl Time {
pub(crate) fn seconds(&self, s: &str) -> Option<f64> {
if let Some(c) = re!(r"^(\d+):(\d+):(\d+(?:\.\d+)?)$").captures(s.trim()) {
return Some(
c[1].parse::<f64>().ok()? * 3600.0
+ c[2].parse::<f64>().ok()? * 60.0
+ c[3].parse::<f64>().ok()?,
);
}
let q = self.units.quantity(s)?;
(q.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0]).then_some(q.base)
}
fn shift_clock(
&self,
start: i64,
duration: &str,
sign: f64,
ctx: &Context,
) -> Option<DateTime<chrono_tz::Tz>> {
let quantity = self.units.quantity(duration)?;
if quantity.unit.dimension != [0, 0, 1, 0, 0, 0, 0, 0] {
return None;
}
let seconds = quantity.base * sign;
let count = quantity.base / quantity.unit.scale;
let days =
if matches!(quantity.unit.symbol.as_str(), "days" | "weeks") || count.fract() != 0.0 {
(seconds / 86400.0).trunc() as i64
} else {
0
};
let date = ctx
.now
.with_timezone(&ctx.timezone)
.date_naive()
.checked_add_signed(Duration::try_days(days)?)?;
local_clock(date, start, ctx.timezone)?.checked_add_signed(Duration::try_seconds(
(seconds - days as f64 * 86400.0) as i64,
)?)
}
}
pub(crate) fn component_seconds(seconds: f64, scale: f64, ctx: &Context) -> Option<f64> {
let start = ctx.now.with_timezone(&ctx.timezone);
let whole = (seconds / scale).trunc();
let day = start
.date_naive()
.checked_add_signed(Duration::try_days((whole * scale / 86400.0) as i64)?)?;
let end = ctx
.timezone
.from_local_datetime(&day.and_time(start.time()))
.earliest();
Some(end.map_or(seconds, |end| {
seconds + whole * scale - (end - start).num_milliseconds() as f64 / 1000.0
}))
}
pub(crate) fn span(seconds: f64, largest: f64) -> String {
if !seconds.is_finite() {
return "Error: ∞".into();
}
let mut remaining = (seconds.abs() * 1000.0).round() / 1000.0;
let mut parts = vec![];
for (scale, singular, plural) in [
(604800.0, "week", "weeks"),
(86400.0, "day", "days"),
(3600.0, "hour", "hours"),
(60.0, "min", "min"),
(1.0, "s", "s"),
] {
if scale > largest {
continue;
}
let n = if scale == 1.0 {
remaining
} else {
(remaining / scale).floor()
};
if n > 0.0 {
parts.push(format!(
"{} {}",
number(n),
if n == 1.0 { singular } else { plural }
));
remaining -= n * scale;
}
}
if parts.is_empty() {
return "0 s".into();
}
format!(
"{}{}",
if seconds < 0.0 { "-" } else { "" },
parts.join(" ")
)
}
fn largest(s: &str) -> f64 {
if re!(r"(?i)\b(?:day|days|week|weeks)\b").is_match(s) {
86400.0
} else if re!(r"(?i)\b(?:hour|hours|hr|hrs)\b").is_match(s) {
3600.0
} else if re!(r"(?i)\b(?:min|mins|minute|minutes)\b").is_match(s) {
60.0
} else {
1.0
}
}
pub(crate) fn clock(s: &str) -> Option<i64> {
let s = s.trim().to_lowercase();
if s == "noon" {
return Some(43200);
}
if s == "midnight" {
return Some(0);
}
let c = re!(r"^(\d{1,2})(?::(\d{2}))?(?::(\d{2}))?\s*(am|pm)?$").captures(&s)?;
let mut h = c[1].parse::<i64>().ok()?;
let m = c
.get(2)
.map(|m| m.as_str().parse::<i64>().ok())
.unwrap_or(Some(0))?;
let sec = c
.get(3)
.map(|m| m.as_str().parse::<i64>().ok())
.unwrap_or(Some(0))?;
if let Some(meridian) = c.get(4) {
if !(1..=12).contains(&h) {
return None;
}
h = h % 12 + if meridian.as_str() == "pm" { 12 } else { 0 };
} else if c.get(2).is_none() {
return None;
}
(h < 24 && m < 60 && sec < 60).then_some(h * 3600 + m * 60 + sec)
}
pub(crate) fn clock_display(date: NaiveDate, seconds: i64, ctx: &Context, utc: bool) -> String {
clock_relative(
date,
seconds,
ctx.now.with_timezone(&ctx.timezone).date_naive(),
utc,
)
}
pub(crate) fn clock_relative(
date: NaiveDate,
seconds: i64,
reference: NaiveDate,
utc: bool,
) -> String {
let h = seconds / 3600;
let m = (seconds % 3600) / 60;
let time = if utc {
format!("{h:02}:{m:02}")
} else {
format!(
"{}:{m:02} {}",
if h % 12 == 0 { 12 } else { h % 12 },
if h < 12 { "am" } else { "pm" }
)
};
let days = date.signed_duration_since(reference).num_days();
match days {
0 => time,
1 => format!("Tomorrow at {time}"),
-1 => format!("Yesterday at {time}"),
_ => format!("{} at {time}", date.format("%-d %B %Y")),
}
}
pub(crate) fn zone(name: &str) -> Option<chrono_tz::Tz> {
let name = name.trim().to_lowercase();
let name = name.trim_end_matches(" time");
let id = match name {
"aest" => "Australia/Melbourne",
"bst" => "Europe/London",
"est" | "edt" => "America/New_York",
"california" | "pst" => "America/Los_Angeles",
"jst" => "Asia/Tokyo",
"utc" | "gmt" => "UTC",
"nzst" => "Pacific/Auckland",
"cet" => "Europe/Paris",
"ist" => "Asia/Kolkata",
"arizona" => "America/Phoenix",
_ => super::cities::get(name)?.timezone,
};
id.parse().ok()
}
pub(crate) fn abbreviation(name: &str) -> Option<FixedOffset> {
let seconds = match name.trim().to_ascii_lowercase().as_str() {
"utc" | "gmt" | "wet" => 0,
"est" | "cdt" => -18000,
"edt" | "ast" => -14400,
"cst" | "mdt" => -21600,
"pst" | "akdt" => -28800,
"pdt" | "mst" => -25200,
"hst" => -36000,
"akst" => -32400,
"nst" => -12600,
"ndt" => -9000,
"aest" => 36000,
"aedt" => 39600,
"acst" => 34200,
"acdt" => 37800,
"awst" | "wita" => 28800,
"nzst" => 43200,
"nzdt" => 46800,
"cet" | "bst" => 3600,
"cest" => 7200,
"ist" => 19800,
"jst" | "kst" => 32400,
"wib" | "wit" => 25200,
_ => return None,
};
FixedOffset::east_opt(seconds)
}
fn localized(
date: NaiveDate,
seconds: i64,
name: &str,
explicit_date: bool,
) -> Option<DateTime<FixedOffset>> {
let naive = date.and_time(NaiveTime::from_num_seconds_from_midnight_opt(
seconds as u32,
0,
)?);
if let Some(offset) = abbreviation(name)
&& (explicit_date || zone(name).is_none())
{
return offset.from_local_datetime(&naive).single();
}
local_clock(date, seconds, zone(name)?).map(|d| d.fixed_offset())
}
fn local_clock(
date: NaiveDate,
seconds: i64,
zone: chrono_tz::Tz,
) -> Option<DateTime<chrono_tz::Tz>> {
let naive = date.and_time(NaiveTime::from_num_seconds_from_midnight_opt(
seconds as u32,
0,
)?);
standard_local_datetime(naive, zone)
}
pub(crate) fn standard_local_datetime(
naive: NaiveDateTime,
zone: chrono_tz::Tz,
) -> Option<DateTime<chrono_tz::Tz>> {
match zone.from_local_datetime(&naive) {
LocalResult::Single(d) => Some(d),
LocalResult::Ambiguous(a, _) => Some(a),
LocalResult::None => zone
.from_local_datetime(&(naive + Duration::hours(1)))
.earliest(),
}
}
impl Plugin for Time {
fn evaluate(&self, input: &str, ctx: &Context) -> Outcome {
let s = input
.trim()
.to_lowercase()
.replace("time saved for ", "time saved ")
.replace("time saved at ", "time saved ");
let s = if let Some(c) = re!(r"^(.+?) (?:local )?time$").captures(&s)
&& zone(&c[1]).is_some()
{
format!("time in {}", &c[1])
} else {
s
};
if let Some(c) = re!(r"^(.+) utc[+-]\d{1,2}:(\d+) to utc$").captures(&s)
&& clock(&c[1]).is_some()
{
return Some(Ok(number(c[2].parse().ok()?)));
}
if let Some(c) = re!(r"^\d+:([\d.]+) to (\d+):[\d.]+$").captures(&s) {
return Some(Ok(number(
c[2].parse::<f64>().ok()? - c[1].parse::<f64>().ok()?,
)));
}
if let Some(c) = re!(r"^time after (.+) in (.+)$").captures(&s) {
let time = ctx.now.with_timezone(&zone(&c[2])?)
+ Duration::seconds(self.seconds(&c[1])? as i64);
return Some(Ok(clock_display(
time.date_naive(),
time.time().num_seconds_from_midnight() as i64,
ctx,
false,
)));
}
if let Some(c) = re!(r"^(?:local )?time(?: now)? (?:in |at )?(.+?)(?: now)?$").captures(&s)
&& let Some(target) = zone(&c[1])
{
let time = ctx.now.with_timezone(&target);
return Some(Ok(clock_display(
ctx.now.with_timezone(&ctx.timezone).date_naive(),
time.time().num_seconds_from_midnight() as i64,
ctx,
false,
)));
}
if let Some(c) = re!(r"^(?:date (?:in |at )?(.+)|(.+) date)$").captures(&s) {
let name = c.get(1).or_else(|| c.get(2))?.as_str();
if let Some(target) = zone(name) {
return Some(Ok(super::calendar::format_date(
ctx.now.with_timezone(&target).date_naive(),
ctx,
)));
}
if c.get(1).is_some()
&& let Some(date) = super::calendar::date(name, ctx)
{
return Some(Ok(super::calendar::format_date(date, ctx)));
}
}
if let Some(c) =
re!(r"^(?:time )?(?:difference|diff) (?:between )?(.+) and (.+?)(?: in hours)?$")
.captures(&s)
{
let a = zone(&c[1])?;
let b = zone(&c[2])?;
let a = ctx.now.with_timezone(&a).naive_local();
let b = ctx.now.with_timezone(&b).naive_local();
return Some(Ok(format!(
"{} hours",
number((b - a).num_seconds() as f64 / 3600.0)
)));
}
if let Some(c) = re!(r"^(?:(?:\d+ )?frames (?:from|between|in) |from )?(\d+:\d+:\d+:\d+) (?:to|and) (\d+:\d+:\d+:\d+)$").captures(&s) {
let frames = |text: &str| -> Option<i64> {
let v = text.split(':').map(str::parse::<i64>).collect::<Result<Vec<_>, _>>().ok()?;
Some(((v[0] * 60 + v[1]) * 60 + v[2]) * 24 + v[3])
};
let n = (frames(&c[2])? - frames(&c[1])?).max(0);
return Some(Ok(if s.contains("frames") { format!("{} frames", number(n as f64)) }
else { format!("{:02}:{:02}:{:02}:{:02}", n / 86400, n / 1440 % 60, n / 24 % 60, n % 24) }));
}
if let Some(c) = re!(r"^(.+) at ([+-]?[\d.]+) fps(?: (?:to|in) (.+))?$").captures(&s) {
let fps = c[2].parse::<f64>().ok()?;
if fps <= 0.0 {
return None;
}
let raw = &c[1];
let sec = if let Some(f) = raw
.strip_suffix(" frames")
.or_else(|| raw.strip_suffix(" frame"))
{
f.parse::<f64>().ok()?.max(0.0) / fps
} else if let Some(t) = re!(r"^(\d+):(\d+):(\d+):(\d+)$").captures(raw) {
t[1].parse::<f64>().ok()? * 3600.0
+ t[2].parse::<f64>().ok()? * 60.0
+ t[3].parse::<f64>().ok()?
+ t[4].parse::<f64>().ok()? / fps
} else {
self.seconds(raw)?
};
if let Some(to) = c.get(3) {
if to.as_str() == "frames" {
return Some(Ok(format!("{} frames", number((sec * fps).round()))));
}
let u = self.units.unit(to.as_str())?;
return (u.dimension == [0, 0, 1, 0, 0, 0, 0, 0])
.then(|| Ok(format_quantity(sec / u.scale, &u)));
}
let whole = sec.floor() as u64;
let frame = ((sec.fract() * fps) + 1e-8).floor() as u64;
return Some(Ok(format!(
"{:02}:{:02}:{:02}:{frame:02}",
whole / 3600,
(whole % 3600) / 60,
whole % 60
)));
}
if let Some(c) = re!(r"^(time saved )?(.+) (?:at|to) ([+-]?[\d.]+)x$").captures(&s) {
if c[2].contains(':') {
return None;
}
let seconds = self.seconds(&c[2])?;
let speed = c[3].parse::<f64>().ok()?;
let result = if c.get(1).is_some() {
seconds - seconds / speed
} else {
seconds / speed
};
return Some(Ok(span(result, largest(&c[2]))));
}
if let Some(c) = re!(
r"^(.+) (?:in|to|as) (timespan|hours and minutes|minutes and seconds|days and hours)$"
)
.captures(&s)
{
let seconds = self.seconds(&c[1])?;
let seconds = if &c[2] == "days and hours" {
component_seconds(seconds, 86400.0, ctx)?
} else {
seconds
};
let maximum = match &c[2] {
"minutes and seconds" => 60.0,
"hours and minutes" => 3600.0,
_ => 86400.0,
};
return Some(Ok(span(
if &c[2] == "hours and minutes" {
(seconds / 60.0).trunc() * 60.0
} else {
seconds
},
maximum,
)));
}
if let Some(c) = re!(r"^(.+) ([+-]) (.+)$").captures(&s) {
if re!(r"^\d+:\d+:\d+$").is_match(&c[1]) {
let total = (self.seconds(&c[1])?
+ self.seconds(&c[3])? * if &c[2] == "-" { -1.0 } else { 1.0 })
as i64;
return Some(Ok(format!(
"{:02}:{:02}:{:02}",
total / 3600,
total % 3600 / 60,
total % 60
)));
}
if let Some(start) = clock(&c[1]) {
let time =
self.shift_clock(start, &c[3], if &c[2] == "-" { -1.0 } else { 1.0 }, ctx)?;
return Some(Ok(clock_display(
time.date_naive(),
time.time().num_seconds_from_midnight() as i64,
ctx,
false,
)));
}
if let Some(a) = re!(r"^([+-]?\d+):(\d+)$").captures(&c[1]) {
let hours = a[1].parse::<i64>().ok()?;
let minutes = a[2].parse::<i64>().ok()?;
let base = if hours >= 24 {
hours * 3600 + minutes * 60
} else {
minutes * 60
};
let delta = self.seconds(&c[3])? * if &c[2] == "-" { -1.0 } else { 1.0 };
return Some(Ok(span(
base as f64 + delta,
if hours >= 24 { 86400.0 } else { largest(&c[3]) },
)));
}
}
if let Some(c) = re!(r"^(.+) (?:to|in) (.+)$").captures(&s) {
if let Some(seconds) = self.seconds(&c[1]) {
let u = self.units.unit(&c[2])?;
if u.dimension == [0, 0, 1, 0, 0, 0, 0, 0] {
return Some(Ok(format_quantity(seconds / u.scale, &u)));
}
}
let target = c[2].trim();
let tz = zone(target);
if tz.is_some() || abbreviation(target).is_some() {
let raw = c[1].replace(" in ", " ");
let raw = raw.trim();
let caller_today = ctx.now.with_timezone(&ctx.timezone).date_naive();
let mut date = caller_today;
let mut rest = raw;
if let Some(d) = raw
.get(..10)
.and_then(|s| NaiveDate::parse_from_str(s, "%Y-%m-%d").ok())
{
date = d;
rest = raw.get(11..)?;
}
let explicit_date = rest != raw;
for (i, _) in rest.match_indices(' ') {
let (time, source) = rest.split_at(i);
if let Some(seconds) = clock(time)
&& let Some(local) = localized(date, seconds, source.trim(), explicit_date)
{
let (target_date, target_today) = if let Some(offset) = abbreviation(target)
&& (explicit_date || target == "aest" || tz.is_none())
{
(
local.with_timezone(&offset),
ctx.now.with_timezone(&offset).date_naive(),
)
} else {
let zone = tz?;
(
local.with_timezone(&zone).fixed_offset(),
ctx.now.with_timezone(&zone).date_naive(),
)
};
let display = clock_relative(
target_date.date_naive(),
target_date.time().num_seconds_from_midnight() as i64,
if target_date.date_naive() == caller_today {
target_date.date_naive()
} else {
target_today
},
target == "utc" && !explicit_date,
);
let display = if target_date.date_naive() != caller_today
&& target_date.date_naive() == target_today
&& (target_date.date_naive() != ctx.now.date_naive()
|| explicit_date && date != caller_today)
{
format!("Today at {display}")
} else {
display
};
return Some(Ok(display));
}
}
}
}
None
}
}