1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//! Time input for scheduled sends, reminders and snoozes.
//!
//! `When` is plain data here. Turning a local time plus an IANA zone into UTC needs a time-zone
//! database, so that conversion lives in the server (`sew-proto` carries none). Each route that
//! takes a `When` adds its own min/max bounds relative to the request time.
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::error::{Validate, ValidationError};
use crate::time::{LocalDateTime, Timestamp};
/// The local wall-clock format: `YYYY-MM-DDTHH:MM` (no seconds, no offset), as a strftime
/// pattern. [`LocalDateTime::parse`] reads it.
pub const LOCAL_DATE_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M";
/// Longest IANA time-zone name accepted.
pub const TIMEZONE_MAX_LEN: usize = 64;
/// "At what time": an absolute instant, a local wall-clock time in a named zone, or a delay.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum When {
/// An absolute instant.
At {
/// RFC 3339 with `Z` or an offset.
at: Timestamp,
},
/// A local wall-clock time.
Local {
/// `YYYY-MM-DDTHH:MM`, no seconds, no offset.
date_time: String,
/// An IANA zone name; absent means the member's profile zone, then UTC.
#[serde(default, skip_serializing_if = "Option::is_none")]
timezone: Option<String>,
},
/// A delay from the request's clock time.
In {
/// Milliseconds from now.
ms: u64,
},
}
/// Whether `s` looks like an IANA zone name (`Area/City`, `UTC`, `Etc/GMT+5`). Whether the
/// zone exists is checked by the server.
pub fn is_timezone_name(s: &str) -> bool {
(1..=TIMEZONE_MAX_LEN).contains(&s.len())
&& s.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'/' | b'_' | b'-' | b'+'))
&& !s.starts_with('/')
&& !s.ends_with('/')
&& !s.contains("//")
}
impl When {
/// The parsed local time for `Local`.
pub fn local_date_time(&self) -> Option<LocalDateTime> {
match self {
When::Local { date_time, .. } => LocalDateTime::parse(date_time),
_ => None,
}
}
}
impl Validate for When {
fn validate(&self) -> Result<(), ValidationError> {
match self {
When::At { .. } | When::In { .. } => Ok(()),
When::Local {
date_time,
timezone,
} => {
if date_time.len() != 16 || self.local_date_time().is_none() {
return Err(ValidationError::invalid(
"date_time",
"bad_local_time: expected YYYY-MM-DDTHH:MM",
));
}
if let Some(tz) = timezone
&& !is_timezone_name(tz)
{
return Err(ValidationError::invalid(
"timezone",
"bad_timezone: expected an IANA zone name",
));
}
Ok(())
}
}
}
}