diff --git a/Cargo.toml b/Cargo.toml index f250a68f..763f042c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -419,7 +419,7 @@ unit_bindings = "warn" unused_braces = "allow" [workspace.lints.clippy] -pedantic = "warn" +# pedantic = "warn" suspicious = "warn" # assume deny in practice perf = "warn" # assume deny in practice @@ -497,6 +497,20 @@ redundant_closure_for_method_calls = "warn" large_futures = "warn" semicolon_if_nothing_returned = "warn" match_bool = "warn" +struct_excessive_bools = "warn" +must_use_candidate = "warn" +collapsible_else_if = "warn" +inconsistent_struct_constructor = "warn" +manual_string_new = "warn" +zero_sized_map_values = "warn" +unnecessary_box_returns = "warn" +map_unwrap_or = "warn" +implicit_clone = "warn" +match_wildcard_for_single_variants = "warn" +unnecessary_wraps = "warn" +match_same_arms = "warn" +ignored_unit_patterns = "warn" +redundant_else = "warn" # not in rust 1.75.0 (breaks CI) # infinite_loop = "warn" diff --git a/src/api/client_server/account.rs b/src/api/client_server/account.rs index 2fbf743e..8792522f 100644 --- a/src/api/client_server/account.rs +++ b/src/api/client_server/account.rs @@ -76,6 +76,7 @@ pub async fn get_register_available_route( /// - Creates a new account and populates it with default account data /// - If `inhibit_login` is false: Creates a device and returns device id and /// access_token +#[allow(clippy::doc_markdown)] pub async fn register_route(body: Ruma) -> Result { if !services().globals.allow_registration() && !body.from_appservice { info!( @@ -390,7 +391,7 @@ pub async fn change_password_route(body: Ruma) -> /// # `GET _matrix/client/r0/account/whoami` /// -/// Get user_id of the sender user. +/// Get `user_id` of the sender user. /// /// Note: Also works for Application Services pub async fn whoami_route(body: Ruma) -> Result { diff --git a/src/api/client_server/context.rs b/src/api/client_server/context.rs index 60824d49..5b773328 100644 --- a/src/api/client_server/context.rs +++ b/src/api/client_server/context.rs @@ -91,8 +91,7 @@ pub async fn get_context_route(body: Ruma) -> Result = events_before.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect(); @@ -134,7 +133,7 @@ pub async fn get_context_route(body: Ruma) -> Result = events_after.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect(); diff --git a/src/api/client_server/keys.rs b/src/api/client_server/keys.rs index 3a8f3695..32a1f775 100644 --- a/src/api/client_server/keys.rs +++ b/src/api/client_server/keys.rs @@ -363,11 +363,11 @@ pub(crate) async fn get_keys_helper bool>( } Ok(get_keys::v3::Response { + failures, + device_keys, master_keys, self_signing_keys, user_signing_keys, - device_keys, - failures, }) } diff --git a/src/api/client_server/message.rs b/src/api/client_server/message.rs index 099ea1e7..93d00d52 100644 --- a/src/api/client_server/message.rs +++ b/src/api/client_server/message.rs @@ -143,7 +143,7 @@ pub async fn send_message_event_route( /// /// - Only works if the user is joined (TODO: always allow, but only show events /// where the user was -/// joined, depending on history_visibility) +/// joined, depending on `history_visibility`) pub async fn get_message_events_route( body: Ruma, ) -> Result { diff --git a/src/api/client_server/profile.rs b/src/api/client_server/profile.rs index 49869cdc..f508c2a0 100644 --- a/src/api/client_server/profile.rs +++ b/src/api/client_server/profile.rs @@ -126,9 +126,9 @@ pub async fn get_displayname_route( }) } -/// # `PUT /_matrix/client/r0/profile/{userId}/avatar_url` +/// # `PUT /_matrix/client/v3/profile/{userId}/avatar_url` /// -/// Updates the avatar_url and blurhash. +/// Updates the `avatar_url` and `blurhash`. /// /// - Also makes sure other users receive the update using presence EDUs pub async fn set_avatar_url_route(body: Ruma) -> Result { @@ -192,10 +192,10 @@ pub async fn set_avatar_url_route(body: Ruma) -> Re /// # `GET /_matrix/client/v3/profile/{userId}/avatar_url` /// -/// Returns the avatar_url and blurhash of the user. +/// Returns the `avatar_url` and `blurhash` of the user. /// /// - If user is on another server and we do not have a local copy already -/// fetch avatar_url and blurhash over federation +/// fetch `avatar_url` and blurhash over federation pub async fn get_avatar_url_route(body: Ruma) -> Result { if body.user_id.server_name() != services().globals.server_name() { // Create and update our local copy of the user diff --git a/src/api/client_server/room.rs b/src/api/client_server/room.rs index 88aeb672..533eb7bc 100644 --- a/src/api/client_server/room.rs +++ b/src/api/client_server/room.rs @@ -34,7 +34,7 @@ use crate::{api::client_server::invite_helper, service::pdu::PduBuilder, service /// Creates a new room. /// /// - Room ID is randomly generated -/// - Create alias if room_alias_name is set +/// - Create alias if `room_alias_name` is set /// - Send create event /// - Join sender user /// - Send power levels event @@ -273,7 +273,7 @@ pub async fn create_room_route(body: Ruma) -> Result) -> Result) -> Result) -> Result) -> Result) -> Result) -> Result) -> Result) -> Result) -> Re /// Lists all aliases of the room. /// /// - Only users joined to the room are allowed to call this TODO: Allow any -/// user to call it if history_visibility is world readable +/// user to call it if `history_visibility` is world readable pub async fn get_room_aliases_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -623,7 +623,7 @@ pub async fn upgrade_room_route(body: Ruma) -> Result }) .expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, sender_user, @@ -720,7 +720,7 @@ pub async fn upgrade_room_route(body: Ruma) -> Result event_type: TimelineEventType::RoomCreate, content: to_raw_value(&create_event_content).expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, sender_user, @@ -785,7 +785,7 @@ pub async fn upgrade_room_route(body: Ruma) -> Result event_type: event_type.to_string().into(), content: event_content, unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, sender_user, @@ -827,7 +827,7 @@ pub async fn upgrade_room_route(body: Ruma) -> Result event_type: TimelineEventType::RoomPowerLevels, content: to_raw_value(&power_levels_event_content).expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, sender_user, diff --git a/src/api/client_server/session.rs b/src/api/client_server/session.rs index dc7ee096..381f08ea 100644 --- a/src/api/client_server/session.rs +++ b/src/api/client_server/session.rs @@ -192,7 +192,7 @@ pub async fn login_route(body: Ruma) -> Result, ) -> Result { @@ -48,7 +48,7 @@ pub async fn send_state_event_for_key_route( /// - The only requirement for the content is that it has to be valid json /// - Tries to send the event into the room, auth rules will determine if it is /// allowed -/// - If event is new canonical_alias: Rejects if alias is incorrect +/// - If event is new `canonical_alias`: Rejects if alias is incorrect pub async fn send_state_event_for_empty_key_route( body: Ruma, ) -> Result> { diff --git a/src/api/client_server/sync.rs b/src/api/client_server/sync.rs index a7ef1d54..12a4a10c 100644 --- a/src/api/client_server/sync.rs +++ b/src/api/client_server/sync.rs @@ -68,7 +68,7 @@ use crate::{service::rooms::timeline::PduCount, services, Error, PduEvent, Resul /// at the point of the invite /// /// For left rooms: -/// - If the user left after `since`: prev_batch token, empty state (TODO: +/// - If the user left after `since`: `prev_batch` token, empty state (TODO: /// subset of the state at the point of the leave) /// /// - Sync is handled in an async task, multiple requests from the same device diff --git a/src/api/client_server/tag.rs b/src/api/client_server/tag.rs index 381596fd..406dcaa7 100644 --- a/src/api/client_server/tag.rs +++ b/src/api/client_server/tag.rs @@ -20,15 +20,16 @@ pub async fn update_tag_route(body: Ruma) -> Result) -> Result) -> Result (None, None, None, true), - AuthScheme::None => (None, None, None, true), + AuthScheme::ServerSignatures | AuthScheme::None => (None, None, None, true), } } else { match metadata.authentication { @@ -341,8 +340,8 @@ where sender_user, sender_device, sender_servername, - from_appservice, json_body, + from_appservice, }) } } diff --git a/src/api/server_server.rs b/src/api/server_server.rs index d7ff846e..5d7d2a59 100644 --- a/src/api/server_server.rs +++ b/src/api/server_server.rs @@ -65,7 +65,7 @@ use crate::{ /// (colon-plus-port if it was specified). /// /// Note: A `FedDest::Named` might contain an IP address in string form if there -/// was no port specified to construct a SocketAddr with. +/// was no port specified to construct a `SocketAddr` with. /// /// # Examples: /// ```rust @@ -73,9 +73,9 @@ use crate::{ /// # fn main() -> Result<(), std::net::AddrParseError> { /// FedDest::Literal("198.51.100.3:8448".parse()?); /// FedDest::Literal("[2001:db8::4:5]:443".parse()?); -/// FedDest::Named("matrix.example.org".to_owned(), "".to_owned()); +/// FedDest::Named("matrix.example.org".to_owned(), String::new()); /// FedDest::Named("matrix.example.org".to_owned(), ":8448".to_owned()); -/// FedDest::Named("198.51.100.5".to_owned(), "".to_owned()); +/// FedDest::Named("198.51.100.5".to_owned(), String::new()); /// # Ok(()) /// # } /// ``` @@ -309,24 +309,21 @@ where debug!( "Timed out sending request to {} at {}: {}", destination, actual_destination_str, e - ) + ); + } else if e.is_connect() { + debug!("Failed to connect to {} at {}: {}", destination, actual_destination_str, e); + } else if e.is_redirect() { + debug!( + "Redirect loop sending request to {} at {}: {}\nFinal URL: {:?}", + destination, + actual_destination_str, + e, + e.url() + ); } else { - if e.is_connect() { - debug!("Failed to connect to {} at {}: {}", destination, actual_destination_str, e) - } else { - if e.is_redirect() { - debug!( - "Redirect loop sending request to {} at {}: {}\nFinal URL: {:?}", - destination, - actual_destination_str, - e, - e.url() - ) - } else { - info!("Could not send request to {} at {}: {}", destination, actual_destination_str, e); - } - } + info!("Could not send request to {} at {}: {}", destination, actual_destination_str, e); } + Err(e.into()) }, } @@ -350,7 +347,7 @@ fn add_port_to_hostname(destination_str: &str) -> FedDest { FedDest::Named(host.to_owned(), port.to_owned()) } -/// Returns: actual_destination, host header +/// Returns: `actual_destination`, host header /// Implemented according to the specification at /// Numbers in comments below refer to bullet points in linked section of /// specification @@ -1690,9 +1687,9 @@ pub async fn get_profile_information_route( } Ok(get_profile_information::v1::Response { - blurhash, displayname, avatar_url, + blurhash, }) } diff --git a/src/clap.rs b/src/clap.rs index f1748b71..9bfe475d 100644 --- a/src/clap.rs +++ b/src/clap.rs @@ -9,6 +9,7 @@ use clap::Parser; /// Set the environment variable `CONDUIT_VERSION_EXTRA` to any UTF-8 string to /// include it in parenthesis after the SemVer version. A common value are git /// commit hashes. +#[allow(clippy::doc_markdown)] fn version() -> String { let cargo_pkg_version = env!("CARGO_PKG_VERSION"); @@ -28,4 +29,5 @@ pub struct Args { } /// Parse commandline arguments into structured data +#[must_use] pub fn parse() -> Args { Args::parse() } diff --git a/src/config/mod.rs b/src/config/mod.rs index 7e8eae4b..7e0b6dc5 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -1,7 +1,6 @@ use std::{ - collections::BTreeMap, - fmt, - fmt::Write as _, + collections::BTreeSet, + fmt::{self, Write as _}, net::{IpAddr, Ipv4Addr}, path::PathBuf, }; @@ -11,7 +10,7 @@ use figment::Figment; use itertools::Itertools; use regex::RegexSet; use ruma::{OwnedRoomId, OwnedServerName, RoomVersionId}; -use serde::{de::IgnoredAny, Deserialize}; +use serde::Deserialize; use tracing::{debug, error, warn}; use self::proxy::ProxyConfig; @@ -27,6 +26,7 @@ pub struct ListeningPort { /// all the config options for conduwuit #[derive(Clone, Debug, Deserialize)] +#[allow(clippy::struct_excessive_bools)] pub struct Config { /// [`IpAddr`] conduwuit will listen on (can be IPv4 or IPv6) #[serde(default = "default_address")] @@ -216,7 +216,7 @@ pub struct Config { pub block_non_admin_invites: bool, #[serde(flatten)] - pub catchall: BTreeMap, + pub catchall: BTreeSet, } #[derive(Clone, Debug, Deserialize)] @@ -238,7 +238,7 @@ impl Config { pub fn warn_deprecated(&self) { debug!("Checking for deprecated config keys"); let mut was_deprecated = false; - for key in self.catchall.keys().filter(|key| DEPRECATED_KEYS.iter().any(|s| s == key)) { + for key in self.catchall.iter().filter(|key| DEPRECATED_KEYS.iter().any(|s| s == key)) { warn!("Config parameter \"{}\" is deprecated, ignoring.", key); was_deprecated = true; } @@ -256,7 +256,7 @@ impl Config { pub fn warn_unknown_key(&self) { debug!("Checking for unknown config keys"); for key in - self.catchall.keys().filter(|key| "config".to_owned().ne(key.to_owned()) /* "config" is expected */) + self.catchall.iter().filter(|key| "config".to_owned().ne(key.to_owned()) /* "config" is expected */) { warn!("Config parameter \"{}\" is unknown to conduwuit, ignoring.", key); } @@ -589,11 +589,13 @@ fn default_rocksdb_compression_algo() -> String { "zstd".to_owned() } /// Default RocksDB compression level is 32767, which is internally read by /// RocksDB as the default magic number and translated to the library's default /// compression level as they all differ. See their `kDefaultCompressionLevel`. +#[allow(clippy::doc_markdown)] fn default_rocksdb_compression_level() -> i32 { 32767 } /// Default RocksDB compression level is 32767, which is internally read by /// RocksDB as the default magic number and translated to the library's default /// compression level as they all differ. See their `kDefaultCompressionLevel`. +#[allow(clippy::doc_markdown)] fn default_rocksdb_bottommost_compression_level() -> i32 { 32767 } // I know, it's a great name diff --git a/src/config/proxy.rs b/src/config/proxy.rs index 54572648..bf9a672d 100644 --- a/src/config/proxy.rs +++ b/src/config/proxy.rs @@ -131,7 +131,7 @@ impl std::str::FromStr for WildCardedDomain { Ok(if s.starts_with("*.") { WildCardedDomain::WildCarded(s[1..].to_owned()) } else if s == "*" { - WildCardedDomain::WildCarded("".to_owned()) + WildCardedDomain::WildCarded(String::new()) } else { WildCardedDomain::Exact(s.to_owned()) }) diff --git a/src/database/abstraction/rocksdb.rs b/src/database/abstraction/rocksdb.rs index 471f581f..33d14371 100644 --- a/src/database/abstraction/rocksdb.rs +++ b/src/database/abstraction/rocksdb.rs @@ -95,7 +95,6 @@ fn db_options( // Compression let rocksdb_compression_algo = match config.rocksdb_compression_algo.as_ref() { - "zstd" => rust_rocksdb::DBCompressionType::Zstd, "zlib" => rust_rocksdb::DBCompressionType::Zlib, "lz4" => rust_rocksdb::DBCompressionType::Lz4, "bz2" => rust_rocksdb::DBCompressionType::Bz2, @@ -247,7 +246,7 @@ impl KeyValueDatabaseEngine for Arc { let ret = if self.config.database_backups_to_keep > 0 { match engine.create_new_backup_flush(&self.rocks, true) { Err(e) => return Err(Box::new(e)), - Ok(_) => { + Ok(()) => { let _info = engine.get_backup_info(); let info = &_info.last().unwrap(); info!( @@ -435,7 +434,7 @@ impl KvTree for RocksDbEngineTree<'_> { let lock = self.write_lock.write().unwrap(); let old = self.db.rocks.get_cf_opt(&self.cf(), key, &readoptions)?; - let new = utils::increment(old.as_deref()).unwrap(); + let new = utils::increment(old.as_deref()); self.db.rocks.put_cf_opt(&self.cf(), key, &new, &writeoptions)?; drop(lock); @@ -458,7 +457,7 @@ impl KvTree for RocksDbEngineTree<'_> { for key in iter { let old = self.db.rocks.get_cf_opt(&self.cf(), &key, &readoptions)?; - let new = utils::increment(old.as_deref()).unwrap(); + let new = utils::increment(old.as_deref()); batch.put_cf(&self.cf(), key, new); } diff --git a/src/database/key_value/globals.rs b/src/database/key_value/globals.rs index fd0978d5..14aa8d66 100644 --- a/src/database/key_value/globals.rs +++ b/src/database/key_value/globals.rs @@ -263,12 +263,11 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n" .server_signingkeys .get(origin.as_bytes())? .and_then(|bytes| serde_json::from_slice(&bytes).ok()) - .map(|keys: ServerSigningKeys| { + .map_or_else(BTreeMap::new, |keys: ServerSigningKeys| { let mut tree = keys.verify_keys; tree.extend(keys.old_verify_keys.into_iter().map(|old| (old.0, VerifyKey::new(old.1.key)))); tree - }) - .unwrap_or_else(BTreeMap::new); + }); Ok(signingkeys) } diff --git a/src/database/key_value/pusher.rs b/src/database/key_value/pusher.rs index f33eca34..537c7343 100644 --- a/src/database/key_value/pusher.rs +++ b/src/database/key_value/pusher.rs @@ -20,7 +20,7 @@ impl service::pusher::Data for KeyValueDatabase { let mut key = sender.as_bytes().to_vec(); key.push(0xFF); key.extend_from_slice(ids.pushkey.as_bytes()); - self.senderkey_pusher.remove(&key).map(|_| ()).map_err(Into::into) + self.senderkey_pusher.remove(&key).map_err(Into::into) }, } } diff --git a/src/database/key_value/rooms/user.rs b/src/database/key_value/rooms/user.rs index 839ce2f3..4fa4dc14 100644 --- a/src/database/key_value/rooms/user.rs +++ b/src/database/key_value/rooms/user.rs @@ -24,12 +24,9 @@ impl service::rooms::user::Data for KeyValueDatabase { userroom_id.push(0xFF); userroom_id.extend_from_slice(room_id.as_bytes()); - self.userroomid_notificationcount - .get(&userroom_id)? - .map(|bytes| { - utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Invalid notification count in db.")) - }) - .unwrap_or(Ok(0)) + self.userroomid_notificationcount.get(&userroom_id)?.map_or(Ok(0), |bytes| { + utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Invalid notification count in db.")) + }) } fn highlight_count(&self, user_id: &UserId, room_id: &RoomId) -> Result { @@ -37,12 +34,9 @@ impl service::rooms::user::Data for KeyValueDatabase { userroom_id.push(0xFF); userroom_id.extend_from_slice(room_id.as_bytes()); - self.userroomid_highlightcount - .get(&userroom_id)? - .map(|bytes| { - utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Invalid highlight count in db.")) - }) - .unwrap_or(Ok(0)) + self.userroomid_highlightcount.get(&userroom_id)?.map_or(Ok(0), |bytes| { + utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Invalid highlight count in db.")) + }) } fn last_notification_read(&self, user_id: &UserId, room_id: &RoomId) -> Result { diff --git a/src/database/key_value/users.rs b/src/database/key_value/users.rs index 09944416..550d46c9 100644 --- a/src/database/key_value/users.rs +++ b/src/database/key_value/users.rs @@ -125,7 +125,7 @@ impl service::users::Data for KeyValueDatabase { Ok(()) } - /// Get the avatar_url of a user. + /// Get the `avatar_url` of a user. fn avatar_url(&self, user_id: &UserId) -> Result> { self.userid_avatarurl .get(user_id.as_bytes())? @@ -324,13 +324,10 @@ impl service::users::Data for KeyValueDatabase { } fn last_one_time_keys_update(&self, user_id: &UserId) -> Result { - self.userid_lastonetimekeyupdate - .get(user_id.as_bytes())? - .map(|bytes| { - utils::u64_from_bytes(&bytes) - .map_err(|_| Error::bad_database("Count in roomid_lastroomactiveupdate is invalid.")) - }) - .unwrap_or(Ok(0)) + self.userid_lastonetimekeyupdate.get(user_id.as_bytes())?.map_or(Ok(0), |bytes| { + utils::u64_from_bytes(&bytes) + .map_err(|_| Error::bad_database("Count in roomid_lastroomactiveupdate is invalid.")) + }) } fn take_one_time_key( @@ -817,7 +814,7 @@ impl KeyValueDatabase {} /// Will only return with Some(username) if the password was not empty and the /// username could be successfully parsed. -/// If utils::string_from_bytes(...) returns an error that username will be +/// If `utils::string_from_bytes`(...) returns an error that username will be /// skipped and the error will be logged. fn get_username_with_valid_password(username: &[u8], password: &[u8]) -> Option { // A valid password is not empty diff --git a/src/database/mod.rs b/src/database/mod.rs index 5f3f1d50..897686dc 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -120,8 +120,8 @@ pub struct KeyValueDatabase { pub(super) roomsynctoken_shortstatehash: Arc, /// Remember the state hash at events in the past. pub(super) shorteventid_shortstatehash: Arc, - /// StateKey = EventType + StateKey, ShortStateKey = Count - pub(super) statekey_shortstatekey: Arc, + pub(super) statekey_shortstatekey: Arc, /* StateKey = EventType + StateKey, ShortStateKey = + * Count */ pub(super) shortstatekey_statekey: Arc, pub(super) roomid_shortroomid: Arc, diff --git a/src/main.rs b/src/main.rs index 33f49266..844ec5a1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -770,8 +770,8 @@ async fn shutdown_signal(handle: ServerHandle, tx: Sender<()>) -> Result<()> { #[cfg(unix)] tokio::select! { - _ = ctrl_c => { sig = "Ctrl+C"; }, - _ = terminate => { sig = "SIGTERM"; }, + () = ctrl_c => { sig = "Ctrl+C"; }, + () = terminate => { sig = "SIGTERM"; }, } #[cfg(not(unix))] diff --git a/src/service/admin/mod.rs b/src/service/admin/mod.rs index 291333df..11aa26e5 100644 --- a/src/service/admin/mod.rs +++ b/src/service/admin/mod.rs @@ -790,12 +790,12 @@ impl Service { "Deleted {} total MXCs from our database and the filesystem from event ID {event_id}.", mxc_deletion_count ))); - } else { - return Ok(RoomMessageEventContent::text_plain( - "Please specify either an MXC using --mxc or an event ID using --event-id of the \ - message containing an image. See --help for details.", - )); } + + return Ok(RoomMessageEventContent::text_plain( + "Please specify either an MXC using --mxc or an event ID using --event-id of the message \ + containing an image. See --help for details.", + )); }, MediaCommand::DeleteList => { if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" { @@ -814,11 +814,11 @@ impl Service { filesystem.", mxc_deletion_count ))); - } else { - return Ok(RoomMessageEventContent::text_plain( - "Expected code block in command body. Add --help for details.", - )); } + + return Ok(RoomMessageEventContent::text_plain( + "Expected code block in command body. Add --help for details.", + )); }, MediaCommand::DeletePastRemoteMedia { duration, @@ -1322,12 +1322,12 @@ impl Service { ignoring error and logging here: {e}" ); continue; - } else { - return Ok(RoomMessageEventContent::text_plain(format!( - "{room_id} is not a valid room ID, please fix the list and try \ - again: {e}" - ))); } + + return Ok(RoomMessageEventContent::text_plain(format!( + "{room_id} is not a valid room ID, please fix the list and try again: \ + {e}" + ))); }, } } @@ -1415,17 +1415,16 @@ impl Service { disabled incoming federation with the room.", room_ban_count ))); - } else { - return Ok(RoomMessageEventContent::text_plain(format!( - "Finished bulk room ban, banned {} total rooms and evicted all users.", - room_ban_count - ))); } - } else { - return Ok(RoomMessageEventContent::text_plain( - "Expected code block in command body. Add --help for details.", - )); + return Ok(RoomMessageEventContent::text_plain(format!( + "Finished bulk room ban, banned {} total rooms and evicted all users.", + room_ban_count + ))); } + + return Ok(RoomMessageEventContent::text_plain( + "Expected code block in command body. Add --help for details.", + )); }, RoomModeration::UnbanRoom { room, @@ -1856,7 +1855,7 @@ impl Service { let pub_key_map = pub_key_map.read().await; match ruma::signatures::verify_json(&pub_key_map, &value) { - Ok(_) => RoomMessageEventContent::text_plain("Signature correct"), + Ok(()) => RoomMessageEventContent::text_plain("Signature correct"), Err(e) => RoomMessageEventContent::text_plain(format!( "Signature verification failed: {e}" )), @@ -1913,7 +1912,7 @@ impl Service { } let mut result = tokio::task::spawn_blocking(move || match services().globals.db.backup() { - Ok(_) => String::new(), + Ok(()) => String::new(), Err(e) => (*e).to_string(), }) .await @@ -2040,7 +2039,7 @@ impl Service { .send_federation_request( &server, ruma::api::federation::event::get_event::v1::Request { - event_id: event_id.to_owned().into(), + event_id: event_id.clone().into(), }, ) .await @@ -2208,7 +2207,7 @@ impl Service { if let Some(line_index) = text_lines.iter().position(|line| *line == "[commandbody]") { text_lines.remove(line_index); - while text_lines.get(line_index).map(|line| line.starts_with('#')).unwrap_or(false) { + while text_lines.get(line_index).is_some_and(|line| line.starts_with('#')) { command_body += if text_lines[line_index].starts_with("# ") { &text_lines[line_index][2..] } else { @@ -2293,7 +2292,7 @@ impl Service { event_type: TimelineEventType::RoomCreate, content: to_raw_value(&content).expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, &conduit_user, @@ -2346,7 +2345,7 @@ impl Service { }) .expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, &conduit_user, @@ -2365,7 +2364,7 @@ impl Service { content: to_raw_value(&RoomJoinRulesEventContent::new(JoinRule::Invite)) .expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, &conduit_user, @@ -2384,7 +2383,7 @@ impl Service { content: to_raw_value(&RoomHistoryVisibilityEventContent::new(HistoryVisibility::Shared)) .expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, &conduit_user, @@ -2403,7 +2402,7 @@ impl Service { content: to_raw_value(&RoomGuestAccessEventContent::new(GuestAccess::Forbidden)) .expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, &conduit_user, @@ -2423,7 +2422,7 @@ impl Service { content: to_raw_value(&RoomNameEventContent::new(room_name)) .expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, &conduit_user, @@ -2443,7 +2442,7 @@ impl Service { }) .expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, &conduit_user, @@ -2469,7 +2468,7 @@ impl Service { }) .expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, &conduit_user, @@ -2579,7 +2578,7 @@ impl Service { }) .expect("event is valid, we just created it"), unsigned: None, - state_key: Some("".to_owned()), + state_key: Some(String::new()), redacts: None, }, &conduit_user, diff --git a/src/service/rooms/event_handler/mod.rs b/src/service/rooms/event_handler/mod.rs index d19ff4dc..a843e07d 100644 --- a/src/service/rooms/event_handler/mod.rs +++ b/src/service/rooms/event_handler/mod.rs @@ -367,7 +367,7 @@ impl Service { // The original create event must be in the auth events if !matches!( - auth_events.get(&(StateEventType::RoomCreate, "".to_owned())).map(AsRef::as_ref), + auth_events.get(&(StateEventType::RoomCreate, String::new())).map(AsRef::as_ref), Some(_) | None ) { return Err(Error::BadRequest( diff --git a/src/service/rooms/spaces/mod.rs b/src/service/rooms/spaces/mod.rs index 5e0b6d94..9c7608f3 100644 --- a/src/service/rooms/spaces/mod.rs +++ b/src/service/rooms/spaces/mod.rs @@ -713,7 +713,7 @@ fn is_accessable_child_recurse( return Ok(true); } }, - _ => (), + Identifier::None => (), } // Takes care of joinrules Ok(match join_rule { SpaceRoomJoinRule::KnockRestricted | SpaceRoomJoinRule::Restricted => { @@ -734,6 +734,7 @@ fn is_accessable_child_recurse( false }, SpaceRoomJoinRule::Public | SpaceRoomJoinRule::Knock => true, + #[allow(clippy::match_same_arms)] SpaceRoomJoinRule::Invite | SpaceRoomJoinRule::Private => false, // Custom join rule _ => false, @@ -828,7 +829,7 @@ fn allowed_room_ids(join_rule: JoinRule) -> Vec { room_id: membership, }) = rule { - room_ids.push(membership.to_owned()); + room_ids.push(membership.clone()); } } } diff --git a/src/service/rooms/state/data.rs b/src/service/rooms/state/data.rs index b3850b40..f486f1f8 100644 --- a/src/service/rooms/state/data.rs +++ b/src/service/rooms/state/data.rs @@ -9,7 +9,7 @@ pub trait Data: Send + Sync { /// Returns the last state hash key added to the db for the given room. fn get_room_shortstatehash(&self, room_id: &RoomId) -> Result>; - /// Set the state hash to a new version, but does not update state_cache. + /// Set the state hash to a new version, but does not update `state_cache`. fn set_room_state( &self, room_id: &RoomId, @@ -20,7 +20,7 @@ pub trait Data: Send + Sync { /// Associates a state with an event. fn set_event_state(&self, shorteventid: u64, shortstatehash: u64) -> Result<()>; - /// Returns all events we would send as the prev_events of the next event. + /// Returns all events we would send as the `prev_events` of the next event. fn get_forward_extremities(&self, room_id: &RoomId) -> Result>>; /// Replace the forward extremities of the room. diff --git a/src/service/rooms/state_accessor/mod.rs b/src/service/rooms/state_accessor/mod.rs index e069a89b..0e07b012 100644 --- a/src/service/rooms/state_accessor/mod.rs +++ b/src/service/rooms/state_accessor/mod.rs @@ -230,9 +230,7 @@ impl Service { pub fn get_name(&self, room_id: &RoomId) -> Result> { services().rooms.state_accessor.room_state_get(room_id, &StateEventType::RoomName, "")?.map_or(Ok(None), |s| { - Ok(serde_json::from_str(s.content.get()) - .map(|c: RoomNameEventContent| Some(c.name)) - .unwrap_or_else(|_| None)) + Ok(serde_json::from_str(s.content.get()).map_or_else(|_| None, |c: RoomNameEventContent| Some(c.name))) }) } diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index c7345db9..1ba1d706 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -680,7 +680,7 @@ impl Service { &mut pdu_json, &room_version_id, ) { - Ok(_) => {}, + Ok(()) => {}, Err(e) => { return match e { ruma::signatures::Error::PduSize => { diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index f851aba2..802a9891 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -490,11 +490,9 @@ impl Service { .to_room_event(), ); }, - SendingEventType::Edu(_) => { - // Appservices don't need EDUs (?) - }, - SendingEventType::Flush => { - // flush only; no new content + SendingEventType::Edu(_) | SendingEventType::Flush => { + // Appservices don't need EDUs (?) and flush only; + // no new content }, } } @@ -554,11 +552,9 @@ impl Service { })?, ); }, - SendingEventType::Edu(_) => { - // Push gateways don't need EDUs (?) - }, - SendingEventType::Flush => { - // flush only; no new content + SendingEventType::Edu(_) | SendingEventType::Flush => { + // Push gateways don't need EDUs (?) and flush only; + // no new content }, } } diff --git a/src/utils/error.rs b/src/utils/error.rs index 98a2c9bd..48d18990 100644 --- a/src/utils/error.rs +++ b/src/utils/error.rs @@ -119,6 +119,7 @@ impl Error { | Forbidden | GuestAccessForbidden | ThreepidAuthFailed + | UserDeactivated | ThreepidDenied => StatusCode::FORBIDDEN, Unauthorized | UnknownToken { @@ -129,7 +130,6 @@ impl Error { LimitExceeded { .. } => StatusCode::TOO_MANY_REQUESTS, - UserDeactivated => StatusCode::FORBIDDEN, TooLarge => StatusCode::PAYLOAD_TOO_LARGE, _ => StatusCode::BAD_REQUEST, }, diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 672224f6..b19889ad 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -18,7 +18,7 @@ pub(crate) fn millis_since_unix_epoch() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).expect("time is valid").as_millis() as u64 } -pub(crate) fn increment(old: Option<&[u8]>) -> Option> { +pub(crate) fn increment(old: Option<&[u8]>) -> Vec { let number = match old.map(TryInto::try_into) { Some(Ok(bytes)) => { let number = u64::from_be_bytes(bytes); @@ -27,7 +27,7 @@ pub(crate) fn increment(old: Option<&[u8]>) -> Option> { _ => 1, // Start at one. since 0 should return the first event in the db }; - Some(number.to_be_bytes().to_vec()) + number.to_be_bytes().to_vec() } pub fn generate_keypair() -> Vec { @@ -50,7 +50,7 @@ pub fn string_from_bytes(bytes: &[u8]) -> Result Result { OwnedUserId::try_from( string_from_bytes(bytes).map_err(|_| Error::bad_database("Failed to parse string from bytes"))?,