Skip to main content

fauna_api/
rooms.rs

1use std::ops::Deref;
2use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
3
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6use serde_json::{Value, json};
7
8use crate::authentification::{CredentialsOrApiKey, Profile};
9use crate::error::Result;
10use crate::http::{client, encode, ok};
11use crate::shared::server::{
12    Authorization, Hooks as ServerHooks, Presence, Room, connect as connect_server,
13};
14use crate::tickets::{optional, parse_date};
15
16/// What a member may do: `read` sees the state, `write` can also set it.
17#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "lowercase")]
19pub enum Role {
20    #[default]
21    Read,
22    Write,
23}
24
25/// Who is in a room: everyone in a group, directly or through a nested group, or
26/// one person by email. A person's room takes groups its owner is in; a group's
27/// room takes groups nested inside it.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(untagged)]
30pub enum Member {
31    Group { group: String, role: Role },
32    Email { email: String, role: Role },
33}
34
35/// A live room a person or a group owns. Everyone in it sees `state` change live.
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct LiveRoom {
38    pub id: String,
39    pub name: String,
40
41    /// The group that owns it; `None` when a person does.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub group: Option<String>,
44
45    pub members: Vec<Member>,
46
47    /// Any JSON, up to 256 KB, always set whole. Fauna never reads it.
48    pub state: Value,
49    /// Goes up by one with every state change.
50    pub version: u64,
51
52    pub created: DateTime<Utc>,
53    pub updated: DateTime<Utc>,
54}
55
56impl LiveRoom {
57    pub fn from_json(json: &Value) -> LiveRoom {
58        LiveRoom {
59            id: json["id"].as_str().unwrap_or_default().to_string(),
60            name: json["name"].as_str().unwrap_or_default().to_string(),
61            group: optional(&json["group"]),
62            members: serde_json::from_value(json["members"].clone()).unwrap_or_default(),
63            state: json["state"].clone(),
64            version: json["version"].as_u64().unwrap_or_default(),
65            created: parse_date(&json["created"]).unwrap_or_default(),
66            updated: parse_date(&json["updated"]).unwrap_or_default(),
67        }
68    }
69}
70
71/// What `create` takes. Every field is optional.
72#[derive(Debug, Clone, Default, Serialize)]
73pub struct Draft {
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub name: Option<String>,
76    /// A group you are a direct admin of, to own the room. Without it, you own it.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub group: Option<String>,
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub members: Option<Vec<Member>>,
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub state: Option<Value>,
83}
84
85/// One of a room's groups someone is in: `through` is the group's own id when
86/// they are directly in it, else the nested group they come in through.
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct PersonGroup {
89    pub id: String,
90    pub through: String,
91}
92
93impl PersonGroup {
94    pub fn from_json(json: &Value) -> PersonGroup {
95        PersonGroup {
96            id: json["id"].as_str().unwrap_or_default().to_string(),
97            through: json["through"].as_str().unwrap_or_default().to_string(),
98        }
99    }
100}
101
102/// Someone in a room: their profile, and each of the room's groups they're in.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct Person {
105    pub profile: Profile,
106    pub groups: Vec<PersonGroup>,
107}
108
109impl Person {
110    pub fn from_json(json: &Value) -> Person {
111        Person {
112            profile: Profile::from_json(&json["profile"]).unwrap_or_default(),
113            groups: json["groups"]
114                .as_array()
115                .map(|groups| groups.iter().map(PersonGroup::from_json).collect())
116                .unwrap_or_default(),
117        }
118    }
119}
120
121/// Room hooks, plus `on_state` whenever someone changes the state. Every method
122/// defaults to a no-op.
123pub trait Hooks: ServerHooks {
124    fn on_state(&self, _room: &StateRoom, _state: &Value, _version: u64) {}
125}
126
127impl Hooks for () {}
128
129/// Make a live room. You own it, also when you sign with an API key, or with
130/// `draft.group`, that group does: you must be its direct admin. Everyone in an
131/// owner group reads its room, and its admins manage it. Only the owner changes
132/// who is in it or deletes it.
133pub async fn create(authorization: &CredentialsOrApiKey, draft: &Draft) -> Result<LiveRoom> {
134    let response = client()
135        .post(format!("{}/rooms", crate::get_url()))
136        .header(
137            "Authorization",
138            match authorization {
139                CredentialsOrApiKey::Credentials(credentials) => {
140                    format!("Token {}", credentials.token)
141                }
142                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
143            },
144        )
145        .json(draft)
146        .send()
147        .await?;
148    let json: Value = ok(response).await?.json().await?;
149    Ok(LiveRoom::from_json(&json))
150}
151
152/// A room you own or are a member of, with its state.
153pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<LiveRoom> {
154    let response = client()
155        .get(format!("{}/rooms/{}", crate::get_url(), encode(id)))
156        .header(
157            "Authorization",
158            match authorization {
159                CredentialsOrApiKey::Credentials(credentials) => {
160                    format!("Token {}", credentials.token)
161                }
162                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
163            },
164        )
165        .send()
166        .await?;
167    let json: Value = ok(response).await?.json().await?;
168    Ok(LiveRoom::from_json(&json))
169}
170
171/// Everyone in a room: everyone in its groups (and its owner group), directly or
172/// through a nested group, and its email members. Anyone who can read the room.
173pub async fn people(authorization: &CredentialsOrApiKey, id: &str) -> Result<Vec<Person>> {
174    let response = client()
175        .get(format!("{}/rooms/{}/people", crate::get_url(), encode(id)))
176        .header(
177            "Authorization",
178            match authorization {
179                CredentialsOrApiKey::Credentials(credentials) => {
180                    format!("Token {}", credentials.token)
181                }
182                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
183            },
184        )
185        .send()
186        .await?;
187    let rows: Vec<Value> = ok(response).await?.json().await?;
188    Ok(rows.iter().map(Person::from_json).collect())
189}
190
191/// Replace who is in a room. Its owner only: the person, or for a group's room,
192/// that group's admins.
193pub async fn set_members(
194    authorization: &CredentialsOrApiKey,
195    id: &str,
196    members: &[Member],
197) -> Result<LiveRoom> {
198    let response = client()
199        .put(format!("{}/rooms/{}/members", crate::get_url(), encode(id)))
200        .header(
201            "Authorization",
202            match authorization {
203                CredentialsOrApiKey::Credentials(credentials) => {
204                    format!("Token {}", credentials.token)
205                }
206                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
207            },
208        )
209        .json(&json!({ "members": members }))
210        .send()
211        .await?;
212    let json: Value = ok(response).await?.json().await?;
213    Ok(LiveRoom::from_json(&json))
214}
215
216/// Replace a room's state; everyone in it sees the change. The owner (for a
217/// group's room, that group's admins) and writers only. With `if_version`, it
218/// writes only while the room is still at that version. Resolves to the new
219/// version.
220pub async fn set_state(
221    authorization: &CredentialsOrApiKey,
222    id: &str,
223    state: &Value,
224    if_version: Option<u64>,
225) -> Result<u64> {
226    let response = client()
227        .put(format!("{}/rooms/{}/state", crate::get_url(), encode(id)))
228        .header(
229            "Authorization",
230            match authorization {
231                CredentialsOrApiKey::Credentials(credentials) => {
232                    format!("Token {}", credentials.token)
233                }
234                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
235            },
236        )
237        .json(&json!({ "state": state, "ifVersion": if_version }))
238        .send()
239        .await?;
240    let body: Value = ok(response).await?.json().await?;
241    Ok(body["version"].as_u64().unwrap_or_default())
242}
243
244/// Delete a room; everyone in it is disconnected. Its owner only: the person, or
245/// for a group's room, that group's admins.
246pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
247    let response = client()
248        .delete(format!("{}/rooms/{}", crate::get_url(), encode(id)))
249        .header(
250            "Authorization",
251            match authorization {
252                CredentialsOrApiKey::Credentials(credentials) => {
253                    format!("Token {}", credentials.token)
254                }
255                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
256            },
257        )
258        .send()
259        .await?;
260    ok(response).await?;
261    Ok(())
262}
263
264#[derive(Default)]
265struct Snapshot {
266    name: String,
267    state: Value,
268    version: u64,
269    role: Role,
270}
271
272/// A live room you are in: its state, kept current, and who else is here.
273#[derive(Clone)]
274pub struct StateRoom {
275    room: Room,
276    snapshot: Arc<Mutex<Snapshot>>,
277}
278
279impl Deref for StateRoom {
280    type Target = Room;
281    fn deref(&self) -> &Room {
282        &self.room
283    }
284}
285
286struct StateHooks {
287    snapshot: Arc<Mutex<Snapshot>>,
288    user: Arc<dyn Hooks>,
289}
290
291impl StateHooks {
292    fn room(&self, room: &Room) -> StateRoom {
293        StateRoom {
294            room: room.clone(),
295            snapshot: self.snapshot.clone(),
296        }
297    }
298}
299
300impl ServerHooks for StateHooks {
301    fn create_room(&self, room: &Room, state: &Value) {
302        self.user.create_room(room, state);
303    }
304
305    fn create_presence(&self, room: &Room, presence: &Presence) {
306        self.user.create_presence(room, presence);
307    }
308
309    fn remove_presence(&self, room: &Room, presence: &Presence) {
310        self.user.remove_presence(room, presence);
311    }
312
313    fn on_connection(&self, room: &Room, state: &Value) {
314        self.room(room).hydrate(state);
315        self.user.on_connection(room, state);
316    }
317
318    fn on_event(&self, room: &Room, packet: &Value) -> bool {
319        let live = self.room(room);
320        let handled = live.handle_event(packet);
321        if handled {
322            self.user.on_state(&live, &live.state(), live.version());
323        }
324        self.user.on_event(room, packet) || handled
325    }
326
327    fn on_presence(&self, room: &Room) {
328        self.user.on_presence(room);
329    }
330
331    fn on_closed(&self, room: &Room, reason: Option<&str>) {
332        self.user.on_closed(room, reason);
333    }
334}
335
336impl StateRoom {
337    fn snapshot(&self) -> MutexGuard<'_, Snapshot> {
338        self.snapshot.lock().unwrap_or_else(PoisonError::into_inner)
339    }
340
341    pub fn name(&self) -> String {
342        self.snapshot().name.clone()
343    }
344
345    pub fn state(&self) -> Value {
346        self.snapshot().state.clone()
347    }
348
349    pub fn version(&self) -> u64 {
350        self.snapshot().version
351    }
352
353    /// What you may do here. The owner writes.
354    pub fn role(&self) -> Role {
355        self.snapshot().role
356    }
357
358    pub fn hydrate(&self, snapshot: &Value) {
359        if !snapshot.is_object() {
360            return;
361        }
362        let mut current = self.snapshot();
363        current.name = snapshot["name"].as_str().unwrap_or_default().to_string();
364        current.state = snapshot["state"].clone();
365        current.version = snapshot["version"].as_u64().unwrap_or_default();
366        current.role = if snapshot["role"] == "write" {
367            Role::Write
368        } else {
369            Role::Read
370        };
371    }
372
373    pub fn handle_event(&self, packet: &Value) -> bool {
374        if packet["event"] != "state" {
375            return false;
376        }
377        let mut current = self.snapshot();
378        current.state = packet["data"]["state"].clone();
379        if let Some(version) = packet["data"]["version"].as_u64() {
380            current.version = version;
381        }
382        true
383    }
384
385    /// Replace the state for everyone here. Writers only; with `if_version`, only
386    /// while the room is at that version.
387    pub fn set_state(&self, state: &Value, if_version: Option<u64>) {
388        self.post(&json!({
389            "event": "set-state",
390            "data": { "state": state, "ifVersion": if_version },
391        }));
392    }
393
394    pub async fn connect(
395        authorization: &CredentialsOrApiKey,
396        target_id: &str,
397        hooks: Option<Arc<dyn Hooks>>,
398    ) -> Result<(StateRoom, Presence)> {
399        let snapshot = Arc::new(Mutex::new(Snapshot::default()));
400        let me = connect_server(
401            Authorization::Server {
402                authorization: authorization.clone(),
403                server: format!("fauna:live:{target_id}"),
404                group: None,
405            },
406            &format!("{}/rooms/live", crate::get_url()),
407            Arc::new(StateHooks {
408                snapshot: snapshot.clone(),
409                user: hooks.unwrap_or_else(|| Arc::new(())),
410            }),
411        )
412        .await?;
413        let room = StateRoom {
414            room: me.room().clone(),
415            snapshot,
416        };
417        Ok((room, me))
418    }
419}