Fix all clippy warnings, shorten line len in client_server

This commit is contained in:
Devin Ragotzy 2020-07-25 23:56:50 -04:00 committed by timokoesters
parent 3ccbd02081
commit 62df9ca580
No known key found for this signature in database
GPG Key ID: 24DA7517711A2BA4
5 changed files with 155 additions and 100 deletions

View File

@ -230,7 +230,7 @@ pub fn register_route(
Ok(register::Response { Ok(register::Response {
access_token: Some(token), access_token: Some(token),
user_id, user_id,
device_id: Some(device_id.into()), device_id: Some(device_id),
} }
.into()) .into())
} }
@ -257,11 +257,22 @@ pub fn login_route(
if let (login::UserInfo::MatrixId(username), login::LoginInfo::Password { password }) = if let (login::UserInfo::MatrixId(username), login::LoginInfo::Password { password }) =
(body.user.clone(), body.login_info.clone()) (body.user.clone(), body.login_info.clone())
{ {
let user_id = UserId::parse_with_server_name(username, db.globals.server_name()).map_err(|_| Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?; let user_id = UserId::parse_with_server_name(username, db.globals.server_name())
let hash = db.users.password_hash(&user_id)?.ok_or(Error::BadRequest(ErrorKind::Forbidden, "Wrong username or password."))?; .map_err(|_| Error::BadRequest(
ErrorKind::InvalidUsername,
"Username is invalid."
))?;
let hash = db.users.password_hash(&user_id)?
.ok_or(Error::BadRequest(
ErrorKind::Forbidden,
"Wrong username or password."
))?;
if hash.is_empty() { if hash.is_empty() {
return Err(Error::BadRequest(ErrorKind::UserDeactivated, "The user has been deactivated")); return Err(Error::BadRequest(
ErrorKind::UserDeactivated,
"The user has been deactivated"
));
} }
let hash_matches = let hash_matches =
@ -298,7 +309,7 @@ pub fn login_route(
user_id, user_id,
access_token: token, access_token: token,
home_server: Some(db.globals.server_name().to_owned()), home_server: Some(db.globals.server_name().to_owned()),
device_id: device_id.into(), device_id,
well_known: None, well_known: None,
} }
.into()) .into())
@ -1702,8 +1713,7 @@ pub fn leave_room_route(
ErrorKind::BadState, ErrorKind::BadState,
"Cannot leave a room you are not a member of.", "Cannot leave a room you are not a member of.",
))? ))?
.content .content,
.clone(),
) )
.map_err(|_| Error::bad_database("Invalid member event in database."))? .map_err(|_| Error::bad_database("Invalid member event in database."))?
.deserialize() .deserialize()
@ -1746,8 +1756,7 @@ pub fn kick_user_route(
ErrorKind::BadState, ErrorKind::BadState,
"Cannot kick member that's not in the room.", "Cannot kick member that's not in the room.",
))? ))?
.content .content,
.clone(),
) )
.expect("Raw::from_value always works") .expect("Raw::from_value always works")
.deserialize() .deserialize()
@ -1882,8 +1891,7 @@ pub fn unban_user_route(
ErrorKind::BadState, ErrorKind::BadState,
"Cannot unban a user who is not banned.", "Cannot unban a user who is not banned.",
))? ))?
.content .content,
.clone(),
) )
.map_err(|_| Error::bad_database("Invalid member event in database."))? .map_err(|_| Error::bad_database("Invalid member event in database."))?
.deserialize() .deserialize()
@ -2049,6 +2057,8 @@ pub async fn get_public_rooms_filtered_route(
db: State<'_, Database>, db: State<'_, Database>,
_body: Ruma<get_public_rooms_filtered::Request>, _body: Ruma<get_public_rooms_filtered::Request>,
) -> ConduitResult<get_public_rooms_filtered::Response> { ) -> ConduitResult<get_public_rooms_filtered::Response> {
use ruma::events::room;
let mut chunk = db let mut chunk = db
.rooms .rooms
.public_rooms() .public_rooms()
@ -2060,63 +2070,110 @@ pub async fn get_public_rooms_filtered_route(
let chunk = directory::PublicRoomsChunk { let chunk = directory::PublicRoomsChunk {
aliases: Vec::new(), aliases: Vec::new(),
canonical_alias: state.get(&(EventType::RoomCanonicalAlias, "".to_owned())).map_or(Ok::<_, Error>(None), |s| { canonical_alias: state
Ok(serde_json::from_value::< .get(&(EventType::RoomCanonicalAlias, "".to_owned()))
Raw<ruma::events::room::canonical_alias::CanonicalAliasEventContent>, .map_or(Ok::<_, Error>(None), |s| {
Ok(serde_json::from_value::<
Raw<room::canonical_alias::CanonicalAliasEventContent>,
>(s.content.clone()) >(s.content.clone())
.map_err(|_| Error::bad_database("Invalid canonical alias event in database."))? .map_err(|_| {
Error::bad_database("Invalid canonical alias event in database.")
})?
.deserialize() .deserialize()
.map_err(|_| Error::bad_database("Invalid canonical alias event in database."))? .map_err(|_| {
Error::bad_database("Invalid canonical alias event in database.")
})?
.alias) .alias)
})?, })?,
name: state.get(&(EventType::RoomName, "".to_owned())).map_or(Ok::<_, Error>(None), |s| { name: state.get(&(EventType::RoomName, "".to_owned())).map_or(
Ok(serde_json::from_value::<Raw<ruma::events::room::name::NameEventContent>>( Ok::<_, Error>(None),
s.content.clone(), |s| {
) Ok(serde_json::from_value::<Raw<room::name::NameEventContent>>(
.map_err(|_| Error::bad_database("Invalid room name event in database."))? s.content.clone(),
.deserialize() )
.map_err(|_| Error::bad_database("Invalid room name event in database."))? .map_err(|_| Error::bad_database("Invalid room name event in database."))?
.name() .deserialize()
.map(|n| n.to_owned())) .map_err(|_| Error::bad_database("Invalid room name event in database."))?
})?, .name()
.map(|n| n.to_owned()))
},
)?,
num_joined_members: (db.rooms.room_members(&room_id).count() as u32).into(), num_joined_members: (db.rooms.room_members(&room_id).count() as u32).into(),
room_id, room_id,
topic: state.get(&(EventType::RoomTopic, "".to_owned())).map_or(Ok::<_, Error>(None), |s| { topic: state.get(&(EventType::RoomTopic, "".to_owned())).map_or(
Ok(Some(serde_json::from_value::< Ok::<_, Error>(None),
Raw<ruma::events::room::topic::TopicEventContent>, |s| {
Ok(Some(
serde_json::from_value::<Raw<room::topic::TopicEventContent>>(
s.content.clone(),
)
.map_err(|_| {
Error::bad_database("Invalid room topic event in database.")
})?
.deserialize()
.map_err(|_| {
Error::bad_database("Invalid room topic event in database.")
})?
.topic,
))
},
)?,
world_readable: state
.get(&(EventType::RoomHistoryVisibility, "".to_owned()))
.map_or(Ok::<_, Error>(false), |s| {
Ok(serde_json::from_value::<
Raw<room::history_visibility::HistoryVisibilityEventContent>,
>(s.content.clone()) >(s.content.clone())
.map_err(|_| Error::bad_database("Invalid room topic event in database."))? .map_err(|_| {
Error::bad_database(
"Invalid room history visibility event in database.",
)
})?
.deserialize() .deserialize()
.map_err(|_| Error::bad_database("Invalid room topic event in database."))? .map_err(|_| {
.topic)) Error::bad_database(
})?, "Invalid room history visibility event in database.",
world_readable: state.get(&(EventType::RoomHistoryVisibility, "".to_owned())).map_or(Ok::<_, Error>(false), |s| { )
Ok(serde_json::from_value::< })?
Raw<ruma::events::room::history_visibility::HistoryVisibilityEventContent>, .history_visibility
>(s.content.clone()) == history_visibility::HistoryVisibility::WorldReadable)
.map_err(|_| Error::bad_database("Invalid room history visibility event in database."))? })?,
.deserialize() guest_can_join: state
.map_err(|_| Error::bad_database("Invalid room history visibility event in database."))? .get(&(EventType::RoomGuestAccess, "".to_owned()))
.history_visibility == history_visibility::HistoryVisibility::WorldReadable) .map_or(Ok::<_, Error>(false), |s| {
})?, Ok(
guest_can_join: state.get(&(EventType::RoomGuestAccess, "".to_owned())).map_or(Ok::<_, Error>(false), |s| { serde_json::from_value::<
Ok(serde_json::from_value::< Raw<room::guest_access::GuestAccessEventContent>,
Raw<ruma::events::room::guest_access::GuestAccessEventContent>, >(s.content.clone())
>(s.content.clone()) .map_err(|_| {
.map_err(|_| Error::bad_database("Invalid room guest access event in database."))? Error::bad_database("Invalid room guest access event in database.")
.deserialize() })?
.map_err(|_| Error::bad_database("Invalid room guest access event in database."))? .deserialize()
.guest_access == guest_access::GuestAccess::CanJoin) .map_err(|_| {
})?, Error::bad_database("Invalid room guest access event in database.")
avatar_url: state.get(&(EventType::RoomAvatar, "".to_owned())).map_or( Ok::<_, Error>(None),|s| { })?
Ok(Some(serde_json::from_value::< .guest_access
Raw<ruma::events::room::avatar::AvatarEventContent>, == guest_access::GuestAccess::CanJoin,
>(s.content.clone()) )
.map_err(|_| Error::bad_database("Invalid room avatar event in database."))? })?,
.deserialize() avatar_url: state.get(&(EventType::RoomAvatar, "".to_owned())).map_or(
.map_err(|_| Error::bad_database("Invalid room avatar event in database."))? Ok::<_, Error>(None),
.url)) |s| {
})?, Ok(Some(
serde_json::from_value::<Raw<room::avatar::AvatarEventContent>>(
s.content.clone(),
)
.map_err(|_| {
Error::bad_database("Invalid room avatar event in database.")
})?
.deserialize()
.map_err(|_| {
Error::bad_database("Invalid room avatar event in database.")
})?
.url,
))
},
)?,
}; };
Ok::<_, Error>(chunk) Ok::<_, Error>(chunk)
}) })
@ -2338,7 +2395,11 @@ pub fn create_state_event_for_key_route(
.filter(|room| room == &body.room_id) // Make sure it's the right room .filter(|room| room == &body.room_id) // Make sure it's the right room
.is_none() .is_none()
{ {
return Err(Error::BadRequest(ErrorKind::Forbidden, "You are only allowed to send canonical_alias events when it's aliases already exists")); return Err(Error::BadRequest(
ErrorKind::Forbidden,
"You are only allowed to send canonical_alias \
events when it's aliases already exists",
));
} }
} }
} }

