fauna-api 1.0.814

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use std::ops::Deref;

use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::contacts::{Contact, Owner, post};
use crate::authentification::CredentialsOrApiKey;
use crate::error::Result;
use crate::http::{deserialize_date, serialize_date};
use crate::integrations::Platform;
use crate::parrot::chat::ChatSummary;

/// `Contact | Owner | string` in the TypeScript SDK: a known contact, one of the inbox's
/// owners, or a bare address.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ContactOrOwnerOrString {
    Contact(Contact),
    Owner(Owner),
    String(String),
}

/// A line under one of a chat's messages, by its position: why it never arrived, or that it
/// waits for an owner's approval.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Note {
    pub position: u32,
    pub text: String,
}

/// `{ platform, name, guildName }` in the TypeScript SDK: the Discord or Slack channel a chat is.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatChannel {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub platform: Option<Platform>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guild_name: Option<String>,
}

/// One of an inbox's chats: the Parrot chat the inbox owns, with who it's with and how
/// they're reached. Its messages are the chat's: open its room with `parrot::chat::open_room`
/// on its id. What the inbox's members and its agent write there goes out to its people.
#[derive(Debug, Clone)]
pub struct Chat {
    pub summary: ChatSummary,
    pub inbox_id: String,
    pub participants: Vec<ContactOrOwnerOrString>,
    /// The Discord or Slack channel it is, when it's one.
    pub channel: Option<ChatChannel>,
    /// The platform it's reached on.
    pub platform: Option<Platform>,
    pub archived: bool,
    pub remind_at: Option<DateTime<Utc>>,
    pub notes: Vec<Note>,
}

impl Deref for Chat {
    type Target = ChatSummary;

    fn deref(&self) -> &ChatSummary {
        &self.summary
    }
}

impl Chat {
    pub fn from_json(json: &Value) -> Chat {
        Chat {
            summary: ChatSummary::from_json(json),
            inbox_id: id_text(&json["inboxId"]),
            participants: serde_json::from_value(json["participants"].clone()).unwrap_or_default(),
            channel: serde_json::from_value(json["channel"].clone()).ok(),
            platform: serde_json::from_value(json["platform"].clone()).ok(),
            archived: json["archived"] == true,
            remind_at: crate::tickets::parse_date(&json["remindAt"]),
            notes: serde_json::from_value(json["notes"].clone()).unwrap_or_default(),
        }
    }
}

/// A chat paired with the time its reminder is due.
#[derive(Debug, Clone)]
pub struct Reminder {
    pub chat: Chat,
    pub remind_at: DateTime<Utc>,
}

/// `'broadcast' | 'group'` in the TypeScript SDK: a separate one to each recipient, or one
/// shared thread.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SendMode {
    Broadcast,
    Group,
}

/// Where a scheduled send goes: a reply in a chat, or a fresh compose to a set of recipients
/// (hydrated to contacts).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ScheduledContext {
    Chat {
        #[serde(rename = "chatId")]
        chat_id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        platform: Option<Platform>,
    },
    Compose {
        recipients: Vec<ContactOrOwnerOrString>,
        mode: SendMode,
        platform: Platform,
    },
}

/// A queued outbound message the server sends at `send_at`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledSend {
    pub id: String,
    #[serde(
        deserialize_with = "deserialize_date",
        serialize_with = "serialize_date"
    )]
    pub send_at: DateTime<Utc>,
    #[serde(
        deserialize_with = "deserialize_date",
        serialize_with = "serialize_date"
    )]
    pub created_at: DateTime<Utc>,
    pub message: String,
    pub context: ScheduledContext,
}

/// An id the server sent as a string or a number.
fn id_text(json: &Value) -> String {
    match json {
        Value::String(id) => id.clone(),
        Value::Null => String::new(),
        id => id.to_string(),
    }
}

fn inbox_body(inbox_id: Option<&str>) -> Value {
    match inbox_id.filter(|id| !id.is_empty()) {
        Some(inbox_id) => json!({ "inboxId": inbox_id }),
        None => json!({}),
    }
}

async fn list_view(
    authorization: &CredentialsOrApiKey,
    path: &str,
    inbox_id: Option<&str>,
) -> Result<Vec<Chat>> {
    let rows: Vec<Value> = post(authorization, path, Some(inbox_body(inbox_id)))
        .await?
        .json()
        .await?;
    Ok(rows.iter().map(Chat::from_json).collect())
}

/// The inbox working set: everything except archived chats and chats parked for a future
/// reminder.
pub async fn list_inbox(
    authorization: &CredentialsOrApiKey,
    inbox_id: Option<&str>,
) -> Result<Vec<Chat>> {
    list_view(authorization, "/cicada/inbox", inbox_id).await
}

/// The archive.
pub async fn list_archived(
    authorization: &CredentialsOrApiKey,
    inbox_id: Option<&str>,
) -> Result<Vec<Chat>> {
    list_view(authorization, "/cicada/archived", inbox_id).await
}

