1
0
Fork 0
mirror of https://gitlab.com/famedly/conduit.git synced 2024-06-26 05:18:18 +02:00

cargo clippy

This commit is contained in:
Nyaaori 2022-10-10 14:09:11 +02:00
parent ca82b2940d
commit f430b87459
No known key found for this signature in database
GPG key ID: E7819C3ED4D1F82E
32 changed files with 139 additions and 166 deletions

View file

@ -333,7 +333,7 @@ pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3:
Ok(whoami::v3::Response {
user_id: sender_user.clone(),
device_id,
is_guest: services().users.is_deactivated(&sender_user)?,
is_guest: services().users.is_deactivated(sender_user)?,
})
}
@ -383,7 +383,7 @@ pub async fn deactivate_route(
}
// Make the user leave all rooms before deactivation
client_server::leave_all_rooms(&sender_user).await?;
client_server::leave_all_rooms(sender_user).await?;
// Remove devices and mark account as deactivated
services().users.deactivate_account(sender_user)?;

View file

@ -234,7 +234,7 @@ pub async fn get_key_changes_route(
services()
.users
.keys_changed(
&room_id.to_string(),
room_id.as_ref(),
body.from.parse().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`.")
})?,
@ -264,7 +264,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
let mut get_over_federation = HashMap::new();
for (user_id, device_ids) in device_keys_input {
let user_id: &UserId = &**user_id;
let user_id: &UserId = user_id;
if user_id.server_name() != services().globals.server_name() {
get_over_federation

View file

@ -62,15 +62,13 @@ pub async fn join_room_by_id_route(
servers.push(body.room_id.server_name().to_owned());
let ret = join_room_by_id_helper(
join_room_by_id_helper(
body.sender_user.as_deref(),
&body.room_id,
&servers,
body.third_party_signed.as_ref(),
)
.await;
ret
.await
}
/// # `POST /_matrix/client/r0/join/{roomIdOrAlias}`
@ -171,7 +169,7 @@ pub async fn kick_user_route(
.room_state_get(
&body.room_id,
&StateEventType::RoomMember,
&body.user_id.to_string(),
body.user_id.as_ref(),
)?
.ok_or(Error::BadRequest(
ErrorKind::BadState,
@ -230,7 +228,7 @@ pub async fn ban_user_route(
.room_state_get(
&body.room_id,
&StateEventType::RoomMember,
&body.user_id.to_string(),
body.user_id.as_ref(),
)?
.map_or(
Ok(RoomMemberEventContent {
@ -297,7 +295,7 @@ pub async fn unban_user_route(
.room_state_get(
&body.room_id,
&StateEventType::RoomMember,
&body.user_id.to_string(),
body.user_id.as_ref(),
)?
.ok_or(Error::BadRequest(
ErrorKind::BadState,
@ -408,7 +406,7 @@ pub async fn get_member_events_route(
.await?
.iter()
.filter(|(key, _)| key.0 == StateEventType::RoomMember)
.map(|(_, pdu)| pdu.to_member_event().into())
.map(|(_, pdu)| pdu.to_member_event())
.collect(),
})
}
@ -864,7 +862,7 @@ pub(crate) async fn invite_helper<'a>(
"${}",
ruma::signatures::reference_hash(
&pdu_json,
&services().rooms.state.get_room_version(&room_id)?
&services().rooms.state.get_room_version(room_id)?
)
.expect("ruma can calculate reference hashes")
);
@ -878,7 +876,7 @@ pub(crate) async fn invite_helper<'a>(
create_invite::v2::Request {
room_id,
event_id: expected_event_id,
room_version: &services().rooms.state.get_room_version(&room_id)?,
room_version: &services().rooms.state.get_room_version(room_id)?,
event: &PduEvent::convert_to_outgoing_federation_event(pdu_json.clone()),
invite_room_state: &invite_room_state,
},
@ -938,7 +936,7 @@ pub(crate) async fn invite_helper<'a>(
if !services()
.rooms
.state_cache
.is_joined(sender_user, &room_id)?
.is_joined(sender_user, room_id)?
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,

View file

@ -1,8 +1,6 @@
use crate::{
api::client_server::invite_helper, service::pdu::PduBuilder, services, Error, Result, Ruma,
};
use ruma::serde::JsonObject;
use ruma::OwnedRoomAliasId;
use ruma::{
api::client::{
error::ErrorKind,
@ -23,7 +21,9 @@ use ruma::{
},
RoomEventType, StateEventType,
},
int, CanonicalJsonObject, RoomAliasId, RoomId,
int,
serde::JsonObject,
CanonicalJsonObject, OwnedRoomAliasId, RoomAliasId, RoomId,
};
use serde_json::{json, value::to_raw_value};
use std::{cmp::max, collections::BTreeMap, sync::Arc};
@ -213,14 +213,11 @@ pub async fn create_room_route(
// 3. Power levels
// Figure out preset. We need it for preset specific events
let preset = body
.preset
.clone()
.unwrap_or_else(|| match &body.visibility {
room::Visibility::Private => RoomPreset::PrivateChat,
room::Visibility::Public => RoomPreset::PublicChat,
_ => RoomPreset::PrivateChat, // Room visibility should not be custom
});
let preset = body.preset.clone().unwrap_or(match &body.visibility {
room::Visibility::Private => RoomPreset::PrivateChat,
room::Visibility::Public => RoomPreset::PublicChat,
_ => RoomPreset::PrivateChat, // Room visibility should not be custom
});
let mut users = BTreeMap::new();
users.insert(sender_user.clone(), int!(100));

View file

@ -53,11 +53,11 @@ pub async fn login_route(body: Ruma<login::v3::IncomingRequest>) -> Result<login
} else {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type."));
};
let user_id = UserId::parse_with_server_name(
username.to_owned(),
services().globals.server_name(),
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
let user_id =
UserId::parse_with_server_name(username, services().globals.server_name())
.map_err(|_| {
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?;
let hash = services()
.users
.password_hash(&user_id)?

View file

@ -207,7 +207,7 @@ async fn sync_helper(
device_list_updates.extend(
services()
.users
.keys_changed(&sender_user.to_string(), since, None)
.keys_changed(sender_user.as_ref(), since, None)
.filter_map(|r| r.ok()),
);
@ -673,7 +673,7 @@ async fn sync_helper(
device_list_updates.extend(
services()
.users
.keys_changed(&room_id.to_string(), since, None)
.keys_changed(room_id.as_ref(), since, None)
.filter_map(|r| r.ok()),
);
@ -951,8 +951,8 @@ async fn sync_helper(
},
presence: Presence {
events: presence_updates
.into_iter()
.map(|(_, v)| Raw::new(&v).expect("PresenceEvent always serializes successfully"))
.into_values()
.map(|v| Raw::new(&v).expect("PresenceEvent always serializes successfully"))
.collect(),
},
account_data: GlobalAccountData {

View file

@ -58,7 +58,7 @@ pub async fn send_event_to_device_route(
services().users.add_to_device_event(
sender_user,
target_user_id,
&target_device_id,
target_device_id,
&body.event_type,
event.deserialize_as().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")

View file

@ -75,7 +75,7 @@ pub async fn search_users_route(
let user_is_in_shared_rooms = services()
.rooms
.user
.get_shared_rooms(vec![sender_user.clone(), user_id.clone()])
.get_shared_rooms(vec![sender_user.clone(), user_id])
.ok()?
.next()
.is_some();

View file

@ -75,7 +75,7 @@ use tracing::{info, warn};
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FedDest {
Literal(SocketAddr),
Named(String, String),
@ -686,7 +686,7 @@ pub async fn send_transaction_message_route(
services()
.rooms
.event_handler
.acl_check(&sender_servername, &room_id)?;
.acl_check(sender_servername, &room_id)?;
let mutex = Arc::clone(
services()
@ -705,7 +705,7 @@ pub async fn send_transaction_message_route(
.rooms
.event_handler
.handle_incoming_pdu(
&sender_servername,
sender_servername,
&event_id,
&room_id,
value,
@ -974,7 +974,7 @@ pub async fn get_missing_events_route(
services()
.rooms
.event_handler
.acl_check(&sender_servername, &body.room_id)?;
.acl_check(sender_servername, &body.room_id)?;
let mut queued_events = body.latest_events.clone();
let mut events = Vec::new();
@ -1053,7 +1053,7 @@ pub async fn get_event_authorization_route(
services()
.rooms
.event_handler
.acl_check(&sender_servername, &body.room_id)?;
.acl_check(sender_servername, &body.room_id)?;
let event = services()
.rooms
@ -1112,7 +1112,7 @@ pub async fn get_room_state_route(
services()
.rooms
.event_handler
.acl_check(&sender_servername, &body.room_id)?;
.acl_check(sender_servername, &body.room_id)?;
let shortstatehash = services()
.rooms
@ -1128,8 +1128,8 @@ pub async fn get_room_state_route(
.state_accessor
.state_full_ids(shortstatehash)
.await?
.into_iter()
.map(|(_, id)| {
.into_values()
.map(|id| {
PduEvent::convert_to_outgoing_federation_event(
services()
.rooms
@ -1193,7 +1193,7 @@ pub async fn get_room_state_ids_route(
services()
.rooms
.event_handler
.acl_check(&sender_servername, &body.room_id)?;
.acl_check(sender_servername, &body.room_id)?;
let shortstatehash = services()
.rooms
@ -1209,8 +1209,8 @@ pub async fn get_room_state_ids_route(
.state_accessor
.state_full_ids(shortstatehash)
.await?
.into_iter()
.map(|(_, id)| (*id).to_owned())
.into_values()
.map(|id| (*id).to_owned())
.collect();
let auth_chain_ids = services()
@ -1250,7 +1250,7 @@ pub async fn create_join_event_template_route(
services()
.rooms
.event_handler
.acl_check(&sender_servername, &body.room_id)?;
.acl_check(sender_servername, &body.room_id)?;
let mutex_state = Arc::clone(
services()
@ -1354,7 +1354,7 @@ async fn create_join_event(
services()
.rooms
.event_handler
.acl_check(&sender_servername, room_id)?;
.acl_check(sender_servername, room_id)?;
// TODO: Conduit does not implement restricted join rules yet, we always reject
let join_rules_event = services().rooms.state_accessor.room_state_get(
@ -1448,10 +1448,7 @@ async fn create_join_event(
let auth_chain_ids = services()
.rooms
.auth_chain
.get_auth_chain(
room_id,
state_ids.iter().map(|(_, id)| id.clone()).collect(),
)
.get_auth_chain(room_id, state_ids.values().cloned().collect())
.await?;
let servers = services()
@ -1527,7 +1524,7 @@ pub async fn create_invite_route(
services()
.rooms
.event_handler
.acl_check(&sender_servername, &body.room_id)?;
.acl_check(sender_servername, &body.room_id)?;
if !services()
.globals

View file

@ -232,7 +232,7 @@ fn default_pdu_cache_capacity() -> u32 {
}
fn default_cleanup_second_interval() -> u32 {
1 * 60 // every minute
60 // every minute
}
fn default_max_request_size() -> u32 {

View file

@ -193,7 +193,7 @@ impl KvTree for RocksDbEngineTree<'_> {
fn increment(&self, key: &[u8]) -> Result<Vec<u8>> {
let lock = self.write_lock.write().unwrap();
let old = self.db.rocks.get_cf(&self.cf(), &key)?;
let old = self.db.rocks.get_cf(&self.cf(), key)?;
let new = utils::increment(old.as_deref()).unwrap();
self.db.rocks.put_cf(&self.cf(), key, &new)?;

View file

@ -48,13 +48,13 @@ pub struct Engine {
impl Engine {
fn prepare_conn(path: &Path, cache_size_kb: u32) -> Result<Connection> {
let conn = Connection::open(&path)?;
let conn = Connection::open(path)?;
conn.pragma_update(Some(Main), "page_size", &2048)?;
conn.pragma_update(Some(Main), "journal_mode", &"WAL")?;
conn.pragma_update(Some(Main), "synchronous", &"NORMAL")?;
conn.pragma_update(Some(Main), "cache_size", &(-i64::from(cache_size_kb)))?;
conn.pragma_update(Some(Main), "wal_autocheckpoint", &0)?;
conn.pragma_update(Some(Main), "page_size", 2048)?;
conn.pragma_update(Some(Main), "journal_mode", "WAL")?;
conn.pragma_update(Some(Main), "synchronous", "NORMAL")?;
conn.pragma_update(Some(Main), "cache_size", -i64::from(cache_size_kb))?;
conn.pragma_update(Some(Main), "wal_autocheckpoint", 0)?;
Ok(conn)
}
@ -75,7 +75,7 @@ impl Engine {
pub fn flush_wal(self: &Arc<Self>) -> Result<()> {
self.write_lock()
.pragma_update(Some(Main), "wal_checkpoint", &"RESTART")?;
.pragma_update(Some(Main), "wal_checkpoint", "RESTART")?;
Ok(())
}
}

View file

@ -134,7 +134,7 @@ impl service::globals::Data for KeyValueDatabase {
let mut parts = keypair_bytes.splitn(2, |&b| b == 0xff);
let keypair = utils::string_from_bytes(
utils::string_from_bytes(
// 1. version
parts
.next()
@ -151,9 +151,7 @@ impl service::globals::Data for KeyValueDatabase {
.and_then(|(version, key)| {
Ed25519KeyPair::from_der(key, version)
.map_err(|_| Error::bad_database("Private or public keys are invalid."))
});
keypair
})
}
fn remove_keypair(&self) -> Result<()> {
self.global.remove(b"keypair")

View file

@ -40,7 +40,7 @@ impl service::pusher::Data for KeyValueDatabase {
self.senderkey_pusher
.get(&senderkey)?
.map(|push| {
serde_json::from_slice(&*push)
serde_json::from_slice(&push)
.map_err(|_| Error::bad_database("Invalid Pusher in db."))
})
.transpose()
@ -53,7 +53,7 @@ impl service::pusher::Data for KeyValueDatabase {
self.senderkey_pusher
.scan_prefix(prefix)
.map(|(_, push)| {
serde_json::from_slice(&*push)
serde_json::from_slice(&push)
.map_err(|_| Error::bad_database("Invalid Pusher in db."))
})
.collect()

View file

@ -9,7 +9,7 @@ impl service::rooms::alias::Data for KeyValueDatabase {
let mut aliasid = room_id.as_bytes().to_vec();
aliasid.push(0xff);
aliasid.extend_from_slice(&services().globals.next_count()?.to_be_bytes());
self.aliasid_alias.insert(&aliasid, &*alias.as_bytes())?;
self.aliasid_alias.insert(&aliasid, alias.as_bytes())?;
Ok(())
}

View file

@ -88,7 +88,7 @@ impl service::rooms::edus::presence::Data for KeyValueDatabase {
for (key, value) in self
.presenceid_presence
.iter_from(&*first_possible_edu, false)
.iter_from(&first_possible_edu, false)
.take_while(|(key, _)| key.starts_with(&prefix))
{
let user_id = UserId::parse(

View file

@ -17,7 +17,7 @@ impl service::rooms::edus::typing::Data for KeyValueDatabase {
room_typing_id.extend_from_slice(&count);
self.typingid_userid
.insert(&room_typing_id, &*user_id.as_bytes())?;
.insert(&room_typing_id, user_id.as_bytes())?;
self.roomid_lasttypingupdate
.insert(room_id.as_bytes(), &count)?;

View file

@ -15,7 +15,7 @@ impl service::rooms::search::Data for KeyValueDatabase {
let mut key = shortroomid.to_be_bytes().to_vec();
key.extend_from_slice(word.as_bytes());
key.push(0xff);
key.extend_from_slice(&pdu_id);
key.extend_from_slice(pdu_id);
(key, Vec::new())
});

View file

@ -39,7 +39,7 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
{
hash_map::Entry::Vacant(v) => {
if let Some(last_count) = self
.pdus_until(&sender_user, &room_id, u64::MAX)?
.pdus_until(sender_user, room_id, u64::MAX)?
.filter_map(|r| {
// Filter out buggy events
if r.is_err() {
@ -205,8 +205,7 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
.unwrap()
.insert(pdu.room_id.clone(), count);
self.eventid_pduid
.insert(pdu.event_id.as_bytes(), &pdu_id)?;
self.eventid_pduid.insert(pdu.event_id.as_bytes(), pdu_id)?;
self.eventid_outlierpdu.remove(pdu.event_id.as_bytes())?;
Ok(())

View file

@ -114,7 +114,7 @@ impl service::rooms::user::Data for KeyValueDatabase {
utils::common_elements(iterators, Ord::cmp)
.expect("users is not empty")
.map(|bytes| {
RoomId::parse(utils::string_from_bytes(&*bytes).map_err(|_| {
RoomId::parse(utils::string_from_bytes(&bytes).map_err(|_| {
Error::bad_database("Invalid RoomId bytes in userroomid_joined")
})?)
.map_err(|_| Error::bad_database("Invalid RoomId in userroomid_joined."))

View file

@ -38,7 +38,7 @@ impl service::sending::Data for KeyValueDatabase {
fn delete_all_active_requests_for(&self, outgoing_kind: &OutgoingKind) -> Result<()> {
let prefix = outgoing_kind.get_prefix();
for (key, _) in self.servercurrentevent_data.scan_prefix(prefix.clone()) {
for (key, _) in self.servercurrentevent_data.scan_prefix(prefix) {
self.servercurrentevent_data.remove(&key)?;
}
@ -51,7 +51,7 @@ impl service::sending::Data for KeyValueDatabase {
self.servercurrentevent_data.remove(&key).unwrap();
}
for (key, _) in self.servernameevent_data.scan_prefix(prefix.clone()) {
for (key, _) in self.servernameevent_data.scan_prefix(prefix) {
self.servernameevent_data.remove(&key).unwrap();
}
@ -67,7 +67,7 @@ impl service::sending::Data for KeyValueDatabase {
for (outgoing_kind, event) in requests {
let mut key = outgoing_kind.get_prefix();
key.extend_from_slice(if let SendingEventType::Pdu(value) = &event {
&**value
value
} else {
&[]
});
@ -91,7 +91,7 @@ impl service::sending::Data for KeyValueDatabase {
let prefix = outgoing_kind.get_prefix();
return Box::new(
self.servernameevent_data
.scan_prefix(prefix.clone())
.scan_prefix(prefix)
.map(|(k, v)| parse_servercurrentevent(&k, v).map(|(_, ev)| (ev, k))),
);
}
@ -155,7 +155,7 @@ fn parse_servercurrentevent(
let mut parts = key[1..].splitn(3, |&b| b == 0xff);
let user = parts.next().expect("splitn always returns one element");
let user_string = utils::string_from_bytes(&user)
let user_string = utils::string_from_bytes(user)
.map_err(|_| Error::bad_database("Invalid user string in servercurrentevent"))?;
let user_id = UserId::parse(user_string)
.map_err(|_| Error::bad_database("Invalid user id in servercurrentevent"))?;

View file

@ -5,10 +5,9 @@ use ruma::{
encryption::{CrossSigningKey, DeviceKeys, OneTimeKey},
events::{AnyToDeviceEvent, StateEventType},
serde::Raw,
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, OwnedUserId, UInt,
UserId,
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, OwnedDeviceId,
OwnedDeviceKeyId, OwnedMxcUri, OwnedUserId, UInt, UserId,
};
use ruma::{OwnedDeviceId, OwnedDeviceKeyId, OwnedMxcUri};
use tracing::warn;
use crate::{
@ -380,13 +379,12 @@ impl service::users::Data for KeyValueDatabase {
Ok((
serde_json::from_slice(
&*key
.rsplit(|&b| b == 0xff)
key.rsplit(|&b| b == 0xff)
.next()
.ok_or_else(|| Error::bad_database("OneTimeKeyId in db is invalid."))?,
)
.map_err(|_| Error::bad_database("OneTimeKeyId in db is invalid."))?,
serde_json::from_slice(&*value)
serde_json::from_slice(&value)
.map_err(|_| Error::bad_database("OneTimeKeys in db are invalid."))?,
))
})
@ -410,7 +408,7 @@ impl service::users::Data for KeyValueDatabase {
.map(|(bytes, _)| {
Ok::<_, Error>(
serde_json::from_slice::<OwnedDeviceKeyId>(
&*bytes.rsplit(|&b| b == 0xff).next().ok_or_else(|| {
bytes.rsplit(|&b| b == 0xff).next().ok_or_else(|| {
Error::bad_database("OneTimeKey ID in db is invalid.")
})?,
)

View file

@ -2,22 +2,17 @@ pub mod abstraction;
pub mod key_value;
use crate::{services, utils, Config, Error, PduEvent, Result, Services, SERVICES};
use abstraction::KeyValueDatabaseEngine;
use abstraction::KvTree;
use abstraction::{KeyValueDatabaseEngine, KvTree};
use directories::ProjectDirs;
use lru_cache::LruCache;
use ruma::CanonicalJsonValue;
use ruma::OwnedDeviceId;
use ruma::OwnedEventId;
use ruma::OwnedRoomId;
use ruma::OwnedUserId;
use ruma::{
events::{
push_rules::PushRulesEventContent, room::message::RoomMessageEventContent,
GlobalAccountDataEvent, GlobalAccountDataEventType, StateEventType,
},
push::Ruleset,
EventId, RoomId, UserId,
CanonicalJsonValue, EventId, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId,
UserId,
};
use std::{
collections::{BTreeMap, HashMap, HashSet},

View file

@ -24,7 +24,7 @@ pub use utils::error::{Error, Result};
pub static SERVICES: RwLock<Option<&'static Services>> = RwLock::new(None);
pub fn services<'a>() -> &'static Services {
&SERVICES
SERVICES
.read()
.unwrap()
.expect("SERVICES should be initialized when this is called")

View file

@ -444,7 +444,7 @@ impl_ruma_handler!(T1, T2, T3, T4, T5, T6, T7);
impl_ruma_handler!(T1, T2, T3, T4, T5, T6, T7, T8);
fn method_to_filter(method: Method) -> MethodFilter {
let method_filter = match method {
match method {
Method::DELETE => MethodFilter::DELETE,
Method::GET => MethodFilter::GET,
Method::HEAD => MethodFilter::HEAD,
@ -454,6 +454,5 @@ fn method_to_filter(method: Method) -> MethodFilter {
Method::PUT => MethodFilter::PUT,
Method::TRACE => MethodFilter::TRACE,
m => panic!("Unsupported HTTP method: {:?}", m),
};
method_filter
}
}

View file

@ -179,7 +179,7 @@ impl Service {
}
pub fn start_handler(self: &Arc<Self>) {
let self2 = Arc::clone(&self);
let self2 = Arc::clone(self);
tokio::spawn(async move {
self2.handler().await;
});
@ -270,13 +270,11 @@ impl Service {
let command_line = lines.next().expect("each string has at least one line");
let body: Vec<_> = lines.collect();
let admin_command = match self.parse_admin_command(&command_line) {
let admin_command = match self.parse_admin_command(command_line) {
Ok(command) => command,
Err(error) => {
let server_name = services().globals.server_name();
let message = error
.to_string()
.replace("server.name", server_name.as_str());
let message = error.replace("server.name", server_name.as_str());
let html_message = self.usage_to_html(&message, server_name);
return RoomMessageEventContent::text_html(message, html_message);
@ -316,8 +314,8 @@ impl Service {
// Backwards compatibility with `register_appservice`-style commands
let command_with_dashes;
if argv.len() > 1 && argv[1].contains("_") {
command_with_dashes = argv[1].replace("_", "-");
if argv.len() > 1 && argv[1].contains('_') {
command_with_dashes = argv[1].replace('_', "-");
argv[1] = &command_with_dashes;
}
@ -631,7 +629,7 @@ impl Service {
let displayname = format!("{} ⚡️", user_id.localpart());
services()
.users
.set_displayname(&user_id, Some(displayname.clone()))?;
.set_displayname(&user_id, Some(displayname))?;
// Initial account data
services().account_data.update(
@ -771,7 +769,7 @@ impl Service {
let text = text.replace("subcommand", "command");
// Escape option names (e.g. `<element-id>`) since they look like HTML tags
let text = text.replace("<", "&lt;").replace(">", "&gt;");
let text = text.replace('<', "&lt;").replace('>', "&gt;");
// Italicize the first line (command name and version text)
let re = Regex::new("^(.*?)\n").expect("Regex compilation should not fail");
@ -799,7 +797,7 @@ impl Service {
while text_lines
.get(line_index)
.map(|line| line.starts_with("#"))
.map(|line| line.starts_with('#'))
.unwrap_or(false)
{
command_body += if text_lines[line_index].starts_with("# ") {
@ -830,12 +828,10 @@ impl Service {
};
// Add HTML line-breaks
let text = text
.replace("\n\n\n", "\n\n")
.replace("\n", "<br>\n")
.replace("[nobr]<br>", "");
text
text.replace("\n\n\n", "\n\n")
.replace('\n', "<br>\n")
.replace("[nobr]<br>", "")
}
/// Create the admin room.
@ -1110,7 +1106,7 @@ impl Service {
state_key: Some(user_id.to_string()),
redacts: None,
},
&user_id,
user_id,
&room_id,
&state_lock,
)?;
@ -1142,8 +1138,8 @@ impl Service {
PduBuilder {
event_type: RoomEventType::RoomMessage,
content: to_raw_value(&RoomMessageEventContent::text_html(
format!("## Thank you for trying out Conduit!\n\nConduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.\n\nHelpful links:\n> Website: https://conduit.rs\n> Git and Documentation: https://gitlab.com/famedly/conduit\n> Report issues: https://gitlab.com/famedly/conduit/-/issues\n\nFor a list of available commands, send the following message in this room: `@conduit:{}: --help`\n\nHere are some rooms you can join (by typing the command):\n\nConduit room (Ask questions and get notified on updates):\n`/join #conduit:fachschaften.org`\n\nConduit lounge (Off-topic, only Conduit users are allowed to join)\n`/join #conduit-lounge:conduit.rs`", services().globals.server_name()).to_owned(),
format!("<h2>Thank you for trying out Conduit!</h2>\n<p>Conduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.</p>\n<p>Helpful links:</p>\n<blockquote>\n<p>Website: https://conduit.rs<br>Git and Documentation: https://gitlab.com/famedly/conduit<br>Report issues: https://gitlab.com/famedly/conduit/-/issues</p>\n</blockquote>\n<p>For a list of available commands, send the following message in this room: <code>@conduit:{}: --help</code></p>\n<p>Here are some rooms you can join (by typing the command):</p>\n<p>Conduit room (Ask questions and get notified on updates):<br><code>/join #conduit:fachschaften.org</code></p>\n<p>Conduit lounge (Off-topic, only Conduit users are allowed to join)<br><code>/join #conduit-lounge:conduit.rs</code></p>\n", services().globals.server_name()).to_owned(),
format!("## Thank you for trying out Conduit!\n\nConduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.\n\nHelpful links:\n> Website: https://conduit.rs\n> Git and Documentation: https://gitlab.com/famedly/conduit\n> Report issues: https://gitlab.com/famedly/conduit/-/issues\n\nFor a list of available commands, send the following message in this room: `@conduit:{}: --help`\n\nHere are some rooms you can join (by typing the command):\n\nConduit room (Ask questions and get notified on updates):\n`/join #conduit:fachschaften.org`\n\nConduit lounge (Off-topic, only Conduit users are allowed to join)\n`/join #conduit-lounge:conduit.rs`", services().globals.server_name()),
format!("<h2>Thank you for trying out Conduit!</h2>\n<p>Conduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.</p>\n<p>Helpful links:</p>\n<blockquote>\n<p>Website: https://conduit.rs<br>Git and Documentation: https://gitlab.com/famedly/conduit<br>Report issues: https://gitlab.com/famedly/conduit/-/issues</p>\n</blockquote>\n<p>For a list of available commands, send the following message in this room: <code>@conduit:{}: --help</code></p>\n<p>Here are some rooms you can join (by typing the command):</p>\n<p>Conduit room (Ask questions and get notified on updates):<br><code>/join #conduit:fachschaften.org</code></p>\n<p>Conduit lounge (Off-topic, only Conduit users are allowed to join)<br><code>/join #conduit-lounge:conduit.rs</code></p>\n", services().globals.server_name()),
))
.expect("event is valid, we just created it"),
unsigned: None,