View File

@ -1,6 +1,8 @@
use crate::{utils, Error, Result}; use crate::{utils, Error, Result};
use std::mem; use std::mem;
pub type FileMeta = (Option<String>, String, Vec<u8>);
pub struct Media { pub struct Media {
pub(super) mediaid_file: sled::Tree, // MediaId = MXC + WidthHeight + Filename + ContentType pub(super) mediaid_file: sled::Tree, // MediaId = MXC + WidthHeight + Filename + ContentType
} }
@ -29,7 +31,7 @@ impl Media {
} }
/// Downloads a file. /// Downloads a file.
pub fn get(&self, mxc: String) -> Result<Option<(Option<String>, String, Vec<u8>)>> { pub fn get(&self, mxc: String) -> Result<Option<FileMeta>> {
let mut prefix = mxc.as_bytes().to_vec(); let mut prefix = mxc.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
prefix.extend_from_slice(&0_u32.to_be_bytes()); // Width = 0 if it's not a thumbnail prefix.extend_from_slice(&0_u32.to_be_bytes()); // Width = 0 if it's not a thumbnail
@ -66,12 +68,7 @@ impl Media {
} }
/// Downloads a file's thumbnail. /// Downloads a file's thumbnail.
pub fn get_thumbnail( pub fn get_thumbnail(&self, mxc: String, width: u32, height: u32) -> Result<Option<FileMeta>> {
&self,
mxc: String,
width: u32,
height: u32,
) -> Result<Option<(Option<String>, String, Vec<u8>)>> {
let mut main_prefix = mxc.as_bytes().to_vec(); let mut main_prefix = mxc.as_bytes().to_vec();
main_prefix.push(0xff); main_prefix.push(0xff);

View File

@ -250,6 +250,7 @@ impl Rooms {
} }
/// Creates a new persisted data unit and adds it to a room. /// Creates a new persisted data unit and adds it to a room.
#[allow(clippy::too_many_arguments, clippy::blocks_in_if_conditions)]
pub fn append_pdu( pub fn append_pdu(
&self, &self,
room_id: RoomId, room_id: RoomId,
@ -288,7 +289,7 @@ impl Rooms {
}, },
|power_levels| { |power_levels| {
Ok(serde_json::from_value::<Raw<PowerLevelsEventContent>>( Ok(serde_json::from_value::<Raw<PowerLevelsEventContent>>(
power_levels.content.clone(), power_levels.content,
) )
.expect("Raw::from_value always works.") .expect("Raw::from_value always works.")
.deserialize() .deserialize()
@ -298,13 +299,13 @@ impl Rooms {
let sender_membership = self let sender_membership = self
.room_state_get(&room_id, &EventType::RoomMember, &sender.to_string())? .room_state_get(&room_id, &EventType::RoomMember, &sender.to_string())?
.map_or(Ok::<_, Error>(member::MembershipState::Leave), |pdu| { .map_or(Ok::<_, Error>(member::MembershipState::Leave), |pdu| {
Ok(serde_json::from_value::<Raw<member::MemberEventContent>>( Ok(
pdu.content.clone(), serde_json::from_value::<Raw<member::MemberEventContent>>(pdu.content)
.expect("Raw::from_value always works.")
.deserialize()
.map_err(|_| Error::bad_database("Invalid Member event in db."))?
.membership,
) )
.expect("Raw::from_value always works.")
.deserialize()
.map_err(|_| Error::bad_database("Invalid Member event in db."))?
.membership)
})?; })?;
let sender_power = power_levels.users.get(&sender).map_or_else( let sender_power = power_levels.users.get(&sender).map_or_else(
@ -341,7 +342,7 @@ impl Rooms {
)? )?
.map_or(Ok::<_, Error>(member::MembershipState::Leave), |pdu| { .map_or(Ok::<_, Error>(member::MembershipState::Leave), |pdu| {
Ok(serde_json::from_value::<Raw<member::MemberEventContent>>( Ok(serde_json::from_value::<Raw<member::MemberEventContent>>(
pdu.content.clone(), pdu.content,
) )
.expect("Raw::from_value always works.") .expect("Raw::from_value always works.")
.deserialize() .deserialize()
@ -373,7 +374,7 @@ impl Rooms {
.map_or(Ok::<_, Error>(join_rules::JoinRule::Public), |pdu| { .map_or(Ok::<_, Error>(join_rules::JoinRule::Public), |pdu| {
Ok(serde_json::from_value::< Ok(serde_json::from_value::<
Raw<join_rules::JoinRulesEventContent>, Raw<join_rules::JoinRulesEventContent>,
>(pdu.content.clone()) >(pdu.content)
.expect("Raw::from_value always works.") .expect("Raw::from_value always works.")
.deserialize() .deserialize()
.map_err(|_| { .map_err(|_| {
@ -501,7 +502,7 @@ impl Rooms {
let mut unsigned = unsigned.unwrap_or_default(); let mut unsigned = unsigned.unwrap_or_default();
if let Some(state_key) = &state_key { if let Some(state_key) = &state_key {
if let Some(prev_pdu) = self.room_state_get(&room_id, &event_type, &state_key)? { if let Some(prev_pdu) = self.room_state_get(&room_id, &event_type, &state_key)? {
unsigned.insert("prev_content".to_owned(), prev_pdu.content.clone()); unsigned.insert("prev_content".to_owned(), prev_pdu.content);
unsigned.insert( unsigned.insert(
"prev_sender".to_owned(), "prev_sender".to_owned(),
serde_json::to_value(prev_pdu.sender).expect("UserId::to_value always works"), serde_json::to_value(prev_pdu.sender).expect("UserId::to_value always works"),
@ -575,28 +576,24 @@ impl Rooms {
self.roomstateid_pdu.insert(key, &*pdu_json.to_string())?; self.roomstateid_pdu.insert(key, &*pdu_json.to_string())?;
} }
match event_type { if let EventType::RoomRedaction = event_type {
EventType::RoomRedaction => { if let Some(redact_id) = &redacts {
if let Some(redact_id) = &redacts { // TODO: Reason
// TODO: Reason let _reason =
let _reason = serde_json::from_value::<Raw<redaction::RedactionEventContent>>(content)
serde_json::from_value::<Raw<redaction::RedactionEventContent>>(content) .expect("Raw::from_value always works.")
.expect("Raw::from_value always works.") .deserialize()
.deserialize() .map_err(|_| {
.map_err(|_| { Error::BadRequest(
Error::BadRequest( ErrorKind::InvalidParam,
ErrorKind::InvalidParam, "Invalid redaction event content.",
"Invalid redaction event content.", )
) })?
})? .reason;
.reason;
self.redact_pdu(&redact_id)?; self.redact_pdu(&redact_id)?;
}
} }
_ => {}
} }
self.edus.room_read_set(&room_id, &sender, index)?; self.edus.room_read_set(&room_id, &sender, index)?;
Ok(pdu.event_id) Ok(pdu.event_id)

View File

@ -42,7 +42,7 @@ impl Uiaa {
.map(|session| { .map(|session| {
Ok::<_, Error>(self.get_uiaa_session(&user_id, &device_id, session)?) Ok::<_, Error>(self.get_uiaa_session(&user_id, &device_id, session)?)
}) })
.unwrap_or(Ok(uiaainfo.clone()))?; .unwrap_or_else(|| Ok(uiaainfo.clone()))?;
// Find out what the user completed // Find out what the user completed
match &**kind { match &**kind {

View File

@ -502,7 +502,7 @@ impl Users {
)); ));
} }
let mut user_signing_key_key = prefix.clone(); let mut user_signing_key_key = prefix;
user_signing_key_key.extend_from_slice(user_signing_key_id.as_bytes()); user_signing_key_key.extend_from_slice(user_signing_key_id.as_bytes());
self.keyid_key.insert( self.keyid_key.insert(