/// Chats with a future reminder, each with its due time.
pub async fn list_reminders(
    authorization: &CredentialsOrApiKey,
    inbox_id: Option<&str>,
) -> Result<Vec<Reminder>> {
    let rows: Vec<Value> = post(
        authorization,
        "/cicada/reminders",
        Some(inbox_body(inbox_id)),
    )
    .await?
    .json()
    .await?;
    Ok(rows
        .iter()
        .map(|row| Reminder {
            chat: Chat::from_json(&row["chat"]),
            remind_at: crate::tickets::parse_date(&row["remindAt"]).unwrap_or_default(),
        })
        .collect())
}

/// One chat, or None once it's gone.
pub async fn get(authorization: &CredentialsOrApiKey, chat_id: &str) -> Result<Option<Chat>> {
    let json: Value = post(
        authorization,
        "/cicada/chats/get",
        Some(json!({ "chatId": chat_id })),
    )
    .await?
    .json()
    .await?;
    Ok(json.is_object().then(|| Chat::from_json(&json)))
}

/// Deletes a chat and its messages. A history pull never brings them back.
pub async fn remove(authorization: &CredentialsOrApiKey, chat_id: &str) -> Result<()> {
    post(
        authorization,
        "/cicada/chats/delete",
        Some(json!({ "chatId": chat_id })),
    )
    .await?;
    Ok(())
}

/// The `options` argument of `compose`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ComposeOptions {
    pub recipients: Vec<String>,
    pub platform: Platform,
    pub text: String,
    pub mode: SendMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inbox_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub account_id: Option<String>,
}

/// Starts (or appends to) chats with picked contacts on a platform. `recipients` are contact
/// keys (email, handle or phone). `broadcast` sends a separate one to each; `group` sends one
/// shared thread (one each on platforms without a real group). Resolves to the chats it wrote
/// in.
pub async fn compose(
    authorization: &CredentialsOrApiKey,
    options: &ComposeOptions,
) -> Result<Vec<String>> {
    let json: Value = post(
        authorization,
        "/cicada/compose",
        Some(serde_json::to_value(options)?),
    )
    .await?
    .json()
    .await?;
    Ok(serde_json::from_value(json["chatIds"].clone()).unwrap_or_default())
}

/// Moves a chat in or out of the archive.
pub async fn archive(
    authorization: &CredentialsOrApiKey,
    chat_id: &str,
    archived: bool,
) -> Result<()> {
    post(
        authorization,
        "/cicada/chats/archive",
        Some(json!({ "chatId": chat_id, "archived": archived })),
    )
    .await?;
    Ok(())
}

/// Sets (or clears, with None) a reminder; when it's due the chat comes back to the top of the
/// inbox.
pub async fn remind(
    authorization: &CredentialsOrApiKey,
    chat_id: &str,
    at: Option<DateTime<Utc>>,
) -> Result<()> {
    post(
        authorization,
        "/cicada/chats/remind",
        Some(json!({
            "chatId": chat_id,
            "at": at.map(|at| at.to_rfc3339_opts(SecondsFormat::Millis, true)),
        })),
    )
    .await?;
    Ok(())
}

/// `{ recipients, mode }` in the TypeScript SDK: who a scheduled compose goes to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ComposeTarget {
    pub recipients: Vec<String>,
    pub mode: SendMode,
}

/// The `options` argument of `schedule`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleOptions {
    #[serde(
        deserialize_with = "deserialize_date",
        serialize_with = "serialize_date"
    )]
    pub send_at: DateTime<Utc>,
    pub text: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub platform: Option<Platform>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chat_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compose: Option<ComposeTarget>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inbox_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub account_id: Option<String>,
}

/// Queues an outbound message: a reply in `chat_id`, or `compose` for fresh chats. Resolves to
/// its id.
pub async fn schedule(
    authorization: &CredentialsOrApiKey,
    options: &ScheduleOptions,
) -> Result<String> {
    let json: Value = post(
        authorization,
        "/cicada/schedule",
        Some(serde_json::to_value(options)?),
    )
    .await?
    .json()
    .await?;
    Ok(id_text(&json["id"]))
}

pub async fn list_scheduled(
    authorization: &CredentialsOrApiKey,
    inbox_id: Option<&str>,
) -> Result<Vec<ScheduledSend>> {
    Ok(post(
        authorization,
        "/cicada/scheduled/list",
        Some(inbox_body(inbox_id)),
    )
    .await?
    .json()
    .await?)
}

pub async fn cancel_scheduled(authorization: &CredentialsOrApiKey, scheduled: &str) -> Result<()> {
    post(
        authorization,
        "/cicada/scheduled/cancel",
        Some(json!({ "scheduled": scheduled })),
    )
    .await?;
    Ok(())
}