improve: presence

This commit is contained in:
timokoesters 2020-07-28 15:58:50 +02:00
parent 05f9d927b8
commit d891bbb5dc
No known key found for this signature in database
GPG key ID: 24DA7517711A2BA4
5 changed files with 304 additions and 149 deletions

View file

@ -1,62 +0,0 @@
use crate::{Error, Result};
use ruma::Raw;
pub struct GlobalEdus {
//pub globalallid_globalall: sled::Tree, // ToDevice, GlobalAllId = UserId + Count
pub(super) presenceid_presence: sled::Tree, // Presence, PresenceId = Count + UserId
}
impl GlobalEdus {
/// Adds a global event which will be saved until a new event replaces it (e.g. presence updates).
pub fn update_presence(
&self,
presence: ruma::events::presence::PresenceEvent,
globals: &super::globals::Globals,
) -> Result<()> {
// Remove old entry
if let Some(old) = self
.presenceid_presence
.iter()
.keys()
.rev()
.filter_map(|r| r.ok())
.find(|key| {
key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element")
== presence.sender.to_string().as_bytes()
})
{
// This is the old global_latest
self.presenceid_presence.remove(old)?;
}
let mut presence_id = globals.next_count()?.to_be_bytes().to_vec();
presence_id.push(0xff);
presence_id.extend_from_slice(&presence.sender.to_string().as_bytes());
self.presenceid_presence.insert(
presence_id,
&*serde_json::to_string(&presence).expect("PresenceEvent can be serialized"),
)?;
Ok(())
}
/// Returns an iterator over the most recent presence updates that happened after the event with id `since`.
pub fn presence_since(
&self,
since: u64,
) -> Result<impl Iterator<Item = Result<Raw<ruma::events::presence::PresenceEvent>>>> {
let first_possible_edu = (since + 1).to_be_bytes().to_vec(); // +1 so we don't send the event at since
Ok(self
.presenceid_presence
.range(&*first_possible_edu..)
.filter_map(|r| r.ok())
.map(|(_, v)| {
Ok(serde_json::from_slice(&v)
.map_err(|_| Error::bad_database("Invalid presence event in db."))?)
}))
}
}

View file

