Skip to main content

fauna_api/
calendar.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value, json};
4
5use crate::authentification::{Credentials, CredentialsOrApiKey};
6use crate::error::Result;
7use crate::groups::Group;
8use crate::http::{client, encode, ok};
9
10/// An invitee's answer. Everyone starts at `Invited`.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "lowercase")]
13pub enum Answer {
14    Invited,
15    Yes,
16    No,
17    Maybe,
18}
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct Attendee {
22    pub email: String,
23    pub response: Answer,
24}
25
26/// Whose calendar an event is on.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "lowercase")]
29pub enum CalendarKind {
30    Person,
31    Group,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct Calendar {
36    pub kind: CalendarKind,
37    pub id: String,
38    pub name: String,
39}
40
41/// A linked calendar an event syncs from.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(rename_all = "lowercase")]
44pub enum Source {
45    Google,
46    Microsoft,
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase")]
51pub struct Event {
52    pub id: String,
53    /// The calendar it's on: yours, a group's, or whoever invited you.
54    pub calendar: Calendar,
55    pub title: String,
56    #[serde(default)]
57    pub notes: String,
58    #[serde(default)]
59    pub place: String,
60    /// For a recurring event in a list, this occurrence's.
61    #[serde(with = "chrono::serde::ts_milliseconds")]
62    pub start: DateTime<Utc>,
63    #[serde(with = "chrono::serde::ts_milliseconds")]
64    pub end: DateTime<Utc>,
65    #[serde(default)]
66    pub all_day: bool,
67    /// An IANA time zone, like America/New_York. A recurring event repeats on
68    /// its clock.
69    #[serde(default)]
70    pub time_zone: String,
71    /// An RRULE without its prefix, like FREQ=WEEKLY;BYDAY=MO. Empty for a one
72    /// off.
73    #[serde(default)]
74    pub recurrence: String,
75    /// Minutes before each start to email a reminder; 0 for none.
76    #[serde(default)]
77    pub reminder: u32,
78    #[serde(default)]
79    pub attendees: Vec<Attendee>,
80    /// A linked Google or Outlook calendar it syncs from, or `None` for Fauna's
81    /// own.
82    #[serde(default)]
83    pub source: Option<Source>,
84    /// You can change it: it's on your calendar or one of your groups'.
85    #[serde(default)]
86    pub editable: bool,
87    /// Your answer, when you're invited.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub response: Option<Answer>,
90    #[serde(with = "chrono::serde::ts_milliseconds")]
91    pub created: DateTime<Utc>,
92    #[serde(with = "chrono::serde::ts_milliseconds")]
93    pub updated: DateTime<Utc>,
94}
95
96/// A new event. Only `title`, `start` and `end` are required.
97#[derive(Debug, Clone)]
98pub struct Draft {
99    pub title: String,
100    pub start: DateTime<Utc>,
101    pub end: DateTime<Utc>,
102    pub all_day: Option<bool>,
103    /// UTC by default.
104    pub time_zone: Option<String>,
105    pub place: Option<String>,
106    pub notes: Option<String>,
107    pub recurrence: Option<String>,
108    /// 10 minutes by default; 0 for none.
109    pub reminder: Option<u32>,
110    /// Emails to invite. Each gets an invitation.
111    pub attendees: Option<Vec<String>>,
112}
113
114/// `Partial<Draft>`: what `update` changes. Unset fields stay as they are.
115#[derive(Debug, Clone, Default)]
116pub struct PartialDraft {
117    pub title: Option<String>,
118    pub start: Option<DateTime<Utc>>,
119    pub end: Option<DateTime<Utc>>,
120    pub all_day: Option<bool>,
121    pub time_zone: Option<String>,
122    pub place: Option<String>,
123    pub notes: Option<String>,
124    pub recurrence: Option<String>,
125    pub reminder: Option<u32>,
126    pub attendees: Option<Vec<String>>,
127}
128
129fn draft_json(draft: PartialDraft) -> Value {
130    let mut body = Map::new();
131    let mut set = |key: &str, value: Option<Value>| {
132        if let Some(value) = value {
133            body.insert(key.to_string(), value);
134        }
135    };
136    set("title", draft.title.map(Value::from));
137    set("start", draft.start.map(|at| json!(at.timestamp_millis())));
138    set("end", draft.end.map(|at| json!(at.timestamp_millis())));
139    set("allDay", draft.all_day.map(Value::from));
140    set("timeZone", draft.time_zone.map(Value::from));
141    set("place", draft.place.map(Value::from));
142    set("notes", draft.notes.map(Value::from));
143    set("recurrence", draft.recurrence.map(Value::from));
144    set("reminder", draft.reminder.map(Value::from));
145    set("attendees", draft.attendees.map(|emails| json!(emails)));
146    Value::Object(body)
147}
148
149/// Events between `from` and `to` (at most 400 days apart), one per
150/// occurrence, soonest first. With `group`, that group's calendar; otherwise
151/// yours, your groups' and the events you're invited to.
152pub async fn list(
153    authorization: &CredentialsOrApiKey,
154    from: DateTime<Utc>,
155    to: DateTime<Utc>,
156    group: Option<&Group>,
157) -> Result<Vec<Event>> {
158    let mut request = client()
159        .get(format!(
160            "{}/calendar/events?from={}&to={}",
161            crate::get_url(),
162            from.timestamp_millis(),
163            to.timestamp_millis()
164        ))
165        .header(
166            "Authorization",
167            match authorization {
168                CredentialsOrApiKey::Credentials(credentials) => {
169                    format!("Token {}", credentials.token)
170                }
171                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
172            },
173        );
174    if let Some(group) = group {
175        request = request.header("Group", &group.id);
176    }
177    let response = request.send().await?;
178    Ok(ok(response).await?.json().await?)
179}
180
181/// One event on your calendar, a group's, or one you're invited to.
182pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<Event> {
183    let response = client()
184        .get(format!(
185            "{}/calendar/events/{}",
186            crate::get_url(),
187            encode(id)
188        ))
189        .header(
190            "Authorization",
191            match authorization {
192                CredentialsOrApiKey::Credentials(credentials) => {
193                    format!("Token {}", credentials.token)
194                }
195                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
196            },
197        )
198        .send()
199        .await?;
200    Ok(ok(response).await?.json().await?)
201}
202
203/// Put an event on your calendar, or `group`'s, and email everyone it invites.
204pub async fn create(
205    authorization: &CredentialsOrApiKey,
206    draft: Draft,
207    group: Option<&Group>,
208) -> Result<Event> {
209    let mut request = client()
210        .post(format!("{}/calendar/events", crate::get_url()))
211        .header(
212            "Authorization",
213            match authorization {
214                CredentialsOrApiKey::Credentials(credentials) => {
215                    format!("Token {}", credentials.token)
216                }
217                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
218            },
219        );
220    if let Some(group) = group {
221        request = request.header("Group", &group.id);
222    }
223    let body = draft_json(PartialDraft {
224        title: Some(draft.title),
225        start: Some(draft.start),
226        end: Some(draft.end),
227        all_day: draft.all_day,
228        time_zone: draft.time_zone,
229        place: draft.place,
230        notes: draft.notes,
231        recurrence: draft.recurrence,
232        reminder: draft.reminder,
233        attendees: draft.attendees,
234    });
235    let response = request.json(&body).send().await?;
236    Ok(ok(response).await?.json().await?)
237}
238
239/// Change an event on your calendar or a group's. A recurring event changes as
240/// a whole. New invitees get invited; the rest hear about a new time or place.
241pub async fn update(
242    authorization: &CredentialsOrApiKey,
243    id: &str,
244    update: PartialDraft,
245) -> Result<Event> {
246    let response = client()
247        .patch(format!(
248            "{}/calendar/events/{}",
249            crate::get_url(),
250            encode(id)
251        ))
252        .header(
253            "Authorization",
254            match authorization {
255                CredentialsOrApiKey::Credentials(credentials) => {
256                    format!("Token {}", credentials.token)
257                }
258                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
259            },
260        )
261        .json(&draft_json(update))
262        .send()
263        .await?;
264    Ok(ok(response).await?.json().await?)
265}
266
267/// Remove an event from your calendar or a group's, telling everyone it
268/// invited.
269pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
270    let response = client()
271        .delete(format!(
272            "{}/calendar/events/{}",
273            crate::get_url(),
274            encode(id)
275        ))
276        .header(
277            "Authorization",
278            match authorization {
279                CredentialsOrApiKey::Credentials(credentials) => {
280                    format!("Token {}", credentials.token)
281                }
282                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
283            },
284        )
285        .send()
286        .await?;
287    ok(response).await?;
288    Ok(())
289}
290
291/// Answer an event you're invited to: `Yes`, `No` or `Maybe`.
292pub async fn respond(
293    authorization: &CredentialsOrApiKey,
294    id: &str,
295    answer: Answer,
296) -> Result<Event> {
297    let response = client()
298        .post(format!(
299            "{}/calendar/events/{}/respond",
300            crate::get_url(),
301            encode(id)
302        ))
303        .header(
304            "Authorization",
305            match authorization {
306                CredentialsOrApiKey::Credentials(credentials) => {
307                    format!("Token {}", credentials.token)
308                }
309                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
310            },
311        )
312        .json(&json!({ "response": answer }))
313        .send()
314        .await?;
315    Ok(ok(response).await?.json().await?)
316}
317
318#[derive(Deserialize)]
319struct FeedUrl {
320    url: String,
321}
322
323/// Your own secret .ics link for your calendar, or `group`'s, for Google, Apple or
324/// Outlook to subscribe to. Each person has their own link, and a group's stops
325/// working when you leave the group.
326pub async fn feed(authorization: &CredentialsOrApiKey, group: Option<&Group>) -> Result<String> {
327    let mut request = client()
328        .get(format!("{}/calendar/feed", crate::get_url()))
329        .header(
330            "Authorization",
331            match authorization {
332                CredentialsOrApiKey::Credentials(credentials) => {
333                    format!("Token {}", credentials.token)
334                }
335                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
336            },
337        );
338    if let Some(group) = group {
339        request = request.header("Group", &group.id);
340    }
341    let response = request.send().await?;
342    let feed: FeedUrl = ok(response).await?.json().await?;
343    Ok(feed.url)
344}
345
346/// A new .ics link of your own for your calendar, or `group`'s. Your old one stops
347/// working; nobody else's changes.
348pub async fn reset_feed(credentials: &Credentials, group: Option<&Group>) -> Result<String> {
349    let mut request = client()
350        .post(format!("{}/calendar/feed/reset", crate::get_url()))
351        .header("Authorization", format!("Token {}", credentials.token));
352    if let Some(group) = group {
353        request = request.header("Group", &group.id);
354    }
355    let response = request.send().await?;
356    let feed: FeedUrl = ok(response).await?.json().await?;
357    Ok(feed.url)
358}