diff --git a/src/admin/debug/commands.rs b/src/admin/debug/commands.rs index d55d63a2c..5d2491a65 100644 --- a/src/admin/debug/commands.rs +++ b/src/admin/debug/commands.rs @@ -121,7 +121,7 @@ pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result { } else { "PDU found in our database" }; - write!(self, "{msg}\n```json\n{text}\n```",) + write!(self, "{msg}\n```json\n{text}\n```") }, } .await @@ -189,10 +189,7 @@ pub(super) async fn get_remote_pdu_list(&self, server: OwnedServerName, force: b for event_id in list { if force { - match self - .get_remote_pdu(event_id.to_owned(), server.clone()) - .await - { + match self.get_remote_pdu(event_id.clone(), server.clone()).await { | Err(e) => { failed_count = failed_count.saturating_add(1); self.services @@ -207,7 +204,7 @@ pub(super) async fn get_remote_pdu_list(&self, server: OwnedServerName, force: b }, } } else { - self.get_remote_pdu(event_id.to_owned(), server.clone()) + self.get_remote_pdu(event_id.clone(), server.clone()) .await?; success_count = success_count.saturating_add(1); } diff --git a/src/admin/federation/commands.rs b/src/admin/federation/commands.rs index 9f6e91270..34abada33 100644 --- a/src/admin/federation/commands.rs +++ b/src/admin/federation/commands.rs @@ -129,6 +129,6 @@ pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result .collect::>() .join("\n"); - self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```",)) + self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```")) .await } diff --git a/src/admin/media/commands.rs b/src/admin/media/commands.rs index a79cc3855..6943d82d5 100644 --- a/src/admin/media/commands.rs +++ b/src/admin/media/commands.rs @@ -262,7 +262,7 @@ pub(super) async fn delete_past_remote_media( ) .await?; - self.write_str(&format!("Deleted {deleted_count} total files.",)) + self.write_str(&format!("Deleted {deleted_count} total files.")) .await } @@ -272,7 +272,7 @@ pub(super) async fn delete_all_from_user(&self, username: String) -> Result { let deleted_count = self.services.media.delete_from_user(&user_id).await?; - self.write_str(&format!("Deleted {deleted_count} total files.",)) + self.write_str(&format!("Deleted {deleted_count} total files.")) .await } @@ -331,7 +331,7 @@ pub(super) async fn delete_all_from_server( } } - self.write_str(&format!("Deleted {deleted_count} total files.",)) + self.write_str(&format!("Deleted {deleted_count} total files.")) .await } diff --git a/src/admin/query/room_alias.rs b/src/admin/query/room_alias.rs index 5187e5fe4..a390e3bb1 100644 --- a/src/admin/query/room_alias.rs +++ b/src/admin/query/room_alias.rs @@ -53,7 +53,7 @@ pub(super) async fn process(subcommand: RoomAliasCommand, context: &Context<'_>) .rooms .alias .all_local_aliases() - .map(|(room_id, alias)| (room_id.to_owned(), alias.to_owned())) + .map(|(room_id, alias)| (room_id, alias.to_owned())) .collect::>() .await; let query_time = timer.elapsed(); diff --git a/src/admin/room/alias.rs b/src/admin/room/alias.rs index 5e8aba9f4..939b36a9a 100644 --- a/src/admin/room/alias.rs +++ b/src/admin/room/alias.rs @@ -139,7 +139,7 @@ pub(super) async fn process(command: RoomAliasCommand, context: &Context<'_>) -> .rooms .alias .all_local_aliases() - .map(|(room_id, localpart)| (room_id.into(), localpart.into())) + .map(|(room_id, localpart)| (room_id, localpart.into())) .collect::>() .await; diff --git a/src/admin/room/commands.rs b/src/admin/room/commands.rs index d8e409119..06061311c 100644 --- a/src/admin/room/commands.rs +++ b/src/admin/room/commands.rs @@ -72,7 +72,7 @@ pub(super) async fn list_rooms( .collect::>() .join("\n"); - self.write_str(&format!("Rooms ({}):\n```\n{body}\n```", rooms.len(),)) + self.write_str(&format!("Rooms ({}):\n```\n{body}\n```", rooms.len())) .await } diff --git a/src/admin/room/directory.rs b/src/admin/room/directory.rs index ac24dbec7..30fe355a0 100644 --- a/src/admin/room/directory.rs +++ b/src/admin/room/directory.rs @@ -67,7 +67,7 @@ pub(super) async fn process(command: RoomDirectoryCommand, context: &Context<'_> .join("\n"); context - .write_str(&format!("Rooms (page {page}):\n```\n{body}\n```",)) + .write_str(&format!("Rooms (page {page}):\n```\n{body}\n```")) .await }, } diff --git a/src/admin/room/info.rs b/src/admin/room/info.rs index c8b735eeb..cfb7a8a83 100644 --- a/src/admin/room/info.rs +++ b/src/admin/room/info.rs @@ -66,7 +66,7 @@ async fn list_joined_members(&self, room_id: OwnedRoomId, local_only: bool) -> R .collect::>() .join("\n"); - self.write_str(&format!("{num} Members in Room \"{room_name}\":\n```\n{body}\n```",)) + self.write_str(&format!("{num} Members in Room \"{room_name}\":\n```\n{body}\n```")) .await } diff --git a/src/admin/room/moderation.rs b/src/admin/room/moderation.rs index 640008333..3ae9d978e 100644 --- a/src/admin/room/moderation.rs +++ b/src/admin/room/moderation.rs @@ -71,7 +71,7 @@ async fn ban_room(&self, room: OwnedRoomOrAliasId) -> Result { debug!("Room specified is a room ID, banning room ID"); - room_id.to_owned() + room_id.clone() } else if room.is_room_alias_id() { let room_alias = match RoomAliasId::parse(&room) { | Ok(room_alias) => room_alias, @@ -203,7 +203,7 @@ async fn ban_list_of_rooms(&self) -> Result { }, }; - room_ids.push(room_id.to_owned()); + room_ids.push(room_id.clone()); } if room_alias_or_id.is_room_alias_id() { @@ -346,7 +346,7 @@ async fn unban_room(&self, room: OwnedRoomOrAliasId) -> Result { debug!("Room specified is a room ID, unbanning room ID"); self.services.rooms.metadata.ban_room(&room_id, false); - room_id.to_owned() + room_id.clone() } else if room.is_room_alias_id() { let room_alias = match RoomAliasId::parse(&room) { | Ok(room_alias) => room_alias, @@ -449,6 +449,6 @@ async fn list_banned_rooms(&self, no_details: bool) -> Result { .collect::>() .join("\n"); - self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```",)) + self.write_str(&format!("Rooms Banned ({num}):\n```\n{body}\n```")) .await } diff --git a/src/admin/server/commands.rs b/src/admin/server/commands.rs index 51e47976e..462c047d6 100644 --- a/src/admin/server/commands.rs +++ b/src/admin/server/commands.rs @@ -159,8 +159,8 @@ pub(super) async fn list_features(&self) -> Result { let mut enabled_features = conduwuit::info::introspection::ENABLED_FEATURES .lock() .expect("locked") - .iter() - .flat_map(|(_, f)| f.iter()) + .values() + .flat_map(|f| f.iter()) .collect::>(); enabled_features.sort_unstable(); diff --git a/src/admin/user/commands.rs b/src/admin/user/commands.rs index cd866a474..1ae3a2b94 100644 --- a/src/admin/user/commands.rs +++ b/src/admin/user/commands.rs @@ -295,7 +295,7 @@ pub(super) async fn reset_password( self.services .users .remove_device(&user_id, &device_id) - .await + .await; }) .await; write!(self, "\nAll existing sessions have been logged out.").await?; @@ -458,7 +458,7 @@ pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result { .collect::>() .join("\n"); - self.write_str(&format!("Rooms {user_id} Joined ({}):\n```\n{body}\n```", rooms.len(),)) + self.write_str(&format!("Rooms {user_id} Joined ({}):\n```\n{body}\n```", rooms.len())) .await } @@ -510,7 +510,7 @@ pub(super) async fn force_join_list_of_local_users( .rooms .state_cache .room_members(&room_id) - .ready_any(|user_id| server_admins.contains(&user_id.to_owned())) + .ready_any(|user_id| server_admins.contains(&user_id)) .await { return Err!("There is not a single server admin in the room.",); @@ -624,7 +624,7 @@ pub(super) async fn force_join_all_local_users( .rooms .state_cache .room_members(&room_id) - .ready_any(|user_id| server_admins.contains(&user_id.to_owned())) + .ready_any(|user_id| server_admins.contains(&user_id)) .await { return Err!("There is not a single server admin in the room.",); @@ -687,7 +687,7 @@ pub(super) async fn force_join_room( ); join_room_by_id_helper(self.services, &user_id, &room_id, None, &servers, &None).await?; - self.write_str(&format!("{user_id} has been joined to {room_id}.",)) + self.write_str(&format!("{user_id} has been joined to {room_id}.")) .await } @@ -719,7 +719,7 @@ pub(super) async fn force_leave_room( .boxed() .await?; - self.write_str(&format!("{user_id} has left {room_id}.",)) + self.write_str(&format!("{user_id} has left {room_id}.")) .await } @@ -788,7 +788,7 @@ pub(super) async fn make_user_admin(&self, user_id: String) -> Result { .boxed() .await?; - self.write_str(&format!("{user_id} has been granted admin privileges.",)) + self.write_str(&format!("{user_id} has been granted admin privileges.")) .await } @@ -1044,7 +1044,7 @@ pub(super) async fn logout(&self, user_id: String) -> Result { self.services .users .remove_device(&user_id, &device_id) - .await + .await; }) .await; self.write_str(&format!("User {user_id} has been logged out from all devices.")) diff --git a/src/api/client/membership/invite.rs b/src/api/client/membership/invite.rs index fd44c68f0..82be4f85b 100644 --- a/src/api/client/membership/invite.rs +++ b/src/api/client/membership/invite.rs @@ -10,7 +10,7 @@ use ruma::{ RoomId, UserId, api::{ client::membership::invite_user::{self, v3::InviteUserId}, - federation::membership::{RawStrippedState, create_invite}, + federation::membership::create_invite, }, events::room::member::{MembershipState, RoomMemberEventContent}, }; diff --git a/src/api/router/auth.rs b/src/api/router/auth.rs index dbfe58f03..809ddd2df 100644 --- a/src/api/router/auth.rs +++ b/src/api/router/auth.rs @@ -34,7 +34,7 @@ pub(super) struct Auth { pub(super) appservice_info: Option, } -pub(crate) trait CheckAuth: AuthScheme { +pub(super) trait CheckAuth: AuthScheme { fn authenticate + Sync>( services: &Services, incoming_request: &hyper::Request, diff --git a/src/core/matrix/event.rs b/src/core/matrix/event.rs index cd8541963..5af35634c 100644 --- a/src/core/matrix/event.rs +++ b/src/core/matrix/event.rs @@ -11,7 +11,7 @@ use std::fmt::Debug; use ruma::{ CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId, - RoomVersionId, UserId, events::TimelineEventType, room_version_rules::RoomVersionRules, + UserId, events::TimelineEventType, room_version_rules::RoomVersionRules, }; use serde::Deserialize; use serde_json::{Value as JsonValue, value::RawValue as RawJsonValue}; diff --git a/src/core/matrix/event/id.rs b/src/core/matrix/event/id.rs index 80636af6a..8a1d05fe5 100644 --- a/src/core/matrix/event/id.rs +++ b/src/core/matrix/event/id.rs @@ -1,7 +1,7 @@ use ruma::{CanonicalJsonObject, OwnedEventId, room_version_rules::RoomVersionRules}; use serde_json::value::RawValue as RawJsonValue; -use crate::{Err, Result, err}; +use crate::{Result, err}; /// Generates a correct eventId for the incoming pdu. /// diff --git a/src/core/matrix/event/redact.rs b/src/core/matrix/event/redact.rs index 019683923..31414d5bf 100644 --- a/src/core/matrix/event/redact.rs +++ b/src/core/matrix/event/redact.rs @@ -1,5 +1,5 @@ use ruma::{ - OwnedEventId, RoomVersionId, + OwnedEventId, events::{TimelineEventType, room::redaction::RoomRedactionEventContent}, room_version_rules::RoomVersionRules, }; @@ -64,8 +64,6 @@ pub(super) fn redacts_id( event: &E, room_version_rules: &RoomVersionRules, ) -> Option { - use RoomVersionId::*; - if *event.kind() != TimelineEventType::RoomRedaction { return None; } diff --git a/src/core/matrix/pdu.rs b/src/core/matrix/pdu.rs index 436e1c123..b05389988 100644 --- a/src/core/matrix/pdu.rs +++ b/src/core/matrix/pdu.rs @@ -127,9 +127,7 @@ impl Event for Pdu { } else { // v12+ let constructed_hash = self.event_id.as_str().replace('$', "!"); - RoomId::parse(&constructed_hash) - .expect("event ID can be parsed") - .to_owned() + RoomId::parse(&constructed_hash).expect("event ID can be parsed") } } @@ -200,9 +198,7 @@ impl Event for &Pdu { } else { // v12+ let constructed_hash = self.event_id.as_str().replace('$', "!"); - RoomId::parse(&constructed_hash) - .expect("event ID can be parsed") - .to_owned() + RoomId::parse(&constructed_hash).expect("event ID can be parsed") } } diff --git a/src/core/matrix/pdu/redact.rs b/src/core/matrix/pdu/redact.rs index 768106d85..280c62622 100644 --- a/src/core/matrix/pdu/redact.rs +++ b/src/core/matrix/pdu/redact.rs @@ -1,7 +1,7 @@ use ruma::{RoomVersionId, canonical_json::redact_content_in_place}; use serde_json::{Value as JsonValue, json, value::to_raw_value}; -use crate::{Err, Error, Result, err, implement}; +use crate::{Err, Result, err, implement}; #[implement(super::Pdu)] pub fn redact(&mut self, room_version_id: &RoomVersionId, reason: JsonValue) -> Result { diff --git a/src/core/matrix/state_res/event_auth.rs b/src/core/matrix/state_res/event_auth.rs index 659385fbb..6f11722c4 100644 --- a/src/core/matrix/state_res/event_auth.rs +++ b/src/core/matrix/state_res/event_auth.rs @@ -85,6 +85,7 @@ pub fn auth_types_for_event( if kind == &TimelineEventType::RoomMember { #[derive(Deserialize)] + #[allow(unused)] struct RoomMemberContentFields { membership: Option>, third_party_invite: Option>, @@ -1003,8 +1004,8 @@ where } else { let allow = sender_creator || sender_power - .filter(|&p| p >= &power_levels.invite) - .is_some(); + .as_ref() + .is_some_and(|&p| p >= &power_levels.invite); if !allow { warn!( %sender, @@ -1029,7 +1030,10 @@ where }, | MembershipState::Leave => { let can_unban = if target_user_current_membership == MembershipState::Ban { - sender_creator || sender_power.filter(|&p| p >= &power_levels.ban).is_some() + sender_creator + || sender_power + .as_ref() + .is_some_and(|&p| p >= &power_levels.ban) } else { true }; @@ -1040,7 +1044,10 @@ where if sender_creator { // sender is a creator true - } else if sender_power.filter(|&p| p >= &power_levels.kick).is_none() { + } else if sender_power + .as_ref() + .is_none_or(|&p| p < &power_levels.kick) + { // sender lacks kick power level false } else if let Some(sp) = sender_power { @@ -1128,7 +1135,9 @@ where false } else { let allow = sender_creator - || (sender_power.filter(|&p| p >= &power_levels.ban).is_some() + || (sender_power + .as_ref() + .is_some_and(|&p| p >= &power_levels.ban) && target_power < sender_power); if !allow { warn!( diff --git a/src/core/matrix/state_res/mod.rs b/src/core/matrix/state_res/mod.rs index 5da383be3..2f06a5dcc 100644 --- a/src/core/matrix/state_res/mod.rs +++ b/src/core/matrix/state_res/mod.rs @@ -163,7 +163,7 @@ where // Sequentially auth check each control event. let resolved_control = iterative_auth_check( - &room_version, + room_version, sorted_control_levels.iter().stream().map(AsRef::as_ref), initial_state, &event_fetch, @@ -203,7 +203,7 @@ where trace!(list = ?sorted_left_events, "events left, sorted, running iterative auth check"); let mut resolved_state = iterative_auth_check( - &room_version, + room_version, sorted_left_events.iter().stream().map(AsRef::as_ref), resolved_control, // The control events are added to the final resolved state &event_fetch, @@ -668,7 +668,7 @@ where "Failed to parse create event ID from room ID/hash: {e}" )) })?; - let create_event = fetch_event(create_event_id.into()) + let create_event = fetch_event(create_event_id) .await .ok_or_else(|| Error::NotFound("Failed to find create event".into()))?; auth_state.insert(create_event.event_type().with_state_key(""), create_event); diff --git a/src/core/matrix/state_res/power_levels.rs b/src/core/matrix/state_res/power_levels.rs index 16eb93864..6b76b4c84 100644 --- a/src/core/matrix/state_res/power_levels.rs +++ b/src/core/matrix/state_res/power_levels.rs @@ -10,7 +10,12 @@ use ruma::{ use serde::Deserialize; use serde_json::{Error, from_str as from_json_str}; -use super::{Result, serde_backports::*}; +use super::{ + Result, + serde_backports::{ + vec_deserialize_int_powerlevel_values, vec_deserialize_v1_powerlevel_values, + }, +}; use crate::error; #[derive(Deserialize)] @@ -47,11 +52,11 @@ struct IntRoomPowerLevelsEventContent { } impl IntRoomPowerLevelsEventContent { - fn to_room_power_levels_content( + fn into_room_power_levels_content( self, auth_rules: &AuthorizationRules, ) -> RoomPowerLevelsEventContent { - let IntRoomPowerLevelsEventContent { + let Self { ban, events, events_default, @@ -116,7 +121,7 @@ fn deserialize_integer_power_levels( auth_rules: &AuthorizationRules, ) -> Option { match from_json_str::(content) { - | Ok(content) => Some(content.to_room_power_levels_content(auth_rules)), + | Ok(content) => Some(content.into_room_power_levels_content(auth_rules)), | Err(_) => { error!("m.room.power_levels event is not valid with integer values"); None diff --git a/src/core/matrix/state_res/serde_backports.rs b/src/core/matrix/state_res/serde_backports.rs index 188190d15..ef6c4d90a 100644 --- a/src/core/matrix/state_res/serde_backports.rs +++ b/src/core/matrix/state_res/serde_backports.rs @@ -16,7 +16,9 @@ use serde::{ /// /// To be used like this: /// `#[serde(deserialize_with = "vec_deserialize_v1_powerlevel_values")]` -pub fn vec_deserialize_v1_powerlevel_values<'de, D, T>(de: D) -> Result, D::Error> +pub(super) fn vec_deserialize_v1_powerlevel_values<'de, D, T>( + de: D, +) -> Result, D::Error> where D: Deserializer<'de>, T: Deserialize<'de> + Ord, @@ -76,7 +78,9 @@ where /// /// To be used like this: /// `#[serde(deserialize_with = "vec_deserialize_int_powerlevel_values")]` -pub fn vec_deserialize_int_powerlevel_values<'de, D, T>(de: D) -> Result, D::Error> +pub(super) fn vec_deserialize_int_powerlevel_values<'de, D, T>( + de: D, +) -> Result, D::Error> where D: Deserializer<'de>, T: Deserialize<'de> + Ord, diff --git a/src/core/matrix/versions.rs b/src/core/matrix/versions.rs index 2d8bd673b..fa2284e7d 100644 --- a/src/core/matrix/versions.rs +++ b/src/core/matrix/versions.rs @@ -1,5 +1,6 @@ use std::collections::BTreeMap; +#[must_use] pub fn versions() -> Vec { vec![ "r0.0.1".to_owned(), @@ -23,6 +24,7 @@ pub fn versions() -> Vec { ] } +#[must_use] pub fn unstable_features() -> BTreeMap { BTreeMap::from_iter([ ("org.matrix.e2e_cross_signing".to_owned(), true), diff --git a/src/database/tests.rs b/src/database/tests.rs index 7131691bd..4949d4f9e 100644 --- a/src/database/tests.rs +++ b/src/database/tests.rs @@ -1,6 +1,6 @@ #![allow(clippy::needless_borrows_for_generic_args)] -use std::{borrow::Cow, fmt::Debug}; +use std::borrow::Cow; use conduwuit::{ arrayvec::ArrayVec, @@ -12,7 +12,7 @@ use conduwuit::{ use serde::Serialize; use crate::{ - Ignore, Interfix, de, ser, + Ignore, de, ser, ser::{Json, serialize_to_vec}, }; @@ -470,6 +470,7 @@ fn serde_tuple_option_none_none() { } #[test] +#[allow(clippy::type_complexity)] fn serde_tuple_option_some_none_some() { let room_id = room_id!("!room:example.com"); let user_id = user_id!("@user:example.com"); diff --git a/src/main/runtime.rs b/src/main/runtime.rs index e90290121..47b86a693 100644 --- a/src/main/runtime.rs +++ b/src/main/runtime.rs @@ -22,7 +22,7 @@ const WORKER_NAME: &str = "conduwuit:worker"; const WORKER_MIN: usize = 2; const WORKER_KEEPALIVE: u64 = 36; const MAX_BLOCKING_THREADS: usize = 1024; -const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(10000); +const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10); #[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] const DISABLE_MUZZY_THRESHOLD: usize = 4; diff --git a/src/router/layers.rs b/src/router/layers.rs index ee17f243f..9b61cdb04 100644 --- a/src/router/layers.rs +++ b/src/router/layers.rs @@ -163,7 +163,7 @@ fn cors_layer(_server: &Server) -> CorsLayer { .allow_origin(cors::Any) .allow_methods(METHODS) .allow_headers(headers) - .max_age(Duration::from_secs(86400)) + .max_age(Duration::from_hours(24)) } fn body_limit_layer(server: &Server) -> DefaultBodyLimit { diff --git a/src/service/admin/mod.rs b/src/service/admin/mod.rs index 93bda513d..ae3c14eac 100644 --- a/src/service/admin/mod.rs +++ b/src/service/admin/mod.rs @@ -395,7 +395,7 @@ impl Service { let mut stream = admin_users; while let Some(user_id) = stream.next().await { - generated_admin_list.push(user_id.to_owned()); + generated_admin_list.push(user_id.clone()); } } } diff --git a/src/service/emergency/mod.rs b/src/service/emergency/mod.rs index f741c9e05..4f99ee9c3 100644 --- a/src/service/emergency/mod.rs +++ b/src/service/emergency/mod.rs @@ -72,7 +72,7 @@ impl Service { None, server_user, GlobalAccountDataEventType::PushRules.to_string().into(), - &serde_json::to_value(&GlobalAccountDataEvent::new(PushRulesEventContent::new( + &serde_json::to_value(GlobalAccountDataEvent::new(PushRulesEventContent::new( ruleset, ))) .expect("to json value always works"), diff --git a/src/service/federation/execute.rs b/src/service/federation/execute.rs index 23e37fe5e..0c147c1ef 100644 --- a/src/service/federation/execute.rs +++ b/src/service/federation/execute.rs @@ -289,7 +289,7 @@ fn handle_error( /// requests for either versioned or unversioned endpoints, by requiring that /// the `Input` of the `PathBuilder` of the endpoint implements /// `FederationPathBuilderInput`. -pub(crate) trait FederationPathBuilderInput { +pub trait FederationPathBuilderInput { fn create() -> Self; } diff --git a/src/service/key_backups/mod.rs b/src/service/key_backups/mod.rs index 747c61e41..3adbc46b1 100644 --- a/src/service/key_backups/mod.rs +++ b/src/service/key_backups/mod.rs @@ -210,7 +210,7 @@ pub async fn get_all( .ignore_err() .ready_for_each(|((_, _, room_id, session_id), key_backup_data): KeyVal<'_>| { rooms - .entry(room_id.into()) + .entry(room_id) .or_insert_with(default) .sessions .insert(session_id.into(), key_backup_data); diff --git a/src/service/media/remote.rs b/src/service/media/remote.rs index 2a02ae9c8..c5862a576 100644 --- a/src/service/media/remote.rs +++ b/src/service/media/remote.rs @@ -215,7 +215,7 @@ async fn handle_thumbnail_file( .await .map(|()| FileMeta { content: Some(content.file), - content_type: content.content_type.map(Into::into), + content_type: content.content_type, content_disposition: Some(content_disposition), }) } @@ -243,7 +243,7 @@ async fn handle_content_file( .await .map(|()| FileMeta { content: Some(content.file), - content_type: content.content_type.map(Into::into), + content_type: content.content_type, content_disposition: Some(content_disposition), }) } @@ -364,7 +364,7 @@ pub async fn fetch_remote_thumbnail_legacy( body.width, body.height, ); - request.method = body.method.clone(); + request.method.clone_from(&body.method); request.allow_remote = body.allow_remote; request.allow_redirect = body.allow_redirect; request.animated = body.animated; diff --git a/src/service/migrations.rs b/src/service/migrations.rs index dd3a2f54c..189afb585 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -610,19 +610,9 @@ async fn fix_readreceiptid_readreceipt_duplicates(services: &Services) -> Result .expect_ok() .ready_for_each(|key: Key| { let (ref room_id, _, ref user_id) = key; - let last_room = cur_room.replace( - room_id - .as_str() - .try_into() - .expect("invalid room_id in database"), - ); + let last_room = cur_room.replace(room_id.as_str().into()); - let last_user = cur_user.replace( - user_id - .as_str() - .try_into() - .expect("invalid user_id in database"), - ); + let last_user = cur_user.replace(user_id.as_str().into()); let is_dup = cur_room == last_room && cur_user == last_user; if is_dup { diff --git a/src/service/password_reset/data.rs b/src/service/password_reset/data.rs index db29328a5..8c5c7d6ec 100644 --- a/src/service/password_reset/data.rs +++ b/src/service/password_reset/data.rs @@ -20,7 +20,7 @@ pub struct ResetTokenInfo { impl ResetTokenInfo { // one hour - const MAX_TOKEN_AGE: Duration = Duration::from_secs(60 * 60); + const MAX_TOKEN_AGE: Duration = Duration::from_hours(1); pub fn is_valid(&self) -> bool { let now = SystemTime::now(); diff --git a/src/service/presence/presence.rs b/src/service/presence/presence.rs index 247608eca..db976adfa 100644 --- a/src/service/presence/presence.rs +++ b/src/service/presence/presence.rs @@ -48,7 +48,7 @@ impl Presence { let now = utils::millis_since_unix_epoch(); let last_active_ago = Some(UInt::new_saturating(now.saturating_sub(self.last_active_ts))); let mut content = PresenceEventContent::new(self.state.clone()); - content.status_msg = self.status_msg.clone(); + content.status_msg.clone_from(&self.status_msg); content.currently_active = Some(self.currently_active); content.last_active_ago = last_active_ago; content.displayname = users.displayname(user_id).await.ok(); diff --git a/src/service/pusher/mod.rs b/src/service/pusher/mod.rs index 70bd8ad02..42cfda34d 100644 --- a/src/service/pusher/mod.rs +++ b/src/service/pusher/mod.rs @@ -13,7 +13,7 @@ use ipaddress::IPAddress; use ruma::{ DeviceId, OwnedDeviceId, RoomId, UInt, UserId, api::{ - IncomingResponse, MatrixVersion, OutgoingRequest, + IncomingResponse, OutgoingRequest, auth_scheme::NoAuthentication, client::push::{Pusher, PusherKind, set_pusher}, path_builder::SinglePath, @@ -42,7 +42,6 @@ struct Services { globals: Dep, config: Dep, client: Dep, - state: Dep, state_accessor: Dep, state_cache: Dep, users: Dep, @@ -65,7 +64,6 @@ impl crate::Service for Service { globals: args.depend::("globals"), client: args.depend::("client"), config: args.depend::("config"), - state: args.depend::("rooms::state"), state_accessor: args .depend::("rooms::state_accessor"), state_cache: args.depend::("rooms::state_cache"), @@ -200,8 +198,6 @@ impl Service { + Debug + Send, { - const VERSIONS: [MatrixVersion; 1] = [MatrixVersion::V1_0]; - let dest = dest.replace(self.services.globals.notification_push_path(), ""); trace!("Push gateway destination: {dest}"); diff --git a/src/service/resolver/dns.rs b/src/service/resolver/dns.rs index 3a0b25519..e9336f814 100644 --- a/src/service/resolver/dns.rs +++ b/src/service/resolver/dns.rs @@ -53,9 +53,9 @@ impl Resolver { opts.cache_size = config.dns_cache_entries as usize; opts.preserve_intermediates = true; opts.negative_min_ttl = Some(Duration::from_secs(config.dns_min_ttl_nxdomain)); - opts.negative_max_ttl = Some(Duration::from_secs(60 * 60 * 24 * 30)); + opts.negative_max_ttl = Some(Duration::from_hours(720)); opts.positive_min_ttl = Some(Duration::from_secs(config.dns_min_ttl)); - opts.positive_max_ttl = Some(Duration::from_secs(60 * 60 * 24 * 7)); + opts.positive_max_ttl = Some(Duration::from_hours(168)); opts.timeout = Duration::from_secs(config.dns_timeout); opts.attempts = config.dns_attempts as usize; opts.try_tcp_on_error = config.dns_tcp_fallback; diff --git a/src/service/rooms/alias/mod.rs b/src/service/rooms/alias/mod.rs index 6816bf9c7..10fb50185 100644 --- a/src/service/rooms/alias/mod.rs +++ b/src/service/rooms/alias/mod.rs @@ -7,7 +7,7 @@ use conduwuit::{ utils::{ReadyExt, stream::TryIgnore}, }; use database::{Deserialized, Ignore, Interfix, Map}; -use futures::{Stream, StreamExt, TryFutureExt}; +use futures::{Stream, StreamExt}; use ruma::{ OwnedRoomAliasId, OwnedRoomId, OwnedServerName, OwnedUserId, RoomAliasId, RoomId, RoomOrAliasId, UserId, events::StateEventType, diff --git a/src/service/rooms/event_handler/handle_incoming_pdu.rs b/src/service/rooms/event_handler/handle_incoming_pdu.rs index 950c18dca..ecb2fc17f 100644 --- a/src/service/rooms/event_handler/handle_incoming_pdu.rs +++ b/src/service/rooms/event_handler/handle_incoming_pdu.rs @@ -14,7 +14,7 @@ use futures::{ use ruma::{ CanonicalJsonValue, EventId, OwnedUserId, RoomId, ServerName, UserId, events::{ - StateEventType, TimelineEventType, + TimelineEventType, room::member::{MembershipState, RoomMemberEventContent}, }, }; @@ -209,7 +209,7 @@ pub async fn handle_incoming_pdu<'a>( } // Fetch create event - let ref create_event = self + let create_event = &self .services .state_accessor .get_room_create_event(room_id) diff --git a/src/service/rooms/short/mod.rs b/src/service/rooms/short/mod.rs index 7c21e826e..20685442b 100644 --- a/src/service/rooms/short/mod.rs +++ b/src/service/rooms/short/mod.rs @@ -278,8 +278,8 @@ where let (short_state_keys, short_event_ids): pair_of!(Vec<_>) = short_state.unzip().await; StreamExt::zip( - self.multi_get_statekey_from_short(stream::iter(short_state_keys.into_iter())), - self.multi_get_eventid_from_short(stream::iter(short_event_ids.into_iter())), + self.multi_get_statekey_from_short(stream::iter(short_state_keys)), + self.multi_get_eventid_from_short(stream::iter(short_event_ids)), ) .ready_filter_map(|state_event| match state_event { | (Ok(state_key), Ok(event_id)) => Some(Ok((state_key, event_id))), diff --git a/src/service/rooms/state_accessor/mod.rs b/src/service/rooms/state_accessor/mod.rs index b1eb9e5d3..ca0394f28 100644 --- a/src/service/rooms/state_accessor/mod.rs +++ b/src/service/rooms/state_accessor/mod.rs @@ -98,18 +98,16 @@ impl Service { pub async fn is_world_readable(&self, room_id: &RoomId) -> bool { self.room_state_get_content(room_id, &StateEventType::RoomHistoryVisibility, "") .await - .map(|c: RoomHistoryVisibilityEventContent| { + .is_ok_and(|c: RoomHistoryVisibilityEventContent| { c.history_visibility == HistoryVisibility::WorldReadable }) - .unwrap_or(false) } /// Checks if guests are able to join a given room pub async fn guest_can_join(&self, room_id: &RoomId) -> bool { self.room_state_get_content(room_id, &StateEventType::RoomGuestAccess, "") .await - .map(|c: RoomGuestAccessEventContent| c.guest_access == GuestAccess::CanJoin) - .unwrap_or(false) + .is_ok_and(|c: RoomGuestAccessEventContent| c.guest_access == GuestAccess::CanJoin) } /// Gets the primary alias from canonical alias event diff --git a/src/service/rooms/summary/mod.rs b/src/service/rooms/summary/mod.rs index 2ac78292c..4c779c796 100644 --- a/src/service/rooms/summary/mod.rs +++ b/src/service/rooms/summary/mod.rs @@ -254,7 +254,7 @@ impl Service { }; summaries.push(summary.summary); - inaccessible_children.extend(summary.inaccessible_children.into_iter()); + inaccessible_children.extend(summary.inaccessible_children); // Don't traverse the tree deeper than max_depth #[allow( diff --git a/src/service/rooms/timeline/backfill.rs b/src/service/rooms/timeline/backfill.rs index 842f274e1..9930cf466 100644 --- a/src/service/rooms/timeline/backfill.rs +++ b/src/service/rooms/timeline/backfill.rs @@ -9,7 +9,7 @@ use conduwuit_core::{ }, validated, warn, }; -use futures::{FutureExt, StreamExt}; +use futures::FutureExt; use ruma::{ CanonicalJsonObject, EventId, OwnedServerName, RoomId, ServerName, api::federation, events::TimelineEventType, uint, diff --git a/src/service/sending/antispam.rs b/src/service/sending/antispam.rs index 796e08ba4..9cc1b52c3 100644 --- a/src/service/sending/antispam.rs +++ b/src/service/sending/antispam.rs @@ -4,7 +4,7 @@ use bytes::BytesMut; use conduwuit::{Err, Result, debug_error, err, utils, utils::response::LimitReadExt, warn}; use reqwest::Client; use ruma::api::{ - IncomingResponse, MatrixVersion, OutgoingRequest, + IncomingResponse, OutgoingRequest, auth_scheme::{AppserviceToken, SendAccessToken}, path_builder::VersionHistory, }; @@ -23,7 +23,6 @@ where + Debug + Send, { - const VERSIONS: [MatrixVersion; 1] = [MatrixVersion::V1_15]; let http_request = request .try_into_http_request::( base_url, diff --git a/src/service/sending/data.rs b/src/service/sending/data.rs index 53aec7d08..59f5c0647 100644 --- a/src/service/sending/data.rs +++ b/src/service/sending/data.rs @@ -224,7 +224,7 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se .ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?; ( - Destination::Push(user_id.to_owned(), pushkey_string), + Destination::Push(user_id, pushkey_string), if value.is_empty() { SendingEvent::Pdu(event.into()) } else { diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index ccdccbca3..026a7132f 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -203,9 +203,7 @@ impl Service { S: Stream + Send, { let requests = servers - .map(|server| { - (Destination::Federation(server.into()), SendingEvent::Pdu(pdu_id.to_owned())) - }) + .map(|server| (Destination::Federation(server), SendingEvent::Pdu(pdu_id.to_owned()))) .collect::>() .await; diff --git a/src/service/server_keys/acquire.rs b/src/service/server_keys/acquire.rs index 0f8c943c2..a14056257 100644 --- a/src/service/server_keys/acquire.rs +++ b/src/service/server_keys/acquire.rs @@ -236,5 +236,5 @@ async fn acquire_notary_result(&self, missing: &mut Batch, server_keys: ServerSi } fn keys_count(batch: &Batch) -> usize { - batch.iter().flat_map(|(_, key_ids)| key_ids.iter()).count() + batch.values().flat_map(|key_ids| key_ids.iter()).count() } diff --git a/src/service/server_keys/mod.rs b/src/service/server_keys/mod.rs index 26b4ffc70..5df3e5193 100644 --- a/src/service/server_keys/mod.rs +++ b/src/service/server_keys/mod.rs @@ -50,7 +50,7 @@ pub type PubKeys = PublicKeySet; impl crate::Service for Service { fn build(args: crate::Args<'_>) -> Result> { - let minimum_valid = Duration::from_secs(3600); + let minimum_valid = Duration::from_hours(1); let (keypair, verify_keys) = keypair::init(args.db)?; debug_assert!(verify_keys.len() == 1, "only one active verify_key supported"); @@ -171,11 +171,10 @@ pub async fn verify_keys_for(&self, origin: &ServerName) -> VerifyKeys { let mut keys = self .signing_keys_for(origin) .await - .map(|keys| merge_old_keys(keys).verify_keys) - .unwrap_or(BTreeMap::new()); + .map_or(BTreeMap::new(), |keys| merge_old_keys(keys).verify_keys); if self.services.globals.server_is_ours(origin) { - keys.extend(self.verify_keys.clone().into_iter()); + keys.extend(self.verify_keys.clone()); } keys diff --git a/src/service/server_keys/util.rs b/src/service/server_keys/util.rs index 96757604f..760ab31de 100644 --- a/src/service/server_keys/util.rs +++ b/src/service/server_keys/util.rs @@ -23,8 +23,8 @@ pub(super) fn required_keys( }; let entry = map.entry(server.clone()).or_default(); - set.iter() - .map(|(k, _)| k.clone()) + set.keys() + .cloned() .map(TryInto::try_into) .filter_map(Result::ok) .for_each(|key_id| entry.push(key_id)); diff --git a/src/service/sync/mod.rs b/src/service/sync/mod.rs index 3bf54a34c..44fc3ac2f 100644 --- a/src/service/sync/mod.rs +++ b/src/service/sync/mod.rs @@ -39,6 +39,7 @@ struct Services { typing: Dep, } +#[allow(unused, reason = "TODO refactor")] struct SlidingSyncCache { lists: BTreeMap, subscriptions: BTreeMap, diff --git a/src/service/sync/watch.rs b/src/service/sync/watch.rs index f6dd77271..ce8f20f5f 100644 --- a/src/service/sync/watch.rs +++ b/src/service/sync/watch.rs @@ -64,7 +64,7 @@ pub async fn watch(&self, user_id: &UserId, device_id: &DeviceId) -> Result { futures.push(self.db.pduid_pdu.watch_prefix(&short_roomid)); // EDUs - let typing_room_id = room_id.to_owned(); + let typing_room_id = room_id.clone(); let typing_wait_for_update = async move { self.services.typing.wait_for_update(&typing_room_id).await; }; diff --git a/src/service/threepid/session.rs b/src/service/threepid/session.rs index 5f3af93b2..f8f42d2c0 100644 --- a/src/service/threepid/session.rs +++ b/src/service/threepid/session.rs @@ -43,7 +43,7 @@ pub(crate) struct ValidationToken { impl ValidationToken { // one hour - const MAX_TOKEN_AGE: Duration = Duration::from_secs(60 * 60); + const MAX_TOKEN_AGE: Duration = Duration::from_hours(1); const RANDOM_TOKEN_LENGTH: usize = 16; pub(super) fn new_random() -> Self { diff --git a/src/service/transactions/mod.rs b/src/service/transactions/mod.rs index 1ee7f4000..ae03499d7 100644 --- a/src/service/transactions/mod.rs +++ b/src/service/transactions/mod.rs @@ -315,7 +315,7 @@ impl Service { | TxnState::Active(_) => None, }) .collect(); - cached_entries.sort_by(|a, b| a.1.cmp(&b.1)); + cached_entries.sort_by_key(|a| a.1); // Remove the oldest cached entries to get under the limit for (key, _) in cached_entries.into_iter().take(excess) { diff --git a/src/service/users/mod.rs b/src/service/users/mod.rs index 5c4e42a46..3100f0590 100644 --- a/src/service/users/mod.rs +++ b/src/service/users/mod.rs @@ -165,10 +165,9 @@ impl Service { .account_data .get_global(recipient_user, GlobalAccountDataEventType::InvitePermissionConfig) .await - .map(|config: InvitePermissionConfigEvent| { + .map_or(FilterLevel::Allow, |config: InvitePermissionConfigEvent| { config.content.user_filter_level(sender_user) }) - .unwrap_or(FilterLevel::Allow) } }