fauna-api 1.0.811

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

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::authentification::CredentialsOrApiKey;
use crate::error::Result;
use crate::http::{client, encode, ok};
use crate::parrot::chat::ChatSummary;
use crate::parrot::generative::Author;

/// Whose chat it is: one of your groups, a friendship, or a partnership of one
/// of your groups.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OwnerKind {
    Group,
    Friend,
    Partnership,
}

/// For a partnership: your group in it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OwnerGroup {
    pub id: String,
    pub name: String,
}

/// Who a chat belongs to, and how much you trust it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Owner {
    pub kind: OwnerKind,
    /// The group, friendship or partnership id.
    pub id: String,
    /// The group's name, your friend's name, or the partner group's name.
    pub name: String,
    /// Your trust in your friend, or your group's trust in the partner group, in
    /// [0, 1). `None` for your own groups, which always count.
    #[serde(default)]
    pub trust: Option<f64>,
    /// For a partnership: your group in it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group: Option<OwnerGroup>,
}

/// A chat you share with others: the Parrot chat, and whose it is. Signed in with an API key,
/// its `unread` is the key's own place.
#[derive(Debug, Clone, Serialize)]
pub struct Chat {
    #[serde(flatten)]
    pub summary: ChatSummary,
    pub owner: Owner,
}

impl Deref for Chat {
    type Target = ChatSummary;

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

impl Chat {
    pub fn from_json(json: &Value) -> Option<Chat> {
        Some(Chat {
            summary: ChatSummary::from_json(json),
            owner: serde_json::from_value(json["owner"].clone()).ok()?,
        })
    }
}

impl<'de> Deserialize<'de> for Chat {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        Chat::from_json(&Value::deserialize(deserializer)?)
            .ok_or_else(|| serde::de::Error::custom("a shared chat needs its owner"))
    }
}

/// A message as plain text: mentions as names, files as `[file: name]`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    pub position: u32,
    pub role: String,
    pub text: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub author: Option<Author>,
    /// Milliseconds since the epoch.
    pub created: i64,
}

/// What you haven't read, in chats that pass a trust threshold.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Unread {
    pub total: u32,
    #[serde(default)]
    pub chats: Vec<Chat>,
}

/// A chat in a catch up, with what you hadn't read, oldest first.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaughtUpChat {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub human: bool,
    pub owner: Owner,
    pub updated: i64,
    #[serde(default)]
    pub messages: Vec<Message>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaughtUp {
    #[serde(default)]
    pub chats: Vec<CaughtUpChat>,
    /// More unread is waiting: catch up again for the next batch.
    pub more: bool,
    /// Unread left in chats that pass, after this batch.
    pub unread: u32,
}

/// The chat a search found a message in.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatReference {
    pub id: String,
    pub name: String,
    pub owner: Owner,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Found {
    pub chat: ChatReference,
    pub message: Message,
}

/// The `options` argument of `unread`.
#[derive(Debug, Clone, Copy, Default)]
pub struct UnreadOptions {
    /// Chats you trust at least this much, in [0, 1]. Defaults to 0.1.
    pub min_trust: Option<f64>,
}

/// The `options` argument of `catch_up`.
#[derive(Debug, Clone, Copy, Default)]
pub struct CatchUpOptions {
    /// Chats you trust at least this much, in [0, 1]. Defaults to 0.1.
    pub min_trust: Option<f64>,
    /// Most messages to return, 1 to 500. Defaults to 100.
    pub max: Option<u32>,
}

/// The `options` argument of `search`.
#[derive(Debug, Clone, Copy, Default)]
pub struct SearchOptions {
    /// Matches to skip from the newest.
    pub cursor: Option<u32>,
    /// Page size, 1 to 100. Defaults to 20.
    pub max: Option<u32>,
}

/// Every chat you share with others, newest first: your groups', your friends'
/// and your groups' partnerships', each with its owner, your trust in it and
/// what you haven't read.
pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Chat>> {
    let response = client()
        .get(format!("{}/chats/shared", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    let rows: Vec<Value> = ok(response).await?.json().await?;
    Ok(rows.iter().filter_map(Chat::from_json).collect())
}

/// What you haven't read in chats you trust at least `min_trust` (default 0.1).
/// Your own groups' chats always count.
pub async fn unread(authorization: &CredentialsOrApiKey, options: UnreadOptions) -> Result<Unread> {
    let query = options
        .min_trust
        .map(|min_trust| format!("?minTrust={}", encode(&min_trust.to_string())))
        .unwrap_or_default();
    let response = client()
        .get(format!("{}/chats/unread{}", crate::get_url(), query))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(Unread {
        total: json["total"].as_u64().unwrap_or_default() as u32,
        chats: json["chats"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(Chat::from_json)
            .collect(),
    })
}

/// Everything you haven't read in chats you trust at least `min_trust` (default
/// 0.1), oldest first within each chat, at most `max` messages (default 100),
/// read as it's returned. Call again while `more` is true. A reader that never
/// opened a chat starts with its newest 20.
pub async fn catch_up(
    authorization: &CredentialsOrApiKey,
    options: CatchUpOptions,
) -> Result<CaughtUp> {
    let response = client()
        .post(format!("{}/chats/catch-up", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&json!({ "minTrust": options.min_trust, "max": options.max }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Messages holding every word of `query` across every chat you share with
/// others, newest first. `cursor` skips that many matches from the newest; `max`
/// is the page size (default 20).
pub async fn search(
    authorization: &CredentialsOrApiKey,
    query: &str,
    options: SearchOptions,
) -> Result<Vec<Found>> {
    let response = client()
        .post(format!("{}/chats/search", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&json!({ "query": query, "cursor": options.cursor, "max": options.max }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Post `text` in a chat, as you. Everyone in it sees it live, its webhooks fire
/// and it counts toward memories, like any message. Signed in with an API key,
/// the message is authored by the key, by its name, and never moves trust. In a chat
/// that isn't people only, it starts a model reply as any message does.
pub async fn post(authorization: &CredentialsOrApiKey, chat: &str, text: &str) -> Result<()> {
    let opened = client()
        .post(format!("{}/chat/live/open", crate::parrot::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&json!({ "chatId": chat }))
        .send()
        .await?;
    ok(opened).await?;
    let response = client()
        .post(format!("{}/chat/live/append", crate::parrot::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .header("Server", format!("parrot:chat:{chat}"))
        .json(&json!({ "role": "USER", "parts": [{ "type": "TEXT", "text": text }] }))
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}