fauna-api 1.0.814

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

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

use super::tools::page_tools;
use crate::authentification::CredentialsOrApiKey;
use crate::error::{Error, Result};
use crate::http::{client, encode, ok};
use crate::marmot::web::{WebRoom, WebRoomHooks, WebTarget, connect_web_room};
use crate::parrot::generative::Tool;
use crate::parrot::room::{ChatRoom, RoomHooks, connect_room};
use crate::parrot::share::{ChatTarget, OpenRoomOptions, open_room};
use crate::shared::server::Presence;

/// Public join URL for a web-room access code (chat joins via ensure, not the URL).
/// `origin` defaults to `https://app.faunakit.com`.
pub fn share_url(code: &str, origin: Option<&str>) -> String {
    // Trailing slash is required: without it Vite (and many static hosts) serve
    // the app root `index.html` instead of `extensions/web/index.html`.
    let origin = origin.unwrap_or("https://app.faunakit.com");
    format!(
        "{}/extensions/web/?access-code={}",
        origin.strip_suffix('/').unwrap_or(origin),
        encode(code)
    )
}

#[derive(Default, Clone)]
pub struct SessionHooks {
    pub web: Option<Arc<dyn WebRoomHooks>>,
    pub chat: Option<Arc<dyn RoomHooks>>,
}

/// A paired live session: one `WebRoom` (live page DOM) + one `ChatRoom`.
/// Share links carry only the web access code; chat uses ensure + Parrot code.
#[derive(Clone)]
pub struct ExtensionWebSession {
    pub web: WebRoom,
    pub chat: ChatRoom,
    pub web_self: Presence,
    pub chat_self: Presence,
    /// Bare web access code used in the share URL.
    pub code: String,
}

impl ExtensionWebSession {
    pub fn share_code(&self) -> String {
        self.code.clone()
    }

    /// Page tools routed through the web room (host executes).
    pub fn page_tools(&self) -> Vec<Tool> {
        let web = self.web.clone();
        page_tools(Arc::new(move |name, params| {
            let web = web.clone();
            Box::pin(async move {
                let name = match serde_json::to_value(name)? {
                    Value::String(name) => name,
                    name => name.to_string(),
                };
                web.invoke_tool(&name, params, None).await
            })
        }))
    }

    pub fn close(&self) {
        self.web.publish_closed();
        self.web.disconnect();
        self.chat.disconnect();
    }
}

/// Cached chat half of a share. The content script only mints/opens the room
/// (`open_room`); the chat iframe owns the live `ChatRoom` socket so the host
/// does not double-join presence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedChatRoom {
    pub reference: String,
    pub room_id: String,
    pub code: String,
}

/// Open (or return) a shared Parrot chat room for this tab. Lives until the host
/// leaves the page: panel close must not destroy it. Does not connect a socket
/// here; call `connect_room` from the chat UI with `code`.
pub async fn ensure_chat_room(
    authorization: &CredentialsOrApiKey,
    cached: Option<&CachedChatRoom>,
) -> Result<CachedChatRoom> {
    if let Some(cached) = cached.filter(|cached| !cached.code.is_empty()) {
        return Ok(cached.clone());
    }
    let opened = open_room(
        authorization,
        OpenRoomOptions {
            share: Some(true),
            ..OpenRoomOptions::default()
        },
    )
    .await?;
    Ok(CachedChatRoom {
        reference: opened.reference,
        room_id: opened.room_id,
        code: opened.code.unwrap_or_default(),
    })
}

/// `{ accessCode } | { reference }` in the TypeScript SDK: a web room as a guest
/// joined it, or as its host opened it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessScope {
    AccessCode { access_code: String },
    Reference { reference: String },
}

/// The `opts` argument of `ensure_chat_from_web_access`.
#[derive(Debug, Clone, Default)]
pub struct EnsureOptions {
    pub room: Option<String>,
}

/// `{ room, code }` in the TypeScript SDK.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnsuredChat {
    pub room: String,
    pub code: String,
}