View file

@ -4,7 +4,6 @@ use ruma::events::AnySyncTimelineEvent;
use crate::{services, Error, PduEvent, Result};
use bytes::BytesMut;
use ruma::api::IncomingResponse;
use ruma::{
api::{
client::push::{get_pushers, set_pusher, PusherKind},
@ -12,7 +11,7 @@ use ruma::{
self,
v1::{Device, Notification, NotificationCounts, NotificationPriority},
},
MatrixVersion, OutgoingRequest, SendAccessToken,
IncomingResponse, MatrixVersion, OutgoingRequest, SendAccessToken,
},
events::{
room::{name::RoomNameEventContent, power_levels::RoomPowerLevelsEventContent},

View file

@ -284,7 +284,7 @@ impl Service {
RoomVersion::new(room_version_id).expect("room version is supported");
let mut val = match ruma::signatures::verify_event(
&*pub_key_map.read().expect("RwLock is poisoned."),
&pub_key_map.read().expect("RwLock is poisoned."),
&value,
room_version_id,
) {
@ -1198,7 +1198,7 @@ impl Service {
.fetch_and_handle_outliers(
origin,
&[prev_event_id.clone()],
&create_event,
create_event,
room_id,
pub_key_map,
)
@ -1224,7 +1224,7 @@ impl Service {
amount += 1;
for prev_prev in &pdu.prev_events {
if !graph.contains_key(prev_prev) {
todo_outlier_stack.push(dbg!(prev_prev.clone()));
todo_outlier_stack.push(prev_prev.clone());
}
}
@ -1248,7 +1248,7 @@ impl Service {
}
}
let sorted = state_res::lexicographical_topological_sort(dbg!(&graph), |event_id| {
let sorted = state_res::lexicographical_topological_sort(&graph, |event_id| {
// This return value is the key used for sorting events,
// events are then sorted by power level, time,
// and lexically by event_id.
@ -1482,8 +1482,8 @@ impl Service {
}
let mut futures: FuturesUnordered<_> = servers
.into_iter()
.map(|(server, _)| async move {
.into_keys()
.map(|server| async move {
(
services()
.sending

View file

@ -1,7 +1,6 @@
use crate::Result;
use ruma::{EventId, OwnedEventId, RoomId};
use std::collections::HashSet;
use std::sync::Arc;
use std::{collections::HashSet, sync::Arc};
use tokio::sync::MutexGuard;
pub trait Data: Send + Sync {

View file

@ -93,7 +93,7 @@ impl Service {
services().rooms.state_cache.update_joined_count(room_id)?;
self.db
.set_room_state(room_id, shortstatehash, &state_lock)?;
.set_room_state(room_id, shortstatehash, state_lock)?;
Ok(())
}
@ -331,7 +331,7 @@ impl Service {
.transpose()?;
let room_version = create_event_content
.map(|create_event| create_event.room_version)
.ok_or_else(|| Error::BadDatabase("Invalid room version"))?;
.ok_or(Error::BadDatabase("Invalid room version"))?;
Ok(room_version)
}

View file

@ -2,29 +2,29 @@ mod data;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use std::{
collections::HashSet,
sync::{Arc, Mutex},
};
pub use data::Data;
use regex::Regex;
use ruma::canonical_json::to_canonical_value;
use ruma::events::room::power_levels::RoomPowerLevelsEventContent;
use ruma::push::Ruleset;
use ruma::state_res::RoomVersion;
use ruma::CanonicalJsonObject;
use ruma::CanonicalJsonValue;
use ruma::OwnedEventId;
use ruma::OwnedRoomId;
use ruma::OwnedServerName;
use ruma::{
api::client::error::ErrorKind,
canonical_json::to_canonical_value,
events::{
push_rules::PushRulesEvent,
room::{create::RoomCreateEventContent, member::MembershipState},
room::{
create::RoomCreateEventContent, member::MembershipState,
power_levels::RoomPowerLevelsEventContent,
},
GlobalAccountDataEventType, RoomEventType, StateEventType,
},
push::{Action, Tweak},
state_res, uint, EventId, RoomAliasId, RoomId, UserId,
push::{Action, Ruleset, Tweak},
state_res,
state_res::RoomVersion,
uint, CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId,
OwnedServerName, RoomAliasId, RoomId, UserId,
};
use serde::Deserialize;
use serde_json::value::to_raw_value;
@ -267,7 +267,7 @@ impl Service {
.account_data
.get(
None,
&user,
user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.map(|event| {
@ -276,13 +276,13 @@ impl Service {
})
.transpose()?
.map(|ev: PushRulesEvent| ev.content.global)
.unwrap_or_else(|| Ruleset::server_default(&user));
.unwrap_or_else(|| Ruleset::server_default(user));
let mut highlight = false;
let mut notify = false;
for action in services().pusher.get_actions(
&user,
user,
&rules_for_user,
&power_levels,
&sync_pdu,
@ -307,10 +307,8 @@ impl Service {
highlights.push(user.clone());
}
for push_key in services().pusher.get_pushkeys(&user) {
services()
.sending
.send_push_pdu(&*pdu_id, &user, push_key?)?;
for push_key in services().pusher.get_pushkeys(user) {
services().sending.send_push_pdu(&pdu_id, user, push_key?)?;
}
}
@ -388,7 +386,7 @@ impl Service {
&& services().globals.emergency_password().is_none();
if to_conduit && !from_conduit && admin_room.as_ref() == Some(&pdu.room_id) {
services().admin.process_message(body.to_string());
services().admin.process_message(body);
}
}
}
@ -583,8 +581,8 @@ impl Service {
prev_events,
depth,
auth_events: auth_events
.iter()
.map(|(_, pdu)| pdu.event_id.clone())
.values()
.map(|pdu| pdu.event_id.clone())
.collect(),
redacts,
unsigned: if unsigned.is_empty() {
@ -683,7 +681,7 @@ impl Service {
state_lock: &MutexGuard<'_, ()>, // Take mutex guard to make sure users get the room state mutex
) -> Result<Arc<EventId>> {
let (pdu, pdu_json) =
self.create_hash_and_sign_event(pdu_builder, sender, room_id, &state_lock)?;
self.create_hash_and_sign_event(pdu_builder, sender, room_id, state_lock)?;
// We append to state before appending the pdu, so we don't have a moment in time with the
// pdu without it's state. This is okay because append_pdu can't fail.

View file

@ -110,7 +110,7 @@ impl Service {
}
pub fn start_handler(self: &Arc<Self>) {
let self2 = Arc::clone(&self);
let self2 = Arc::clone(self);
tokio::spawn(async move {
self2.handler().await.unwrap();
});
@ -280,7 +280,7 @@ impl Service {
device_list_changes.extend(
services()
.users
.keys_changed(&room_id.to_string(), since, None)
.keys_changed(room_id.as_ref(), since, None)
.filter_map(|r| r.ok())
.filter(|user_id| user_id.server_name() == services().globals.server_name()),
);
@ -487,7 +487,7 @@ impl Service {
let response = appservice_server::send_request(
services()
.appservice
.get_registration(&id)
.get_registration(id)
.map_err(|e| (kind.clone(), e))?
.ok_or_else(|| {
(
@ -562,7 +562,7 @@ impl Service {
let pusher = match services()
.pusher
.get_pusher(&userid, pushkey)
.get_pusher(userid, pushkey)
.map_err(|e| (OutgoingKind::Push(userid.clone(), pushkey.clone()), e))?
{
Some(pusher) => pusher,
@ -573,18 +573,18 @@ impl Service {
.account_data
.get(
None,
&userid,
userid,
GlobalAccountDataEventType::PushRules.to_string().into(),
)
.unwrap_or_default()
.and_then(|event| serde_json::from_str::<PushRulesEvent>(event.get()).ok())
.map(|ev: PushRulesEvent| ev.content.global)
.unwrap_or_else(|| push::Ruleset::server_default(&userid));
.unwrap_or_else(|| push::Ruleset::server_default(userid));
let unread: UInt = services()
.rooms
.user
.notification_count(&userid, &pdu.room_id)
.notification_count(userid, &pdu.room_id)
.map_err(|e| (kind.clone(), e))?
.try_into()
.expect("notification count can't go that high");
@ -593,7 +593,7 @@ impl Service {
let _response = services()
.pusher
.send_push_notice(&userid, unread, &pusher, rules_for_user, &pdu)
.send_push_notice(userid, unread, &pusher, rules_for_user, &pdu)
.await
.map(|_response| kind.clone())
.map_err(|e| (kind.clone(), e));
@ -638,7 +638,7 @@ impl Service {
let permit = services().sending.maximum_requests.acquire().await;
let response = server_server::send_request(
&*server,
server,
send_transaction_message::v1::Request {
origin: services().globals.server_name(),
pdus: &pdu_jsons,