use std::collections::{BTreeMap, HashMap};
use std::ops::Deref;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};
use std::time::Duration;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use futures_util::StreamExt;
use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use tokio::sync::oneshot;
use crate::authentification::CredentialsOrApiKey;
use crate::drive::Progress;
use crate::error::{Error, Result};
use crate::http::{client, ok, progress_body};
use crate::shared::server::{Authorization, Hooks, Presence, Room, connect};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum WebNode {
Element {
id: u64,
tag: String,
#[serde(default)]
attributes: BTreeMap<String, String>,
#[serde(default)]
children: Vec<u64>,
},
Text {
id: u64,
#[serde(default)]
text: String,
},
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct WebViewport {
pub width: f64,
pub height: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WebSnapshot {
pub root: u64,
pub nodes: HashMap<u64, WebNode>,
pub viewport: WebViewport,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum WebMutation {
Insert {
parent: u64,
node: WebNode,
#[serde(default)]
subtree: Vec<WebNode>,
before: Option<u64>,
},
Remove {
id: u64,
},
Text {
id: u64,
text: String,
},
Attribute {
id: u64,
name: String,
value: Option<String>,
},
Viewport {
width: f64,
height: f64,
},
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HtmlPointer {
pub x: f64,
pub y: f64,
#[serde(default)]
pub scroll_x: f64,
#[serde(default)]
pub scroll_y: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub visible: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub shape: Option<String>,
}
pub const WEB_ASSET_SCHEME: &str = "fauna-web-asset:";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchedMedia {
pub data: Vec<u8>,
pub content_type: String,
}
pub type MediaFetcher =
Arc<dyn Fn(String) -> BoxFuture<'static, Option<FetchedMedia>> + Send + Sync>;
static MEDIA_FETCHER: RwLock<Option<MediaFetcher>> = RwLock::new(None);
pub fn set_media_fetcher(fetcher: Option<MediaFetcher>) {
*MEDIA_FETCHER
.write()
.unwrap_or_else(PoisonError::into_inner) = fetcher;
}
fn consider_url(raw: Option<&str>, into: &mut Vec<String>) {
let Some(raw) = raw else {
return;
};
let trimmed = raw.trim();
if trimmed.is_empty()
|| trimmed.starts_with(WEB_ASSET_SCHEME)
|| trimmed.starts_with("javascript:")
{
return;
}
if trimmed.starts_with('#') || trimmed.starts_with("mailto:") || trimmed.starts_with("tel:") {
return;
}
if trimmed.starts_with("blob:") {
return;
}
if trimmed.starts_with("data:") {
return;
}
if !into.iter().any(|known| known == trimmed) {
into.push(trimmed.to_string());
}
}
fn find_ignore_case(haystack: &str, needle: &str, from: usize) -> Option<usize> {
let bytes = haystack.as_bytes();
let needle = needle.as_bytes();
(from..=bytes.len().saturating_sub(needle.len())).find(|&index| {
bytes.len() >= index + needle.len()
&& bytes[index..index + needle.len()].eq_ignore_ascii_case(needle)
})
}
fn skip_whitespace(text: &str, mut index: usize) -> usize {
while let Some(c) = text[index..].chars().next() {
if !c.is_whitespace() {
break;
}
index += c.len_utf8();
}
index
}
fn for_each_css_url_token(css: &str, mut visit: impl FnMut(&str, &str, usize, usize)) {
let mut from = 0;
while let Some(start) = find_ignore_case(css, "url(", from) {
let i = skip_whitespace(css, start + 4);
if i >= css.len() {
break;
}
let first = css.as_bytes()[i];
if first == b'"' || first == b'\'' {
let quote = if first == b'"' { "\"" } else { "'" };
let begin = i + 1;
let Some(close_quote) = css[begin..].find(quote).map(|offset| begin + offset) else {
break;
};
let Some(close_paren) = css[close_quote + 1..]
.find(')')
.map(|offset| close_quote + 1 + offset)
else {
break;
};
visit(&css[begin..close_quote], quote, start, close_paren + 1);
from = close_paren + 1;
continue;
}
let Some(close_paren) = css[i..].find(')').map(|offset| i + offset) else {
break;
};
visit(css[i..close_paren].trim(), "", start, close_paren + 1);
from = close_paren + 1;
}
}
fn next_import(css: &str, mut from: usize) -> Option<(usize, usize, String)> {
while let Some(start) = find_ignore_case(css, "@import", from) {
from = start + 1;
let after = start + "@import".len();
let i = skip_whitespace(css, after);
if i == after {
continue;
}
let bytes = css.as_bytes();
let mut target = None;
let mut end = i;
if find_ignore_case(css, "url(", i) == Some(i) {
let j = skip_whitespace(css, i + 4);
let quote = bytes.get(j).copied().filter(|c| *c == b'"' || *c == b'\'');
let begin = if quote.is_some() { j + 1 } else { j };
let stop = css[begin..]
.find(['\'', '"', ')'])
.map_or(css.len(), |offset| begin + offset);
if stop > begin {
let mut k = stop;
let closed = match quote {
Some(quote) => {
bytes.get(k) == Some("e) && {
k += 1;
true
}
}
None => true,
};
if closed {
let k = skip_whitespace(css, k);
if bytes.get(k) == Some(&b')') {
target = Some(css[begin..stop].to_string());
end = k + 1;
}
}
}
} else if let Some("e) = bytes.get(i).filter(|c| **c == b'"' || **c == b'\'') {
let begin = i + 1;
if let Some(stop) = css[begin..].find(['\'', '"']).map(|offset| begin + offset)
&& stop > begin
&& bytes[stop] == quote
{
target = Some(css[begin..stop].to_string());
end = stop + 1;
}
}
let Some(target) = target else {
continue;
};
let mut end = skip_whitespace(css, end);
if bytes.get(end) == Some(&b';') {
end += 1;
}
return Some((start, end, target));
}
None
}
pub fn extract_css_urls(css: &str) -> Vec<String> {
let mut found = Vec::new();
for_each_css_url_token(css, |raw, _, _, _| consider_url(Some(raw), &mut found));
let mut from = 0;
while let Some((_, end, target)) = next_import(css, from) {
consider_url(Some(&target), &mut found);
from = end;
}
found
}
pub fn rewrite_css_urls(css: &str, map: &HashMap<String, String>) -> String {
let mut out = String::new();
let mut cursor = 0;
for_each_css_url_token(css, |raw, quote, start, end| {
out.push_str(&css[cursor..start]);
match map.get(raw.trim()) {
None => out.push_str(&css[start..end]),
Some(code) => out.push_str(&format!("url({quote}{WEB_ASSET_SCHEME}{code}{quote})")),
}
cursor = end;
});
out.push_str(&css[cursor..]);
let mut rewritten = String::new();
let mut cursor = 0;
while let Some((start, end, target)) = next_import(&out, cursor) {
rewritten.push_str(&out[cursor..start]);
let trimmed = target.trim();
match map.get(trimmed) {
Some(code) if !trimmed.starts_with("data:") => {
rewritten.push_str(&format!("@import url(\"{WEB_ASSET_SCHEME}{code}\");"))
}
_ => rewritten.push_str(&out[start..end]),
}
cursor = end;
}
rewritten.push_str(&out[cursor..]);
rewritten
}
fn asset_code_at(html: &str, from: usize) -> Option<(usize, usize, &str)> {
let mut from = from;
while let Some(offset) = html[from..].find(WEB_ASSET_SCHEME) {
let start = from + offset;
let begin = start + WEB_ASSET_SCHEME.len();
let length = html[begin..]
.bytes()
.take_while(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'-')
.count();
if length > 0 {
return Some((start, begin + length, &html[begin..begin + length]));
}
from = begin;
}
None
}
pub fn extract_asset_codes(html: &str) -> Vec<String> {
let mut codes: Vec<String> = Vec::new();
let mut from = 0;
while let Some((_, end, code)) = asset_code_at(html, from) {
if !codes.iter().any(|known| known == code) {
codes.push(code.to_string());
}
from = end;
}
codes
}
pub fn materialize_asset_urls(html: &str, blobs: &HashMap<String, String>) -> String {
let mut out = String::new();
let mut cursor = 0;
while let Some((start, end, code)) = asset_code_at(html, cursor) {
out.push_str(&html[cursor..start]);
match blobs.get(code) {
Some(url) => out.push_str(url),
None => out.push_str(&html[start..end]),
}
cursor = end;
}
out.push_str(&html[cursor..]);
out
}
fn decode_data_url(url: &str) -> Option<FetchedMedia> {
let comma = url.find(',')?;
let header = &url[5..comma];
let payload = &url[comma + 1..];
let content_type = header
.split(';')
.next()
.filter(|kind| !kind.is_empty())
.unwrap_or("application/octet-stream")
.to_string();
if header.contains(";base64") {
return Some(FetchedMedia {
data: STANDARD.decode(payload).ok()?,
content_type,
});
}
Some(FetchedMedia {
data: percent_encoding::percent_decode_str(payload).collect(),
content_type,
})
}
pub async fn fetch_media_bytes(url: &str) -> Option<FetchedMedia> {
if url.starts_with("data:") {
return decode_data_url(url);
}
let fetcher = MEDIA_FETCHER
.read()
.unwrap_or_else(PoisonError::into_inner)
.clone();
if let Some(fetcher) = fetcher
&& let Some(via) = fetcher(url.to_string()).await
{
return Some(via);
}
let response = client().get(url).send().await.ok()?;
if !response.status().is_success() {
return None;
}
let content_type = response
.headers()
.get("Content-Type")
.and_then(|value| value.to_str().ok())
.filter(|value| !value.is_empty())
.unwrap_or("application/octet-stream")
.to_string();
Some(FetchedMedia {
data: response.bytes().await.ok()?.to_vec(),
content_type,
})
}
pub fn absolute_url(url: &str, base: Option<&str>) -> String {
if url.starts_with("data:") || url.starts_with("blob:") || url.starts_with(WEB_ASSET_SCHEME) {
return url.to_string();
}
let base = base
.filter(|base| !base.is_empty())
.unwrap_or("https://localhost/");
reqwest::Url::parse(base)
.and_then(|base| base.join(url))
.map(|resolved| resolved.to_string())
.unwrap_or_else(|_| url.to_string())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebTarget {
Code { code: String },
Reference { reference: String },
}
fn target_header(request: reqwest::RequestBuilder, target: &WebTarget) -> reqwest::RequestBuilder {
match target {
WebTarget::Code { code } => request.header("Access-Code", code),
WebTarget::Reference { reference } => request.header("Server", reference),
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BootstrapMeta {
pub version: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub viewport: Option<WebViewport>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_length: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub html: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AssetUploadResult {
pub asset_id: String,
pub access_code: String,
pub content_type: String,
}
#[derive(Clone, Default)]
pub struct BootstrapOptions {
pub version: Option<u64>,
pub viewport: Option<WebViewport>,
pub content_type: Option<String>,
pub on_progress: Option<Progress>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BootstrapUpload {
pub ok: bool,
pub version: u64,
}
fn authorization_header(authorization: &CredentialsOrApiKey) -> String {
match authorization {
CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
}
}
pub async fn upload_bootstrap(
authorization: &CredentialsOrApiKey,
target: &WebTarget,
html: &[u8],
options: BootstrapOptions,
) -> Result<BootstrapUpload> {
let version = options.version.unwrap_or(1);
let mut request = target_header(
client()
.post(format!("{}/extensions/web/bootstrap", super::get_url()))
.header("Authorization", authorization_header(authorization)),
target,
)
.header(
"Content-Type",
options
.content_type
.as_deref()
.unwrap_or("text/html; charset=utf-8"),
)
.header("Bootstrap-Version", version.to_string());
if let Some(viewport) = options.viewport {
request = request
.header("Viewport-Width", viewport.width.to_string())
.header("Viewport-Height", viewport.height.to_string());
}
let response = request
.header("Content-Length", html.len())
.body(progress_body(html.to_vec(), options.on_progress.clone()))
.send()
.await
.map_err(|_| Error::Message("Failed to upload bootstrap.".to_string()))?;
if let Some(progress) = &options.on_progress {
progress(1.0);
}
let status = response.status();
let text = response.text().await.unwrap_or_default();
if !status.is_success() {
return Err(Error::Message(if text.is_empty() {
format!("{}: bootstrap upload failed", status.as_u16())
} else {
text
}));
}
Ok(serde_json::from_str(&text).unwrap_or(BootstrapUpload { ok: true, version }))
}
async fn read_body(
response: reqwest::Response,
content_length: u64,
on_progress: Option<Progress>,
) -> Result<Vec<u8>> {
let mut out = Vec::new();
let mut body = response.bytes_stream();
while let Some(chunk) = body.next().await {
out.extend_from_slice(&chunk?);
if let Some(progress) = &on_progress
&& content_length > 0
{
progress((out.len() as f64 / content_length as f64).min(1.0));
}
}
if let Some(progress) = &on_progress {
progress(1.0);
}
Ok(out)
}
fn header_text(response: &reqwest::Response, name: &str) -> Option<String> {
response
.headers()
.get(name)
.and_then(|value| value.to_str().ok())
.filter(|value| !value.is_empty())
.map(str::to_string)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bootstrap {
pub html: String,
pub content_length: u64,
pub content_type: String,
}
pub async fn download_bootstrap(
authorization: &CredentialsOrApiKey,
target: &WebTarget,
on_progress: Option<Progress>,
) -> Result<Bootstrap> {
let response = target_header(
client()
.get(format!("{}/extensions/web/bootstrap", super::get_url()))
.header("Authorization", authorization_header(authorization)),
target,
)
.send()
.await?;
let response = ok(response).await?;
let content_type = header_text(&response, "Content-Type")
.unwrap_or_else(|| "text/html; charset=utf-8".to_string());
let content_length = header_text(&response, "Content-Length")
.and_then(|length| length.parse().ok())
.unwrap_or(0);
let buffer = read_body(response, content_length, on_progress).await?;
Ok(Bootstrap {
html: String::from_utf8_lossy(&buffer).into_owned(),
content_length,
content_type,
})
}
#[derive(Clone, Default)]
pub struct AssetOptions {
pub asset_id: Option<String>,
pub on_progress: Option<Progress>,
}
pub async fn upload_asset(
authorization: &CredentialsOrApiKey,
target: &WebTarget,
data: &[u8],
content_type: &str,
options: AssetOptions,
) -> Result<AssetUploadResult> {
let safe_type = content_type
.split(';')
.next()
.map(str::trim)
.filter(|kind| !kind.is_empty())
.unwrap_or("application/octet-stream");
let mut request = target_header(
client()
.post(format!("{}/extensions/web/asset", super::get_url()))
.header("Authorization", authorization_header(authorization)),
target,
)
.header("Content-Type", safe_type);
if let Some(asset_id) = &options.asset_id {
request = request.header("Asset-Id", asset_id);
}
let response = request
.header("Content-Length", data.len())
.body(progress_body(data.to_vec(), options.on_progress.clone()))
.send()
.await
.map_err(|_| Error::Message("Failed to upload asset.".to_string()))?;
if let Some(progress) = &options.on_progress {
progress(1.0);
}
let status = response.status();
let text = response.text().await.unwrap_or_default();
if !status.is_success() {
return Err(Error::Message(if text.is_empty() {
format!("{}: asset upload failed", status.as_u16())
} else {
text
}));
}
Ok(serde_json::from_str(&text)?)
}
pub async fn download_asset(
authorization: &CredentialsOrApiKey,
access_code: &str,
on_progress: Option<Progress>,
) -> Result<FetchedMedia> {
let response = client()
.get(format!("{}/extensions/web/asset", super::get_url()))
.header("Authorization", authorization_header(authorization))
.header("File-Access-Code", access_code)
.send()
.await?;
let response = ok(response).await?;
let content_type = header_text(&response, "Content-Type")
.unwrap_or_else(|| "application/octet-stream".to_string());
let content_length = header_text(&response, "Content-Length")
.and_then(|length| length.parse().ok())
.unwrap_or(0);
let data = read_body(response, content_length, on_progress).await?;
Ok(FetchedMedia { data, content_type })
}
pub struct ProgressStage {
pub weight: f64,
pub run: Box<dyn FnOnce(Progress) -> BoxFuture<'static, Result<()>> + Send>,
}
pub async fn weighted_progress(
stages: Vec<ProgressStage>,
on_progress: Option<Progress>,
) -> Result<()> {
let total = stages
.iter()
.map(|stage| stage.weight.max(0.0))
.sum::<f64>();
let total = if total == 0.0 { 1.0 } else { total };
let mut completed = 0.0;
for stage in stages {
let weight = stage.weight.max(0.0);
let outer = on_progress.clone();
let done = completed;
(stage.run)(Arc::new(move |p: f64| {
if let Some(progress) = &outer {
progress((done + p.clamp(0.0, 1.0) * weight) / total);
}
}))
.await?;
completed += weight;
if let Some(progress) = &on_progress {
progress(completed / total);
}
}
Ok(())
}
pub trait WebRoomHooks: Send + Sync {
fn on_bootstrap(&self, _room: &WebRoom, _bootstrap: &BootstrapMeta) {}
fn on_snapshot(&self, _room: &WebRoom, _snapshot: &WebSnapshot) {}
fn on_mutation(&self, _room: &WebRoom, _mutation: &WebMutation) {}
fn on_closed(&self, _room: &WebRoom) {}
fn on_presence(&self, _room: &WebRoom) {}
}
impl WebRoomHooks for () {}
pub type WebToolHandler =
Arc<dyn Fn(String, Map<String, Value>) -> BoxFuture<'static, Result<String>> + Send + Sync>;
struct WebState {
hooks: Arc<dyn WebRoomHooks>,
latest: Option<WebSnapshot>,
bootstrap: Option<BootstrapMeta>,
tool_handler: Option<(u64, WebToolHandler)>,
next_handler: u64,
pending_tools: HashMap<String, oneshot::Sender<Result<String>>>,
host_principal: Option<String>,
can_invite: bool,
owned: bool,
}
#[derive(Clone)]
pub struct WebRoom {
room: Room,
state: Arc<Mutex<WebState>>,
}
impl Deref for WebRoom {
type Target = Room;
fn deref(&self) -> &Room {
&self.room
}
}
impl WebRoom {
fn new(
room: Room,
hooks: Arc<dyn WebRoomHooks>,
connection_state: &Value,
owned: bool,
) -> WebRoom {
let meta = &connection_state["room"];
WebRoom {
room,
state: Arc::new(Mutex::new(WebState {
hooks,
latest: None,
bootstrap: None,
tool_handler: None,
next_handler: 0,
pending_tools: HashMap::new(),
host_principal: meta["hostPrincipal"]
.as_str()
.filter(|principal| !principal.is_empty())
.map(str::to_string),
can_invite: meta["canInvite"].as_bool().unwrap_or(false),
owned,
})),
}
}
fn state(&self) -> MutexGuard<'_, WebState> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
fn hooks(&self) -> Arc<dyn WebRoomHooks> {
self.state().hooks.clone()
}
pub fn set_hooks(&self, hooks: Arc<dyn WebRoomHooks>) {
self.state().hooks = hooks;
}
pub fn from_parent(
parent: &Room,
hooks: Option<Arc<dyn WebRoomHooks>>,
connection_state: &Value,
) -> WebRoom {
WebRoom::new(
parent.clone(),
hooks.unwrap_or_else(|| Arc::new(())),
connection_state,
false,
)
}
pub fn get_host_principal(&self) -> Option<String> {
self.state().host_principal.clone()
}
pub fn can_invite(&self) -> bool {
self.state().can_invite
}
pub fn get_snapshot(&self) -> Option<WebSnapshot> {
self.state().latest.clone()
}
pub fn get_bootstrap(&self) -> Option<BootstrapMeta> {
self.state().bootstrap.clone()
}
pub fn disconnect(&self) {
if !self.state().owned {
return;
}
self.room.disconnect();
}
pub fn ingest_snapshot(&self, snapshot: WebSnapshot) {
self.state().latest = Some(snapshot.clone());
self.hooks().on_snapshot(self, &snapshot);
}
pub fn ingest_bootstrap(&self, meta: BootstrapMeta) {
self.state().bootstrap = Some(meta.clone());
self.hooks().on_bootstrap(self, &meta);
}
pub fn publish_bootstrap(&self, meta: BootstrapMeta) {
self.post(&json!({ "event": "web-bootstrap", "data": { "bootstrap": meta } }));
self.state().bootstrap = Some(meta);
}
pub fn publish_snapshot(&self, snapshot: WebSnapshot) {
self.post(&json!({ "event": "web-snapshot", "data": { "snapshot": snapshot } }));
self.state().latest = Some(snapshot);
}
pub fn publish_mutation(&self, mutation: &WebMutation) {
self.post(&json!({ "event": "web-mutation", "data": { "mutation": mutation } }));
}
pub fn publish_closed(&self) {
self.post(&json!({ "event": "web-closed", "data": {} }));
}
pub fn set_tool_handler(&self, handler: WebToolHandler) -> Box<dyn FnOnce() + Send + Sync> {
let id = {
let mut state = self.state();
state.next_handler += 1;
let id = state.next_handler;
state.tool_handler = Some((id, handler));
id
};
let state = Arc::downgrade(&self.state);
Box::new(move || {
if let Some(state) = state.upgrade() {
let mut state = state.lock().unwrap_or_else(PoisonError::into_inner);
if state
.tool_handler
.as_ref()
.is_some_and(|(current, _)| *current == id)
{
state.tool_handler = None;
}
}
})
}
pub async fn invoke_tool(
&self,
name: &str,
params: Map<String, Value>,
timeout_ms: Option<u64>,
) -> Result<String> {
let handler = self
.state()
.tool_handler
.as_ref()
.map(|(_, handler)| handler.clone());
if let Some(handler) = handler {
return handler(name.to_string(), params).await;
}
let id = uuid::Uuid::new_v4().to_string();
let (resolve, result) = oneshot::channel();
self.state().pending_tools.insert(id.clone(), resolve);
self.post(&json!({ "event": "web-tool-call", "data": { "id": id, "name": name, "params": params } }));
match tokio::time::timeout(Duration::from_millis(timeout_ms.unwrap_or(30_000)), result)
.await
{
Ok(Ok(result)) => result,
_ => {
self.state().pending_tools.remove(&id);
Err(Error::Message(format!("Tool timed out: {name}")))
}
}
}
pub fn handle_event(&self, packet: &Value) -> bool {
let data = &packet["data"];
match packet["event"].as_str().unwrap_or_default() {
"web-bootstrap" => {
let bootstrap: Option<BootstrapMeta> =
serde_json::from_value(data["bootstrap"].clone()).ok();
self.state().bootstrap = bootstrap.clone();
if let Some(bootstrap) = bootstrap {
self.hooks().on_bootstrap(self, &bootstrap);
}
true
}
"web-snapshot" => {
let snapshot: Option<WebSnapshot> =
serde_json::from_value(data["snapshot"].clone()).ok();
self.state().latest = snapshot.clone();
if let Some(snapshot) = snapshot {
self.hooks().on_snapshot(self, &snapshot);
}
true
}
"web-mutation" => {
if let Ok(mutation) =
serde_json::from_value::<WebMutation>(data["mutation"].clone())
{
self.hooks().on_mutation(self, &mutation);
}
true
}
"web-tool-call" => {
self.handle_tool_call(data);
true
}
"web-tool-result" => {
let Some(id) = data["id"].as_str().filter(|id| !id.is_empty()) else {
return true;
};
let Some(pending) = self.state().pending_tools.remove(id) else {
return true;
};
let result =
if data["error"].is_null() || data["error"] == false || data["error"] == "" {
Ok(match &data["result"] {
Value::Null => String::new(),
Value::String(result) => result.clone(),
result => result.to_string(),
})
} else {
Err(Error::Message(match &data["error"] {
Value::String(error) => error.clone(),
error => error.to_string(),
}))
};
let _ = pending.send(result);
true
}
"web-closed" | "server-closed" => {
self.hooks().on_closed(self);
true
}
_ => false,
}
}
fn handle_tool_call(&self, data: &Value) {
let id = data["id"].clone();
let Some(name) = data["name"]
.as_str()
.filter(|name| !name.is_empty())
.map(str::to_string)
else {
return;
};
if id.is_null() || id == "" {
return;
}
let Some(handler) = self
.state()
.tool_handler
.as_ref()
.map(|(_, handler)| handler.clone())
else {
return;
};
let params = data["params"].as_object().cloned().unwrap_or_default();
let room = self.clone();
tokio::spawn(async move {
match handler(name, params).await {
Ok(result) => room.post(
&json!({ "event": "web-tool-result", "data": { "id": id, "result": result } }),
),
Err(error) => room.post(&json!({
"event": "web-tool-result",
"data": { "id": id, "error": error.to_string() },
})),
}
});
}
}
struct WebHooks {
room: Mutex<Option<WebRoom>>,
hooks: Arc<dyn WebRoomHooks>,
}
impl WebHooks {
fn room(&self, room: &Room, state: &Value) -> WebRoom {
let mut slot = self.room.lock().unwrap_or_else(PoisonError::into_inner);
slot.get_or_insert_with(|| WebRoom::new(room.clone(), self.hooks.clone(), state, true))
.clone()
}
}
impl Hooks for WebHooks {
fn create_room(&self, room: &Room, state: &Value) {
let created = self.room(room, state);
if let Ok(bootstrap) = serde_json::from_value::<BootstrapMeta>(state["bootstrap"].clone()) {
created.ingest_bootstrap(bootstrap);
}
if let Ok(snapshot) = serde_json::from_value::<WebSnapshot>(state["snapshot"].clone()) {
created.ingest_snapshot(snapshot);
}
}
fn on_event(&self, room: &Room, packet: &Value) -> bool {
self.room(room, &Value::Null).handle_event(packet)
}
fn on_presence(&self, room: &Room) {
let room = self.room(room, &Value::Null);
room.hooks().on_presence(&room);
}
fn on_closed(&self, room: &Room, _reason: Option<&str>) {
let room = self.room(room, &Value::Null);
room.hooks().on_closed(&room);
}
}
pub async fn connect_web_room(
authorization: &CredentialsOrApiKey,
target: &WebTarget,
hooks: Option<Arc<dyn WebRoomHooks>>,
) -> Result<(WebRoom, Presence)> {
let auth = match target {
WebTarget::Code { code } => Authorization::AccessCode {
authorization: authorization.clone(),
access_code: code.clone(),
},
WebTarget::Reference { reference } => Authorization::Server {
authorization: authorization.clone(),
server: reference.clone(),
group: None,
},
};
let web_hooks = Arc::new(WebHooks {
room: Mutex::new(None),
hooks: hooks.unwrap_or_else(|| Arc::new(())),
});
let me = connect(
auth,
&format!("{}/extensions/web/live", super::get_url()),
web_hooks.clone(),
)
.await?;
let room = web_hooks.room(me.room(), &Value::Null);
room.hooks().on_presence(&room);
Ok((room, me))
}