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::chat::{CreateChatOptions, create_chat, delete_chat};
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;
pub fn share_url(code: &str, origin: Option<&str>) -> String {
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>>,
}
#[derive(Clone)]
pub struct ExtensionWebSession {
pub web: WebRoom,
pub chat: ChatRoom,
pub web_self: Presence,
pub chat_self: Presence,
pub code: String,
made_chat: Option<(CredentialsOrApiKey, String)>,
}
impl ExtensionWebSession {
pub fn share_code(&self) -> String {
self.code.clone()
}
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();
if let Some((authorization, chat_id)) = self.made_chat.clone() {
tokio::spawn(async move {
let _ = delete_chat(&authorization, &chat_id, None).await;
});
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedChatRoom {
pub chat_id: String,
pub reference: String,
pub room_id: String,
pub code: String,
}
async fn open_share_chat(authorization: &CredentialsOrApiKey) -> Result<CachedChatRoom> {
let chat_id = create_chat(
authorization,
Some("Web share"),
None,
CreateChatOptions {
temporary: Some(true),
..CreateChatOptions::default()
},
)
.await?;
let opened = open_room(
authorization,
&chat_id,
OpenRoomOptions {
share: Some(true),
..OpenRoomOptions::default()
},
)
.await?;
Ok(CachedChatRoom {
chat_id,
reference: opened.reference,
room_id: opened.room_id,
code: opened.code.unwrap_or_default(),
})
}
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());
}
open_share_chat(authorization).await
}
pub async fn end_chat_room(
authorization: &CredentialsOrApiKey,
chat: &CachedChatRoom,
) -> Result<()> {
delete_chat(authorization, &chat.chat_id, None).await
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessScope {
AccessCode { access_code: String },
Reference { reference: String },
}
#[derive(Debug, Clone, Default)]
pub struct EnsureOptions {
pub room: Option<String>,
}
#[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),
}
}
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(),
)),
}
}
pub async fn open_session(
authorization: &CredentialsOrApiKey,
hooks: SessionHooks,
) -> Result<ExtensionWebSession> {
let opened_chat = open_share_chat(authorization).await?;
let chat_code = opened_chat.code.clone();
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,
made_chat: Some((authorization.clone(), opened_chat.chat_id)),
})
}
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(),
made_chat: None,
})
}
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(())
}