2020-12-08 09:33:44 +00:00
|
|
|
use crate::{utils, Error, Result};
|
2021-01-27 02:53:03 +00:00
|
|
|
use std::{
|
|
|
|
collections::HashMap,
|
|
|
|
sync::{Arc, RwLock},
|
|
|
|
};
|
2020-12-08 09:33:44 +00:00
|
|
|
|
2021-06-08 16:10:00 +00:00
|
|
|
use super::abstraction::Tree;
|
|
|
|
|
2020-12-08 09:33:44 +00:00
|
|
|
pub struct Appservice {
|
|
|
|
pub(super) cached_registrations: Arc<RwLock<HashMap<String, serde_yaml::Value>>>,
|
2021-06-08 16:10:00 +00:00
|
|
|
pub(super) id_appserviceregistrations: Arc<dyn Tree>,
|
2020-12-08 09:33:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Appservice {
|
|
|
|
pub fn register_appservice(&self, yaml: serde_yaml::Value) -> Result<()> {
|
|
|
|
// TODO: Rumaify
|
|
|
|
let id = yaml.get("id").unwrap().as_str().unwrap();
|
2021-06-08 16:10:00 +00:00
|
|
|
self.id_appserviceregistrations.insert(
|
|
|
|
id.as_bytes(),
|
|
|
|
serde_yaml::to_string(&yaml).unwrap().as_bytes(),
|
|
|
|
)?;
|
2020-12-08 09:33:44 +00:00
|
|
|
self.cached_registrations
|
|
|
|
.write()
|
|
|
|
.unwrap()
|
|
|
|
.insert(id.to_owned(), yaml);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_registration(&self, id: &str) -> Result<Option<serde_yaml::Value>> {
|
|
|
|
self.cached_registrations
|
|
|
|
.read()
|
|
|
|
.unwrap()
|
|
|
|
.get(id)
|
|
|
|
.map_or_else(
|
|
|
|
|| {
|
2021-06-17 18:34:14 +00:00
|
|
|
self.id_appserviceregistrations
|
2021-06-08 16:10:00 +00:00
|
|
|
.get(id.as_bytes())?
|
2020-12-08 09:33:44 +00:00
|
|
|
.map(|bytes| {
|
2021-06-17 18:34:14 +00:00
|
|
|
serde_yaml::from_slice(&bytes).map_err(|_| {
|
2020-12-08 09:33:44 +00:00
|
|
|
Error::bad_database(
|
|
|
|
"Invalid registration bytes in id_appserviceregistrations.",
|
|
|
|
)
|
2021-06-17 18:34:14 +00:00
|
|
|
})
|
2020-12-08 09:33:44 +00:00
|
|
|
})
|
2021-06-17 18:34:14 +00:00
|
|
|
.transpose()
|
2020-12-08 09:33:44 +00:00
|
|
|
},
|
|
|
|
|r| Ok(Some(r.clone())),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-08-02 08:13:34 +00:00
|
|
|
pub fn iter_ids(&self) -> Result<impl Iterator<Item = Result<String>> + '_> {
|
2021-06-08 16:10:00 +00:00
|
|
|
Ok(self.id_appserviceregistrations.iter().map(|(id, _)| {
|
2021-06-17 18:34:14 +00:00
|
|
|
utils::string_from_bytes(&id)
|
|
|
|
.map_err(|_| Error::bad_database("Invalid id bytes in id_appserviceregistrations."))
|
2021-06-08 16:10:00 +00:00
|
|
|
}))
|
2020-12-08 09:33:44 +00:00
|
|
|
}
|
|
|
|
|
2021-08-02 08:13:34 +00:00
|
|
|
pub fn all(&self) -> Result<Vec<(String, serde_yaml::Value)>> {
|
|
|
|
self.iter_ids()?
|
|
|
|
.filter_map(|id| id.ok())
|
|
|
|
.map(move |id| {
|
|
|
|
Ok((
|
|
|
|
id.clone(),
|
|
|
|
self.get_registration(&id)?
|
|
|
|
.expect("iter_ids only returns appservices that exist"),
|
|
|
|
))
|
|
|
|
})
|
|
|
|
.collect()
|
2020-12-08 09:33:44 +00:00
|
|
|
}
|
|
|
|
}
|