fauna-api 1.0.786

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

use crate::authentification::{Credentials, CredentialsOrApiKey};
use crate::error::Result;
use crate::groups::Group;
use crate::http::{client, encode, ok};

/// An invitee's answer. Everyone starts at `Invited`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Answer {
    Invited,
    Yes,
    No,
    Maybe,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Attendee {
    pub email: String,
    pub response: Answer,
}

/// Whose calendar an event is on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CalendarKind {
    Person,
    Group,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Calendar {
    pub kind: CalendarKind,
    pub id: String,
    pub name: String,
}

/// A linked calendar an event syncs from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Source {
    Google,
    Microsoft,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Event {
    pub id: String,
    /// The calendar it's on: yours, a group's, or whoever invited you.
    pub calendar: Calendar,
    pub title: String,
    #[serde(default)]
    pub notes: String,
    #[serde(default)]
    pub place: String,
    /// For a recurring event in a list, this occurrence's.
    #[serde(with = "chrono::serde::ts_milliseconds")]
    pub start: DateTime<Utc>,
    #[serde(with = "chrono::serde::ts_milliseconds")]
    pub end: DateTime<Utc>,
    #[serde(default)]
    pub all_day: bool,
    /// An IANA time zone, like America/New_York. A recurring event repeats on
    /// its clock.
    #[serde(default)]
    pub time_zone: String,
    /// An RRULE without its prefix, like FREQ=WEEKLY;BYDAY=MO. Empty for a one
    /// off.
    #[serde(default)]
    pub recurrence: String,
    /// Minutes before each start to email a reminder; 0 for none.
    #[serde(default)]
    pub reminder: u32,
    #[serde(default)]
    pub attendees: Vec<Attendee>,
    /// A linked Google or Outlook calendar it syncs from, or `None` for Fauna's
    /// own.
    #[serde(default)]
    pub source: Option<Source>,
    /// You can change it: it's on your calendar or one of your groups'.
    #[serde(default)]
    pub editable: bool,
    /// Your answer, when you're invited.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub response: Option<Answer>,
    /// Where `calendar.event.started` is POSTed as each occurrence starts. Only
    /// its calendar's owners see it.
    #[serde(default)]
    pub webhook: Option<String>,
    /// Signs those deliveries (verify them with `webhooks::verify`). Only on the
    /// `create` or `update` that set `webhook`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub webhook_secret: Option<String>,
    #[serde(with = "chrono::serde::ts_milliseconds")]
    pub created: DateTime<Utc>,
    #[serde(with = "chrono::serde::ts_milliseconds")]
    pub updated: DateTime<Utc>,
}

/// A new event. Only `title`, `start` and `end` are required.
#[derive(Debug, Clone)]
pub struct Draft {
    pub title: String,
    pub start: DateTime<Utc>,
    pub end: DateTime<Utc>,
    pub all_day: Option<bool>,
    /// UTC by default.
    pub time_zone: Option<String>,
    pub place: Option<String>,
    pub notes: Option<String>,
    pub recurrence: Option<String>,
    /// 10 minutes by default; 0 for none.
    pub reminder: Option<u32>,
    /// Emails to invite. Each gets an invitation.
    pub attendees: Option<Vec<String>>,
    /// A URL to POST `calendar.event.started` to as each occurrence starts. A
    /// new one gets a new secret; `update` with `""` removes it.
    pub webhook: Option<String>,
}

/// `Partial<Draft>`: what `update` changes. Unset fields stay as they are.
#[derive(Debug, Clone, Default)]
pub struct PartialDraft {
    pub title: Option<String>,
    pub start: Option<DateTime<Utc>>,
    pub end: Option<DateTime<Utc>>,
    pub all_day: Option<bool>,
    pub time_zone: Option<String>,
    pub place: Option<String>,
    pub notes: Option<String>,
    pub recurrence: Option<String>,
    pub reminder: Option<u32>,
    pub attendees: Option<Vec<String>>,
    pub webhook: Option<String>,
}