@ -1,15 +1,25 @@
use crate::{utils, Error, Result};
use js_int::UInt;
use ruma::{
events::{AnyEvent as EduEvent, SyncEphemeralRoomEvent},
events::{
presence::{PresenceEvent, PresenceEventContent},
AnyEvent as EduEvent, SyncEphemeralRoomEvent,
},
presence::PresenceState,
Raw, RoomId, UserId,
};
use std::convert::TryFrom;
use std::{
collections::HashMap,
convert::{TryFrom, TryInto},
};
pub struct RoomEdus {
pub(in super::super) roomuserid_lastread: sled::Tree, // RoomUserId = Room + User
pub(in super::super) roomlatestid_roomlatest: sled::Tree, // Read Receipts, RoomLatestId = RoomId + Count + UserId
pub(in super::super) roomactiveid_userid: sled::Tree, // Typing, RoomActiveId = RoomId + TimeoutTime + Count
pub(in super::super) roomid_lastroomactiveupdate: sled::Tree, // LastRoomActiveUpdate = Count
pub(in super::super) presenceid_presence: sled::Tree, // PresenceId = RoomId + Count + UserId
pub(in super::super) userid_lastpresenceupdate: sled::Tree, // LastPresenceUpdate = Count
}
impl RoomEdus {
@ -263,4 +273,181 @@ impl RoomEdus {
})?))
})
}
/// Adds a presence event which will be saved until a new event replaces it.
///
/// Note: This method takes a RoomId because presence updates are always bound to rooms to
/// make sure users outside these rooms can't see them.
pub fn update_presence(
&self,
user_id: &UserId,
room_id: &RoomId,
presence: ruma::events::presence::PresenceEvent,
globals: &super::super::globals::Globals,
) -> Result<()> {
// TODO: Remove old entry? Or maybe just wipe completely from time to time?
let count = globals.next_count()?.to_be_bytes();
let mut presence_id = room_id.to_string().as_bytes().to_vec();
presence_id.push(0xff);
presence_id.extend_from_slice(&count);
presence_id.push(0xff);
presence_id.extend_from_slice(&presence.sender.to_string().as_bytes());
self.presenceid_presence.insert(
presence_id,
&*serde_json::to_string(&presence).expect("PresenceEvent can be serialized"),
)?;
self.userid_lastpresenceupdate.insert(
&user_id.to_string().as_bytes(),
&utils::millis_since_unix_epoch().to_be_bytes(),
)?;
Ok(())
}
/// Resets the presence timeout, so the user will stay in their current presence state.
pub fn ping_presence(&self, user_id: &UserId) -> Result<()> {
self.userid_lastpresenceupdate.insert(
&user_id.to_string().as_bytes(),
&utils::millis_since_unix_epoch().to_be_bytes(),
)?;
Ok(())
}
/// Returns the timestamp of the last presence update of this user in millis since the unix epoch.
pub fn last_presence_update(&self, user_id: &UserId) -> Result<Option<u64>> {
self.userid_lastpresenceupdate
.get(&user_id.to_string().as_bytes())?
.map(|bytes| {
utils::u64_from_bytes(&bytes).map_err(|_| {
Error::bad_database("Invalid timestamp in userid_lastpresenceupdate.")
})
})
.transpose()
}
/// Sets all users to offline who have been quiet for too long.
pub fn presence_maintain(
&self,
rooms: &super::Rooms,
globals: &super::super::globals::Globals,
) -> Result<()> {
let current_timestamp = utils::millis_since_unix_epoch();
for (user_id_bytes, last_timestamp) in self
.userid_lastpresenceupdate
.iter()
.filter_map(|r| r.ok())
.filter_map(|(k, bytes)| {
Some((
k,
utils::u64_from_bytes(&bytes)
.map_err(|_| {
Error::bad_database("Invalid timestamp in userid_lastpresenceupdate.")
})
.ok()?,
))
})
.take_while(|(_, timestamp)| current_timestamp - timestamp > 5 * 60_000) // 5 Minutes
{
self.userid_lastpresenceupdate.remove(&user_id_bytes)?;
// Send new presence events to set the user offline
let count = globals.next_count()?.to_be_bytes();
let user_id = utils::string_from_bytes(&user_id_bytes)
.map_err(|_| {
Error::bad_database("Invalid UserId bytes in userid_lastpresenceupdate.")
})?
.try_into()
.map_err(|_| Error::bad_database("Invalid UserId in userid_lastpresenceupdate."))?;
for room_id in rooms.rooms_joined(&user_id).filter_map(|r| r.ok()) {
let mut presence_id = room_id.to_string().as_bytes().to_vec();
presence_id.push(0xff);
presence_id.extend_from_slice(&count);
presence_id.push(0xff);
presence_id.extend_from_slice(&user_id_bytes);
self.presenceid_presence.insert(
presence_id,
&*serde_json::to_string(&PresenceEvent {
content: PresenceEventContent {
avatar_url: None,
currently_active: None,
displayname: None,
last_active_ago: Some(
last_timestamp.try_into().expect("time is valid"),
),
presence: PresenceState::Offline,
status_msg: None,
},
sender: user_id.clone(),
})
.expect("PresenceEvent can be serialized"),
)?;
}
}
Ok(())
}
/// Returns an iterator over the most recent presence updates that happened after the event with id `since`.
pub fn presence_since(
&self,
room_id: &RoomId,
since: u64,
rooms: &super::Rooms,
globals: &super::super::globals::Globals,
) -> Result<HashMap<UserId, PresenceEvent>> {
self.presence_maintain(rooms, globals)?;
let mut prefix = room_id.to_string().as_bytes().to_vec();
prefix.push(0xff);
let mut first_possible_edu = prefix.clone();
first_possible_edu.extend_from_slice(&(since + 1).to_be_bytes()); // +1 so we don't send the event at since
let mut hashmap = HashMap::new();
for (key, value) in self
.presenceid_presence
.range(&*first_possible_edu..)
.filter_map(|r| r.ok())
.take_while(|(key, _)| key.starts_with(&prefix))
{
let user_id = UserId::try_from(
utils::string_from_bytes(
key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
)
.map_err(|_| Error::bad_database("Invalid UserId bytes in presenceid_presence."))?,
)
.map_err(|_| Error::bad_database("Invalid UserId in presenceid_presence."))?;
let mut presence = serde_json::from_slice::<PresenceEvent>(&value)
.map_err(|_| Error::bad_database("Invalid presence event in db."))?;
let current_timestamp: UInt = utils::millis_since_unix_epoch()
.try_into()
.expect("time is valid");
if presence.content.presence == PresenceState::Online {
// Don't set last_active_ago when the user is online
presence.content.last_active_ago = None;
} else {
// Convert from timestamp to duration
presence.content.last_active_ago = presence
.content
.last_active_ago
.map(|timestamp| current_timestamp - timestamp);
}
hashmap.insert(user_id, presence);
}
Ok(hashmap)
}
}