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    /// Where `calendar.event.started` is POSTed as each occurrence starts. Only
91    /// its calendar's owners see it.
92    #[serde(default)]
93    pub webhook: Option<String>,
94    /// Signs those deliveries (verify them with `webhooks::verify`). Only on the
95    /// `create` or `update` that set `webhook`.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub webhook_secret: Option<String>,
98    #[serde(with = "chrono::serde::ts_milliseconds")]
99    pub created: DateTime<Utc>,
100    #[serde(with = "chrono::serde::ts_milliseconds")]
101    pub updated: DateTime<Utc>,
102}
103
104/// A new event. Only `title`, `start` and `end` are required.
105#[derive(Debug, Clone)]
106pub struct Draft {
107    pub title: String,
108    pub start: DateTime<Utc>,
109    pub end: DateTime<Utc>,
110    pub all_day: Option<bool>,
111    /// UTC by default.
112    pub time_zone: Option<String>,
113    pub place: Option<String>,
114    pub notes: Option<String>,
115    pub recurrence: Option<String>,
116    /// 10 minutes by default; 0 for none.
117    pub reminder: Option<u32>,
118    /// Emails to invite. Each gets an invitation.
119    pub attendees: Option<Vec<String>>,
120    /// A URL to POST `calendar.event.started` to as each occurrence starts. A
121    /// new one gets a new secret; `update` with `""` removes it.
122    pub webhook: Option<String>,
123}
124
125/// `Partial<Draft>`: what `update` changes. Unset fields stay as they are.
126#[derive(Debug, Clone, Default)]
127pub struct PartialDraft {
128    pub title: Option<String>,
129    pub start: Option<DateTime<Utc>>,
130    pub end: Option<DateTime<Utc>>,
131    pub all_day: Option<bool>,
132    pub time_zone: Option<String>,
133    pub place: Option<String>,
134    pub notes: Option<String>,
135    pub recurrence: Option<String>,
136    pub reminder: Option<u32>,
137    pub attendees: Option<Vec<String>>,
138    pub webhook: Option<String>,
139}
140
141fn draft_json(draft: PartialDraft) -> Value {
142    let mut body = Map::new();
143    let mut set = |key: &str, value: Option<Value>| {
144        if let Some(value) = value {
145            body.insert(key.to_string(), value);
146        }
147    };
148    set("title", draft.title.map(Value::from));
149    set("start", draft.start.map(|at| json!(at.timestamp_millis())));
150    set("end", draft.end.map(|at| json!(at.timestamp_millis())));
151    set("allDay", draft.all_day.map(Value::from));
152    set("timeZone", draft.time_zone.map(Value::from));
153    set("place", draft.place.map(Value::from));
154    set("notes", draft.notes.map(Value::from));
155    set("recurrence", draft.recurrence.map(Value::from));
156    set("reminder", draft.reminder.map(Value::from));
157    set("attendees", draft.attendees.map(|emails| json!(emails)));
158    set("webhook", draft.webhook.map(Value::from));
159    Value::Object(body)
160}
161
162/// Events between `from` and `to` (at most 400 days apart), one per
163/// occurrence, soonest first. With `group`, that group's calendar; otherwise
164/// yours, your groups' and the events you're invited to.
165pub async fn list(
166    authorization: &CredentialsOrApiKey,
167    from: DateTime<Utc>,
168    to: DateTime<Utc>,
169    group: Option<&Group>,
170) -> Result<Vec<Event>> {
171    let mut request = client()
172        .get(format!(
173            "{}/calendar/events?from={}&to={}",
174            crate::get_url(),
175            from.timestamp_millis(),
176            to.timestamp_millis()
177        ))
178        .header(
179            "Authorization",
180            match authorization {
181                CredentialsOrApiKey::Credentials(credentials) => {
182                    format!("Token {}", credentials.token)
183                }
184                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
185            },
186        );
187    if let Some(group) = group {
188        request = request.header("Group", &group.id);
189    }
190    let response = request.send().await?;
191    Ok(ok(response).await?.json().await?)
192}
193
194/// One event on your calendar, a group's, or one you're invited to.
195pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<Event> {
196    let response = client()
197        .get(format!(
198            "{}/calendar/events/{}",
199            crate::get_url(),
200            encode(id)
201        ))
202        .header(
203            "Authorization",
204            match authorization {
205                CredentialsOrApiKey::Credentials(credentials) => {
206                    format!("Token {}", credentials.token)
207                }
208                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
209            },
210        )
211        .send()
212        .await?;
213    Ok(ok(response).await?.json().await?)
214}
215
216/// Put an event on your calendar, or `group`'s, and email everyone it invites.
217pub async fn create(
218    authorization: &CredentialsOrApiKey,
219    draft: Draft,
220    group: Option<&Group>,
221) -> Result<Event> {
222    let mut request = client()
223        .post(format!("{}/calendar/events", crate::get_url()))
224        .header(
225            "Authorization",
226            match authorization {
227                CredentialsOrApiKey::Credentials(credentials) => {
228                    format!("Token {}", credentials.token)
229                }
230                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
231            },
232        );
233    if let Some(group) = group {
234        request = request.header("Group", &group.id);
235    }
236    let body = draft_json(PartialDraft {
237        title: Some(draft.title),
238        start: Some(draft.start),
239        end: Some(draft.end),
240        all_day: draft.all_day,
241        time_zone: draft.time_zone,
242        place: draft.place,
243        notes: draft.notes,
244        recurrence: draft.recurrence,
245        reminder: draft.reminder,
246        attendees: draft.attendees,
247        webhook: draft.webhook,
248    });
249    let response = request.json(&body).send().await?;
250    Ok(ok(response).await?.json().await?)
251}
252
253/// Change an event on your calendar or a group's. A recurring event changes as
254/// a whole. New invitees get invited; the rest hear about a new time or place.
255pub async fn update(
256    authorization: &CredentialsOrApiKey,
257    id: &str,
258    update: PartialDraft,
259) -> Result<Event> {
260    let response = client()
261        .patch(format!(
262            "{}/calendar/events/{}",
263            crate::get_url(),
264            encode(id)
265        ))
266        .header(
267            "Authorization",
268            match authorization {
269                CredentialsOrApiKey::Credentials(credentials) => {
270                    format!("Token {}", credentials.token)
271                }
272                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
273            },
274        )
275        .json(&draft_json(update))
276        .send()
277        .await?;
278    Ok(ok(response).await?.json().await?)
279}
280
281/// Remove an event from your calendar or a group's, telling everyone it
282/// invited.
283pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
284    let response = client()
285        .delete(format!(
286            "{}/calendar/events/{}",
287            crate::get_url(),
288            encode(id)
289        ))
290        .header(
291            "Authorization",
292            match authorization {
293                CredentialsOrApiKey::Credentials(credentials) => {
294                    format!("Token {}", credentials.token)
295                }
296                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
297            },
298        )
299        .send()
300        .await?;
301    ok(response).await?;
302    Ok(())
303}
304
305/// Answer an event you're invited to: `Yes`, `No` or `Maybe`.
306pub async fn respond(
307    authorization: &CredentialsOrApiKey,
308    id: &str,
309    answer: Answer,
310) -> Result<Event> {
311    let response = client()
312        .post(format!(
313            "{}/calendar/events/{}/respond",
314            crate::get_url(),
315            encode(id)
316        ))
317        .header(
318            "Authorization",
319            match authorization {
320                CredentialsOrApiKey::Credentials(credentials) => {
321                    format!("Token {}", credentials.token)
322                }
323                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
324            },
325        )
326        .json(&json!({ "response": answer }))
327        .send()
328        .await?;
329    Ok(ok(response).await?.json().await?)
330}
331
332#[derive(Deserialize)]
333struct FeedUrl {
334    url: String,
335}
336
337/// Your own secret .ics link for your calendar, or `group`'s, for Google, Apple or
338/// Outlook to subscribe to. Each person has their own link, and a group's stops
339/// working when you leave the group.
340pub async fn feed(authorization: &CredentialsOrApiKey, group: Option<&Group>) -> Result<String> {
341    let mut request = client()
342        .get(format!("{}/calendar/feed", crate::get_url()))
343        .header(
344            "Authorization",
345            match authorization {
346                CredentialsOrApiKey::Credentials(credentials) => {
347                    format!("Token {}", credentials.token)
348                }
349                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
350            },
351        );
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}
359
360/// A new .ics link of your own for your calendar, or `group`'s. Your old one stops
361/// working; nobody else's changes.
362pub async fn reset_feed(credentials: &Credentials, group: Option<&Group>) -> Result<String> {
363    let mut request = client()
364        .post(format!("{}/calendar/feed/reset", crate::get_url()))
365        .header("Authorization", format!("Token {}", credentials.token));
366    if let Some(group) = group {
367        request = request.header("Group", &group.id);
368    }
369    let response = request.send().await?;
370    let feed: FeedUrl = ok(response).await?.json().await?;
371    Ok(feed.url)
372}