fn scoped(
    request: reqwest::RequestBuilder,
    authorization: &CredentialsOrApiKey,
    scope: &AccessScope,
) -> reqwest::RequestBuilder {
    let request = request.header("Content-Type", "application/json").header(
        "Authorization",
        match authorization {
            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
        },
    );
    match scope {
        AccessScope::AccessCode { access_code } => request.header("Access-Code", access_code),
        AccessScope::Reference { reference } => request.header("Server", reference),
    }
}

/// Bind (host) or open the Parrot room paired with a web room. The host binds a
/// room it opened (`room` is its reference). Always returns a fresh Parrot access
/// code for `connect_room(ChatTarget::Code { code })`.
pub async fn ensure_chat_from_web_access(
    authorization: &CredentialsOrApiKey,
    scope: &AccessScope,
    opts: EnsureOptions,
) -> Result<EnsuredChat> {
    let body = match opts.room.filter(|room| !room.is_empty()) {
        Some(room) => json!({ "room": room }),
        None => json!({}),
    };
    let response = scoped(
        client().post(format!(
            "{}/extensions/web/chat/ensure",
            crate::marmot::get_url()
        )),
        authorization,
        scope,
    )
    .json(&body)
    .send()
    .await?;
    let json: Value = ok(response).await?.json().await?;
    match (
        json["room"].as_str().filter(|room| !room.is_empty()),
        json["code"].as_str().filter(|code| !code.is_empty()),
    ) {
        (Some(room), Some(code)) => Ok(EnsuredChat {
            room: room.to_string(),
            code: code.to_string(),
        }),
        _ => Err(Error::Message(
            "Invalid web chat ensure response.".to_string(),
        )),
    }
}

/// Opens a shared chat and a hosted web room paired with it. Page capture stays
/// with the browser, so the session only carries the rooms.
pub async fn open_session(
    authorization: &CredentialsOrApiKey,
    hooks: SessionHooks,
) -> Result<ExtensionWebSession> {
    let opened_chat = open_room(
        authorization,
        OpenRoomOptions {
            share: Some(true),
            ..OpenRoomOptions::default()
        },
    )
    .await?;
    let chat_code = opened_chat.code.clone().unwrap_or_default();

    let reference = format!("web:{}", uuid::Uuid::new_v4());
    let (web, web_self) = connect_web_room(
        authorization,
        &WebTarget::Reference {
            reference: reference.clone(),
        },
        hooks.web,
    )
    .await?;
    let web_code = web.generate_access_code().await?;
    ensure_chat_from_web_access(
        authorization,
        &AccessScope::Reference { reference },
        EnsureOptions {
            room: Some(opened_chat.reference),
        },
    )
    .await?;

    let (chat, chat_self) = connect_room(
        authorization,
        &ChatTarget::Code { code: chat_code },
        hooks.chat,
    )
    .await?;

    Ok(ExtensionWebSession {
        web,
        chat,
        web_self,
        chat_self,
        code: web_code,
    })
}

/// Joins a shared page by its web access code, with the chat paired with it.
pub async fn join_room(
    authorization: &CredentialsOrApiKey,
    web_code: &str,
    hooks: SessionHooks,
) -> Result<ExtensionWebSession> {
    let (web, web_self) = connect_web_room(
        authorization,
        &WebTarget::Code {
            code: web_code.to_string(),
        },
        hooks.web,
    )
    .await?;

    let ensured = ensure_chat_from_web_access(
        authorization,
        &AccessScope::AccessCode {
            access_code: web_code.to_string(),
        },
        EnsureOptions::default(),
    )
    .await?;
    let (chat, chat_self) = connect_room(
        authorization,
        &ChatTarget::Code { code: ensured.code },
        hooks.chat,
    )
    .await?;

    Ok(ExtensionWebSession {
        web,
        chat,
        web_self,
        chat_self,
        code: web_code.to_string(),
    })
}

pub async fn invite(
    authorization: &CredentialsOrApiKey,
    email: &str,
    join_url: &str,
    scope: &AccessScope,
) -> Result<()> {
    let response = scoped(
        client().post(format!(
            "{}/extensions/web/invite",
            crate::marmot::get_url()
        )),
        authorization,
        scope,
    )
    .json(&json!({ "email": email, "joinUrl": join_url }))
    .send()
    .await?;
    ok(response).await?;
    Ok(())
}