Skip to main content

fauna_api/extensions/web/
session.rs

1use std::sync::Arc;
2
3use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
5
6use super::tools::page_tools;
7use crate::authentification::CredentialsOrApiKey;
8use crate::error::{Error, Result};
9use crate::http::{client, encode, ok};
10use crate::marmot::web::{WebRoom, WebRoomHooks, WebTarget, connect_web_room};
11use crate::parrot::chat::{CreateChatOptions, create_chat, delete_chat};
12use crate::parrot::generative::Tool;
13use crate::parrot::room::{ChatRoom, RoomHooks, connect_room};
14use crate::parrot::share::{ChatTarget, OpenRoomOptions, open_room};
15use crate::shared::server::Presence;
16
17/// Public join URL for a web-room access code (chat joins via ensure, not the URL).
18/// `origin` defaults to `https://app.faunakit.com`.
19pub fn share_url(code: &str, origin: Option<&str>) -> String {
20    // Trailing slash is required: without it Vite (and many static hosts) serve
21    // the app root `index.html` instead of `extensions/web/index.html`.
22    let origin = origin.unwrap_or("https://app.faunakit.com");
23    format!(
24        "{}/extensions/web/?access-code={}",
25        origin.strip_suffix('/').unwrap_or(origin),
26        encode(code)
27    )
28}
29
30#[derive(Default, Clone)]
31pub struct SessionHooks {
32    pub web: Option<Arc<dyn WebRoomHooks>>,
33    pub chat: Option<Arc<dyn RoomHooks>>,
34}
35
36/// A paired live session: one `WebRoom` (live page DOM) + one `ChatRoom`.
37/// Share links carry only the web access code; chat uses ensure + Parrot code.
38#[derive(Clone)]
39pub struct ExtensionWebSession {
40    pub web: WebRoom,
41    pub chat: ChatRoom,
42    pub web_self: Presence,
43    pub chat_self: Presence,
44    /// Bare web access code used in the share URL.
45    pub code: String,
46    /// The temporary chat this session made as host, deleted when it closes.
47    made_chat: Option<(CredentialsOrApiKey, String)>,
48}
49
50impl ExtensionWebSession {
51    pub fn share_code(&self) -> String {
52        self.code.clone()
53    }
54
55    /// Page tools routed through the web room (host executes).
56    pub fn page_tools(&self) -> Vec<Tool> {
57        let web = self.web.clone();
58        page_tools(Arc::new(move |name, params| {
59            let web = web.clone();
60            Box::pin(async move {
61                let name = match serde_json::to_value(name)? {
62                    Value::String(name) => name,
63                    name => name.to_string(),
64                };
65                web.invoke_tool(&name, params, None).await
66            })
67        }))
68    }
69
70    pub fn close(&self) {
71        self.web.publish_closed();
72        self.web.disconnect();
73        self.chat.disconnect();
74        if let Some((authorization, chat_id)) = self.made_chat.clone() {
75            // A failed delete is left to the idle sweep.
76            tokio::spawn(async move {
77                let _ = delete_chat(&authorization, &chat_id, None).await;
78            });
79        }
80    }
81}
82
83/// Cached chat half of a share: a temporary Parrot chat. The content script only
84/// makes and opens it (`open_room`); the chat iframe owns the live `ChatRoom`
85/// socket so the host does not double-join presence.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "camelCase")]
88pub struct CachedChatRoom {
89    pub chat_id: String,
90    pub reference: String,
91    pub room_id: String,
92    pub code: String,
93}
94
95/// A share's temporary chat, opened with an access code.
96async fn open_share_chat(authorization: &CredentialsOrApiKey) -> Result<CachedChatRoom> {
97    let chat_id = create_chat(
98        authorization,
99        Some("Web share"),
100        None,
101        CreateChatOptions {
102            temporary: Some(true),
103            ..CreateChatOptions::default()
104        },
105    )
106    .await?;
107    let opened = open_room(
108        authorization,
109        &chat_id,
110        OpenRoomOptions { share: Some(true) },
111    )
112    .await?;
113    Ok(CachedChatRoom {
114        chat_id,
115        reference: opened.reference,
116        room_id: opened.room_id,
117        code: opened.code.unwrap_or_default(),
118    })
119}
120
121/// Open (or return) this tab's shared chat, a temporary Parrot chat. Lives until
122/// the host leaves the page (`end_chat_room`): closing the panel keeps it. Does
123/// not connect a socket here; call `connect_room` from the chat UI with `code`.
124pub async fn ensure_chat_room(
125    authorization: &CredentialsOrApiKey,
126    cached: Option<&CachedChatRoom>,
127) -> Result<CachedChatRoom> {
128    if let Some(cached) = cached.filter(|cached| !cached.code.is_empty()) {
129        return Ok(cached.clone());
130    }
131    open_share_chat(authorization).await
132}
133
134/// Deletes a share's temporary chat once the host leaves.
135pub async fn end_chat_room(
136    authorization: &CredentialsOrApiKey,
137    chat: &CachedChatRoom,
138) -> Result<()> {
139    delete_chat(authorization, &chat.chat_id, None).await
140}
141
142/// `{ accessCode } | { reference }` in the TypeScript SDK: a web room as a guest
143/// joined it, or as its host opened it.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub enum AccessScope {
146    AccessCode { access_code: String },
147    Reference { reference: String },
148}
149
150/// The `opts` argument of `ensure_chat_from_web_access`.
151#[derive(Debug, Clone, Default)]
152pub struct EnsureOptions {
153    pub room: Option<String>,
154}
155
156/// `{ room, code }` in the TypeScript SDK.
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct EnsuredChat {
159    pub room: String,
160    pub code: String,
161}
162
163fn scoped(
164    request: reqwest::RequestBuilder,
165    authorization: &CredentialsOrApiKey,
166    scope: &AccessScope,
167) -> reqwest::RequestBuilder {
168    let request = request.header("Content-Type", "application/json").header(
169        "Authorization",
170        match authorization {
171            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
172            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
173        },
174    );
175    match scope {
176        AccessScope::AccessCode { access_code } => request.header("Access-Code", access_code),
177        AccessScope::Reference { reference } => request.header("Server", reference),
178    }
179}
180
181/// Bind (host) or open the Parrot room paired with a web room. The host binds a
182/// room it opened (`room` is its reference). Always returns a fresh Parrot access
183/// code for `connect_room(ChatTarget::Code { code })`.
184pub async fn ensure_chat_from_web_access(
185    authorization: &CredentialsOrApiKey,
186    scope: &AccessScope,
187    opts: EnsureOptions,
188) -> Result<EnsuredChat> {
189    let body = match opts.room.filter(|room| !room.is_empty()) {
190        Some(room) => json!({ "room": room }),
191        None => json!({}),
192    };
193    let response = scoped(
194        client().post(format!(
195            "{}/extensions/web/chat/ensure",
196            crate::marmot::get_url()
197        )),
198        authorization,
199        scope,
200    )
201    .json(&body)
202    .send()
203    .await?;
204    let json: Value = ok(response).await?.json().await?;
205    match (
206        json["room"].as_str().filter(|room| !room.is_empty()),
207        json["code"].as_str().filter(|code| !code.is_empty()),
208    ) {
209        (Some(room), Some(code)) => Ok(EnsuredChat {
210            room: room.to_string(),
211            code: code.to_string(),
212        }),
213        _ => Err(Error::Message(
214            "Invalid web chat ensure response.".to_string(),
215        )),
216    }
217}
218
219/// Opens a shared chat and a hosted web room paired with it. Page capture stays
220/// with the browser, so the session only carries the rooms.
221pub async fn open_session(
222    authorization: &CredentialsOrApiKey,
223    hooks: SessionHooks,
224) -> Result<ExtensionWebSession> {
225    let opened_chat = open_share_chat(authorization).await?;
226    let chat_code = opened_chat.code.clone();
227
228    let reference = format!("web:{}", uuid::Uuid::new_v4());
229    let (web, web_self) = connect_web_room(
230        authorization,
231        &WebTarget::Reference {
232            reference: reference.clone(),
233        },
234        hooks.web,
235    )
236    .await?;
237    let web_code = web.generate_access_code().await?;
238    ensure_chat_from_web_access(
239        authorization,
240        &AccessScope::Reference { reference },
241        EnsureOptions {
242            room: Some(opened_chat.reference),
243        },
244    )
245    .await?;
246
247    let (chat, chat_self) = connect_room(
248        authorization,
249        &ChatTarget::Code { code: chat_code },
250        hooks.chat,
251    )
252    .await?;
253
254    Ok(ExtensionWebSession {
255        web,
256        chat,
257        web_self,
258        chat_self,
259        code: web_code,
260        made_chat: Some((authorization.clone(), opened_chat.chat_id)),
261    })
262}
263
264/// Joins a shared page by its web access code, with the chat paired with it.
265pub async fn join_room(
266    authorization: &CredentialsOrApiKey,
267    web_code: &str,
268    hooks: SessionHooks,
269) -> Result<ExtensionWebSession> {
270    let (web, web_self) = connect_web_room(
271        authorization,
272        &WebTarget::Code {
273            code: web_code.to_string(),
274        },
275        hooks.web,
276    )
277    .await?;
278
279    let ensured = ensure_chat_from_web_access(
280        authorization,
281        &AccessScope::AccessCode {
282            access_code: web_code.to_string(),
283        },
284        EnsureOptions::default(),
285    )
286    .await?;
287    let (chat, chat_self) = connect_room(
288        authorization,
289        &ChatTarget::Code { code: ensured.code },
290        hooks.chat,
291    )
292    .await?;
293
294    Ok(ExtensionWebSession {
295        web,
296        chat,
297        web_self,
298        chat_self,
299        code: web_code.to_string(),
300        made_chat: None,
301    })
302}
303
304pub async fn invite(
305    authorization: &CredentialsOrApiKey,
306    email: &str,
307    join_url: &str,
308    scope: &AccessScope,
309) -> Result<()> {
310    let response = scoped(
311        client().post(format!(
312            "{}/extensions/web/invite",
313            crate::marmot::get_url()
314        )),
315        authorization,
316        scope,
317    )
318    .json(&json!({ "email": email, "joinUrl": join_url }))
319    .send()
320    .await?;
321    ok(response).await?;
322    Ok(())
323}