use std::collections::BTreeSet; use bytes::Bytes; use common::{ event::{Down, Event, Media}, frame::{self, DOWN_MAX}, model::{Id, Presence}, }; use tracing::warn; use crate::{ db::{self, Connection}, error::ServerError, hub::{ConnId, Hub}, network::Shared, }; pub enum To { User(Id), Users(Vec), Community(Id), CommunityExcept(Id, Id), Outsiders(Id), Related(Id), Builders, Everyone, Conn(ConnId), } pub struct Broadcast { pub to: To, pub down: Down, } impl Broadcast { pub fn new(to: To, event: Event) -> Self { Self { to, down: Down::Event(Box::new(event)), } } pub fn media(conn: ConnId, media: Media) -> Self { Self { to: To::Conn(conn), down: Down::Media(media), } } } pub(crate) async fn publish(shared: &Shared, db: &Connection, broadcasts: Vec) { for broadcast in broadcasts { match resolve(shared, &broadcast, db).await { Ok(ids) => deliver(&shared.services.hub, &ids, &broadcast.down), Err(error) => warn!("resolve: {error}"), } } } pub(crate) fn direct(hub: &Hub, broadcasts: Vec) { for broadcast in broadcasts { let ids = match &broadcast.to { To::Conn(id) => vec![*id], To::User(user_id) => hub.conns_of(std::slice::from_ref(user_id)), To::Users(user_ids) => hub.conns_of(user_ids), _ => { warn!("direct: target needs the database"); continue; } }; deliver(hub, &ids, &broadcast.down); } } pub(crate) async fn job( shared: &Shared, work: impl AsyncFnOnce(&Connection) -> Result, ServerError>, ) -> Result<(), ServerError> { let db = shared.db.lock().await?; let out = db::atomic(&db, work(&db)).await?; publish(shared, &db, out).await; Ok(()) } fn deliver(hub: &Hub, ids: &[ConnId], down: &Down) { let Ok(framed) = frame::encode(down, DOWN_MAX) else { warn!("event too large"); return; }; let droppable = matches!(down, Down::Event(event) if matches!(**event, Event::Typing { .. })); hub.send(ids, &Bytes::from(framed), droppable); } async fn resolve( shared: &Shared, broadcast: &Broadcast, db: &Connection, ) -> Result, ServerError> { let hub = &shared.services.hub; let mut ids = match &broadcast.to { To::Conn(id) => vec![*id], To::Everyone => hub.all(), To::User(user_id) => hub.conns_of(std::slice::from_ref(user_id)), To::Users(user_ids) => hub.conns_of(user_ids), To::Builders => hub.conns_of(&db::user::builder_ids(db).await?), To::Community(community_id) => community_conns(shared, *community_id, db).await?, To::CommunityExcept(community_id, user_id) => { let mut ids = community_conns(shared, *community_id, db).await?; let own = hub.conns_of(std::slice::from_ref(user_id)); ids.retain(|id| !own.contains(id)); ids } To::Related(user_id) => hub.conns_of(&related_user_ids(*user_id, db).await?), To::Outsiders(community_id) => { let mut ids = community_conns(shared, *community_id, db).await?; let inside = hub.conns_of(&shared.services.rooms.room_users(*community_id)); ids.retain(|id| !inside.contains(id)); ids } }; let community = matches!(broadcast.to, To::Community(_) | To::CommunityExcept(..)); if let Some((community_id, user_id)) = voice_subject(&broadcast.down).filter(|_| community) && hidden(user_id, community_id, db).await { let mut insiders = shared.services.rooms.room_users(community_id); insiders.push(user_id); let keep = hub.conns_of(&insiders); ids.retain(|id| keep.contains(id)); } Ok(ids) } pub(crate) async fn hidden(user_id: Id, community_id: Id, db: &Connection) -> bool { matches!(db::user::presence(user_id, db).await, Ok(Presence::Offline)) && !matches!( db::community::kind_of(community_id, db).await, Ok(Some(db::community::Kind::Direct)) ) } fn voice_subject(down: &Down) -> Option<(Id, Id)> { let Down::Event(event) = down else { return None; }; match &**event { Event::VoiceJoined { community_id, user_id, } | Event::VoiceLeft { community_id, user_id, } | Event::VoiceMuted { community_id: Some(community_id), user_id, .. } | Event::ShareStopped { community_id, user_id, .. } => Some((*community_id, *user_id)), Event::ShareStarted { community_id, share, } => Some((*community_id, share.user_id)), _ => None, } } async fn community_conns( shared: &Shared, community_id: Id, db: &Connection, ) -> Result, ServerError> { let hub = &shared.services.hub; let mut ids = hub.conns_of(&db::member::member_ids(community_id, db).await?); ids.extend(hub.watchers(community_id)); ids.sort_unstable(); ids.dedup(); Ok(ids) } pub(crate) async fn related_user_ids(user_id: Id, db: &Connection) -> Result, ServerError> { let mut user_ids = BTreeSet::from([user_id]); for community in db::community::communities_of(user_id, db).await? { user_ids.extend(db::member::member_ids(community.id, db).await?); } for friend in db::friend::state(user_id, db).await?.friends { user_ids.insert(friend.id); } Ok(user_ids.into_iter().collect()) }