From 4de83b02cd4f86f9b8c4a9bdf78acc5a9632b621 Mon Sep 17 00:00:00 2001 From: Awiteb Date: Fri, 12 Jul 2024 22:50:24 +0300 Subject: [PATCH] chore: Functions to send an event to user & check if it is online Signed-off-by: Awiteb --- crates/oxidetalis/src/extensions.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/oxidetalis/src/extensions.rs b/crates/oxidetalis/src/extensions.rs index f0fa891..558c948 100644 --- a/crates/oxidetalis/src/extensions.rs +++ b/crates/oxidetalis/src/extensions.rs @@ -18,6 +18,7 @@ use std::sync::Arc; use chrono::Utc; use oxidetalis_config::Config; +use oxidetalis_core::types::PublicKey; use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator}; use salvo::Depot; use sea_orm::DatabaseConnection; @@ -25,7 +26,7 @@ use uuid::Uuid; use crate::{ nonce::NonceCache, - websocket::{OnlineUsers, ServerEvent, SocketUserData}, + websocket::{OnlineUsers, ServerEvent, SocketUserData, Unsigned}, }; /// Extension trait for the Depot. @@ -54,6 +55,12 @@ pub trait OnlineUsersExt { /// Disconnect inactive users (who not respond for the ping event) async fn disconnect_inactive_users(&self); + + /// Returns the connection id of the user, if it is online + async fn is_online(&self, public_key: &PublicKey) -> Option; + + /// Send an event to user by connection id + async fn send(&self, conn_id: &Uuid, event: ServerEvent); } impl DepotExt for Depot { @@ -113,4 +120,20 @@ impl OnlineUsersExt for OnlineUsers { true }); } + + async fn is_online(&self, public_key: &PublicKey) -> Option { + self.read() + .await + .iter() + .find(|(_, u)| &u.public_key == public_key) + .map(|(c, _)| *c) + } + + async fn send(&self, conn_id: &Uuid, event: ServerEvent) { + if let Some((_, user)) = self.read().await.iter().find(|(c, _)| *c == conn_id) { + let _ = user + .sender + .unbounded_send(Ok(event.sign(&user.shared_secret).as_ref().into())); + } + } }