BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / google_calendar / write.rs

write.rs

write.rs 6.7 KiB Download Raw
1use chrono::Datelike;
2use serde_json::{Value, json};
3
4use crate::calendar::{Attendee, NewEvent, Repeat, Reply};
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct GoogleEventDraft {
8 pub subject: String,
9 pub start: chrono::DateTime<chrono::Utc>,
10 pub end: chrono::DateTime<chrono::Utc>,
11 pub local: Option<LocalTimes>,
12 pub attendees: Vec<Attendee>,
13 pub details: String,
14 pub join_url: Option<String>,
15 pub repeat: Repeat,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct LocalTimes {
20 pub start: chrono::NaiveDateTime,
21 pub end: chrono::NaiveDateTime,
22 pub iana_zone: String,
23}
24
25const LOCAL_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S";
26
27impl From<&NewEvent> for GoogleEventDraft {
28 fn from(event: &NewEvent) -> Self {
29 GoogleEventDraft {
30 subject: event.subject.clone(),
31 start: event.start,
32 end: event.end,
33 local: event
34 .time_zone_name
35 .as_ref()
36 .and_then(|_| iana_time_zone::get_timezone().ok())
37 .map(|iana_zone| LocalTimes {
38 start: event.local_start,
39 end: event.local_end,
40 iana_zone,
41 }),
42 attendees: event.attendees.clone(),
43 details: event.details.clone(),
44 join_url: None,
45 repeat: event.repeat,
46 }
47 }
48}
49
50pub fn rrule_for_repeat(repeat: Repeat, start: chrono::NaiveDateTime) -> Option<String> {
51 match repeat {
52 Repeat::Never => None,
53 Repeat::Daily => Some("RRULE:FREQ=DAILY".to_owned()),
54 Repeat::Weekdays => Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR".to_owned()),
55 Repeat::Weekly => {
56 let day = match start.weekday() {
57 chrono::Weekday::Mon => "MO",
58 chrono::Weekday::Tue => "TU",
59 chrono::Weekday::Wed => "WE",
60 chrono::Weekday::Thu => "TH",
61 chrono::Weekday::Fri => "FR",
62 chrono::Weekday::Sat => "SA",
63 chrono::Weekday::Sun => "SU",
64 };
65 Some(format!("RRULE:FREQ=WEEKLY;BYDAY={day}"))
66 }
67 }
68}
69
70pub fn google_event_body(draft: &GoogleEventDraft) -> Value {
71 let mut description = draft.details.clone();
72 if let Some(join_url) = &draft.join_url {
73 if !description.is_empty() {
74 description.push_str("\n\n");
75 }
76 description.push_str(join_url);
77 }
78 let (start, end) = match &draft.local {
79 Some(local) => (
80 json!({
81 "dateTime": local.start.format(LOCAL_TIME_FORMAT).to_string(),
82 "timeZone": local.iana_zone,
83 }),
84 json!({
85 "dateTime": local.end.format(LOCAL_TIME_FORMAT).to_string(),
86 "timeZone": local.iana_zone,
87 }),
88 ),
89 None => (
90 json!({
91 "dateTime": draft.start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
92 "timeZone": "UTC",
93 }),
94 json!({
95 "dateTime": draft.end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
96 "timeZone": "UTC",
97 }),
98 ),
99 };
100 let series_start = draft
101 .local
102 .as_ref()
103 .map_or(draft.start.naive_utc(), |local| local.start);
104 let mut body = json!({
105 "summary": draft.subject,
106 "start": start,
107 "end": end,
108 "attendees": draft.attendees.iter().map(|attendee| json!({
109 "email": attendee.address,
110 "displayName": attendee.name,
111 })).collect::<Vec<_>>(),
112 });
113 if let Some(join_url) = &draft.join_url {
114 body["location"] = json!(join_url);
115 }
116 if !description.is_empty() {
117 body["description"] = json!(description);
118 }
119 if let Some(rrule) = rrule_for_repeat(draft.repeat, series_start) {
120 body["recurrence"] = json!([rrule]);
121 }
122 body
123}
124
125pub fn google_rsvp_status(reply: Reply) -> &'static str {
126 match reply {
127 Reply::Accept => "accepted",
128 Reply::Tentative => "tentative",
129 Reply::Decline => "declined",
130 }
131}
132
133pub fn google_rsvp_query(send_updates: bool) -> String {
134 format!("sendUpdates={}", if send_updates { "all" } else { "none" })
135}
136
137#[cfg(test)]
138mod tests {
139 use chrono::TimeZone;
140
141 use super::*;
142
143 fn draft(repeat: Repeat) -> GoogleEventDraft {
144 GoogleEventDraft {
145 subject: "Sync".into(),
146 start: chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap(),
147 end: chrono::Utc
148 .with_ymd_and_hms(2026, 11, 11, 9, 30, 0)
149 .unwrap(),
150 local: None,
151 attendees: vec![Attendee {
152 name: "Mara".into(),
153 address: "mara@example.com".into(),
154 }],
155 details: "Notes".into(),
156 join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
157 repeat,
158 }
159 }
160
161 #[test]
162 fn a_weekly_series_repeats_in_the_local_zone_on_the_local_weekday() {
163 let mut weekly = draft(Repeat::Weekly);
164 let late_monday = chrono::NaiveDate::from_ymd_opt(2026, 6, 8)
165 .unwrap()
166 .and_hms_opt(0, 30, 0)
167 .unwrap();
168 weekly.local = Some(LocalTimes {
169 start: late_monday,
170 end: late_monday + chrono::Duration::minutes(30),
171 iana_zone: "Europe/Berlin".into(),
172 });
173 let body = google_event_body(&weekly);
174 assert_eq!(body["start"]["dateTime"], "2026-06-08T00:30:00");
175 assert_eq!(body["start"]["timeZone"], "Europe/Berlin");
176 assert_eq!(body["recurrence"][0], "RRULE:FREQ=WEEKLY;BYDAY=MO");
177 }
178
179 #[test]
180 fn body_puts_join_link_in_location_and_description() {
181 let body = google_event_body(&draft(Repeat::Never));
182 assert_eq!(
183 body["location"],
184 "https://teams.microsoft.com/l/meetup-join/x"
185 );
186 assert!(
187 body["description"]
188 .as_str()
189 .unwrap()
190 .contains("teams.microsoft.com")
191 );
192 assert!(body.get("recurrence").is_none());
193 }
194
195 #[test]
196 fn weekdays_rrule_and_rsvp_query() {
197 assert_eq!(
198 rrule_for_repeat(
199 Repeat::Weekdays,
200 chrono::Utc
201 .with_ymd_and_hms(2026, 11, 11, 9, 0, 0)
202 .unwrap()
203 .naive_utc()
204 )
205 .as_deref(),
206 Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR")
207 );
208 assert_eq!(google_rsvp_status(Reply::Decline), "declined");
209 assert_eq!(google_rsvp_query(true), "sendUpdates=all");
210 assert_eq!(google_rsvp_query(false), "sendUpdates=none");
211 }
212}