chore: code cleanup

next
Timo Kösters 2021-04-14 10:43:31 +02:00
parent abddfc2d2a
commit c1953efa6b
No known key found for this signature in database
GPG Key ID: 24DA7517711A2BA4
5 changed files with 59 additions and 56 deletions

View File

@ -568,9 +568,7 @@ async fn join_room_by_id_helper(
serde_json::from_value::<member::MembershipState>( serde_json::from_value::<member::MembershipState>(
pdu.content pdu.content
.get("membership") .get("membership")
.ok_or_else(|| { .ok_or(Error::BadServerResponse("Invalid member event content"))?
Error::BadServerResponse("Invalid member event content")
})?
.clone(), .clone(),
) )
.map_err(|_| { .map_err(|_| {
@ -578,8 +576,7 @@ async fn join_room_by_id_helper(
})?, })?,
&pdu.sender, &pdu.sender,
Some(invite_state), Some(invite_state),
&db.account_data, db,
&db.globals,
)?; )?;
} }
state.insert((pdu.kind.clone(), state_key.clone()), pdu.event_id.clone()); state.insert((pdu.kind.clone(), state_key.clone()), pdu.event_id.clone());

View File

@ -222,7 +222,7 @@ pub fn get_actions<'a>(
user_display_name: db user_display_name: db
.users .users
.displayname(&user)? .displayname(&user)?
.unwrap_or(user.localpart().to_owned()), .unwrap_or_else(|| user.localpart().to_owned()),
users_power_levels: power_levels.users, users_power_levels: power_levels.users,
default_power_level: power_levels.users_default, default_power_level: power_levels.users_default,
notification_power_levels: power_levels.notifications, notification_power_levels: power_levels.notifications,

View File

