1use crate::events::Present;
16use crate::store::{now_ms, Change, NotesStore};
17use std::collections::HashMap;
18use std::sync::{Arc, Mutex};
19
20pub const IDLE_MS: i64 = 30_000;
22pub const HELD_IDLE_MS: i64 = 10 * 60_000;
24
25pub const COLOURS: [&str; 8] = ["#d9480f", "#2b8a3e", "#1971c2", "#9c36b5", "#e8590c", "#0c8599", "#c2255c", "#5f3dc4"];
29
30#[derive(Debug, Clone)]
31struct Entry {
32 present: Present,
33 org: String,
34 held: u32,
35 last: i64,
36}
37
38#[derive(Debug, Default)]
40pub struct Presence {
41 entries: Mutex<HashMap<(String, String), Entry>>,
42}
43
44#[derive(Debug, Clone)]
46pub struct Who {
47 pub principal: String,
48 pub name: String,
49 pub agent: bool,
50}
51
52pub fn colour_of(principal: &str) -> &'static str {
54 let h = principal.bytes().fold(0u32, |h, b| h.wrapping_mul(31).wrapping_add(b as u32));
55 COLOURS[(h as usize) % COLOURS.len()]
56}
57
58impl NotesStore {
59 fn entries(&self) -> std::sync::MutexGuard<'_, HashMap<(String, String), Entry>> {
60 self.presence.entries.lock().unwrap_or_else(|p| p.into_inner())
61 }
62
63 #[allow(clippy::too_many_arguments)]
67 pub fn arrive(&self, id: &str, org: &str, session: &str, who: &Who, held: bool, client: Option<u64>, awareness: Option<String>) -> Present {
68 self.sweep();
69 let key = (id.to_string(), session.to_string());
70 let mut entries = self.entries();
71 let e = entries.entry(key).or_insert_with(|| Entry {
72 present: Present { id: id.to_string(), session: session.to_string(), principal: who.principal.clone(), name: who.name.clone(), agent: who.agent, colour: colour_of(&who.principal).to_string(), client: None, awareness: None, at: now_ms() },
73 org: org.to_string(),
74 held: 0,
75 last: now_ms(),
76 });
77 if held {
78 e.held += 1;
79 }
80 if client.is_some() {
81 e.present.client = client;
82 }
83 if awareness.is_some() {
84 e.present.awareness = awareness;
85 }
86 e.last = now_ms();
87 e.present.at = e.last;
88 let present = e.present.clone();
89 drop(entries);
90 self.said(Change::Present { org: org.to_string(), present: present.clone() });
91 present
92 }
93
94 pub fn taken(&self, id: &str, session: &str, principal: &str) -> bool {
96 self.entries().get(&(id.to_string(), session.to_string())).is_some_and(|e| e.present.principal != principal)
97 }
98
99 pub fn leave(&self, id: &str, session: &str) {
102 let key = (id.to_string(), session.to_string());
103 let mut entries = self.entries();
104 let gone = match entries.get_mut(&key) {
105 Some(e) if e.held > 1 => {
106 e.held -= 1;
107 None
108 }
109 Some(_) => entries.remove(&key),
110 None => None,
111 };
112 drop(entries);
113 if let Some(e) = gone {
114 self.said(Change::Left { id: e.present.id, org: e.org, session: e.present.session, client: e.present.client });
115 }
116 }
117
118 pub fn present(&self, id: &str) -> Vec<Present> {
120 self.sweep();
121 let mut out: Vec<Present> = self.entries().values().filter(|e| e.present.id == id).map(|e| e.present.clone()).collect();
122 out.sort_by(|a, b| a.at.cmp(&b.at).then(a.session.cmp(&b.session)));
123 out
124 }
125
126 pub fn sweep(&self) {
128 let now = now_ms();
129 let mut entries = self.entries();
130 let idle: Vec<(String, String)> = entries.iter().filter(|(_, e)| now - e.last > if e.held > 0 { HELD_IDLE_MS } else { IDLE_MS }).map(|(k, _)| k.clone()).collect();
131 let gone: Vec<Entry> = idle.into_iter().filter_map(|k| entries.remove(&k)).collect();
132 drop(entries);
133 for e in gone {
134 self.said(Change::Left { id: e.present.id, org: e.org, session: e.present.session, client: e.present.client });
135 }
136 }
137}
138
139pub struct Held {
142 pub(crate) store: Arc<NotesStore>,
143 pub(crate) id: String,
144 pub(crate) session: String,
145}
146
147impl Drop for Held {
148 fn drop(&mut self) {
149 self.store.leave(&self.id, &self.session);
150 }
151}