fauna_api/extensions/web/
session.rs1use 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::generative::Tool;
12use crate::parrot::room::{ChatRoom, RoomHooks, connect_room};
13use crate::parrot::share::{ChatTarget, OpenRoomOptions, open_room};
14use crate::shared::server::Presence;
15
16pub fn share_url(code: &str, origin: Option<&str>) -> String {
19 let origin = origin.unwrap_or("https://app.faunakit.com");
22 format!(
23 "{}/extensions/web/?access-code={}",
24 origin.strip_suffix('/').unwrap_or(origin),
25 encode(code)
26 )
27}
28
29#[derive(Default, Clone)]
30pub struct SessionHooks {
31 pub web: Option<Arc<dyn WebRoomHooks>>,
32 pub chat: Option<Arc<dyn RoomHooks>>,
33}
34
35#[derive(Clone)]
38pub struct ExtensionWebSession {
39 pub web: WebRoom,
40 pub chat: ChatRoom,
41 pub web_self: Presence,
42 pub chat_self: Presence,
43 pub code: String,
45}
46
47impl ExtensionWebSession {
48 pub fn share_code(&self) -> String {
49 self.code.clone()
50 }
51
52 pub fn page_tools(&self) -> Vec<Tool> {
54 let web = self.web.clone();
55 page_tools(Arc::new(move |name, params| {
56 let web = web.clone();
57 Box::pin(async move {
58 let name = match serde_json::to_value(name)? {
59 Value::String(name) => name,
60 name => name.to_string(),
61 };
62 web.invoke_tool(&name, params, None).await
63 })
64 }))
65 }
66
67 pub fn close(&self) {
68 self.web.publish_closed();
69 self.web.disconnect();
70 self.chat.disconnect();
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "camelCase")]
79pub struct CachedChatRoom {
80 pub reference: String,
81 pub room_id: String,
82 pub code: String,
83}
84
85pub async fn ensure_chat_room(
89 authorization: &CredentialsOrApiKey,
90 cached: Option<&CachedChatRoom>,
91) -> Result<CachedChatRoom> {
92 if let Some(cached) = cached.filter(|cached| !cached.code.is_empty()) {
93 return Ok(cached.clone());
94 }
95 let opened = open_room(
96 authorization,
97 OpenRoomOptions {
98 share: Some(true),
99 ..OpenRoomOptions::default()
100 },
101 )
102 .await?;
103 Ok(CachedChatRoom {
104 reference: opened.reference,
105 room_id: opened.room_id,
106 code: opened.code.unwrap_or_default(),
107 })
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
113pub enum AccessScope {
114 AccessCode { access_code: String },
115 Reference { reference: String },
116}
117
118#[derive(Debug, Clone, Default)]
120pub struct EnsureOptions {
121 pub room: Option<String>,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct EnsuredChat {
127 pub room: String,
128 pub code: String,
129}
130
131fn scoped(
132 request: reqwest::RequestBuilder,
133 authorization: &CredentialsOrApiKey,
134 scope: &AccessScope,
135) -> reqwest::RequestBuilder {
136 let request = request.header("Content-Type", "application/json").header(
137 "Authorization",
138 match authorization {
139 CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
140 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
141 },
142 );
143 match scope {
144 AccessScope::AccessCode { access_code } => request.header("Access-Code", access_code),
145 AccessScope::Reference { reference } => request.header("Server", reference),
146 }
147}
148
149pub async fn ensure_chat_from_web_access(
153 authorization: &CredentialsOrApiKey,
154 scope: &AccessScope,
155 opts: EnsureOptions,
156) -> Result<EnsuredChat> {
157 let body = match opts.room.filter(|room| !room.is_empty()) {
158 Some(room) => json!({ "room": room }),
159 None => json!({}),
160 };
161 let response = scoped(
162 client().post(format!(
163 "{}/extensions/web/chat/ensure",
164 crate::marmot::get_url()
165 )),
166 authorization,
167 scope,
168 )
169 .json(&body)
170 .send()
171 .await?;
172 let json: Value = ok(response).await?.json().await?;
173 match (
174 json["room"].as_str().filter(|room| !room.is_empty()),
175 json["code"].as_str().filter(|code| !code.is_empty()),
176 ) {
177 (Some(room), Some(code)) => Ok(EnsuredChat {
178 room: room.to_string(),
179 code: code.to_string(),
180 }),
181 _ => Err(Error::Message(
182 "Invalid web chat ensure response.".to_string(),
183 )),
184 }
185}
186
187pub async fn open_session(
190 authorization: &CredentialsOrApiKey,
191 hooks: SessionHooks,
192) -> Result<ExtensionWebSession> {
193 let opened_chat = open_room(
194 authorization,
195 OpenRoomOptions {
196 share: Some(true),
197 ..OpenRoomOptions::default()
198 },
199 )
200 .await?;
201 let chat_code = opened_chat.code.clone().unwrap_or_default();
202
203 let reference = format!("web:{}", uuid::Uuid::new_v4());
204 let (web, web_self) = connect_web_room(
205 authorization,
206 &WebTarget::Reference {
207 reference: reference.clone(),
208 },
209 hooks.web,
210 )
211 .await?;
212 let web_code = web.generate_access_code().await?;
213 ensure_chat_from_web_access(
214 authorization,
215 &AccessScope::Reference { reference },
216 EnsureOptions {
217 room: Some(opened_chat.reference),
218 },
219 )
220 .await?;
221
222 let (chat, chat_self) = connect_room(
223 authorization,
224 &ChatTarget::Code { code: chat_code },
225 hooks.chat,
226 )
227 .await?;
228
229 Ok(ExtensionWebSession {
230 web,
231 chat,
232 web_self,
233 chat_self,
234 code: web_code,
235 })
236}
237
238pub async fn join_room(
240 authorization: &CredentialsOrApiKey,
241 web_code: &str,
242 hooks: SessionHooks,
243) -> Result<ExtensionWebSession> {
244 let (web, web_self) = connect_web_room(
245 authorization,
246 &WebTarget::Code {
247 code: web_code.to_string(),
248 },
249 hooks.web,
250 )
251 .await?;
252
253 let ensured = ensure_chat_from_web_access(
254 authorization,
255 &AccessScope::AccessCode {
256 access_code: web_code.to_string(),
257 },
258 EnsureOptions::default(),
259 )
260 .await?;
261 let (chat, chat_self) = connect_room(
262 authorization,
263 &ChatTarget::Code { code: ensured.code },
264 hooks.chat,
265 )
266 .await?;
267
268 Ok(ExtensionWebSession {
269 web,
270 chat,
271 web_self,
272 chat_self,
273 code: web_code.to_string(),
274 })
275}
276
277pub async fn invite(
278 authorization: &CredentialsOrApiKey,
279 email: &str,
280 join_url: &str,
281 scope: &AccessScope,
282) -> Result<()> {
283 let response = scoped(
284 client().post(format!(
285 "{}/extensions/web/invite",
286 crate::marmot::get_url()
287 )),
288 authorization,
289 scope,
290 )
291 .json(&json!({ "email": email, "joinUrl": join_url }))
292 .send()
293 .await?;
294 ok(response).await?;
295 Ok(())
296}