fauna-api 1.0.686

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::{Value, json};

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

/// The `options` argument of `create_chat`.
#[derive(Debug, Clone, Default)]
pub struct CreateChatOptions {
    /// People only for good: sends never start a model reply.
    pub human: Option<bool>,
    /// Instructs every model reply in the chat.
    pub system_prompt: Option<String>,
    /// Only you can delete it or move it to another group; it still goes away
    /// with its group.
    pub locked: Option<bool>,
    /// The Termite repository Parrot works in during replies, by id: yours for
    /// a personal chat, the group's for a group chat.
    pub repository: Option<u64>,
}

/// Create a chat, owned by the caller or by `group`. `human` makes it a people
/// only chat for good: sends never start a model reply. `system_prompt`
/// instructs every model reply in the chat. `locked` lets only you delete it or
/// move it to another group. `repository` is a Termite repository Parrot works
/// in during replies. `name` defaults to `New Chat`.
pub async fn create_chat(
    authorization: &CredentialsOrApiKey,
    name: Option<&str>,
    group: Option<&Group>,
    options: CreateChatOptions,
) -> Result<String> {
    let mut request = client()
        .post(format!("{}/chat/create", super::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
        .json(&json!({
            "name": name.unwrap_or("New Chat"),
            "human": options.human == Some(true),
            "systemPrompt": options.system_prompt,
            "locked": options.locked == Some(true),
            "repository": options.repository,
        }))
        .send()
        .await?;
    let json: serde_json::Value = ok(response).await?.json().await?;
    Ok(json["id"].as_str().unwrap_or_default().to_string())
}

pub async fn delete_chat(
    authorization: &CredentialsOrApiKey,
    id: &str,
    group: Option<&Group>,
) -> Result<()> {
    let mut request = client()
        .post(format!("{}/chat/delete", super::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.json(&json!({ "id": id })).send().await?;
    ok(response).await?;
    Ok(())
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LastMessage {
    #[serde(default)]
    pub parts: Vec<serde_json::Value>,
    pub role: String,
    pub created_at: DateTime<Utc>,
    pub position: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub author: Option<Profile>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

impl LastMessage {
    pub fn from_json(json: &Value) -> Option<LastMessage> {
        if !json.is_object() {
            return None;
        }
        let created_at = crate::tickets::parse_date(&json["createdAt"])?;
        let position = json["position"].as_f64()?;
        Some(LastMessage {
            parts: json["parts"].as_array().cloned().unwrap_or_default(),
            role: match &json["role"] {
                Value::Null => String::new(),
                Value::String(role) => role.clone(),
                role => role.to_string(),
            },
            created_at,
            position: position as u32,
            author: Profile::from_json(&json["author"]),
            model: json["model"]
                .as_str()
                .filter(|model| !model.is_empty())
                .map(str::to_string),
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatSummary {
    pub id: String,
    pub name: String,
    pub principal_id: String,
    /// People only: sends never start a model reply.
    #[serde(default)]
    pub human: bool,
    /// Only whoever made it can delete it or move it.
    #[serde(default)]
    pub locked: bool,
    /// The repository Parrot works in, by id.
    #[serde(default)]
    pub repository: Option<u64>,
    /// Milliseconds since the epoch.
    pub created: i64,
    /// Milliseconds since the epoch.
    pub updated: i64,
    #[serde(default)]
    pub last: Option<LastMessage>,
    /// Messages the caller hasn't read. A person and each of their API keys keep
    /// their own place; one that never marked the chat sees only its newest 20.
    #[serde(default)]
    pub unread: u32,
}

pub async fn list_chats(
    authorization: &CredentialsOrApiKey,
    group: Option<&Group>,
) -> Result<Vec<ChatSummary>> {
    let mut request = client()
        .get(format!("{}/chat/all", super::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 rows: Vec<Value> = ok(response).await?.json().await?;
    rows.into_iter()
        .map(|mut row| {
            let last = LastMessage::from_json(&row["last"]);
            row["last"] = Value::Null;
            let mut summary: ChatSummary = serde_json::from_value(row)?;
            summary.last = last;
            Ok(summary)
        })
        .collect()
}

pub async fn rename_chat(
    authorization: &CredentialsOrApiKey,
    id: &str,
    name: &str,
    group: Option<&Group>,
) -> Result<()> {
    let mut request = client()
        .post(format!("{}/chat/rename", super::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
        .json(&json!({ "id": id, "name": name }))
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

/// Mark a chat read for the caller, up to `position` (the next unread one) or
/// all of it. Signed in with an API key, the key keeps its own place, apart from
/// its person. Sending a message reads the chat for its sender. Returns what's
/// left unread.
pub async fn mark_read(
    authorization: &CredentialsOrApiKey,
    id: &str,
    position: Option<u32>,
    group: Option<&Group>,
) -> Result<u32> {
    let mut request = client()
        .post(format!("{}/chat/mark-read", super::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
        .json(&json!({ "id": id, "position": position }))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(json["unread"].as_u64().unwrap_or_default() as u32)
}