fn draft_json(draft: PartialDraft) -> Value {
    let mut body = Map::new();
    let mut set = |key: &str, value: Option<Value>| {
        if let Some(value) = value {
            body.insert(key.to_string(), value);
        }
    };
    set("title", draft.title.map(Value::from));
    set("start", draft.start.map(|at| json!(at.timestamp_millis())));
    set("end", draft.end.map(|at| json!(at.timestamp_millis())));
    set("allDay", draft.all_day.map(Value::from));
    set("timeZone", draft.time_zone.map(Value::from));
    set("place", draft.place.map(Value::from));
    set("notes", draft.notes.map(Value::from));
    set("recurrence", draft.recurrence.map(Value::from));
    set("reminder", draft.reminder.map(Value::from));
    set("attendees", draft.attendees.map(|emails| json!(emails)));
    set("webhook", draft.webhook.map(Value::from));
    Value::Object(body)
}

/// Events between `from` and `to` (at most 400 days apart), one per
/// occurrence, soonest first. With `group`, that group's calendar; otherwise
/// yours, your groups' and the events you're invited to.
pub async fn list(
    authorization: &CredentialsOrApiKey,
    from: DateTime<Utc>,
    to: DateTime<Utc>,
    group: Option<&Group>,
) -> Result<Vec<Event>> {
    let mut request = client()
        .get(format!(
            "{}/calendar/events?from={}&to={}",
            crate::get_url(),
            from.timestamp_millis(),
            to.timestamp_millis()
        ))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request.send().await?;
    Ok(ok(response).await?.json().await?)
}

/// One event on your calendar, a group's, or one you're invited to.
pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<Event> {
    let response = client()
        .get(format!(
            "{}/calendar/events/{}",
            crate::get_url(),
            encode(id)
        ))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Put an event on your calendar, or `group`'s, and email everyone it invites.
pub async fn create(
    authorization: &CredentialsOrApiKey,
    draft: Draft,
    group: Option<&Group>,
) -> Result<Event> {
    let mut request = client()
        .post(format!("{}/calendar/events", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let body = draft_json(PartialDraft {
        title: Some(draft.title),
        start: Some(draft.start),
        end: Some(draft.end),
        all_day: draft.all_day,
        time_zone: draft.time_zone,
        place: draft.place,
        notes: draft.notes,
        recurrence: draft.recurrence,
        reminder: draft.reminder,
        attendees: draft.attendees,
        webhook: draft.webhook,
    });
    let response = request.json(&body).send().await?;
    Ok(ok(response).await?.json().await?)
}

/// Change an event on your calendar or a group's. A recurring event changes as
/// a whole. New invitees get invited; the rest hear about a new time or place.
pub async fn update(
    authorization: &CredentialsOrApiKey,
    id: &str,
    update: PartialDraft,
) -> Result<Event> {
    let response = client()
        .patch(format!(
            "{}/calendar/events/{}",
            crate::get_url(),
            encode(id)
        ))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&draft_json(update))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Remove an event from your calendar or a group's, telling everyone it
/// invited.
pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
    let response = client()
        .delete(format!(
            "{}/calendar/events/{}",
            crate::get_url(),
            encode(id)
        ))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

/// Answer an event you're invited to: `Yes`, `No` or `Maybe`.
pub async fn respond(
    authorization: &CredentialsOrApiKey,
    id: &str,
    answer: Answer,
) -> Result<Event> {
    let response = client()
        .post(format!(
            "{}/calendar/events/{}/respond",
            crate::get_url(),
            encode(id)
        ))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&json!({ "response": answer }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

#[derive(Deserialize)]
struct FeedUrl {
    url: String,
}

/// Your own secret .ics link for your calendar, or `group`'s, for Google, Apple or
/// Outlook to subscribe to. Each person has their own link, and a group's stops
/// working when you leave the group.
pub async fn feed(authorization: &CredentialsOrApiKey, group: Option<&Group>) -> Result<String> {
    let mut request = client()
        .get(format!("{}/calendar/feed", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request.send().await?;
    let feed: FeedUrl = ok(response).await?.json().await?;
    Ok(feed.url)
}

/// A new .ics link of your own for your calendar, or `group`'s. Your old one stops
/// working; nobody else's changes.
pub async fn reset_feed(credentials: &Credentials, group: Option<&Group>) -> Result<String> {
    let mut request = client()
        .post(format!("{}/calendar/feed/reset", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token));
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request.send().await?;
    let feed: FeedUrl = ok(response).await?.json().await?;
    Ok(feed.url)
}