conduit/src/database/global_edus.rs

56 lines
1.8 KiB
Rust
Raw Normal View History

2020-05-09 20:47:09 +01:00
use crate::Result;
2020-06-05 17:19:26 +01:00
use ruma::events::EventJson;
2020-05-09 20:47:09 +01:00
pub struct GlobalEdus {
2020-05-17 18:56:40 +01:00
//pub globalallid_globalall: sled::Tree, // ToDevice, GlobalAllId = UserId + Count
2020-06-04 21:36:48 +01:00
pub(super) presenceid_presence: sled::Tree, // Presence, PresenceId = Count + UserId
2020-05-09 20:47:09 +01:00
}
impl GlobalEdus {
/// Adds a global event which will be saved until a new event replaces it (e.g. presence updates).
2020-06-04 21:36:48 +01:00
pub fn update_presence(
2020-05-09 20:47:09 +01:00
&self,
2020-06-05 17:19:26 +01:00
presence: ruma::events::presence::PresenceEvent,
2020-05-09 20:47:09 +01:00
globals: &super::globals::Globals,
) -> Result<()> {
// Remove old entry
if let Some(old) = self
2020-06-04 21:36:48 +01:00
.presenceid_presence
2020-05-09 20:47:09 +01:00
.iter()
.keys()
.rev()
.filter_map(|r| r.ok())
.find(|key| {
2020-06-04 21:36:48 +01:00
key.rsplit(|&b| b == 0xff).next().unwrap() == presence.sender.to_string().as_bytes()
2020-05-09 20:47:09 +01:00
})
{
// This is the old global_latest
2020-06-04 21:36:48 +01:00
self.presenceid_presence.remove(old)?;
2020-05-09 20:47:09 +01:00
}
2020-06-04 21:36:48 +01:00
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());
2020-05-09 20:47:09 +01:00
2020-06-04 21:36:48 +01:00
self.presenceid_presence
.insert(presence_id, &*serde_json::to_string(&presence)?)?;
2020-05-09 20:47:09 +01:00
Ok(())
}
/// Returns an iterator over the most recent presence updates that happened after the event with id `since`.
2020-06-04 21:36:48 +01:00
pub fn presence_since(
2020-05-09 20:47:09 +01:00
&self,
since: u64,
2020-06-05 17:19:26 +01:00
) -> Result<impl Iterator<Item = Result<EventJson<ruma::events::presence::PresenceEvent>>>>
{
2020-06-04 21:36:48 +01:00
let first_possible_edu = (since + 1).to_be_bytes().to_vec(); // +1 so we don't send the event at since
2020-05-09 20:47:09 +01:00
Ok(self
2020-06-04 21:36:48 +01:00
.presenceid_presence
2020-05-09 20:47:09 +01:00
.range(&*first_possible_edu..)
.filter_map(|r| r.ok())
.map(|(_, v)| Ok(serde_json::from_slice(&v)?)))
}
}