use crate::events::Present;
use crate::store::{now_ms, Change, NotesStore};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
pub const IDLE_MS: i64 = 30_000;
pub const HELD_IDLE_MS: i64 = 10 * 60_000;
pub const COLOURS: [&str; 8] = ["#d9480f", "#2b8a3e", "#1971c2", "#9c36b5", "#e8590c", "#0c8599", "#c2255c", "#5f3dc4"];
#[derive(Debug, Clone)]
struct Entry {
present: Present,
org: String,
held: u32,
last: i64,
}
#[derive(Debug, Default)]
pub struct Presence {
entries: Mutex<HashMap<(String, String), Entry>>,
}
#[derive(Debug, Clone)]
pub struct Who {
pub principal: String,
pub name: String,
pub agent: bool,
}
pub fn colour_of(principal: &str) -> &'static str {
let h = principal.bytes().fold(0u32, |h, b| h.wrapping_mul(31).wrapping_add(b as u32));
COLOURS[(h as usize) % COLOURS.len()]
}
impl NotesStore {
fn entries(&self) -> std::sync::MutexGuard<'_, HashMap<(String, String), Entry>> {
self.presence.entries.lock().unwrap_or_else(|p| p.into_inner())
}
#[allow(clippy::too_many_arguments)]
pub fn arrive(&self, id: &str, org: &str, session: &str, who: &Who, held: bool, client: Option<u64>, awareness: Option<String>) -> Present {
self.sweep();
let key = (id.to_string(), session.to_string());
let mut entries = self.entries();
let e = entries.entry(key).or_insert_with(|| Entry {
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() },
org: org.to_string(),
held: 0,
last: now_ms(),
});
if held {
e.held += 1;
}
if client.is_some() {
e.present.client = client;
}
if awareness.is_some() {
e.present.awareness = awareness;
}
e.last = now_ms();
e.present.at = e.last;
let present = e.present.clone();
drop(entries);
self.said(Change::Present { org: org.to_string(), present: present.clone() });
present
}
pub fn taken(&self, id: &str, session: &str, principal: &str) -> bool {
self.entries().get(&(id.to_string(), session.to_string())).is_some_and(|e| e.present.principal != principal)
}
pub fn leave(&self, id: &str, session: &str) {
let key = (id.to_string(), session.to_string());
let mut entries = self.entries();
let gone = match entries.get_mut(&key) {
Some(e) if e.held > 1 => {
e.held -= 1;
None
}
Some(_) => entries.remove(&key),
None => None,
};
drop(entries);
if let Some(e) = gone {
self.said(Change::Left { id: e.present.id, org: e.org, session: e.present.session, client: e.present.client });
}
}
pub fn present(&self, id: &str) -> Vec<Present> {
self.sweep();
let mut out: Vec<Present> = self.entries().values().filter(|e| e.present.id == id).map(|e| e.present.clone()).collect();
out.sort_by(|a, b| a.at.cmp(&b.at).then(a.session.cmp(&b.session)));
out
}
pub fn sweep(&self) {
let now = now_ms();
let mut entries = self.entries();
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();
let gone: Vec<Entry> = idle.into_iter().filter_map(|k| entries.remove(&k)).collect();
drop(entries);
for e in gone {
self.said(Change::Left { id: e.present.id, org: e.org, session: e.present.session, client: e.present.client });
}
}
}
pub struct Held {
pub(crate) store: Arc<NotesStore>,
pub(crate) id: String,
pub(crate) session: String,
}
impl Drop for Held {
fn drop(&mut self) {
self.store.leave(&self.id, &self.session);
}
}