conduwuit/src/database/key_value/appservice.rs

81 lines
2.6 KiB
Rust
Raw Normal View History

use ruma::api::appservice::Registration;
2022-09-07 13:25:51 +02:00
use crate::{database::KeyValueDatabase, service, utils, Error, Result};
impl service::appservice::Data for KeyValueDatabase {
/// Registers an appservice and returns the ID to the caller
fn register_appservice(&self, yaml: Registration) -> Result<String> {
let id = yaml.id.as_str();
2021-06-08 18:10:00 +02:00
self.id_appserviceregistrations.insert(
id.as_bytes(),
serde_yaml::to_string(&yaml).unwrap().as_bytes(),
)?;
self.cached_registrations
.write()
.unwrap()
.insert(id.to_owned(), yaml.clone());
Ok(id.to_owned())
}
/// Remove an appservice registration
2022-01-13 12:26:23 +01:00
///
/// # Arguments
2022-01-13 12:26:23 +01:00
///
/// * `service_name` - the name you send to register the service previously
fn unregister_appservice(&self, service_name: &str) -> Result<()> {
self.id_appserviceregistrations
.remove(service_name.as_bytes())?;
2022-01-13 12:26:23 +01:00
self.cached_registrations
.write()
.unwrap()
.remove(service_name);
2021-12-20 15:46:36 +01:00
Ok(())
}
fn get_registration(&self, id: &str) -> Result<Option<Registration>> {
self.cached_registrations
.read()
.unwrap()
.get(id)
.map_or_else(
|| {
2021-06-17 20:34:14 +02:00
self.id_appserviceregistrations
2021-06-08 18:10:00 +02:00
.get(id.as_bytes())?
.map(|bytes| {
2021-06-17 20:34:14 +02:00
serde_yaml::from_slice(&bytes).map_err(|_| {
Error::bad_database(
"Invalid registration bytes in id_appserviceregistrations.",
)
2021-06-17 20:34:14 +02:00
})
})
2021-06-17 20:34:14 +02:00
.transpose()
},
|r| Ok(Some(r.clone())),
)
}
2022-10-05 09:34:25 +02:00
fn iter_ids<'a>(&'a self) -> Result<Box<dyn Iterator<Item = Result<String>> + 'a>> {
2022-10-05 20:34:31 +02:00
Ok(Box::new(self.id_appserviceregistrations.iter().map(
|(id, _)| {
utils::string_from_bytes(&id).map_err(|_| {
Error::bad_database("Invalid id bytes in id_appserviceregistrations.")
})
},
)))
}
fn all(&self) -> Result<Vec<(String, Registration)>> {
self.iter_ids()?
.filter_map(std::result::Result::ok)
.map(move |id| {
Ok((
id.clone(),
self.get_registration(&id)?
.expect("iter_ids only returns appservices that exist"),
))
})
.collect()
}
}