@ -706,14 +706,14 @@ impl Rooms {
userroom_id.extend_from_slice(pdu.room_id.as_bytes()); userroom_id.extend_from_slice(pdu.room_id.as_bytes());
if notify { if notify {
&self self
.userroomid_notificationcount .userroomid_notificationcount
.update_and_fetch(&userroom_id, utils::increment)? .update_and_fetch(&userroom_id, utils::increment)?
.expect("utils::increment will always put in a value"); .expect("utils::increment will always put in a value");
} }
if highlight { if highlight {
&self self
.userroomid_highlightcount .userroomid_highlightcount
.update_and_fetch(&userroom_id, utils::increment)? .update_and_fetch(&userroom_id, utils::increment)?
.expect("utils::increment will always put in a value"); .expect("utils::increment will always put in a value");
@ -743,12 +743,10 @@ impl Rooms {
let membership = serde_json::from_value::<member::MembershipState>( let membership = serde_json::from_value::<member::MembershipState>(
pdu.content pdu.content
.get("membership") .get("membership")
.ok_or_else(|| { .ok_or(Error::BadRequest(
Error::BadRequest( ErrorKind::InvalidParam,
ErrorKind::InvalidParam, "Invalid member event content",
"Invalid member event content", ))?
)
})?
.clone(), .clone(),
) )
.map_err(|_| { .map_err(|_| {
@ -807,8 +805,7 @@ impl Rooms {
membership, membership,
&pdu.sender, &pdu.sender,
invite_state, invite_state,
&db.account_data, db,
&db.globals,
)?; )?;
} }
} }
@ -1205,7 +1202,7 @@ impl Rooms {
.iter() .iter()
.filter_map(|event_id| Some(self.get_pdu(event_id).ok()??.depth)) .filter_map(|event_id| Some(self.get_pdu(event_id).ok()??.depth))
.max() .max()
.unwrap_or(uint!(0)) .unwrap_or_else(|| uint!(0))
+ uint!(1); + uint!(1);
let mut unsigned = unsigned.unwrap_or_default(); let mut unsigned = unsigned.unwrap_or_default();
@ -1542,8 +1539,7 @@ impl Rooms {
membership: member::MembershipState, membership: member::MembershipState,
sender: &UserId, sender: &UserId,
last_state: Option<Vec<Raw<AnyStrippedStateEvent>>>, last_state: Option<Vec<Raw<AnyStrippedStateEvent>>>,
account_data: &super::account_data::AccountData, db: &Database,
globals: &super::globals::Globals,
) -> Result<()> { ) -> Result<()> {
let mut roomserver_id = room_id.as_bytes().to_vec(); let mut roomserver_id = room_id.as_bytes().to_vec();
roomserver_id.push(0xff); roomserver_id.push(0xff);
@ -1603,23 +1599,32 @@ impl Rooms {
// .ok(); // .ok();
// Copy old tags to new room // Copy old tags to new room
if let Some(tag_event) = account_data.get::<ruma::events::tag::TagEvent>( if let Some(tag_event) =
Some(&predecessor.room_id), db.account_data.get::<ruma::events::tag::TagEvent>(
user_id, Some(&predecessor.room_id),
EventType::Tag, user_id,
)? { EventType::Tag,
account_data )?
.update(Some(room_id), user_id, EventType::Tag, &tag_event, globals) {
db.account_data
.update(
Some(room_id),
user_id,
EventType::Tag,
&tag_event,
&db.globals,
)
.ok(); .ok();
}; };
// Copy direct chat flag // Copy direct chat flag
if let Some(mut direct_event) = account_data if let Some(mut direct_event) =
.get::<ruma::events::direct::DirectEvent>( db.account_data.get::<ruma::events::direct::DirectEvent>(
None, None,
user_id, user_id,
EventType::Direct, EventType::Direct,
)? { )?
{
let mut room_ids_updated = false; let mut room_ids_updated = false;
for room_ids in direct_event.content.0.values_mut() { for room_ids in direct_event.content.0.values_mut() {
@ -1630,12 +1635,12 @@ impl Rooms {
} }
if room_ids_updated { if room_ids_updated {
account_data.update( db.account_data.update(
None, None,
user_id, user_id,
EventType::Direct, EventType::Direct,
&direct_event, &direct_event,
globals, &db.globals,
)?; )?;
} }
}; };
@ -1652,7 +1657,8 @@ impl Rooms {
} }
member::MembershipState::Invite => { member::MembershipState::Invite => {
// We want to know if the sender is ignored by the receiver // We want to know if the sender is ignored by the receiver
let is_ignored = account_data let is_ignored = db
.account_data
.get::<ignored_user_list::IgnoredUserListEvent>( .get::<ignored_user_list::IgnoredUserListEvent>(
None, // Ignored users are in global account data None, // Ignored users are in global account data
&user_id, // Receiver &user_id, // Receiver
@ -1673,7 +1679,7 @@ impl Rooms {
.expect("state to bytes always works"), .expect("state to bytes always works"),
)?; )?;
self.roomuserid_invitecount self.roomuserid_invitecount
.insert(&roomuser_id, &globals.next_count()?.to_be_bytes())?; .insert(&roomuser_id, &db.globals.next_count()?.to_be_bytes())?;
self.userroomid_joined.remove(&userroom_id)?; self.userroomid_joined.remove(&userroom_id)?;
self.roomuserid_joined.remove(&roomuser_id)?; self.roomuserid_joined.remove(&roomuser_id)?;
self.userroomid_leftstate.remove(&userroom_id)?; self.userroomid_leftstate.remove(&userroom_id)?;
@ -1693,7 +1699,7 @@ impl Rooms {
serde_json::to_vec(&Vec::<Raw<AnySyncStateEvent>>::new()).unwrap(), serde_json::to_vec(&Vec::<Raw<AnySyncStateEvent>>::new()).unwrap(),
)?; // TODO )?; // TODO
self.roomuserid_leftcount self.roomuserid_leftcount
.insert(&roomuser_id, &globals.next_count()?.to_be_bytes())?; .insert(&roomuser_id, &db.globals.next_count()?.to_be_bytes())?;
self.userroomid_joined.remove(&userroom_id)?; self.userroomid_joined.remove(&userroom_id)?;
self.roomuserid_joined.remove(&roomuser_id)?; self.roomuserid_joined.remove(&roomuser_id)?;
self.userroomid_invitestate.remove(&userroom_id)?; self.userroomid_invitestate.remove(&userroom_id)?;
@ -1729,8 +1735,7 @@ impl Rooms {
MembershipState::Leave, MembershipState::Leave,
user_id, user_id,
last_state, last_state,
&db.account_data, db,
&db.globals,
)?; )?;
} else { } else {
let mut event = serde_json::from_value::<Raw<member::MemberEventContent>>( let mut event = serde_json::from_value::<Raw<member::MemberEventContent>>(

View File

@ -1413,15 +1413,16 @@ pub fn get_missing_events_route<'a>(
let mut i = 0; let mut i = 0;
while i < queued_events.len() && events.len() < u64::from(body.limit) as usize { while i < queued_events.len() && events.len() < u64::from(body.limit) as usize {
if let Some(pdu) = db.rooms.get_pdu_json(&queued_events[i])? { if let Some(pdu) = db.rooms.get_pdu_json(&queued_events[i])? {
if body.earliest_events.contains( let event_id =
&serde_json::from_value( serde_json::from_value(
serde_json::to_value(pdu.get("event_id").cloned().ok_or_else(|| { serde_json::to_value(pdu.get("event_id").cloned().ok_or_else(|| {
Error::bad_database("Event in db has no event_id field.") Error::bad_database("Event in db has no event_id field.")
})?) })?)
.expect("canonical json is valid json value"), .expect("canonical json is valid json value"),
) )
.map_err(|_| Error::bad_database("Invalid event_id field in pdu in db."))?, .map_err(|_| Error::bad_database("Invalid event_id field in pdu in db."))?;
) {
if body.earliest_events.contains(&event_id) {
i += 1; i += 1;
continue; continue;
} }
@ -1541,9 +1542,10 @@ pub async fn create_invite_route<'a>(
serde_json::to_value( serde_json::to_value(
signed_event signed_event
.get("sender") .get("sender")
.ok_or_else(|| { .ok_or(Error::BadRequest(
Error::BadRequest(ErrorKind::InvalidParam, "Event had no sender field.") ErrorKind::InvalidParam,
})? "Event had no sender field.",
))?
.clone(), .clone(),
) )
.expect("CanonicalJsonValue to serde_json::Value always works"), .expect("CanonicalJsonValue to serde_json::Value always works"),
@ -1553,9 +1555,10 @@ pub async fn create_invite_route<'a>(
serde_json::to_value( serde_json::to_value(
signed_event signed_event
.get("state_key") .get("state_key")
.ok_or_else(|| { .ok_or(Error::BadRequest(
Error::BadRequest(ErrorKind::InvalidParam, "Event had no state_key field.") ErrorKind::InvalidParam,
})? "Event had no state_key field.",
))?
.clone(), .clone(),
) )
.expect("CanonicalJsonValue to serde_json::Value always works"), .expect("CanonicalJsonValue to serde_json::Value always works"),
@ -1586,8 +1589,7 @@ pub async fn create_invite_route<'a>(
MembershipState::Invite, MembershipState::Invite,
&sender, &sender,
Some(invite_state), Some(invite_state),
&db.account_data, &db,
&db.globals,
)?; )?;
} }
@ -1638,10 +1640,9 @@ pub async fn fetch_required_signing_keys(
) -> Result<()> { ) -> Result<()> {
// We go through all the signatures we see on the value and fetch the corresponding signing // We go through all the signatures we see on the value and fetch the corresponding signing
// keys // keys
for (signature_server, signature) in match event for (signature_server, signature) in match event.get("signatures").ok_or(
.get("signatures") Error::BadServerResponse("No signatures in server response pdu."),
.ok_or_else(|| Error::BadServerResponse("No signatures in server response pdu."))? )? {
{
CanonicalJsonValue::Object(map) => map, CanonicalJsonValue::Object(map) => map,
_ => { _ => {
return Err(Error::BadServerResponse( return Err(Error::BadServerResponse(

View File

@ -69,7 +69,7 @@ pub fn calculate_hash(password: &str) -> Result<String, argon2::Error> {
argon2::hash_encoded(password.as_bytes(), salt.as_bytes(), &hashing_config) argon2::hash_encoded(password.as_bytes(), salt.as_bytes(), &hashing_config)
} }
pub fn common_elements<'a>( pub fn common_elements(
mut iterators: impl Iterator<Item = impl Iterator<Item = Vec<u8>>>, mut iterators: impl Iterator<Item = impl Iterator<Item = Vec<u8>>>,
check_order: impl Fn(&[u8], &[u8]) -> Ordering, check_order: impl Fn(&[u8], &[u8]) -> Ordering,
) -> Option<impl Iterator<Item = Vec<u8>>> { ) -> Option<impl Iterator<Item = Vec<u8>>> {