2025-02-23 01:17:45 -05:00
|
|
|
use conduwuit::{Error, Result, utils};
|
2024-07-27 23:25:13 +00:00
|
|
|
use ruma::{
|
2025-02-23 01:17:45 -05:00
|
|
|
UInt, UserId,
|
2024-07-27 23:25:13 +00:00
|
|
|
events::presence::{PresenceEvent, PresenceEventContent},
|
|
|
|
|
presence::PresenceState,
|
|
|
|
|
};
|
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
|
|
|
|
|
|
use crate::users;
|
|
|
|
|
|
|
|
|
|
/// Represents data required to be kept in order to implement the presence
|
|
|
|
|
/// specification.
|
|
|
|
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
|
|
|
|
pub(super) struct Presence {
|
|
|
|
|
state: PresenceState,
|
|
|
|
|
currently_active: bool,
|
|
|
|
|
last_active_ts: u64,
|
|
|
|
|
status_msg: Option<String>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Presence {
|
|
|
|
|
#[must_use]
|
|
|
|
|
pub(super) fn new(
|
2024-12-15 00:05:47 -05:00
|
|
|
state: PresenceState,
|
|
|
|
|
currently_active: bool,
|
|
|
|
|
last_active_ts: u64,
|
|
|
|
|
status_msg: Option<String>,
|
2024-07-27 23:25:13 +00:00
|
|
|
) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
state,
|
|
|
|
|
currently_active,
|
|
|
|
|
last_active_ts,
|
|
|
|
|
status_msg,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub(super) fn from_json_bytes(bytes: &[u8]) -> Result<Self> {
|
2024-12-15 00:05:47 -05:00
|
|
|
serde_json::from_slice(bytes)
|
|
|
|
|
.map_err(|_| Error::bad_database("Invalid presence data in database"))
|
2024-07-27 23:25:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Creates a PresenceEvent from available data.
|
2024-12-15 00:05:47 -05:00
|
|
|
pub(super) async fn to_presence_event(
|
|
|
|
|
&self,
|
|
|
|
|
user_id: &UserId,
|
|
|
|
|
users: &users::Service,
|
|
|
|
|
) -> PresenceEvent {
|
2024-07-27 23:25:13 +00:00
|
|
|
let now = utils::millis_since_unix_epoch();
|
2025-01-08 17:57:12 +08:00
|
|
|
let last_active_ago = Some(UInt::new_saturating(now.saturating_sub(self.last_active_ts)));
|
2024-07-27 23:25:13 +00:00
|
|
|
|
2024-08-08 17:18:30 +00:00
|
|
|
PresenceEvent {
|
2024-07-27 23:25:13 +00:00
|
|
|
sender: user_id.to_owned(),
|
|
|
|
|
content: PresenceEventContent {
|
|
|
|
|
presence: self.state.clone(),
|
|
|
|
|
status_msg: self.status_msg.clone(),
|
|
|
|
|
currently_active: Some(self.currently_active),
|
|
|
|
|
last_active_ago,
|
2024-08-08 17:18:30 +00:00
|
|
|
displayname: users.displayname(user_id).await.ok(),
|
|
|
|
|
avatar_url: users.avatar_url(user_id).await.ok(),
|
2024-07-27 23:25:13 +00:00
|
|
|
},
|
2024-08-08 17:18:30 +00:00
|
|
|
}
|
2024-07-27 23:25:13 +00:00
|
|
|
}
|
|
|
|
|
}
|